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 "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))
50 using namespace shibsp;
51 using namespace xmltooling;
56 #if defined (_MSC_VER)
57 #pragma warning( push )
58 #pragma warning( disable : 4250 )
61 class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
64 SAML2Consumer(const DOMElement* e, const char* appId)
65 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML2")) {
68 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
69 m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(BEARER_POLICY_RULE, e);
72 virtual ~SAML2Consumer() {
79 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
80 AssertionConsumerService::generateMetadata(role, handlerURL);
81 role.addSupport(samlconstants::SAML20P_NS);
85 void implementProtocol(
86 const Application& application,
87 const HTTPRequest& httpRequest,
88 HTTPResponse& httpResponse,
89 SecurityPolicy& policy,
90 const PropertySet* settings,
91 const XMLObject& xmlObject
94 SecurityPolicyRule* m_ssoRule;
98 #if defined (_MSC_VER)
99 #pragma warning( pop )
102 Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
104 return new SAML2Consumer(p.first, p.second);
108 class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
111 _rulenamed(const char* name) : m_name(name) {}
112 bool operator()(const SecurityPolicyRule* rule) const {
113 return rule ? !strcmp(m_name, rule->getType()) : false;
123 void SAML2Consumer::implementProtocol(
124 const Application& application,
125 const HTTPRequest& httpRequest,
126 HTTPResponse& httpResponse,
127 SecurityPolicy& policy,
128 const PropertySet* settings,
129 const XMLObject& xmlObject
132 // Implementation of SAML 2.0 SSO profile(s).
133 m_log.debug("processing message against SAML 2.0 SSO profile");
135 // Remember whether we already established trust.
136 // None of the SAML 2 bindings require security at the protocol layer.
137 bool alreadySecured = policy.isAuthenticated();
139 // Check for errors...this will throw if it's not a successful message.
140 checkError(&xmlObject, policy.getIssuerMetadata());
142 const Response* response = dynamic_cast<const Response*>(&xmlObject);
144 throw FatalProfileException("Incoming message was not a samlp:Response.");
146 const vector<saml2::Assertion*>& assertions = response->getAssertions();
147 const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
148 if (assertions.empty() && encassertions.empty())
149 throw FatalProfileException("Incoming message contained no SAML assertions.");
151 // Maintain list of "legit" tokens to feed to SP subsystems.
152 const Subject* ssoSubject=NULL;
153 const AuthnStatement* ssoStatement=NULL;
154 vector<const opensaml::Assertion*> tokens;
156 // Also track "bad" tokens that we'll cache but not use.
157 // This is necessary because there may be valid tokens not aimed at us.
158 vector<const opensaml::Assertion*> badtokens;
160 // And also track "owned" tokens that we decrypt here.
161 vector<saml2::Assertion*> ownedtokens;
163 // With this flag on, we ignore any unsigned assertions.
164 const EntityDescriptor* entity = NULL;
165 pair<bool,bool> flag = make_pair(false,false);
166 if (alreadySecured && policy.getIssuerMetadata()) {
167 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
168 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
171 // authnskew allows rejection of SSO if AuthnInstant is too old.
172 const PropertySet* sessionProps = application.getPropertySet("Sessions");
173 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
175 // Saves off error messages potentially helpful for users.
176 string contextualError;
178 // Ensure the Bearer rule is in the policy set.
179 if (find_if(policy.getRules(), _rulenamed(BEARER_POLICY_RULE)) == NULL)
180 policy.getRules().push_back(m_ssoRule);
182 // Populate recipient as audience.
183 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
185 time_t now = time(NULL);
186 for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
188 // Skip unsigned assertion?
189 if (!(*a)->getSignature() && flag.first && flag.second)
190 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
192 // We clear the security flag, so we can tell whether the token was secured on its own.
193 policy.setAuthenticated(false);
196 // Extract message bits and re-verify Issuer information.
197 extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
199 // Run the policy over the assertion. Handles replay, freshness, and
200 // signature verification, assuming the relevant rules are configured,
201 // along with condition and profile enforcement.
202 policy.evaluate(*(*a), &httpRequest);
204 // If no security is in place now, we kick it.
205 if (!alreadySecured && !policy.isAuthenticated())
206 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
208 // If we hadn't established Issuer yet, redo the signedAssertions check.
209 if (!entity && policy.getIssuerMetadata()) {
210 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
211 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
212 if (!(*a)->getSignature() && flag.first && flag.second)
213 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
217 SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
218 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
220 if (subcondata && subcondata->getAddress()) {
221 auto_ptr_char boundip(subcondata->getAddress());
222 checkAddress(application, httpRequest, boundip.get());
225 // Track it as a valid token.
226 tokens.push_back(*a);
228 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
229 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
230 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
231 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
232 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
233 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
237 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
238 if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
239 ssoSubject = (*a)->getSubject();
241 catch (exception& ex) {
242 m_log.warn("detected a problem with assertion: %s", ex.what());
244 contextualError = ex.what();
245 badtokens.push_back(*a);
249 // In case we need decryption...
250 CredentialResolver* cr=application.getCredentialResolver();
251 if (!cr && !encassertions.empty())
252 m_log.warn("found encrypted assertions, but no CredentialResolver was available");
254 for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
255 // Attempt to decrypt it.
256 saml2::Assertion* decrypted=NULL;
258 Locker credlocker(cr);
259 auto_ptr<MetadataCredentialCriteria> mcc(
260 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
262 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
263 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
266 ownedtokens.push_back(decrypted);
267 if (m_log.isDebugEnabled())
268 m_log.debugStream() << "decrypted Assertion: " << *decrypted << logging::eol;
271 catch (exception& ex) {
272 m_log.error(ex.what());
278 // We clear the security flag, so we can tell whether the token was secured on its own.
279 policy.setAuthenticated(false);
282 // Extract message bits and re-verify Issuer information.
283 extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
285 // Run the policy over the assertion. Handles replay, freshness, and
286 // signature verification, assuming the relevant rules are configured,
287 // along with condition and profile enforcement.
288 // We have to marshall the object first to ensure signatures can be checked.
289 if (!decrypted->getDOM())
290 decrypted->marshall();
291 policy.evaluate(*decrypted, &httpRequest);
293 // If no security is in place now, we kick it.
294 if (!alreadySecured && !policy.isAuthenticated())
295 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
297 // If we hadn't established Issuer yet, redo the signedAssertions check.
298 if (!entity && policy.getIssuerMetadata()) {
299 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
300 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
301 if (!decrypted->getSignature() && flag.first && flag.second)
302 throw SecurityPolicyException("The decrypted assertion was unsigned, violating local security policy.");
306 SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
307 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
309 if (subcondata && subcondata->getAddress()) {
310 auto_ptr_char boundip(subcondata->getAddress());
311 checkAddress(application, httpRequest, boundip.get());
314 // Track it as a valid token.
315 tokens.push_back(decrypted);
317 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
318 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
319 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
320 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
321 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
322 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
326 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
327 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
328 ssoSubject = decrypted->getSubject();
330 catch (exception& ex) {
331 m_log.warn("detected a problem with assertion: %s", ex.what());
333 contextualError = ex.what();
334 badtokens.push_back(decrypted);
339 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
340 if (contextualError.empty())
341 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
342 throw FatalProfileException(contextualError.c_str());
345 // May need to decrypt NameID.
346 bool ownedName = false;
347 NameID* ssoName = ssoSubject->getNameID();
349 EncryptedID* encname = ssoSubject->getEncryptedID();
352 m_log.warn("found encrypted NameID, but no decryption credential was available");
354 Locker credlocker(cr);
355 auto_ptr<MetadataCredentialCriteria> mcc(
356 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
359 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get()));
360 ssoName = dynamic_cast<NameID*>(decryptedID.get());
363 decryptedID.release();
364 if (m_log.isDebugEnabled())
365 m_log.debugStream() << "decrypted NameID: " << *ssoName << logging::eol;
368 catch (exception& ex) {
369 m_log.error(ex.what());
375 m_log.debug("SSO profile processing completed successfully");
377 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
378 // To complete processing, we need to extract and resolve attributes and then create the session.
380 // Now we have to extract the authentication details for session setup.
382 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
383 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ?
384 (ssoStatement->getSessionNotOnOrAfterEpoch() + XMLToolingConfig::getConfig().clock_skew_secs) : 0;
385 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
386 if (!lifetime.first || lifetime.second == 0)
387 lifetime.second = 28800;
389 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
391 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
393 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
396 // The context will handle deleting attributes and new tokens.
397 auto_ptr<ResolutionContext> ctx(
400 policy.getIssuerMetadata(),
401 samlconstants::SAML20P_NS,
404 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
405 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
411 // Copy over any new tokens, but leave them in the context for cleanup.
412 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
415 // Now merge in bad tokens for caching.
416 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
418 application.getServiceProvider().getSessionCache()->insert(
424 samlconstants::SAML20P_NS,
426 ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
427 ssoStatement->getSessionIndex(),
428 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
429 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
431 ctx.get() ? &ctx->getResolvedAttributes() : NULL
436 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
441 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());