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