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 1.x 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/Attribute.h"
32 # include "attribute/filtering/AttributeFilter.h"
33 # include "attribute/filtering/BasicFilteringContext.h"
34 # include "attribute/resolver/AttributeExtractor.h"
35 # include "attribute/resolver/ResolutionContext.h"
36 # include <saml/saml1/core/Assertions.h>
37 # include <saml/saml1/core/Protocols.h>
38 # include <saml/saml1/profile/BrowserSSOProfileValidator.h>
39 # include <saml/saml2/metadata/Metadata.h>
40 using namespace opensaml::saml1;
41 using namespace opensaml::saml1p;
42 using namespace opensaml;
44 using saml2::NameIDBuilder;
45 using saml2md::EntityDescriptor;
47 # include "lite/SAMLConstants.h"
50 using namespace shibsp;
51 using namespace xmltooling;
52 using namespace log4cpp;
57 #if defined (_MSC_VER)
58 #pragma warning( push )
59 #pragma warning( disable : 4250 )
62 class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
65 SAML1Consumer(const DOMElement* e, const char* appId)
66 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
68 m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
71 virtual ~SAML1Consumer() {}
75 string implementProtocol(
76 const Application& application,
77 const HTTPRequest& httpRequest,
78 SecurityPolicy& policy,
79 const PropertySet* settings,
80 const XMLObject& xmlObject
86 #if defined (_MSC_VER)
87 #pragma warning( pop )
90 Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
92 return new SAML1Consumer(p.first, p.second);
99 string SAML1Consumer::implementProtocol(
100 const Application& application,
101 const HTTPRequest& httpRequest,
102 SecurityPolicy& policy,
103 const PropertySet* settings,
104 const XMLObject& xmlObject
107 // Implementation of SAML 1.x SSO profile(s).
108 m_log.debug("processing message against SAML 1.x SSO profile");
110 // With the binding aspects now moved out to the MessageDecoder,
111 // the focus here is on the assertion content. For SAML 1.x POST,
112 // all the security comes from the protocol layer, and signing
113 // the assertion isn't sufficient. So we can check the policy
114 // object now and bail if it's not a secure message.
115 if (m_post && !policy.isSecure())
116 throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
118 // Remember whether we already established trust.
119 bool alreadySecured = policy.isSecure();
121 // Check for errors...this will throw if it's not a successful message.
122 checkError(&xmlObject);
124 const Response* response = dynamic_cast<const Response*>(&xmlObject);
126 throw FatalProfileException("Incoming message was not a samlp:Response.");
128 const vector<saml1::Assertion*>& assertions = response->getAssertions();
129 if (assertions.empty())
130 throw FatalProfileException("Incoming message contained no SAML assertions.");
132 // Maintain list of "legit" tokens to feed to SP subsystems.
133 const AuthenticationStatement* ssoStatement=NULL;
134 vector<const opensaml::Assertion*> tokens;
136 // Also track "bad" tokens that we'll cache but not use.
137 // This is necessary because there may be valid tokens not aimed at us.
138 vector<const opensaml::Assertion*> badtokens;
140 // Profile validator.
141 time_t now = time(NULL);
142 BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now);
144 // With this flag on, we ignore any unsigned assertions.
145 pair<bool,bool> flag = settings->getBool("signedAssertions");
147 for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
148 // Skip unsigned assertion?
149 if (!(*a)->getSignature() && flag.first && flag.second) {
150 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
151 badtokens.push_back(*a);
156 // We clear the security flag, so we can tell whether the token was secured on its own.
157 policy.setSecure(false);
159 // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
160 // and signature verification, assuming the relevant rules are configured.
161 policy.evaluate(*(*a));
163 // If no security is in place now, we kick it.
164 if (!alreadySecured && !policy.isSecure()) {
165 m_log.warn("unable to establish security of assertion");
166 badtokens.push_back(*a);
170 // Now do profile and core semantic validation to ensure we can use it for SSO.
171 ssoValidator.validateAssertion(*(*a));
173 // Track it as a valid token.
174 tokens.push_back(*a);
176 // Save off the first valid SSO statement.
177 if (!ssoStatement && !(*a)->getAuthenticationStatements().empty())
178 ssoStatement = (*a)->getAuthenticationStatements().front();
180 catch (exception& ex) {
181 m_log.warn("detected a problem with assertion: %s", ex.what());
182 badtokens.push_back(*a);
187 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
190 SubjectLocality* locality = ssoStatement->getSubjectLocality();
191 if (locality && locality->getIPAddress()) {
192 auto_ptr_char ip(locality->getIPAddress());
193 checkAddress(application, httpRequest, ip.get());
196 m_log.debug("SSO profile processing completed successfully");
198 NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
200 // Now we have to extract the authentication details for attribute and session setup.
202 // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
203 const PropertySet* sessionProps = application.getPropertySet("Sessions");
204 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
205 if (!lifetime.first || lifetime.second == 0)
206 lifetime.second = 28800;
208 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
209 // To complete processing, we need to extract and resolve attributes and then create the session.
210 multimap<string,Attribute*> resolvedAttributes;
211 AttributeExtractor* extractor = application.getAttributeExtractor();
213 m_log.debug("extracting pushed attributes...");
214 Locker extlocker(extractor);
217 extractor->extractAttributes(application, policy.getIssuerMetadata(), *n, resolvedAttributes);
219 catch (exception& ex) {
220 m_log.error("caught exception extracting attributes: %s", ex.what());
223 for (vector<const opensaml::Assertion*>::const_iterator t = tokens.begin(); t!=tokens.end(); ++t) {
225 extractor->extractAttributes(application, policy.getIssuerMetadata(), *(*t), resolvedAttributes);
227 catch (exception& ex) {
228 m_log.error("caught exception extracting attributes: %s", ex.what());
232 AttributeFilter* filter = application.getAttributeFilter();
233 if (filter && !resolvedAttributes.empty()) {
234 BasicFilteringContext fc(application, resolvedAttributes, policy.getIssuerMetadata(), ssoStatement->getAuthenticationMethod());
235 Locker filtlocker(filter);
237 filter->filterAttributes(fc, resolvedAttributes);
239 catch (exception& ex) {
240 m_log.error("caught exception filtering attributes: %s", ex.what());
241 m_log.error("dumping extracted attributes due to filtering exception");
242 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,shibsp::Attribute>());
243 resolvedAttributes.clear();
248 // Normalize the SAML 1.x NameIdentifier...
249 auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : NULL);
251 nameid->setName(n->getName());
252 nameid->setFormat(n->getFormat());
253 nameid->setNameQualifier(n->getNameQualifier());
256 const EntityDescriptor* issuerMetadata =
257 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
258 auto_ptr<ResolutionContext> ctx(
262 (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
263 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
265 ssoStatement->getAuthenticationMethod(),
273 // Copy over any new tokens, but leave them in the context for cleanup.
274 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
276 // Copy over new attributes, and transfer ownership.
277 resolvedAttributes.insert(ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
278 ctx->getResolvedAttributes().clear();
281 // Now merge in bad tokens for caching.
282 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
285 string key = application.getServiceProvider().getSessionCache()->insert(
286 now + lifetime.second,
288 httpRequest.getRemoteAddr().c_str(),
290 (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
291 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
293 ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
295 ssoStatement->getAuthenticationMethod(),
300 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());
304 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());