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 const char* loc = getString("Location").second;
238 string hurl(handlerURL);
242 auto_ptr_XMLCh widen(hurl.c_str());
243 saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
244 ep->setLocation(widen.get());
245 ep->setBinding(getXMLString("Binding").second);
246 if (!strncmp(handlerURL, "https", 5)) {
247 pair<bool,const XMLCh*> index = getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
249 ep->setIndex(index.second);
251 ep->setIndex(getXMLString("index").second);
254 ep->setIndex(getXMLString("index").second);
256 role.getAssertionConsumerServices().push_back(ep);
259 opensaml::SecurityPolicy* AssertionConsumerService::createSecurityPolicy(
260 const Application& application, const xmltooling::QName* role, bool validate, const char* policyId
263 return new SecurityPolicy(application, role, validate, policyId);
266 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
269 DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
272 virtual ~DummyContext() {
273 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
276 vector<Attribute*>& getResolvedAttributes() {
279 vector<Assertion*>& getResolvedAssertions() {
284 vector<Attribute*> m_attributes;
285 static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
288 vector<Assertion*> DummyContext::m_tokens;
290 ResolutionContext* AssertionConsumerService::resolveAttributes(
291 const Application& application,
292 const saml2md::RoleDescriptor* issuer,
293 const XMLCh* protocol,
294 const saml1::NameIdentifier* v1nameid,
295 const saml2::NameID* nameid,
296 const XMLCh* authncontext_class,
297 const XMLCh* authncontext_decl,
298 const vector<const Assertion*>* tokens
301 // First we do the extraction of any pushed information, including from metadata.
302 vector<Attribute*> resolvedAttributes;
303 AttributeExtractor* extractor = application.getAttributeExtractor();
305 Locker extlocker(extractor);
307 pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
309 m_log.debug("extracting metadata-derived attributes...");
311 // We pass NULL for "issuer" because the IdP isn't the one asserting metadata-based attributes.
312 extractor->extractAttributes(application, NULL, *issuer, resolvedAttributes);
313 for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
314 vector<string>& ids = (*a)->getAliases();
315 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
316 *id = mprefix.second + *id;
319 catch (exception& ex) {
320 m_log.error("caught exception extracting attributes: %s", ex.what());
324 m_log.debug("extracting pushed attributes...");
327 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
329 catch (exception& ex) {
330 m_log.error("caught exception extracting attributes: %s", ex.what());
335 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
337 catch (exception& ex) {
338 m_log.error("caught exception extracting attributes: %s", ex.what());
342 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
344 extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
346 catch (exception& ex) {
347 m_log.error("caught exception extracting attributes: %s", ex.what());
352 AttributeFilter* filter = application.getAttributeFilter();
353 if (filter && !resolvedAttributes.empty()) {
354 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
355 Locker filtlocker(filter);
357 filter->filterAttributes(fc, resolvedAttributes);
359 catch (exception& ex) {
360 m_log.error("caught exception filtering attributes: %s", ex.what());
361 m_log.error("dumping extracted attributes due to filtering exception");
362 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
363 resolvedAttributes.clear();
369 AttributeResolver* resolver = application.getAttributeResolver();
371 m_log.debug("resolving attributes...");
373 Locker locker(resolver);
374 auto_ptr<ResolutionContext> ctx(
375 resolver->createResolutionContext(
377 issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : NULL,
386 resolver->resolveAttributes(*ctx.get());
387 // Copy over any pushed attributes.
388 if (!resolvedAttributes.empty())
389 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
390 return ctx.release();
393 catch (exception& ex) {
394 m_log.error("attribute resolution failed: %s", ex.what());
397 if (!resolvedAttributes.empty())
398 return new DummyContext(resolvedAttributes);
402 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
404 policy.setMessageID(assertion.getID());
405 policy.setIssueInstant(assertion.getIssueInstantEpoch());
407 if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
408 const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
410 m_log.debug("extracting issuer from SAML 2.0 assertion");
411 policy.setIssuer(a2->getIssuer());
415 const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
417 m_log.debug("extracting issuer from SAML 1.x assertion");
418 policy.setIssuer(a1->getIssuer());
422 if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
423 if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
424 m_log.warn("non-system entity issuer, skipping metadata lookup");
427 m_log.debug("searching metadata for assertion issuer...");
428 pair<const EntityDescriptor*,const RoleDescriptor*> entity;
429 MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
430 mc.entityID_unicode = policy.getIssuer()->getName();
431 mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
432 mc.protocol = protocol;
433 entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
435 auto_ptr_char iname(policy.getIssuer()->getName());
436 m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
438 else if (!entity.second) {
439 m_log.warn("unable to find compatible IdP role in metadata");
442 policy.setIssuerMetadata(entity.second);
449 void AssertionConsumerService::maintainHistory(
450 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
453 static const char* defProps="; path=/";
455 const PropertySet* sessionProps=application.getPropertySet("Sessions");
456 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
458 if (idpHistory.first && idpHistory.second) {
459 pair<bool,const char*> cookieProps=sessionProps->getString("cookieProps");
460 if (!cookieProps.first)
461 cookieProps.second=defProps;
463 // Set an IdP history cookie locally (essentially just a CDC).
464 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
466 // Either leave in memory or set an expiration.
467 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
468 if (!days.first || days.second==0) {
469 string c = string(cdc.set(entityID)) + cookieProps.second;
470 response.setCookie(CommonDomainCookie::CDCName, c.c_str());
473 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
476 struct tm* ptime=gmtime_r(&now,&res);
478 struct tm* ptime=gmtime(&now);
481 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
482 string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
483 response.setCookie(CommonDomainCookie::CDCName, c.c_str());