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