2 * Copyright 2001-2010 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 "Application.h"
28 # include "ServiceProvider.h"
29 # include "SessionCache.h"
30 # include "attribute/resolver/ResolutionContext.h"
31 # include <saml/exceptions.h>
32 # include <saml/SAMLConfig.h>
33 # include <saml/binding/SecurityPolicyRule.h>
34 # include <saml/saml2/core/Protocols.h>
35 # include <saml/saml2/metadata/Metadata.h>
36 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
37 # include <saml/saml2/profile/SAML2AssertionPolicy.h>
38 # include <xmltooling/XMLToolingConfig.h>
39 # include <xmltooling/io/HTTPRequest.h>
40 # include <xmltooling/util/DateTime.h>
41 using namespace opensaml::saml2;
42 using namespace opensaml::saml2p;
43 using namespace opensaml::saml2md;
44 using namespace opensaml;
46 # define min(a,b) (((a) < (b)) ? (a) : (b))
49 # include "lite/SAMLConstants.h"
52 using namespace shibsp;
53 using namespace xmltooling;
58 #if defined (_MSC_VER)
59 #pragma warning( push )
60 #pragma warning( disable : 4250 )
63 class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
66 SAML2Consumer(const DOMElement* e, const char* appId)
67 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML2")) {
70 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
71 m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(BEARER_POLICY_RULE, e);
74 virtual ~SAML2Consumer() {
81 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
82 AssertionConsumerService::generateMetadata(role, handlerURL);
83 role.addSupport(samlconstants::SAML20P_NS);
87 void implementProtocol(
88 const Application& application,
89 const HTTPRequest& httpRequest,
90 HTTPResponse& httpResponse,
91 SecurityPolicy& policy,
93 const XMLObject& xmlObject
96 SecurityPolicyRule* m_ssoRule;
98 const XMLCh* getProtocolFamily() const {
99 return samlconstants::SAML20P_NS;
104 #if defined (_MSC_VER)
105 #pragma warning( pop )
108 Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
110 return new SAML2Consumer(p.first, p.second);
114 class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
117 _rulenamed(const char* name) : m_name(name) {}
118 bool operator()(const SecurityPolicyRule* rule) const {
119 return rule ? !strcmp(m_name, rule->getType()) : false;
129 void SAML2Consumer::implementProtocol(
130 const Application& application,
131 const HTTPRequest& httpRequest,
132 HTTPResponse& httpResponse,
133 SecurityPolicy& policy,
135 const XMLObject& xmlObject
138 // Implementation of SAML 2.0 SSO profile(s).
139 m_log.debug("processing message against SAML 2.0 SSO profile");
141 // Remember whether we already established trust.
142 // None of the SAML 2 bindings require security at the protocol layer.
143 bool alreadySecured = policy.isAuthenticated();
145 // Check for errors...this will throw if it's not a successful message.
146 checkError(&xmlObject, policy.getIssuerMetadata());
148 const Response* response = dynamic_cast<const Response*>(&xmlObject);
150 throw FatalProfileException("Incoming message was not a samlp:Response.");
152 const vector<saml2::Assertion*>& assertions = response->getAssertions();
153 const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
154 if (assertions.empty() && encassertions.empty())
155 throw FatalProfileException("Incoming message contained no SAML assertions.");
157 // Maintain list of "legit" tokens to feed to SP subsystems.
158 const Subject* ssoSubject=nullptr;
159 const AuthnStatement* ssoStatement=nullptr;
160 vector<const opensaml::Assertion*> tokens;
162 // Also track "bad" tokens that we'll cache but not use.
163 // This is necessary because there may be valid tokens not aimed at us.
164 vector<const opensaml::Assertion*> badtokens;
166 // And also track "owned" tokens that we decrypt here.
167 vector<saml2::Assertion*> ownedtokens;
169 // With this flag on, we ignore any unsigned assertions.
170 const EntityDescriptor* entity = nullptr;
171 pair<bool,bool> flag = make_pair(false,false);
172 if (alreadySecured && policy.getIssuerMetadata()) {
173 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
174 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
177 // authnskew allows rejection of SSO if AuthnInstant is too old.
178 const PropertySet* sessionProps = application.getPropertySet("Sessions");
179 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
181 // Saves off error messages potentially helpful for users.
182 string contextualError;
184 // Ensure the Bearer rule is in the policy set.
185 if (find_if(policy.getRules(), _rulenamed(BEARER_POLICY_RULE)) == nullptr)
186 policy.getRules().push_back(m_ssoRule);
188 // Populate recipient as audience.
189 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
191 time_t now = time(nullptr);
192 for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
194 // Skip unsigned assertion?
195 if (!(*a)->getSignature() && flag.first && flag.second)
196 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
198 // We clear the security flag, so we can tell whether the token was secured on its own.
199 policy.setAuthenticated(false);
202 // Extract message bits and re-verify Issuer information.
203 extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
205 // Run the policy over the assertion. Handles replay, freshness, and
206 // signature verification, assuming the relevant rules are configured,
207 // along with condition and profile enforcement.
208 policy.evaluate(*(*a), &httpRequest);
210 // If no security is in place now, we kick it.
211 if (!alreadySecured && !policy.isAuthenticated())
212 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
214 // If we hadn't established Issuer yet, redo the signedAssertions check.
215 if (!entity && policy.getIssuerMetadata()) {
216 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
217 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
218 if (!(*a)->getSignature() && flag.first && flag.second)
219 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
223 SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
224 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
226 if (subcondata && subcondata->getAddress()) {
227 auto_ptr_char boundip(subcondata->getAddress());
228 checkAddress(application, httpRequest, boundip.get());
231 // Track it as a valid token.
232 tokens.push_back(*a);
234 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
235 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
236 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
237 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
238 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
239 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
243 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
244 if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
245 ssoSubject = (*a)->getSubject();
247 catch (exception& ex) {
248 m_log.warn("detected a problem with assertion: %s", ex.what());
250 contextualError = ex.what();
251 badtokens.push_back(*a);
255 // In case we need decryption...
256 CredentialResolver* cr=application.getCredentialResolver();
257 if (!cr && !encassertions.empty())
258 m_log.warn("found encrypted assertions, but no CredentialResolver was available");
260 for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
261 // Attempt to decrypt it.
262 saml2::Assertion* decrypted=nullptr;
264 Locker credlocker(cr);
265 auto_ptr<MetadataCredentialCriteria> mcc(
266 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : nullptr
268 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
269 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
272 ownedtokens.push_back(decrypted);
273 if (m_log.isDebugEnabled())
274 m_log.debugStream() << "decrypted Assertion: " << *decrypted << logging::eol;
277 catch (exception& ex) {
278 m_log.error(ex.what());
284 // We clear the security flag, so we can tell whether the token was secured on its own.
285 policy.setAuthenticated(false);
288 // Extract message bits and re-verify Issuer information.
289 extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
291 // Run the policy over the assertion. Handles replay, freshness, and
292 // signature verification, assuming the relevant rules are configured,
293 // along with condition and profile enforcement.
294 // We have to marshall the object first to ensure signatures can be checked.
295 if (!decrypted->getDOM())
296 decrypted->marshall();
297 policy.evaluate(*decrypted, &httpRequest);
299 // If no security is in place now, we kick it.
300 if (!alreadySecured && !policy.isAuthenticated())
301 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
303 // If we hadn't established Issuer yet, redo the signedAssertions check.
304 if (!entity && policy.getIssuerMetadata()) {
305 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
306 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
307 if (!decrypted->getSignature() && flag.first && flag.second)
308 throw SecurityPolicyException("The decrypted assertion was unsigned, violating local security policy.");
312 SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
313 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
315 if (subcondata && subcondata->getAddress()) {
316 auto_ptr_char boundip(subcondata->getAddress());
317 checkAddress(application, httpRequest, boundip.get());
320 // Track it as a valid token.
321 tokens.push_back(decrypted);
323 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
324 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
325 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
326 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
327 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
328 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
332 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
333 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
334 ssoSubject = decrypted->getSubject();
336 catch (exception& ex) {
337 m_log.warn("detected a problem with assertion: %s", ex.what());
339 contextualError = ex.what();
340 badtokens.push_back(decrypted);
345 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
346 if (contextualError.empty())
347 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
348 throw FatalProfileException(contextualError.c_str());
351 // May need to decrypt NameID.
352 bool ownedName = false;
353 NameID* ssoName = ssoSubject->getNameID();
355 EncryptedID* encname = ssoSubject->getEncryptedID();
358 m_log.warn("found encrypted NameID, but no decryption credential was available");
360 Locker credlocker(cr);
361 auto_ptr<MetadataCredentialCriteria> mcc(
362 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : nullptr
365 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get()));
366 ssoName = dynamic_cast<NameID*>(decryptedID.get());
369 decryptedID.release();
370 if (m_log.isDebugEnabled())
371 m_log.debugStream() << "decrypted NameID: " << *ssoName << logging::eol;
374 catch (exception& ex) {
375 m_log.error(ex.what());
381 m_log.debug("SSO profile processing completed successfully");
383 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
384 // To complete processing, we need to extract and resolve attributes and then create the session.
386 // Now we have to extract the authentication details for session setup.
388 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
389 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ?
390 (ssoStatement->getSessionNotOnOrAfterEpoch() + XMLToolingConfig::getConfig().clock_skew_secs) : 0;
391 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
392 if (!lifetime.first || lifetime.second == 0)
393 lifetime.second = 28800;
395 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
397 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
399 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
402 // The context will handle deleting attributes and new tokens.
403 auto_ptr<ResolutionContext> ctx(
406 policy.getIssuerMetadata(),
407 samlconstants::SAML20P_NS,
410 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : nullptr,
411 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : nullptr,
417 // Copy over any new tokens, but leave them in the context for cleanup.
418 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
421 // Now merge in bad tokens for caching.
422 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
424 application.getServiceProvider().getSessionCache()->insert(
430 samlconstants::SAML20P_NS,
432 ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : nullptr,
433 ssoStatement->getSessionIndex(),
434 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : nullptr,
435 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : nullptr,
437 ctx.get() ? &ctx->getResolvedAttributes() : nullptr
442 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
447 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());