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