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::EntityDescriptor;
44 using opensaml::saml2md::IDPSSODescriptor;
45 using opensaml::saml2md::SPSSODescriptor;
46 using opensaml::saml2md::isValidForProtocol;
48 # include "lite/CommonDomainCookie.h"
51 using namespace shibspconstants;
52 using namespace shibsp;
53 using namespace opensaml;
54 using namespace xmltooling;
57 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
58 : AbstractHandler(e, log)
60 ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
65 string address(appId);
66 address += getString("Location").second;
67 setAddress(address.c_str());
69 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
70 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
71 getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS)
73 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
78 AssertionConsumerService::~AssertionConsumerService()
85 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
88 SPConfig& conf = SPConfig::getConfig();
91 if (conf.isEnabled(SPConfig::OutOfProcess)) {
92 // When out of process, we run natively and directly process the message.
93 // RelayState will be fully handled during message processing.
95 string key = processMessage(request.getApplication(), request, entityID, relayState);
96 return sendRedirect(request, key.c_str(), entityID.c_str(), relayState.c_str());
99 // When not out of process, we remote all the message processing.
100 DDF out,in = wrap(request);
101 DDFJanitor jin(in), jout(out);
104 out=request.getServiceProvider().getListenerService()->send(in);
106 catch (XMLToolingException& ex) {
107 // Try for RelayState recovery.
108 if (ex.getProperty("RelayState"))
109 relayState = ex.getProperty("RelayState");
111 recoverRelayState(request.getApplication(), request, relayState);
113 catch (exception& ex2) {
114 m_log.error("trapped an error during RelayState recovery while handling an error: %s", ex2.what());
119 // We invoke RelayState recovery one last time on this side of the boundary.
120 if (out["RelayState"].isstring())
121 relayState = out["RelayState"].string();
122 recoverRelayState(request.getApplication(), request, relayState);
124 // If it worked, we have a session key.
125 if (!out["key"].isstring())
126 throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
128 // Take care of cookie business and wrap it up.
129 return sendRedirect(request, out["key"].string(), out["entity_id"].string(), relayState.c_str());
132 catch (XMLToolingException& ex) {
133 // Try and preserve RelayState.
134 if (!relayState.empty())
135 ex.addProperty("RelayState", relayState.c_str());
140 void AssertionConsumerService::receive(DDF& in, ostream& out)
143 const char* aid=in["application_id"].string();
144 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
146 // Something's horribly wrong.
147 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
148 throw ConfigurationException("Unable to locate application for new session, deleted?");
151 // Unpack the request.
152 auto_ptr<HTTPRequest> http(getRequest(in));
155 string relayState, entityID;
157 string key = processMessage(*app, *http.get(), entityID, relayState);
159 // Repack for return to caller.
160 DDF ret=DDF(NULL).structure();
161 DDFJanitor jret(ret);
162 ret.addmember("key").string(key.c_str());
163 if (!entityID.empty())
164 ret.addmember("entity_id").string(entityID.c_str());
165 if (!relayState.empty())
166 ret.addmember("RelayState").string(relayState.c_str());
169 catch (XMLToolingException& ex) {
170 // Try and preserve RelayState if we can.
171 if (!relayState.empty())
172 ex.addProperty("RelayState", relayState.c_str());
177 string AssertionConsumerService::processMessage(
178 const Application& application, HTTPRequest& httpRequest, string& entityID, string& relayState
182 // Locate policy key.
183 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
185 policyId = application.getString("policyId"); // unqualified in Application(s) element
187 // Access policy properties.
188 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
189 pair<bool,bool> validate = settings->getBool("validate");
191 // Lock metadata for use by policy.
192 Locker metadataLocker(application.getMetadataProvider());
194 // Create the policy.
195 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
197 // Decode the message and process it in a protocol-specific way.
198 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
200 throw BindingException("Failed to decode an SSO protocol response.");
201 recoverRelayState(application, httpRequest, relayState);
202 string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
204 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
206 entityID = issuer.get();
210 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
214 pair<bool,long> AssertionConsumerService::sendRedirect(
215 SPRequest& request, const char* key, const char* entityID, const char* relayState
218 // We've got a good session, so set the session cookie.
219 pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
221 k += shib_cookie.second;
222 request.setCookie(shib_cookie.first.c_str(), k.c_str());
225 maintainHistory(request, entityID, shib_cookie.second);
227 // Now redirect to the state value. By now, it should be set to *something* usable.
228 return make_pair(true, request.sendRedirect(relayState));
231 void AssertionConsumerService::checkAddress(
232 const Application& application, const HTTPRequest& httpRequest, const char* issuedTo
235 const PropertySet* props=application.getPropertySet("Sessions");
236 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
237 if (!checkAddress.first)
238 checkAddress.second=true;
240 if (checkAddress.second) {
241 m_log.debug("checking client address");
242 if (httpRequest.getRemoteAddr() != issuedTo) {
243 throw FatalProfileException(
244 "Your client's current address ($client_addr) differs from the one used when you authenticated "
245 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
246 "Please contact your local support staff or help desk for assistance.",
247 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
255 void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
256 const char* loc = getString("Location").second;
257 string hurl(handlerURL);
261 auto_ptr_XMLCh widen(hurl.c_str());
262 saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
263 ep->setLocation(widen.get());
264 ep->setBinding(getXMLString("Binding").second);
265 ep->setIndex(getXMLString("index").second);
266 role.getAssertionConsumerServices().push_back(ep);
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 const saml2md::EntityDescriptor* entity = issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : NULL;
306 // First we do the extraction of any pushed information, including from metadata.
307 vector<Attribute*> resolvedAttributes;
308 AttributeExtractor* extractor = application.getAttributeExtractor();
310 Locker extlocker(extractor);
312 pair<bool,const char*> prefix = application.getString("metadataAttributePrefix");
314 m_log.debug("extracting metadata-derived attributes...");
316 extractor->extractAttributes(application, issuer, *entity, resolvedAttributes);
317 for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
318 vector<string>& ids = (*a)->getAliases();
319 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
320 *id = prefix.second + *id;
323 catch (exception& ex) {
324 m_log.error("caught exception extracting attributes: %s", ex.what());
328 m_log.debug("extracting pushed attributes...");
331 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
333 catch (exception& ex) {
334 m_log.error("caught exception extracting attributes: %s", ex.what());
339 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
341 catch (exception& ex) {
342 m_log.error("caught exception extracting attributes: %s", ex.what());
346 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
348 extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
350 catch (exception& ex) {
351 m_log.error("caught exception extracting attributes: %s", ex.what());
356 AttributeFilter* filter = application.getAttributeFilter();
357 if (filter && !resolvedAttributes.empty()) {
358 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
359 Locker filtlocker(filter);
361 filter->filterAttributes(fc, resolvedAttributes);
363 catch (exception& ex) {
364 m_log.error("caught exception filtering attributes: %s", ex.what());
365 m_log.error("dumping extracted attributes due to filtering exception");
366 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
367 resolvedAttributes.clear();
373 AttributeResolver* resolver = application.getAttributeResolver();
375 m_log.debug("resolving attributes...");
377 Locker locker(resolver);
378 auto_ptr<ResolutionContext> ctx(
379 resolver->createResolutionContext(
390 resolver->resolveAttributes(*ctx.get());
391 // Copy over any pushed attributes.
392 if (!resolvedAttributes.empty())
393 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
394 return ctx.release();
397 catch (exception& ex) {
398 m_log.error("attribute resolution failed: %s", ex.what());
401 if (!resolvedAttributes.empty())
402 return new DummyContext(resolvedAttributes);
406 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
408 policy.setMessageID(assertion.getID());
409 policy.setIssueInstant(assertion.getIssueInstantEpoch());
411 if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20P_NS)) {
412 const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
414 m_log.debug("extracting issuer from SAML 2.0 assertion");
415 policy.setIssuer(a2->getIssuer());
419 const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
421 m_log.debug("extracting issuer from SAML 1.x assertion");
422 policy.setIssuer(a1->getIssuer());
426 if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
427 m_log.debug("searching metadata for assertion issuer...");
428 const EntityDescriptor* entity = policy.getMetadataProvider()->getEntityDescriptor(policy.getIssuer()->getName());
430 m_log.debug("matched assertion issuer against metadata, searching for applicable role...");
431 const IDPSSODescriptor* idp=find_if(entity->getIDPSSODescriptors(), isValidForProtocol(protocol));
433 policy.setIssuerMetadata(idp);
434 else if (m_log.isWarnEnabled())
435 m_log.warn("unable to find compatible IdP role in metadata");
437 else if (m_log.isWarnEnabled()) {
438 auto_ptr_char iname(policy.getIssuer()->getName());
439 m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
446 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* entityID, const char* cookieProps) const
451 const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
452 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
453 if (!idpHistory.first || idpHistory.second) {
454 // Set an IdP history cookie locally (essentially just a CDC).
455 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
457 // Either leave in memory or set an expiration.
458 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
459 if (!days.first || days.second==0) {
460 string c = string(cdc.set(entityID)) + cookieProps;
461 request.setCookie(CommonDomainCookie::CDCName, c.c_str());
464 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
467 struct tm* ptime=gmtime_r(&now,&res);
469 struct tm* ptime=gmtime(&now);
472 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
473 string c = string(cdc.set(entityID)) + cookieProps + "; expires=" + timebuf;
474 request.setCookie(CommonDomainCookie::CDCName, c.c_str());