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() {}
65 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
66 AssertionConsumerService::generateMetadata(role, handlerURL);
67 role.addSupport(samlconstants::SAML20P_NS);
71 void implementProtocol(
72 const Application& application,
73 const HTTPRequest& httpRequest,
74 HTTPResponse& httpResponse,
75 SecurityPolicy& policy,
76 const PropertySet* settings,
77 const XMLObject& xmlObject
82 #if defined (_MSC_VER)
83 #pragma warning( pop )
86 Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
88 return new SAML2Consumer(p.first, p.second);
95 void SAML2Consumer::implementProtocol(
96 const Application& application,
97 const HTTPRequest& httpRequest,
98 HTTPResponse& httpResponse,
99 SecurityPolicy& policy,
100 const PropertySet* settings,
101 const XMLObject& xmlObject
104 // Implementation of SAML 2.0 SSO profile(s).
105 m_log.debug("processing message against SAML 2.0 SSO profile");
107 // Remember whether we already established trust.
108 // None of the SAML 2 bindings require security at the protocol layer.
109 bool alreadySecured = policy.isAuthenticated();
111 // Check for errors...this will throw if it's not a successful message.
112 checkError(&xmlObject);
114 const Response* response = dynamic_cast<const Response*>(&xmlObject);
116 throw FatalProfileException("Incoming message was not a samlp:Response.");
118 const vector<saml2::Assertion*>& assertions = response->getAssertions();
119 const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
120 if (assertions.empty() && encassertions.empty())
121 throw FatalProfileException("Incoming message contained no SAML assertions.");
123 // Maintain list of "legit" tokens to feed to SP subsystems.
124 const Subject* ssoSubject=NULL;
125 const AuthnStatement* ssoStatement=NULL;
126 vector<const opensaml::Assertion*> tokens;
128 // Also track "bad" tokens that we'll cache but not use.
129 // This is necessary because there may be valid tokens not aimed at us.
130 vector<const opensaml::Assertion*> badtokens;
132 // And also track "owned" tokens that we decrypt here.
133 vector<saml2::Assertion*> ownedtokens;
135 // Profile validator.
136 time_t now = time(NULL);
137 string dest = httpRequest.getRequestURL();
138 BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str());
140 // With this flag on, we ignore any unsigned assertions.
141 pair<bool,bool> flag = settings->getBool("signedAssertions");
143 // authnskew allows rejection of SSO if AuthnInstant is too old.
144 const PropertySet* sessionProps = application.getPropertySet("Sessions");
145 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("authnskew") : pair<bool,unsigned int>(false,0);
147 // Saves off error messages potentially helpful for users.
148 string contextualError;
150 for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
152 // Skip unsigned assertion?
153 if (!(*a)->getSignature() && flag.first && flag.second)
154 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
156 // We clear the security flag, so we can tell whether the token was secured on its own.
157 policy.setAuthenticated(false);
160 // Extract message bits and re-verify Issuer information.
161 extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
163 // Run the policy over the assertion. Handles replay, freshness, and
164 // signature verification, assuming the relevant rules are configured.
165 policy.evaluate(*(*a));
167 // If no security is in place now, we kick it.
168 if (!alreadySecured && !policy.isAuthenticated())
169 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
171 // Now do profile and core semantic validation to ensure we can use it for SSO.
172 ssoValidator.validateAssertion(*(*a));
175 checkAddress(application, httpRequest, ssoValidator.getAddress());
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 (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
184 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
185 else 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());
196 contextualError = ex.what();
197 badtokens.push_back(*a);
201 // In case we need decryption...
202 CredentialResolver* cr=application.getCredentialResolver();
203 if (!cr && !encassertions.empty())
204 m_log.warn("found encrypted assertions, but no CredentialResolver was available");
206 for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
207 // Attempt to decrypt it.
208 saml2::Assertion* decrypted=NULL;
210 Locker credlocker(cr);
211 auto_ptr<MetadataCredentialCriteria> mcc(
212 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
214 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, mcc.get()));
215 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
218 ownedtokens.push_back(decrypted);
221 catch (exception& ex) {
222 m_log.error(ex.what());
228 // Skip unsigned assertion?
229 if (!decrypted->getSignature() && flag.first && flag.second)
230 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
232 // We clear the security flag, so we can tell whether the token was secured on its own.
233 policy.setAuthenticated(false);
236 // Extract message bits and re-verify Issuer information.
237 extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
239 // Run the policy over the assertion. Handles replay, freshness, and
240 // signature verification, assuming the relevant rules are configured.
241 // We have to marshall the object first to ensure signatures can be checked.
242 if (!decrypted->getDOM())
243 decrypted->marshall();
244 policy.evaluate(*decrypted);
246 // If no security is in place now, we kick it.
247 if (!alreadySecured && !policy.isAuthenticated())
248 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
250 // Now do profile and core semantic validation to ensure we can use it for SSO.
251 ssoValidator.validateAssertion(*decrypted);
254 checkAddress(application, httpRequest, ssoValidator.getAddress());
256 // Track it as a valid token.
257 tokens.push_back(decrypted);
259 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
260 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
261 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
262 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
263 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
264 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
268 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
269 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
270 ssoSubject = decrypted->getSubject();
272 catch (exception& ex) {
273 m_log.warn("detected a problem with assertion: %s", ex.what());
275 contextualError = ex.what();
276 badtokens.push_back(decrypted);
281 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
282 if (contextualError.empty())
283 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
284 throw FatalProfileException(contextualError.c_str());
287 // May need to decrypt NameID.
288 bool ownedName = false;
289 NameID* ssoName = ssoSubject->getNameID();
291 EncryptedID* encname = ssoSubject->getEncryptedID();
294 m_log.warn("found encrypted NameID, but no decryption credential was available");
296 Locker credlocker(cr);
297 auto_ptr<MetadataCredentialCriteria> mcc(
298 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
301 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
302 ssoName = dynamic_cast<NameID*>(decryptedID.get());
305 decryptedID.release();
308 catch (exception& ex) {
309 m_log.error(ex.what());
315 m_log.debug("SSO profile processing completed successfully");
317 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
318 // To complete processing, we need to extract and resolve attributes and then create the session.
320 // Now we have to extract the authentication details for session setup.
322 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
323 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
324 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
325 if (!lifetime.first || lifetime.second == 0)
326 lifetime.second = 28800;
328 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
330 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
332 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
335 // The context will handle deleting attributes and new tokens.
336 auto_ptr<ResolutionContext> ctx(
339 policy.getIssuerMetadata(),
340 samlconstants::SAML20P_NS,
343 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
344 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
350 // Copy over any new tokens, but leave them in the context for cleanup.
351 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
354 // Now merge in bad tokens for caching.
355 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
357 application.getServiceProvider().getSessionCache()->insert(
362 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
363 samlconstants::SAML20P_NS,
365 ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
366 ssoStatement->getSessionIndex(),
367 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
368 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
370 ctx.get() ? &ctx->getResolvedAttributes() : NULL
375 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
380 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());