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 // We look up decryption credentials based on the peer who did the encrypting.
189 CredentialCriteria cc;
190 if (policy.getIssuerMetadata()) {
191 auto_ptr_char assertingParty(dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent())->getEntityID());
192 cc.setPeerName(assertingParty.get());
194 CredentialResolver* cr=application.getCredentialResolver();
196 if (!cr && !encassertions.empty())
197 m_log.warn("found encrypted assertions, but no CredentialResolver was available");
199 for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
200 // Attempt to decrypt it.
201 saml2::Assertion* decrypted=NULL;
203 Locker credlocker(cr);
204 auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("providerId").second, &cc));
205 decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
208 ownedtokens.push_back(decrypted);
211 catch (exception& ex) {
212 m_log.error(ex.what());
217 // Skip unsigned assertion?
218 if (!decrypted->getSignature() && flag.first && flag.second) {
219 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
220 badtokens.push_back(decrypted);
225 // We clear the security flag, so we can tell whether the token was secured on its own.
226 policy.setSecure(false);
228 // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
229 // and signature verification, assuming the relevant rules are configured.
230 // We have to marshall the object first to ensure signatures can be checked.
231 decrypted->marshall();
232 policy.evaluate(*decrypted);
234 // If no security is in place now, we kick it.
235 if (!alreadySecured && !policy.isSecure()) {
236 m_log.warn("unable to establish security of assertion");
237 badtokens.push_back(decrypted);
241 // Now do profile and core semantic validation to ensure we can use it for SSO.
242 ssoValidator.validateAssertion(*decrypted);
246 if (ssoValidator.getAddress())
247 checkAddress(application, httpRequest, ssoValidator.getAddress());
249 catch (exception& ex) {
250 // We save off the message if there's no SSO statement yet.
252 addressMismatch = ex.what();
256 // Track it as a valid token.
257 tokens.push_back(decrypted);
259 // Save off the first valid SSO statement, but favor the "soonest" session expiration.
260 const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
261 for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
262 if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
266 // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
267 if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
268 ssoSubject = decrypted->getSubject();
270 catch (exception& ex) {
271 m_log.warn("detected a problem with assertion: %s", ex.what());
272 badtokens.push_back(decrypted);
277 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
278 if (addressMismatch.empty())
279 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
280 throw FatalProfileException(addressMismatch.c_str());
283 // May need to decrypt NameID.
284 bool ownedName = false;
285 NameID* ssoName = ssoSubject->getNameID();
287 EncryptedID* encname = ssoSubject->getEncryptedID();
290 m_log.warn("found encrypted NameID, but no decryption credential was available");
292 Locker credlocker(cr);
294 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("providerId").second,&cc));
295 ssoName = dynamic_cast<NameID*>(decryptedID.get());
298 decryptedID.release();
301 catch (exception& ex) {
302 m_log.error(ex.what());
308 m_log.debug("SSO profile processing completed successfully");
310 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
311 // To complete processing, we need to resolve attributes and then create the session.
314 const EntityDescriptor* issuerMetadata = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
315 auto_ptr<ResolutionContext> ctx(
316 resolveAttributes(application, httpRequest, issuerMetadata, ssoName, &tokens)
319 // Copy over any new tokens, but leave them in the context for cleanup.
320 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
322 // Now merge in bad tokens for caching.
323 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
325 // Now we have to extract the authentication details for session setup.
327 // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
328 time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
329 const PropertySet* sessionProps = application.getPropertySet("Sessions");
330 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : make_pair(true,28800);
332 lifetime.second = 28800;
333 if (lifetime.second != 0) {
335 sessionExp = now + lifetime.second; // IdP says nothing, calulate based on SP.
337 sessionExp = min(sessionExp, now + lifetime.second); // Use the lowest.
341 const AuthnContext* authnContext = ssoStatement->getAuthnContext();
342 auto_ptr_char authnClass((authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL);
343 auto_ptr_char authnDecl((authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL);
344 auto_ptr_char index(ssoStatement->getSessionIndex());
345 auto_ptr_char authnInstant(ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL);
347 vector<shibsp::Attribute*>& attrs = ctx->getResolvedAttributes();
348 string key = application.getServiceProvider().getSessionCache()->insert(
351 httpRequest.getRemoteAddr().c_str(),
361 attrs.clear(); // Attributes are owned by cache now.
365 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
372 for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());