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 "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SessionCache.h"
28 #include "attribute/Attribute.h"
29 #include "attribute/filtering/AttributeFilter.h"
30 #include "attribute/filtering/BasicFilteringContext.h"
31 #include "attribute/resolver/AttributeExtractor.h"
32 #include "attribute/resolver/ResolutionContext.h"
33 #include "handler/AssertionConsumerService.h"
35 #include <saml/saml1/core/Assertions.h>
36 #include <saml/saml1/core/Protocols.h>
37 #include <saml/saml1/profile/BrowserSSOProfileValidator.h>
38 #include <saml/saml2/metadata/Metadata.h>
40 using namespace shibsp;
41 using namespace opensaml::saml1;
42 using namespace opensaml::saml1p;
43 using namespace opensaml;
44 using namespace xmltooling;
45 using namespace log4cpp;
48 using saml2::NameIDBuilder;
49 using saml2md::EntityDescriptor;
53 #if defined (_MSC_VER)
54 #pragma warning( push )
55 #pragma warning( disable : 4250 )
58 class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
61 SAML1Consumer(const DOMElement* e, const char* appId)
62 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SAML1")) {
63 m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
65 virtual ~SAML1Consumer() {}
68 string implementProtocol(
69 const Application& application,
70 const HTTPRequest& httpRequest,
71 SecurityPolicy& policy,
72 const PropertySet* settings,
73 const XMLObject& xmlObject
79 #if defined (_MSC_VER)
80 #pragma warning( pop )
83 Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
85 return new SAML1Consumer(p.first, p.second);
90 string SAML1Consumer::implementProtocol(
91 const Application& application,
92 const HTTPRequest& httpRequest,
93 SecurityPolicy& policy,
94 const PropertySet* settings,
95 const XMLObject& xmlObject
98 // Implementation of SAML 1.x SSO profile(s).
99 m_log.debug("processing message against SAML 1.x SSO profile");
101 // With the binding aspects now moved out to the MessageDecoder,
102 // the focus here is on the assertion content. For SAML 1.x POST,
103 // all the security comes from the protocol layer, and signing
104 // the assertion isn't sufficient. So we can check the policy
105 // object now and bail if it's not a secure message.
106 if (m_post && !policy.isSecure())
107 throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
109 // Remember whether we already established trust.
110 bool alreadySecured = policy.isSecure();
112 // Check for errors...this will throw if it's not a successful message.
113 checkError(&xmlObject);
115 const Response* response = dynamic_cast<const Response*>(&xmlObject);
117 throw FatalProfileException("Incoming message was not a samlp:Response.");
119 const vector<saml1::Assertion*>& assertions = response->getAssertions();
120 if (assertions.empty())
121 throw FatalProfileException("Incoming message contained no SAML assertions.");
123 // Maintain list of "legit" tokens to feed to SP subsystems.
124 const AuthenticationStatement* ssoStatement=NULL;
125 vector<const opensaml::Assertion*> tokens;
127 // Also track "bad" tokens that we'll cache but not use.
128 // This is necessary because there may be valid tokens not aimed at us.
129 vector<const opensaml::Assertion*> badtokens;
131 // Profile validator.
132 time_t now = time(NULL);
133 BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now);
135 // With this flag on, we ignore any unsigned assertions.
136 pair<bool,bool> flag = settings->getBool("signedAssertions");
138 for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
139 // Skip unsigned assertion?
140 if (!(*a)->getSignature() && flag.first && flag.second) {
141 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
142 badtokens.push_back(*a);
147 // We clear the security flag, so we can tell whether the token was secured on its own.
148 policy.setSecure(false);
150 // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
151 // and signature verification, assuming the relevant rules are configured.
152 policy.evaluate(*(*a));
154 // If no security is in place now, we kick it.
155 if (!alreadySecured && !policy.isSecure()) {
156 m_log.warn("unable to establish security of assertion");
157 badtokens.push_back(*a);
161 // Now do profile and core semantic validation to ensure we can use it for SSO.
162 ssoValidator.validateAssertion(*(*a));
164 // Track it as a valid token.
165 tokens.push_back(*a);
167 // Save off the first valid SSO statement.
168 if (!ssoStatement && !(*a)->getAuthenticationStatements().empty())
169 ssoStatement = (*a)->getAuthenticationStatements().front();
171 catch (exception& ex) {
172 m_log.warn("detected a problem with assertion: %s", ex.what());
173 badtokens.push_back(*a);
178 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
181 SubjectLocality* locality = ssoStatement->getSubjectLocality();
182 if (locality && locality->getIPAddress()) {
183 auto_ptr_char ip(locality->getIPAddress());
184 checkAddress(application, httpRequest, ip.get());
187 m_log.debug("SSO profile processing completed successfully");
189 NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
191 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
192 // To complete processing, we need to extract and resolve attributes and then create the session.
193 multimap<string,Attribute*> resolvedAttributes;
194 AttributeExtractor* extractor = application.getAttributeExtractor();
196 m_log.debug("extracting pushed attributes...");
197 Locker extlocker(extractor);
200 extractor->extractAttributes(application, policy.getIssuerMetadata(), *n, resolvedAttributes);
202 catch (exception& ex) {
203 m_log.error("caught exception extracting attributes: %s", ex.what());
206 for (vector<const opensaml::Assertion*>::const_iterator t = tokens.begin(); t!=tokens.end(); ++t) {
208 extractor->extractAttributes(application, policy.getIssuerMetadata(), *(*t), resolvedAttributes);
210 catch (exception& ex) {
211 m_log.error("caught exception extracting attributes: %s", ex.what());
215 AttributeFilter* filter = application.getAttributeFilter();
216 if (filter && !resolvedAttributes.empty()) {
217 BasicFilteringContext fc(application, policy.getIssuerMetadata());
218 Locker filtlocker(filter);
220 filter->filterAttributes(fc, resolvedAttributes);
222 catch (exception& ex) {
223 m_log.error("caught exception filtering attributes: %s", ex.what());
224 m_log.error("dumping extracted attributes due to filtering exception");
225 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,shibsp::Attribute>());
226 resolvedAttributes.clear();
231 // First, normalize the SAML 1.x NameIdentifier...
232 auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : NULL);
234 nameid->setName(n->getName());
235 nameid->setFormat(n->getFormat());
236 nameid->setNameQualifier(n->getNameQualifier());
239 const EntityDescriptor* issuerMetadata =
240 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
241 auto_ptr<ResolutionContext> ctx(
242 resolveAttributes(application, issuerMetadata, nameid.get(), &tokens, &resolvedAttributes)
246 // Copy over any new tokens, but leave them in the context for cleanup.
247 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
249 // Copy over new attributes, and transfer ownership.
250 resolvedAttributes.insert(ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
251 ctx->getResolvedAttributes().clear();
254 // Now merge in bad tokens for caching.
255 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
257 // Now we have to extract the authentication details for session setup.
259 // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
260 const PropertySet* sessionProps = application.getPropertySet("Sessions");
261 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : make_pair(true,28800);
263 lifetime.second = 28800;
264 auto_ptr_char authnInstant(
265 ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL
267 auto_ptr_char authnMethod(ssoStatement->getAuthenticationMethod());
270 string key = application.getServiceProvider().getSessionCache()->insert(
271 lifetime.second ? now + lifetime.second : 0,
273 httpRequest.getRemoteAddr().c_str(),
283 resolvedAttributes.clear(); // Attributes are owned by cache now.
287 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());