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 char* AssertionConsumerService::getType() const
229 return "AssertionConsumerService";
232 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
234 // Initial guess at index to use.
235 pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
236 if (!strncmp(handlerURL, "https", 5))
237 ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
239 ix = getUnsignedInt("index");
243 // Find maximum index in use and go one higher.
244 const vector<saml2md::AssertionConsumerService*>& services = const_cast<const SPSSODescriptor&>(role).getAssertionConsumerServices();
245 if (!services.empty() && ix.second <= services.back()->getIndex().second)
246 ix.second = services.back()->getIndex().second + 1;
248 const char* loc = getString("Location").second;
249 string hurl(handlerURL);
253 auto_ptr_XMLCh widen(hurl.c_str());
255 saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
256 ep->setLocation(widen.get());
257 ep->setBinding(getXMLString("Binding").second);
258 ep->setIndex(ix.second);
259 role.getAssertionConsumerServices().push_back(ep);
262 opensaml::SecurityPolicy* AssertionConsumerService::createSecurityPolicy(
263 const Application& application, const xmltooling::QName* role, bool validate, const char* policyId
266 return new SecurityPolicy(application, role, validate, policyId);
269 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
272 DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
275 virtual ~DummyContext() {
276 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
279 vector<Attribute*>& getResolvedAttributes() {
282 vector<Assertion*>& getResolvedAssertions() {
287 vector<Attribute*> m_attributes;
288 static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
291 vector<Assertion*> DummyContext::m_tokens;
293 ResolutionContext* AssertionConsumerService::resolveAttributes(
294 const Application& application,
295 const saml2md::RoleDescriptor* issuer,
296 const XMLCh* protocol,
297 const saml1::NameIdentifier* v1nameid,
298 const saml2::NameID* nameid,
299 const XMLCh* authncontext_class,
300 const XMLCh* authncontext_decl,
301 const vector<const Assertion*>* tokens
304 // First we do the extraction of any pushed information, including from metadata.
305 vector<Attribute*> resolvedAttributes;
306 AttributeExtractor* extractor = application.getAttributeExtractor();
308 Locker extlocker(extractor);
310 pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
312 m_log.debug("extracting metadata-derived attributes...");
314 // We pass nullptr for "issuer" because the IdP isn't the one asserting metadata-based attributes.
315 extractor->extractAttributes(application, nullptr, *issuer, resolvedAttributes);
316 for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
317 vector<string>& ids = (*a)->getAliases();
318 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
319 *id = mprefix.second + *id;
322 catch (exception& ex) {
323 m_log.error("caught exception extracting attributes: %s", ex.what());
327 m_log.debug("extracting pushed attributes...");
330 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
332 catch (exception& ex) {
333 m_log.error("caught exception extracting attributes: %s", ex.what());
338 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
340 catch (exception& ex) {
341 m_log.error("caught exception extracting attributes: %s", ex.what());
345 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
347 extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
349 catch (exception& ex) {
350 m_log.error("caught exception extracting attributes: %s", ex.what());
355 AttributeFilter* filter = application.getAttributeFilter();
356 if (filter && !resolvedAttributes.empty()) {
357 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
358 Locker filtlocker(filter);
360 filter->filterAttributes(fc, resolvedAttributes);
362 catch (exception& ex) {
363 m_log.error("caught exception filtering attributes: %s", ex.what());
364 m_log.error("dumping extracted attributes due to filtering exception");
365 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
366 resolvedAttributes.clear();
371 m_log.warn("no AttributeExtractor plugin installed, check log during startup");
375 AttributeResolver* resolver = application.getAttributeResolver();
377 m_log.debug("resolving attributes...");
379 Locker locker(resolver);
380 auto_ptr<ResolutionContext> ctx(
381 resolver->createResolutionContext(
383 issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : nullptr,
392 resolver->resolveAttributes(*ctx.get());
393 // Copy over any pushed attributes.
394 if (!resolvedAttributes.empty())
395 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
396 return ctx.release();
399 catch (exception& ex) {
400 m_log.error("attribute resolution failed: %s", ex.what());
403 if (!resolvedAttributes.empty())
404 return new DummyContext(resolvedAttributes);
408 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
410 policy.setMessageID(assertion.getID());
411 policy.setIssueInstant(assertion.getIssueInstantEpoch());
413 if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
414 const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
416 m_log.debug("extracting issuer from SAML 2.0 assertion");
417 policy.setIssuer(a2->getIssuer());
421 const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
423 m_log.debug("extracting issuer from SAML 1.x assertion");
424 policy.setIssuer(a1->getIssuer());
428 if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
429 if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
430 m_log.warn("non-system entity issuer, skipping metadata lookup");
433 m_log.debug("searching metadata for assertion issuer...");
434 pair<const EntityDescriptor*,const RoleDescriptor*> entity;
435 MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
436 mc.entityID_unicode = policy.getIssuer()->getName();
437 mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
438 mc.protocol = protocol;
439 entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
441 auto_ptr_char iname(policy.getIssuer()->getName());
442 m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
444 else if (!entity.second) {
445 m_log.warn("unable to find compatible IdP role in metadata");
448 policy.setIssuerMetadata(entity.second);
455 void AssertionConsumerService::maintainHistory(
456 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
459 static const char* defProps="; path=/";
461 const PropertySet* sessionProps=application.getPropertySet("Sessions");
462 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
464 if (idpHistory.first && idpHistory.second) {
465 pair<bool,const char*> cookieProps=sessionProps->getString("cookieProps");
466 if (!cookieProps.first)
467 cookieProps.second=defProps;
469 // Set an IdP history cookie locally (essentially just a CDC).
470 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
472 // Either leave in memory or set an expiration.
473 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
474 if (!days.first || days.second==0) {
475 string c = string(cdc.set(entityID)) + cookieProps.second;
476 response.setCookie(CommonDomainCookie::CDCName, c.c_str());
479 time_t now=time(nullptr) + (days.second * 24 * 60 * 60);
482 struct tm* ptime=gmtime_r(&now,&res);
484 struct tm* ptime=gmtime(&now);
487 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
488 string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
489 response.setCookie(CommonDomainCookie::CDCName, c.c_str());