2 * Copyright 2001-2007 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 "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SessionCache.h"
28 #include "attribute/resolver/ResolutionContext.h"
29 #include "handler/AssertionConsumerService.h"
31 #include <saml/saml2/core/Protocols.h>
32 #include <saml/saml2/profile/BrowserSSOProfileValidator.h>
33 #include <saml/saml2/metadata/Metadata.h>
35 using namespace shibsp;
36 using namespace opensaml::saml2;
37 using namespace opensaml::saml2p;
38 using namespace opensaml;
39 using namespace xmltooling;
40 using namespace log4cpp;
42 using saml2md::EntityDescriptor;
46 #if defined (_MSC_VER)
47 #pragma warning( push )
48 #pragma warning( disable : 4250 )
51 class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
54 SAML2Consumer(const DOMElement* e, const char* appId)
55 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SAML2")) {
57 virtual ~SAML2Consumer() {}
60 string implementProtocol(
61 const Application& application,
62 const HTTPRequest& httpRequest,
63 SecurityPolicy& policy,
64 const PropertySet* settings,
65 const XMLObject& xmlObject
69 #if defined (_MSC_VER)
70 #pragma warning( pop )
73 Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
75 return new SAML2Consumer(p.first, p.second);
80 string SAML2Consumer::implementProtocol(
81 const Application& application,
82 const HTTPRequest& httpRequest,
83 SecurityPolicy& policy,
84 const PropertySet* settings,
85 const XMLObject& xmlObject
88 // Implementation of SAML 2.0 SSO profile(s).
89 m_log.debug("processing message against SAML 2.0 SSO profile");
91 // Remember whether we already established trust.
92 // None of the SAML 2 bindings require security at the protocol layer.
93 bool alreadySecured = policy.isSecure();
95 // Check for errors...this will throw if it's not a successful message.
96 checkError(&xmlObject);
98 const Response* response = dynamic_cast<const Response*>(&xmlObject);
100 throw FatalProfileException("Incoming message was not a samlp:Response.");
102 const vector<saml2::Assertion*>& assertions = response->getAssertions();
103 const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
104 if (assertions.empty() && encassertions.empty())
105 throw FatalProfileException("Incoming message contained no SAML assertions.");
107 // Maintain list of "legit" tokens to feed to SP subsystems.
108 const Subject* ssoSubject=NULL;
109 const AuthnStatement* ssoStatement=NULL;
110 vector<const opensaml::Assertion*> tokens;
112 // Also track "bad" tokens that we'll cache but not use.
113 // This is necessary because there may be valid tokens not aimed at us.
114 vector<const opensaml::Assertion*> badtokens;
116 // And also track "owned" tokens that we decrypt here.
117 vector<saml2::Assertion*> ownedtokens;
119 // Profile validator.
120 time_t now = time(NULL);
121 string dest = httpRequest.getRequestURL();
122 BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str());
124 // With this flag on, we ignore any unsigned assertions.
125 pair<bool,bool> flag = settings->getBool("signedAssertions");
127 // Saves off IP-mismatch error message because it's potentially helpful for users.
128 string addressMismatch;
130 for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
131 // Skip unsigned assertion?
132 if (!(*a)->getSignature() && flag.first && flag.second) {
133 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
134 badtokens.push_back(*a);
139 // We clear the security flag, so we can tell whether the token was secured on its own.
140 policy.setSecure(false);
142 // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
143 // and signature verification, assuming the relevant rules are configured.
144 policy.evaluate(*(*a));
146 // If no security is in place now, we kick it.
147 if (!alreadySecured && !policy.isSecure()) {
148 m_log.warn("unable to establish security of assertion");
149 badtokens.push_back(*a);
153 // Now do profile and core semantic validation to ensure we can use it for SSO.
154 ssoValidator.validateAssertion(*(*a));
158 if (ssoValidator.getAddress())
159 checkAddress(application, httpRequest, ssoValidator.getAddress());
161 catch (exception& ex) {
162 // We save off the message if there's no SSO statement yet.
164 addressMismatch = ex.what();
168 // Track it as a valid token.
169 tokens.push_back(*a);
171 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
172 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
173 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
174 if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
178 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
179 if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
180 ssoSubject = (*a)->getSubject();
182 catch (exception& ex) {
183 m_log.warn("detected a problem with assertion: %s", ex.what());
184 badtokens.push_back(*a);
188 CredentialResolver* cr=NULL;
\r
189 const PropertySet* credUse = application.getCredentialUse(
\r
190 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL
\r
193 cr = application.getServiceProvider().getCredentialResolver(credUse->getString("Encryption").second);
194 if (!cr && !encassertions.empty())
195 m_log.warn("found encrypted assertions, but no decryption credential was available");
197 for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
198 // Attempt to decrypt it.
199 saml2::Assertion* decrypted=NULL;
201 Locker credlocker(cr);
202 auto_ptr<XMLObject> wrapper((*ea)->decrypt(cr, application.getXMLString("providerId").second));
203 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
206 ownedtokens.push_back(decrypted);
209 catch (exception& ex) {
210 m_log.error(ex.what());
215 // Skip unsigned assertion?
216 if (!decrypted->getSignature() && flag.first && flag.second) {
217 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
218 badtokens.push_back(decrypted);
223 // We clear the security flag, so we can tell whether the token was secured on its own.
224 policy.setSecure(false);
226 // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
227 // and signature verification, assuming the relevant rules are configured.
228 // We have to marshall the object first to ensure signatures can be checked.
229 decrypted->marshall();
230 policy.evaluate(*decrypted);
232 // If no security is in place now, we kick it.
233 if (!alreadySecured && !policy.isSecure()) {
234 m_log.warn("unable to establish security of assertion");
235 badtokens.push_back(decrypted);
239 // Now do profile and core semantic validation to ensure we can use it for SSO.
240 ssoValidator.validateAssertion(*decrypted);
244 if (ssoValidator.getAddress())
245 checkAddress(application, httpRequest, ssoValidator.getAddress());
247 catch (exception& ex) {
248 // We save off the message if there's no SSO statement yet.
250 addressMismatch = ex.what();
254 // Track it as a valid token.
255 tokens.push_back(decrypted);
257 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
258 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
259 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
260 if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
264 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
265 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
266 ssoSubject = decrypted->getSubject();
268 catch (exception& ex) {
269 m_log.warn("detected a problem with assertion: %s", ex.what());
270 badtokens.push_back(decrypted);
275 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
276 if (addressMismatch.empty())
277 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
278 throw FatalProfileException(addressMismatch.c_str());
281 // May need to decrypt NameID.
282 bool ownedName = false;
283 NameID* ssoName = ssoSubject->getNameID();
285 EncryptedID* encname = ssoSubject->getEncryptedID();
288 m_log.warn("found encrypted NameID, but no decryption credential was available");
290 Locker credlocker(cr);
292 auto_ptr<XMLObject> decryptedID(encname->decrypt(cr,application.getXMLString("providerId").second));
293 ssoName = dynamic_cast<NameID*>(decryptedID.get());
296 decryptedID.release();
299 catch (exception& ex) {
300 m_log.error(ex.what());
306 m_log.debug("SSO profile processing completed successfully");
308 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
309 // To complete processing, we need to resolve attributes and then create the session.
312 const EntityDescriptor* issuerMetadata = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
313 auto_ptr<ResolutionContext> ctx(
314 resolveAttributes(application, httpRequest, issuerMetadata, ssoName, &tokens)
317 // Copy over any new tokens, but leave them in the context for cleanup.
318 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
320 // Now merge in bad tokens for caching.
321 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
323 // Now we have to extract the authentication details for session setup.
325 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
326 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
327 const PropertySet* sessionProps = application.getPropertySet("Sessions");
328 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : make_pair(true,28800);
330 lifetime.second = 28800;
331 if (lifetime.second != 0) {
333 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
335 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
339 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
340 auto_ptr_char authnClass((authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL);
341 auto_ptr_char authnDecl((authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL);
342 auto_ptr_char index(ssoStatement->getSessionIndex());
343 auto_ptr_char authnInstant(ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL);
345 vector<shibsp::Attribute*>& attrs = ctx->getResolvedAttributes();
346 string key = application.getServiceProvider().getSessionCache()->insert(
349 httpRequest.getRemoteAddr().c_str(),
359 attrs.clear(); // Attributes are owned by cache now.
363 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
370 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());