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