Reducing header overuse, non-inlining selected methods (CPPOST-35).
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML2Consumer.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  * SAML2Consumer.cpp
19  *
20  * SAML 2.0 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/saml2/core/Protocols.h>
34 # include <saml/saml2/metadata/Metadata.h>
35 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
36 # include <saml/saml2/profile/SAML2AssertionPolicy.h>
37 # include <xmltooling/XMLToolingConfig.h>
38 # include <xmltooling/util/DateTime.h>
39 using namespace opensaml::saml2;
40 using namespace opensaml::saml2p;
41 using namespace opensaml::saml2md;
42 using namespace opensaml;
43 # ifndef min
44 #  define min(a,b)            (((a) < (b)) ? (a) : (b))
45 # endif
46 #endif
47
48 using namespace shibsp;
49 using namespace xmltooling;
50 using namespace std;
51
52 namespace shibsp {
53
54 #if defined (_MSC_VER)
55     #pragma warning( push )
56     #pragma warning( disable : 4250 )
57 #endif
58
59     class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
60     {
61     public:
62         SAML2Consumer(const DOMElement* e, const char* appId)
63             : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML2")) {
64 #ifndef SHIBSP_LITE
65             m_ssoRule = NULL;
66             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
67                 m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(BEARER_POLICY_RULE, e);
68 #endif
69         }
70         virtual ~SAML2Consumer() {
71 #ifndef SHIBSP_LITE
72             delete m_ssoRule;
73 #endif
74         }
75
76 #ifndef SHIBSP_LITE
77         void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
78             AssertionConsumerService::generateMetadata(role, handlerURL);
79             role.addSupport(samlconstants::SAML20P_NS);
80         }
81
82     private:
83         void implementProtocol(
84             const Application& application,
85             const HTTPRequest& httpRequest,
86             HTTPResponse& httpResponse,
87             SecurityPolicy& policy,
88             const PropertySet* settings,
89             const XMLObject& xmlObject
90             ) const;
91
92         SecurityPolicyRule* m_ssoRule;
93 #endif
94     };
95
96 #if defined (_MSC_VER)
97     #pragma warning( pop )
98 #endif
99
100     Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
101     {
102         return new SAML2Consumer(p.first, p.second);
103     }
104
105 #ifndef SHIBSP_LITE
106     class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
107     {
108     public:
109         _rulenamed(const char* name) : m_name(name) {}
110         bool operator()(const SecurityPolicyRule* rule) const {
111             return rule ? !strcmp(m_name, rule->getType()) : false;
112         }
113     private:
114         const char* m_name;
115     };
116 #endif
117 };
118
119 #ifndef SHIBSP_LITE
120
121 void SAML2Consumer::implementProtocol(
122     const Application& application,
123     const HTTPRequest& httpRequest,
124     HTTPResponse& httpResponse,
125     SecurityPolicy& policy,
126     const PropertySet* settings,
127     const XMLObject& xmlObject
128     ) const
129 {
130     // Implementation of SAML 2.0 SSO profile(s).
131     m_log.debug("processing message against SAML 2.0 SSO profile");
132
133     // Remember whether we already established trust.
134     // None of the SAML 2 bindings require security at the protocol layer.
135     bool alreadySecured = policy.isAuthenticated();
136
137     // Check for errors...this will throw if it's not a successful message.
138     checkError(&xmlObject, policy.getIssuerMetadata());
139
140     const Response* response = dynamic_cast<const Response*>(&xmlObject);
141     if (!response)
142         throw FatalProfileException("Incoming message was not a samlp:Response.");
143
144     const vector<saml2::Assertion*>& assertions = response->getAssertions();
145     const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
146     if (assertions.empty() && encassertions.empty())
147         throw FatalProfileException("Incoming message contained no SAML assertions.");
148
149     // Maintain list of "legit" tokens to feed to SP subsystems.
150     const Subject* ssoSubject=NULL;
151     const AuthnStatement* ssoStatement=NULL;
152     vector<const opensaml::Assertion*> tokens;
153
154     // Also track "bad" tokens that we'll cache but not use.
155     // This is necessary because there may be valid tokens not aimed at us.
156     vector<const opensaml::Assertion*> badtokens;
157
158     // And also track "owned" tokens that we decrypt here.
159     vector<saml2::Assertion*> ownedtokens;
160
161     // With this flag on, we ignore any unsigned assertions.
162     const EntityDescriptor* entity = NULL;
163     pair<bool,bool> flag = make_pair(false,false);
164     if (alreadySecured && policy.getIssuerMetadata()) {
165         entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
166         flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
167     }
168
169     // authnskew allows rejection of SSO if AuthnInstant is too old.
170     const PropertySet* sessionProps = application.getPropertySet("Sessions");
171     pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
172
173     // Saves off error messages potentially helpful for users.
174     string contextualError;
175
176     // Ensure the Bearer rule is in the policy set.
177     if (find_if(policy.getRules(), _rulenamed(BEARER_POLICY_RULE)) == NULL)
178         policy.getRules().push_back(m_ssoRule);
179
180     // Populate recipient as audience.
181     policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
182
183     time_t now = time(NULL);
184     for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
185         try {
186             // Skip unsigned assertion?
187             if (!(*a)->getSignature() && flag.first && flag.second)
188                 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
189
190             // We clear the security flag, so we can tell whether the token was secured on its own.
191             policy.setAuthenticated(false);
192             policy.reset(true);
193
194             // Extract message bits and re-verify Issuer information.
195             extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
196
197             // Run the policy over the assertion. Handles replay, freshness, and
198             // signature verification, assuming the relevant rules are configured,
199             // along with condition and profile enforcement.
200             policy.evaluate(*(*a), &httpRequest);
201
202             // If no security is in place now, we kick it.
203             if (!alreadySecured && !policy.isAuthenticated())
204                 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
205
206             // If we hadn't established Issuer yet, redo the signedAssertions check.
207             if (!entity && policy.getIssuerMetadata()) {
208                 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
209                 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
210                 if (!(*a)->getSignature() && flag.first && flag.second)
211                     throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
212             }
213
214             // Address checking.
215             SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
216                 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
217                 );
218             if (subcondata && subcondata->getAddress()) {
219                 auto_ptr_char boundip(subcondata->getAddress());
220                 checkAddress(application, httpRequest, boundip.get());
221             }
222
223             // Track it as a valid token.
224             tokens.push_back(*a);
225
226             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
227             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
228             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
229                 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
230                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
231                 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
232                     ssoStatement = *s;
233             }
234
235             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
236             if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
237                 ssoSubject = (*a)->getSubject();
238         }
239         catch (exception& ex) {
240             m_log.warn("detected a problem with assertion: %s", ex.what());
241             if (!ssoStatement)
242                 contextualError = ex.what();
243             badtokens.push_back(*a);
244         }
245     }
246
247     // In case we need decryption...
248     CredentialResolver* cr=application.getCredentialResolver();
249     if (!cr && !encassertions.empty())
250         m_log.warn("found encrypted assertions, but no CredentialResolver was available");
251
252     for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
253         // Attempt to decrypt it.
254         saml2::Assertion* decrypted=NULL;
255         try {
256             Locker credlocker(cr);
257             auto_ptr<MetadataCredentialCriteria> mcc(
258                 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
259                 );
260             auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
261             decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
262             if (decrypted) {
263                 wrapper.release();
264                 ownedtokens.push_back(decrypted);
265                 if (m_log.isDebugEnabled())
266                     m_log.debugStream() << "decrypted Assertion: " << *decrypted << logging::eol;
267             }
268         }
269         catch (exception& ex) {
270             m_log.error(ex.what());
271         }
272         if (!decrypted)
273             continue;
274
275         try {
276             // We clear the security flag, so we can tell whether the token was secured on its own.
277             policy.setAuthenticated(false);
278             policy.reset(true);
279
280             // Extract message bits and re-verify Issuer information.
281             extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
282
283             // Run the policy over the assertion. Handles replay, freshness, and
284             // signature verification, assuming the relevant rules are configured,
285             // along with condition and profile enforcement.
286             // We have to marshall the object first to ensure signatures can be checked.
287             if (!decrypted->getDOM())
288                 decrypted->marshall();
289             policy.evaluate(*decrypted, &httpRequest);
290
291             // If no security is in place now, we kick it.
292             if (!alreadySecured && !policy.isAuthenticated())
293                 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
294
295             // If we hadn't established Issuer yet, redo the signedAssertions check.
296             if (!entity && policy.getIssuerMetadata()) {
297                 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
298                 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
299                 if (!decrypted->getSignature() && flag.first && flag.second)
300                     throw SecurityPolicyException("The decrypted assertion was unsigned, violating local security policy.");
301             }
302
303             // Address checking.
304             SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
305                 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
306                 );
307             if (subcondata && subcondata->getAddress()) {
308                 auto_ptr_char boundip(subcondata->getAddress());
309                 checkAddress(application, httpRequest, boundip.get());
310             }
311
312             // Track it as a valid token.
313             tokens.push_back(decrypted);
314
315             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
316             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
317             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
318                 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
319                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
320                 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
321                     ssoStatement = *s;
322             }
323
324             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
325             if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
326                 ssoSubject = decrypted->getSubject();
327         }
328         catch (exception& ex) {
329             m_log.warn("detected a problem with assertion: %s", ex.what());
330             if (!ssoStatement)
331                 contextualError = ex.what();
332             badtokens.push_back(decrypted);
333         }
334     }
335
336     if (!ssoStatement) {
337         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
338         if (contextualError.empty())
339             throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
340         throw FatalProfileException(contextualError.c_str());
341     }
342
343     // May need to decrypt NameID.
344     bool ownedName = false;
345     NameID* ssoName = ssoSubject->getNameID();
346     if (!ssoName) {
347         EncryptedID* encname = ssoSubject->getEncryptedID();
348         if (encname) {
349             if (!cr)
350                 m_log.warn("found encrypted NameID, but no decryption credential was available");
351             else {
352                 Locker credlocker(cr);
353                 auto_ptr<MetadataCredentialCriteria> mcc(
354                     policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
355                     );
356                 try {
357                     auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get()));
358                     ssoName = dynamic_cast<NameID*>(decryptedID.get());
359                     if (ssoName) {
360                         ownedName = true;
361                         decryptedID.release();
362                         if (m_log.isDebugEnabled())
363                             m_log.debugStream() << "decrypted NameID: " << *ssoName << logging::eol;
364                     }
365                 }
366                 catch (exception& ex) {
367                     m_log.error(ex.what());
368                 }
369             }
370         }
371     }
372
373     m_log.debug("SSO profile processing completed successfully");
374
375     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
376     // To complete processing, we need to extract and resolve attributes and then create the session.
377
378     // Now we have to extract the authentication details for session setup.
379
380     // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
381     time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ?
382         (ssoStatement->getSessionNotOnOrAfterEpoch() + XMLToolingConfig::getConfig().clock_skew_secs) : 0;
383     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
384     if (!lifetime.first || lifetime.second == 0)
385         lifetime.second = 28800;
386     if (sessionExp == 0)
387         sessionExp = now + lifetime.second;     // IdP says nothing, calulate based on SP.
388     else
389         sessionExp = min(sessionExp, now + lifetime.second);    // Use the lowest.
390
391     const AuthnContext* authnContext = ssoStatement->getAuthnContext();
392
393     try {
394         // The context will handle deleting attributes and new tokens.
395         auto_ptr<ResolutionContext> ctx(
396             resolveAttributes(
397                 application,
398                 policy.getIssuerMetadata(),
399                 samlconstants::SAML20P_NS,
400                 NULL,
401                 ssoName,
402                 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
403                 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
404                 &tokens
405                 )
406             );
407
408         if (ctx.get()) {
409             // Copy over any new tokens, but leave them in the context for cleanup.
410             tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
411         }
412
413         // Now merge in bad tokens for caching.
414         tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
415
416         application.getServiceProvider().getSessionCache()->insert(
417             application,
418             httpRequest,
419             httpResponse,
420             sessionExp,
421             entity,
422             samlconstants::SAML20P_NS,
423             ssoName,
424             ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
425             ssoStatement->getSessionIndex(),
426             (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
427             (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
428             &tokens,
429             ctx.get() ? &ctx->getResolvedAttributes() : NULL
430             );
431
432         if (ownedName)
433             delete ssoName;
434         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
435     }
436     catch (exception&) {
437         if (ownedName)
438             delete ssoName;
439         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
440         throw;
441     }
442 }
443
444 #endif