2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
24 * SAML 1.x assertion consumer service.
28 #include "handler/AssertionConsumerService.h"
31 # include "Application.h"
32 # include "ServiceProvider.h"
33 # include "SessionCache.h"
34 # include "TransactionLog.h"
35 # include "attribute/resolver/ResolutionContext.h"
36 # include <boost/scoped_ptr.hpp>
37 # include <boost/iterator/indirect_iterator.hpp>
38 # include <saml/exceptions.h>
39 # include <saml/SAMLConfig.h>
40 # include <saml/binding/SecurityPolicy.h>
41 # include <saml/binding/SecurityPolicyRule.h>
42 # include <saml/saml1/core/Assertions.h>
43 # include <saml/saml1/core/Protocols.h>
44 # include <saml/saml2/metadata/Metadata.h>
45 # include <xmltooling/XMLToolingConfig.h>
46 # include <xmltooling/io/HTTPRequest.h>
47 # include <xmltooling/util/DateTime.h>
48 using namespace opensaml::saml1;
49 using namespace opensaml::saml1p;
50 using namespace opensaml;
51 using namespace boost;
53 using saml2::NameIDBuilder;
54 using saml2md::EntityDescriptor;
55 using saml2md::SPSSODescriptor;
56 using saml2md::MetadataException;
58 # include "lite/SAMLConstants.h"
61 using namespace shibsp;
62 using namespace xmltooling;
67 #if defined (_MSC_VER)
68 #pragma warning( push )
69 #pragma warning( disable : 4250 )
72 class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
75 SAML1Consumer(const DOMElement* e, const char* appId)
76 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
78 m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
79 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
80 m_ssoRule.reset(SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(SAML1BROWSERSSO_POLICY_RULE, e));
83 virtual ~SAML1Consumer() {}
86 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
87 AssertionConsumerService::generateMetadata(role, handlerURL);
88 role.addSupport(samlconstants::SAML11_PROTOCOL_ENUM);
89 role.addSupport(samlconstants::SAML10_PROTOCOL_ENUM);
93 void implementProtocol(
94 const Application& application,
95 const HTTPRequest& httpRequest,
96 HTTPResponse& httpResponse,
97 SecurityPolicy& policy,
99 const XMLObject& xmlObject
103 scoped_ptr<SecurityPolicyRule> m_ssoRule;
105 const XMLCh* getProtocolFamily() const {
106 return samlconstants::SAML11_PROTOCOL_ENUM;
111 #if defined (_MSC_VER)
112 #pragma warning( pop )
115 Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
117 return new SAML1Consumer(p.first, p.second);
121 class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
124 _rulenamed(const char* name) : m_name(name) {}
125 bool operator()(const SecurityPolicyRule* rule) const {
126 return rule ? !strcmp(m_name, rule->getType()) : false;
136 void SAML1Consumer::implementProtocol(
137 const Application& application,
138 const HTTPRequest& httpRequest,
139 HTTPResponse& httpResponse,
140 SecurityPolicy& policy,
142 const XMLObject& xmlObject
145 // Implementation of SAML 1.x SSO profile(s).
146 m_log.debug("processing message against SAML 1.x SSO profile");
148 // Check for errors...this will throw if it's not a successful message.
149 checkError(&xmlObject);
151 // With the binding aspects now moved out to the MessageDecoder,
152 // the focus here is on the assertion content. For SAML 1.x POST,
153 // all the security comes from the protocol layer, and signing
154 // the assertion isn't sufficient. So we can check the policy
155 // object now and bail if it's not a secured message.
156 if (m_post && !policy.isAuthenticated()) {
157 if (policy.getIssuer() && !policy.getIssuerMetadata())
158 throw MetadataException("Security of SAML 1.x SSO POST response not established.");
159 throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
162 // Remember whether we already established trust.
163 bool alreadySecured = policy.isAuthenticated();
165 const Response* response = dynamic_cast<const Response*>(&xmlObject);
167 throw FatalProfileException("Incoming message was not a samlp:Response.");
169 const vector<saml1::Assertion*>& assertions = response->getAssertions();
170 if (assertions.empty())
171 throw FatalProfileException("Incoming message contained no SAML assertions.");
173 pair<bool,int> minor = response->getMinorVersion();
175 // Maintain list of "legit" tokens to feed to SP subsystems.
176 const AuthenticationStatement* ssoStatement=nullptr;
177 vector<const opensaml::Assertion*> tokens;
179 // Also track "bad" tokens that we'll cache but not use.
180 // This is necessary because there may be valid tokens not aimed at us.
181 vector<const opensaml::Assertion*> badtokens;
183 // With this flag on, we ignore any unsigned assertions.
184 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
185 pair<bool,bool> flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
187 // authnskew allows rejection of SSO if AuthnInstant is too old.
188 const PropertySet* sessionProps = application.getPropertySet("Sessions");
189 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
191 // Saves off error messages potentially helpful for users.
192 string contextualError;
194 // Ensure the BrowserSSO rule is in the policy set.
195 if (find_if(policy.getRules(), _rulenamed(SAML1BROWSERSSO_POLICY_RULE)) == nullptr)
196 policy.getRules().push_back(m_ssoRule.get());
198 // Populate recipient as audience.
199 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
201 time_t now = time(nullptr);
202 for (indirect_iterator<vector<saml1::Assertion*>::const_iterator> a = make_indirect_iterator(assertions.begin());
203 a != make_indirect_iterator(assertions.end()); ++a) {
205 // Skip unsigned assertion?
206 if (!a->getSignature() && flag.first && flag.second)
207 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
209 // We clear the security flag, so we can tell whether the token was secured on its own.
210 policy.setAuthenticated(false);
213 // Extract message bits and re-verify Issuer information.
214 extractMessageDetails(
215 *a, (minor.first && minor.second==0) ? samlconstants::SAML10_PROTOCOL_ENUM : samlconstants::SAML11_PROTOCOL_ENUM, policy
218 // Run the policy over the assertion. Handles replay, freshness, and
219 // signature verification, assuming the relevant rules are configured,
220 // along with condition and profile enforcement.
221 policy.evaluate(*a, &httpRequest);
223 // If no security is in place now, we kick it.
224 if (!alreadySecured && !policy.isAuthenticated())
225 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
227 // Track it as a valid token.
228 tokens.push_back(&(*a));
230 // Save off the first valid SSO statement.
231 const vector<AuthenticationStatement*>& statements =
232 const_cast<const saml1::Assertion&>(*a).getAuthenticationStatements();
233 for (indirect_iterator<vector<AuthenticationStatement*>::const_iterator> s = make_indirect_iterator(statements.begin());
234 s != make_indirect_iterator(statements.end()); ++s) {
235 if (s->getAuthenticationInstant() &&
236 s->getAuthenticationInstantEpoch() - XMLToolingConfig::getConfig().clock_skew_secs > now) {
237 contextualError = "The login time at your identity provider was future-dated.";
239 else if (authnskew.first && authnskew.second && s->getAuthenticationInstant() &&
240 s->getAuthenticationInstantEpoch() <= now && (now - s->getAuthenticationInstantEpoch() > authnskew.second)) {
241 contextualError = "The gap between now and the time you logged into your identity provider exceeds the allowed limit.";
243 else if (authnskew.first && authnskew.second && s->getAuthenticationInstant() == nullptr) {
244 contextualError = "Your identity provider did not supply a time of login, violating local policy.";
246 else if (!ssoStatement) {
247 ssoStatement = &(*s);
252 catch (std::exception& ex) {
253 m_log.warn("detected a problem with assertion: %s", ex.what());
255 contextualError = ex.what();
256 badtokens.push_back(&(*a));
261 if (contextualError.empty())
262 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
263 throw FatalProfileException(contextualError.c_str());
267 SubjectLocality* locality = ssoStatement->getSubjectLocality();
268 if (locality && locality->getIPAddress()) {
269 auto_ptr_char ip(locality->getIPAddress());
270 checkAddress(application, httpRequest, ip.get());
273 m_log.debug("SSO profile processing completed successfully");
275 NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
277 // Now we have to extract the authentication details for attribute and session setup.
279 // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
280 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
281 if (!lifetime.first || lifetime.second == 0)
282 lifetime.second = 28800;
284 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
285 // To complete processing, we need to extract and resolve attributes and then create the session.
287 // Normalize the SAML 1.x NameIdentifier...
288 scoped_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : nullptr);
290 nameid->setName(n->getName());
291 nameid->setFormat(n->getFormat());
292 nameid->setNameQualifier(n->getNameQualifier());
295 // The context will handle deleting attributes and new tokens.
296 scoped_ptr<ResolutionContext> ctx(
300 policy.getIssuerMetadata(),
301 (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
302 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
307 ssoStatement->getAuthenticationMethod(),
314 // Copy over any new tokens, but leave them in the context for cleanup.
315 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
318 // Now merge in bad tokens for caching.
319 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
322 application.getServiceProvider().getSessionCache()->insert(
327 now + lifetime.second,
329 (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
330 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
332 ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : nullptr,
334 ssoStatement->getAuthenticationMethod(),
337 ctx ? &ctx->getResolvedAttributes() : nullptr
340 scoped_ptr<LoginEvent> login_event(newLoginEvent(application, httpRequest));
342 login_event->m_sessionID = session_id.c_str();
343 login_event->m_peer = entity;
345 (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
346 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM
348 login_event->m_protocol = prot.get();
349 login_event->m_nameID = nameid.get();
350 login_event->m_saml1AuthnStatement = ssoStatement;
351 login_event->m_saml1Response = response;
353 login_event->m_attributes = &ctx->getResolvedAttributes();
354 application.getServiceProvider().getTransactionLog()->write(*login_event);