2 * Copyright 2001-2010 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 "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "SPRequest.h"
28 #include "handler/AssertionConsumerService.h"
29 #include "util/SPConstants.h"
33 # include "attribute/Attribute.h"
34 # include "attribute/filtering/AttributeFilter.h"
35 # include "attribute/filtering/BasicFilteringContext.h"
36 # include "attribute/resolver/AttributeExtractor.h"
37 # include "attribute/resolver/AttributeResolver.h"
38 # include "attribute/resolver/ResolutionContext.h"
39 # include "metadata/MetadataProviderCriteria.h"
40 # include "security/SecurityPolicy.h"
41 # include "security/SecurityPolicyProvider.h"
42 # include <saml/exceptions.h>
43 # include <saml/SAMLConfig.h>
44 # include <saml/saml1/core/Assertions.h>
45 # include <saml/saml2/metadata/Metadata.h>
46 # include <saml/util/CommonDomainCookie.h>
47 using namespace samlconstants;
48 using opensaml::saml2md::MetadataProvider;
49 using opensaml::saml2md::RoleDescriptor;
50 using opensaml::saml2md::EntityDescriptor;
51 using opensaml::saml2md::IDPSSODescriptor;
52 using opensaml::saml2md::SPSSODescriptor;
54 # include "lite/CommonDomainCookie.h"
57 using namespace shibspconstants;
58 using namespace shibsp;
59 using namespace opensaml;
60 using namespace xmltooling;
63 AssertionConsumerService::AssertionConsumerService(
64 const DOMElement* e, const char* appId, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
65 ) : AbstractHandler(e, log, filter, remapper)
67 ,m_decoder(nullptr), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
72 string address(appId);
73 address += getString("Location").second;
74 setAddress(address.c_str());
76 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
77 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
78 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
80 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
85 AssertionConsumerService::~AssertionConsumerService()
92 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
95 SPConfig& conf = SPConfig::getConfig();
97 if (conf.isEnabled(SPConfig::OutOfProcess)) {
98 // When out of process, we run natively and directly process the message.
99 return processMessage(request.getApplication(), request, request);
102 // When not out of process, we remote all the message processing.
103 vector<string> headers(1, "Cookie");
104 DDF out,in = wrap(request, &headers);
105 DDFJanitor jin(in), jout(out);
106 out=request.getServiceProvider().getListenerService()->send(in);
107 return unwrap(request, out);
111 void AssertionConsumerService::receive(DDF& in, ostream& out)
114 const char* aid=in["application_id"].string();
115 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
117 // Something's horribly wrong.
118 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
119 throw ConfigurationException("Unable to locate application for new session, deleted?");
122 // Unpack the request.
123 auto_ptr<HTTPRequest> req(getRequest(in));
125 // Wrap a response shim.
127 DDFJanitor jout(ret);
128 auto_ptr<HTTPResponse> resp(getResponse(ret));
130 // Since we're remoted, the result should either be a throw, a false/0 return,
131 // which we just return as an empty structure, or a response/redirect,
132 // which we capture in the facade and send back.
133 processMessage(*app, *req.get(), *resp.get());
137 pair<bool,long> AssertionConsumerService::processMessage(
138 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
142 // Locate policy key.
143 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
145 policyId = application.getString("policyId"); // unqualified in Application(s) element
147 // Lock metadata for use by policy.
148 Locker metadataLocker(application.getMetadataProvider());
150 // Create the policy.
151 auto_ptr<opensaml::SecurityPolicy> policy(
152 application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &m_role, policyId.second)
157 // Decode the message and process it in a protocol-specific way.
158 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, *(policy.get())));
160 throw BindingException("Failed to decode an SSO protocol response.");
161 DDF postData = recoverPostData(application, httpRequest, httpResponse, relayState.c_str());
162 DDFJanitor postjan(postData);
163 recoverRelayState(application, httpRequest, httpResponse, relayState);
164 implementProtocol(application, httpRequest, httpResponse, *(policy.get()), NULL, *msg.get());
166 auto_ptr_char issuer(policy->getIssuer() ? policy->getIssuer()->getName() : nullptr);
169 if (issuer.get() && *issuer.get())
170 maintainHistory(application, httpRequest, httpResponse, issuer.get());
172 // Now redirect to the state value. By now, it should be set to *something* usable.
173 // First check for POST data.
174 if (!postData.islist()) {
175 m_log.debug("ACS returning via redirect to: %s", relayState.c_str());
176 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
179 m_log.debug("ACS returning via POST to: %s", relayState.c_str());
180 return make_pair(true, sendPostResponse(application, httpResponse, relayState.c_str(), postData));
183 catch (XMLToolingException& ex) {
184 // Check for isPassive error condition.
185 const char* sc2 = ex.getProperty("statusCode2");
186 if (sc2 && !strcmp(sc2, "urn:oasis:names:tc:SAML:2.0:status:NoPassive")) {
187 pair<bool,bool> ignore = getBool("ignoreNoPassive", m_configNS.get()); // namespace-qualified if inside handler element
188 if (ignore.first && ignore.second && !relayState.empty()) {
189 m_log.debug("ignoring SAML status of NoPassive and redirecting to resource...");
190 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
193 if (!relayState.empty())
194 ex.addProperty("RelayState", relayState.c_str());
198 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
202 void AssertionConsumerService::checkAddress(const Application& application, const HTTPRequest& httpRequest, const char* issuedTo) const
204 if (!issuedTo || !*issuedTo)
207 const PropertySet* props=application.getPropertySet("Sessions");
208 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
209 if (!checkAddress.first)
210 checkAddress.second=true;
212 if (checkAddress.second) {
213 m_log.debug("checking client address");
214 if (httpRequest.getRemoteAddr() != issuedTo) {
215 throw FatalProfileException(
216 "Your client's current address ($client_addr) differs from the one used when you authenticated "
217 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
218 "Please contact your local support staff or help desk for assistance.",
219 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
227 const XMLCh* AssertionConsumerService::getProtocolFamily() const
229 return m_decoder ? m_decoder->getProtocolFamily() : nullptr;
232 const char* AssertionConsumerService::getType() const
234 return "AssertionConsumerService";
237 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
239 // Initial guess at index to use.
240 pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
241 if (!strncmp(handlerURL, "https", 5))
242 ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
244 ix = getUnsignedInt("index");
248 // Find maximum index in use and go one higher.
249 const vector<saml2md::AssertionConsumerService*>& services = const_cast<const SPSSODescriptor&>(role).getAssertionConsumerServices();
250 if (!services.empty() && ix.second <= services.back()->getIndex().second)
251 ix.second = services.back()->getIndex().second + 1;
253 const char* loc = getString("Location").second;
254 string hurl(handlerURL);
258 auto_ptr_XMLCh widen(hurl.c_str());
260 saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
261 ep->setLocation(widen.get());
262 ep->setBinding(getXMLString("Binding").second);
263 ep->setIndex(ix.second);
264 role.getAssertionConsumerServices().push_back(ep);
267 opensaml::SecurityPolicy* AssertionConsumerService::createSecurityPolicy(
268 const Application& application, const xmltooling::QName* role, bool validate, const char* policyId
271 return new SecurityPolicy(application, role, validate, policyId);
274 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
277 DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
280 virtual ~DummyContext() {
281 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
284 vector<Attribute*>& getResolvedAttributes() {
287 vector<Assertion*>& getResolvedAssertions() {
292 vector<Attribute*> m_attributes;
293 static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
296 vector<Assertion*> DummyContext::m_tokens;
298 ResolutionContext* AssertionConsumerService::resolveAttributes(
299 const Application& application,
300 const saml2md::RoleDescriptor* issuer,
301 const XMLCh* protocol,
302 const saml1::NameIdentifier* v1nameid,
303 const saml2::NameID* nameid,
304 const XMLCh* authncontext_class,
305 const XMLCh* authncontext_decl,
306 const vector<const Assertion*>* tokens
309 // First we do the extraction of any pushed information, including from metadata.
310 vector<Attribute*> resolvedAttributes;
311 AttributeExtractor* extractor = application.getAttributeExtractor();
313 Locker extlocker(extractor);
315 pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
317 m_log.debug("extracting metadata-derived attributes...");
319 // We pass nullptr for "issuer" because the IdP isn't the one asserting metadata-based attributes.
320 extractor->extractAttributes(application, nullptr, *issuer, resolvedAttributes);
321 for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
322 vector<string>& ids = (*a)->getAliases();
323 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
324 *id = mprefix.second + *id;
327 catch (exception& ex) {
328 m_log.error("caught exception extracting attributes: %s", ex.what());
332 m_log.debug("extracting pushed attributes...");
335 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
337 catch (exception& ex) {
338 m_log.error("caught exception extracting attributes: %s", ex.what());
343 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
345 catch (exception& ex) {
346 m_log.error("caught exception extracting attributes: %s", ex.what());
350 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
352 extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
354 catch (exception& ex) {
355 m_log.error("caught exception extracting attributes: %s", ex.what());
360 AttributeFilter* filter = application.getAttributeFilter();
361 if (filter && !resolvedAttributes.empty()) {
362 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
363 Locker filtlocker(filter);
365 filter->filterAttributes(fc, resolvedAttributes);
367 catch (exception& ex) {
368 m_log.error("caught exception filtering attributes: %s", ex.what());
369 m_log.error("dumping extracted attributes due to filtering exception");
370 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
371 resolvedAttributes.clear();
376 m_log.warn("no AttributeExtractor plugin installed, check log during startup");
380 AttributeResolver* resolver = application.getAttributeResolver();
382 m_log.debug("resolving attributes...");
384 Locker locker(resolver);
385 auto_ptr<ResolutionContext> ctx(
386 resolver->createResolutionContext(
388 issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : nullptr,
397 resolver->resolveAttributes(*ctx.get());
398 // Copy over any pushed attributes.
399 if (!resolvedAttributes.empty())
400 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
401 return ctx.release();
404 catch (exception& ex) {
405 m_log.error("attribute resolution failed: %s", ex.what());
408 if (!resolvedAttributes.empty())
409 return new DummyContext(resolvedAttributes);
413 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
415 policy.setMessageID(assertion.getID());
416 policy.setIssueInstant(assertion.getIssueInstantEpoch());
418 if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
419 const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
421 m_log.debug("extracting issuer from SAML 2.0 assertion");
422 policy.setIssuer(a2->getIssuer());
426 const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
428 m_log.debug("extracting issuer from SAML 1.x assertion");
429 policy.setIssuer(a1->getIssuer());
433 if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
434 if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
435 m_log.warn("non-system entity issuer, skipping metadata lookup");
438 m_log.debug("searching metadata for assertion issuer...");
439 pair<const EntityDescriptor*,const RoleDescriptor*> entity;
440 MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
441 mc.entityID_unicode = policy.getIssuer()->getName();
442 mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
443 mc.protocol = protocol;
444 entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
446 auto_ptr_char iname(policy.getIssuer()->getName());
447 m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
449 else if (!entity.second) {
450 m_log.warn("unable to find compatible IdP role in metadata");
453 policy.setIssuerMetadata(entity.second);
460 void AssertionConsumerService::maintainHistory(
461 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
464 static const char* defProps="; path=/";
466 const PropertySet* sessionProps=application.getPropertySet("Sessions");
467 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
469 if (idpHistory.first && idpHistory.second) {
470 pair<bool,const char*> cookieProps=sessionProps->getString("cookieProps");
471 if (!cookieProps.first)
472 cookieProps.second=defProps;
474 // Set an IdP history cookie locally (essentially just a CDC).
475 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
477 // Either leave in memory or set an expiration.
478 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
479 if (!days.first || days.second==0) {
480 string c = string(cdc.set(entityID)) + cookieProps.second;
481 response.setCookie(CommonDomainCookie::CDCName, c.c_str());
484 time_t now=time(nullptr) + (days.second * 24 * 60 * 60);
487 struct tm* ptime=gmtime_r(&now,&res);
489 struct tm* ptime=gmtime(&now);
492 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
493 string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
494 response.setCookie(CommonDomainCookie::CDCName, c.c_str());