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 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.isAuthenticated();
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 // authnskew allows rejection of SSO if AuthnInstant is too old.
142 const PropertySet* sessionProps = application.getPropertySet("Sessions");
143 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("authnskew") : pair<bool,unsigned int>(false,0);
145 // Saves off error messages potentially helpful for users.
146 string contextualError;
148 for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
149 // Skip unsigned assertion?
150 if (!(*a)->getSignature() && flag.first && flag.second) {
151 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
152 badtokens.push_back(*a);
157 // We clear the security flag, so we can tell whether the token was secured on its own.
158 policy.setAuthenticated(false);
161 // Extract message bits and re-verify Issuer information.
162 extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
164 // Run the policy over the assertion. Handles replay, freshness, and
165 // signature verification, assuming the relevant rules are configured.
166 policy.evaluate(*(*a));
168 // If no security is in place now, we kick it.
169 if (!alreadySecured && !policy.isAuthenticated()) {
170 m_log.warn("unable to establish security of assertion");
171 badtokens.push_back(*a);
175 // Now do profile and core semantic validation to ensure we can use it for SSO.
176 ssoValidator.validateAssertion(*(*a));
180 if (ssoValidator.getAddress())
181 checkAddress(application, httpRequest, ssoValidator.getAddress());
183 catch (exception& ex) {
184 // We save off the message if there's no SSO statement yet.
186 contextualError = ex.what();
190 // Track it as a valid token.
191 tokens.push_back(*a);
193 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
194 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
195 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
196 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
197 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
198 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
202 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
203 if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
204 ssoSubject = (*a)->getSubject();
206 catch (exception& ex) {
207 m_log.warn("detected a problem with assertion: %s", ex.what());
208 badtokens.push_back(*a);
212 // In case we need decryption...
213 CredentialResolver* cr=application.getCredentialResolver();
214 if (!cr && !encassertions.empty())
215 m_log.warn("found encrypted assertions, but no CredentialResolver was available");
217 for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
218 // Attempt to decrypt it.
219 saml2::Assertion* decrypted=NULL;
221 Locker credlocker(cr);
222 auto_ptr<MetadataCredentialCriteria> mcc(
223 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
225 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, mcc.get()));
226 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
229 ownedtokens.push_back(decrypted);
232 catch (exception& ex) {
233 m_log.error(ex.what());
238 // Skip unsigned assertion?
239 if (!decrypted->getSignature() && flag.first && flag.second) {
240 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
241 badtokens.push_back(decrypted);
246 // We clear the security flag, so we can tell whether the token was secured on its own.
247 policy.setAuthenticated(false);
250 // Extract message bits and re-verify Issuer information.
251 extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
253 // Run the policy over the assertion. Handles replay, freshness, and
254 // signature verification, assuming the relevant rules are configured.
255 // We have to marshall the object first to ensure signatures can be checked.
256 if (!decrypted->getDOM())
257 decrypted->marshall();
258 policy.evaluate(*decrypted);
260 // If no security is in place now, we kick it.
261 if (!alreadySecured && !policy.isAuthenticated()) {
262 m_log.warn("unable to establish security of assertion");
263 badtokens.push_back(decrypted);
267 // Now do profile and core semantic validation to ensure we can use it for SSO.
268 ssoValidator.validateAssertion(*decrypted);
272 if (ssoValidator.getAddress())
273 checkAddress(application, httpRequest, ssoValidator.getAddress());
275 catch (exception& ex) {
276 // We save off the message if there's no SSO statement yet.
278 contextualError = ex.what();
282 // Track it as a valid token.
283 tokens.push_back(decrypted);
285 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
286 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
287 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
288 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
289 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
290 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
294 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
295 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
296 ssoSubject = decrypted->getSubject();
298 catch (exception& ex) {
299 m_log.warn("detected a problem with assertion: %s", ex.what());
300 badtokens.push_back(decrypted);
305 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
306 if (contextualError.empty())
307 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
308 throw FatalProfileException(contextualError.c_str());
311 // May need to decrypt NameID.
312 bool ownedName = false;
313 NameID* ssoName = ssoSubject->getNameID();
315 EncryptedID* encname = ssoSubject->getEncryptedID();
318 m_log.warn("found encrypted NameID, but no decryption credential was available");
320 Locker credlocker(cr);
321 auto_ptr<MetadataCredentialCriteria> mcc(
322 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
325 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
326 ssoName = dynamic_cast<NameID*>(decryptedID.get());
329 decryptedID.release();
332 catch (exception& ex) {
333 m_log.error(ex.what());
339 m_log.debug("SSO profile processing completed successfully");
341 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
342 // To complete processing, we need to extract and resolve attributes and then create the session.
344 // Now we have to extract the authentication details for session setup.
346 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
347 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
348 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
349 if (!lifetime.first || lifetime.second == 0)
350 lifetime.second = 28800;
352 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
354 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
356 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
359 // The context will handle deleting attributes and new tokens.
360 auto_ptr<ResolutionContext> ctx(
363 policy.getIssuerMetadata(),
364 samlconstants::SAML20P_NS,
367 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
368 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
374 // Copy over any new tokens, but leave them in the context for cleanup.
375 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
378 // Now merge in bad tokens for caching.
379 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
381 string key = application.getServiceProvider().getSessionCache()->insert(
384 httpRequest.getRemoteAddr().c_str(),
385 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
386 samlconstants::SAML20P_NS,
388 ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
389 ssoStatement->getSessionIndex(),
390 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
391 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
393 ctx.get() ? &ctx->getResolvedAttributes() : NULL
398 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
404 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());