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 "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SessionCache.h"
28 #include "attribute/Attribute.h"
29 #include "attribute/resolver/AttributeExtractor.h"
30 #include "attribute/resolver/ResolutionContext.h"
31 #include "handler/AssertionConsumerService.h"
33 #include <saml/saml2/core/Protocols.h>
34 #include <saml/saml2/profile/BrowserSSOProfileValidator.h>
35 #include <saml/saml2/metadata/Metadata.h>
36 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
38 using namespace shibsp;
39 using namespace opensaml::saml2;
40 using namespace opensaml::saml2p;
41 using namespace opensaml::saml2md;
42 using namespace opensaml;
43 using namespace xmltooling;
44 using namespace log4cpp;
49 #if defined (_MSC_VER)
50 #pragma warning( push )
51 #pragma warning( disable : 4250 )
54 class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
57 SAML2Consumer(const DOMElement* e, const char* appId)
58 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SAML2")) {
60 virtual ~SAML2Consumer() {}
63 string implementProtocol(
64 const Application& application,
65 const HTTPRequest& httpRequest,
66 SecurityPolicy& policy,
67 const PropertySet* settings,
68 const XMLObject& xmlObject
72 #if defined (_MSC_VER)
73 #pragma warning( pop )
76 Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
78 return new SAML2Consumer(p.first, p.second);
83 string SAML2Consumer::implementProtocol(
84 const Application& application,
85 const HTTPRequest& httpRequest,
86 SecurityPolicy& policy,
87 const PropertySet* settings,
88 const XMLObject& xmlObject
91 // Implementation of SAML 2.0 SSO profile(s).
92 m_log.debug("processing message against SAML 2.0 SSO profile");
94 // Remember whether we already established trust.
95 // None of the SAML 2 bindings require security at the protocol layer.
96 bool alreadySecured = policy.isSecure();
98 // Check for errors...this will throw if it's not a successful message.
99 checkError(&xmlObject);
101 const Response* response = dynamic_cast<const Response*>(&xmlObject);
103 throw FatalProfileException("Incoming message was not a samlp:Response.");
105 const vector<saml2::Assertion*>& assertions = response->getAssertions();
106 const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
107 if (assertions.empty() && encassertions.empty())
108 throw FatalProfileException("Incoming message contained no SAML assertions.");
110 // Maintain list of "legit" tokens to feed to SP subsystems.
111 const Subject* ssoSubject=NULL;
112 const AuthnStatement* ssoStatement=NULL;
113 vector<const opensaml::Assertion*> tokens;
115 // Also track "bad" tokens that we'll cache but not use.
116 // This is necessary because there may be valid tokens not aimed at us.
117 vector<const opensaml::Assertion*> badtokens;
119 // And also track "owned" tokens that we decrypt here.
120 vector<saml2::Assertion*> ownedtokens;
122 // Profile validator.
123 time_t now = time(NULL);
124 string dest = httpRequest.getRequestURL();
125 BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str());
127 // With this flag on, we ignore any unsigned assertions.
128 pair<bool,bool> flag = settings->getBool("signedAssertions");
130 // Saves off IP-mismatch error message because it's potentially helpful for users.
131 string addressMismatch;
133 for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
134 // Skip unsigned assertion?
135 if (!(*a)->getSignature() && flag.first && flag.second) {
136 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
137 badtokens.push_back(*a);
142 // We clear the security flag, so we can tell whether the token was secured on its own.
143 policy.setSecure(false);
145 // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
146 // and signature verification, assuming the relevant rules are configured.
147 policy.evaluate(*(*a));
149 // If no security is in place now, we kick it.
150 if (!alreadySecured && !policy.isSecure()) {
151 m_log.warn("unable to establish security of assertion");
152 badtokens.push_back(*a);
156 // Now do profile and core semantic validation to ensure we can use it for SSO.
157 ssoValidator.validateAssertion(*(*a));
161 if (ssoValidator.getAddress())
162 checkAddress(application, httpRequest, ssoValidator.getAddress());
164 catch (exception& ex) {
165 // We save off the message if there's no SSO statement yet.
167 addressMismatch = ex.what();
171 // Track it as a valid token.
172 tokens.push_back(*a);
174 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
175 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
176 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
177 if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
181 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
182 if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
183 ssoSubject = (*a)->getSubject();
185 catch (exception& ex) {
186 m_log.warn("detected a problem with assertion: %s", ex.what());
187 badtokens.push_back(*a);
191 // In case we need decryption...
192 CredentialResolver* cr=application.getCredentialResolver();
193 if (!cr && !encassertions.empty())
194 m_log.warn("found encrypted assertions, but no CredentialResolver was available");
196 for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
197 // Attempt to decrypt it.
198 saml2::Assertion* decrypted=NULL;
200 Locker credlocker(cr);
201 auto_ptr<MetadataCredentialCriteria> mcc(
202 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
204 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, mcc.get()));
205 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
208 ownedtokens.push_back(decrypted);
211 catch (exception& ex) {
212 m_log.error(ex.what());
217 // Skip unsigned assertion?
218 if (!decrypted->getSignature() && flag.first && flag.second) {
219 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
220 badtokens.push_back(decrypted);
225 // We clear the security flag, so we can tell whether the token was secured on its own.
226 policy.setSecure(false);
228 // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
229 // and signature verification, assuming the relevant rules are configured.
230 // We have to marshall the object first to ensure signatures can be checked.
231 policy.evaluate(*decrypted);
233 // If no security is in place now, we kick it.
234 if (!alreadySecured && !policy.isSecure()) {
235 m_log.warn("unable to establish security of assertion");
236 badtokens.push_back(decrypted);
240 // Now do profile and core semantic validation to ensure we can use it for SSO.
241 ssoValidator.validateAssertion(*decrypted);
245 if (ssoValidator.getAddress())
246 checkAddress(application, httpRequest, ssoValidator.getAddress());
248 catch (exception& ex) {
249 // We save off the message if there's no SSO statement yet.
251 addressMismatch = ex.what();
255 // Track it as a valid token.
256 tokens.push_back(decrypted);
258 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
259 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
260 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
261 if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
265 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
266 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
267 ssoSubject = decrypted->getSubject();
269 catch (exception& ex) {
270 m_log.warn("detected a problem with assertion: %s", ex.what());
271 badtokens.push_back(decrypted);
276 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
277 if (addressMismatch.empty())
278 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
279 throw FatalProfileException(addressMismatch.c_str());
282 // May need to decrypt NameID.
283 bool ownedName = false;
284 NameID* ssoName = ssoSubject->getNameID();
286 EncryptedID* encname = ssoSubject->getEncryptedID();
289 m_log.warn("found encrypted NameID, but no decryption credential was available");
291 Locker credlocker(cr);
292 auto_ptr<MetadataCredentialCriteria> mcc(
293 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
296 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
297 ssoName = dynamic_cast<NameID*>(decryptedID.get());
300 decryptedID.release();
303 catch (exception& ex) {
304 m_log.error(ex.what());
310 m_log.debug("SSO profile processing completed successfully");
312 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
313 // To complete processing, we need to extract and resolve attributes and then create the session.
315 multimap<string,Attribute*> resolvedAttributes;
316 AttributeExtractor* extractor = application.getAttributeExtractor();
318 Locker extlocker(extractor);
319 for (vector<const opensaml::Assertion*>::const_iterator t = tokens.begin(); t!=tokens.end(); ++t) {
321 extractor->extractAttributes(application, policy.getIssuerMetadata(), *(*t), resolvedAttributes);
323 catch (exception& ex) {
324 m_log.error("caught exception extracting attributes: %s", ex.what());
330 const EntityDescriptor* issuerMetadata =
331 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
332 auto_ptr<ResolutionContext> ctx(
333 resolveAttributes(application, issuerMetadata, ssoName, &tokens, &resolvedAttributes)
337 // Copy over any new tokens, but leave them in the context for cleanup.
338 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
340 // Copy over new attributes, and transfer ownership.
341 resolvedAttributes.insert(ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
342 ctx->getResolvedAttributes().clear();
345 // Now merge in bad tokens for caching.
346 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
348 // Now we have to extract the authentication details for session setup.
350 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
351 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
352 const PropertySet* sessionProps = application.getPropertySet("Sessions");
353 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : make_pair(true,28800);
355 lifetime.second = 28800;
356 if (lifetime.second != 0) {
358 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
360 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
364 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
365 auto_ptr_char authnClass((authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL);
366 auto_ptr_char authnDecl((authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL);
367 auto_ptr_char index(ssoStatement->getSessionIndex());
368 auto_ptr_char authnInstant(ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL);
370 string key = application.getServiceProvider().getSessionCache()->insert(
373 httpRequest.getRemoteAddr().c_str(),
383 resolvedAttributes.clear(); // Attributes are owned by cache now.
387 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
394 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
395 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());