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/scoped_ptr.hpp>
37 # include <boost/iterator/indirect_iterator.hpp>
38 # include <saml/exceptions.h>
39 # include <saml/SAMLConfig.h>
40 # include <saml/binding/SecurityPolicyRule.h>
41 # include <saml/saml2/core/Protocols.h>
42 # include <saml/saml2/metadata/Metadata.h>
43 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
44 # include <saml/saml2/profile/SAML2AssertionPolicy.h>
45 # include <xmltooling/XMLToolingConfig.h>
46 # include <xmltooling/io/HTTPRequest.h>
47 # include <xmltooling/util/DateTime.h>
48 using namespace opensaml::saml2;
49 using namespace opensaml::saml2p;
50 using namespace opensaml::saml2md;
51 using namespace opensaml;
52 using namespace boost;
54 # define min(a,b) (((a) < (b)) ? (a) : (b))
57 # include "lite/SAMLConstants.h"
60 using namespace shibsp;
61 using namespace xmltooling;
66 #if defined (_MSC_VER)
67 #pragma warning( push )
68 #pragma warning( disable : 4250 )
71 class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
74 SAML2Consumer(const DOMElement* e, const char* appId)
75 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML2")) {
77 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
78 m_ssoRule.reset(SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(BEARER_POLICY_RULE, e));
81 virtual ~SAML2Consumer() {}
84 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
85 AssertionConsumerService::generateMetadata(role, handlerURL);
86 role.addSupport(samlconstants::SAML20P_NS);
90 void implementProtocol(
91 const Application& application,
92 const HTTPRequest& httpRequest,
93 HTTPResponse& httpResponse,
94 SecurityPolicy& policy,
96 const XMLObject& xmlObject
99 scoped_ptr<SecurityPolicyRule> m_ssoRule;
101 const XMLCh* getProtocolFamily() const {
102 return samlconstants::SAML20P_NS;
107 #if defined (_MSC_VER)
108 #pragma warning( pop )
111 Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
113 return new SAML2Consumer(p.first, p.second);
117 class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
120 _rulenamed(const char* name) : m_name(name) {}
121 bool operator()(const SecurityPolicyRule* rule) const {
122 return rule ? !strcmp(m_name, rule->getType()) : false;
132 void SAML2Consumer::implementProtocol(
133 const Application& application,
134 const HTTPRequest& httpRequest,
135 HTTPResponse& httpResponse,
136 SecurityPolicy& policy,
138 const XMLObject& xmlObject
141 // Implementation of SAML 2.0 SSO profile(s).
142 m_log.debug("processing message against SAML 2.0 SSO profile");
144 // Remember whether we already established trust.
145 // None of the SAML 2 bindings require security at the protocol layer.
146 bool alreadySecured = policy.isAuthenticated();
148 // Check for errors...this will throw if it's not a successful message.
149 checkError(&xmlObject, policy.getIssuerMetadata());
151 const Response* response = dynamic_cast<const Response*>(&xmlObject);
153 throw FatalProfileException("Incoming message was not a samlp:Response.");
155 const vector<saml2::Assertion*>& assertions = response->getAssertions();
156 const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
157 if (assertions.empty() && encassertions.empty())
158 throw FatalProfileException("Incoming message contained no SAML assertions.");
160 // Maintain list of "legit" tokens to feed to SP subsystems.
161 const Subject* ssoSubject=nullptr;
162 const AuthnStatement* ssoStatement=nullptr;
163 vector<const opensaml::Assertion*> tokens;
165 // Also track "bad" tokens that we'll cache but not use.
166 // This is necessary because there may be valid tokens not aimed at us.
167 vector<const opensaml::Assertion*> badtokens;
169 // And also track "owned" tokens that we decrypt here.
170 vector< boost::shared_ptr<saml2::Assertion> > ownedtokens;
172 // With this flag on, we ignore any unsigned assertions.
173 const EntityDescriptor* entity = nullptr;
174 pair<bool,bool> flag = make_pair(false,false);
175 if (alreadySecured && policy.getIssuerMetadata()) {
176 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
177 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
180 // authnskew allows rejection of SSO if AuthnInstant is too old.
181 const PropertySet* sessionProps = application.getPropertySet("Sessions");
182 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
184 // Saves off error messages potentially helpful for users.
185 string contextualError;
187 // Ensure the Bearer rule is in the policy set.
188 if (find_if(policy.getRules(), _rulenamed(BEARER_POLICY_RULE)) == nullptr)
189 policy.getRules().push_back(m_ssoRule.get());
191 // Populate recipient as audience.
192 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
194 time_t now = time(nullptr);
195 for (indirect_iterator<vector<saml2::Assertion*>::const_iterator> a = make_indirect_iterator(assertions.begin());
196 a != make_indirect_iterator(assertions.end()); ++a) {
198 // Skip unsigned assertion?
199 if (!a->getSignature() && flag.first && flag.second)
200 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
202 // We clear the security flag, so we can tell whether the token was secured on its own.
203 policy.setAuthenticated(false);
206 // Extract message bits and re-verify Issuer information.
207 extractMessageDetails(*a, samlconstants::SAML20P_NS, policy);
209 // Run the policy over the assertion. Handles replay, freshness, and
210 // signature verification, assuming the relevant rules are configured,
211 // along with condition and profile enforcement.
212 policy.evaluate(*a, &httpRequest);
214 // If no security is in place now, we kick it.
215 if (!alreadySecured && !policy.isAuthenticated())
216 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
218 // If we hadn't established Issuer yet, redo the signedAssertions check.
219 if (!entity && policy.getIssuerMetadata()) {
220 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
221 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
222 if (!a->getSignature() && flag.first && flag.second)
223 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
227 SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
228 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
230 if (subcondata && subcondata->getAddress()) {
231 auto_ptr_char boundip(subcondata->getAddress());
232 checkAddress(application, httpRequest, boundip.get());
235 // Track it as a valid token.
236 tokens.push_back(&(*a));
238 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
239 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion&>(*a).getAuthnStatements();
240 for (indirect_iterator<vector<AuthnStatement*>::const_iterator> s = make_indirect_iterator(statements.begin());
241 s != make_indirect_iterator(statements.end()); ++s) {
242 if (s->getAuthnInstant() && s->getAuthnInstantEpoch() - XMLToolingConfig::getConfig().clock_skew_secs > now) {
243 contextualError = "The login time at your identity provider was future-dated.";
245 else if (authnskew.first && authnskew.second && s->getAuthnInstant() &&
246 s->getAuthnInstantEpoch() <= now && (now - s->getAuthnInstantEpoch() > authnskew.second)) {
247 contextualError = "The gap between now and the time you logged into your identity provider exceeds the allowed limit.";
249 else if (authnskew.first && authnskew.second && s->getAuthnInstant() == nullptr) {
250 contextualError = "Your identity provider did not supply a time of login, violating local policy.";
252 else if (!ssoStatement || s->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch()) {
253 ssoStatement = &(*s);
257 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
258 if (!ssoSubject || (!ssoSubject->getNameID() && a->getSubject()->getNameID()))
259 ssoSubject = a->getSubject();
261 catch (std::exception& ex) {
262 m_log.warn("detected a problem with assertion: %s", ex.what());
264 contextualError = ex.what();
265 badtokens.push_back(&(*a));
269 // In case we need decryption...
270 CredentialResolver* cr=application.getCredentialResolver();
271 if (!cr && !encassertions.empty())
272 m_log.warn("found encrypted assertions, but no CredentialResolver was available");
274 for (indirect_iterator<vector<saml2::EncryptedAssertion*>::const_iterator> ea = make_indirect_iterator(encassertions.begin());
275 ea != make_indirect_iterator(encassertions.end()); ++ea) {
276 // Attempt to decrypt it.
277 boost::shared_ptr<saml2::Assertion> decrypted;
279 Locker credlocker(cr);
280 scoped_ptr<MetadataCredentialCriteria> mcc(
281 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : nullptr
283 boost::shared_ptr<XMLObject> wrapper(ea->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
284 decrypted = dynamic_pointer_cast<saml2::Assertion>(wrapper);
286 ownedtokens.push_back(decrypted);
287 if (m_log.isDebugEnabled())
288 m_log.debugStream() << "decrypted Assertion: " << *decrypted << logging::eol;
291 catch (std::exception& ex) {
292 m_log.error(ex.what());
298 // We clear the security flag, so we can tell whether the token was secured on its own.
299 policy.setAuthenticated(false);
302 // Extract message bits and re-verify Issuer information.
303 extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
305 // Run the policy over the assertion. Handles replay, freshness, and
306 // signature verification, assuming the relevant rules are configured,
307 // along with condition and profile enforcement.
308 // We have to marshall the object first to ensure signatures can be checked.
309 if (!decrypted->getDOM())
310 decrypted->marshall();
311 policy.evaluate(*decrypted, &httpRequest);
313 // If no security is in place now, we kick it.
314 if (!alreadySecured && !policy.isAuthenticated())
315 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
317 // If we hadn't established Issuer yet, redo the signedAssertions check.
318 if (!entity && policy.getIssuerMetadata()) {
319 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
320 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
321 if (!decrypted->getSignature() && flag.first && flag.second)
322 throw SecurityPolicyException("The decrypted assertion was unsigned, violating local security policy.");
326 SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
327 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
329 if (subcondata && subcondata->getAddress()) {
330 auto_ptr_char boundip(subcondata->getAddress());
331 checkAddress(application, httpRequest, boundip.get());
334 // Track it as a valid token.
335 tokens.push_back(decrypted.get());
337 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
338 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted.get())->getAuthnStatements();
339 for (indirect_iterator<vector<AuthnStatement*>::const_iterator> s = make_indirect_iterator(statements.begin());
340 s != make_indirect_iterator(statements.end()); ++s) {
341 if (authnskew.first && authnskew.second && s->getAuthnInstant() && (now - s->getAuthnInstantEpoch() > authnskew.second))
342 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
343 else if (!ssoStatement || s->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
344 ssoStatement = &(*s);
347 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
348 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
349 ssoSubject = decrypted->getSubject();
351 catch (std::exception& ex) {
352 m_log.warn("detected a problem with assertion: %s", ex.what());
354 contextualError = ex.what();
355 badtokens.push_back(decrypted.get());
360 if (contextualError.empty())
361 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
362 throw FatalProfileException(contextualError.c_str());
365 // May need to decrypt NameID.
366 scoped_ptr<XMLObject> decryptedID;
367 NameID* ssoName = ssoSubject->getNameID();
369 EncryptedID* encname = ssoSubject->getEncryptedID();
372 m_log.warn("found encrypted NameID, but no decryption credential was available");
374 Locker credlocker(cr);
375 scoped_ptr<MetadataCredentialCriteria> mcc(
376 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : nullptr
379 decryptedID.reset(encname->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
380 ssoName = dynamic_cast<NameID*>(decryptedID.get());
382 if (m_log.isDebugEnabled())
383 m_log.debugStream() << "decrypted NameID: " << *ssoName << logging::eol;
386 catch (std::exception& ex) {
387 m_log.error(ex.what());
393 m_log.debug("SSO profile processing completed successfully");
395 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
396 // To complete processing, we need to extract and resolve attributes and then create the session.
398 // Now we have to extract the authentication details for session setup.
400 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
401 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ?
402 (ssoStatement->getSessionNotOnOrAfterEpoch() + XMLToolingConfig::getConfig().clock_skew_secs) : 0;
403 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
404 if (!lifetime.first || lifetime.second == 0)
405 lifetime.second = 28800;
407 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
409 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
411 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
413 // The context will handle deleting attributes and new tokens.
414 scoped_ptr<ResolutionContext> ctx(
417 policy.getIssuerMetadata(),
418 samlconstants::SAML20P_NS,
423 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : nullptr,
424 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : nullptr,
430 // Copy over any new tokens, but leave them in the context for cleanup.
431 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
434 // Now merge in bad tokens for caching.
435 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
438 application.getServiceProvider().getSessionCache()->insert(
445 samlconstants::SAML20P_NS,
447 ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : nullptr,
448 ssoStatement->getSessionIndex(),
449 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : nullptr,
450 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : nullptr,
452 ctx ? &ctx->getResolvedAttributes() : nullptr
456 scoped_ptr<TransactionLog::Event> event(newLoginEvent(application, httpRequest));
457 LoginEvent* login_event = dynamic_cast<LoginEvent*>(event.get());
459 login_event->m_sessionID = session_id.c_str();
460 login_event->m_peer = entity;
461 auto_ptr_char prot(getProtocolFamily());
462 login_event->m_protocol = prot.get();
463 login_event->m_nameID = ssoName;
464 login_event->m_saml2AuthnStatement = ssoStatement;
465 login_event->m_saml2Response = response;
467 login_event->m_attributes = &ctx->getResolvedAttributes();
468 application.getServiceProvider().getTransactionLog()->write(*login_event);
471 m_log.warn("unable to audit event, log event object was of an incorrect type");
474 catch (std::exception& ex) {
475 m_log.warn("exception auditing event: %s", ex.what());