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 "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "handler/AssertionConsumerService.h"
28 #include "util/SPConstants.h"
32 # include "attribute/Attribute.h"
33 # include "attribute/filtering/AttributeFilter.h"
34 # include "attribute/filtering/BasicFilteringContext.h"
35 # include "attribute/resolver/AttributeExtractor.h"
36 # include "attribute/resolver/AttributeResolver.h"
37 # include "attribute/resolver/ResolutionContext.h"
38 # include "metadata/MetadataProviderCriteria.h"
39 # include "security/SecurityPolicy.h"
40 # include <saml/SAMLConfig.h>
41 # include <saml/saml1/core/Assertions.h>
42 # include <saml/util/CommonDomainCookie.h>
43 using namespace samlconstants;
44 using opensaml::saml2md::MetadataProvider;
45 using opensaml::saml2md::RoleDescriptor;
46 using opensaml::saml2md::EntityDescriptor;
47 using opensaml::saml2md::IDPSSODescriptor;
48 using opensaml::saml2md::SPSSODescriptor;
50 # include "lite/CommonDomainCookie.h"
53 using namespace shibspconstants;
54 using namespace shibsp;
55 using namespace opensaml;
56 using namespace xmltooling;
59 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
60 : AbstractHandler(e, log)
62 ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
67 string address(appId);
68 address += getString("Location").second;
69 setAddress(address.c_str());
71 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
72 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
73 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
75 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
80 AssertionConsumerService::~AssertionConsumerService()
87 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
90 SPConfig& conf = SPConfig::getConfig();
92 if (conf.isEnabled(SPConfig::OutOfProcess)) {
93 // When out of process, we run natively and directly process the message.
94 return processMessage(request.getApplication(), request, request);
97 // When not out of process, we remote all the message processing.
98 vector<string> headers(1, "Cookie");
99 DDF out,in = wrap(request, &headers);
100 DDFJanitor jin(in), jout(out);
101 out=request.getServiceProvider().getListenerService()->send(in);
102 return unwrap(request, out);
106 void AssertionConsumerService::receive(DDF& in, ostream& out)
109 const char* aid=in["application_id"].string();
110 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
112 // Something's horribly wrong.
113 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
114 throw ConfigurationException("Unable to locate application for new session, deleted?");
117 // Unpack the request.
118 auto_ptr<HTTPRequest> req(getRequest(in));
120 // Wrap a response shim.
122 DDFJanitor jout(ret);
123 auto_ptr<HTTPResponse> resp(getResponse(ret));
125 // Since we're remoted, the result should either be a throw, a false/0 return,
126 // which we just return as an empty structure, or a response/redirect,
127 // which we capture in the facade and send back.
128 processMessage(*app, *req.get(), *resp.get());
132 pair<bool,long> AssertionConsumerService::processMessage(
133 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
137 // Locate policy key.
138 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
140 policyId = application.getString("policyId"); // unqualified in Application(s) element
142 // Access policy properties.
143 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
144 pair<bool,bool> validate = settings->getBool("validate");
146 // Lock metadata for use by policy.
147 Locker metadataLocker(application.getMetadataProvider());
149 // Create the policy.
150 auto_ptr<opensaml::SecurityPolicy> policy(
151 createSecurityPolicy(application, &m_role, validate.first && validate.second, policyId.second)
156 // Decode the message and process it in a protocol-specific way.
157 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, *(policy.get())));
159 throw BindingException("Failed to decode an SSO protocol response.");
160 DDF postData = recoverPostData(application, httpRequest, httpResponse, relayState.c_str());
161 DDFJanitor postjan(postData);
162 recoverRelayState(application, httpRequest, httpResponse, relayState);
163 implementProtocol(application, httpRequest, httpResponse, *(policy.get()), settings, *msg.get());
165 auto_ptr_char issuer(policy->getIssuer() ? policy->getIssuer()->getName() : NULL);
168 if (issuer.get() && *issuer.get())
169 maintainHistory(application, httpRequest, httpResponse, issuer.get());
171 // Now redirect to the state value. By now, it should be set to *something* usable.
172 // First check for POST data.
173 if (!postData.islist()) {
174 m_log.debug("ACS returning via redirect to: %s", relayState.c_str());
175 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
178 m_log.debug("ACS returning via POST to: %s", relayState.c_str());
179 return make_pair(true, sendPostResponse(application, httpResponse, relayState.c_str(), postData));
182 catch (XMLToolingException& ex) {
183 // Check for isPassive error condition.
184 const char* sc2 = ex.getProperty("statusCode2");
185 if (sc2 && !strcmp(sc2, "urn:oasis:names:tc:SAML:2.0:status:NoPassive")) {
186 validate = getBool("ignoreNoPassive", m_configNS.get()); // namespace-qualified if inside handler element
187 if (validate.first && validate.second && !relayState.empty()) {
188 m_log.debug("ignoring SAML status of NoPassive and redirecting to resource...");
189 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
192 if (!relayState.empty())
193 ex.addProperty("RelayState", relayState.c_str());
197 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
201 void AssertionConsumerService::checkAddress(const Application& application, const HTTPRequest& httpRequest, const char* issuedTo) const
203 if (!issuedTo || !*issuedTo)
206 const PropertySet* props=application.getPropertySet("Sessions");
207 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
208 if (!checkAddress.first)
209 checkAddress.second=true;
211 if (checkAddress.second) {
212 m_log.debug("checking client address");
213 if (httpRequest.getRemoteAddr() != issuedTo) {
214 throw FatalProfileException(
215 "Your client's current address ($client_addr) differs from the one used when you authenticated "
216 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
217 "Please contact your local support staff or help desk for assistance.",
218 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
226 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
228 const char* loc = getString("Location").second;
229 string hurl(handlerURL);
233 auto_ptr_XMLCh widen(hurl.c_str());
234 saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
235 ep->setLocation(widen.get());
236 ep->setBinding(getXMLString("Binding").second);
237 if (!strncmp(handlerURL, "https", 5)) {
238 pair<bool,const XMLCh*> index = getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
240 ep->setIndex(index.second);
242 ep->setIndex(getXMLString("index").second);
245 ep->setIndex(getXMLString("index").second);
247 role.getAssertionConsumerServices().push_back(ep);
250 opensaml::SecurityPolicy* AssertionConsumerService::createSecurityPolicy(
251 const Application& application, const xmltooling::QName* role, bool validate, const char* policyId
254 return new SecurityPolicy(application, role, validate, policyId);
257 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
260 DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
263 virtual ~DummyContext() {
264 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
267 vector<Attribute*>& getResolvedAttributes() {
270 vector<Assertion*>& getResolvedAssertions() {
275 vector<Attribute*> m_attributes;
276 static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
279 vector<Assertion*> DummyContext::m_tokens;
281 ResolutionContext* AssertionConsumerService::resolveAttributes(
282 const Application& application,
283 const saml2md::RoleDescriptor* issuer,
284 const XMLCh* protocol,
285 const saml1::NameIdentifier* v1nameid,
286 const saml2::NameID* nameid,
287 const XMLCh* authncontext_class,
288 const XMLCh* authncontext_decl,
289 const vector<const Assertion*>* tokens
292 const saml2md::EntityDescriptor* entity = issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : NULL;
294 // First we do the extraction of any pushed information, including from metadata.
295 vector<Attribute*> resolvedAttributes;
296 AttributeExtractor* extractor = application.getAttributeExtractor();
298 Locker extlocker(extractor);
300 pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
302 m_log.debug("extracting metadata-derived attributes...");
304 extractor->extractAttributes(application, issuer, *entity, resolvedAttributes);
305 for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
306 vector<string>& ids = (*a)->getAliases();
307 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
308 *id = mprefix.second + *id;
311 catch (exception& ex) {
312 m_log.error("caught exception extracting attributes: %s", ex.what());
316 m_log.debug("extracting pushed attributes...");
319 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
321 catch (exception& ex) {
322 m_log.error("caught exception extracting attributes: %s", ex.what());
327 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
329 catch (exception& ex) {
330 m_log.error("caught exception extracting attributes: %s", ex.what());
334 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
336 extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
338 catch (exception& ex) {
339 m_log.error("caught exception extracting attributes: %s", ex.what());
344 AttributeFilter* filter = application.getAttributeFilter();
345 if (filter && !resolvedAttributes.empty()) {
346 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
347 Locker filtlocker(filter);
349 filter->filterAttributes(fc, resolvedAttributes);
351 catch (exception& ex) {
352 m_log.error("caught exception filtering attributes: %s", ex.what());
353 m_log.error("dumping extracted attributes due to filtering exception");
354 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
355 resolvedAttributes.clear();
361 AttributeResolver* resolver = application.getAttributeResolver();
363 m_log.debug("resolving attributes...");
365 Locker locker(resolver);
366 auto_ptr<ResolutionContext> ctx(
367 resolver->createResolutionContext(
378 resolver->resolveAttributes(*ctx.get());
379 // Copy over any pushed attributes.
380 if (!resolvedAttributes.empty())
381 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
382 return ctx.release();
385 catch (exception& ex) {
386 m_log.error("attribute resolution failed: %s", ex.what());
389 if (!resolvedAttributes.empty())
390 return new DummyContext(resolvedAttributes);
394 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
396 policy.setMessageID(assertion.getID());
397 policy.setIssueInstant(assertion.getIssueInstantEpoch());
399 if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
400 const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
402 m_log.debug("extracting issuer from SAML 2.0 assertion");
403 policy.setIssuer(a2->getIssuer());
407 const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
409 m_log.debug("extracting issuer from SAML 1.x assertion");
410 policy.setIssuer(a1->getIssuer());
414 if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
415 if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
416 m_log.warn("non-system entity issuer, skipping metadata lookup");
419 m_log.debug("searching metadata for assertion issuer...");
420 pair<const EntityDescriptor*,const RoleDescriptor*> entity;
421 MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
422 mc.entityID_unicode = policy.getIssuer()->getName();
423 mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
424 mc.protocol = protocol;
425 entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
427 auto_ptr_char iname(policy.getIssuer()->getName());
428 m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
430 else if (!entity.second) {
431 m_log.warn("unable to find compatible IdP role in metadata");
434 policy.setIssuerMetadata(entity.second);
441 void AssertionConsumerService::maintainHistory(
442 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
445 static const char* defProps="; path=/";
447 const PropertySet* sessionProps=application.getPropertySet("Sessions");
448 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
450 if (idpHistory.first && idpHistory.second) {
451 pair<bool,const char*> cookieProps=sessionProps->getString("cookieProps");
452 if (!cookieProps.first)
453 cookieProps.second=defProps;
455 // Set an IdP history cookie locally (essentially just a CDC).
456 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
458 // Either leave in memory or set an expiration.
459 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
460 if (!days.first || days.second==0) {
461 string c = string(cdc.set(entityID)) + cookieProps.second;
462 response.setCookie(CommonDomainCookie::CDCName, c.c_str());
465 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
468 struct tm* ptime=gmtime_r(&now,&res);
470 struct tm* ptime=gmtime(&now);
473 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
474 string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
475 response.setCookie(CommonDomainCookie::CDCName, c.c_str());