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