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 // Saves off IP-mismatch error message because it's potentially helpful for users.
142 string addressMismatch;
144 for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
145 // Skip unsigned assertion?
146 if (!(*a)->getSignature() && flag.first && flag.second) {
147 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
148 badtokens.push_back(*a);
153 // We clear the security flag, so we can tell whether the token was secured on its own.
154 policy.setAuthenticated(false);
157 // Extract message bits and re-verify Issuer information.
158 extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
160 // Run the policy over the assertion. Handles replay, freshness, and
161 // signature verification, assuming the relevant rules are configured.
162 policy.evaluate(*(*a));
164 // If no security is in place now, we kick it.
165 if (!alreadySecured && !policy.isAuthenticated()) {
166 m_log.warn("unable to establish security of assertion");
167 badtokens.push_back(*a);
171 // Now do profile and core semantic validation to ensure we can use it for SSO.
172 ssoValidator.validateAssertion(*(*a));
176 if (ssoValidator.getAddress())
177 checkAddress(application, httpRequest, ssoValidator.getAddress());
179 catch (exception& ex) {
180 // We save off the message if there's no SSO statement yet.
182 addressMismatch = ex.what();
186 // Track it as a valid token.
187 tokens.push_back(*a);
189 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
190 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
191 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
192 if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
196 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
197 if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
198 ssoSubject = (*a)->getSubject();
200 catch (exception& ex) {
201 m_log.warn("detected a problem with assertion: %s", ex.what());
202 badtokens.push_back(*a);
206 // In case we need decryption...
207 CredentialResolver* cr=application.getCredentialResolver();
208 if (!cr && !encassertions.empty())
209 m_log.warn("found encrypted assertions, but no CredentialResolver was available");
211 for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
212 // Attempt to decrypt it.
213 saml2::Assertion* decrypted=NULL;
215 Locker credlocker(cr);
216 auto_ptr<MetadataCredentialCriteria> mcc(
217 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
219 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, mcc.get()));
220 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
223 ownedtokens.push_back(decrypted);
226 catch (exception& ex) {
227 m_log.error(ex.what());
232 // Skip unsigned assertion?
233 if (!decrypted->getSignature() && flag.first && flag.second) {
234 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
235 badtokens.push_back(decrypted);
240 // We clear the security flag, so we can tell whether the token was secured on its own.
241 policy.setAuthenticated(false);
244 // Extract message bits and re-verify Issuer information.
245 extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
247 // Run the policy over the assertion. Handles replay, freshness, and
248 // signature verification, assuming the relevant rules are configured.
249 // We have to marshall the object first to ensure signatures can be checked.
250 if (!decrypted->getDOM())
251 decrypted->marshall();
252 policy.evaluate(*decrypted);
254 // If no security is in place now, we kick it.
255 if (!alreadySecured && !policy.isAuthenticated()) {
256 m_log.warn("unable to establish security of assertion");
257 badtokens.push_back(decrypted);
261 // Now do profile and core semantic validation to ensure we can use it for SSO.
262 ssoValidator.validateAssertion(*decrypted);
266 if (ssoValidator.getAddress())
267 checkAddress(application, httpRequest, ssoValidator.getAddress());
269 catch (exception& ex) {
270 // We save off the message if there's no SSO statement yet.
272 addressMismatch = ex.what();
276 // Track it as a valid token.
277 tokens.push_back(decrypted);
279 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
280 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
281 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
282 if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
286 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
287 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
288 ssoSubject = decrypted->getSubject();
290 catch (exception& ex) {
291 m_log.warn("detected a problem with assertion: %s", ex.what());
292 badtokens.push_back(decrypted);
297 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
298 if (addressMismatch.empty())
299 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
300 throw FatalProfileException(addressMismatch.c_str());
303 // May need to decrypt NameID.
304 bool ownedName = false;
305 NameID* ssoName = ssoSubject->getNameID();
307 EncryptedID* encname = ssoSubject->getEncryptedID();
310 m_log.warn("found encrypted NameID, but no decryption credential was available");
312 Locker credlocker(cr);
313 auto_ptr<MetadataCredentialCriteria> mcc(
314 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
317 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
318 ssoName = dynamic_cast<NameID*>(decryptedID.get());
321 decryptedID.release();
324 catch (exception& ex) {
325 m_log.error(ex.what());
331 m_log.debug("SSO profile processing completed successfully");
333 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
334 // To complete processing, we need to extract and resolve attributes and then create the session.
336 // Now we have to extract the authentication details for session setup.
338 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
339 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
340 const PropertySet* sessionProps = application.getPropertySet("Sessions");
341 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
342 if (!lifetime.first || lifetime.second == 0)
343 lifetime.second = 28800;
345 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
347 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
349 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
352 // The context will handle deleting attributes and new tokens.
353 auto_ptr<ResolutionContext> ctx(
356 policy.getIssuerMetadata(),
357 samlconstants::SAML20P_NS,
360 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
361 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
367 // Copy over any new tokens, but leave them in the context for cleanup.
368 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
371 // Now merge in bad tokens for caching.
372 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
374 string key = application.getServiceProvider().getSessionCache()->insert(
377 httpRequest.getRemoteAddr().c_str(),
378 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
379 samlconstants::SAML20P_NS,
381 ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
382 ssoStatement->getSessionIndex(),
383 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
384 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
386 ctx.get() ? &ctx->getResolvedAttributes() : NULL
391 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
397 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());