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 <saml/exceptions.h>
37 # include <saml/SAMLConfig.h>
38 # include <saml/binding/SecurityPolicy.h>
39 # include <saml/binding/SecurityPolicyRule.h>
40 # include <saml/saml1/core/Assertions.h>
41 # include <saml/saml1/core/Protocols.h>
42 # include <saml/saml2/metadata/Metadata.h>
43 # include <xmltooling/XMLToolingConfig.h>
44 # include <xmltooling/io/HTTPRequest.h>
45 # include <xmltooling/util/DateTime.h>
46 using namespace opensaml::saml1;
47 using namespace opensaml::saml1p;
48 using namespace opensaml;
50 using saml2::NameIDBuilder;
51 using saml2md::EntityDescriptor;
52 using saml2md::SPSSODescriptor;
53 using saml2md::MetadataException;
55 # include "lite/SAMLConstants.h"
58 using namespace shibsp;
59 using namespace xmltooling;
64 #if defined (_MSC_VER)
65 #pragma warning( push )
66 #pragma warning( disable : 4250 )
69 class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
72 SAML1Consumer(const DOMElement* e, const char* appId)
73 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
76 m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
77 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
78 m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(SAML1BROWSERSSO_POLICY_RULE, e);
81 virtual ~SAML1Consumer() {
88 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
89 AssertionConsumerService::generateMetadata(role, handlerURL);
90 role.addSupport(samlconstants::SAML11_PROTOCOL_ENUM);
91 role.addSupport(samlconstants::SAML10_PROTOCOL_ENUM);
95 void implementProtocol(
96 const Application& application,
97 const HTTPRequest& httpRequest,
98 HTTPResponse& httpResponse,
99 SecurityPolicy& policy,
101 const XMLObject& xmlObject
105 SecurityPolicyRule* m_ssoRule;
107 const XMLCh* getProtocolFamily() const {
108 return samlconstants::SAML11_PROTOCOL_ENUM;
113 #if defined (_MSC_VER)
114 #pragma warning( pop )
117 Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
119 return new SAML1Consumer(p.first, p.second);
123 class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
126 _rulenamed(const char* name) : m_name(name) {}
127 bool operator()(const SecurityPolicyRule* rule) const {
128 return rule ? !strcmp(m_name, rule->getType()) : false;
138 void SAML1Consumer::implementProtocol(
139 const Application& application,
140 const HTTPRequest& httpRequest,
141 HTTPResponse& httpResponse,
142 SecurityPolicy& policy,
144 const XMLObject& xmlObject
147 // Implementation of SAML 1.x SSO profile(s).
148 m_log.debug("processing message against SAML 1.x SSO profile");
150 // Check for errors...this will throw if it's not a successful message.
151 checkError(&xmlObject);
153 // With the binding aspects now moved out to the MessageDecoder,
154 // the focus here is on the assertion content. For SAML 1.x POST,
155 // all the security comes from the protocol layer, and signing
156 // the assertion isn't sufficient. So we can check the policy
157 // object now and bail if it's not a secured message.
158 if (m_post && !policy.isAuthenticated()) {
159 if (policy.getIssuer() && !policy.getIssuerMetadata())
160 throw MetadataException("Security of SAML 1.x SSO POST response not established.");
161 throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
164 // Remember whether we already established trust.
165 bool alreadySecured = policy.isAuthenticated();
167 const Response* response = dynamic_cast<const Response*>(&xmlObject);
169 throw FatalProfileException("Incoming message was not a samlp:Response.");
171 const vector<saml1::Assertion*>& assertions = response->getAssertions();
172 if (assertions.empty())
173 throw FatalProfileException("Incoming message contained no SAML assertions.");
175 pair<bool,int> minor = response->getMinorVersion();
177 // Maintain list of "legit" tokens to feed to SP subsystems.
178 const AuthenticationStatement* ssoStatement=nullptr;
179 vector<const opensaml::Assertion*> tokens;
181 // Also track "bad" tokens that we'll cache but not use.
182 // This is necessary because there may be valid tokens not aimed at us.
183 vector<const opensaml::Assertion*> badtokens;
185 // With this flag on, we ignore any unsigned assertions.
186 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
187 pair<bool,bool> flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
189 // authnskew allows rejection of SSO if AuthnInstant is too old.
190 const PropertySet* sessionProps = application.getPropertySet("Sessions");
191 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
193 // Saves off error messages potentially helpful for users.
194 string contextualError;
196 // Ensure the BrowserSSO rule is in the policy set.
197 if (find_if(policy.getRules(), _rulenamed(SAML1BROWSERSSO_POLICY_RULE)) == nullptr)
198 policy.getRules().push_back(m_ssoRule);
200 // Populate recipient as audience.
201 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
203 time_t now = time(nullptr);
204 for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
206 // Skip unsigned assertion?
207 if (!(*a)->getSignature() && flag.first && flag.second)
208 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
210 // We clear the security flag, so we can tell whether the token was secured on its own.
211 policy.setAuthenticated(false);
214 // Extract message bits and re-verify Issuer information.
215 extractMessageDetails(
217 (minor.first && minor.second==0) ? samlconstants::SAML10_PROTOCOL_ENUM : samlconstants::SAML11_PROTOCOL_ENUM, policy
220 // Run the policy over the assertion. Handles replay, freshness, and
221 // signature verification, assuming the relevant rules are configured,
222 // along with condition and profile enforcement.
223 policy.evaluate(*(*a), &httpRequest);
225 // If no security is in place now, we kick it.
226 if (!alreadySecured && !policy.isAuthenticated())
227 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
229 // Track it as a valid token.
230 tokens.push_back(*a);
232 // Save off the first valid SSO statement.
233 const vector<AuthenticationStatement*>& statements =
234 const_cast<const saml1::Assertion*>(*a)->getAuthenticationStatements();
235 for (vector<AuthenticationStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
236 if ((*s)->getAuthenticationInstant() &&
237 (*s)->getAuthenticationInstantEpoch() - XMLToolingConfig::getConfig().clock_skew_secs > now) {
238 contextualError = "The login time at your identity provider was future-dated.";
240 else if (authnskew.first && authnskew.second && (*s)->getAuthenticationInstant() &&
241 (*s)->getAuthenticationInstantEpoch() <= now && (now - (*s)->getAuthenticationInstantEpoch() > authnskew.second)) {
242 contextualError = "The gap between now and the time you logged into your identity provider exceeds the allowed limit.";
244 else if (authnskew.first && authnskew.second && (*s)->getAuthenticationInstant() == nullptr) {
245 contextualError = "Your identity provider did not supply a time of login, violating local policy.";
247 else if (!ssoStatement) {
253 catch (exception& ex) {
254 m_log.warn("detected a problem with assertion: %s", ex.what());
256 contextualError = ex.what();
257 badtokens.push_back(*a);
262 if (contextualError.empty())
263 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
264 throw FatalProfileException(contextualError.c_str());
268 SubjectLocality* locality = ssoStatement->getSubjectLocality();
269 if (locality && locality->getIPAddress()) {
270 auto_ptr_char ip(locality->getIPAddress());
271 checkAddress(application, httpRequest, ip.get());
274 m_log.debug("SSO profile processing completed successfully");
276 NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
278 // Now we have to extract the authentication details for attribute and session setup.
280 // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
281 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
282 if (!lifetime.first || lifetime.second == 0)
283 lifetime.second = 28800;
285 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
286 // To complete processing, we need to extract and resolve attributes and then create the session.
288 // Normalize the SAML 1.x NameIdentifier...
289 auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : nullptr);
291 nameid->setName(n->getName());
292 nameid->setFormat(n->getFormat());
293 nameid->setNameQualifier(n->getNameQualifier());
296 // The context will handle deleting attributes and new tokens.
297 auto_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.get() ? &ctx->getResolvedAttributes() : nullptr
340 auto_ptr<LoginEvent> login_event(newLoginEvent(application, httpRequest));
341 if (login_event.get()) {
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);