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()); // namespace-qualified if inside handler element
166 prop = application.getString("policyId"); // unqualified in Application(s) element
168 // Lock metadata for use by policy.
169 Locker metadataLocker(application.getMetadataProvider());
171 // Create the policy.
172 scoped_ptr<opensaml::SecurityPolicy> policy(
173 application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(
174 application, &IDPSSODescriptor::ELEMENT_QNAME, prop.second
179 scoped_ptr<XMLObject> msg;
181 // Decode the message and process it in a protocol-specific way.
182 msg.reset(m_decoder->decode(relayState, httpRequest, *(policy.get())));
184 throw BindingException("Failed to decode an SSO protocol response.");
185 implementProtocol(application, httpRequest, httpResponse, *policy, nullptr, *msg);
188 auto_ptr_char issuer(policy->getIssuer() ? policy->getIssuer()->getName() : nullptr);
189 if (issuer.get() && *issuer.get())
190 maintainHistory(application, httpRequest, httpResponse, issuer.get());
192 const EntityDescriptor* entity =
193 dynamic_cast<const EntityDescriptor*>(policy->getIssuerMetadata() ? policy->getIssuerMetadata()->getParent() : nullptr);
194 prop = application.getRelyingParty(entity)->getString("sessionHook");
196 string hook(prop.second);
197 httpRequest.absolutize(hook);
199 // Compute the return URL. We use a self-referential link plus a hook indicator to break the cycle
200 // and the relay state.
201 const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
202 string returnURL = httpRequest.getRequestURL();
203 returnURL = returnURL.substr(0, returnURL.find('?')) + "?hook=1";
204 if (!relayState.empty())
205 returnURL += "&target=" + encoder->encode(relayState.c_str());
206 if (hook.find('?') == string::npos)
210 hook += "return=" + encoder->encode(returnURL.c_str());
212 // Add the translated target resource in case it's of interest.
213 if (!relayState.empty()) {
215 recoverRelayState(application, httpRequest, httpResponse, relayState, false);
216 hook += "&target=" + encoder->encode(relayState.c_str());
218 catch (std::exception& ex) {
219 m_log.warn("error recovering relay state: %s", ex.what());
223 return make_pair(true, httpResponse.sendRedirect(hook.c_str()));
226 return finalizeResponse(application, httpRequest, httpResponse, relayState);
228 catch (XMLToolingException& ex) {
229 // Check for isPassive error condition.
230 const char* sc2 = ex.getProperty("statusCode2");
231 if (sc2 && !strcmp(sc2, "urn:oasis:names:tc:SAML:2.0:status:NoPassive")) {
232 pair<bool,bool> ignore = getBool("ignoreNoPassive", m_configNS.get()); // namespace-qualified if inside handler element
233 if (ignore.first && ignore.second && !relayState.empty()) {
234 m_log.debug("ignoring SAML status of NoPassive and redirecting to resource...");
235 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
238 if (!relayState.empty()) {
240 recoverRelayState(application, httpRequest, httpResponse, relayState, false);
242 catch (std::exception& rsex) {
243 m_log.warn("error recovering relay state: %s", rsex.what());
245 ex.addProperty("RelayState", relayState.c_str());
250 scoped_ptr<TransactionLog::Event> event(SPConfig::getConfig().EventManager.newPlugin(LOGIN_EVENT, nullptr));
251 LoginEvent* error_event = dynamic_cast<LoginEvent*>(event.get());
253 error_event->m_exception = &ex;
254 error_event->m_request = &httpRequest;
255 error_event->m_app = &application;
256 if (policy->getIssuerMetadata())
257 error_event->m_peer = dynamic_cast<const EntityDescriptor*>(policy->getIssuerMetadata()->getParent());
258 auto_ptr_char prot(getProtocolFamily());
259 error_event->m_protocol = prot.get();
260 error_event->m_binding = getString("Binding").second;
261 error_event->m_saml2Response = dynamic_cast<const saml2p::StatusResponseType*>(msg.get());
262 if (!error_event->m_saml2Response)
263 error_event->m_saml1Response = dynamic_cast<const saml1p::Response*>(msg.get());
264 application.getServiceProvider().getTransactionLog()->write(*error_event);
267 m_log.warn("unable to audit event, log event object was of an incorrect type");
270 catch (std::exception& ex2) {
271 m_log.warn("exception auditing event: %s", ex2.what());
274 // If no sign of annotation, try to annotate it now.
275 if (!ex.getProperty("statusCode")) {
276 annotateException(&ex, policy->getIssuerMetadata(), nullptr, false); // wait to throw it
282 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
286 pair<bool,long> AssertionConsumerService::finalizeResponse(
287 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse, string& relayState
290 DDF postData = recoverPostData(application, httpRequest, httpResponse, relayState.c_str());
291 DDFJanitor postjan(postData);
292 recoverRelayState(application, httpRequest, httpResponse, relayState);
293 application.limitRedirect(httpRequest, relayState.c_str());
295 // Now redirect to the state value. By now, it should be set to *something* usable.
296 // First check for POST data.
297 if (!postData.islist()) {
298 m_log.debug("ACS returning via redirect to: %s", relayState.c_str());
299 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
302 m_log.debug("ACS returning via POST to: %s", relayState.c_str());
303 return make_pair(true, sendPostResponse(application, httpResponse, relayState.c_str(), postData));
307 void AssertionConsumerService::checkAddress(const Application& application, const HTTPRequest& httpRequest, const char* issuedTo) const
309 if (!issuedTo || !*issuedTo)
312 const PropertySet* props = application.getPropertySet("Sessions");
313 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
314 if (!checkAddress.first)
315 checkAddress.second = true;
317 if (checkAddress.second) {
318 m_log.debug("checking client address");
319 if (httpRequest.getRemoteAddr() != issuedTo) {
320 throw FatalProfileException(
321 "Your client's current address ($client_addr) differs from the one used when you authenticated "
322 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
323 "Please contact your local support staff or help desk for assistance.",
324 namedparams(1, "client_addr", httpRequest.getRemoteAddr().c_str())
332 const XMLCh* AssertionConsumerService::getProtocolFamily() const
334 return m_decoder ? m_decoder->getProtocolFamily() : nullptr;
337 const char* AssertionConsumerService::getType() const
339 return "AssertionConsumerService";
342 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
344 // Initial guess at index to use.
345 pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
346 if (!strncmp(handlerURL, "https", 5))
347 ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
349 ix = getUnsignedInt("index");
353 // Find maximum index in use and go one higher.
354 const vector<saml2md::AssertionConsumerService*>& services = const_cast<const SPSSODescriptor&>(role).getAssertionConsumerServices();
355 if (!services.empty() && ix.second <= services.back()->getIndex().second)
356 ix.second = services.back()->getIndex().second + 1;
358 const char* loc = getString("Location").second;
359 string hurl(handlerURL);
363 auto_ptr_XMLCh widen(hurl.c_str());
365 saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
366 ep->setLocation(widen.get());
367 ep->setBinding(getXMLString("Binding").second);
368 ep->setIndex(ix.second);
369 role.getAssertionConsumerServices().push_back(ep);
372 opensaml::SecurityPolicy* AssertionConsumerService::createSecurityPolicy(
373 const Application& application, const xmltooling::QName* role, bool validate, const char* policyId
376 return new SecurityPolicy(application, role, validate, policyId);
380 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
383 DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
386 virtual ~DummyContext() {
387 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
390 vector<Attribute*>& getResolvedAttributes() {
393 vector<Assertion*>& getResolvedAssertions() {
398 vector<Attribute*> m_attributes;
399 static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
403 vector<Assertion*> DummyContext::m_tokens;
405 ResolutionContext* AssertionConsumerService::resolveAttributes(
406 const Application& application,
407 const saml2md::RoleDescriptor* issuer,
408 const XMLCh* protocol,
409 const saml1::NameIdentifier* v1nameid,
410 const saml2::NameID* nameid,
411 const XMLCh* authncontext_class,
412 const XMLCh* authncontext_decl,
413 const vector<const Assertion*>* tokens
416 return resolveAttributes(
432 ResolutionContext* AssertionConsumerService::resolveAttributes(
433 const Application& application,
434 const GenericRequest* request,
435 const RoleDescriptor* issuer,
436 const XMLCh* protocol,
437 const xmltooling::XMLObject* protmsg,
438 const saml1::NameIdentifier* v1nameid,
439 const saml1::AuthenticationStatement* v1statement,
440 const saml2::NameID* nameid,
441 const saml2::AuthnStatement* statement,
442 const XMLCh* authncontext_class,
443 const XMLCh* authncontext_decl,
444 const vector<const Assertion*>* tokens
447 // First we do the extraction of any pushed information, including from metadata.
448 vector<Attribute*> resolvedAttributes;
449 AttributeExtractor* extractor = application.getAttributeExtractor();
451 Locker extlocker(extractor);
453 pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
455 m_log.debug("extracting metadata-derived attributes...");
457 // We pass nullptr for "issuer" because the IdP isn't the one asserting metadata-based attributes.
458 extractor->extractAttributes(application, request, nullptr, *issuer, resolvedAttributes);
459 for (indirect_iterator<vector<Attribute*>::iterator> a = make_indirect_iterator(resolvedAttributes.begin());
460 a != make_indirect_iterator(resolvedAttributes.end()); ++a) {
461 vector<string>& ids = a->getAliases();
462 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
463 *id = mprefix.second + *id;
466 catch (std::exception& ex) {
467 m_log.error("caught exception extracting attributes: %s", ex.what());
472 m_log.debug("extracting pushed attributes...");
476 extractor->extractAttributes(application, request, issuer, *protmsg, resolvedAttributes);
478 catch (std::exception& ex) {
479 m_log.error("caught exception extracting attributes: %s", ex.what());
483 if (v1nameid || nameid) {
486 extractor->extractAttributes(application, request, issuer, *v1nameid, resolvedAttributes);
488 extractor->extractAttributes(application, request, issuer, *nameid, resolvedAttributes);
490 catch (std::exception& ex) {
491 m_log.error("caught exception extracting attributes: %s", ex.what());
495 if (v1statement || statement) {
498 extractor->extractAttributes(application, request, issuer, *v1statement, resolvedAttributes);
500 extractor->extractAttributes(application, request, issuer, *statement, resolvedAttributes);
502 catch (std::exception& ex) {
503 m_log.error("caught exception extracting attributes: %s", ex.what());
508 for (indirect_iterator<vector<const Assertion*>::const_iterator> t = make_indirect_iterator(tokens->begin());
509 t != make_indirect_iterator(tokens->end()); ++t) {
511 extractor->extractAttributes(application, request, issuer, *t, resolvedAttributes);
513 catch (std::exception& ex) {
514 m_log.error("caught exception extracting attributes: %s", ex.what());
519 AttributeFilter* filter = application.getAttributeFilter();
520 if (filter && !resolvedAttributes.empty()) {
521 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class, authncontext_decl);
522 Locker filtlocker(filter);
524 filter->filterAttributes(fc, resolvedAttributes);
526 catch (std::exception& ex) {
527 m_log.error("caught exception filtering attributes: %s", ex.what());
528 m_log.error("dumping extracted attributes due to filtering exception");
529 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
530 resolvedAttributes.clear();
535 m_log.warn("no AttributeExtractor plugin installed, check log during startup");
539 AttributeResolver* resolver = application.getAttributeResolver();
541 m_log.debug("resolving attributes...");
543 Locker locker(resolver);
544 auto_ptr<ResolutionContext> ctx(
545 resolver->createResolutionContext(
548 issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : nullptr,
557 resolver->resolveAttributes(*ctx);
558 // Copy over any pushed attributes.
559 while (!resolvedAttributes.empty()) {
560 ctx->getResolvedAttributes().push_back(resolvedAttributes.back());
561 resolvedAttributes.pop_back();
563 return ctx.release();
566 catch (std::exception& ex) {
567 m_log.error("attribute resolution failed: %s", ex.what());
570 if (!resolvedAttributes.empty()) {
572 return new DummyContext(resolvedAttributes);
575 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
581 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
583 policy.setMessageID(assertion.getID());
584 policy.setIssueInstant(assertion.getIssueInstantEpoch());
586 if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
587 const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
589 m_log.debug("extracting issuer from SAML 2.0 assertion");
590 policy.setIssuer(a2->getIssuer());
594 const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
596 m_log.debug("extracting issuer from SAML 1.x assertion");
597 policy.setIssuer(a1->getIssuer());
601 if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
602 if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
603 m_log.warn("non-system entity issuer, skipping metadata lookup");
606 m_log.debug("searching metadata for assertion issuer...");
607 pair<const EntityDescriptor*,const RoleDescriptor*> entity;
608 MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
609 mc.entityID_unicode = policy.getIssuer()->getName();
610 mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
611 mc.protocol = protocol;
612 entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
614 auto_ptr_char iname(policy.getIssuer()->getName());
615 m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
617 else if (!entity.second) {
618 m_log.warn("unable to find compatible IdP role in metadata");
621 policy.setIssuerMetadata(entity.second);
626 LoginEvent* AssertionConsumerService::newLoginEvent(const Application& application, const HTTPRequest& request) const
628 if (!SPConfig::getConfig().isEnabled(SPConfig::Logging))
631 auto_ptr<TransactionLog::Event> event(SPConfig::getConfig().EventManager.newPlugin(LOGIN_EVENT, nullptr));
632 LoginEvent* login_event = dynamic_cast<LoginEvent*>(event.get());
634 login_event->m_request = &request;
635 login_event->m_app = &application;
636 login_event->m_binding = getString("Binding").second;
641 m_log.warn("unable to audit event, log event object was of an incorrect type");
644 catch (std::exception& ex) {
645 m_log.warn("exception auditing event: %s", ex.what());
652 void AssertionConsumerService::maintainHistory(
653 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
656 static const char* defProps="; path=/";
657 static const char* sslProps="; path=/; secure";
659 const PropertySet* sessionProps = application.getPropertySet("Sessions");
660 pair<bool,bool> idpHistory = sessionProps->getBool("idpHistory");
662 if (idpHistory.first && idpHistory.second) {
663 pair<bool,const char*> cookieProps = sessionProps->getString("idpHistoryProps");
664 if (!cookieProps.first)
665 cookieProps = sessionProps->getString("cookieProps");
666 if (!cookieProps.first || !strcmp(cookieProps.second, "http"))
667 cookieProps.second = defProps;
668 else if (!strcmp(cookieProps.second, "https"))
669 cookieProps.second = sslProps;
671 // Set an IdP history cookie locally (essentially just a CDC).
672 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
674 // Either leave in memory or set an expiration.
675 pair<bool,unsigned int> days = sessionProps->getUnsignedInt("idpHistoryDays");
676 if (!days.first || days.second == 0) {
677 string c = string(cdc.set(entityID)) + cookieProps.second;
678 response.setCookie(CommonDomainCookie::CDCName, c.c_str());
681 time_t now = time(nullptr) + (days.second * 24 * 60 * 60);
684 struct tm* ptime = gmtime_r(&now,&res);
686 struct tm* ptime = gmtime(&now);
689 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT", ptime);
690 string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
691 response.setCookie(CommonDomainCookie::CDCName, c.c_str());