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;
45 # define min(a,b) (((a) < (b)) ? (a) : (b))
49 using namespace shibsp;
50 using namespace xmltooling;
51 using namespace log4cpp;
56 #if defined (_MSC_VER)
57 #pragma warning( push )
58 #pragma warning( disable : 4250 )
61 class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
64 SAML2Consumer(const DOMElement* e, const char* appId)
65 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SAML2SSO")) {
67 virtual ~SAML2Consumer() {}
71 string implementProtocol(
72 const Application& application,
73 const HTTPRequest& httpRequest,
74 SecurityPolicy& policy,
75 const PropertySet* settings,
76 const XMLObject& xmlObject
81 #if defined (_MSC_VER)
82 #pragma warning( pop )
85 Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
87 return new SAML2Consumer(p.first, p.second);
94 string SAML2Consumer::implementProtocol(
95 const Application& application,
96 const HTTPRequest& httpRequest,
97 SecurityPolicy& policy,
98 const PropertySet* settings,
99 const XMLObject& xmlObject
102 // Implementation of SAML 2.0 SSO profile(s).
103 m_log.debug("processing message against SAML 2.0 SSO profile");
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();
109 // Check for errors...this will throw if it's not a successful message.
110 checkError(&xmlObject);
112 const Response* response = dynamic_cast<const Response*>(&xmlObject);
114 throw FatalProfileException("Incoming message was not a samlp:Response.");
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.");
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;
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;
130 // And also track "owned" tokens that we decrypt here.
131 vector<saml2::Assertion*> ownedtokens;
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());
138 // With this flag on, we ignore any unsigned assertions.
139 pair<bool,bool> flag = settings->getBool("signedAssertions");
141 // Saves off IP-mismatch error message because it's potentially helpful for users.
142 string addressMismatch;
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);
153 // We clear the security flag, so we can tell whether the token was secured on its own.
154 policy.setSecure(false);
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));
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);
167 // Now do profile and core semantic validation to ensure we can use it for SSO.
168 ssoValidator.validateAssertion(*(*a));
172 if (ssoValidator.getAddress())
173 checkAddress(application, httpRequest, ssoValidator.getAddress());
175 catch (exception& ex) {
176 // We save off the message if there's no SSO statement yet.
178 addressMismatch = ex.what();
182 // Track it as a valid token.
183 tokens.push_back(*a);
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())
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();
196 catch (exception& ex) {
197 m_log.warn("detected a problem with assertion: %s", ex.what());
198 badtokens.push_back(*a);
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");
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;
211 Locker credlocker(cr);
212 auto_ptr<MetadataCredentialCriteria> mcc(
213 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
215 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, mcc.get()));
216 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
219 ownedtokens.push_back(decrypted);
222 catch (exception& ex) {
223 m_log.error(ex.what());
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);
236 // We clear the security flag, so we can tell whether the token was secured on its own.
237 policy.setSecure(false);
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);
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);
251 // Now do profile and core semantic validation to ensure we can use it for SSO.
252 ssoValidator.validateAssertion(*decrypted);
256 if (ssoValidator.getAddress())
257 checkAddress(application, httpRequest, ssoValidator.getAddress());
259 catch (exception& ex) {
260 // We save off the message if there's no SSO statement yet.
262 addressMismatch = ex.what();
266 // Track it as a valid token.
267 tokens.push_back(decrypted);
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())
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();
280 catch (exception& ex) {
281 m_log.warn("detected a problem with assertion: %s", ex.what());
282 badtokens.push_back(decrypted);
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());
293 // May need to decrypt NameID.
294 bool ownedName = false;
295 NameID* ssoName = ssoSubject->getNameID();
297 EncryptedID* encname = ssoSubject->getEncryptedID();
300 m_log.warn("found encrypted NameID, but no decryption credential was available");
302 Locker credlocker(cr);
303 auto_ptr<MetadataCredentialCriteria> mcc(
304 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
307 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
308 ssoName = dynamic_cast<NameID*>(decryptedID.get());
311 decryptedID.release();
314 catch (exception& ex) {
315 m_log.error(ex.what());
321 m_log.debug("SSO profile processing completed successfully");
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.
326 // Now we have to extract the authentication details for session setup.
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;
335 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
337 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
339 multimap<string,Attribute*> resolvedAttributes;
340 AttributeExtractor* extractor = application.getAttributeExtractor();
342 m_log.debug("extracting pushed attributes...");
343 Locker extlocker(extractor);
345 extractor->extractAttributes(application, policy.getIssuerMetadata(), *ssoName, resolvedAttributes);
347 catch (exception& ex) {
348 m_log.error("caught exception extracting attributes: %s", ex.what());
350 for (vector<const opensaml::Assertion*>::const_iterator t = tokens.begin(); t!=tokens.end(); ++t) {
352 extractor->extractAttributes(application, policy.getIssuerMetadata(), *(*t), resolvedAttributes);
354 catch (exception& ex) {
355 m_log.error("caught exception extracting attributes: %s", ex.what());
360 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
362 AttributeFilter* filter = application.getAttributeFilter();
363 if (filter && !resolvedAttributes.empty()) {
364 BasicFilteringContext fc(
367 policy.getIssuerMetadata(),
368 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
369 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL
371 Locker filtlocker(filter);
373 filter->filterAttributes(fc, resolvedAttributes);
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();
384 const EntityDescriptor* issuerMetadata =
385 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
386 auto_ptr<ResolutionContext> ctx(
390 samlconstants::SAML20P_NS,
392 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
393 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
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());
403 // Copy over new attributes, and transfer ownership.
404 resolvedAttributes.insert(ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
405 ctx->getResolvedAttributes().clear();
408 // Now merge in bad tokens for caching.
409 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
411 string key = application.getServiceProvider().getSessionCache()->insert(
414 httpRequest.getRemoteAddr().c_str(),
416 samlconstants::SAML20P_NS,
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,
425 resolvedAttributes.clear(); // Attributes are owned by cache now.
429 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
430 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());
436 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
437 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());