2 * Copyright 2001-2009 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/SAMLConfig.h>
33 # include <saml/binding/SecurityPolicy.h>
34 # include <saml/saml1/core/Assertions.h>
35 # include <saml/saml1/core/Protocols.h>
36 # include <saml/saml2/metadata/Metadata.h>
37 # include <xmltooling/util/DateTime.h>
38 using namespace opensaml::saml1;
39 using namespace opensaml::saml1p;
40 using namespace opensaml;
42 using saml2::NameIDBuilder;
43 using saml2md::EntityDescriptor;
44 using saml2md::SPSSODescriptor;
45 using saml2md::MetadataException;
47 # include "lite/SAMLConstants.h"
50 using namespace shibsp;
51 using namespace xmltooling;
56 #if defined (_MSC_VER)
57 #pragma warning( push )
58 #pragma warning( disable : 4250 )
61 class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
64 SAML1Consumer(const DOMElement* e, const char* appId)
65 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
68 m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
69 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
70 m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(SAML1BROWSERSSO_POLICY_RULE, e);
73 virtual ~SAML1Consumer() {
80 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
81 AssertionConsumerService::generateMetadata(role, handlerURL);
82 role.addSupport(samlconstants::SAML11_PROTOCOL_ENUM);
83 role.addSupport(samlconstants::SAML10_PROTOCOL_ENUM);
87 void implementProtocol(
88 const Application& application,
89 const HTTPRequest& httpRequest,
90 HTTPResponse& httpResponse,
91 SecurityPolicy& policy,
92 const PropertySet* settings,
93 const XMLObject& xmlObject
97 SecurityPolicyRule* m_ssoRule;
101 #if defined (_MSC_VER)
102 #pragma warning( pop )
105 Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
107 return new SAML1Consumer(p.first, p.second);
111 class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
114 _rulenamed(const char* name) : m_name(name) {}
115 bool operator()(const SecurityPolicyRule* rule) const {
116 return rule ? !strcmp(m_name, rule->getType()) : false;
126 void SAML1Consumer::implementProtocol(
127 const Application& application,
128 const HTTPRequest& httpRequest,
129 HTTPResponse& httpResponse,
130 SecurityPolicy& policy,
131 const PropertySet* settings,
132 const XMLObject& xmlObject
135 // Implementation of SAML 1.x SSO profile(s).
136 m_log.debug("processing message against SAML 1.x SSO profile");
138 // Check for errors...this will throw if it's not a successful message.
139 checkError(&xmlObject);
141 // With the binding aspects now moved out to the MessageDecoder,
142 // the focus here is on the assertion content. For SAML 1.x POST,
143 // all the security comes from the protocol layer, and signing
144 // the assertion isn't sufficient. So we can check the policy
145 // object now and bail if it's not a secured message.
146 if (m_post && !policy.isAuthenticated()) {
147 if (policy.getIssuer() && !policy.getIssuerMetadata())
148 throw MetadataException("Security of SAML 1.x SSO POST response not established.");
149 throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
152 // Remember whether we already established trust.
153 bool alreadySecured = policy.isAuthenticated();
155 const Response* response = dynamic_cast<const Response*>(&xmlObject);
157 throw FatalProfileException("Incoming message was not a samlp:Response.");
159 const vector<saml1::Assertion*>& assertions = response->getAssertions();
160 if (assertions.empty())
161 throw FatalProfileException("Incoming message contained no SAML assertions.");
163 pair<bool,int> minor = response->getMinorVersion();
165 // Maintain list of "legit" tokens to feed to SP subsystems.
166 const AuthenticationStatement* ssoStatement=NULL;
167 vector<const opensaml::Assertion*> tokens;
169 // Also track "bad" tokens that we'll cache but not use.
170 // This is necessary because there may be valid tokens not aimed at us.
171 vector<const opensaml::Assertion*> badtokens;
173 // With this flag on, we ignore any unsigned assertions.
174 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
175 pair<bool,bool> flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
177 // authnskew allows rejection of SSO if AuthnInstant is too old.
178 const PropertySet* sessionProps = application.getPropertySet("Sessions");
179 pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
181 // Saves off error messages potentially helpful for users.
182 string contextualError;
184 // Ensure the BrowserSSO rule is in the policy set.
185 if (find_if(policy.getRules(), _rulenamed(SAML1BROWSERSSO_POLICY_RULE)) == NULL)
186 policy.getRules().push_back(m_ssoRule);
188 // Populate recipient as audience.
189 policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
191 time_t now = time(NULL);
192 for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
194 // Skip unsigned assertion?
195 if (!(*a)->getSignature() && flag.first && flag.second)
196 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
198 // We clear the security flag, so we can tell whether the token was secured on its own.
199 policy.setAuthenticated(false);
202 // Extract message bits and re-verify Issuer information.
203 extractMessageDetails(
204 *(*a), (minor.first && minor.second==0) ? samlconstants::SAML10_PROTOCOL_ENUM : samlconstants::SAML11_PROTOCOL_ENUM, policy
207 // Run the policy over the assertion. Handles replay, freshness, and
208 // signature verification, assuming the relevant rules are configured,
209 // along with condition and profile enforcement.
210 policy.evaluate(*(*a), &httpRequest);
212 // If no security is in place now, we kick it.
213 if (!alreadySecured && !policy.isAuthenticated())
214 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
216 // Track it as a valid token.
217 tokens.push_back(*a);
219 // Save off the first valid SSO statement.
220 const vector<AuthenticationStatement*>& statements = const_cast<const saml1::Assertion*>(*a)->getAuthenticationStatements();
221 for (vector<AuthenticationStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
222 if (authnskew.first && authnskew.second &&
223 (*s)->getAuthenticationInstant() && (now - (*s)->getAuthenticationInstantEpoch() > authnskew.second))
224 contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
225 else if (!ssoStatement) {
231 catch (exception& ex) {
232 m_log.warn("detected a problem with assertion: %s", ex.what());
234 contextualError = ex.what();
235 badtokens.push_back(*a);
240 if (contextualError.empty())
241 throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
242 throw FatalProfileException(contextualError.c_str());
246 SubjectLocality* locality = ssoStatement->getSubjectLocality();
247 if (locality && locality->getIPAddress()) {
248 auto_ptr_char ip(locality->getIPAddress());
249 checkAddress(application, httpRequest, ip.get());
252 m_log.debug("SSO profile processing completed successfully");
254 NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
256 // Now we have to extract the authentication details for attribute and session setup.
258 // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
259 pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
260 if (!lifetime.first || lifetime.second == 0)
261 lifetime.second = 28800;
263 // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
264 // To complete processing, we need to extract and resolve attributes and then create the session.
266 // Normalize the SAML 1.x NameIdentifier...
267 auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : NULL);
269 nameid->setName(n->getName());
270 nameid->setFormat(n->getFormat());
271 nameid->setNameQualifier(n->getNameQualifier());
274 // The context will handle deleting attributes and new tokens.
275 auto_ptr<ResolutionContext> ctx(
278 policy.getIssuerMetadata(),
279 (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
280 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
283 ssoStatement->getAuthenticationMethod(),
290 // Copy over any new tokens, but leave them in the context for cleanup.
291 tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
294 // Now merge in bad tokens for caching.
295 tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
297 application.getServiceProvider().getSessionCache()->insert(
301 now + lifetime.second,
303 (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
304 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
306 ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
308 ssoStatement->getAuthenticationMethod(),
311 ctx.get() ? &ctx->getResolvedAttributes() : NULL