Reducing header overuse, non-inlining selected methods (CPPOST-35).
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML1Consumer.cpp
1 /*
2  *  Copyright 2001-2009 Internet2
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * SAML1Consumer.cpp
19  *
20  * SAML 1.x assertion consumer service
21  */
22
23 #include "internal.h"
24 #include "handler/AssertionConsumerService.h"
25
26 #ifndef SHIBSP_LITE
27 # include "exceptions.h"
28 # include "Application.h"
29 # include "ServiceProvider.h"
30 # include "SessionCache.h"
31 # include "attribute/resolver/ResolutionContext.h"
32 # include <saml/SAMLConfig.h>
33 # include <saml/binding/SecurityPolicy.h>
34 # include <saml/saml1/core/Assertions.h>
35 # include <saml/saml1/core/Protocols.h>
36 # include <saml/saml2/metadata/Metadata.h>
37 # include <xmltooling/util/DateTime.h>
38 using namespace opensaml::saml1;
39 using namespace opensaml::saml1p;
40 using namespace opensaml;
41 using saml2::NameID;
42 using saml2::NameIDBuilder;
43 using saml2md::EntityDescriptor;
44 using saml2md::SPSSODescriptor;
45 using saml2md::MetadataException;
46 #else
47 # include "lite/SAMLConstants.h"
48 #endif
49
50 using namespace shibsp;
51 using namespace xmltooling;
52 using namespace std;
53
54 namespace shibsp {
55
56 #if defined (_MSC_VER)
57     #pragma warning( push )
58     #pragma warning( disable : 4250 )
59 #endif
60
61     class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
62     {
63     public:
64         SAML1Consumer(const DOMElement* e, const char* appId)
65             : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
66 #ifndef SHIBSP_LITE
67             m_ssoRule = NULL;
68             m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
69             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
70                 m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(SAML1BROWSERSSO_POLICY_RULE, e);
71 #endif
72         }
73         virtual ~SAML1Consumer() {
74 #ifndef SHIBSP_LITE
75             delete m_ssoRule;
76 #endif
77         }
78
79 #ifndef SHIBSP_LITE
80         void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
81             AssertionConsumerService::generateMetadata(role, handlerURL);
82             role.addSupport(samlconstants::SAML11_PROTOCOL_ENUM);
83             role.addSupport(samlconstants::SAML10_PROTOCOL_ENUM);
84         }
85
86     private:
87         void implementProtocol(
88             const Application& application,
89             const HTTPRequest& httpRequest,
90             HTTPResponse& httpResponse,
91             SecurityPolicy& policy,
92             const PropertySet* settings,
93             const XMLObject& xmlObject
94             ) const;
95
96         bool m_post;
97         SecurityPolicyRule* m_ssoRule;
98 #endif
99     };
100
101 #if defined (_MSC_VER)
102     #pragma warning( pop )
103 #endif
104
105     Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
106     {
107         return new SAML1Consumer(p.first, p.second);
108     }
109
110 #ifndef SHIBSP_LITE
111     class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
112     {
113     public:
114         _rulenamed(const char* name) : m_name(name) {}
115         bool operator()(const SecurityPolicyRule* rule) const {
116             return rule ? !strcmp(m_name, rule->getType()) : false;
117         }
118     private:
119         const char* m_name;
120     };
121 #endif
122 };
123
124 #ifndef SHIBSP_LITE
125
126 void SAML1Consumer::implementProtocol(
127     const Application& application,
128     const HTTPRequest& httpRequest,
129     HTTPResponse& httpResponse,
130     SecurityPolicy& policy,
131     const PropertySet* settings,
132     const XMLObject& xmlObject
133     ) const
134 {
135     // Implementation of SAML 1.x SSO profile(s).
136     m_log.debug("processing message against SAML 1.x SSO profile");
137
138     // Check for errors...this will throw if it's not a successful message.
139     checkError(&xmlObject);
140
141     // With the binding aspects now moved out to the MessageDecoder,
142     // the focus here is on the assertion content. For SAML 1.x POST,
143     // all the security comes from the protocol layer, and signing
144     // the assertion isn't sufficient. So we can check the policy
145     // object now and bail if it's not a secured message.
146     if (m_post && !policy.isAuthenticated()) {
147         if (policy.getIssuer() && !policy.getIssuerMetadata())
148             throw MetadataException("Security of SAML 1.x SSO POST response not established.");
149         throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
150     }
151
152     // Remember whether we already established trust.
153     bool alreadySecured = policy.isAuthenticated();
154
155     const Response* response = dynamic_cast<const Response*>(&xmlObject);
156     if (!response)
157         throw FatalProfileException("Incoming message was not a samlp:Response.");
158
159     const vector<saml1::Assertion*>& assertions = response->getAssertions();
160     if (assertions.empty())
161         throw FatalProfileException("Incoming message contained no SAML assertions.");
162
163     pair<bool,int> minor = response->getMinorVersion();
164
165     // Maintain list of "legit" tokens to feed to SP subsystems.
166     const AuthenticationStatement* ssoStatement=NULL;
167     vector<const opensaml::Assertion*> tokens;
168
169     // Also track "bad" tokens that we'll cache but not use.
170     // This is necessary because there may be valid tokens not aimed at us.
171     vector<const opensaml::Assertion*> badtokens;
172
173     // With this flag on, we ignore any unsigned assertions.
174     const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
175     pair<bool,bool> flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
176
177     // authnskew allows rejection of SSO if AuthnInstant is too old.
178     const PropertySet* sessionProps = application.getPropertySet("Sessions");
179     pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
180
181     // Saves off error messages potentially helpful for users.
182     string contextualError;
183
184     // Ensure the BrowserSSO rule is in the policy set.
185     if (find_if(policy.getRules(), _rulenamed(SAML1BROWSERSSO_POLICY_RULE)) == NULL)
186         policy.getRules().push_back(m_ssoRule);
187
188     // Populate recipient as audience.
189     policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
190
191     time_t now = time(NULL);
192     for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
193         try {
194             // Skip unsigned assertion?
195             if (!(*a)->getSignature() && flag.first && flag.second)
196                 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
197
198             // We clear the security flag, so we can tell whether the token was secured on its own.
199             policy.setAuthenticated(false);
200             policy.reset(true);
201
202             // Extract message bits and re-verify Issuer information.
203             extractMessageDetails(
204                 *(*a), (minor.first && minor.second==0) ? samlconstants::SAML10_PROTOCOL_ENUM : samlconstants::SAML11_PROTOCOL_ENUM, policy
205                 );
206
207             // Run the policy over the assertion. Handles replay, freshness, and
208             // signature verification, assuming the relevant rules are configured,
209             // along with condition and profile enforcement.
210             policy.evaluate(*(*a), &httpRequest);
211
212             // If no security is in place now, we kick it.
213             if (!alreadySecured && !policy.isAuthenticated())
214                 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
215
216             // Track it as a valid token.
217             tokens.push_back(*a);
218
219             // Save off the first valid SSO statement.
220             const vector<AuthenticationStatement*>& statements = const_cast<const saml1::Assertion*>(*a)->getAuthenticationStatements();
221             for (vector<AuthenticationStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
222                 if (authnskew.first && authnskew.second &&
223                     (*s)->getAuthenticationInstant() && (now - (*s)->getAuthenticationInstantEpoch() > authnskew.second))
224                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
225                 else if (!ssoStatement) {
226                     ssoStatement = *s;
227                     break;
228                 }
229             }
230         }
231         catch (exception& ex) {
232             m_log.warn("detected a problem with assertion: %s", ex.what());
233             if (!ssoStatement)
234                 contextualError = ex.what();
235             badtokens.push_back(*a);
236         }
237     }
238
239     if (!ssoStatement) {
240         if (contextualError.empty())
241             throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
242         throw FatalProfileException(contextualError.c_str());
243     }
244
245     // Address checking.
246     SubjectLocality* locality = ssoStatement->getSubjectLocality();
247     if (locality && locality->getIPAddress()) {
248         auto_ptr_char ip(locality->getIPAddress());
249         checkAddress(application, httpRequest, ip.get());
250     }
251
252     m_log.debug("SSO profile processing completed successfully");
253
254     NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
255
256     // Now we have to extract the authentication details for attribute and session setup.
257
258     // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
259     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
260     if (!lifetime.first || lifetime.second == 0)
261         lifetime.second = 28800;
262
263     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
264     // To complete processing, we need to extract and resolve attributes and then create the session.
265
266     // Normalize the SAML 1.x NameIdentifier...
267     auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : NULL);
268     if (n) {
269         nameid->setName(n->getName());
270         nameid->setFormat(n->getFormat());
271         nameid->setNameQualifier(n->getNameQualifier());
272     }
273
274     // The context will handle deleting attributes and new tokens.
275     auto_ptr<ResolutionContext> ctx(
276         resolveAttributes(
277             application,
278             policy.getIssuerMetadata(),
279             (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
280                 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
281             n,
282             nameid.get(),
283             ssoStatement->getAuthenticationMethod(),
284             NULL,
285             &tokens
286             )
287         );
288
289     if (ctx.get()) {
290         // Copy over any new tokens, but leave them in the context for cleanup.
291         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
292     }
293
294     // Now merge in bad tokens for caching.
295     tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
296
297     application.getServiceProvider().getSessionCache()->insert(
298         application,
299         httpRequest,
300         httpResponse,
301         now + lifetime.second,
302         entity,
303         (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
304             samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
305         nameid.get(),
306         ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
307         NULL,
308         ssoStatement->getAuthenticationMethod(),
309         NULL,
310         &tokens,
311         ctx.get() ? &ctx->getResolvedAttributes() : NULL
312         );
313 }
314
315 #endif