ec62384fa2d3623ed0ae92b06ee7eb9d54845a71
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML2Consumer.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * SAML2Consumer.cpp
23  *
24  * SAML 2.0 assertion consumer service.
25  */
26
27 #include "internal.h"
28 #include "handler/AssertionConsumerService.h"
29
30 #ifndef SHIBSP_LITE
31 # include "Application.h"
32 # include "ServiceProvider.h"
33 # include "SessionCache.h"
34 # include "TransactionLog.h"
35 # include "attribute/resolver/ResolutionContext.h"
36 # include <boost/iterator/indirect_iterator.hpp>
37 # include <saml/exceptions.h>
38 # include <saml/SAMLConfig.h>
39 # include <saml/binding/SecurityPolicyRule.h>
40 # include <saml/saml2/core/Protocols.h>
41 # include <saml/saml2/metadata/Metadata.h>
42 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
43 # include <saml/saml2/profile/SAML2AssertionPolicy.h>
44 # include <xmltooling/XMLToolingConfig.h>
45 # include <xmltooling/io/HTTPRequest.h>
46 # include <xmltooling/util/DateTime.h>
47 using namespace opensaml::saml2;
48 using namespace opensaml::saml2p;
49 using namespace opensaml::saml2md;
50 using namespace opensaml;
51 using namespace boost;
52 # ifndef min
53 #  define min(a,b)            (((a) < (b)) ? (a) : (b))
54 # endif
55 #else
56 # include "lite/SAMLConstants.h"
57 #endif
58
59 using namespace shibsp;
60 using namespace xmltooling;
61 using namespace std;
62
63 namespace shibsp {
64
65 #if defined (_MSC_VER)
66     #pragma warning( push )
67     #pragma warning( disable : 4250 )
68 #endif
69
70     class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
71     {
72     public:
73         SAML2Consumer(const DOMElement* e, const char* appId)
74             : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML2")) {
75 #ifndef SHIBSP_LITE
76             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
77                 m_ssoRule.reset(SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(BEARER_POLICY_RULE, e));
78 #endif
79         }
80         virtual ~SAML2Consumer() {}
81
82 #ifndef SHIBSP_LITE
83         void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
84             AssertionConsumerService::generateMetadata(role, handlerURL);
85             role.addSupport(samlconstants::SAML20P_NS);
86         }
87
88     private:
89         void implementProtocol(
90             const Application& application,
91             const HTTPRequest& httpRequest,
92             HTTPResponse& httpResponse,
93             SecurityPolicy& policy,
94             const PropertySet*,
95             const XMLObject& xmlObject
96             ) const;
97
98         scoped_ptr<SecurityPolicyRule> m_ssoRule;
99 #else
100         const XMLCh* getProtocolFamily() const {
101             return samlconstants::SAML20P_NS;
102         }
103 #endif
104     };
105
106 #if defined (_MSC_VER)
107     #pragma warning( pop )
108 #endif
109
110     Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
111     {
112         return new SAML2Consumer(p.first, p.second);
113     }
114
115 #ifndef SHIBSP_LITE
116     class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
117     {
118     public:
119         _rulenamed(const char* name) : m_name(name) {}
120         bool operator()(const SecurityPolicyRule* rule) const {
121             return rule ? !strcmp(m_name, rule->getType()) : false;
122         }
123     private:
124         const char* m_name;
125     };
126 #endif
127 };
128
129 #ifndef SHIBSP_LITE
130
131 void SAML2Consumer::implementProtocol(
132     const Application& application,
133     const HTTPRequest& httpRequest,
134     HTTPResponse& httpResponse,
135     SecurityPolicy& policy,
136     const PropertySet*,
137     const XMLObject& xmlObject
138     ) const
139 {
140     // Implementation of SAML 2.0 SSO profile(s).
141     m_log.debug("processing message against SAML 2.0 SSO profile");
142
143     // Remember whether we already established trust.
144     // None of the SAML 2 bindings require security at the protocol layer.
145     bool alreadySecured = policy.isAuthenticated();
146
147     // Check for errors...this will throw if it's not a successful message.
148     checkError(&xmlObject, policy.getIssuerMetadata());
149
150     const Response* response = dynamic_cast<const Response*>(&xmlObject);
151     if (!response)
152         throw FatalProfileException("Incoming message was not a samlp:Response.");
153
154     const vector<saml2::Assertion*>& assertions = response->getAssertions();
155     const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
156     if (assertions.empty() && encassertions.empty())
157         throw FatalProfileException("Incoming message contained no SAML assertions.");
158
159     // Maintain list of "legit" tokens to feed to SP subsystems.
160     const Subject* ssoSubject=nullptr;
161     const AuthnStatement* ssoStatement=nullptr;
162     vector<const opensaml::Assertion*> tokens;
163
164     // Also track "bad" tokens that we'll cache but not use.
165     // This is necessary because there may be valid tokens not aimed at us.
166     vector<const opensaml::Assertion*> badtokens;
167
168     // And also track "owned" tokens that we decrypt here.
169     vector< boost::shared_ptr<saml2::Assertion> > ownedtokens;
170
171     // With this flag on, we block unauthenticated ciphertext when decrypting,
172     // unless the protocol was authenticated.
173     pair<bool,bool> requireAuthenticatedEncryption = application.getBool("requireAuthenticatedEncryption");
174     if (alreadySecured)
175         requireAuthenticatedEncryption.second = false;
176
177     // With this flag on, we ignore any unsigned assertions.
178     const EntityDescriptor* entity = nullptr;
179     pair<bool,bool> requireSignedAssertions = make_pair(false,false);
180     if (alreadySecured && policy.getIssuerMetadata()) {
181         entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
182         const PropertySet* rp = application.getRelyingParty(entity);
183         requireSignedAssertions = rp->getBool("requireSignedAssertions");
184     }
185
186     // authnskew allows rejection of SSO if AuthnInstant is too old.
187     const PropertySet* sessionProps = application.getPropertySet("Sessions");
188     pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
189
190     // Saves off error messages potentially helpful for users.
191     string contextualError;
192
193     // Ensure the Bearer rule is in the policy set.
194     if (find_if(policy.getRules(), _rulenamed(BEARER_POLICY_RULE)) == nullptr)
195         policy.getRules().push_back(m_ssoRule.get());
196
197     // Populate recipient as audience.
198     policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
199
200     time_t now = time(nullptr);
201     for (indirect_iterator<vector<saml2::Assertion*>::const_iterator> a = make_indirect_iterator(assertions.begin());
202             a != make_indirect_iterator(assertions.end()); ++a) {
203         try {
204             // Skip unsigned assertion?
205             if (!a->getSignature() && requireSignedAssertions.first && requireSignedAssertions.second)
206                 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
207
208             // We clear the security flag, so we can tell whether the token was secured on its own.
209             policy.setAuthenticated(false);
210             policy.reset(true);
211
212             // Extract message bits and re-verify Issuer information.
213             extractMessageDetails(*a, samlconstants::SAML20P_NS, policy);
214
215             // Run the policy over the assertion. Handles replay, freshness, and
216             // signature verification, assuming the relevant rules are configured,
217             // along with condition and profile enforcement.
218             policy.evaluate(*a, &httpRequest);
219
220             // If no security is in place now, we kick it.
221             if (!alreadySecured && !policy.isAuthenticated())
222                 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
223
224             // If we hadn't established Issuer yet, redo the signedAssertions check.
225             if (!entity && policy.getIssuerMetadata()) {
226                 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
227                 requireSignedAssertions = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
228                 if (!a->getSignature() && requireSignedAssertions.first && requireSignedAssertions.second)
229                     throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
230             }
231
232             // Address checking.
233             SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
234                 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
235                 );
236             if (subcondata && subcondata->getAddress()) {
237                 auto_ptr_char boundip(subcondata->getAddress());
238                 checkAddress(application, httpRequest, boundip.get());
239             }
240
241             // Track it as a valid token.
242             tokens.push_back(&(*a));
243
244             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
245             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion&>(*a).getAuthnStatements();
246             for (indirect_iterator<vector<AuthnStatement*>::const_iterator> s = make_indirect_iterator(statements.begin());
247                     s != make_indirect_iterator(statements.end()); ++s) {
248                 if (s->getAuthnInstant() && s->getAuthnInstantEpoch() - XMLToolingConfig::getConfig().clock_skew_secs > now) {
249                     contextualError = "The login time at your identity provider was future-dated.";
250                 }
251                 else if (authnskew.first && authnskew.second && s->getAuthnInstant() &&
252                         s->getAuthnInstantEpoch() <= now && (now - s->getAuthnInstantEpoch() > authnskew.second)) {
253                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the allowed limit.";
254                 }
255                 else if (authnskew.first && authnskew.second && s->getAuthnInstant() == nullptr) {
256                     contextualError = "Your identity provider did not supply a time of login, violating local policy.";
257                 }
258                 else if (!ssoStatement || s->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch()) {
259                     ssoStatement = &(*s);
260                 }
261             }
262
263             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
264             if (!ssoSubject || (!ssoSubject->getNameID() && a->getSubject()->getNameID()))
265                 ssoSubject = a->getSubject();
266         }
267         catch (std::exception& ex) {
268             m_log.warn("detected a problem with assertion: %s", ex.what());
269             if (!ssoStatement)
270                 contextualError = ex.what();
271             badtokens.push_back(&(*a));
272         }
273     }
274
275     // In case we need decryption...
276     CredentialResolver* cr = application.getCredentialResolver();
277     if (!cr && !encassertions.empty())
278         m_log.warn("found encrypted assertions, but no CredentialResolver was available");
279
280     for (indirect_iterator<vector<saml2::EncryptedAssertion*>::const_iterator> ea = make_indirect_iterator(encassertions.begin());
281             ea != make_indirect_iterator(encassertions.end()); ++ea) {
282         // Attempt to decrypt it.
283         boost::shared_ptr<saml2::Assertion> decrypted;
284         try {
285             Locker credlocker(cr);
286             scoped_ptr<MetadataCredentialCriteria> mcc(
287                 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : nullptr
288                 );
289             boost::shared_ptr<XMLObject> wrapper(
290                 ea->decrypt(
291                     *cr,
292                     application.getRelyingParty(entity)->getXMLString("entityID").second,
293                     mcc.get(),
294                     requireAuthenticatedEncryption.first && requireAuthenticatedEncryption.second
295                     )
296                 );
297             decrypted = dynamic_pointer_cast<saml2::Assertion>(wrapper);
298             if (decrypted) {
299                 ownedtokens.push_back(decrypted);
300                 if (m_log.isDebugEnabled())
301                     m_log.debugStream() << "decrypted Assertion: " << *decrypted << logging::eol;
302             }
303         }
304         catch (std::exception& ex) {
305             m_log.error("failed to decrypt assertion: %s", ex.what());
306         }
307         if (!decrypted)
308             continue;
309
310         try {
311             // Skip unsigned assertion?
312             if (!decrypted->getSignature() && requireSignedAssertions.first && requireSignedAssertions.second)
313                 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
314
315             // We clear the security flag, so we can tell whether the token was secured on its own.
316             policy.setAuthenticated(false);
317             policy.reset(true);
318
319             // Extract message bits and re-verify Issuer information.
320             extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
321
322             // Run the policy over the assertion. Handles replay, freshness, and
323             // signature verification, assuming the relevant rules are configured,
324             // along with condition and profile enforcement.
325             // We have to marshall the object first to ensure signatures can be checked.
326             if (!decrypted->getDOM())
327                 decrypted->marshall();
328             policy.evaluate(*decrypted, &httpRequest);
329
330             // If no security is in place now, we kick it.
331             if (!alreadySecured && !policy.isAuthenticated())
332                 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
333
334             // If we hadn't established Issuer yet, redo the signedAssertions check.
335             if (!entity && policy.getIssuerMetadata()) {
336                 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
337                 requireSignedAssertions = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
338                 if (!decrypted->getSignature() && requireSignedAssertions.first && requireSignedAssertions.second)
339                     throw SecurityPolicyException("The decrypted assertion was unsigned, violating local security policy.");
340             }
341
342             // Address checking.
343             SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
344                 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
345                 );
346             if (subcondata && subcondata->getAddress()) {
347                 auto_ptr_char boundip(subcondata->getAddress());
348                 checkAddress(application, httpRequest, boundip.get());
349             }
350
351             // Track it as a valid token.
352             tokens.push_back(decrypted.get());
353
354             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
355             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted.get())->getAuthnStatements();
356             for (indirect_iterator<vector<AuthnStatement*>::const_iterator> s = make_indirect_iterator(statements.begin());
357                     s != make_indirect_iterator(statements.end()); ++s) {
358                 if (authnskew.first && authnskew.second && s->getAuthnInstant() && (now - s->getAuthnInstantEpoch() > authnskew.second))
359                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
360                 else if (!ssoStatement || s->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
361                     ssoStatement = &(*s);
362             }
363
364             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
365             if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
366                 ssoSubject = decrypted->getSubject();
367         }
368         catch (std::exception& ex) {
369             m_log.warn("detected a problem with assertion: %s", ex.what());
370             if (!ssoStatement)
371                 contextualError = ex.what();
372             badtokens.push_back(decrypted.get());
373         }
374     }
375
376     if (!ssoStatement) {
377         if (contextualError.empty())
378             throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
379         throw FatalProfileException(contextualError.c_str());
380     }
381
382     // May need to decrypt NameID.
383     scoped_ptr<XMLObject> decryptedID;
384     NameID* ssoName = ssoSubject->getNameID();
385     if (!ssoName) {
386         EncryptedID* encname = ssoSubject->getEncryptedID();
387         if (encname) {
388             if (!cr)
389                 m_log.warn("found encrypted NameID, but no decryption credential was available");
390             else {
391                 Locker credlocker(cr);
392                 scoped_ptr<MetadataCredentialCriteria> mcc(
393                     policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : nullptr
394                     );
395                 try {
396                     decryptedID.reset(encname->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
397                     ssoName = dynamic_cast<NameID*>(decryptedID.get());
398                     if (ssoName) {
399                         if (m_log.isDebugEnabled())
400                             m_log.debugStream() << "decrypted NameID: " << *ssoName << logging::eol;
401                     }
402                 }
403                 catch (std::exception& ex) {
404                     m_log.error("failed to decrypt NameID: %s", ex.what());
405                 }
406             }
407         }
408     }
409
410     m_log.debug("SSO profile processing completed successfully");
411
412     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
413     // To complete processing, we need to extract and resolve attributes and then create the session.
414
415     // Now we have to extract the authentication details for session setup.
416
417     // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
418     time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ?
419         (ssoStatement->getSessionNotOnOrAfterEpoch() + XMLToolingConfig::getConfig().clock_skew_secs) : 0;
420     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
421     if (!lifetime.first || lifetime.second == 0)
422         lifetime.second = 28800;
423     if (sessionExp == 0)
424         sessionExp = now + lifetime.second;     // IdP says nothing, calulate based on SP.
425     else
426         sessionExp = min(sessionExp, now + lifetime.second);    // Use the lowest.
427
428     const AuthnContext* authnContext = ssoStatement->getAuthnContext();
429
430     // The context will handle deleting attributes and new tokens.
431     scoped_ptr<ResolutionContext> ctx(
432         resolveAttributes(
433             application,
434             &httpRequest,
435             policy.getIssuerMetadata(),
436             samlconstants::SAML20P_NS,
437             response,
438             nullptr,
439             nullptr,
440             ssoName,
441             ssoStatement,
442             (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : nullptr,
443             (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : nullptr,
444             &tokens
445             )
446         );
447
448     if (ctx) {
449         // Copy over any new tokens, but leave them in the context for cleanup.
450         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
451     }
452
453     // Now merge in bad tokens for caching.
454     tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
455
456     string session_id;
457     application.getServiceProvider().getSessionCache()->insert(
458         session_id,
459         application,
460         httpRequest,
461         httpResponse,
462         sessionExp,
463         entity,
464         samlconstants::SAML20P_NS,
465         ssoName,
466         ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : nullptr,
467         ssoStatement->getSessionIndex(),
468         (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : nullptr,
469         (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : nullptr,
470         &tokens,
471         ctx ? &ctx->getResolvedAttributes() : nullptr
472         );
473
474     try {
475         scoped_ptr<TransactionLog::Event> event(newLoginEvent(application, httpRequest));
476         LoginEvent* login_event = dynamic_cast<LoginEvent*>(event.get());
477         if (login_event) {
478             login_event->m_sessionID = session_id.c_str();
479             login_event->m_peer = entity;
480             auto_ptr_char prot(getProtocolFamily());
481             login_event->m_protocol = prot.get();
482             login_event->m_nameID = ssoName;
483             login_event->m_saml2AuthnStatement = ssoStatement;
484             login_event->m_saml2Response = response;
485             if (ctx)
486                 login_event->m_attributes = &ctx->getResolvedAttributes();
487             application.getServiceProvider().getTransactionLog()->write(*login_event);
488         }
489         else {
490             m_log.warn("unable to audit event, log event object was of an incorrect type");
491         }
492     }
493     catch (std::exception& ex) {
494         m_log.warn("exception auditing event: %s", ex.what());
495     }
496 }
497
498 #endif