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;
43 using opensaml::saml2md::EntityDescriptor;
44 using opensaml::saml2md::IDPSSODescriptor;
45 using opensaml::saml2md::SPSSODescriptor;
47 # include "lite/CommonDomainCookie.h"
50 using namespace shibspconstants;
51 using namespace shibsp;
52 using namespace opensaml;
53 using namespace xmltooling;
56 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
57 : AbstractHandler(e, log)
59 ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
64 string address(appId);
65 address += getString("Location").second;
66 setAddress(address.c_str());
68 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
69 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
70 getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS)
72 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
77 AssertionConsumerService::~AssertionConsumerService()
84 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
87 SPConfig& conf = SPConfig::getConfig();
90 if (conf.isEnabled(SPConfig::OutOfProcess)) {
91 // When out of process, we run natively and directly process the message.
92 // RelayState will be fully handled during message processing.
94 string key = processMessage(request.getApplication(), request, entityID, relayState);
95 return sendRedirect(request, key.c_str(), entityID.c_str(), relayState.c_str());
98 // When not out of process, we remote all the message processing.
99 DDF out,in = wrap(request);
100 DDFJanitor jin(in), jout(out);
103 out=request.getServiceProvider().getListenerService()->send(in);
105 catch (XMLToolingException& ex) {
106 // Try for RelayState recovery.
107 if (ex.getProperty("RelayState"))
108 relayState = ex.getProperty("RelayState");
110 recoverRelayState(request.getApplication(), request, relayState);
112 catch (exception& ex2) {
113 m_log.error("trapped an error during RelayState recovery while handling an error: %s", ex2.what());
118 // We invoke RelayState recovery one last time on this side of the boundary.
119 if (out["RelayState"].isstring())
120 relayState = out["RelayState"].string();
121 recoverRelayState(request.getApplication(), request, relayState);
123 // If it worked, we have a session key.
124 if (!out["key"].isstring())
125 throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
127 // Take care of cookie business and wrap it up.
128 return sendRedirect(request, out["key"].string(), out["entity_id"].string(), relayState.c_str());
131 catch (XMLToolingException& ex) {
132 // Try and preserve RelayState.
133 if (!relayState.empty())
134 ex.addProperty("RelayState", relayState.c_str());
139 void AssertionConsumerService::receive(DDF& in, ostream& out)
142 const char* aid=in["application_id"].string();
143 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
145 // Something's horribly wrong.
146 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
147 throw ConfigurationException("Unable to locate application for new session, deleted?");
150 // Unpack the request.
151 auto_ptr<HTTPRequest> http(getRequest(in));
154 string relayState, entityID;
156 string key = processMessage(*app, *http.get(), entityID, relayState);
158 // Repack for return to caller.
159 DDF ret=DDF(NULL).structure();
160 DDFJanitor jret(ret);
161 ret.addmember("key").string(key.c_str());
162 if (!entityID.empty())
163 ret.addmember("entity_id").string(entityID.c_str());
164 if (!relayState.empty())
165 ret.addmember("RelayState").string(relayState.c_str());
168 catch (XMLToolingException& ex) {
169 // Try and preserve RelayState if we can.
170 if (!relayState.empty())
171 ex.addProperty("RelayState", relayState.c_str());
176 string AssertionConsumerService::processMessage(
177 const Application& application, HTTPRequest& httpRequest, string& entityID, string& relayState
181 // Locate policy key.
182 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
184 policyId = application.getString("policyId"); // unqualified in Application(s) element
186 // Access policy properties.
187 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
188 pair<bool,bool> validate = settings->getBool("validate");
190 // Lock metadata for use by policy.
191 Locker metadataLocker(application.getMetadataProvider());
193 // Create the policy.
194 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
196 // Decode the message and process it in a protocol-specific way.
197 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
199 throw BindingException("Failed to decode an SSO protocol response.");
200 recoverRelayState(application, httpRequest, relayState);
201 string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
203 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
205 entityID = issuer.get();
209 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
213 pair<bool,long> AssertionConsumerService::sendRedirect(
214 SPRequest& request, const char* key, const char* entityID, const char* relayState
217 // We've got a good session, so set the session cookie.
218 pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
220 k += shib_cookie.second;
221 request.setCookie(shib_cookie.first.c_str(), k.c_str());
224 maintainHistory(request, entityID, shib_cookie.second);
226 // Now redirect to the state value. By now, it should be set to *something* usable.
227 return make_pair(true, request.sendRedirect(relayState));
230 void AssertionConsumerService::checkAddress(
231 const Application& application, const HTTPRequest& httpRequest, const char* issuedTo
234 const PropertySet* props=application.getPropertySet("Sessions");
235 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
236 if (!checkAddress.first)
237 checkAddress.second=true;
239 if (checkAddress.second) {
240 m_log.debug("checking client address");
241 if (httpRequest.getRemoteAddr() != issuedTo) {
242 throw FatalProfileException(
243 "Your client's current address ($client_addr) differs from the one used when you authenticated "
244 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
245 "Please contact your local support staff or help desk for assistance.",
246 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
254 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
255 const char* loc = getString("Location").second;
256 string hurl(handlerURL);
260 auto_ptr_XMLCh widen(hurl.c_str());
261 saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
262 ep->setLocation(widen.get());
263 ep->setBinding(getXMLString("Binding").second);
264 ep->setIndex(getXMLString("index").second);
265 role.getAssertionConsumerServices().push_back(ep);
268 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
271 DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
274 virtual ~DummyContext() {
275 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
278 vector<Attribute*>& getResolvedAttributes() {
281 vector<Assertion*>& getResolvedAssertions() {
286 vector<Attribute*> m_attributes;
287 static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
290 vector<Assertion*> DummyContext::m_tokens;
292 ResolutionContext* AssertionConsumerService::resolveAttributes(
293 const Application& application,
294 const saml2md::RoleDescriptor* issuer,
295 const XMLCh* protocol,
296 const saml1::NameIdentifier* v1nameid,
297 const saml2::NameID* nameid,
298 const XMLCh* authncontext_class,
299 const XMLCh* authncontext_decl,
300 const vector<const Assertion*>* tokens
303 const saml2md::EntityDescriptor* entity = issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : NULL;
305 // First we do the extraction of any pushed information, including from metadata.
306 vector<Attribute*> resolvedAttributes;
307 AttributeExtractor* extractor = application.getAttributeExtractor();
309 Locker extlocker(extractor);
311 pair<bool,const char*> prefix = application.getString("metadataAttributePrefix");
313 m_log.debug("extracting metadata-derived attributes...");
315 extractor->extractAttributes(application, issuer, *entity, resolvedAttributes);
316 for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
317 vector<string>& ids = (*a)->getAliases();
318 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
319 *id = prefix.second + *id;
322 catch (exception& ex) {
323 m_log.error("caught exception extracting attributes: %s", ex.what());
327 m_log.debug("extracting pushed attributes...");
330 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
332 catch (exception& ex) {
333 m_log.error("caught exception extracting attributes: %s", ex.what());
338 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
340 catch (exception& ex) {
341 m_log.error("caught exception extracting attributes: %s", ex.what());
345 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
347 extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
349 catch (exception& ex) {
350 m_log.error("caught exception extracting attributes: %s", ex.what());
355 AttributeFilter* filter = application.getAttributeFilter();
356 if (filter && !resolvedAttributes.empty()) {
357 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
358 Locker filtlocker(filter);
360 filter->filterAttributes(fc, resolvedAttributes);
362 catch (exception& ex) {
363 m_log.error("caught exception filtering attributes: %s", ex.what());
364 m_log.error("dumping extracted attributes due to filtering exception");
365 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
366 resolvedAttributes.clear();
372 AttributeResolver* resolver = application.getAttributeResolver();
374 m_log.debug("resolving attributes...");
376 Locker locker(resolver);
377 auto_ptr<ResolutionContext> ctx(
378 resolver->createResolutionContext(
389 resolver->resolveAttributes(*ctx.get());
390 // Copy over any pushed attributes.
391 if (!resolvedAttributes.empty())
392 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
393 return ctx.release();
396 catch (exception& ex) {
397 m_log.error("attribute resolution failed: %s", ex.what());
400 if (!resolvedAttributes.empty())
401 return new DummyContext(resolvedAttributes);
405 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
407 policy.setMessageID(assertion.getID());
408 policy.setIssueInstant(assertion.getIssueInstantEpoch());
410 if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20P_NS)) {
411 const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
413 m_log.debug("extracting issuer from SAML 2.0 assertion");
414 policy.setIssuer(a2->getIssuer());
418 const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
420 m_log.debug("extracting issuer from SAML 1.x assertion");
421 policy.setIssuer(a1->getIssuer());
425 if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
426 m_log.debug("searching metadata for assertion issuer...");
427 const EntityDescriptor* entity = policy.getMetadataProvider()->getEntityDescriptor(policy.getIssuer()->getName());
429 m_log.debug("matched assertion issuer against metadata, searching for applicable role...");
430 const IDPSSODescriptor* idp=entity->getIDPSSODescriptor(protocol);
432 policy.setIssuerMetadata(idp);
433 else if (m_log.isWarnEnabled())
434 m_log.warn("unable to find compatible IdP role in metadata");
436 else if (m_log.isWarnEnabled()) {
437 auto_ptr_char iname(policy.getIssuer()->getName());
438 m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
445 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* entityID, const char* cookieProps) const
450 const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
451 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
452 if (!idpHistory.first || idpHistory.second) {
453 // Set an IdP history cookie locally (essentially just a CDC).
454 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
456 // Either leave in memory or set an expiration.
457 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
458 if (!days.first || days.second==0) {
459 string c = string(cdc.set(entityID)) + cookieProps;
460 request.setCookie(CommonDomainCookie::CDCName, c.c_str());
463 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
466 struct tm* ptime=gmtime_r(&now,&res);
468 struct tm* ptime=gmtime(&now);
471 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
472 string c = string(cdc.set(entityID)) + cookieProps + "; expires=" + timebuf;
473 request.setCookie(CommonDomainCookie::CDCName, c.c_str());