2 * Copyright 2001-2010 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 "Application.h"
28 # include "ServiceProvider.h"
29 # include "SessionCache.h"
30 # include "attribute/resolver/ResolutionContext.h"
31 # include <saml/exceptions.h>
32 # include <saml/SAMLConfig.h>
33 # include <saml/binding/SecurityPolicy.h>
34 # include <saml/binding/SecurityPolicyRule.h>
35 # include <saml/saml1/core/Assertions.h>
36 # include <saml/saml1/core/Protocols.h>
37 # include <saml/saml2/metadata/Metadata.h>
38 # include <xmltooling/io/HTTPRequest.h>
39 # include <xmltooling/util/DateTime.h>
40 using namespace opensaml::saml1;
41 using namespace opensaml::saml1p;
42 using namespace opensaml;
44 using saml2::NameIDBuilder;
45 using saml2md::EntityDescriptor;
46 using saml2md::SPSSODescriptor;
47 using saml2md::MetadataException;
49 # include "lite/SAMLConstants.h"
52 using namespace shibsp;
53 using namespace xmltooling;
58 #if defined (_MSC_VER)
59 #pragma warning( push )
60 #pragma warning( disable : 4250 )
63 class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
66 SAML1Consumer(const DOMElement* e, const char* appId)
67 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
70 m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
71 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
72 m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(SAML1BROWSERSSO_POLICY_RULE, e);
75 virtual ~SAML1Consumer() {
82 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
83 AssertionConsumerService::generateMetadata(role, handlerURL);
84 role.addSupport(samlconstants::SAML11_PROTOCOL_ENUM);
85 role.addSupport(samlconstants::SAML10_PROTOCOL_ENUM);
89 void implementProtocol(
90 const Application& application,
91 const HTTPRequest& httpRequest,
92 HTTPResponse& httpResponse,
93 SecurityPolicy& policy,
95 const XMLObject& xmlObject
99 SecurityPolicyRule* m_ssoRule;
103 #if defined (_MSC_VER)
104 #pragma warning( pop )
107 Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
109 return new SAML1Consumer(p.first, p.second);
113 class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
116 _rulenamed(const char* name) : m_name(name) {}
117 bool operator()(const SecurityPolicyRule* rule) const {
118 return rule ? !strcmp(m_name, rule->getType()) : false;
128 void SAML1Consumer::implementProtocol(
129 const Application& application,
130 const HTTPRequest& httpRequest,
131 HTTPResponse& httpResponse,
132 SecurityPolicy& policy,
134 const XMLObject& xmlObject
137 // Implementation of SAML 1.x SSO profile(s).
138 m_log.debug("processing message against SAML 1.x SSO profile");
140 // Check for errors...this will throw if it's not a successful message.
141 checkError(&xmlObject);
143 // With the binding aspects now moved out to the MessageDecoder,
144 // the focus here is on the assertion content. For SAML 1.x POST,
145 // all the security comes from the protocol layer, and signing
146 // the assertion isn't sufficient. So we can check the policy
147 // object now and bail if it's not a secured message.
148 if (m_post && !policy.isAuthenticated()) {
149 if (policy.getIssuer() && !policy.getIssuerMetadata())
150 throw MetadataException("Security of SAML 1.x SSO POST response not established.");
151 throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
154 // Remember whether we already established trust.
155 bool alreadySecured = policy.isAuthenticated();
157 const Response* response = dynamic_cast<const Response*>(&xmlObject);
159 throw FatalProfileException("Incoming message was not a samlp:Response.");
161 const vector<saml1::Assertion*>& assertions = response->getAssertions();
162 if (assertions.empty())
163 throw FatalProfileException("Incoming message contained no SAML assertions.");
165 pair<bool,int> minor = response->getMinorVersion();
167 // Maintain list of "legit" tokens to feed to SP subsystems.
168 const AuthenticationStatement* ssoStatement=nullptr;
169 vector<const opensaml::Assertion*> tokens;
171 // Also track "bad" tokens that we'll cache but not use.
172 // This is necessary because there may be valid tokens not aimed at us.
173 vector<const opensaml::Assertion*> badtokens;
175 // With this flag on, we ignore any unsigned assertions.
176 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
177 pair<bool,bool> flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
179 // authnskew allows rejection of SSO if AuthnInstant is too old.
180 const PropertySet* sessionProps = application.getPropertySet("Sessions");
181 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
183 // Saves off error messages potentially helpful for users.
184 string contextualError;
186 // Ensure the BrowserSSO rule is in the policy set.
187 if (find_if(policy.getRules(), _rulenamed(SAML1BROWSERSSO_POLICY_RULE)) == nullptr)
188 policy.getRules().push_back(m_ssoRule);
190 // Populate recipient as audience.
191 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
193 time_t now = time(nullptr);
194 for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
196 // Skip unsigned assertion?
197 if (!(*a)->getSignature() && flag.first && flag.second)
198 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
200 // We clear the security flag, so we can tell whether the token was secured on its own.
201 policy.setAuthenticated(false);
204 // Extract message bits and re-verify Issuer information.
205 extractMessageDetails(
206 *(*a), (minor.first && minor.second==0) ? samlconstants::SAML10_PROTOCOL_ENUM : samlconstants::SAML11_PROTOCOL_ENUM, policy
209 // Run the policy over the assertion. Handles replay, freshness, and
210 // signature verification, assuming the relevant rules are configured,
211 // along with condition and profile enforcement.
212 policy.evaluate(*(*a), &httpRequest);
214 // If no security is in place now, we kick it.
215 if (!alreadySecured && !policy.isAuthenticated())
216 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
218 // Track it as a valid token.
219 tokens.push_back(*a);
221 // Save off the first valid SSO statement.
222 const vector<AuthenticationStatement*>& statements = const_cast<const saml1::Assertion*>(*a)->getAuthenticationStatements();
223 for (vector<AuthenticationStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
224 if (authnskew.first && authnskew.second &&
225 (*s)->getAuthenticationInstant() && (now - (*s)->getAuthenticationInstantEpoch() > authnskew.second))
226 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
227 else if (!ssoStatement) {
233 catch (exception& ex) {
234 m_log.warn("detected a problem with assertion: %s", ex.what());
236 contextualError = ex.what();
237 badtokens.push_back(*a);
242 if (contextualError.empty())
243 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
244 throw FatalProfileException(contextualError.c_str());
248 SubjectLocality* locality = ssoStatement->getSubjectLocality();
249 if (locality && locality->getIPAddress()) {
250 auto_ptr_char ip(locality->getIPAddress());
251 checkAddress(application, httpRequest, ip.get());
254 m_log.debug("SSO profile processing completed successfully");
256 NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
258 // Now we have to extract the authentication details for attribute and session setup.
260 // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
261 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
262 if (!lifetime.first || lifetime.second == 0)
263 lifetime.second = 28800;
265 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
266 // To complete processing, we need to extract and resolve attributes and then create the session.
268 // Normalize the SAML 1.x NameIdentifier...
269 auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : nullptr);
271 nameid->setName(n->getName());
272 nameid->setFormat(n->getFormat());
273 nameid->setNameQualifier(n->getNameQualifier());
276 // The context will handle deleting attributes and new tokens.
277 auto_ptr<ResolutionContext> ctx(
280 policy.getIssuerMetadata(),
281 (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
282 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
285 ssoStatement->getAuthenticationMethod(),
292 // Copy over any new tokens, but leave them in the context for cleanup.
293 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
296 // Now merge in bad tokens for caching.
297 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
299 application.getServiceProvider().getSessionCache()->insert(
303 now + lifetime.second,
305 (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
306 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
308 ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : nullptr,
310 ssoStatement->getAuthenticationMethod(),
313 ctx.get() ? &ctx->getResolvedAttributes() : nullptr