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/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"
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>
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;
51 #if defined (_MSC_VER)
52 #pragma warning( push )
53 #pragma warning( disable : 4250 )
56 class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
59 SAML2Consumer(const DOMElement* e, const char* appId)
60 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SAML2")) {
62 virtual ~SAML2Consumer() {}
65 string implementProtocol(
66 const Application& application,
67 const HTTPRequest& httpRequest,
68 SecurityPolicy& policy,
69 const PropertySet* settings,
70 const XMLObject& xmlObject
74 #if defined (_MSC_VER)
75 #pragma warning( pop )
78 Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
80 return new SAML2Consumer(p.first, p.second);
85 string SAML2Consumer::implementProtocol(
86 const Application& application,
87 const HTTPRequest& httpRequest,
88 SecurityPolicy& policy,
89 const PropertySet* settings,
90 const XMLObject& xmlObject
93 // Implementation of SAML 2.0 SSO profile(s).
94 m_log.debug("processing message against SAML 2.0 SSO profile");
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();
100 // Check for errors...this will throw if it's not a successful message.
101 checkError(&xmlObject);
103 const Response* response = dynamic_cast<const Response*>(&xmlObject);
105 throw FatalProfileException("Incoming message was not a samlp:Response.");
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.");
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;
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;
121 // And also track "owned" tokens that we decrypt here.
122 vector<saml2::Assertion*> ownedtokens;
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());
129 // With this flag on, we ignore any unsigned assertions.
130 pair<bool,bool> flag = settings->getBool("signedAssertions");
132 // Saves off IP-mismatch error message because it's potentially helpful for users.
133 string addressMismatch;
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);
144 // We clear the security flag, so we can tell whether the token was secured on its own.
145 policy.setSecure(false);
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));
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);
158 // Now do profile and core semantic validation to ensure we can use it for SSO.
159 ssoValidator.validateAssertion(*(*a));
163 if (ssoValidator.getAddress())
164 checkAddress(application, httpRequest, ssoValidator.getAddress());
166 catch (exception& ex) {
167 // We save off the message if there's no SSO statement yet.
169 addressMismatch = ex.what();
173 // Track it as a valid token.
174 tokens.push_back(*a);
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())
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();
187 catch (exception& ex) {
188 m_log.warn("detected a problem with assertion: %s", ex.what());
189 badtokens.push_back(*a);
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");
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;
202 Locker credlocker(cr);
203 auto_ptr<MetadataCredentialCriteria> mcc(
204 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
206 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, mcc.get()));
207 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
210 ownedtokens.push_back(decrypted);
213 catch (exception& ex) {
214 m_log.error(ex.what());
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);
227 // We clear the security flag, so we can tell whether the token was secured on its own.
228 policy.setSecure(false);
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);
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);
242 // Now do profile and core semantic validation to ensure we can use it for SSO.
243 ssoValidator.validateAssertion(*decrypted);
247 if (ssoValidator.getAddress())
248 checkAddress(application, httpRequest, ssoValidator.getAddress());
250 catch (exception& ex) {
251 // We save off the message if there's no SSO statement yet.
253 addressMismatch = ex.what();
257 // Track it as a valid token.
258 tokens.push_back(decrypted);
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())
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();
271 catch (exception& ex) {
272 m_log.warn("detected a problem with assertion: %s", ex.what());
273 badtokens.push_back(decrypted);
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());
284 // May need to decrypt NameID.
285 bool ownedName = false;
286 NameID* ssoName = ssoSubject->getNameID();
288 EncryptedID* encname = ssoSubject->getEncryptedID();
291 m_log.warn("found encrypted NameID, but no decryption credential was available");
293 Locker credlocker(cr);
294 auto_ptr<MetadataCredentialCriteria> mcc(
295 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
298 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
299 ssoName = dynamic_cast<NameID*>(decryptedID.get());
302 decryptedID.release();
305 catch (exception& ex) {
306 m_log.error(ex.what());
312 m_log.debug("SSO profile processing completed successfully");
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.
317 // Now we have to extract the authentication details for session setup.
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);
324 lifetime.second = 28800;
325 if (lifetime.second != 0) {
327 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
329 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
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);
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 AttributeFilter* filter = application.getAttributeFilter();
361 if (filter && !resolvedAttributes.empty()) {
362 BasicFilteringContext fc(application, resolvedAttributes, policy.getIssuerMetadata(), authnClass.get(), authnDecl.get());
363 Locker filtlocker(filter);
365 filter->filterAttributes(fc, resolvedAttributes);
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();
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)
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());
386 // Copy over new attributes, and transfer ownership.
387 resolvedAttributes.insert(ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
388 ctx->getResolvedAttributes().clear();
391 // Now merge in bad tokens for caching.
392 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
394 string key = application.getServiceProvider().getSessionCache()->insert(
397 httpRequest.getRemoteAddr().c_str(),
407 resolvedAttributes.clear(); // Attributes are owned by cache now.
411 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
418 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
419 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());