2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
24 * SAML 2.0 assertion consumer service.
28 #include "handler/AssertionConsumerService.h"
31 # include "Application.h"
32 # include "ServiceProvider.h"
33 # include "SessionCache.h"
34 # include "TransactionLog.h"
35 # include "attribute/resolver/ResolutionContext.h"
36 # include <boost/iterator/indirect_iterator.hpp>
37 # include <saml/exceptions.h>
38 # include <saml/SAMLConfig.h>
39 # include <saml/binding/SecurityPolicyRule.h>
40 # include <saml/saml2/core/Protocols.h>
41 # include <saml/saml2/metadata/Metadata.h>
42 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
43 # include <saml/saml2/profile/SAML2AssertionPolicy.h>
44 # include <xmltooling/XMLToolingConfig.h>
45 # include <xmltooling/io/HTTPRequest.h>
46 # include <xmltooling/util/DateTime.h>
47 using namespace opensaml::saml2;
48 using namespace opensaml::saml2p;
49 using namespace opensaml::saml2md;
50 using namespace opensaml;
51 using namespace boost;
53 # define min(a,b) (((a) < (b)) ? (a) : (b))
56 # include "lite/SAMLConstants.h"
59 using namespace shibsp;
60 using namespace xmltooling;
65 #if defined (_MSC_VER)
66 #pragma warning( push )
67 #pragma warning( disable : 4250 )
70 class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
73 SAML2Consumer(const DOMElement* e, const char* appId)
74 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML2")) {
76 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
77 m_ssoRule.reset(SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(BEARER_POLICY_RULE, e));
80 virtual ~SAML2Consumer() {}
83 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
84 AssertionConsumerService::generateMetadata(role, handlerURL);
85 role.addSupport(samlconstants::SAML20P_NS);
89 void implementProtocol(
90 const Application& application,
91 const HTTPRequest& httpRequest,
92 HTTPResponse& httpResponse,
93 SecurityPolicy& policy,
95 const XMLObject& xmlObject
98 scoped_ptr<SecurityPolicyRule> m_ssoRule;
100 const XMLCh* getProtocolFamily() const {
101 return samlconstants::SAML20P_NS;
106 #if defined (_MSC_VER)
107 #pragma warning( pop )
110 Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
112 return new SAML2Consumer(p.first, p.second);
116 class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
119 _rulenamed(const char* name) : m_name(name) {}
120 bool operator()(const SecurityPolicyRule* rule) const {
121 return rule ? !strcmp(m_name, rule->getType()) : false;
131 void SAML2Consumer::implementProtocol(
132 const Application& application,
133 const HTTPRequest& httpRequest,
134 HTTPResponse& httpResponse,
135 SecurityPolicy& policy,
137 const XMLObject& xmlObject
140 // Implementation of SAML 2.0 SSO profile(s).
141 m_log.debug("processing message against SAML 2.0 SSO profile");
143 // Remember whether we already established trust.
144 // None of the SAML 2 bindings require security at the protocol layer.
145 bool alreadySecured = policy.isAuthenticated();
147 // Check for errors...this will throw if it's not a successful message.
148 checkError(&xmlObject, policy.getIssuerMetadata());
150 const Response* response = dynamic_cast<const Response*>(&xmlObject);
152 throw FatalProfileException("Incoming message was not a samlp:Response.");
154 const vector<saml2::Assertion*>& assertions = response->getAssertions();
155 const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
156 if (assertions.empty() && encassertions.empty())
157 throw FatalProfileException("Incoming message contained no SAML assertions.");
159 // Maintain list of "legit" tokens to feed to SP subsystems.
160 const Subject* ssoSubject=nullptr;
161 const AuthnStatement* ssoStatement=nullptr;
162 vector<const opensaml::Assertion*> tokens;
164 // Also track "bad" tokens that we'll cache but not use.
165 // This is necessary because there may be valid tokens not aimed at us.
166 vector<const opensaml::Assertion*> badtokens;
168 // And also track "owned" tokens that we decrypt here.
169 vector< boost::shared_ptr<saml2::Assertion> > ownedtokens;
171 // With this flag on, we block unauthenticated ciphertext when decrypting,
172 // unless the protocol was authenticated.
173 pair<bool,bool> requireAuthenticatedCipher = application.getBool("requireAuthenticatedCipher");
175 requireAuthenticatedCipher.second = false;
177 // With this flag on, we ignore any unsigned assertions.
178 const EntityDescriptor* entity = nullptr;
179 pair<bool,bool> requireSignedAssertions = make_pair(false,false);
180 if (alreadySecured && policy.getIssuerMetadata()) {
181 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
182 const PropertySet* rp = application.getRelyingParty(entity);
183 requireSignedAssertions = rp->getBool("requireSignedAssertions");
186 // authnskew allows rejection of SSO if AuthnInstant is too old.
187 const PropertySet* sessionProps = application.getPropertySet("Sessions");
188 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
190 // Saves off error messages potentially helpful for users.
191 string contextualError;
193 // Ensure the Bearer rule is in the policy set.
194 if (find_if(policy.getRules(), _rulenamed(BEARER_POLICY_RULE)) == nullptr)
195 policy.getRules().push_back(m_ssoRule.get());
197 // Populate recipient as audience.
198 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
200 time_t now = time(nullptr);
201 for (indirect_iterator<vector<saml2::Assertion*>::const_iterator> a = make_indirect_iterator(assertions.begin());
202 a != make_indirect_iterator(assertions.end()); ++a) {
204 // Skip unsigned assertion?
205 if (!a->getSignature() && requireSignedAssertions.first && requireSignedAssertions.second)
206 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
208 // We clear the security flag, so we can tell whether the token was secured on its own.
209 policy.setAuthenticated(false);
212 // Extract message bits and re-verify Issuer information.
213 extractMessageDetails(*a, samlconstants::SAML20P_NS, policy);
215 // Run the policy over the assertion. Handles replay, freshness, and
216 // signature verification, assuming the relevant rules are configured,
217 // along with condition and profile enforcement.
218 policy.evaluate(*a, &httpRequest);
220 // If no security is in place now, we kick it.
221 if (!alreadySecured && !policy.isAuthenticated())
222 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
224 // If we hadn't established Issuer yet, redo the signedAssertions check.
225 if (!entity && policy.getIssuerMetadata()) {
226 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
227 requireSignedAssertions = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
228 if (!a->getSignature() && requireSignedAssertions.first && requireSignedAssertions.second)
229 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
233 SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
234 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
236 if (subcondata && subcondata->getAddress()) {
237 auto_ptr_char boundip(subcondata->getAddress());
238 checkAddress(application, httpRequest, boundip.get());
241 // Track it as a valid token.
242 tokens.push_back(&(*a));
244 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
245 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion&>(*a).getAuthnStatements();
246 for (indirect_iterator<vector<AuthnStatement*>::const_iterator> s = make_indirect_iterator(statements.begin());
247 s != make_indirect_iterator(statements.end()); ++s) {
248 if (s->getAuthnInstant() && s->getAuthnInstantEpoch() - XMLToolingConfig::getConfig().clock_skew_secs > now) {
249 contextualError = "The login time at your identity provider was future-dated.";
251 else if (authnskew.first && authnskew.second && s->getAuthnInstant() &&
252 s->getAuthnInstantEpoch() <= now && (now - s->getAuthnInstantEpoch() > authnskew.second)) {
253 contextualError = "The gap between now and the time you logged into your identity provider exceeds the allowed limit.";
255 else if (authnskew.first && authnskew.second && s->getAuthnInstant() == nullptr) {
256 contextualError = "Your identity provider did not supply a time of login, violating local policy.";
258 else if (!ssoStatement || s->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch()) {
259 ssoStatement = &(*s);
263 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
264 if (!ssoSubject || (!ssoSubject->getNameID() && a->getSubject()->getNameID()))
265 ssoSubject = a->getSubject();
267 catch (std::exception& ex) {
268 m_log.warn("detected a problem with assertion: %s", ex.what());
270 contextualError = ex.what();
271 badtokens.push_back(&(*a));
275 // In case we need decryption...
276 CredentialResolver* cr = application.getCredentialResolver();
277 if (!cr && !encassertions.empty())
278 m_log.warn("found encrypted assertions, but no CredentialResolver was available");
280 for (indirect_iterator<vector<saml2::EncryptedAssertion*>::const_iterator> ea = make_indirect_iterator(encassertions.begin());
281 ea != make_indirect_iterator(encassertions.end()); ++ea) {
282 // Attempt to decrypt it.
283 boost::shared_ptr<saml2::Assertion> decrypted;
285 Locker credlocker(cr);
286 scoped_ptr<MetadataCredentialCriteria> mcc(
287 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : nullptr
289 boost::shared_ptr<XMLObject> wrapper(
292 application.getRelyingParty(entity)->getXMLString("entityID").second,
294 requireAuthenticatedCipher.first && requireAuthenticatedCipher.second
297 decrypted = dynamic_pointer_cast<saml2::Assertion>(wrapper);
299 ownedtokens.push_back(decrypted);
300 if (m_log.isDebugEnabled())
301 m_log.debugStream() << "decrypted Assertion: " << *decrypted << logging::eol;
304 catch (std::exception& ex) {
305 m_log.error("failed to decrypt assertion: %s", ex.what());
311 // Skip unsigned assertion?
312 if (!decrypted->getSignature() && requireSignedAssertions.first && requireSignedAssertions.second)
313 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
315 // We clear the security flag, so we can tell whether the token was secured on its own.
316 policy.setAuthenticated(false);
319 // Extract message bits and re-verify Issuer information.
320 extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
322 // Run the policy over the assertion. Handles replay, freshness, and
323 // signature verification, assuming the relevant rules are configured,
324 // along with condition and profile enforcement.
325 // We have to marshall the object first to ensure signatures can be checked.
326 if (!decrypted->getDOM())
327 decrypted->marshall();
328 policy.evaluate(*decrypted, &httpRequest);
330 // If no security is in place now, we kick it.
331 if (!alreadySecured && !policy.isAuthenticated())
332 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
334 // If we hadn't established Issuer yet, redo the signedAssertions check.
335 if (!entity && policy.getIssuerMetadata()) {
336 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
337 requireSignedAssertions = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
338 if (!decrypted->getSignature() && requireSignedAssertions.first && requireSignedAssertions.second)
339 throw SecurityPolicyException("The decrypted assertion was unsigned, violating local security policy.");
343 SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
344 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
346 if (subcondata && subcondata->getAddress()) {
347 auto_ptr_char boundip(subcondata->getAddress());
348 checkAddress(application, httpRequest, boundip.get());
351 // Track it as a valid token.
352 tokens.push_back(decrypted.get());
354 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
355 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted.get())->getAuthnStatements();
356 for (indirect_iterator<vector<AuthnStatement*>::const_iterator> s = make_indirect_iterator(statements.begin());
357 s != make_indirect_iterator(statements.end()); ++s) {
358 if (authnskew.first && authnskew.second && s->getAuthnInstant() && (now - s->getAuthnInstantEpoch() > authnskew.second))
359 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
360 else if (!ssoStatement || s->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
361 ssoStatement = &(*s);
364 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
365 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
366 ssoSubject = decrypted->getSubject();
368 catch (std::exception& ex) {
369 m_log.warn("detected a problem with assertion: %s", ex.what());
371 contextualError = ex.what();
372 badtokens.push_back(decrypted.get());
377 if (contextualError.empty())
378 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
379 throw FatalProfileException(contextualError.c_str());
382 // May need to decrypt NameID.
383 scoped_ptr<XMLObject> decryptedID;
384 NameID* ssoName = ssoSubject->getNameID();
386 EncryptedID* encname = ssoSubject->getEncryptedID();
389 m_log.warn("found encrypted NameID, but no decryption credential was available");
391 Locker credlocker(cr);
392 scoped_ptr<MetadataCredentialCriteria> mcc(
393 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : nullptr
396 decryptedID.reset(encname->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
397 ssoName = dynamic_cast<NameID*>(decryptedID.get());
399 if (m_log.isDebugEnabled())
400 m_log.debugStream() << "decrypted NameID: " << *ssoName << logging::eol;
403 catch (std::exception& ex) {
404 m_log.error("failed to decrypt NameID: %s", ex.what());
410 m_log.debug("SSO profile processing completed successfully");
412 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
413 // To complete processing, we need to extract and resolve attributes and then create the session.
415 // Now we have to extract the authentication details for session setup.
417 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
418 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ?
419 (ssoStatement->getSessionNotOnOrAfterEpoch() + XMLToolingConfig::getConfig().clock_skew_secs) : 0;
420 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
421 if (!lifetime.first || lifetime.second == 0)
422 lifetime.second = 28800;
424 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
426 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
428 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
430 // The context will handle deleting attributes and new tokens.
431 scoped_ptr<ResolutionContext> ctx(
435 policy.getIssuerMetadata(),
436 samlconstants::SAML20P_NS,
442 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : nullptr,
443 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : nullptr,
449 // Copy over any new tokens, but leave them in the context for cleanup.
450 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
453 // Now merge in bad tokens for caching.
454 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
457 application.getServiceProvider().getSessionCache()->insert(
464 samlconstants::SAML20P_NS,
466 ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : nullptr,
467 ssoStatement->getSessionIndex(),
468 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : nullptr,
469 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : nullptr,
471 ctx ? &ctx->getResolvedAttributes() : nullptr
475 scoped_ptr<TransactionLog::Event> event(newLoginEvent(application, httpRequest));
476 LoginEvent* login_event = dynamic_cast<LoginEvent*>(event.get());
478 login_event->m_sessionID = session_id.c_str();
479 login_event->m_peer = entity;
480 auto_ptr_char prot(getProtocolFamily());
481 login_event->m_protocol = prot.get();
482 login_event->m_nameID = ssoName;
483 login_event->m_saml2AuthnStatement = ssoStatement;
484 login_event->m_saml2Response = response;
486 login_event->m_attributes = &ctx->getResolvedAttributes();
487 application.getServiceProvider().getTransactionLog()->write(*login_event);
490 m_log.warn("unable to audit event, log event object was of an incorrect type");
493 catch (std::exception& ex) {
494 m_log.warn("exception auditing event: %s", ex.what());