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, policy.getIssuerMetadata());
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 // With this flag on, we ignore any unsigned assertions.
136 const EntityDescriptor* entity = NULL;
137 pair<bool,bool> flag = make_pair(false,false);
138 if (alreadySecured && policy.getIssuerMetadata()) {
139 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
140 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
143 time_t now = time(NULL);
144 string dest = httpRequest.getRequestURL();
146 // authnskew allows rejection of SSO if AuthnInstant is too old.
147 const PropertySet* sessionProps = application.getPropertySet("Sessions");
148 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
150 // Saves off error messages potentially helpful for users.
151 string contextualError;
153 for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
155 // Skip unsigned assertion?
156 if (!(*a)->getSignature() && flag.first && flag.second)
157 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
159 // We clear the security flag, so we can tell whether the token was secured on its own.
160 policy.setAuthenticated(false);
163 // Extract message bits and re-verify Issuer information.
164 extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
166 // Run the policy over the assertion. Handles replay, freshness, and
167 // signature verification, assuming the relevant rules are configured.
168 policy.evaluate(*(*a));
170 // If no security is in place now, we kick it.
171 if (!alreadySecured && !policy.isAuthenticated())
172 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
174 // If we hadn't established Issuer yet, redo the signedAssertions check.
175 if (!entity && policy.getIssuerMetadata()) {
176 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
177 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
178 if (!(*a)->getSignature() && flag.first && flag.second)
179 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
182 // Now do profile and core semantic validation to ensure we can use it for SSO.
183 BrowserSSOProfileValidator ssoValidator(
184 application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str()
186 ssoValidator.validateAssertion(*(*a));
189 checkAddress(application, httpRequest, ssoValidator.getAddress());
191 // Track it as a valid token.
192 tokens.push_back(*a);
194 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
195 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
196 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
197 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
198 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
199 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
203 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
204 if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
205 ssoSubject = (*a)->getSubject();
207 catch (exception& ex) {
208 m_log.warn("detected a problem with assertion: %s", ex.what());
210 contextualError = ex.what();
211 badtokens.push_back(*a);
215 // In case we need decryption...
216 CredentialResolver* cr=application.getCredentialResolver();
217 if (!cr && !encassertions.empty())
218 m_log.warn("found encrypted assertions, but no CredentialResolver was available");
220 for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
221 // Attempt to decrypt it.
222 saml2::Assertion* decrypted=NULL;
224 Locker credlocker(cr);
225 auto_ptr<MetadataCredentialCriteria> mcc(
226 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
228 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
229 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
232 ownedtokens.push_back(decrypted);
233 if (m_log.isDebugEnabled())
234 m_log.debugStream() << "decrypted Assertion: " << *decrypted << logging::eol;
237 catch (exception& ex) {
238 m_log.error(ex.what());
244 // We clear the security flag, so we can tell whether the token was secured on its own.
245 policy.setAuthenticated(false);
248 // Extract message bits and re-verify Issuer information.
249 extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
251 // Run the policy over the assertion. Handles replay, freshness, and
252 // signature verification, assuming the relevant rules are configured.
253 // We have to marshall the object first to ensure signatures can be checked.
254 if (!decrypted->getDOM())
255 decrypted->marshall();
256 policy.evaluate(*decrypted);
258 // If no security is in place now, we kick it.
259 if (!alreadySecured && !policy.isAuthenticated())
260 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
262 // If we hadn't established Issuer yet, redo the signedAssertions check.
263 if (!entity && policy.getIssuerMetadata()) {
264 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
265 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
266 if (!decrypted->getSignature() && flag.first && flag.second)
267 throw SecurityPolicyException("The decrypted assertion was unsigned, violating local security policy.");
270 // Now do profile and core semantic validation to ensure we can use it for SSO.
271 BrowserSSOProfileValidator ssoValidator(
272 application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str()
274 ssoValidator.validateAssertion(*decrypted);
277 checkAddress(application, httpRequest, ssoValidator.getAddress());
279 // Track it as a valid token.
280 tokens.push_back(decrypted);
282 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
283 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
284 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
285 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
286 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
287 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
291 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
292 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
293 ssoSubject = decrypted->getSubject();
295 catch (exception& ex) {
296 m_log.warn("detected a problem with assertion: %s", ex.what());
298 contextualError = ex.what();
299 badtokens.push_back(decrypted);
304 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
305 if (contextualError.empty())
306 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
307 throw FatalProfileException(contextualError.c_str());
310 // May need to decrypt NameID.
311 bool ownedName = false;
312 NameID* ssoName = ssoSubject->getNameID();
314 EncryptedID* encname = ssoSubject->getEncryptedID();
317 m_log.warn("found encrypted NameID, but no decryption credential was available");
319 Locker credlocker(cr);
320 auto_ptr<MetadataCredentialCriteria> mcc(
321 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
324 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get()));
325 ssoName = dynamic_cast<NameID*>(decryptedID.get());
328 decryptedID.release();
329 if (m_log.isDebugEnabled())
330 m_log.debugStream() << "decrypted NameID: " << *ssoName << logging::eol;
333 catch (exception& ex) {
334 m_log.error(ex.what());
340 m_log.debug("SSO profile processing completed successfully");
342 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
343 // To complete processing, we need to extract and resolve attributes and then create the session.
345 // Now we have to extract the authentication details for session setup.
347 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
348 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ?
349 (ssoStatement->getSessionNotOnOrAfterEpoch() + XMLToolingConfig::getConfig().clock_skew_secs) : 0;
350 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
351 if (!lifetime.first || lifetime.second == 0)
352 lifetime.second = 28800;
354 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
356 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
358 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
361 // The context will handle deleting attributes and new tokens.
362 auto_ptr<ResolutionContext> ctx(
365 policy.getIssuerMetadata(),
366 samlconstants::SAML20P_NS,
369 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
370 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
376 // Copy over any new tokens, but leave them in the context for cleanup.
377 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
380 // Now merge in bad tokens for caching.
381 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
383 application.getServiceProvider().getSessionCache()->insert(
389 samlconstants::SAML20P_NS,
391 ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
392 ssoStatement->getSessionIndex(),
393 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
394 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
396 ctx.get() ? &ctx->getResolvedAttributes() : NULL
401 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
406 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());