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/resolver/ResolutionContext.h"
32 # include <saml/saml1/core/Assertions.h>
33 # include <saml/saml1/core/Protocols.h>
34 # include <saml/saml1/profile/BrowserSSOProfileValidator.h>
35 # include <saml/saml2/metadata/Metadata.h>
36 using namespace opensaml::saml1;
37 using namespace opensaml::saml1p;
38 using namespace opensaml;
40 using saml2::NameIDBuilder;
41 using saml2md::EntityDescriptor;
42 using saml2md::MetadataException;
44 # include "lite/SAMLConstants.h"
47 using namespace shibsp;
48 using namespace xmltooling;
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".SSO.SAML1")) {
64 m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
67 virtual ~SAML1Consumer() {}
71 string implementProtocol(
72 const Application& application,
73 const HTTPRequest& httpRequest,
74 SecurityPolicy& policy,
75 const PropertySet* settings,
76 const XMLObject& xmlObject
82 #if defined (_MSC_VER)
83 #pragma warning( pop )
86 Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
88 return new SAML1Consumer(p.first, p.second);
95 string SAML1Consumer::implementProtocol(
96 const Application& application,
97 const HTTPRequest& httpRequest,
98 SecurityPolicy& policy,
99 const PropertySet* settings,
100 const XMLObject& xmlObject
103 // Implementation of SAML 1.x SSO profile(s).
104 m_log.debug("processing message against SAML 1.x SSO profile");
106 // Check for errors...this will throw if it's not a successful message.
107 checkError(&xmlObject);
109 // With the binding aspects now moved out to the MessageDecoder,
110 // the focus here is on the assertion content. For SAML 1.x POST,
111 // all the security comes from the protocol layer, and signing
112 // the assertion isn't sufficient. So we can check the policy
113 // object now and bail if it's not a secured message.
114 if (m_post && !policy.isAuthenticated()) {
115 if (policy.getIssuer() && !policy.getIssuerMetadata())
116 throw MetadataException("Security of SAML 1.x SSO POST response not established.");
117 throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
120 // Remember whether we already established trust.
121 bool alreadySecured = policy.isAuthenticated();
123 const Response* response = dynamic_cast<const Response*>(&xmlObject);
125 throw FatalProfileException("Incoming message was not a samlp:Response.");
127 const vector<saml1::Assertion*>& assertions = response->getAssertions();
128 if (assertions.empty())
129 throw FatalProfileException("Incoming message contained no SAML assertions.");
131 pair<bool,int> minor = response->getMinorVersion();
133 // Maintain list of "legit" tokens to feed to SP subsystems.
134 const AuthenticationStatement* ssoStatement=NULL;
135 vector<const opensaml::Assertion*> tokens;
137 // Also track "bad" tokens that we'll cache but not use.
138 // This is necessary because there may be valid tokens not aimed at us.
139 vector<const opensaml::Assertion*> badtokens;
141 // Profile validator.
142 time_t now = time(NULL);
143 BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now);
145 // With this flag on, we ignore any unsigned assertions.
146 pair<bool,bool> flag = settings->getBool("signedAssertions");
148 for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
149 // Skip unsigned assertion?
150 if (!(*a)->getSignature() && flag.first && flag.second) {
151 m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
152 badtokens.push_back(*a);
157 // We clear the security flag, so we can tell whether the token was secured on its own.
158 policy.setAuthenticated(false);
161 // Extract message bits and re-verify Issuer information.
162 extractMessageDetails(
163 *(*a), (minor.first && minor.second==0) ? samlconstants::SAML10_PROTOCOL_ENUM : samlconstants::SAML11_PROTOCOL_ENUM, policy
166 // Run the policy over the assertion. Handles replay, freshness, and
167 // signature verification, assuming the relevant rules are configured.
168 policy.evaluate(*(*a));
170 // If no security is in place now, we kick it.
171 if (!alreadySecured && !policy.isAuthenticated()) {
172 m_log.warn("unable to establish security of assertion");
173 badtokens.push_back(*a);
177 // Now do profile and core semantic validation to ensure we can use it for SSO.
178 ssoValidator.validateAssertion(*(*a));
180 // Track it as a valid token.
181 tokens.push_back(*a);
183 // Save off the first valid SSO statement.
184 if (!ssoStatement && !(*a)->getAuthenticationStatements().empty())
185 ssoStatement = (*a)->getAuthenticationStatements().front();
187 catch (exception& ex) {
188 m_log.warn("detected a problem with assertion: %s", ex.what());
189 badtokens.push_back(*a);
194 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
197 SubjectLocality* locality = ssoStatement->getSubjectLocality();
198 if (locality && locality->getIPAddress()) {
199 auto_ptr_char ip(locality->getIPAddress());
200 checkAddress(application, httpRequest, ip.get());
203 m_log.debug("SSO profile processing completed successfully");
205 NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
207 // Now we have to extract the authentication details for attribute and session setup.
209 // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
210 const PropertySet* sessionProps = application.getPropertySet("Sessions");
211 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
212 if (!lifetime.first || lifetime.second == 0)
213 lifetime.second = 28800;
215 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
216 // To complete processing, we need to extract and resolve attributes and then create the session.
218 // Normalize the SAML 1.x NameIdentifier...
219 auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : NULL);
221 nameid->setName(n->getName());
222 nameid->setFormat(n->getFormat());
223 nameid->setNameQualifier(n->getNameQualifier());
226 // The context will handle deleting attributes and new tokens.
227 auto_ptr<ResolutionContext> ctx(
230 policy.getIssuerMetadata(),
231 (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
232 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
235 ssoStatement->getAuthenticationMethod(),
242 // Copy over any new tokens, but leave them in the context for cleanup.
243 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
246 // Now merge in bad tokens for caching.
247 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
249 return application.getServiceProvider().getSessionCache()->insert(
250 now + lifetime.second,
252 httpRequest.getRemoteAddr().c_str(),
253 policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
254 (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
255 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
257 ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
259 ssoStatement->getAuthenticationMethod(),
262 ctx.get() ? &ctx->getResolvedAttributes() : NULL