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