2 * Copyright 2001-2007 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.
18 * AssertionConsumerService.cpp
20 * Base class for handlers that create sessions by consuming SSO protocol responses.
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "handler/AssertionConsumerService.h"
28 #include "util/SPConstants.h"
32 # include "attribute/Attribute.h"
33 # include "attribute/filtering/AttributeFilter.h"
34 # include "attribute/filtering/BasicFilteringContext.h"
35 # include "attribute/resolver/AttributeExtractor.h"
36 # include "attribute/resolver/AttributeResolver.h"
37 # include "attribute/resolver/ResolutionContext.h"
38 # include "security/SecurityPolicy.h"
39 # include <saml/SAMLConfig.h>
40 # include <saml/saml1/core/Assertions.h>
41 # include <saml/util/CommonDomainCookie.h>
42 using namespace samlconstants;
44 # include "lite/CommonDomainCookie.h"
47 using namespace shibspconstants;
48 using namespace shibsp;
49 using namespace opensaml;
50 using namespace xmltooling;
53 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
54 : AbstractHandler(e, log)
56 ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
61 string address(appId);
62 address += getString("Location").second;
63 setAddress(address.c_str());
65 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
66 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
67 getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS)
69 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
74 AssertionConsumerService::~AssertionConsumerService()
81 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
84 SPConfig& conf = SPConfig::getConfig();
87 if (conf.isEnabled(SPConfig::OutOfProcess)) {
88 // When out of process, we run natively and directly process the message.
89 // RelayState will be fully handled during message processing.
91 string key = processMessage(request.getApplication(), request, entityID, relayState);
92 return sendRedirect(request, key.c_str(), entityID.c_str(), relayState.c_str());
95 // When not out of process, we remote all the message processing.
96 DDF out,in = wrap(request);
97 DDFJanitor jin(in), jout(out);
100 out=request.getServiceProvider().getListenerService()->send(in);
102 catch (XMLToolingException& ex) {
103 // Try for RelayState recovery.
104 if (ex.getProperty("RelayState"))
105 relayState = ex.getProperty("RelayState");
107 recoverRelayState(request.getApplication(), request, relayState);
109 catch (exception& ex2) {
110 m_log.error("trapped an error during RelayState recovery while handling an error: %s", ex2.what());
115 // We invoke RelayState recovery one last time on this side of the boundary.
116 if (out["RelayState"].isstring())
117 relayState = out["RelayState"].string();
118 recoverRelayState(request.getApplication(), request, relayState);
120 // If it worked, we have a session key.
121 if (!out["key"].isstring())
122 throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
124 // Take care of cookie business and wrap it up.
125 return sendRedirect(request, out["key"].string(), out["entity_id"].string(), relayState.c_str());
128 catch (XMLToolingException& ex) {
129 // Try and preserve RelayState.
130 if (!relayState.empty())
131 ex.addProperty("RelayState", relayState.c_str());
136 void AssertionConsumerService::receive(DDF& in, ostream& out)
139 const char* aid=in["application_id"].string();
140 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
142 // Something's horribly wrong.
143 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
144 throw ConfigurationException("Unable to locate application for new session, deleted?");
147 // Unpack the request.
148 auto_ptr<HTTPRequest> http(getRequest(in));
151 string relayState, entityID;
153 string key = processMessage(*app, *http.get(), entityID, relayState);
155 // Repack for return to caller.
156 DDF ret=DDF(NULL).structure();
157 DDFJanitor jret(ret);
158 ret.addmember("key").string(key.c_str());
159 if (!entityID.empty())
160 ret.addmember("entity_id").string(entityID.c_str());
161 if (!relayState.empty())
162 ret.addmember("RelayState").string(relayState.c_str());
165 catch (XMLToolingException& ex) {
166 // Try and preserve RelayState if we can.
167 if (!relayState.empty())
168 ex.addProperty("RelayState", relayState.c_str());
173 string AssertionConsumerService::processMessage(
174 const Application& application, HTTPRequest& httpRequest, string& entityID, string& relayState
178 // Locate policy key.
179 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
181 policyId = application.getString("policyId"); // unqualified in Application(s) element
183 // Access policy properties.
184 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
185 pair<bool,bool> validate = settings->getBool("validate");
187 // Lock metadata for use by policy.
188 Locker metadataLocker(application.getMetadataProvider());
190 // Create the policy.
191 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
193 // Decode the message and process it in a protocol-specific way.
194 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
196 throw BindingException("Failed to decode an SSO protocol response.");
197 recoverRelayState(application, httpRequest, relayState);
198 string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
200 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
202 entityID = issuer.get();
206 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
210 pair<bool,long> AssertionConsumerService::sendRedirect(
211 SPRequest& request, const char* key, const char* entityID, const char* relayState
214 // We've got a good session, so set the session cookie.
215 pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
217 k += shib_cookie.second;
218 request.setCookie(shib_cookie.first.c_str(), k.c_str());
221 maintainHistory(request, entityID, shib_cookie.second);
223 // Now redirect to the state value. By now, it should be set to *something* usable.
224 return make_pair(true, request.sendRedirect(relayState));
227 void AssertionConsumerService::checkAddress(
228 const Application& application, const HTTPRequest& httpRequest, const char* issuedTo
231 const PropertySet* props=application.getPropertySet("Sessions");
232 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
233 if (!checkAddress.first)
234 checkAddress.second=true;
236 if (checkAddress.second) {
237 m_log.debug("checking client address");
238 if (httpRequest.getRemoteAddr() != issuedTo) {
239 throw FatalProfileException(
240 "Your client's current address ($client_addr) differs from the one used when you authenticated "
241 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
242 "Please contact your local support staff or help desk for assistance.",
243 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
251 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
254 DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
257 virtual ~DummyContext() {
258 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
261 vector<Attribute*>& getResolvedAttributes() {
264 vector<Assertion*>& getResolvedAssertions() {
269 vector<Attribute*> m_attributes;
270 static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
273 vector<Assertion*> DummyContext::m_tokens;
275 ResolutionContext* AssertionConsumerService::resolveAttributes(
276 const Application& application,
277 const saml2md::RoleDescriptor* issuer,
278 const XMLCh* protocol,
279 const saml1::NameIdentifier* v1nameid,
280 const saml2::NameID* nameid,
281 const XMLCh* authncontext_class,
282 const XMLCh* authncontext_decl,
283 const vector<const Assertion*>* tokens
286 const saml2md::EntityDescriptor* entity = issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : NULL;
288 // First we do the extraction of any pushed information, including from metadata.
289 vector<Attribute*> resolvedAttributes;
290 AttributeExtractor* extractor = application.getAttributeExtractor();
292 Locker extlocker(extractor);
294 pair<bool,const char*> prefix = application.getString("metadataAttributePrefix");
296 m_log.debug("extracting metadata-derived attributes...");
298 extractor->extractAttributes(application, issuer, *entity, resolvedAttributes);
299 for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
300 vector<string>& ids = (*a)->getAliases();
301 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
302 *id = prefix.second + *id;
305 catch (exception& ex) {
306 m_log.error("caught exception extracting attributes: %s", ex.what());
310 m_log.debug("extracting pushed attributes...");
313 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
315 catch (exception& ex) {
316 m_log.error("caught exception extracting attributes: %s", ex.what());
321 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
323 catch (exception& ex) {
324 m_log.error("caught exception extracting attributes: %s", ex.what());
328 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
330 extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
332 catch (exception& ex) {
333 m_log.error("caught exception extracting attributes: %s", ex.what());
338 AttributeFilter* filter = application.getAttributeFilter();
339 if (filter && !resolvedAttributes.empty()) {
340 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
341 Locker filtlocker(filter);
343 filter->filterAttributes(fc, resolvedAttributes);
345 catch (exception& ex) {
346 m_log.error("caught exception filtering attributes: %s", ex.what());
347 m_log.error("dumping extracted attributes due to filtering exception");
348 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
349 resolvedAttributes.clear();
355 AttributeResolver* resolver = application.getAttributeResolver();
357 m_log.debug("resolving attributes...");
359 Locker locker(resolver);
360 auto_ptr<ResolutionContext> ctx(
361 resolver->createResolutionContext(
372 resolver->resolveAttributes(*ctx.get());
373 // Copy over any pushed attributes.
374 if (!resolvedAttributes.empty())
375 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
376 return ctx.release();
379 catch (exception& ex) {
380 m_log.error("attribute resolution failed: %s", ex.what());
383 if (!resolvedAttributes.empty())
384 return new DummyContext(resolvedAttributes);
389 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* entityID, const char* cookieProps) const
394 const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
395 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
396 if (!idpHistory.first || idpHistory.second) {
397 // Set an IdP history cookie locally (essentially just a CDC).
398 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
400 // Either leave in memory or set an expiration.
401 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
402 if (!days.first || days.second==0) {
403 string c = string(cdc.set(entityID)) + cookieProps;
404 request.setCookie(CommonDomainCookie::CDCName, c.c_str());
407 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
410 struct tm* ptime=gmtime_r(&now,&res);
412 struct tm* ptime=gmtime(&now);
415 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
416 string c = string(cdc.set(entityID)) + cookieProps + "; expires=" + timebuf;
417 request.setCookie(CommonDomainCookie::CDCName, c.c_str());