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/SPConstants.h"
37 # include "attribute/Attribute.h"
38 # include "attribute/filtering/AttributeFilter.h"
39 # include "attribute/filtering/BasicFilteringContext.h"
40 # include "attribute/resolver/AttributeExtractor.h"
41 # include "attribute/resolver/AttributeResolver.h"
42 # include "attribute/resolver/ResolutionContext.h"
43 # include "metadata/MetadataProviderCriteria.h"
44 # include "security/SecurityPolicy.h"
45 # include "security/SecurityPolicyProvider.h"
46 # include <boost/iterator/indirect_iterator.hpp>
47 # include <saml/exceptions.h>
48 # include <saml/SAMLConfig.h>
49 # include <saml/saml1/core/Assertions.h>
50 # include <saml/saml1/core/Protocols.h>
51 # include <saml/saml2/core/Protocols.h>
52 # include <saml/saml2/metadata/Metadata.h>
53 # include <saml/util/CommonDomainCookie.h>
54 using namespace samlconstants;
55 using opensaml::saml2md::MetadataProvider;
56 using opensaml::saml2md::RoleDescriptor;
57 using opensaml::saml2md::EntityDescriptor;
58 using opensaml::saml2md::IDPSSODescriptor;
59 using opensaml::saml2md::SPSSODescriptor;
61 # include "lite/CommonDomainCookie.h"
64 using namespace shibspconstants;
65 using namespace shibsp;
66 using namespace opensaml;
67 using namespace xmltooling;
68 using namespace boost;
71 AssertionConsumerService::AssertionConsumerService(
72 const DOMElement* e, const char* appId, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
73 ) : AbstractHandler(e, log, filter, remapper)
77 string address(appId);
78 address += getString("Location").second;
79 setAddress(address.c_str());
81 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
83 SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
84 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
87 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
92 AssertionConsumerService::~AssertionConsumerService()
96 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
99 SPConfig& conf = SPConfig::getConfig();
101 if (conf.isEnabled(SPConfig::OutOfProcess)) {
102 // When out of process, we run natively and directly process the message.
103 return processMessage(request.getApplication(), request, request);
106 // When not out of process, we remote all the message processing.
107 vector<string> headers(1, "Cookie");
108 headers.push_back("User-Agent");
109 headers.push_back("Accept-Language");
110 DDF out,in = wrap(request, &headers);
111 DDFJanitor jin(in), jout(out);
112 out=request.getServiceProvider().getListenerService()->send(in);
113 return unwrap(request, out);
117 void AssertionConsumerService::receive(DDF& in, ostream& out)
120 const char* aid=in["application_id"].string();
121 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
123 // Something's horribly wrong.
124 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
125 throw ConfigurationException("Unable to locate application for new session, deleted?");
128 // Unpack the request.
129 scoped_ptr<HTTPRequest> req(getRequest(in));
131 // Wrap a response shim.
133 DDFJanitor jout(ret);
134 scoped_ptr<HTTPResponse> resp(getResponse(ret));
136 // Since we're remoted, the result should either be a throw, a false/0 return,
137 // which we just return as an empty structure, or a response/redirect,
138 // which we capture in the facade and send back.
139 processMessage(*app, *req, *resp);
143 pair<bool,long> AssertionConsumerService::processMessage(
144 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
148 // Locate policy key.
149 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
151 policyId = application.getString("policyId"); // unqualified in Application(s) element
153 // Lock metadata for use by policy.
154 Locker metadataLocker(application.getMetadataProvider());
156 // Create the policy.
157 scoped_ptr<opensaml::SecurityPolicy> policy(
158 application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &IDPSSODescriptor::ELEMENT_QNAME, policyId.second)
162 scoped_ptr<XMLObject> msg;
164 // Decode the message and process it in a protocol-specific way.
165 msg.reset(m_decoder->decode(relayState, httpRequest, *(policy.get())));
167 throw BindingException("Failed to decode an SSO protocol response.");
168 DDF postData = recoverPostData(application, httpRequest, httpResponse, relayState.c_str());
169 DDFJanitor postjan(postData);
170 recoverRelayState(application, httpRequest, httpResponse, relayState);
171 limitRelayState(m_log, application, httpRequest, relayState.c_str());
172 implementProtocol(application, httpRequest, httpResponse, *policy, nullptr, *msg);
174 auto_ptr_char issuer(policy->getIssuer() ? policy->getIssuer()->getName() : nullptr);
177 if (issuer.get() && *issuer.get())
178 maintainHistory(application, httpRequest, httpResponse, issuer.get());
180 // Now redirect to the state value. By now, it should be set to *something* usable.
181 // First check for POST data.
182 if (!postData.islist()) {
183 m_log.debug("ACS returning via redirect to: %s", relayState.c_str());
184 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
187 m_log.debug("ACS returning via POST to: %s", relayState.c_str());
188 return make_pair(true, sendPostResponse(application, httpResponse, relayState.c_str(), postData));
191 catch (XMLToolingException& ex) {
192 // Check for isPassive error condition.
193 const char* sc2 = ex.getProperty("statusCode2");
194 if (sc2 && !strcmp(sc2, "urn:oasis:names:tc:SAML:2.0:status:NoPassive")) {
195 pair<bool,bool> ignore = getBool("ignoreNoPassive", m_configNS.get()); // namespace-qualified if inside handler element
196 if (ignore.first && ignore.second && !relayState.empty()) {
197 m_log.debug("ignoring SAML status of NoPassive and redirecting to resource...");
198 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
201 if (!relayState.empty())
202 ex.addProperty("RelayState", relayState.c_str());
206 scoped_ptr<TransactionLog::Event> event(SPConfig::getConfig().EventManager.newPlugin(LOGIN_EVENT, nullptr));
207 LoginEvent* error_event = dynamic_cast<LoginEvent*>(event.get());
209 error_event->m_exception = &ex;
210 error_event->m_request = &httpRequest;
211 error_event->m_app = &application;
212 if (policy->getIssuerMetadata())
213 error_event->m_peer = dynamic_cast<const EntityDescriptor*>(policy->getIssuerMetadata()->getParent());
214 auto_ptr_char prot(getProtocolFamily());
215 error_event->m_protocol = prot.get();
216 error_event->m_binding = getString("Binding").second;
217 error_event->m_saml2Response = dynamic_cast<const saml2p::StatusResponseType*>(msg.get());
218 if (!error_event->m_saml2Response)
219 error_event->m_saml1Response = dynamic_cast<const saml1p::Response*>(msg.get());
220 application.getServiceProvider().getTransactionLog()->write(*error_event);
223 m_log.warn("unable to audit event, log event object was of an incorrect type");
226 catch (std::exception& ex2) {
227 m_log.warn("exception auditing event: %s", ex2.what());
230 // If no sign of annotation, try to annotate it now.
231 if (!ex.getProperty("statusCode")) {
232 annotateException(&ex, policy->getIssuerMetadata(), nullptr, false); // wait to throw it
238 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
242 void AssertionConsumerService::checkAddress(const Application& application, const HTTPRequest& httpRequest, const char* issuedTo) const
244 if (!issuedTo || !*issuedTo)
247 const PropertySet* props = application.getPropertySet("Sessions");
248 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
249 if (!checkAddress.first)
250 checkAddress.second = true;
252 if (checkAddress.second) {
253 m_log.debug("checking client address");
254 if (httpRequest.getRemoteAddr() != issuedTo) {
255 throw FatalProfileException(
256 "Your client's current address ($client_addr) differs from the one used when you authenticated "
257 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
258 "Please contact your local support staff or help desk for assistance.",
259 namedparams(1, "client_addr", httpRequest.getRemoteAddr().c_str())
267 const XMLCh* AssertionConsumerService::getProtocolFamily() const
269 return m_decoder ? m_decoder->getProtocolFamily() : nullptr;
272 const char* AssertionConsumerService::getType() const
274 return "AssertionConsumerService";
277 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
279 // Initial guess at index to use.
280 pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
281 if (!strncmp(handlerURL, "https", 5))
282 ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
284 ix = getUnsignedInt("index");
288 // Find maximum index in use and go one higher.
289 const vector<saml2md::AssertionConsumerService*>& services = const_cast<const SPSSODescriptor&>(role).getAssertionConsumerServices();
290 if (!services.empty() && ix.second <= services.back()->getIndex().second)
291 ix.second = services.back()->getIndex().second + 1;
293 const char* loc = getString("Location").second;
294 string hurl(handlerURL);
298 auto_ptr_XMLCh widen(hurl.c_str());
300 saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
301 ep->setLocation(widen.get());
302 ep->setBinding(getXMLString("Binding").second);
303 ep->setIndex(ix.second);
304 role.getAssertionConsumerServices().push_back(ep);
307 opensaml::SecurityPolicy* AssertionConsumerService::createSecurityPolicy(
308 const Application& application, const xmltooling::QName* role, bool validate, const char* policyId
311 return new SecurityPolicy(application, role, validate, policyId);
314 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
317 DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
320 virtual ~DummyContext() {
321 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
324 vector<Attribute*>& getResolvedAttributes() {
327 vector<Assertion*>& getResolvedAssertions() {
332 vector<Attribute*> m_attributes;
333 static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
336 vector<Assertion*> DummyContext::m_tokens;
338 ResolutionContext* AssertionConsumerService::resolveAttributes(
339 const Application& application,
340 const saml2md::RoleDescriptor* issuer,
341 const XMLCh* protocol,
342 const saml1::NameIdentifier* v1nameid,
343 const saml2::NameID* nameid,
344 const XMLCh* authncontext_class,
345 const XMLCh* authncontext_decl,
346 const vector<const Assertion*>* tokens
349 return resolveAttributes(
364 ResolutionContext* AssertionConsumerService::resolveAttributes(
365 const Application& application,
366 const GenericRequest* request,
367 const saml2md::RoleDescriptor* issuer,
368 const XMLCh* protocol,
369 const saml1::NameIdentifier* v1nameid,
370 const saml1::AuthenticationStatement* v1statement,
371 const saml2::NameID* nameid,
372 const saml2::AuthnStatement* statement,
373 const XMLCh* authncontext_class,
374 const XMLCh* authncontext_decl,
375 const vector<const Assertion*>* tokens
378 // First we do the extraction of any pushed information, including from metadata.
379 vector<Attribute*> resolvedAttributes;
380 AttributeExtractor* extractor = application.getAttributeExtractor();
382 Locker extlocker(extractor);
384 pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
386 m_log.debug("extracting metadata-derived attributes...");
388 // We pass nullptr for "issuer" because the IdP isn't the one asserting metadata-based attributes.
389 extractor->extractAttributes(application, request, nullptr, *issuer, resolvedAttributes);
390 for (indirect_iterator<vector<Attribute*>::iterator> a = make_indirect_iterator(resolvedAttributes.begin());
391 a != make_indirect_iterator(resolvedAttributes.end()); ++a) {
392 vector<string>& ids = a->getAliases();
393 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
394 *id = mprefix.second + *id;
397 catch (std::exception& ex) {
398 m_log.error("caught exception extracting attributes: %s", ex.what());
403 m_log.debug("extracting pushed attributes...");
405 if (v1nameid || nameid) {
408 extractor->extractAttributes(application, request, issuer, *v1nameid, resolvedAttributes);
410 extractor->extractAttributes(application, request, issuer, *nameid, resolvedAttributes);
412 catch (std::exception& ex) {
413 m_log.error("caught exception extracting attributes: %s", ex.what());
417 if (v1statement || statement) {
420 extractor->extractAttributes(application, request, issuer, *v1statement, resolvedAttributes);
422 extractor->extractAttributes(application, request, issuer, *statement, resolvedAttributes);
424 catch (std::exception& ex) {
425 m_log.error("caught exception extracting attributes: %s", ex.what());
430 for (indirect_iterator<vector<const Assertion*>::const_iterator> t = make_indirect_iterator(tokens->begin());
431 t != make_indirect_iterator(tokens->end()); ++t) {
433 extractor->extractAttributes(application, request, issuer, *t, resolvedAttributes);
435 catch (std::exception& ex) {
436 m_log.error("caught exception extracting attributes: %s", ex.what());
441 AttributeFilter* filter = application.getAttributeFilter();
442 if (filter && !resolvedAttributes.empty()) {
443 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
444 Locker filtlocker(filter);
446 filter->filterAttributes(fc, resolvedAttributes);
448 catch (std::exception& ex) {
449 m_log.error("caught exception filtering attributes: %s", ex.what());
450 m_log.error("dumping extracted attributes due to filtering exception");
451 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
452 resolvedAttributes.clear();
457 m_log.warn("no AttributeExtractor plugin installed, check log during startup");
461 AttributeResolver* resolver = application.getAttributeResolver();
463 m_log.debug("resolving attributes...");
465 Locker locker(resolver);
466 auto_ptr<ResolutionContext> ctx(
467 resolver->createResolutionContext(
469 issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : nullptr,
478 resolver->resolveAttributes(*ctx);
479 // Copy over any pushed attributes.
480 while (!resolvedAttributes.empty()) {
481 ctx->getResolvedAttributes().push_back(resolvedAttributes.back());
482 resolvedAttributes.pop_back();
484 return ctx.release();
487 catch (std::exception& ex) {
488 m_log.error("attribute resolution failed: %s", ex.what());
491 if (!resolvedAttributes.empty()) {
493 return new DummyContext(resolvedAttributes);
496 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
502 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
504 policy.setMessageID(assertion.getID());
505 policy.setIssueInstant(assertion.getIssueInstantEpoch());
507 if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
508 const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
510 m_log.debug("extracting issuer from SAML 2.0 assertion");
511 policy.setIssuer(a2->getIssuer());
515 const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
517 m_log.debug("extracting issuer from SAML 1.x assertion");
518 policy.setIssuer(a1->getIssuer());
522 if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
523 if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
524 m_log.warn("non-system entity issuer, skipping metadata lookup");
527 m_log.debug("searching metadata for assertion issuer...");
528 pair<const EntityDescriptor*,const RoleDescriptor*> entity;
529 MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
530 mc.entityID_unicode = policy.getIssuer()->getName();
531 mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
532 mc.protocol = protocol;
533 entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
535 auto_ptr_char iname(policy.getIssuer()->getName());
536 m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
538 else if (!entity.second) {
539 m_log.warn("unable to find compatible IdP role in metadata");
542 policy.setIssuerMetadata(entity.second);
547 LoginEvent* AssertionConsumerService::newLoginEvent(const Application& application, const xmltooling::HTTPRequest& request) const
549 if (!SPConfig::getConfig().isEnabled(SPConfig::Logging))
552 auto_ptr<TransactionLog::Event> event(SPConfig::getConfig().EventManager.newPlugin(LOGIN_EVENT, nullptr));
553 LoginEvent* login_event = dynamic_cast<LoginEvent*>(event.get());
555 login_event->m_request = &request;
556 login_event->m_app = &application;
557 login_event->m_binding = getString("Binding").second;
562 m_log.warn("unable to audit event, log event object was of an incorrect type");
565 catch (std::exception& ex) {
566 m_log.warn("exception auditing event: %s", ex.what());
573 void AssertionConsumerService::maintainHistory(
574 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
577 static const char* defProps="; path=/";
579 const PropertySet* sessionProps=application.getPropertySet("Sessions");
580 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
582 if (idpHistory.first && idpHistory.second) {
583 pair<bool,const char*> cookieProps=sessionProps->getString("idpHistoryProps");
584 if (!cookieProps.first)
585 cookieProps=sessionProps->getString("cookieProps");
586 if (!cookieProps.first)
587 cookieProps.second=defProps;
589 // Set an IdP history cookie locally (essentially just a CDC).
590 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
592 // Either leave in memory or set an expiration.
593 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
594 if (!days.first || days.second==0) {
595 string c = string(cdc.set(entityID)) + cookieProps.second;
596 response.setCookie(CommonDomainCookie::CDCName, c.c_str());
599 time_t now=time(nullptr) + (days.second * 24 * 60 * 60);
602 struct tm* ptime=gmtime_r(&now,&res);
604 struct tm* ptime=gmtime(&now);
607 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
608 string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
609 response.setCookie(CommonDomainCookie::CDCName, c.c_str());