2 * Copyright 2001-2007 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 "security/SecurityPolicy.h"
39 # include <saml/SAMLConfig.h>
40 # include <saml/saml1/core/Assertions.h>
41 # include <saml/util/CommonDomainCookie.h>
42 using namespace samlconstants;
43 using opensaml::saml2md::MetadataProvider;
44 using opensaml::saml2md::RoleDescriptor;
45 using opensaml::saml2md::EntityDescriptor;
46 using opensaml::saml2md::IDPSSODescriptor;
47 using opensaml::saml2md::SPSSODescriptor;
49 # include "lite/CommonDomainCookie.h"
52 using namespace shibspconstants;
53 using namespace shibsp;
54 using namespace opensaml;
55 using namespace xmltooling;
58 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
59 : AbstractHandler(e, log)
61 ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
66 string address(appId);
67 address += getString("Location").second;
68 setAddress(address.c_str());
70 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
71 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
72 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
74 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
79 AssertionConsumerService::~AssertionConsumerService()
86 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
89 SPConfig& conf = SPConfig::getConfig();
91 if (conf.isEnabled(SPConfig::OutOfProcess)) {
92 // When out of process, we run natively and directly process the message.
93 return processMessage(request.getApplication(), request, request);
96 // When not out of process, we remote all the message processing.
97 vector<string> headers(1, "Cookie");
98 DDF out,in = wrap(request, &headers);
99 DDFJanitor jin(in), jout(out);
100 out=request.getServiceProvider().getListenerService()->send(in);
101 return unwrap(request, out);
105 void AssertionConsumerService::receive(DDF& in, ostream& out)
108 const char* aid=in["application_id"].string();
109 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
111 // Something's horribly wrong.
112 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
113 throw ConfigurationException("Unable to locate application for new session, deleted?");
116 // Unpack the request.
117 auto_ptr<HTTPRequest> req(getRequest(in));
119 // Wrap a response shim.
121 DDFJanitor jout(ret);
122 auto_ptr<HTTPResponse> resp(getResponse(ret));
124 // Since we're remoted, the result should either be a throw, a false/0 return,
125 // which we just return as an empty structure, or a response/redirect,
126 // which we capture in the facade and send back.
127 processMessage(*app, *req.get(), *resp.get());
131 pair<bool,long> AssertionConsumerService::processMessage(
132 const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
136 // Locate policy key.
137 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
139 policyId = application.getString("policyId"); // unqualified in Application(s) element
141 // Access policy properties.
142 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
143 pair<bool,bool> validate = settings->getBool("validate");
145 // Lock metadata for use by policy.
146 Locker metadataLocker(application.getMetadataProvider());
148 // Create the policy.
149 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
154 // Decode the message and process it in a protocol-specific way.
155 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
157 throw BindingException("Failed to decode an SSO protocol response.");
158 recoverRelayState(application, httpRequest, httpResponse, relayState);
159 implementProtocol(application, httpRequest, httpResponse, policy, settings, *msg.get());
161 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
164 if (issuer.get() && *issuer.get())
165 maintainHistory(application, httpRequest, httpResponse, issuer.get());
167 // Now redirect to the state value. By now, it should be set to *something* usable.
168 return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
170 catch (XMLToolingException& ex) {
171 if (!relayState.empty())
172 ex.addProperty("RelayState", relayState.c_str());
176 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
180 void AssertionConsumerService::checkAddress(const Application& application, const HTTPRequest& httpRequest, const char* issuedTo) const
182 if (!issuedTo || !*issuedTo)
185 const PropertySet* props=application.getPropertySet("Sessions");
186 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
187 if (!checkAddress.first)
188 checkAddress.second=true;
190 if (checkAddress.second) {
191 m_log.debug("checking client address");
192 if (httpRequest.getRemoteAddr() != issuedTo) {
193 throw FatalProfileException(
194 "Your client's current address ($client_addr) differs from the one used when you authenticated "
195 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
196 "Please contact your local support staff or help desk for assistance.",
197 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
205 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
206 const char* loc = getString("Location").second;
207 string hurl(handlerURL);
211 auto_ptr_XMLCh widen(hurl.c_str());
212 saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
213 ep->setLocation(widen.get());
214 ep->setBinding(getXMLString("Binding").second);
215 if (!strncmp(handlerURL, "https", 5)) {
216 pair<bool,const XMLCh*> index = getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
218 ep->setIndex(index.second);
220 ep->setIndex(getXMLString("index").second);
223 ep->setIndex(getXMLString("index").second);
225 role.getAssertionConsumerServices().push_back(ep);
228 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
231 DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
234 virtual ~DummyContext() {
235 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
238 vector<Attribute*>& getResolvedAttributes() {
241 vector<Assertion*>& getResolvedAssertions() {
246 vector<Attribute*> m_attributes;
247 static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
250 vector<Assertion*> DummyContext::m_tokens;
252 ResolutionContext* AssertionConsumerService::resolveAttributes(
253 const Application& application,
254 const saml2md::RoleDescriptor* issuer,
255 const XMLCh* protocol,
256 const saml1::NameIdentifier* v1nameid,
257 const saml2::NameID* nameid,
258 const XMLCh* authncontext_class,
259 const XMLCh* authncontext_decl,
260 const vector<const Assertion*>* tokens
263 const saml2md::EntityDescriptor* entity = issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : NULL;
265 // First we do the extraction of any pushed information, including from metadata.
266 vector<Attribute*> resolvedAttributes;
267 AttributeExtractor* extractor = application.getAttributeExtractor();
269 Locker extlocker(extractor);
271 pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
273 m_log.debug("extracting metadata-derived attributes...");
275 extractor->extractAttributes(application, issuer, *entity, resolvedAttributes);
276 for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
277 vector<string>& ids = (*a)->getAliases();
278 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
279 *id = mprefix.second + *id;
282 catch (exception& ex) {
283 m_log.error("caught exception extracting attributes: %s", ex.what());
287 m_log.debug("extracting pushed attributes...");
290 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
292 catch (exception& ex) {
293 m_log.error("caught exception extracting attributes: %s", ex.what());
298 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
300 catch (exception& ex) {
301 m_log.error("caught exception extracting attributes: %s", ex.what());
305 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
307 extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
309 catch (exception& ex) {
310 m_log.error("caught exception extracting attributes: %s", ex.what());
315 AttributeFilter* filter = application.getAttributeFilter();
316 if (filter && !resolvedAttributes.empty()) {
317 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
318 Locker filtlocker(filter);
320 filter->filterAttributes(fc, resolvedAttributes);
322 catch (exception& ex) {
323 m_log.error("caught exception filtering attributes: %s", ex.what());
324 m_log.error("dumping extracted attributes due to filtering exception");
325 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
326 resolvedAttributes.clear();
332 AttributeResolver* resolver = application.getAttributeResolver();
334 m_log.debug("resolving attributes...");
336 Locker locker(resolver);
337 auto_ptr<ResolutionContext> ctx(
338 resolver->createResolutionContext(
349 resolver->resolveAttributes(*ctx.get());
350 // Copy over any pushed attributes.
351 if (!resolvedAttributes.empty())
352 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
354 // Attach global prefix if needed.
355 pair<bool,const char*> prefix = application.getString("attributePrefix");
357 for (vector<Attribute*>::iterator a = ctx->getResolvedAttributes().begin(); a != ctx->getResolvedAttributes().end(); ++a) {
358 vector<string>& ids = (*a)->getAliases();
359 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
360 *id = prefix.second + *id;
364 return ctx.release();
367 catch (exception& ex) {
368 m_log.error("attribute resolution failed: %s", ex.what());
371 if (!resolvedAttributes.empty()) {
372 // Attach global prefix if needed.
373 pair<bool,const char*> prefix = application.getString("attributePrefix");
375 for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
376 vector<string>& ids = (*a)->getAliases();
377 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
378 *id = prefix.second + *id;
382 return new DummyContext(resolvedAttributes);
387 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
389 policy.setMessageID(assertion.getID());
390 policy.setIssueInstant(assertion.getIssueInstantEpoch());
392 if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20_NS)) {
393 const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
395 m_log.debug("extracting issuer from SAML 2.0 assertion");
396 policy.setIssuer(a2->getIssuer());
400 const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
402 m_log.debug("extracting issuer from SAML 1.x assertion");
403 policy.setIssuer(a1->getIssuer());
407 if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
408 if (policy.getIssuer()->getFormat() && !XMLString::equals(policy.getIssuer()->getFormat(), saml2::NameIDType::ENTITY)) {
409 m_log.warn("non-system entity issuer, skipping metadata lookup");
412 m_log.debug("searching metadata for assertion issuer...");
413 MetadataProvider::Criteria mc(policy.getIssuer()->getName(), &IDPSSODescriptor::ELEMENT_QNAME, protocol);
414 pair<const EntityDescriptor*,const RoleDescriptor*> entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
416 auto_ptr_char iname(policy.getIssuer()->getName());
417 m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
419 else if (!entity.second) {
420 m_log.warn("unable to find compatible IdP role in metadata");
423 policy.setIssuerMetadata(entity.second);
430 void AssertionConsumerService::maintainHistory(
431 const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* entityID
434 static const char* defProps="; path=/";
436 const PropertySet* sessionProps=application.getPropertySet("Sessions");
437 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
439 if (!idpHistory.first || idpHistory.second) {
440 pair<bool,const char*> cookieProps=sessionProps->getString("cookieProps");
441 if (!cookieProps.first)
442 cookieProps.second=defProps;
444 // Set an IdP history cookie locally (essentially just a CDC).
445 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
447 // Either leave in memory or set an expiration.
448 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
449 if (!days.first || days.second==0) {
450 string c = string(cdc.set(entityID)) + cookieProps.second;
451 response.setCookie(CommonDomainCookie::CDCName, c.c_str());
454 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
457 struct tm* ptime=gmtime_r(&now,&res);
459 struct tm* ptime=gmtime(&now);
462 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
463 string c = string(cdc.set(entityID)) + cookieProps.second + "; expires=" + timebuf;
464 response.setCookie(CommonDomainCookie::CDCName, c.c_str());