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/util/CommonDomainCookie.h>
30 #include <shibsp/SPConfig.h>
31 #include <shibsp/SPConstants.h>
37 using namespace shibsp;
38 using namespace shibtarget;
39 using namespace shibboleth;
41 using namespace log4cpp;
44 using opensaml::CommonDomainCookie;
45 using opensaml::URLEncoder;
48 class SessionInitiator : virtual public IHandler
51 SessionInitiator(const DOMElement* e) {}
52 ~SessionInitiator() {}
53 pair<bool,void*> run(ShibTarget* st, bool isHandler=true) const;
54 pair<bool,void*> ShibAuthnRequest(
56 const IHandler* shire,
59 const char* providerId
63 class SAML1Consumer : virtual public IHandler, public virtual Remoted
66 SAML1Consumer(const DOMElement* e);
68 pair<bool,void*> run(ShibTarget* st, bool isHandler=true) const;
69 DDF receive(const DDF& in);
75 int SAML1Consumer::counter = 0;
77 class ShibLogout : virtual public IHandler
80 ShibLogout(const DOMElement* e) {}
82 pair<bool,void*> run(ShibTarget* st, bool isHandler=true) const;
87 IPlugIn* ShibSessionInitiatorFactory(const DOMElement* e)
89 return new SessionInitiator(e);
92 IPlugIn* SAML1POSTFactory(const DOMElement* e)
94 return new SAML1Consumer(e);
97 IPlugIn* SAML1ArtifactFactory(const DOMElement* e)
99 return new SAML1Consumer(e);
102 IPlugIn* ShibLogoutFactory(const DOMElement* e)
104 return new ShibLogout(e);
107 pair<bool,void*> SessionInitiator::run(ShibTarget* st, bool isHandler) const
110 const char* resource=NULL;
111 const IHandler* ACS=NULL;
112 const IApplication* app=st->getApplication();
116 * Binding is CGI query string with:
117 * target the resource to direct back to later
118 * acsIndex optional index of an ACS to use on the way back in
119 * providerId optional direct invocation of a specific IdP
121 const char* option=st->getRequestParameter("acsIndex");
123 ACS=app->getAssertionConsumerServiceByIndex(atoi(option));
124 option=st->getRequestParameter("providerId");
126 resource=st->getRequestParameter("target");
127 if (!resource || !*resource) {
128 pair<bool,const char*> home=app->getString("homeURL");
130 resource=home.second;
132 throw FatalProfileException("Session initiator requires a target parameter or a homeURL application property.");
135 dupresource=resource;
136 resource=dupresource.c_str();
140 // Here we actually use metadata to invoke the SSO service directly.
141 // The only currently understood binding is the Shibboleth profile.
142 Metadata m(app->getMetadataProviders());
143 const IEntityDescriptor* entity=m.lookup(option);
145 throw MetadataException("Session initiator unable to locate metadata for provider ($1).", params(1,option));
146 const IIDPSSODescriptor* role=entity->getIDPSSODescriptor(shibspconstants::SHIB1_PROTOCOL_ENUM);
148 throw MetadataException(
149 "Session initiator unable to locate a Shibboleth-aware identity provider role for provider ($1).", params(1,option)
151 const IEndpointManager* SSO=role->getSingleSignOnServiceManager();
152 const IEndpoint* ep=SSO->getEndpointByBinding(shibspconstants::SHIB1_AUTHNREQUEST_PROFILE_URI);
154 throw MetadataException(
155 "Session initiator unable to locate compatible SSO service for provider ($1).", params(1,option)
157 auto_ptr_char dest(ep->getLocation());
158 return ShibAuthnRequest(
159 st,ACS ? ACS : app->getDefaultAssertionConsumerService(),dest.get(),resource,app->getString("providerId").second
164 // We're running as a "virtual handler" from within the filter.
165 // The target resource is the current one and everything else is defaulted.
166 resource=st->getRequestURL();
169 if (!ACS) ACS=app->getDefaultAssertionConsumerService();
171 // For now, we only support external session initiation via a wayfURL
172 pair<bool,const char*> wayfURL=getProperties()->getString("wayfURL");
174 throw ConfigurationException("Session initiator is missing wayfURL property.");
176 pair<bool,const XMLCh*> wayfBinding=getProperties()->getXMLString("wayfBinding");
177 if (!wayfBinding.first || !XMLString::compareString(wayfBinding.second,shibspconstants::SHIB1_AUTHNREQUEST_PROFILE_URI))
179 return ShibAuthnRequest(st,ACS,wayfURL.second,resource,app->getString("providerId").second);
180 else if (!strcmp(getProperties()->getString("wayfBinding").second,"urn:mace:shibboleth:1.0:profiles:EAuth")) {
181 // TODO: Finalize E-Auth profile URI
182 pair<bool,bool> localRelayState=st->getConfig()->getPropertySet("InProcess")->getBool("localRelayState");
183 if (!localRelayState.first || !localRelayState.second)
184 throw ConfigurationException("E-Authn requests cannot include relay state, so localRelayState must be enabled.");
186 // Here we store the state in a cookie.
187 pair<string,const char*> shib_cookie=st->getCookieNameProps("_shibstate_");
188 st->setCookie(shib_cookie.first,opensaml::SAMLConfig::getConfig().getURLEncoder()->encode(resource) + shib_cookie.second);
189 return make_pair(true, st->sendRedirect(wayfURL.second));
192 throw UnsupportedProfileException("Unsupported WAYF binding ($1).", params(1,getProperties()->getString("wayfBinding").second));
195 // Handles Shib 1.x AuthnRequest profile.
196 pair<bool,void*> SessionInitiator::ShibAuthnRequest(
198 const IHandler* shire,
201 const char* providerId
204 // Compute the ACS URL. We add the ACS location to the base handlerURL.
205 // Legacy configs will not have the Location property specified, so no suffix will be added.
206 string ACSloc=st->getHandlerURL(target);
207 pair<bool,const char*> loc=shire ? shire->getProperties()->getString("Location") : pair<bool,const char*>(false,NULL);
208 if (loc.first) ACSloc+=loc.second;
210 URLEncoder* urlenc = opensaml::SAMLConfig::getConfig().getURLEncoder();
213 sprintf(timebuf,"%u",time(NULL));
214 string req=string(dest) + "?shire=" + urlenc->encode(ACSloc.c_str()) + "&time=" + timebuf;
216 // How should the resource value be preserved?
217 pair<bool,bool> localRelayState=st->getConfig()->getPropertySet("InProcess")->getBool("localRelayState");
218 if (!localRelayState.first || !localRelayState.second) {
219 // The old way, just send it along.
220 req+="&target=" + urlenc->encode(target);
223 // Here we store the state in a cookie and send a fixed
224 // value to the IdP so we can recognize it on the way back.
225 pair<string,const char*> shib_cookie=st->getCookieNameProps("_shibstate_");
226 st->setCookie(shib_cookie.first,urlenc->encode(target) + shib_cookie.second);
227 req+="&target=cookie";
230 // Only omitted for 1.1 style requests.
232 req+="&providerId=" + urlenc->encode(providerId);
234 return make_pair(true, st->sendRedirect(req));
237 SAML1Consumer::SAML1Consumer(const DOMElement* e)
239 m_address += ('A' + (counter++));
240 m_address += "::SAML1Consumer::run";
242 // Register for remoted messages.
243 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
244 ListenerService* listener=ShibTargetConfig::getConfig().getINI()->getListener();
246 listener->regListener(m_address.c_str(),this);
248 throw ListenerException("Plugin requires a Listener service");
252 SAML1Consumer::~SAML1Consumer()
254 ListenerService* listener=ShibTargetConfig::getConfig().getINI()->getListener();
255 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
256 listener->unregListener(m_address.c_str(),this);
261 * IPC message definitions:
263 * [A-Z]::SAML1Consumer::run
269 * SAMLResponse or SAMLart list
275 DDF SAML1Consumer::receive(const DDF& in)
278 saml::NDC ndc("receive");
280 Category& log=Category::getInstance(SHIBT_LOGCAT".SAML1Consumer");
283 const char* aid=in["application_id"].string();
284 const IApplication* app=aid ? ShibTargetConfig::getConfig().getINI()->getApplication(aid) : NULL;
286 // Something's horribly wrong.
287 log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
288 throw SAMLException("Unable to locate application for new session, deleted?");
291 // Check required parameters.
292 const char* client_address=in["client_address"].string();
293 const char* recipient=in["recipient"].string();
294 if (!client_address || !recipient)
295 throw SAMLException("Required parameters missing in call to SAML1Consumer::run");
297 log.debug("processing new assertion for %s", client_address);
298 log.debug("recipient: %s", recipient);
299 log.debug("application: %s", app->getId());
301 // Access the application config. It's already locked behind us.
302 STConfig& stc=static_cast<STConfig&>(ShibTargetConfig::getConfig());
303 IConfig* conf=stc.getINI();
305 auto_ptr_XMLCh wrecipient(recipient);
307 pair<bool,bool> checkAddress=pair<bool,bool>(false,true);
308 pair<bool,bool> checkReplay=pair<bool,bool>(false,true);
309 const PropertySet* props=app->getPropertySet("Sessions");
311 checkAddress=props->getBool("checkAddress");
312 if (!checkAddress.first)
313 checkAddress.second=true;
314 checkReplay=props->getBool("checkReplay");
315 if (!checkReplay.first)
316 checkReplay.second=true;
319 // Supports either version...
320 pair<bool,unsigned int> version=getProperties()->getUnsignedInt("MinorVersion","urn:oasis:names:tc:SAML:1.0:protocol");
324 const IRoleDescriptor* role=NULL;
325 Metadata m(app->getMetadataProviders());
326 SAMLBrowserProfile::BrowserProfileResponse bpr;
329 const char* samlResponse=in["SAMLResponse"].string();
332 log.debug("executing Browser/POST profile...");
333 bpr=app->getBrowserProfile()->receive(
336 checkReplay.second ? conf->getReplayCache() : NULL,
342 vector<const char*> SAMLart;
343 DDF arts=in["SAMLart"];
344 DDF art=arts.first();
345 while (art.isstring()) {
346 SAMLart.push_back(art.string());
349 auto_ptr<SAMLBrowserProfile::ArtifactMapper> artifactMapper(app->getArtifactMapper());
350 log.debug("executing Browser/Artifact profile...");
351 bpr=app->getBrowserProfile()->receive(
354 artifactMapper.get(),
355 checkReplay.second ? conf->getReplayCache() : NULL,
359 // Blow it away to clear any locks that might be held.
360 delete artifactMapper.release();
363 // Try and map to metadata (again).
364 // Once the metadata layer is in the SAML core, the repetition should be fixed.
365 const IEntityDescriptor* provider=m.lookup(bpr.assertion->getIssuer());
366 if (!provider && bpr.authnStatement->getSubject()->getNameIdentifier() &&
367 bpr.authnStatement->getSubject()->getNameIdentifier()->getNameQualifier())
368 provider=m.lookup(bpr.authnStatement->getSubject()->getNameIdentifier()->getNameQualifier());
370 const IIDPSSODescriptor* IDP=provider->getIDPSSODescriptor(
371 version.second==1 ? saml::XML::SAML11_PROTOCOL_ENUM : saml::XML::SAML10_PROTOCOL_ENUM
376 // This isn't likely, since the profile must have found a role.
378 MetadataException ex("Unable to locate role-specific metadata for identity provider.");
379 annotateException(&ex,provider); // throws it
382 // Maybe verify the client address....
383 if (checkAddress.second) {
384 log.debug("verifying client address");
385 // Verify the client address exists
386 const XMLCh* wip = bpr.authnStatement->getSubjectIP();
388 // Verify the client address matches authentication
389 auto_ptr_char this_ip(wip);
390 if (strcmp(client_address, this_ip.get())) {
391 FatalProfileException ex(
392 SESSION_E_ADDRESSMISMATCH,
393 "Your client's current address ($1) differs from the one used when you authenticated "
394 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
395 "Please contact your local support staff or help desk for assistance.",
396 params(1,client_address)
398 annotateException(&ex,role); // throws it
403 catch (SAMLException&) {
408 log.error("caught unknown exception");
413 SAMLException e("An unexpected error occurred while creating your session.");
414 annotateException(&e,role);
418 // It passes all our tests -- create a new session.
419 log.info("creating new session");
423 // Insert into cache.
424 auto_ptr_char authContext(bpr.authnStatement->getAuthMethod());
425 string key=conf->getSessionCache()->insert(
427 role->getEntityDescriptor(),
429 bpr.authnStatement->getSubject(),
433 // objects owned by cache now
434 log.debug("new session id: %s", key.c_str());
435 auto_ptr_char oname(role->getEntityDescriptor()->getId());
436 out=DDF(NULL).structure();
437 out.addmember("key").string(key.c_str());
438 out.addmember("provider_id").string(oname.get());
444 SAMLException e("An unexpected error occurred while creating your session.");
445 annotateException(&e,role);
452 pair<bool,void*> SAML1Consumer::run(ShibTarget* st, bool isHandler) const
455 DDFJanitor jin(in),jout(out);
457 pair<bool,const XMLCh*> binding=getProperties()->getXMLString("Binding");
458 if (!binding.first || !XMLString::compareString(binding.second,SAMLBrowserProfile::BROWSER_POST)) {
459 #ifdef HAVE_STRCASECMP
460 if (strcasecmp(st->getRequestMethod(), "POST")) {
462 if (_stricmp(st->getRequestMethod(), "POST")) {
464 st->log(ShibTarget::LogLevelInfo, "SAML 1.x Browser/POST handler ignoring non-POST request");
465 return pair<bool,void*>(false,NULL);
467 #ifdef HAVE_STRCASECMP
468 if (!st->getContentType() || strcasecmp(st->getContentType(),"application/x-www-form-urlencoded")) {
470 if (!st->getContentType() || _stricmp(st->getContentType(),"application/x-www-form-urlencoded")) {
472 st->log(ShibTarget::LogLevelInfo, "SAML 1.x Browser/POST handler ignoring submission with unknown content-type.");
473 return pair<bool,void*>(false,NULL);
476 const char* samlResponse = st->getRequestParameter("SAMLResponse");
478 st->log(ShibTarget::LogLevelInfo, "SAML 1.x Browser/POST handler ignoring request with no SAMLResponse parameter.");
479 return pair<bool,void*>(false,NULL);
482 in=DDF(m_address.c_str()).structure();
483 in.addmember("SAMLResponse").string(samlResponse);
485 else if (!XMLString::compareString(binding.second,SAMLBrowserProfile::BROWSER_ARTIFACT)) {
486 #ifdef HAVE_STRCASECMP
487 if (strcasecmp(st->getRequestMethod(), "GET")) {
489 if (_stricmp(st->getRequestMethod(), "GET")) {
491 st->log(ShibTarget::LogLevelInfo, "SAML 1.x Browser/Artifact handler ignoring non-GET request");
492 return pair<bool,void*>(false,NULL);
495 const char* SAMLart=st->getRequestParameter("SAMLart");
497 st->log(ShibTarget::LogLevelInfo, "SAML 1.x Browser/Artifact handler ignoring request with no SAMLart parameter.");
498 return pair<bool,void*>(false,NULL);
501 in=DDF(m_address.c_str()).structure();
502 DDF artlist=in.addmember("SAMLart").list();
505 artlist.add(DDF(NULL).string(SAMLart));
506 SAMLart=st->getRequestParameter("SAMLart",artlist.integer());
510 // Compute the endpoint location.
511 string hURL=st->getHandlerURL(st->getRequestURL());
512 pair<bool,const char*> loc=getProperties()->getString("Location");
513 string recipient=loc.first ? hURL + loc.second : hURL;
514 in.addmember("recipient").string(recipient.c_str());
516 // Add remaining parameters.
517 in.addmember("application_id").string(st->getApplication()->getId());
518 in.addmember("client_address").string(st->getRemoteAddr());
520 out=st->getConfig()->getListener()->send(in);
521 if (!out["key"].isstring())
522 throw FatalProfileException("Remote processing of SAML 1.x Browser profile did not return a usable session key.");
523 string key=out["key"].string();
525 st->log(ShibTarget::LogLevelDebug, string("profile processing succeeded, new session created (") + key + ")");
527 const char* target=st->getRequestParameter("TARGET");
528 if (target && !strcmp(target,"default")) {
529 pair<bool,const char*> homeURL=st->getApplication()->getString("homeURL");
530 target=homeURL.first ? homeURL.second : "/";
532 else if (!target || !strcmp(target,"cookie")) {
533 // Pull the target value from the "relay state" cookie.
534 pair<string,const char*> relay_cookie = st->getCookieNameProps("_shibstate_");
535 const char* relay_state = st->getCookie(relay_cookie.first);
536 if (!relay_state || !*relay_state) {
537 // No apparent relay state value to use, so fall back on the default.
538 pair<bool,const char*> homeURL=st->getApplication()->getString("homeURL");
539 target=homeURL.first ? homeURL.second : "/";
542 char* rscopy=strdup(relay_state);
543 opensaml::SAMLConfig::getConfig().getURLEncoder()->decode(rscopy);
548 st->setCookie(relay_cookie.first,relay_cookie.second);
551 // We've got a good session, set the session cookie.
552 pair<string,const char*> shib_cookie=st->getCookieNameProps("_shibsession_");
553 st->setCookie(shib_cookie.first, key + shib_cookie.second);
555 const char* providerId=out["provider_id"].string();
557 const PropertySet* sessionProps=st->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(st->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 st->setCookie(CommonDomainCookie::CDCName,string(cdc.set(providerId)) + shib_cookie.second);
568 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
571 struct tm* ptime=gmtime_r(&now,&res);
573 struct tm* ptime=gmtime(&now);
576 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
578 CommonDomainCookie::CDCName,
579 string(cdc.set(providerId)) + shib_cookie.second + "; expires=" + timebuf
585 // Now redirect to the target.
586 return make_pair(true, st->sendRedirect(target));
589 pair<bool,void*> ShibLogout::run(ShibTarget* st, bool isHandler) const
591 // Recover the session key.
592 pair<string,const char*> shib_cookie = st->getCookieNameProps("_shibsession_");
593 const char* session_id = st->getCookie(shib_cookie.first);
595 // Logout is best effort.
596 if (session_id && *session_id) {
598 st->getConfig()->getSessionCache()->remove(session_id,st->getApplication(),st->getRemoteAddr());
600 catch (SAMLException& e) {
601 st->log(ShibTarget::LogLevelError, string("logout processing failed with exception: ") + e.what());
605 st->log(ShibTarget::LogLevelError, "logout processing failed with unknown exception");
608 // We send the cookie property alone, which acts as an empty value.
609 st->setCookie(shib_cookie.first,shib_cookie.second);
612 const char* ret=st->getRequestParameter("return");
614 ret=getProperties()->getString("ResponseLocation").second;
616 ret=st->getApplication()->getString("homeURL").second;
619 return make_pair(true, st->sendRedirect(ret));