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)
59 string address(appId);
60 address += getString("Location").second;
61 setAddress(address.c_str());
63 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
64 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
65 getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS)
67 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
72 AssertionConsumerService::~AssertionConsumerService()
79 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
82 SPConfig& conf = SPConfig::getConfig();
85 if (conf.isEnabled(SPConfig::OutOfProcess)) {
86 // When out of process, we run natively and directly process the message.
87 // RelayState will be fully handled during message processing.
89 string key = processMessage(request.getApplication(), request, entityID, relayState);
90 return sendRedirect(request, key.c_str(), entityID.c_str(), relayState.c_str());
93 // When not out of process, we remote all the message processing.
94 DDF out,in = wrap(request);
95 DDFJanitor jin(in), jout(out);
98 out=request.getServiceProvider().getListenerService()->send(in);
100 catch (XMLToolingException& ex) {
101 // Try for RelayState recovery.
102 if (ex.getProperty("RelayState"))
103 relayState = ex.getProperty("RelayState");
105 recoverRelayState(request.getApplication(), request, relayState);
107 catch (exception& ex2) {
108 m_log.error("trapped an error during RelayState recovery while handling an error: %s", ex2.what());
113 // We invoke RelayState recovery one last time on this side of the boundary.
114 if (out["RelayState"].isstring())
115 relayState = out["RelayState"].string();
116 recoverRelayState(request.getApplication(), request, relayState);
118 // If it worked, we have a session key.
119 if (!out["key"].isstring())
120 throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
122 // Take care of cookie business and wrap it up.
123 return sendRedirect(request, out["key"].string(), out["entity_id"].string(), relayState.c_str());
126 catch (XMLToolingException& ex) {
127 // Try and preserve RelayState.
128 if (!relayState.empty())
129 ex.addProperty("RelayState", relayState.c_str());
134 void AssertionConsumerService::receive(DDF& in, ostream& out)
137 const char* aid=in["application_id"].string();
138 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
140 // Something's horribly wrong.
141 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
142 throw ConfigurationException("Unable to locate application for new session, deleted?");
145 // Unpack the request.
146 auto_ptr<HTTPRequest> http(getRequest(in));
149 string relayState, entityID;
151 string key = processMessage(*app, *http.get(), entityID, relayState);
153 // Repack for return to caller.
154 DDF ret=DDF(NULL).structure();
155 DDFJanitor jret(ret);
156 ret.addmember("key").string(key.c_str());
157 if (!entityID.empty())
158 ret.addmember("entity_id").string(entityID.c_str());
159 if (!relayState.empty())
160 ret.addmember("RelayState").string(relayState.c_str());
163 catch (XMLToolingException& ex) {
164 // Try and preserve RelayState if we can.
165 if (!relayState.empty())
166 ex.addProperty("RelayState", relayState.c_str());
171 string AssertionConsumerService::processMessage(
172 const Application& application, HTTPRequest& httpRequest, string& entityID, string& relayState
176 // Locate policy key.
177 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
179 policyId = application.getString("policyId"); // unqualified in Application(s) element
181 // Access policy properties.
182 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
183 pair<bool,bool> validate = settings->getBool("validate");
185 // Lock metadata for use by policy.
186 Locker metadataLocker(application.getMetadataProvider());
188 // Create the policy.
189 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
191 // Decode the message and process it in a protocol-specific way.
192 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
194 throw BindingException("Failed to decode an SSO protocol response.");
195 recoverRelayState(application, httpRequest, relayState);
196 string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
198 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
200 entityID = issuer.get();
204 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
208 pair<bool,long> AssertionConsumerService::sendRedirect(
209 SPRequest& request, const char* key, const char* entityID, const char* relayState
212 // We've got a good session, so set the session cookie.
213 pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
215 k += shib_cookie.second;
216 request.setCookie(shib_cookie.first.c_str(), k.c_str());
219 maintainHistory(request, entityID, shib_cookie.second);
221 // Now redirect to the state value. By now, it should be set to *something* usable.
222 return make_pair(true, request.sendRedirect(relayState));
225 void AssertionConsumerService::checkAddress(
226 const Application& application, const HTTPRequest& httpRequest, const char* issuedTo
229 const PropertySet* props=application.getPropertySet("Sessions");
230 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
231 if (!checkAddress.first)
232 checkAddress.second=true;
234 if (checkAddress.second) {
235 m_log.debug("checking client address");
236 if (httpRequest.getRemoteAddr() != issuedTo) {
237 throw FatalProfileException(
238 "Your client's current address ($client_addr) differs from the one used when you authenticated "
239 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
240 "Please contact your local support staff or help desk for assistance.",
241 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
249 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
252 DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
255 virtual ~DummyContext() {
256 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
259 vector<Attribute*>& getResolvedAttributes() {
262 vector<Assertion*>& getResolvedAssertions() {
267 vector<Attribute*> m_attributes;
268 static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
271 vector<Assertion*> DummyContext::m_tokens;
273 ResolutionContext* AssertionConsumerService::resolveAttributes(
274 const Application& application,
275 const saml2md::RoleDescriptor* issuer,
276 const XMLCh* protocol,
277 const saml1::NameIdentifier* v1nameid,
278 const saml2::NameID* nameid,
279 const XMLCh* authncontext_class,
280 const XMLCh* authncontext_decl,
281 const vector<const Assertion*>* tokens
284 const saml2md::EntityDescriptor* entity = dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent());
286 // First we do the extraction of any pushed information, including from metadata.
287 vector<Attribute*> resolvedAttributes;
288 AttributeExtractor* extractor = application.getAttributeExtractor();
290 Locker extlocker(extractor);
292 m_log.debug("extracting metadata-derived attributes...");
294 extractor->extractAttributes(application, issuer, *entity, resolvedAttributes);
296 catch (exception& ex) {
297 m_log.error("caught exception extracting attributes: %s", ex.what());
300 m_log.debug("extracting pushed attributes...");
303 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
305 catch (exception& ex) {
306 m_log.error("caught exception extracting attributes: %s", ex.what());
311 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
313 catch (exception& ex) {
314 m_log.error("caught exception extracting attributes: %s", ex.what());
318 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
320 extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
322 catch (exception& ex) {
323 m_log.error("caught exception extracting attributes: %s", ex.what());
328 AttributeFilter* filter = application.getAttributeFilter();
329 if (filter && !resolvedAttributes.empty()) {
330 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
331 Locker filtlocker(filter);
333 filter->filterAttributes(fc, resolvedAttributes);
335 catch (exception& ex) {
336 m_log.error("caught exception filtering attributes: %s", ex.what());
337 m_log.error("dumping extracted attributes due to filtering exception");
338 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
339 resolvedAttributes.clear();
345 AttributeResolver* resolver = application.getAttributeResolver();
347 m_log.debug("resolving attributes...");
349 Locker locker(resolver);
350 auto_ptr<ResolutionContext> ctx(
351 resolver->createResolutionContext(
362 resolver->resolveAttributes(*ctx.get());
363 // Copy over any pushed attributes.
364 if (!resolvedAttributes.empty())
365 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
366 return ctx.release();
369 catch (exception& ex) {
370 m_log.error("attribute resolution failed: %s", ex.what());
373 if (!resolvedAttributes.empty())
374 return new DummyContext(resolvedAttributes);
379 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* entityID, const char* cookieProps) const
384 const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
385 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
386 if (!idpHistory.first || idpHistory.second) {
387 // Set an IdP history cookie locally (essentially just a CDC).
388 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
390 // Either leave in memory or set an expiration.
391 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
392 if (!days.first || days.second==0) {
393 string c = string(cdc.set(entityID)) + cookieProps;
394 request.setCookie(CommonDomainCookie::CDCName, c.c_str());
397 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
400 struct tm* ptime=gmtime_r(&now,&res);
402 struct tm* ptime=gmtime(&now);
405 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
406 string c = string(cdc.set(entityID)) + cookieProps + "; expires=" + timebuf;
407 request.setCookie(CommonDomainCookie::CDCName, c.c_str());