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/resolver/AttributeExtractor.h"
30 #include "attribute/resolver/ResolutionContext.h"
31 #include "handler/AssertionConsumerService.h"
33 #include <saml/saml1/core/Assertions.h>
34 #include <saml/saml1/core/Protocols.h>
35 #include <saml/saml1/profile/BrowserSSOProfileValidator.h>
36 #include <saml/saml2/metadata/Metadata.h>
38 using namespace shibsp;
39 using namespace opensaml::saml1;
40 using namespace opensaml::saml1p;
41 using namespace opensaml;
42 using namespace xmltooling;
43 using namespace log4cpp;
46 using saml2::NameIDBuilder;
47 using saml2md::EntityDescriptor;
51 #if defined (_MSC_VER)
52 #pragma warning( push )
53 #pragma warning( disable : 4250 )
56 class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
59 SAML1Consumer(const DOMElement* e, const char* appId)
60 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SAML1")) {
61 m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
63 virtual ~SAML1Consumer() {}
66 string implementProtocol(
67 const Application& application,
68 const HTTPRequest& httpRequest,
69 SecurityPolicy& policy,
70 const PropertySet* settings,
71 const XMLObject& xmlObject
77 #if defined (_MSC_VER)
78 #pragma warning( pop )
81 Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
83 return new SAML1Consumer(p.first, p.second);
88 string SAML1Consumer::implementProtocol(
89 const Application& application,
90 const HTTPRequest& httpRequest,
91 SecurityPolicy& policy,
92 const PropertySet* settings,
93 const XMLObject& xmlObject
96 // Implementation of SAML 1.x SSO profile(s).
97 m_log.debug("processing message against SAML 1.x SSO profile");
99 // With the binding aspects now moved out to the MessageDecoder,
100 // the focus here is on the assertion content. For SAML 1.x POST,
101 // all the security comes from the protocol layer, and signing
102 // the assertion isn't sufficient. So we can check the policy
103 // object now and bail if it's not a secure message.
104 if (m_post && !policy.isSecure())
105 throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
107 // Remember whether we already established trust.
108 bool alreadySecured = policy.isSecure();
110 // Check for errors...this will throw if it's not a successful message.
111 checkError(&xmlObject);
113 const Response* response = dynamic_cast<const Response*>(&xmlObject);
115 throw FatalProfileException("Incoming message was not a samlp:Response.");
117 const vector<saml1::Assertion*>& assertions = response->getAssertions();
118 if (assertions.empty())
119 throw FatalProfileException("Incoming message contained no SAML assertions.");
121 // Maintain list of "legit" tokens to feed to SP subsystems.
122 const AuthenticationStatement* ssoStatement=NULL;
123 vector<const opensaml::Assertion*> tokens;
125 // Also track "bad" tokens that we'll cache but not use.
126 // This is necessary because there may be valid tokens not aimed at us.
127 vector<const opensaml::Assertion*> badtokens;
129 // Profile validator.
130 time_t now = time(NULL);
131 BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now);
133 // With this flag on, we ignore any unsigned assertions.
134 pair<bool,bool> flag = settings->getBool("signedAssertions");
136 for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
137 // Skip unsigned assertion?
138 if (!(*a)->getSignature() && flag.first && flag.second) {
139 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
140 badtokens.push_back(*a);
145 // We clear the security flag, so we can tell whether the token was secured on its own.
146 policy.setSecure(false);
148 // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
149 // and signature verification, assuming the relevant rules are configured.
150 policy.evaluate(*(*a));
152 // If no security is in place now, we kick it.
153 if (!alreadySecured && !policy.isSecure()) {
154 m_log.warn("unable to establish security of assertion");
155 badtokens.push_back(*a);
159 // Now do profile and core semantic validation to ensure we can use it for SSO.
160 ssoValidator.validateAssertion(*(*a));
162 // Track it as a valid token.
163 tokens.push_back(*a);
165 // Save off the first valid SSO statement.
166 if (!ssoStatement && !(*a)->getAuthenticationStatements().empty())
167 ssoStatement = (*a)->getAuthenticationStatements().front();
169 catch (exception& ex) {
170 m_log.warn("detected a problem with assertion: %s", ex.what());
171 badtokens.push_back(*a);
176 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
179 SubjectLocality* locality = ssoStatement->getSubjectLocality();
180 if (locality && locality->getIPAddress()) {
181 auto_ptr_char ip(locality->getIPAddress());
182 checkAddress(application, httpRequest, ip.get());
185 m_log.debug("SSO profile processing completed successfully");
187 NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
189 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
190 // To complete processing, we need to extract and resolve attributes and then create the session.
191 multimap<string,Attribute*> resolvedAttributes;
192 AttributeExtractor* extractor = application.getAttributeExtractor();
194 m_log.debug("extracting pushed attributes...");
195 Locker extlocker(extractor);
198 extractor->extractAttributes(application, policy.getIssuerMetadata(), *n, resolvedAttributes);
200 catch (exception& ex) {
201 m_log.error("caught exception extracting attributes: %s", ex.what());
204 for (vector<const opensaml::Assertion*>::const_iterator t = tokens.begin(); t!=tokens.end(); ++t) {
206 extractor->extractAttributes(application, policy.getIssuerMetadata(), *(*t), resolvedAttributes);
208 catch (exception& ex) {
209 m_log.error("caught exception extracting attributes: %s", ex.what());
214 // First, normalize the SAML 1.x NameIdentifier...
215 auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : NULL);
217 nameid->setName(n->getName());
218 nameid->setFormat(n->getFormat());
219 nameid->setNameQualifier(n->getNameQualifier());
222 const EntityDescriptor* issuerMetadata =
223 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
224 auto_ptr<ResolutionContext> ctx(
225 resolveAttributes(application, issuerMetadata, nameid.get(), &tokens, &resolvedAttributes)
229 // Copy over any new tokens, but leave them in the context for cleanup.
230 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
232 // Copy over new attributes, and transfer ownership.
233 resolvedAttributes.insert(ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
234 ctx->getResolvedAttributes().clear();
237 // Now merge in bad tokens for caching.
238 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
240 // Now we have to extract the authentication details for session setup.
242 // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
243 const PropertySet* sessionProps = application.getPropertySet("Sessions");
244 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : make_pair(true,28800);
246 lifetime.second = 28800;
247 auto_ptr_char authnInstant(
248 ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL
250 auto_ptr_char authnMethod(ssoStatement->getAuthenticationMethod());
253 string key = application.getServiceProvider().getSessionCache()->insert(
254 lifetime.second ? now + lifetime.second : 0,
256 httpRequest.getRemoteAddr().c_str(),
266 resolvedAttributes.clear(); // Attributes are owned by cache now.
270 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());