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/resolver/ResolutionContext.h"
32 # include <saml/saml2/core/Protocols.h>
33 # include <saml/saml2/profile/BrowserSSOProfileValidator.h>
34 # include <saml/saml2/metadata/Metadata.h>
35 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
36 using namespace opensaml::saml2;
37 using namespace opensaml::saml2p;
38 using namespace opensaml::saml2md;
39 using namespace opensaml;
41 # define min(a,b) (((a) < (b)) ? (a) : (b))
45 using namespace shibsp;
46 using namespace xmltooling;
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".SSO.SAML2")) {
62 virtual ~SAML2Consumer() {}
66 string implementProtocol(
67 const Application& application,
68 const HTTPRequest& httpRequest,
69 SecurityPolicy& policy,
70 const PropertySet* settings,
71 const XMLObject& xmlObject
76 #if defined (_MSC_VER)
77 #pragma warning( pop )
80 Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
82 return new SAML2Consumer(p.first, p.second);
89 string SAML2Consumer::implementProtocol(
90 const Application& application,
91 const HTTPRequest& httpRequest,
92 SecurityPolicy& policy,
93 const PropertySet* settings,
94 const XMLObject& xmlObject
97 // Implementation of SAML 2.0 SSO profile(s).
98 m_log.debug("processing message against SAML 2.0 SSO profile");
100 // Remember whether we already established trust.
101 // None of the SAML 2 bindings require security at the protocol layer.
102 bool alreadySecured = policy.isSecure();
104 // Check for errors...this will throw if it's not a successful message.
105 checkError(&xmlObject);
107 const Response* response = dynamic_cast<const Response*>(&xmlObject);
109 throw FatalProfileException("Incoming message was not a samlp:Response.");
111 const vector<saml2::Assertion*>& assertions = response->getAssertions();
112 const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
113 if (assertions.empty() && encassertions.empty())
114 throw FatalProfileException("Incoming message contained no SAML assertions.");
116 // Maintain list of "legit" tokens to feed to SP subsystems.
117 const Subject* ssoSubject=NULL;
118 const AuthnStatement* ssoStatement=NULL;
119 vector<const opensaml::Assertion*> tokens;
121 // Also track "bad" tokens that we'll cache but not use.
122 // This is necessary because there may be valid tokens not aimed at us.
123 vector<const opensaml::Assertion*> badtokens;
125 // And also track "owned" tokens that we decrypt here.
126 vector<saml2::Assertion*> ownedtokens;
128 // Profile validator.
129 time_t now = time(NULL);
130 string dest = httpRequest.getRequestURL();
131 BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str());
133 // With this flag on, we ignore any unsigned assertions.
134 pair<bool,bool> flag = settings->getBool("signedAssertions");
136 // Saves off IP-mismatch error message because it's potentially helpful for users.
137 string addressMismatch;
139 for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
140 // Skip unsigned assertion?
141 if (!(*a)->getSignature() && flag.first && flag.second) {
142 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
143 badtokens.push_back(*a);
148 // We clear the security flag, so we can tell whether the token was secured on its own.
149 policy.setSecure(false);
151 // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
152 // and signature verification, assuming the relevant rules are configured.
153 policy.evaluate(*(*a));
155 // If no security is in place now, we kick it.
156 if (!alreadySecured && !policy.isSecure()) {
157 m_log.warn("unable to establish security of assertion");
158 badtokens.push_back(*a);
162 // Now do profile and core semantic validation to ensure we can use it for SSO.
163 ssoValidator.validateAssertion(*(*a));
167 if (ssoValidator.getAddress())
168 checkAddress(application, httpRequest, ssoValidator.getAddress());
170 catch (exception& ex) {
171 // We save off the message if there's no SSO statement yet.
173 addressMismatch = ex.what();
177 // Track it as a valid token.
178 tokens.push_back(*a);
180 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
181 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
182 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
183 if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
187 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
188 if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
189 ssoSubject = (*a)->getSubject();
191 catch (exception& ex) {
192 m_log.warn("detected a problem with assertion: %s", ex.what());
193 badtokens.push_back(*a);
197 // In case we need decryption...
198 CredentialResolver* cr=application.getCredentialResolver();
199 if (!cr && !encassertions.empty())
200 m_log.warn("found encrypted assertions, but no CredentialResolver was available");
202 for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
203 // Attempt to decrypt it.
204 saml2::Assertion* decrypted=NULL;
206 Locker credlocker(cr);
207 auto_ptr<MetadataCredentialCriteria> mcc(
208 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
210 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, mcc.get()));
211 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
214 ownedtokens.push_back(decrypted);
217 catch (exception& ex) {
218 m_log.error(ex.what());
223 // Skip unsigned assertion?
224 if (!decrypted->getSignature() && flag.first && flag.second) {
225 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
226 badtokens.push_back(decrypted);
231 // We clear the security flag, so we can tell whether the token was secured on its own.
232 policy.setSecure(false);
234 // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
235 // and signature verification, assuming the relevant rules are configured.
236 // We have to marshall the object first to ensure signatures can be checked.
237 policy.evaluate(*decrypted);
239 // If no security is in place now, we kick it.
240 if (!alreadySecured && !policy.isSecure()) {
241 m_log.warn("unable to establish security of assertion");
242 badtokens.push_back(decrypted);
246 // Now do profile and core semantic validation to ensure we can use it for SSO.
247 ssoValidator.validateAssertion(*decrypted);
251 if (ssoValidator.getAddress())
252 checkAddress(application, httpRequest, ssoValidator.getAddress());
254 catch (exception& ex) {
255 // We save off the message if there's no SSO statement yet.
257 addressMismatch = ex.what();
261 // Track it as a valid token.
262 tokens.push_back(decrypted);
264 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
265 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
266 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
267 if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
271 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
272 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
273 ssoSubject = decrypted->getSubject();
275 catch (exception& ex) {
276 m_log.warn("detected a problem with assertion: %s", ex.what());
277 badtokens.push_back(decrypted);
282 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
283 if (addressMismatch.empty())
284 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
285 throw FatalProfileException(addressMismatch.c_str());
288 // May need to decrypt NameID.
289 bool ownedName = false;
290 NameID* ssoName = ssoSubject->getNameID();
292 EncryptedID* encname = ssoSubject->getEncryptedID();
295 m_log.warn("found encrypted NameID, but no decryption credential was available");
297 Locker credlocker(cr);
298 auto_ptr<MetadataCredentialCriteria> mcc(
299 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
302 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
303 ssoName = dynamic_cast<NameID*>(decryptedID.get());
306 decryptedID.release();
309 catch (exception& ex) {
310 m_log.error(ex.what());
316 m_log.debug("SSO profile processing completed successfully");
318 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
319 // To complete processing, we need to extract and resolve attributes and then create the session.
321 // Now we have to extract the authentication details for session setup.
323 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
324 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
325 const PropertySet* sessionProps = application.getPropertySet("Sessions");
326 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
327 if (!lifetime.first || lifetime.second == 0)
328 lifetime.second = 28800;
330 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
332 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
334 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
337 // The context will handle deleting attributes and new tokens.
338 auto_ptr<ResolutionContext> ctx(
341 policy.getIssuerMetadata(),
342 samlconstants::SAML20P_NS,
345 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
346 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
352 // Copy over any new tokens, but leave them in the context for cleanup.
353 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
356 // Now merge in bad tokens for caching.
357 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
359 string key = application.getServiceProvider().getSessionCache()->insert(
362 httpRequest.getRemoteAddr().c_str(),
363 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
364 samlconstants::SAML20P_NS,
366 ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
367 ssoStatement->getSessionIndex(),
368 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
369 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
371 ctx.get() ? &ctx->getResolvedAttributes() : NULL
376 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
382 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());