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