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