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