2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * AssertionConsumerService.cpp
24 * Base class for handlers that create sessions by consuming SSO protocol responses.
28 #include "exceptions.h"
29 #include "Application.h"
30 #include "ServiceProvider.h"
31 #include "SPRequest.h"
32 #include "handler/AssertionConsumerService.h"
33 #include "util/CGIParser.h"
34 #include "util/SPConstants.h"
38 # include "attribute/Attribute.h"
39 # include "attribute/filtering/AttributeFilter.h"
40 # include "attribute/filtering/BasicFilteringContext.h"
41 # include "attribute/resolver/AttributeExtractor.h"
42 # include "attribute/resolver/AttributeResolver.h"
43 # include "attribute/resolver/ResolutionContext.h"
44 # include "metadata/MetadataProviderCriteria.h"
45 # include "security/SecurityPolicy.h"
46 # include "security/SecurityPolicyProvider.h"
47 # include <boost/iterator/indirect_iterator.hpp>
48 # include <saml/exceptions.h>
49 # include <saml/SAMLConfig.h>
50 # include <saml/saml1/core/Assertions.h>
51 # include <saml/saml1/core/Protocols.h>
52 # include <saml/saml2/core/Protocols.h>
53 # include <saml/saml2/metadata/Metadata.h>
54 # include <saml/util/CommonDomainCookie.h>
55 using namespace samlconstants;
56 using opensaml::saml2md::MetadataProvider;
57 using opensaml::saml2md::RoleDescriptor;
58 using opensaml::saml2md::EntityDescriptor;
59 using opensaml::saml2md::IDPSSODescriptor;
60 using opensaml::saml2md::SPSSODescriptor;
62 # include "lite/CommonDomainCookie.h"
65 #include <xmltooling/XMLToolingConfig.h>
66 #include <xmltooling/util/URLEncoder.h>
68 using namespace shibspconstants;
69 using namespace shibsp;
70 using namespace opensaml;
71 using namespace xmltooling;
72 using namespace boost;
75 AssertionConsumerService::AssertionConsumerService(
76 const DOMElement* e, const char* appId, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
77 ) : AbstractHandler(e, log, filter, remapper)
81 string address(appId);
82 address += getString("Location").second;
83 setAddress(address.c_str());
85 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
87 SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
88 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
91 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
96 AssertionConsumerService::~AssertionConsumerService()
100 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
102 // Check for a message back to the ACS from a post-session hook.
103 if (request.getQueryString() && strstr(request.getQueryString(), "hook=1")) {
104 // Parse the query string only to preserve any POST data.
105 CGIParser cgi(request, true);
106 pair<CGIParser::walker,CGIParser::walker> param = cgi.getParameters("hook");
107 if (param.first != param.second && param.first->second && !strcmp(param.first->second, "1")) {
109 param = cgi.getParameters("target");
110 if (param.first != param.second && param.first->second)
111 target = param.first->second;
112 return finalizeResponse(request.getApplication(), request, request, target);
116 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
117 // When out of process, we run natively and directly process the message.
118 return processMessage(request.getApplication(), request, request);
121 // When not out of process, we remote all the message processing.
122 vector<string> headers(1, "Cookie");
123 headers.push_back("User-Agent");
124 headers.push_back("Accept-Language");
125 DDF out,in = wrap(request, &headers);
126 DDFJanitor jin(in), jout(out);
127 out = request.getServiceProvider().getListenerService()->send(in);
128 return unwrap(request, out);
132 void AssertionConsumerService::receive(DDF& in, ostream& out)
135 const char* aid = in["application_id"].string();
136 const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
138 // Something's horribly wrong.
139 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
140 throw ConfigurationException("Unable to locate application for new session, deleted?");
143 // Unpack the request.
144 scoped_ptr<HTTPRequest> req(getRequest(in));
146 // Wrap a response shim.
148 DDFJanitor jout(ret);
149 scoped_ptr<HTTPResponse> resp(getResponse(ret));
151 // Since we're remoted, the result should either be a throw, a false/0 return,
152 // which we just return as an empty structure, or a response/redirect,
153 // which we capture in the facade and send back.
154 processMessage(*app, *req, *resp);
158 pair<bool,long> AssertionConsumerService::processMessage(
159 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
163 // Locate policy key.
164 pair<bool,const char*> prop = getString("policyId", m_configNS.get()); // may be namespace-qualified if inside handler element
166 prop = getString("policyId"); // try unqualified
168 prop = application.getString("policyId"); // unqualified in Application(s) element
170 // Lock metadata for use by policy.
171 Locker metadataLocker(application.getMetadataProvider());
173 // Create the policy.
174 scoped_ptr<opensaml::SecurityPolicy> policy(
175 application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(
176 application, &IDPSSODescriptor::ELEMENT_QNAME, prop.second
181 scoped_ptr<XMLObject> msg;
183 // Decode the message and process it in a protocol-specific way.
184 msg.reset(m_decoder->decode(relayState, httpRequest, *(policy.get())));
186 throw BindingException("Failed to decode an SSO protocol response.");
187 implementProtocol(application, httpRequest, httpResponse, *policy, nullptr, *msg);
190 auto_ptr_char issuer(policy->getIssuer() ? policy->getIssuer()->getName() : nullptr);
191 if (issuer.get() && *issuer.get())
192 maintainHistory(application, httpRequest, httpResponse, issuer.get());
194 const EntityDescriptor* entity =
195 dynamic_cast<const EntityDescriptor*>(policy->getIssuerMetadata() ? policy->getIssuerMetadata()->getParent() : nullptr);
196 prop = application.getRelyingParty(entity)->getString("sessionHook");
198 string hook(prop.second);
199 httpRequest.absolutize(hook);
201 // Compute the return URL. We use a self-referential link plus a hook indicator to break the cycle
202 // and the relay state.
203 const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
204 string returnURL = httpRequest.getRequestURL();
205 returnURL = returnURL.substr(0, returnURL.find('?')) + "?hook=1";
206 if (!relayState.empty())
207 returnURL += "&target=" + encoder->encode(relayState.c_str());
208 if (hook.find('?') == string::npos)
212 hook += "return=" + encoder->encode(returnURL.c_str());
214 // Add the translated target resource in case it's of interest.
215 if (!relayState.empty()) {
217 recoverRelayState(application, httpRequest, httpResponse, relayState, false);
218 hook += "&target=" + encoder->encode(relayState.c_str());
220 catch (std::exception& ex) {
221 m_log.warn("error recovering relay state: %s", ex.what());
225 return make_pair(true, httpResponse.sendRedirect(hook.c_str()));
228 return finalizeResponse(application, httpRequest, httpResponse, relayState);
230 catch (XMLToolingException& ex) {
231 // Recover relay state.
232 if (!relayState.empty()) {
234 recoverRelayState(application, httpRequest, httpResponse, relayState, false);
236 catch (std::exception& rsex) {
237 m_log.warn("error recovering relay state: %s", rsex.what());
239 recoverRelayState(application, httpRequest, httpResponse, relayState, false);
243 // Check for isPassive error condition.
244 const char* sc2 = ex.getProperty("statusCode2");
245 if (sc2 && !strcmp(sc2, "urn:oasis:names:tc:SAML:2.0:status:NoPassive")) {
246 pair<bool,bool> ignore = getBool("ignoreNoPassive", m_configNS.get()); // may be namespace-qualified inside handler element
248 ignore = getBool("ignoreNoPassive"); // try unqualified
249 if (ignore.first && ignore.second && !relayState.empty()) {
250 m_log.debug("ignoring SAML status of NoPassive and redirecting to resource...");
251 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
255 ex.addProperty("RelayState", relayState.c_str());
259 scoped_ptr<TransactionLog::Event> event(SPConfig::getConfig().EventManager.newPlugin(LOGIN_EVENT, nullptr));
260 LoginEvent* error_event = dynamic_cast<LoginEvent*>(event.get());
262 error_event->m_exception = &ex;
263 error_event->m_request = &httpRequest;
264 error_event->m_app = &application;
265 if (policy->getIssuerMetadata())
266 error_event->m_peer = dynamic_cast<const EntityDescriptor*>(policy->getIssuerMetadata()->getParent());
267 auto_ptr_char prot(getProtocolFamily());
268 error_event->m_protocol = prot.get();
269 error_event->m_binding = getString("Binding").second;
270 error_event->m_saml2Response = dynamic_cast<const saml2p::StatusResponseType*>(msg.get());
271 if (!error_event->m_saml2Response)
272 error_event->m_saml1Response = dynamic_cast<const saml1p::Response*>(msg.get());
273 application.getServiceProvider().getTransactionLog()->write(*error_event);
276 m_log.warn("unable to audit event, log event object was of an incorrect type");
279 catch (std::exception& ex2) {
280 m_log.warn("exception auditing event: %s", ex2.what());
283 // If no sign of annotation, try to annotate it now.
284 if (!ex.getProperty("statusCode")) {
285 annotateException(&ex, policy->getIssuerMetadata(), nullptr, false); // wait to throw it
291 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
295 pair<bool,long> AssertionConsumerService::finalizeResponse(
296 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, string& relayState
299 DDF postData = recoverPostData(application, httpRequest, httpResponse, relayState.c_str());
300 DDFJanitor postjan(postData);
301 recoverRelayState(application, httpRequest, httpResponse, relayState);
302 application.limitRedirect(httpRequest, relayState.c_str());
304 // Now redirect to the state value. By now, it should be set to *something* usable.
305 // First check for POST data.
306 if (!postData.islist()) {
307 m_log.debug("ACS returning via redirect to: %s", relayState.c_str());
308 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
311 m_log.debug("ACS returning via POST to: %s", relayState.c_str());
312 return make_pair(true, sendPostResponse(application, httpResponse, relayState.c_str(), postData));
316 void AssertionConsumerService::checkAddress(const Application& application, const HTTPRequest& httpRequest, const char* issuedTo) const
318 if (!issuedTo || !*issuedTo)
321 const PropertySet* props = application.getPropertySet("Sessions");
322 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
323 if (!checkAddress.first)
324 checkAddress.second = true;
326 if (checkAddress.second) {
327 m_log.debug("checking client address");
328 if (httpRequest.getRemoteAddr() != issuedTo) {
329 throw FatalProfileException(
330 "Your client's current address ($client_addr) differs from the one used when you authenticated "
331 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
332 "Please contact your local support staff or help desk for assistance.",
333 namedparams(1, "client_addr", httpRequest.getRemoteAddr().c_str())
341 const XMLCh* AssertionConsumerService::getProtocolFamily() const
343 return m_decoder ? m_decoder->getProtocolFamily() : nullptr;
346 const char* AssertionConsumerService::getType() const
348 return "AssertionConsumerService";
351 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
353 // Initial guess at index to use.
354 pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
355 if (!strncmp(handlerURL, "https", 5))
356 ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
358 ix = getUnsignedInt("index");
362 // Find maximum index in use and go one higher.
363 const vector<saml2md::AssertionConsumerService*>& services = const_cast<const SPSSODescriptor&>(role).getAssertionConsumerServices();
364 if (!services.empty() && ix.second <= services.back()->getIndex().second)
365 ix.second = services.back()->getIndex().second + 1;
367 const char* loc = getString("Location").second;
368 string hurl(handlerURL);
372 auto_ptr_XMLCh widen(hurl.c_str());
374 saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
375 ep->setLocation(widen.get());
376 ep->setBinding(getXMLString("Binding").second);
377 ep->setIndex(ix.second);
378 role.getAssertionConsumerServices().push_back(ep);
381 opensaml::SecurityPolicy* AssertionConsumerService::createSecurityPolicy(
382 const Application& application, const xmltooling::QName* role, bool validate, const char* policyId
385 return new SecurityPolicy(application, role, validate, policyId);
389 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
392 DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
395 virtual ~DummyContext() {
396 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
399 vector<Attribute*>& getResolvedAttributes() {
402 vector<Assertion*>& getResolvedAssertions() {
407 vector<Attribute*> m_attributes;
408 static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
412 vector<Assertion*> DummyContext::m_tokens;
414 ResolutionContext* AssertionConsumerService::resolveAttributes(
415 const Application& application,
416 const saml2md::RoleDescriptor* issuer,
417 const XMLCh* protocol,
418 const saml1::NameIdentifier* v1nameid,
419 const saml2::NameID* nameid,
420 const XMLCh* authncontext_class,
421 const XMLCh* authncontext_decl,
422 const vector<const Assertion*>* tokens
425 return resolveAttributes(
441 ResolutionContext* AssertionConsumerService::resolveAttributes(
442 const Application& application,
443 const GenericRequest* request,
444 const RoleDescriptor* issuer,
445 const XMLCh* protocol,
446 const xmltooling::XMLObject* protmsg,
447 const saml1::NameIdentifier* v1nameid,
448 const saml1::AuthenticationStatement* v1statement,
449 const saml2::NameID* nameid,
450 const saml2::AuthnStatement* statement,
451 const XMLCh* authncontext_class,
452 const XMLCh* authncontext_decl,
453 const vector<const Assertion*>* tokens
456 // First we do the extraction of any pushed information, including from metadata.
457 vector<Attribute*> resolvedAttributes;
458 AttributeExtractor* extractor = application.getAttributeExtractor();
460 Locker extlocker(extractor);
462 pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
464 m_log.debug("extracting metadata-derived attributes...");
466 // We pass nullptr for "issuer" because the IdP isn't the one asserting metadata-based attributes.
467 extractor->extractAttributes(application, request, nullptr, *issuer, resolvedAttributes);
468 for (indirect_iterator<vector<Attribute*>::iterator> a = make_indirect_iterator(resolvedAttributes.begin());
469 a != make_indirect_iterator(resolvedAttributes.end()); ++a) {
470 vector<string>& ids = a->getAliases();
471 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
472 *id = mprefix.second + *id;
475 catch (std::exception& ex) {
476 m_log.error("caught exception extracting attributes: %s", ex.what());
481 m_log.debug("extracting pushed attributes...");
485 extractor->extractAttributes(application, request, issuer, *protmsg, resolvedAttributes);
487 catch (std::exception& ex) {
488 m_log.error("caught exception extracting attributes: %s", ex.what());
492 if (v1nameid || nameid) {
495 extractor->extractAttributes(application, request, issuer, *v1nameid, resolvedAttributes);
497 extractor->extractAttributes(application, request, issuer, *nameid, resolvedAttributes);
499 catch (std::exception& ex) {
500 m_log.error("caught exception extracting attributes: %s", ex.what());
504 if (v1statement || statement) {
507 extractor->extractAttributes(application, request, issuer, *v1statement, resolvedAttributes);
509 extractor->extractAttributes(application, request, issuer, *statement, resolvedAttributes);
511 catch (std::exception& ex) {
512 m_log.error("caught exception extracting attributes: %s", ex.what());
517 for (indirect_iterator<vector<const Assertion*>::const_iterator> t = make_indirect_iterator(tokens->begin());
518 t != make_indirect_iterator(tokens->end()); ++t) {
520 extractor->extractAttributes(application, request, issuer, *t, resolvedAttributes);
522 catch (std::exception& ex) {
523 m_log.error("caught exception extracting attributes: %s", ex.what());
528 AttributeFilter* filter = application.getAttributeFilter();
529 if (filter && !resolvedAttributes.empty()) {
530 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class, authncontext_decl);
531 Locker filtlocker(filter);
533 filter->filterAttributes(fc, resolvedAttributes);
535 catch (std::exception& ex) {
536 m_log.error("caught exception filtering attributes: %s", ex.what());
537 m_log.error("dumping extracted attributes due to filtering exception");
538 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
539 resolvedAttributes.clear();
544 m_log.warn("no AttributeExtractor plugin installed, check log during startup");
548 AttributeResolver* resolver = application.getAttributeResolver();
550 m_log.debug("resolving attributes...");
552 Locker locker(resolver);
553 auto_ptr<ResolutionContext> ctx(
554 resolver->createResolutionContext(
557 issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : nullptr,
566 resolver->resolveAttributes(*ctx);
567 // Copy over any pushed attributes.
568 while (!resolvedAttributes.empty()) {
569 ctx->getResolvedAttributes().push_back(resolvedAttributes.back());
570 resolvedAttributes.pop_back();
572 return ctx.release();
575 catch (std::exception& ex) {
576 m_log.error("attribute resolution failed: %s", ex.what());
579 if (!resolvedAttributes.empty()) {
581 return new DummyContext(resolvedAttributes);
584 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
590 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
592 policy.setMessageID(assertion.getID());
593 policy.setIssueInstant(assertion.getIssueInstantEpoch());
595 if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
596 const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
598 m_log.debug("extracting issuer from SAML 2.0 assertion");
599 policy.setIssuer(a2->getIssuer());
603 const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
605 m_log.debug("extracting issuer from SAML 1.x assertion");
606 policy.setIssuer(a1->getIssuer());
610 if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
611 if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
612 m_log.warn("non-system entity issuer, skipping metadata lookup");
615 m_log.debug("searching metadata for assertion issuer...");
616 pair<const EntityDescriptor*,const RoleDescriptor*> entity;
617 MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
618 mc.entityID_unicode = policy.getIssuer()->getName();
619 mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
620 mc.protocol = protocol;
621 entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
623 auto_ptr_char iname(policy.getIssuer()->getName());
624 m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
626 else if (!entity.second) {
627 m_log.warn("unable to find compatible IdP role in metadata");
630 policy.setIssuerMetadata(entity.second);
635 LoginEvent* AssertionConsumerService::newLoginEvent(const Application& application, const HTTPRequest& request) const
637 if (!SPConfig::getConfig().isEnabled(SPConfig::Logging))
640 auto_ptr<TransactionLog::Event> event(SPConfig::getConfig().EventManager.newPlugin(LOGIN_EVENT, nullptr));
641 LoginEvent* login_event = dynamic_cast<LoginEvent*>(event.get());
643 login_event->m_request = &request;
644 login_event->m_app = &application;
645 login_event->m_binding = getString("Binding").second;
650 m_log.warn("unable to audit event, log event object was of an incorrect type");
653 catch (std::exception& ex) {
654 m_log.warn("exception auditing event: %s", ex.what());
661 void AssertionConsumerService::maintainHistory(
662 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
665 static const char* defProps="; path=/";
666 static const char* sslProps="; path=/; secure";
668 const PropertySet* sessionProps = application.getPropertySet("Sessions");
669 pair<bool,bool> idpHistory = sessionProps->getBool("idpHistory");
671 if (idpHistory.first && idpHistory.second) {
672 pair<bool,const char*> cookieProps = sessionProps->getString("idpHistoryProps");
673 if (!cookieProps.first)
674 cookieProps = sessionProps->getString("cookieProps");
675 if (!cookieProps.first || !strcmp(cookieProps.second, "http"))
676 cookieProps.second = defProps;
677 else if (!strcmp(cookieProps.second, "https"))
678 cookieProps.second = sslProps;
680 // Set an IdP history cookie locally (essentially just a CDC).
681 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
683 // Either leave in memory or set an expiration.
684 pair<bool,unsigned int> days = sessionProps->getUnsignedInt("idpHistoryDays");
685 if (!days.first || days.second == 0) {
686 string c = string(cdc.set(entityID)) + cookieProps.second;
687 response.setCookie(CommonDomainCookie::CDCName, c.c_str());
690 time_t now = time(nullptr) + (days.second * 24 * 60 * 60);
693 struct tm* ptime = gmtime_r(&now,&res);
695 struct tm* ptime = gmtime(&now);
698 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT", ptime);
699 string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
700 response.setCookie(CommonDomainCookie::CDCName, c.c_str());