2 * Copyright 2001-2007 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * SAML 2.0 assertion consumer service
24 #include "handler/AssertionConsumerService.h"
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;
46 using namespace shibsp;
47 using namespace xmltooling;
48 using namespace log4cpp;
53 #if defined (_MSC_VER)
54 #pragma warning( push )
55 #pragma warning( disable : 4250 )
58 class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
61 SAML2Consumer(const DOMElement* e, const char* appId)
62 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SAML2")) {
64 virtual ~SAML2Consumer() {}
68 string implementProtocol(
69 const Application& application,
70 const HTTPRequest& httpRequest,
71 SecurityPolicy& policy,
72 const PropertySet* settings,
73 const XMLObject& xmlObject
78 #if defined (_MSC_VER)
79 #pragma warning( pop )
82 Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
84 return new SAML2Consumer(p.first, p.second);
91 string SAML2Consumer::implementProtocol(
92 const Application& application,
93 const HTTPRequest& httpRequest,
94 SecurityPolicy& policy,
95 const PropertySet* settings,
96 const XMLObject& xmlObject
99 // Implementation of SAML 2.0 SSO profile(s).
100 m_log.debug("processing message against SAML 2.0 SSO profile");
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();
106 // Check for errors...this will throw if it's not a successful message.
107 checkError(&xmlObject);
109 const Response* response = dynamic_cast<const Response*>(&xmlObject);
111 throw FatalProfileException("Incoming message was not a samlp:Response.");
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.");
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;
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;
127 // And also track "owned" tokens that we decrypt here.
128 vector<saml2::Assertion*> ownedtokens;
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());
135 // With this flag on, we ignore any unsigned assertions.
136 pair<bool,bool> flag = settings->getBool("signedAssertions");
138 // Saves off IP-mismatch error message because it's potentially helpful for users.
139 string addressMismatch;
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);
150 // We clear the security flag, so we can tell whether the token was secured on its own.
151 policy.setSecure(false);
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));
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);
164 // Now do profile and core semantic validation to ensure we can use it for SSO.
165 ssoValidator.validateAssertion(*(*a));
169 if (ssoValidator.getAddress())
170 checkAddress(application, httpRequest, ssoValidator.getAddress());
172 catch (exception& ex) {
173 // We save off the message if there's no SSO statement yet.
175 addressMismatch = ex.what();
179 // Track it as a valid token.
180 tokens.push_back(*a);
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())
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();
193 catch (exception& ex) {
194 m_log.warn("detected a problem with assertion: %s", ex.what());
195 badtokens.push_back(*a);
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");
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;
208 Locker credlocker(cr);
209 auto_ptr<MetadataCredentialCriteria> mcc(
210 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
212 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, mcc.get()));
213 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
216 ownedtokens.push_back(decrypted);
219 catch (exception& ex) {
220 m_log.error(ex.what());
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);
233 // We clear the security flag, so we can tell whether the token was secured on its own.
234 policy.setSecure(false);
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);
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);
248 // Now do profile and core semantic validation to ensure we can use it for SSO.
249 ssoValidator.validateAssertion(*decrypted);
253 if (ssoValidator.getAddress())
254 checkAddress(application, httpRequest, ssoValidator.getAddress());
256 catch (exception& ex) {
257 // We save off the message if there's no SSO statement yet.
259 addressMismatch = ex.what();
263 // Track it as a valid token.
264 tokens.push_back(decrypted);
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())
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();
277 catch (exception& ex) {
278 m_log.warn("detected a problem with assertion: %s", ex.what());
279 badtokens.push_back(decrypted);
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());
290 // May need to decrypt NameID.
291 bool ownedName = false;
292 NameID* ssoName = ssoSubject->getNameID();
294 EncryptedID* encname = ssoSubject->getEncryptedID();
297 m_log.warn("found encrypted NameID, but no decryption credential was available");
299 Locker credlocker(cr);
300 auto_ptr<MetadataCredentialCriteria> mcc(
301 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
304 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
305 ssoName = dynamic_cast<NameID*>(decryptedID.get());
308 decryptedID.release();
311 catch (exception& ex) {
312 m_log.error(ex.what());
318 m_log.debug("SSO profile processing completed successfully");
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.
323 // Now we have to extract the authentication details for session setup.
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);
330 lifetime.second = 28800;
331 if (lifetime.second != 0) {
333 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
335 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
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);
345 multimap<string,Attribute*> resolvedAttributes;
346 AttributeExtractor* extractor = application.getAttributeExtractor();
348 m_log.debug("extracting pushed attributes...");
349 Locker extlocker(extractor);
351 extractor->extractAttributes(application, policy.getIssuerMetadata(), *ssoName, resolvedAttributes);
353 catch (exception& ex) {
354 m_log.error("caught exception extracting attributes: %s", ex.what());
356 for (vector<const opensaml::Assertion*>::const_iterator t = tokens.begin(); t!=tokens.end(); ++t) {
358 extractor->extractAttributes(application, policy.getIssuerMetadata(), *(*t), resolvedAttributes);
360 catch (exception& ex) {
361 m_log.error("caught exception extracting attributes: %s", ex.what());
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);
371 filter->filterAttributes(fc, resolvedAttributes);
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();
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)
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());
392 // Copy over new attributes, and transfer ownership.
393 resolvedAttributes.insert(ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
394 ctx->getResolvedAttributes().clear();
397 // Now merge in bad tokens for caching.
398 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
400 string key = application.getServiceProvider().getSessionCache()->insert(
403 httpRequest.getRemoteAddr().c_str(),
413 resolvedAttributes.clear(); // Attributes are owned by cache now.
417 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
424 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
425 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());