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 // 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 // Skip unsigned assertion?
245 if (!decrypted->getSignature() && flag.first && flag.second)
246 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
248 // We clear the security flag, so we can tell whether the token was secured on its own.
249 policy.setAuthenticated(false);
252 // Extract message bits and re-verify Issuer information.
253 extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
255 // Run the policy over the assertion. Handles replay, freshness, and
256 // signature verification, assuming the relevant rules are configured.
257 // We have to marshall the object first to ensure signatures can be checked.
258 if (!decrypted->getDOM())
259 decrypted->marshall();
260 policy.evaluate(*decrypted);
262 // If no security is in place now, we kick it.
263 if (!alreadySecured && !policy.isAuthenticated())
264 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
266 // Now do profile and core semantic validation to ensure we can use it for SSO.
267 BrowserSSOProfileValidator ssoValidator(
268 application.getRelyingParty(entity)->getXMLString("entityID").second, application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str()
270 ssoValidator.validateAssertion(*decrypted);
273 checkAddress(application, httpRequest, ssoValidator.getAddress());
275 // Track it as a valid token.
276 tokens.push_back(decrypted);
278 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
279 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
280 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
281 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
282 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
283 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
287 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
288 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
289 ssoSubject = decrypted->getSubject();
291 catch (exception& ex) {
292 m_log.warn("detected a problem with assertion: %s", ex.what());
294 contextualError = ex.what();
295 badtokens.push_back(decrypted);
300 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
301 if (contextualError.empty())
302 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
303 throw FatalProfileException(contextualError.c_str());
306 // May need to decrypt NameID.
307 bool ownedName = false;
308 NameID* ssoName = ssoSubject->getNameID();
310 EncryptedID* encname = ssoSubject->getEncryptedID();
313 m_log.warn("found encrypted NameID, but no decryption credential was available");
315 Locker credlocker(cr);
316 auto_ptr<MetadataCredentialCriteria> mcc(
317 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
320 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get()));
321 ssoName = dynamic_cast<NameID*>(decryptedID.get());
324 decryptedID.release();
325 if (m_log.isDebugEnabled())
326 m_log.debugStream() << "decrypted NameID: " << *ssoName << logging::eol;
329 catch (exception& ex) {
330 m_log.error(ex.what());
336 m_log.debug("SSO profile processing completed successfully");
338 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
339 // To complete processing, we need to extract and resolve attributes and then create the session.
341 // Now we have to extract the authentication details for session setup.
343 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
344 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
345 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
346 if (!lifetime.first || lifetime.second == 0)
347 lifetime.second = 28800;
349 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
351 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
353 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
356 // The context will handle deleting attributes and new tokens.
357 auto_ptr<ResolutionContext> ctx(
360 policy.getIssuerMetadata(),
361 samlconstants::SAML20P_NS,
364 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
365 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
371 // Copy over any new tokens, but leave them in the context for cleanup.
372 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
375 // Now merge in bad tokens for caching.
376 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
378 application.getServiceProvider().getSessionCache()->insert(
384 samlconstants::SAML20P_NS,
386 ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
387 ssoStatement->getSessionIndex(),
388 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
389 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
391 ctx.get() ? &ctx->getResolvedAttributes() : NULL
396 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
401 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());