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 <saml/exceptions.h>
47 # include <saml/SAMLConfig.h>
48 # include <saml/saml1/core/Assertions.h>
49 # include <saml/saml2/metadata/Metadata.h>
50 # include <saml/util/CommonDomainCookie.h>
51 using namespace samlconstants;
52 using opensaml::saml2md::MetadataProvider;
53 using opensaml::saml2md::RoleDescriptor;
54 using opensaml::saml2md::EntityDescriptor;
55 using opensaml::saml2md::IDPSSODescriptor;
56 using opensaml::saml2md::SPSSODescriptor;
58 # include "lite/CommonDomainCookie.h"
61 using namespace shibspconstants;
62 using namespace shibsp;
63 using namespace opensaml;
64 using namespace xmltooling;
67 AssertionConsumerService::AssertionConsumerService(
68 const DOMElement* e, const char* appId, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
69 ) : AbstractHandler(e, log, filter, remapper)
71 ,m_decoder(nullptr), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
76 string address(appId);
77 address += getString("Location").second;
78 setAddress(address.c_str());
80 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
81 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
82 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
84 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
89 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 DDF out,in = wrap(request, &headers);
109 DDFJanitor jin(in), jout(out);
110 out=request.getServiceProvider().getListenerService()->send(in);
111 return unwrap(request, out);
115 void AssertionConsumerService::receive(DDF& in, ostream& out)
118 const char* aid=in["application_id"].string();
119 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
121 // Something's horribly wrong.
122 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
123 throw ConfigurationException("Unable to locate application for new session, deleted?");
126 // Unpack the request.
127 auto_ptr<HTTPRequest> req(getRequest(in));
129 // Wrap a response shim.
131 DDFJanitor jout(ret);
132 auto_ptr<HTTPResponse> resp(getResponse(ret));
134 // Since we're remoted, the result should either be a throw, a false/0 return,
135 // which we just return as an empty structure, or a response/redirect,
136 // which we capture in the facade and send back.
137 processMessage(*app, *req.get(), *resp.get());
141 pair<bool,long> AssertionConsumerService::processMessage(
142 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
146 // Locate policy key.
147 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
149 policyId = application.getString("policyId"); // unqualified in Application(s) element
151 // Lock metadata for use by policy.
152 Locker metadataLocker(application.getMetadataProvider());
154 // Create the policy.
155 auto_ptr<opensaml::SecurityPolicy> policy(
156 application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &m_role, policyId.second)
160 bool relayStateOK = true;
162 // Decode the message and process it in a protocol-specific way.
163 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, *(policy.get())));
165 throw BindingException("Failed to decode an SSO protocol response.");
166 DDF postData = recoverPostData(application, httpRequest, httpResponse, relayState.c_str());
167 DDFJanitor postjan(postData);
168 recoverRelayState(application, httpRequest, httpResponse, relayState);
169 limitRelayState(m_log, application, httpRequest, relayState.c_str());
170 implementProtocol(application, httpRequest, httpResponse, *(policy.get()), NULL, *msg.get());
172 auto_ptr_char issuer(policy->getIssuer() ? policy->getIssuer()->getName() : nullptr);
175 if (issuer.get() && *issuer.get())
176 maintainHistory(application, httpRequest, httpResponse, issuer.get());
178 // Now redirect to the state value. By now, it should be set to *something* usable.
179 // First check for POST data.
180 if (!postData.islist()) {
181 m_log.debug("ACS returning via redirect to: %s", relayState.c_str());
182 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
185 m_log.debug("ACS returning via POST to: %s", relayState.c_str());
186 return make_pair(true, sendPostResponse(application, httpResponse, relayState.c_str(), postData));
189 catch (XMLToolingException& ex) {
191 // Check for isPassive error condition.
192 const char* sc2 = ex.getProperty("statusCode2");
193 if (sc2 && !strcmp(sc2, "urn:oasis:names:tc:SAML:2.0:status:NoPassive")) {
194 pair<bool,bool> ignore = getBool("ignoreNoPassive", m_configNS.get()); // namespace-qualified if inside handler element
195 if (ignore.first && ignore.second && !relayState.empty()) {
196 m_log.debug("ignoring SAML status of NoPassive and redirecting to resource...");
197 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
201 if (!relayState.empty())
202 ex.addProperty("RelayState", relayState.c_str());
206 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
210 void AssertionConsumerService::checkAddress(const Application& application, const HTTPRequest& httpRequest, const char* issuedTo) const
212 if (!issuedTo || !*issuedTo)
215 const PropertySet* props=application.getPropertySet("Sessions");
216 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
217 if (!checkAddress.first)
218 checkAddress.second=true;
220 if (checkAddress.second) {
221 m_log.debug("checking client address");
222 if (httpRequest.getRemoteAddr() != issuedTo) {
223 throw FatalProfileException(
224 "Your client's current address ($client_addr) differs from the one used when you authenticated "
225 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
226 "Please contact your local support staff or help desk for assistance.",
227 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
235 const XMLCh* AssertionConsumerService::getProtocolFamily() const
237 return m_decoder ? m_decoder->getProtocolFamily() : nullptr;
240 const char* AssertionConsumerService::getType() const
242 return "AssertionConsumerService";
245 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
247 // Initial guess at index to use.
248 pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
249 if (!strncmp(handlerURL, "https", 5))
250 ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
252 ix = getUnsignedInt("index");
256 // Find maximum index in use and go one higher.
257 const vector<saml2md::AssertionConsumerService*>& services = const_cast<const SPSSODescriptor&>(role).getAssertionConsumerServices();
258 if (!services.empty() && ix.second <= services.back()->getIndex().second)
259 ix.second = services.back()->getIndex().second + 1;
261 const char* loc = getString("Location").second;
262 string hurl(handlerURL);
266 auto_ptr_XMLCh widen(hurl.c_str());
268 saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
269 ep->setLocation(widen.get());
270 ep->setBinding(getXMLString("Binding").second);
271 ep->setIndex(ix.second);
272 role.getAssertionConsumerServices().push_back(ep);
275 opensaml::SecurityPolicy* AssertionConsumerService::createSecurityPolicy(
276 const Application& application, const xmltooling::QName* role, bool validate, const char* policyId
279 return new SecurityPolicy(application, role, validate, policyId);
282 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
285 DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
288 virtual ~DummyContext() {
289 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
292 vector<Attribute*>& getResolvedAttributes() {
295 vector<Assertion*>& getResolvedAssertions() {
300 vector<Attribute*> m_attributes;
301 static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
304 vector<Assertion*> DummyContext::m_tokens;
306 ResolutionContext* AssertionConsumerService::resolveAttributes(
307 const Application& application,
308 const saml2md::RoleDescriptor* issuer,
309 const XMLCh* protocol,
310 const saml1::NameIdentifier* v1nameid,
311 const saml2::NameID* nameid,
312 const XMLCh* authncontext_class,
313 const XMLCh* authncontext_decl,
314 const vector<const Assertion*>* tokens
317 return resolveAttributes(
331 ResolutionContext* AssertionConsumerService::resolveAttributes(
332 const Application& application,
333 const saml2md::RoleDescriptor* issuer,
334 const XMLCh* protocol,
335 const saml1::NameIdentifier* v1nameid,
336 const saml1::AuthenticationStatement* v1statement,
337 const saml2::NameID* nameid,
338 const saml2::AuthnStatement* statement,
339 const XMLCh* authncontext_class,
340 const XMLCh* authncontext_decl,
341 const vector<const Assertion*>* tokens
344 // First we do the extraction of any pushed information, including from metadata.
345 vector<Attribute*> resolvedAttributes;
346 AttributeExtractor* extractor = application.getAttributeExtractor();
348 Locker extlocker(extractor);
350 pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
352 m_log.debug("extracting metadata-derived attributes...");
354 // We pass nullptr for "issuer" because the IdP isn't the one asserting metadata-based attributes.
355 extractor->extractAttributes(application, nullptr, *issuer, resolvedAttributes);
356 for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
357 vector<string>& ids = (*a)->getAliases();
358 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
359 *id = mprefix.second + *id;
362 catch (exception& ex) {
363 m_log.error("caught exception extracting attributes: %s", ex.what());
368 m_log.debug("extracting pushed attributes...");
370 if (v1nameid || nameid) {
373 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
375 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
377 catch (exception& ex) {
378 m_log.error("caught exception extracting attributes: %s", ex.what());
382 if (v1statement || statement) {
385 extractor->extractAttributes(application, issuer, *v1statement, resolvedAttributes);
387 extractor->extractAttributes(application, issuer, *statement, resolvedAttributes);
389 catch (exception& ex) {
390 m_log.error("caught exception extracting attributes: %s", ex.what());
395 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
397 extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
399 catch (exception& ex) {
400 m_log.error("caught exception extracting attributes: %s", ex.what());
405 AttributeFilter* filter = application.getAttributeFilter();
406 if (filter && !resolvedAttributes.empty()) {
407 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
408 Locker filtlocker(filter);
410 filter->filterAttributes(fc, resolvedAttributes);
412 catch (exception& ex) {
413 m_log.error("caught exception filtering attributes: %s", ex.what());
414 m_log.error("dumping extracted attributes due to filtering exception");
415 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
416 resolvedAttributes.clear();
421 m_log.warn("no AttributeExtractor plugin installed, check log during startup");
425 AttributeResolver* resolver = application.getAttributeResolver();
427 m_log.debug("resolving attributes...");
429 Locker locker(resolver);
430 auto_ptr<ResolutionContext> ctx(
431 resolver->createResolutionContext(
433 issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : nullptr,
442 resolver->resolveAttributes(*ctx.get());
443 // Copy over any pushed attributes.
444 if (!resolvedAttributes.empty())
445 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
446 return ctx.release();
449 catch (exception& ex) {
450 m_log.error("attribute resolution failed: %s", ex.what());
453 if (!resolvedAttributes.empty())
454 return new DummyContext(resolvedAttributes);
458 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
460 policy.setMessageID(assertion.getID());
461 policy.setIssueInstant(assertion.getIssueInstantEpoch());
463 if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
464 const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
466 m_log.debug("extracting issuer from SAML 2.0 assertion");
467 policy.setIssuer(a2->getIssuer());
471 const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
473 m_log.debug("extracting issuer from SAML 1.x assertion");
474 policy.setIssuer(a1->getIssuer());
478 if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
479 if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
480 m_log.warn("non-system entity issuer, skipping metadata lookup");
483 m_log.debug("searching metadata for assertion issuer...");
484 pair<const EntityDescriptor*,const RoleDescriptor*> entity;
485 MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
486 mc.entityID_unicode = policy.getIssuer()->getName();
487 mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
488 mc.protocol = protocol;
489 entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
491 auto_ptr_char iname(policy.getIssuer()->getName());
492 m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
494 else if (!entity.second) {
495 m_log.warn("unable to find compatible IdP role in metadata");
498 policy.setIssuerMetadata(entity.second);
505 void AssertionConsumerService::maintainHistory(
506 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
509 static const char* defProps="; path=/";
511 const PropertySet* sessionProps=application.getPropertySet("Sessions");
512 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
514 if (idpHistory.first && idpHistory.second) {
515 pair<bool,const char*> cookieProps=sessionProps->getString("idpHistoryProps");
516 if (!cookieProps.first)
517 cookieProps=sessionProps->getString("cookieProps");
518 if (!cookieProps.first)
519 cookieProps.second=defProps;
521 // Set an IdP history cookie locally (essentially just a CDC).
522 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
524 // Either leave in memory or set an expiration.
525 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
526 if (!days.first || days.second==0) {
527 string c = string(cdc.set(entityID)) + cookieProps.second;
528 response.setCookie(CommonDomainCookie::CDCName, c.c_str());
531 time_t now=time(nullptr) + (days.second * 24 * 60 * 60);
534 struct tm* ptime=gmtime_r(&now,&res);
536 struct tm* ptime=gmtime(&now);
539 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
540 string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
541 response.setCookie(CommonDomainCookie::CDCName, c.c_str());