2 * Copyright 2001-2005 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 * shib-handlers.cpp -- profile handlers that plug into SP
27 #include <saml/SAMLConfig.h>
28 #include <saml/binding/URLEncoder.h>
29 #include <saml/saml2/metadata/Metadata.h>
30 #include <saml/saml2/metadata/EndpointManager.h>
31 #include <saml/util/CommonDomainCookie.h>
32 #include <shibsp/AbstractHandler.h>
33 #include <shibsp/SPConfig.h>
39 using namespace shibsp;
40 using namespace shibtarget;
41 using namespace shibboleth;
43 using namespace opensaml::saml2md;
44 using namespace log4cpp;
47 using opensaml::CommonDomainCookie;
48 using opensaml::URLEncoder;
50 #if defined (_MSC_VER)
51 #pragma warning( push )
52 #pragma warning( disable : 4250 )
56 class SessionInitiator : public AbstractHandler
59 SessionInitiator(const DOMElement* e) : AbstractHandler(e) {}
60 ~SessionInitiator() {}
61 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
62 pair<bool,long> ShibAuthnRequest(
67 const char* providerId
71 class SAML1Consumer : public AbstractHandler, public virtual Remoted
74 SAML1Consumer(const DOMElement* e);
76 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
77 DDF receive(const DDF& in);
83 int SAML1Consumer::counter = 0;
85 class ShibLogout : public AbstractHandler
88 ShibLogout(const DOMElement* e) : AbstractHandler(e) {}
90 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
94 #if defined (_MSC_VER)
95 #pragma warning( pop )
98 Handler* ShibSessionInitiatorFactory(const DOMElement* const & e)
100 return new SessionInitiator(e);
103 Handler* SAML1POSTFactory(const DOMElement* const & e)
105 return new SAML1Consumer(e);
108 Handler* SAML1ArtifactFactory(const DOMElement* const & e)
110 return new SAML1Consumer(e);
113 Handler* ShibLogoutFactory(const DOMElement* const & e)
115 return new ShibLogout(e);
118 pair<bool,long> SessionInitiator::run(SPRequest& request, bool isHandler) const
121 const char* resource=NULL;
122 const Handler* ACS=NULL;
123 const IApplication& app=dynamic_cast<const IApplication&>(request.getApplication());
127 * Binding is CGI query string with:
128 * target the resource to direct back to later
129 * acsIndex optional index of an ACS to use on the way back in
130 * providerId optional direct invocation of a specific IdP
132 const char* option=request.getParameter("acsIndex");
134 ACS=app.getAssertionConsumerServiceByIndex(atoi(option));
135 option=request.getParameter("providerId");
137 resource=request.getParameter("target");
138 if (!resource || !*resource) {
139 pair<bool,const char*> home=app.getString("homeURL");
141 resource=home.second;
143 throw opensaml::FatalProfileException("Session initiator requires a target parameter or a homeURL application property.");
146 dupresource=resource;
147 resource=dupresource.c_str();
151 // Here we actually use metadata to invoke the SSO service directly.
152 // The only currently understood binding is the Shibboleth profile.
154 MetadataProvider* m=app.getMetadataProvider();
155 xmltooling::Locker locker(m);
156 const EntityDescriptor* entity=m->getEntityDescriptor(option);
158 throw MetadataException("Session initiator unable to locate metadata for provider ($1).", xmltooling::params(1,option));
159 const IDPSSODescriptor* role=entity->getIDPSSODescriptor(shibspconstants::SHIB1_PROTOCOL_ENUM);
161 throw MetadataException(
162 "Session initiator unable to locate a Shibboleth-aware identity provider role for provider ($1).",
163 xmltooling::params(1,option)
165 const EndpointType* ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(
166 shibspconstants::SHIB1_AUTHNREQUEST_PROFILE_URI
169 throw MetadataException(
170 "Session initiator unable to locate compatible SSO service for provider ($1).", xmltooling::params(1,option)
172 auto_ptr_char dest(ep->getLocation());
173 return ShibAuthnRequest(
174 request,ACS ? ACS : app.getDefaultAssertionConsumerService(),dest.get(),resource,app.getString("providerId").second
179 // We're running as a "virtual handler" from within the filter.
180 // The target resource is the current one and everything else is defaulted.
181 resource=request.getRequestURL();
184 if (!ACS) ACS=app.getDefaultAssertionConsumerService();
186 // For now, we only support external session initiation via a wayfURL
187 pair<bool,const char*> wayfURL=getString("wayfURL");
189 throw ConfigurationException("Session initiator is missing wayfURL property.");
191 pair<bool,const XMLCh*> wayfBinding=getXMLString("wayfBinding");
192 if (!wayfBinding.first || !XMLString::compareString(wayfBinding.second,shibspconstants::SHIB1_AUTHNREQUEST_PROFILE_URI))
194 return ShibAuthnRequest(request,ACS,wayfURL.second,resource,app.getString("providerId").second);
195 else if (!strcmp(getString("wayfBinding").second,"urn:mace:shibboleth:1.0:profiles:EAuth")) {
196 // TODO: Finalize E-Auth profile URI
197 pair<bool,bool> localRelayState=request.getServiceProvider().getPropertySet("InProcess")->getBool("localRelayState");
198 if (!localRelayState.first || !localRelayState.second)
199 throw ConfigurationException("E-Authn requests cannot include relay state, so localRelayState must be enabled.");
201 // Here we store the state in a cookie.
202 pair<string,const char*> shib_cookie=app.getCookieNameProps("_shibstate_");
203 string stateval = opensaml::SAMLConfig::getConfig().getURLEncoder()->encode(resource) + shib_cookie.second;
204 request.setCookie(shib_cookie.first.c_str(),stateval.c_str());
205 return make_pair(true, request.sendRedirect(wayfURL.second));
208 throw opensaml::BindingException("Unsupported WAYF binding ($1).", xmltooling::params(1,getString("wayfBinding").second));
211 // Handles Shib 1.x AuthnRequest profile.
212 pair<bool,long> SessionInitiator::ShibAuthnRequest(
214 const Handler* shire,
217 const char* providerId
220 // Compute the ACS URL. We add the ACS location to the base handlerURL.
221 // Legacy configs will not have the Location property specified, so no suffix will be added.
222 string ACSloc=request.getHandlerURL(target);
223 pair<bool,const char*> loc=shire ? shire->getString("Location") : pair<bool,const char*>(false,NULL);
224 if (loc.first) ACSloc+=loc.second;
226 URLEncoder* urlenc = opensaml::SAMLConfig::getConfig().getURLEncoder();
229 sprintf(timebuf,"%u",time(NULL));
230 string req=string(dest) + "?shire=" + urlenc->encode(ACSloc.c_str()) + "&time=" + timebuf;
232 // How should the resource value be preserved?
233 pair<bool,bool> localRelayState=request.getServiceProvider().getPropertySet("InProcess")->getBool("localRelayState");
234 if (!localRelayState.first || !localRelayState.second) {
235 // The old way, just send it along.
236 req+="&target=" + urlenc->encode(target);
239 // Here we store the state in a cookie and send a fixed
240 // value to the IdP so we can recognize it on the way back.
241 pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibstate_");
242 string stateval = urlenc->encode(target) + shib_cookie.second;
243 request.setCookie(shib_cookie.first.c_str(),stateval.c_str());
244 req+="&target=cookie";
247 // Only omitted for 1.1 style requests.
249 req+="&providerId=" + urlenc->encode(providerId);
251 return make_pair(true, request.sendRedirect(req.c_str()));
254 SAML1Consumer::SAML1Consumer(const DOMElement* e) : AbstractHandler(e)
256 m_address += ('A' + (counter++));
257 m_address += "::SAML1Consumer::run";
259 // Register for remoted messages.
260 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
261 SPConfig::getConfig().getServiceProvider()->getListenerService()->regListener(m_address.c_str(),this);
264 SAML1Consumer::~SAML1Consumer()
266 ListenerService* listener=SPConfig::getConfig().getServiceProvider()->getListenerService(false);
267 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
268 listener->unregListener(m_address.c_str(),this);
273 * IPC message definitions:
275 * [A-Z]::SAML1Consumer::run
281 * SAMLResponse or SAMLart list
287 DDF SAML1Consumer::receive(const DDF& in)
290 xmltooling::NDC ndc("receive");
292 Category& log=Category::getInstance(SHIBT_LOGCAT".SAML1Consumer");
295 const char* aid=in["application_id"].string();
296 const IApplication* app=aid ? dynamic_cast<const IApplication*>(SPConfig::getConfig().getServiceProvider()->getApplication(aid)) : NULL;
298 // Something's horribly wrong.
299 log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
300 throw SAMLException("Unable to locate application for new session, deleted?");
303 // Check required parameters.
304 const char* client_address=in["client_address"].string();
305 const char* recipient=in["recipient"].string();
306 if (!client_address || !recipient)
307 throw SAMLException("Required parameters missing in call to SAML1Consumer::run");
309 log.debug("processing new assertion for %s", client_address);
310 log.debug("recipient: %s", recipient);
311 log.debug("application: %s", app->getId());
313 // Access the application config.
314 ServiceProvider* conf=SPConfig::getConfig().getServiceProvider();
315 xmltooling::Locker confLocker(conf);
317 auto_ptr_XMLCh wrecipient(recipient);
319 pair<bool,bool> checkAddress=pair<bool,bool>(false,true);
320 pair<bool,bool> checkReplay=pair<bool,bool>(false,true);
321 const PropertySet* props=app->getPropertySet("Sessions");
323 checkAddress=props->getBool("checkAddress");
324 if (!checkAddress.first)
325 checkAddress.second=true;
326 checkReplay=props->getBool("checkReplay");
327 if (!checkReplay.first)
328 checkReplay.second=true;
331 // Supports either version...
332 pair<bool,unsigned int> version=getUnsignedInt("MinorVersion","urn:oasis:names:tc:SAML:1.0:protocol");
336 const EntityDescriptor* provider=NULL;
337 const RoleDescriptor* role=NULL;
338 MetadataProvider* m=app->getMetadataProvider();
339 xmltooling::Locker locker(m);
340 SAMLBrowserProfile::BrowserProfileResponse bpr;
343 const char* samlResponse=in["SAMLResponse"].string();
346 log.debug("executing Browser/POST profile...");
347 bpr=app->getBrowserProfile()->receive(
356 vector<const char*> SAMLart;
357 DDF arts=in["SAMLart"];
358 DDF art=arts.first();
359 while (art.isstring()) {
360 SAMLart.push_back(art.string());
363 auto_ptr<SAMLBrowserProfile::ArtifactMapper> artifactMapper(app->getArtifactMapper());
364 log.debug("executing Browser/Artifact profile...");
365 bpr=app->getBrowserProfile()->receive(
368 artifactMapper.get(),
373 // Blow it away to clear any locks that might be held.
374 delete artifactMapper.release();
377 // Try and map to metadata (again).
378 // Once the metadata layer is in the SAML core, the repetition will be fixed.
379 provider=m->getEntityDescriptor(bpr.assertion->getIssuer());
380 if (!provider && bpr.authnStatement->getSubject()->getNameIdentifier() &&
381 bpr.authnStatement->getSubject()->getNameIdentifier()->getNameQualifier())
382 provider=m->getEntityDescriptor(bpr.authnStatement->getSubject()->getNameIdentifier()->getNameQualifier());
384 role=provider->getIDPSSODescriptor(
385 version.second==1 ? samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM
389 // This isn't likely, since the profile must have found a role.
391 MetadataException ex("Unable to locate role-specific metadata for identity provider.");
392 annotateException(&ex,provider); // throws it
395 // Maybe verify the client address....
396 if (checkAddress.second) {
397 log.debug("verifying client address");
398 // Verify the client address exists
399 const XMLCh* wip = bpr.authnStatement->getSubjectIP();
401 // Verify the client address matches authentication
402 auto_ptr_char this_ip(wip);
403 if (strcmp(client_address, this_ip.get())) {
404 opensaml::FatalProfileException ex(
405 "Your client's current address ($1) differs from the one used when you authenticated "
406 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
407 "Please contact your local support staff or help desk for assistance.",
408 xmltooling::params(1,client_address)
410 annotateException(&ex,role); // throws it
420 log.error("caught unknown exception");
425 SAMLException e("An unexpected error occurred while creating your session.");
426 shibboleth::annotateException(&e,role);
430 // It passes all our tests -- create a new session.
431 log.info("creating new session");
433 // Insert into cache.
434 auto_ptr_char authContext(bpr.authnStatement->getAuthMethod());
435 string key=dynamic_cast<ISessionCache*>(conf->getSessionCache())->insert(
439 bpr.authnStatement->getSubject(),
443 // objects owned by cache now
444 log.debug("new session id: %s", key.c_str());
445 auto_ptr_char oname(provider->getEntityID());
446 DDF out=DDF(NULL).structure();
447 out.addmember("key").string(key.c_str());
448 out.addmember("provider_id").string(oname.get());
453 pair<bool,long> SAML1Consumer::run(SPRequest& request, bool isHandler) const
456 DDFJanitor jin(in),jout(out);
458 pair<bool,const XMLCh*> binding=getXMLString("Binding");
459 if (!binding.first || !XMLString::compareString(binding.second,SAMLBrowserProfile::BROWSER_POST)) {
460 #ifdef HAVE_STRCASECMP
461 if (strcasecmp(request.getMethod(), "POST")) {
463 if (_stricmp(request.getMethod(), "POST")) {
465 request.log(SPRequest::SPInfo, "SAML 1.x Browser/POST handler ignoring non-POST request");
466 return pair<bool,long>(false,NULL);
468 #ifdef HAVE_STRCASECMP
469 if (strcasecmp(request.getContentType().c_str(),"application/x-www-form-urlencoded")) {
471 if (_stricmp(request.getContentType().c_str(),"application/x-www-form-urlencoded")) {
473 request.log(SPRequest::SPInfo, "SAML 1.x Browser/POST handler ignoring submission with unknown content-type.");
474 return pair<bool,long>(false,0);
477 const char* samlResponse = request.getParameter("SAMLResponse");
479 request.log(SPRequest::SPInfo, "SAML 1.x Browser/POST handler ignoring request with no SAMLResponse parameter.");
480 return pair<bool,long>(false,0);
483 in=DDF(m_address.c_str()).structure();
484 in.addmember("SAMLResponse").string(samlResponse);
486 else if (!XMLString::compareString(binding.second,SAMLBrowserProfile::BROWSER_ARTIFACT)) {
487 #ifdef HAVE_STRCASECMP
488 if (strcasecmp(request.getMethod(), "GET")) {
490 if (_stricmp(request.getMethod(), "GET")) {
492 request.log(SPRequest::SPInfo, "SAML 1.x Browser/Artifact handler ignoring non-GET request");
493 return pair<bool,long>(false,0);
496 vector<const char*> arts;
497 if (request.getParameters("SAMLart",arts)==0) {
498 request.log(SPRequest::SPInfo, "SAML 1.x Browser/Artifact handler ignoring request with no SAMLart parameter.");
499 return pair<bool,long>(false,0);
502 in=DDF(m_address.c_str()).structure();
503 DDF artlist=in.addmember("SAMLart").list();
505 for (vector<const char*>::const_iterator a=arts.begin(); a!=arts.end(); ++a)
506 artlist.add(DDF(NULL).string(*a));
509 // Compute the endpoint location.
510 string hURL=request.getHandlerURL(request.getRequestURL());
511 pair<bool,const char*> loc=getString("Location");
512 string recipient=loc.first ? hURL + loc.second : hURL;
513 in.addmember("recipient").string(recipient.c_str());
515 // Add remaining parameters.
516 in.addmember("application_id").string(request.getApplication().getId());
517 in.addmember("client_address").string(request.getRemoteAddr().c_str());
519 out=request.getServiceProvider().getListenerService()->send(in);
520 if (!out["key"].isstring())
521 throw opensaml::FatalProfileException("Remote processing of SAML 1.x Browser profile did not return a usable session key.");
522 string key=out["key"].string();
524 request.log(SPRequest::SPDebug, string("profile processing succeeded, new session created (") + key + ")");
526 const char* target=request.getParameter("TARGET");
527 if (target && !strcmp(target,"default")) {
528 pair<bool,const char*> homeURL=request.getApplication().getString("homeURL");
529 target=homeURL.first ? homeURL.second : "/";
531 else if (!target || !strcmp(target,"cookie")) {
532 // Pull the target value from the "relay state" cookie.
533 pair<string,const char*> relay_cookie = request.getApplication().getCookieNameProps("_shibstate_");
534 const char* relay_state = request.getCookie(relay_cookie.first.c_str());
535 if (!relay_state || !*relay_state) {
536 // No apparent relay state value to use, so fall back on the default.
537 pair<bool,const char*> homeURL=request.getApplication().getString("homeURL");
538 target=homeURL.first ? homeURL.second : "/";
541 char* rscopy=strdup(relay_state);
542 opensaml::SAMLConfig::getConfig().getURLEncoder()->decode(rscopy);
547 request.setCookie(relay_cookie.first.c_str(),relay_cookie.second);
550 // We've got a good session, set the session cookie.
551 pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
552 key += shib_cookie.second;
553 request.setCookie(shib_cookie.first.c_str(), key.c_str());
555 const char* providerId=out["provider_id"].string();
557 const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
558 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
559 if (!idpHistory.first || idpHistory.second) {
560 // Set an IdP history cookie locally (essentially just a CDC).
561 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
563 // Either leave in memory or set an expiration.
564 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
565 if (!days.first || days.second==0) {
566 key = string(cdc.set(providerId)) + shib_cookie.second;
567 request.setCookie(CommonDomainCookie::CDCName, key.c_str());
570 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
573 struct tm* ptime=gmtime_r(&now,&res);
575 struct tm* ptime=gmtime(&now);
578 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
579 key = string(cdc.set(providerId)) + shib_cookie.second + "; expires=" + timebuf;
580 request.setCookie(CommonDomainCookie::CDCName, key.c_str());
585 // Now redirect to the target.
586 return make_pair(true, request.sendRedirect(target));
589 pair<bool,long> ShibLogout::run(SPRequest& request, bool isHandler) const
591 // Recover the session key.
592 pair<string,const char*> shib_cookie = request.getApplication().getCookieNameProps("_shibsession_");
593 const char* session_id = request.getCookie(shib_cookie.first.c_str());
595 // Logout is best effort.
596 if (session_id && *session_id) {
598 // TODO: port to new cache API
599 //request.getServiceProvider().getSessionCache()->remove(session_id,request.getApplication(),request.getRemoteAddr().c_str());
601 catch (exception& e) {
602 request.log(SPRequest::SPError, string("logout processing failed with exception: ") + e.what());
606 request.log(SPRequest::SPError, "logout processing failed with unknown exception");
609 // We send the cookie property alone, which acts as an empty value.
610 request.setCookie(shib_cookie.first.c_str(),shib_cookie.second);
613 const char* ret=request.getParameter("return");
615 ret=getString("ResponseLocation").second;
617 ret=request.getApplication().getString("homeURL").second;
620 return make_pair(true, request.sendRedirect(ret));