2 * Copyright 2001-2009 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/SAMLConfig.h>
33 # include <saml/saml2/core/Protocols.h>
34 # include <saml/saml2/metadata/Metadata.h>
35 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
36 # include <saml/saml2/profile/SAML2AssertionPolicy.h>
37 # include <xmltooling/XMLToolingConfig.h>
38 # include <xmltooling/util/DateTime.h>
39 using namespace opensaml::saml2;
40 using namespace opensaml::saml2p;
41 using namespace opensaml::saml2md;
42 using namespace opensaml;
44 # define min(a,b) (((a) < (b)) ? (a) : (b))
48 using namespace shibsp;
49 using namespace xmltooling;
54 #if defined (_MSC_VER)
55 #pragma warning( push )
56 #pragma warning( disable : 4250 )
59 class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
62 SAML2Consumer(const DOMElement* e, const char* appId)
63 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML2")) {
66 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
67 m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(BEARER_POLICY_RULE, e);
70 virtual ~SAML2Consumer() {
77 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
78 AssertionConsumerService::generateMetadata(role, handlerURL);
79 role.addSupport(samlconstants::SAML20P_NS);
83 void implementProtocol(
84 const Application& application,
85 const HTTPRequest& httpRequest,
86 HTTPResponse& httpResponse,
87 SecurityPolicy& policy,
88 const PropertySet* settings,
89 const XMLObject& xmlObject
92 SecurityPolicyRule* m_ssoRule;
96 #if defined (_MSC_VER)
97 #pragma warning( pop )
100 Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
102 return new SAML2Consumer(p.first, p.second);
106 class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
109 _rulenamed(const char* name) : m_name(name) {}
110 bool operator()(const SecurityPolicyRule* rule) const {
111 return rule ? !strcmp(m_name, rule->getType()) : false;
121 void SAML2Consumer::implementProtocol(
122 const Application& application,
123 const HTTPRequest& httpRequest,
124 HTTPResponse& httpResponse,
125 SecurityPolicy& policy,
126 const PropertySet* settings,
127 const XMLObject& xmlObject
130 // Implementation of SAML 2.0 SSO profile(s).
131 m_log.debug("processing message against SAML 2.0 SSO profile");
133 // Remember whether we already established trust.
134 // None of the SAML 2 bindings require security at the protocol layer.
135 bool alreadySecured = policy.isAuthenticated();
137 // Check for errors...this will throw if it's not a successful message.
138 checkError(&xmlObject, policy.getIssuerMetadata());
140 const Response* response = dynamic_cast<const Response*>(&xmlObject);
142 throw FatalProfileException("Incoming message was not a samlp:Response.");
144 const vector<saml2::Assertion*>& assertions = response->getAssertions();
145 const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
146 if (assertions.empty() && encassertions.empty())
147 throw FatalProfileException("Incoming message contained no SAML assertions.");
149 // Maintain list of "legit" tokens to feed to SP subsystems.
150 const Subject* ssoSubject=NULL;
151 const AuthnStatement* ssoStatement=NULL;
152 vector<const opensaml::Assertion*> tokens;
154 // Also track "bad" tokens that we'll cache but not use.
155 // This is necessary because there may be valid tokens not aimed at us.
156 vector<const opensaml::Assertion*> badtokens;
158 // And also track "owned" tokens that we decrypt here.
159 vector<saml2::Assertion*> ownedtokens;
161 // With this flag on, we ignore any unsigned assertions.
162 const EntityDescriptor* entity = NULL;
163 pair<bool,bool> flag = make_pair(false,false);
164 if (alreadySecured && policy.getIssuerMetadata()) {
165 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
166 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
169 // authnskew allows rejection of SSO if AuthnInstant is too old.
170 const PropertySet* sessionProps = application.getPropertySet("Sessions");
171 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
173 // Saves off error messages potentially helpful for users.
174 string contextualError;
176 // Ensure the Bearer rule is in the policy set.
177 if (find_if(policy.getRules(), _rulenamed(BEARER_POLICY_RULE)) == NULL)
178 policy.getRules().push_back(m_ssoRule);
180 // Populate recipient as audience.
181 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
183 time_t now = time(NULL);
184 for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
186 // Skip unsigned assertion?
187 if (!(*a)->getSignature() && flag.first && flag.second)
188 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
190 // We clear the security flag, so we can tell whether the token was secured on its own.
191 policy.setAuthenticated(false);
194 // Extract message bits and re-verify Issuer information.
195 extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
197 // Run the policy over the assertion. Handles replay, freshness, and
198 // signature verification, assuming the relevant rules are configured,
199 // along with condition and profile enforcement.
200 policy.evaluate(*(*a), &httpRequest);
202 // If no security is in place now, we kick it.
203 if (!alreadySecured && !policy.isAuthenticated())
204 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
206 // If we hadn't established Issuer yet, redo the signedAssertions check.
207 if (!entity && policy.getIssuerMetadata()) {
208 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
209 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
210 if (!(*a)->getSignature() && flag.first && flag.second)
211 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
215 SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
216 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
218 if (subcondata && subcondata->getAddress()) {
219 auto_ptr_char boundip(subcondata->getAddress());
220 checkAddress(application, httpRequest, boundip.get());
223 // Track it as a valid token.
224 tokens.push_back(*a);
226 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
227 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
228 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
229 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
230 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
231 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
235 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
236 if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
237 ssoSubject = (*a)->getSubject();
239 catch (exception& ex) {
240 m_log.warn("detected a problem with assertion: %s", ex.what());
242 contextualError = ex.what();
243 badtokens.push_back(*a);
247 // In case we need decryption...
248 CredentialResolver* cr=application.getCredentialResolver();
249 if (!cr && !encassertions.empty())
250 m_log.warn("found encrypted assertions, but no CredentialResolver was available");
252 for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
253 // Attempt to decrypt it.
254 saml2::Assertion* decrypted=NULL;
256 Locker credlocker(cr);
257 auto_ptr<MetadataCredentialCriteria> mcc(
258 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
260 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
261 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
264 ownedtokens.push_back(decrypted);
265 if (m_log.isDebugEnabled())
266 m_log.debugStream() << "decrypted Assertion: " << *decrypted << logging::eol;
269 catch (exception& ex) {
270 m_log.error(ex.what());
276 // We clear the security flag, so we can tell whether the token was secured on its own.
277 policy.setAuthenticated(false);
280 // Extract message bits and re-verify Issuer information.
281 extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
283 // Run the policy over the assertion. Handles replay, freshness, and
284 // signature verification, assuming the relevant rules are configured,
285 // along with condition and profile enforcement.
286 // We have to marshall the object first to ensure signatures can be checked.
287 if (!decrypted->getDOM())
288 decrypted->marshall();
289 policy.evaluate(*decrypted, &httpRequest);
291 // If no security is in place now, we kick it.
292 if (!alreadySecured && !policy.isAuthenticated())
293 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
295 // If we hadn't established Issuer yet, redo the signedAssertions check.
296 if (!entity && policy.getIssuerMetadata()) {
297 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
298 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
299 if (!decrypted->getSignature() && flag.first && flag.second)
300 throw SecurityPolicyException("The decrypted assertion was unsigned, violating local security policy.");
304 SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
305 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
307 if (subcondata && subcondata->getAddress()) {
308 auto_ptr_char boundip(subcondata->getAddress());
309 checkAddress(application, httpRequest, boundip.get());
312 // Track it as a valid token.
313 tokens.push_back(decrypted);
315 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
316 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
317 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
318 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
319 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
320 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
324 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
325 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
326 ssoSubject = decrypted->getSubject();
328 catch (exception& ex) {
329 m_log.warn("detected a problem with assertion: %s", ex.what());
331 contextualError = ex.what();
332 badtokens.push_back(decrypted);
337 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
338 if (contextualError.empty())
339 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
340 throw FatalProfileException(contextualError.c_str());
343 // May need to decrypt NameID.
344 bool ownedName = false;
345 NameID* ssoName = ssoSubject->getNameID();
347 EncryptedID* encname = ssoSubject->getEncryptedID();
350 m_log.warn("found encrypted NameID, but no decryption credential was available");
352 Locker credlocker(cr);
353 auto_ptr<MetadataCredentialCriteria> mcc(
354 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
357 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get()));
358 ssoName = dynamic_cast<NameID*>(decryptedID.get());
361 decryptedID.release();
362 if (m_log.isDebugEnabled())
363 m_log.debugStream() << "decrypted NameID: " << *ssoName << logging::eol;
366 catch (exception& ex) {
367 m_log.error(ex.what());
373 m_log.debug("SSO profile processing completed successfully");
375 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
376 // To complete processing, we need to extract and resolve attributes and then create the session.
378 // Now we have to extract the authentication details for session setup.
380 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
381 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ?
382 (ssoStatement->getSessionNotOnOrAfterEpoch() + XMLToolingConfig::getConfig().clock_skew_secs) : 0;
383 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
384 if (!lifetime.first || lifetime.second == 0)
385 lifetime.second = 28800;
387 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
389 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
391 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
394 // The context will handle deleting attributes and new tokens.
395 auto_ptr<ResolutionContext> ctx(
398 policy.getIssuerMetadata(),
399 samlconstants::SAML20P_NS,
402 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
403 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
409 // Copy over any new tokens, but leave them in the context for cleanup.
410 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
413 // Now merge in bad tokens for caching.
414 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
416 application.getServiceProvider().getSessionCache()->insert(
422 samlconstants::SAML20P_NS,
424 ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
425 ssoStatement->getSessionIndex(),
426 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
427 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
429 ctx.get() ? &ctx->getResolvedAttributes() : NULL
434 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
439 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());