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 <saml/exceptions.h>
37 # include <saml/SAMLConfig.h>
38 # include <saml/binding/SecurityPolicyRule.h>
39 # include <saml/saml2/core/Protocols.h>
40 # include <saml/saml2/metadata/Metadata.h>
41 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
42 # include <saml/saml2/profile/SAML2AssertionPolicy.h>
43 # include <xmltooling/XMLToolingConfig.h>
44 # include <xmltooling/io/HTTPRequest.h>
45 # include <xmltooling/util/DateTime.h>
46 using namespace opensaml::saml2;
47 using namespace opensaml::saml2p;
48 using namespace opensaml::saml2md;
49 using namespace opensaml;
51 # define min(a,b) (((a) < (b)) ? (a) : (b))
54 # include "lite/SAMLConstants.h"
57 using namespace shibsp;
58 using namespace xmltooling;
63 #if defined (_MSC_VER)
64 #pragma warning( push )
65 #pragma warning( disable : 4250 )
68 class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
71 SAML2Consumer(const DOMElement* e, const char* appId)
72 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML2")) {
75 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
76 m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(BEARER_POLICY_RULE, e);
79 virtual ~SAML2Consumer() {
86 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
87 AssertionConsumerService::generateMetadata(role, handlerURL);
88 role.addSupport(samlconstants::SAML20P_NS);
92 void implementProtocol(
93 const Application& application,
94 const HTTPRequest& httpRequest,
95 HTTPResponse& httpResponse,
96 SecurityPolicy& policy,
98 const XMLObject& xmlObject
101 SecurityPolicyRule* m_ssoRule;
103 const XMLCh* getProtocolFamily() const {
104 return samlconstants::SAML20P_NS;
109 #if defined (_MSC_VER)
110 #pragma warning( pop )
113 Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
115 return new SAML2Consumer(p.first, p.second);
119 class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
122 _rulenamed(const char* name) : m_name(name) {}
123 bool operator()(const SecurityPolicyRule* rule) const {
124 return rule ? !strcmp(m_name, rule->getType()) : false;
134 void SAML2Consumer::implementProtocol(
135 const Application& application,
136 const HTTPRequest& httpRequest,
137 HTTPResponse& httpResponse,
138 SecurityPolicy& policy,
140 const XMLObject& xmlObject
143 // Implementation of SAML 2.0 SSO profile(s).
144 m_log.debug("processing message against SAML 2.0 SSO profile");
146 // Remember whether we already established trust.
147 // None of the SAML 2 bindings require security at the protocol layer.
148 bool alreadySecured = policy.isAuthenticated();
150 // Check for errors...this will throw if it's not a successful message.
151 checkError(&xmlObject, policy.getIssuerMetadata());
153 const Response* response = dynamic_cast<const Response*>(&xmlObject);
155 throw FatalProfileException("Incoming message was not a samlp:Response.");
157 const vector<saml2::Assertion*>& assertions = response->getAssertions();
158 const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
159 if (assertions.empty() && encassertions.empty())
160 throw FatalProfileException("Incoming message contained no SAML assertions.");
162 // Maintain list of "legit" tokens to feed to SP subsystems.
163 const Subject* ssoSubject=nullptr;
164 const AuthnStatement* ssoStatement=nullptr;
165 vector<const opensaml::Assertion*> tokens;
167 // Also track "bad" tokens that we'll cache but not use.
168 // This is necessary because there may be valid tokens not aimed at us.
169 vector<const opensaml::Assertion*> badtokens;
171 // And also track "owned" tokens that we decrypt here.
172 vector<saml2::Assertion*> ownedtokens;
174 // With this flag on, we ignore any unsigned assertions.
175 const EntityDescriptor* entity = nullptr;
176 pair<bool,bool> flag = make_pair(false,false);
177 if (alreadySecured && policy.getIssuerMetadata()) {
178 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
179 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
182 // authnskew allows rejection of SSO if AuthnInstant is too old.
183 const PropertySet* sessionProps = application.getPropertySet("Sessions");
184 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
186 // Saves off error messages potentially helpful for users.
187 string contextualError;
189 // Ensure the Bearer rule is in the policy set.
190 if (find_if(policy.getRules(), _rulenamed(BEARER_POLICY_RULE)) == nullptr)
191 policy.getRules().push_back(m_ssoRule);
193 // Populate recipient as audience.
194 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
196 time_t now = time(nullptr);
197 for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
199 // Skip unsigned assertion?
200 if (!(*a)->getSignature() && flag.first && flag.second)
201 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
203 // We clear the security flag, so we can tell whether the token was secured on its own.
204 policy.setAuthenticated(false);
207 // Extract message bits and re-verify Issuer information.
208 extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
210 // Run the policy over the assertion. Handles replay, freshness, and
211 // signature verification, assuming the relevant rules are configured,
212 // along with condition and profile enforcement.
213 policy.evaluate(*(*a), &httpRequest);
215 // If no security is in place now, we kick it.
216 if (!alreadySecured && !policy.isAuthenticated())
217 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
219 // If we hadn't established Issuer yet, redo the signedAssertions check.
220 if (!entity && policy.getIssuerMetadata()) {
221 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
222 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
223 if (!(*a)->getSignature() && flag.first && flag.second)
224 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
228 SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
229 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
231 if (subcondata && subcondata->getAddress()) {
232 auto_ptr_char boundip(subcondata->getAddress());
233 checkAddress(application, httpRequest, boundip.get());
236 // Track it as a valid token.
237 tokens.push_back(*a);
239 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
240 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
241 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=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()) {
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 (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 (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
275 // Attempt to decrypt it.
276 saml2::Assertion* decrypted=nullptr;
278 Locker credlocker(cr);
279 auto_ptr<MetadataCredentialCriteria> mcc(
280 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : nullptr
282 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
283 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
286 ownedtokens.push_back(decrypted);
287 if (m_log.isDebugEnabled())
288 m_log.debugStream() << "decrypted Assertion: " << *decrypted << logging::eol;
291 catch (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);
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)->getAuthnStatements();
339 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
340 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
341 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
342 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
346 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
347 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
348 ssoSubject = decrypted->getSubject();
350 catch (exception& ex) {
351 m_log.warn("detected a problem with assertion: %s", ex.what());
353 contextualError = ex.what();
354 badtokens.push_back(decrypted);
359 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
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 bool ownedName = false;
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 auto_ptr<MetadataCredentialCriteria> mcc(
376 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : nullptr
379 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get()));
380 ssoName = dynamic_cast<NameID*>(decryptedID.get());
383 decryptedID.release();
384 if (m_log.isDebugEnabled())
385 m_log.debugStream() << "decrypted NameID: " << *ssoName << logging::eol;
388 catch (exception& ex) {
389 m_log.error(ex.what());
395 m_log.debug("SSO profile processing completed successfully");
397 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
398 // To complete processing, we need to extract and resolve attributes and then create the session.
400 // Now we have to extract the authentication details for session setup.
402 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
403 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ?
404 (ssoStatement->getSessionNotOnOrAfterEpoch() + XMLToolingConfig::getConfig().clock_skew_secs) : 0;
405 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
406 if (!lifetime.first || lifetime.second == 0)
407 lifetime.second = 28800;
409 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
411 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
413 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
416 // The context will handle deleting attributes and new tokens.
417 auto_ptr<ResolutionContext> ctx(
420 policy.getIssuerMetadata(),
421 samlconstants::SAML20P_NS,
426 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : nullptr,
427 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : nullptr,
433 // Copy over any new tokens, but leave them in the context for cleanup.
434 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
437 // Now merge in bad tokens for caching.
438 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
441 application.getServiceProvider().getSessionCache()->insert(
448 samlconstants::SAML20P_NS,
450 ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : nullptr,
451 ssoStatement->getSessionIndex(),
452 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : nullptr,
453 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : nullptr,
455 ctx.get() ? &ctx->getResolvedAttributes() : nullptr
459 auto_ptr<TransactionLog::Event> event(newLoginEvent(application, httpRequest));
460 LoginEvent* login_event = dynamic_cast<LoginEvent*>(event.get());
462 login_event->m_sessionID = session_id.c_str();
463 login_event->m_peer = entity;
464 auto_ptr_char prot(getProtocolFamily());
465 login_event->m_protocol = prot.get();
466 login_event->m_nameID = ssoName;
467 login_event->m_saml2AuthnStatement = ssoStatement;
468 login_event->m_saml2Response = response;
470 login_event->m_attributes = &ctx->getResolvedAttributes();
471 application.getServiceProvider().getTransactionLog()->write(*login_event);
474 m_log.warn("unable to audit event, log event object was of an incorrect type");
477 catch (exception& ex) {
478 m_log.warn("exception auditing event: %s", ex.what());
483 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
488 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());