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 "attribute/resolver/ResolutionContext.h"
35 # include <saml/exceptions.h>
36 # include <saml/SAMLConfig.h>
37 # include <saml/binding/SecurityPolicy.h>
38 # include <saml/binding/SecurityPolicyRule.h>
39 # include <saml/saml1/core/Assertions.h>
40 # include <saml/saml1/core/Protocols.h>
41 # include <saml/saml2/metadata/Metadata.h>
42 # include <xmltooling/XMLToolingConfig.h>
43 # include <xmltooling/io/HTTPRequest.h>
44 # include <xmltooling/util/DateTime.h>
45 using namespace opensaml::saml1;
46 using namespace opensaml::saml1p;
47 using namespace opensaml;
49 using saml2::NameIDBuilder;
50 using saml2md::EntityDescriptor;
51 using saml2md::SPSSODescriptor;
52 using saml2md::MetadataException;
54 # include "lite/SAMLConstants.h"
57 using namespace shibsp;
58 using namespace xmltooling;
63 #if defined (_MSC_VER)
64 #pragma warning( push )
65 #pragma warning( disable : 4250 )
68 class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
71 SAML1Consumer(const DOMElement* e, const char* appId)
72 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
75 m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
76 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
77 m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(SAML1BROWSERSSO_POLICY_RULE, e);
80 virtual ~SAML1Consumer() {
87 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
88 AssertionConsumerService::generateMetadata(role, handlerURL);
89 role.addSupport(samlconstants::SAML11_PROTOCOL_ENUM);
90 role.addSupport(samlconstants::SAML10_PROTOCOL_ENUM);
94 void implementProtocol(
95 const Application& application,
96 const HTTPRequest& httpRequest,
97 HTTPResponse& httpResponse,
98 SecurityPolicy& policy,
100 const XMLObject& xmlObject
104 SecurityPolicyRule* m_ssoRule;
106 const XMLCh* getProtocolFamily() const {
107 return samlconstants::SAML11_PROTOCOL_ENUM;
112 #if defined (_MSC_VER)
113 #pragma warning( pop )
116 Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
118 return new SAML1Consumer(p.first, p.second);
122 class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
125 _rulenamed(const char* name) : m_name(name) {}
126 bool operator()(const SecurityPolicyRule* rule) const {
127 return rule ? !strcmp(m_name, rule->getType()) : false;
137 void SAML1Consumer::implementProtocol(
138 const Application& application,
139 const HTTPRequest& httpRequest,
140 HTTPResponse& httpResponse,
141 SecurityPolicy& policy,
143 const XMLObject& xmlObject
146 // Implementation of SAML 1.x SSO profile(s).
147 m_log.debug("processing message against SAML 1.x SSO profile");
149 // Check for errors...this will throw if it's not a successful message.
150 checkError(&xmlObject);
152 // With the binding aspects now moved out to the MessageDecoder,
153 // the focus here is on the assertion content. For SAML 1.x POST,
154 // all the security comes from the protocol layer, and signing
155 // the assertion isn't sufficient. So we can check the policy
156 // object now and bail if it's not a secured message.
157 if (m_post && !policy.isAuthenticated()) {
158 if (policy.getIssuer() && !policy.getIssuerMetadata())
159 throw MetadataException("Security of SAML 1.x SSO POST response not established.");
160 throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
163 // Remember whether we already established trust.
164 bool alreadySecured = policy.isAuthenticated();
166 const Response* response = dynamic_cast<const Response*>(&xmlObject);
168 throw FatalProfileException("Incoming message was not a samlp:Response.");
170 const vector<saml1::Assertion*>& assertions = response->getAssertions();
171 if (assertions.empty())
172 throw FatalProfileException("Incoming message contained no SAML assertions.");
174 pair<bool,int> minor = response->getMinorVersion();
176 // Maintain list of "legit" tokens to feed to SP subsystems.
177 const AuthenticationStatement* ssoStatement=nullptr;
178 vector<const opensaml::Assertion*> tokens;
180 // Also track "bad" tokens that we'll cache but not use.
181 // This is necessary because there may be valid tokens not aimed at us.
182 vector<const opensaml::Assertion*> badtokens;
184 // With this flag on, we ignore any unsigned assertions.
185 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
186 pair<bool,bool> flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
188 // authnskew allows rejection of SSO if AuthnInstant is too old.
189 const PropertySet* sessionProps = application.getPropertySet("Sessions");
190 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
192 // Saves off error messages potentially helpful for users.
193 string contextualError;
195 // Ensure the BrowserSSO rule is in the policy set.
196 if (find_if(policy.getRules(), _rulenamed(SAML1BROWSERSSO_POLICY_RULE)) == nullptr)
197 policy.getRules().push_back(m_ssoRule);
199 // Populate recipient as audience.
200 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
202 time_t now = time(nullptr);
203 for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=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(
216 (minor.first && minor.second==0) ? samlconstants::SAML10_PROTOCOL_ENUM : samlconstants::SAML11_PROTOCOL_ENUM, policy
219 // Run the policy over the assertion. Handles replay, freshness, and
220 // signature verification, assuming the relevant rules are configured,
221 // along with condition and profile enforcement.
222 policy.evaluate(*(*a), &httpRequest);
224 // If no security is in place now, we kick it.
225 if (!alreadySecured && !policy.isAuthenticated())
226 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
228 // Track it as a valid token.
229 tokens.push_back(*a);
231 // Save off the first valid SSO statement.
232 const vector<AuthenticationStatement*>& statements =
233 const_cast<const saml1::Assertion*>(*a)->getAuthenticationStatements();
234 for (vector<AuthenticationStatement*>::const_iterator s = statements.begin(); s!=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) {
252 catch (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 auto_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 auto_ptr<ResolutionContext> ctx(
299 policy.getIssuerMetadata(),
300 (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
301 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
306 ssoStatement->getAuthenticationMethod(),
313 // Copy over any new tokens, but leave them in the context for cleanup.
314 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
317 // Now merge in bad tokens for caching.
318 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
320 application.getServiceProvider().getSessionCache()->insert(
324 now + lifetime.second,
326 (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
327 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
329 ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : nullptr,
331 ssoStatement->getAuthenticationMethod(),
334 ctx.get() ? &ctx->getResolvedAttributes() : nullptr