2 * Copyright 2001-2009 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 <saml/exceptions.h>
42 # include <saml/SAMLConfig.h>
43 # include <saml/saml1/core/Assertions.h>
44 # include <saml/saml2/metadata/Metadata.h>
45 # include <saml/util/CommonDomainCookie.h>
46 using namespace samlconstants;
47 using opensaml::saml2md::MetadataProvider;
48 using opensaml::saml2md::RoleDescriptor;
49 using opensaml::saml2md::EntityDescriptor;
50 using opensaml::saml2md::IDPSSODescriptor;
51 using opensaml::saml2md::SPSSODescriptor;
53 # include "lite/CommonDomainCookie.h"
56 using namespace shibspconstants;
57 using namespace shibsp;
58 using namespace opensaml;
59 using namespace xmltooling;
62 AssertionConsumerService::AssertionConsumerService(
63 const DOMElement* e, const char* appId, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
64 ) : AbstractHandler(e, log, filter, remapper)
66 ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
71 string address(appId);
72 address += getString("Location").second;
73 setAddress(address.c_str());
75 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
76 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
77 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
79 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
84 AssertionConsumerService::~AssertionConsumerService()
91 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
94 SPConfig& conf = SPConfig::getConfig();
96 if (conf.isEnabled(SPConfig::OutOfProcess)) {
97 // When out of process, we run natively and directly process the message.
98 return processMessage(request.getApplication(), request, request);
101 // When not out of process, we remote all the message processing.
102 vector<string> headers(1, "Cookie");
103 DDF out,in = wrap(request, &headers);
104 DDFJanitor jin(in), jout(out);
105 out=request.getServiceProvider().getListenerService()->send(in);
106 return unwrap(request, out);
110 void AssertionConsumerService::receive(DDF& in, ostream& out)
113 const char* aid=in["application_id"].string();
114 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
116 // Something's horribly wrong.
117 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
118 throw ConfigurationException("Unable to locate application for new session, deleted?");
121 // Unpack the request.
122 auto_ptr<HTTPRequest> req(getRequest(in));
124 // Wrap a response shim.
126 DDFJanitor jout(ret);
127 auto_ptr<HTTPResponse> resp(getResponse(ret));
129 // Since we're remoted, the result should either be a throw, a false/0 return,
130 // which we just return as an empty structure, or a response/redirect,
131 // which we capture in the facade and send back.
132 processMessage(*app, *req.get(), *resp.get());
136 pair<bool,long> AssertionConsumerService::processMessage(
137 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
141 // Locate policy key.
142 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
144 policyId = application.getString("policyId"); // unqualified in Application(s) element
146 // Access policy properties.
147 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
148 pair<bool,bool> validate = settings->getBool("validate");
150 // Lock metadata for use by policy.
151 Locker metadataLocker(application.getMetadataProvider());
153 // Create the policy.
154 auto_ptr<opensaml::SecurityPolicy> policy(
155 createSecurityPolicy(application, &m_role, validate.first && validate.second, policyId.second)
160 // Decode the message and process it in a protocol-specific way.
161 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, *(policy.get())));
163 throw BindingException("Failed to decode an SSO protocol response.");
164 DDF postData = recoverPostData(application, httpRequest, httpResponse, relayState.c_str());
165 DDFJanitor postjan(postData);
166 recoverRelayState(application, httpRequest, httpResponse, relayState);
167 implementProtocol(application, httpRequest, httpResponse, *(policy.get()), settings, *msg.get());
169 auto_ptr_char issuer(policy->getIssuer() ? policy->getIssuer()->getName() : NULL);
172 if (issuer.get() && *issuer.get())
173 maintainHistory(application, httpRequest, httpResponse, issuer.get());
175 // Now redirect to the state value. By now, it should be set to *something* usable.
176 // First check for POST data.
177 if (!postData.islist()) {
178 m_log.debug("ACS returning via redirect to: %s", relayState.c_str());
179 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
182 m_log.debug("ACS returning via POST to: %s", relayState.c_str());
183 return make_pair(true, sendPostResponse(application, httpResponse, relayState.c_str(), postData));
186 catch (XMLToolingException& ex) {
187 // Check for isPassive error condition.
188 const char* sc2 = ex.getProperty("statusCode2");
189 if (sc2 && !strcmp(sc2, "urn:oasis:names:tc:SAML:2.0:status:NoPassive")) {
190 validate = getBool("ignoreNoPassive", m_configNS.get()); // namespace-qualified if inside handler element
191 if (validate.first && validate.second && !relayState.empty()) {
192 m_log.debug("ignoring SAML status of NoPassive and redirecting to resource...");
193 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
196 if (!relayState.empty())
197 ex.addProperty("RelayState", relayState.c_str());
201 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
205 void AssertionConsumerService::checkAddress(const Application& application, const HTTPRequest& httpRequest, const char* issuedTo) const
207 if (!issuedTo || !*issuedTo)
210 const PropertySet* props=application.getPropertySet("Sessions");
211 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
212 if (!checkAddress.first)
213 checkAddress.second=true;
215 if (checkAddress.second) {
216 m_log.debug("checking client address");
217 if (httpRequest.getRemoteAddr() != issuedTo) {
218 throw FatalProfileException(
219 "Your client's current address ($client_addr) differs from the one used when you authenticated "
220 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
221 "Please contact your local support staff or help desk for assistance.",
222 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
230 const char* AssertionConsumerService::getType() const
232 return "AssertionConsumerService";
235 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
237 // Initial guess at index to use.
238 pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
239 if (!strncmp(handlerURL, "https", 5))
240 ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
242 ix = getUnsignedInt("index");
246 // Find maximum index in use and go one higher.
247 const vector<saml2md::AssertionConsumerService*>& services = const_cast<const SPSSODescriptor&>(role).getAssertionConsumerServices();
248 if (!services.empty() && ix.second <= services.back()->getIndex().second)
249 ix.second = services.back()->getIndex().second + 1;
251 const char* loc = getString("Location").second;
252 string hurl(handlerURL);
256 auto_ptr_XMLCh widen(hurl.c_str());
258 saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
259 ep->setLocation(widen.get());
260 ep->setBinding(getXMLString("Binding").second);
261 ep->setIndex(ix.second);
262 role.getAssertionConsumerServices().push_back(ep);
265 opensaml::SecurityPolicy* AssertionConsumerService::createSecurityPolicy(
266 const Application& application, const xmltooling::QName* role, bool validate, const char* policyId
269 return new SecurityPolicy(application, role, validate, policyId);
272 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
275 DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
278 virtual ~DummyContext() {
279 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
282 vector<Attribute*>& getResolvedAttributes() {
285 vector<Assertion*>& getResolvedAssertions() {
290 vector<Attribute*> m_attributes;
291 static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
294 vector<Assertion*> DummyContext::m_tokens;
296 ResolutionContext* AssertionConsumerService::resolveAttributes(
297 const Application& application,
298 const saml2md::RoleDescriptor* issuer,
299 const XMLCh* protocol,
300 const saml1::NameIdentifier* v1nameid,
301 const saml2::NameID* nameid,
302 const XMLCh* authncontext_class,
303 const XMLCh* authncontext_decl,
304 const vector<const Assertion*>* tokens
307 // First we do the extraction of any pushed information, including from metadata.
308 vector<Attribute*> resolvedAttributes;
309 AttributeExtractor* extractor = application.getAttributeExtractor();
311 Locker extlocker(extractor);
313 pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
315 m_log.debug("extracting metadata-derived attributes...");
317 // We pass NULL for "issuer" because the IdP isn't the one asserting metadata-based attributes.
318 extractor->extractAttributes(application, NULL, *issuer, resolvedAttributes);
319 for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
320 vector<string>& ids = (*a)->getAliases();
321 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
322 *id = mprefix.second + *id;
325 catch (exception& ex) {
326 m_log.error("caught exception extracting attributes: %s", ex.what());
330 m_log.debug("extracting pushed attributes...");
333 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
335 catch (exception& ex) {
336 m_log.error("caught exception extracting attributes: %s", ex.what());
341 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
343 catch (exception& ex) {
344 m_log.error("caught exception extracting attributes: %s", ex.what());
348 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
350 extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
352 catch (exception& ex) {
353 m_log.error("caught exception extracting attributes: %s", ex.what());
358 AttributeFilter* filter = application.getAttributeFilter();
359 if (filter && !resolvedAttributes.empty()) {
360 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
361 Locker filtlocker(filter);
363 filter->filterAttributes(fc, resolvedAttributes);
365 catch (exception& ex) {
366 m_log.error("caught exception filtering attributes: %s", ex.what());
367 m_log.error("dumping extracted attributes due to filtering exception");
368 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
369 resolvedAttributes.clear();
374 m_log.warn("no AttributeExtractor plugin installed, check log during startup");
378 AttributeResolver* resolver = application.getAttributeResolver();
380 m_log.debug("resolving attributes...");
382 Locker locker(resolver);
383 auto_ptr<ResolutionContext> ctx(
384 resolver->createResolutionContext(
386 issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : NULL,
395 resolver->resolveAttributes(*ctx.get());
396 // Copy over any pushed attributes.
397 if (!resolvedAttributes.empty())
398 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
399 return ctx.release();
402 catch (exception& ex) {
403 m_log.error("attribute resolution failed: %s", ex.what());
406 if (!resolvedAttributes.empty())
407 return new DummyContext(resolvedAttributes);
411 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
413 policy.setMessageID(assertion.getID());
414 policy.setIssueInstant(assertion.getIssueInstantEpoch());
416 if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
417 const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
419 m_log.debug("extracting issuer from SAML 2.0 assertion");
420 policy.setIssuer(a2->getIssuer());
424 const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
426 m_log.debug("extracting issuer from SAML 1.x assertion");
427 policy.setIssuer(a1->getIssuer());
431 if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
432 if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
433 m_log.warn("non-system entity issuer, skipping metadata lookup");
436 m_log.debug("searching metadata for assertion issuer...");
437 pair<const EntityDescriptor*,const RoleDescriptor*> entity;
438 MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
439 mc.entityID_unicode = policy.getIssuer()->getName();
440 mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
441 mc.protocol = protocol;
442 entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
444 auto_ptr_char iname(policy.getIssuer()->getName());
445 m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
447 else if (!entity.second) {
448 m_log.warn("unable to find compatible IdP role in metadata");
451 policy.setIssuerMetadata(entity.second);
458 void AssertionConsumerService::maintainHistory(
459 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
462 static const char* defProps="; path=/";
464 const PropertySet* sessionProps=application.getPropertySet("Sessions");
465 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
467 if (idpHistory.first && idpHistory.second) {
468 pair<bool,const char*> cookieProps=sessionProps->getString("cookieProps");
469 if (!cookieProps.first)
470 cookieProps.second=defProps;
472 // Set an IdP history cookie locally (essentially just a CDC).
473 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
475 // Either leave in memory or set an expiration.
476 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
477 if (!days.first || days.second==0) {
478 string c = string(cdc.set(entityID)) + cookieProps.second;
479 response.setCookie(CommonDomainCookie::CDCName, c.c_str());
482 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
485 struct tm* ptime=gmtime_r(&now,&res);
487 struct tm* ptime=gmtime(&now);
490 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
491 string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
492 response.setCookie(CommonDomainCookie::CDCName, c.c_str());