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 "exceptions.h"
28 # include "Application.h"
29 # include "ServiceProvider.h"
30 # include "SessionCache.h"
31 # include "attribute/resolver/ResolutionContext.h"
32 # include <saml/SAMLConfig.h>
33 # include <saml/saml2/core/Protocols.h>
34 # include <saml/saml2/metadata/Metadata.h>
35 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
36 # include <saml/saml2/profile/SAML2AssertionPolicy.h>
37 using namespace opensaml::saml2;
38 using namespace opensaml::saml2p;
39 using namespace opensaml::saml2md;
40 using namespace opensaml;
42 # define min(a,b) (((a) < (b)) ? (a) : (b))
46 using namespace shibsp;
47 using namespace xmltooling;
52 #if defined (_MSC_VER)
53 #pragma warning( push )
54 #pragma warning( disable : 4250 )
57 class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
60 SAML2Consumer(const DOMElement* e, const char* appId)
61 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML2")) {
64 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
65 m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(BEARER_POLICY_RULE, e);
68 virtual ~SAML2Consumer() {
75 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
76 AssertionConsumerService::generateMetadata(role, handlerURL);
77 role.addSupport(samlconstants::SAML20P_NS);
81 void implementProtocol(
82 const Application& application,
83 const HTTPRequest& httpRequest,
84 HTTPResponse& httpResponse,
85 SecurityPolicy& policy,
86 const PropertySet* settings,
87 const XMLObject& xmlObject
90 SecurityPolicyRule* m_ssoRule;
94 #if defined (_MSC_VER)
95 #pragma warning( pop )
98 Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
100 return new SAML2Consumer(p.first, p.second);
104 class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
107 _rulenamed(const char* name) : m_name(name) {}
108 bool operator()(const SecurityPolicyRule* rule) const {
109 return rule ? !strcmp(m_name, rule->getType()) : false;
119 void SAML2Consumer::implementProtocol(
120 const Application& application,
121 const HTTPRequest& httpRequest,
122 HTTPResponse& httpResponse,
123 SecurityPolicy& policy,
124 const PropertySet* settings,
125 const XMLObject& xmlObject
128 // Implementation of SAML 2.0 SSO profile(s).
129 m_log.debug("processing message against SAML 2.0 SSO profile");
131 // Remember whether we already established trust.
132 // None of the SAML 2 bindings require security at the protocol layer.
133 bool alreadySecured = policy.isAuthenticated();
135 // Check for errors...this will throw if it's not a successful message.
136 checkError(&xmlObject, policy.getIssuerMetadata());
138 const Response* response = dynamic_cast<const Response*>(&xmlObject);
140 throw FatalProfileException("Incoming message was not a samlp:Response.");
142 const vector<saml2::Assertion*>& assertions = response->getAssertions();
143 const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
144 if (assertions.empty() && encassertions.empty())
145 throw FatalProfileException("Incoming message contained no SAML assertions.");
147 // Maintain list of "legit" tokens to feed to SP subsystems.
148 const Subject* ssoSubject=NULL;
149 const AuthnStatement* ssoStatement=NULL;
150 vector<const opensaml::Assertion*> tokens;
152 // Also track "bad" tokens that we'll cache but not use.
153 // This is necessary because there may be valid tokens not aimed at us.
154 vector<const opensaml::Assertion*> badtokens;
156 // And also track "owned" tokens that we decrypt here.
157 vector<saml2::Assertion*> ownedtokens;
159 // With this flag on, we ignore any unsigned assertions.
160 const EntityDescriptor* entity = NULL;
161 pair<bool,bool> flag = make_pair(false,false);
162 if (alreadySecured && policy.getIssuerMetadata()) {
163 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
164 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
167 // authnskew allows rejection of SSO if AuthnInstant is too old.
168 const PropertySet* sessionProps = application.getPropertySet("Sessions");
169 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
171 // Saves off error messages potentially helpful for users.
172 string contextualError;
174 // Ensure the Bearer rule is in the policy set.
175 if (find_if(policy.getRules(), _rulenamed(BEARER_POLICY_RULE)) == NULL)
176 policy.getRules().push_back(m_ssoRule);
178 // Populate recipient as audience.
179 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
181 time_t now = time(NULL);
182 for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
184 // Skip unsigned assertion?
185 if (!(*a)->getSignature() && flag.first && flag.second)
186 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
188 // We clear the security flag, so we can tell whether the token was secured on its own.
189 policy.setAuthenticated(false);
192 // Extract message bits and re-verify Issuer information.
193 extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
195 // Run the policy over the assertion. Handles replay, freshness, and
196 // signature verification, assuming the relevant rules are configured,
197 // along with condition and profile enforcement.
198 policy.evaluate(*(*a), &httpRequest);
200 // If no security is in place now, we kick it.
201 if (!alreadySecured && !policy.isAuthenticated())
202 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
204 // If we hadn't established Issuer yet, redo the signedAssertions check.
205 if (!entity && policy.getIssuerMetadata()) {
206 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
207 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
208 if (!(*a)->getSignature() && flag.first && flag.second)
209 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
213 SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
214 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
216 if (subcondata && subcondata->getAddress()) {
217 auto_ptr_char boundip(subcondata->getAddress());
218 checkAddress(application, httpRequest, boundip.get());
221 // Track it as a valid token.
222 tokens.push_back(*a);
224 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
225 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
226 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
227 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
228 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
229 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
233 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
234 if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
235 ssoSubject = (*a)->getSubject();
237 catch (exception& ex) {
238 m_log.warn("detected a problem with assertion: %s", ex.what());
240 contextualError = ex.what();
241 badtokens.push_back(*a);
245 // In case we need decryption...
246 CredentialResolver* cr=application.getCredentialResolver();
247 if (!cr && !encassertions.empty())
248 m_log.warn("found encrypted assertions, but no CredentialResolver was available");
250 for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
251 // Attempt to decrypt it.
252 saml2::Assertion* decrypted=NULL;
254 Locker credlocker(cr);
255 auto_ptr<MetadataCredentialCriteria> mcc(
256 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
258 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
259 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
262 ownedtokens.push_back(decrypted);
263 if (m_log.isDebugEnabled())
264 m_log.debugStream() << "decrypted Assertion: " << *decrypted << logging::eol;
267 catch (exception& ex) {
268 m_log.error(ex.what());
274 // We clear the security flag, so we can tell whether the token was secured on its own.
275 policy.setAuthenticated(false);
278 // Extract message bits and re-verify Issuer information.
279 extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
281 // Run the policy over the assertion. Handles replay, freshness, and
282 // signature verification, assuming the relevant rules are configured,
283 // along with condition and profile enforcement.
284 // We have to marshall the object first to ensure signatures can be checked.
285 if (!decrypted->getDOM())
286 decrypted->marshall();
287 policy.evaluate(*decrypted, &httpRequest);
289 // If no security is in place now, we kick it.
290 if (!alreadySecured && !policy.isAuthenticated())
291 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
293 // If we hadn't established Issuer yet, redo the signedAssertions check.
294 if (!entity && policy.getIssuerMetadata()) {
295 entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
296 flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
297 if (!decrypted->getSignature() && flag.first && flag.second)
298 throw SecurityPolicyException("The decrypted assertion was unsigned, violating local security policy.");
302 SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
303 dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
305 if (subcondata && subcondata->getAddress()) {
306 auto_ptr_char boundip(subcondata->getAddress());
307 checkAddress(application, httpRequest, boundip.get());
310 // Track it as a valid token.
311 tokens.push_back(decrypted);
313 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
314 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
315 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
316 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
317 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
318 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
322 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
323 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
324 ssoSubject = decrypted->getSubject();
326 catch (exception& ex) {
327 m_log.warn("detected a problem with assertion: %s", ex.what());
329 contextualError = ex.what();
330 badtokens.push_back(decrypted);
335 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
336 if (contextualError.empty())
337 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
338 throw FatalProfileException(contextualError.c_str());
341 // May need to decrypt NameID.
342 bool ownedName = false;
343 NameID* ssoName = ssoSubject->getNameID();
345 EncryptedID* encname = ssoSubject->getEncryptedID();
348 m_log.warn("found encrypted NameID, but no decryption credential was available");
350 Locker credlocker(cr);
351 auto_ptr<MetadataCredentialCriteria> mcc(
352 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
355 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get()));
356 ssoName = dynamic_cast<NameID*>(decryptedID.get());
359 decryptedID.release();
360 if (m_log.isDebugEnabled())
361 m_log.debugStream() << "decrypted NameID: " << *ssoName << logging::eol;
364 catch (exception& ex) {
365 m_log.error(ex.what());
371 m_log.debug("SSO profile processing completed successfully");
373 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
374 // To complete processing, we need to extract and resolve attributes and then create the session.
376 // Now we have to extract the authentication details for session setup.
378 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
379 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ?
380 (ssoStatement->getSessionNotOnOrAfterEpoch() + XMLToolingConfig::getConfig().clock_skew_secs) : 0;
381 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
382 if (!lifetime.first || lifetime.second == 0)
383 lifetime.second = 28800;
385 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
387 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
389 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
392 // The context will handle deleting attributes and new tokens.
393 auto_ptr<ResolutionContext> ctx(
396 policy.getIssuerMetadata(),
397 samlconstants::SAML20P_NS,
400 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
401 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
407 // Copy over any new tokens, but leave them in the context for cleanup.
408 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
411 // Now merge in bad tokens for caching.
412 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
414 application.getServiceProvider().getSessionCache()->insert(
420 samlconstants::SAML20P_NS,
422 ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
423 ssoStatement->getSessionIndex(),
424 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
425 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
427 ctx.get() ? &ctx->getResolvedAttributes() : NULL
432 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
437 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());