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
26 #include <saml/util/CommonDomainCookie.h>
34 using namespace shibboleth;
35 using namespace shibtarget;
36 using namespace log4cpp;
38 using opensaml::CommonDomainCookie;
41 class SessionInitiator : virtual public IHandler
44 SessionInitiator(const DOMElement* e) {}
45 ~SessionInitiator() {}
46 pair<bool,void*> run(ShibTarget* st, bool isHandler=true) const;
47 pair<bool,void*> ShibAuthnRequest(
49 const IHandler* shire,
52 const char* providerId
56 class SAML1Consumer : virtual public IHandler, public virtual IRemoted
59 SAML1Consumer(const DOMElement* e);
61 pair<bool,void*> run(ShibTarget* st, bool isHandler=true) const;
62 DDF receive(const DDF& in);
68 int SAML1Consumer::counter = 0;
70 class ShibLogout : virtual public IHandler
73 ShibLogout(const DOMElement* e) {}
75 pair<bool,void*> run(ShibTarget* st, bool isHandler=true) const;
80 IPlugIn* ShibSessionInitiatorFactory(const DOMElement* e)
82 return new SessionInitiator(e);
85 IPlugIn* SAML1POSTFactory(const DOMElement* e)
87 return new SAML1Consumer(e);
90 IPlugIn* SAML1ArtifactFactory(const DOMElement* e)
92 return new SAML1Consumer(e);
95 IPlugIn* ShibLogoutFactory(const DOMElement* e)
97 return new ShibLogout(e);
100 pair<bool,void*> SessionInitiator::run(ShibTarget* st, bool isHandler) const
103 const char* resource=NULL;
104 const IHandler* ACS=NULL;
105 const IApplication* app=st->getApplication();
109 * Binding is CGI query string with:
110 * target the resource to direct back to later
111 * acsIndex optional index of an ACS to use on the way back in
112 * providerId optional direct invocation of a specific IdP
114 const char* option=st->getRequestParameter("acsIndex");
116 ACS=app->getAssertionConsumerServiceByIndex(atoi(option));
117 option=st->getRequestParameter("providerId");
119 resource=st->getRequestParameter("target");
120 if (!resource || !*resource) {
121 pair<bool,const char*> home=app->getString("homeURL");
123 resource=home.second;
125 throw FatalProfileException("Session initiator requires a target parameter or a homeURL application property.");
128 dupresource=resource;
129 resource=dupresource.c_str();
133 // Here we actually use metadata to invoke the SSO service directly.
134 // The only currently understood binding is the Shibboleth profile.
135 Metadata m(app->getMetadataProviders());
136 const IEntityDescriptor* entity=m.lookup(option);
138 throw MetadataException("Session initiator unable to locate metadata for provider ($1).", params(1,option));
139 const IIDPSSODescriptor* role=entity->getIDPSSODescriptor(Constants::SHIB_NS);
141 throw MetadataException(
142 "Session initiator unable to locate a Shibboleth-aware identity provider role for provider ($1).", params(1,option)
144 const IEndpointManager* SSO=role->getSingleSignOnServiceManager();
145 const IEndpoint* ep=SSO->getEndpointByBinding(Constants::SHIB_AUTHNREQUEST_PROFILE_URI);
147 throw MetadataException(
148 "Session initiator unable to locate compatible SSO service for provider ($1).", params(1,option)
150 auto_ptr_char dest(ep->getLocation());
151 return ShibAuthnRequest(
152 st,ACS ? ACS : app->getDefaultAssertionConsumerService(),dest.get(),resource,app->getString("providerId").second
157 // We're running as a "virtual handler" from within the filter.
158 // The target resource is the current one and everything else is defaulted.
159 resource=st->getRequestURL();
162 if (!ACS) ACS=app->getDefaultAssertionConsumerService();
164 // For now, we only support external session initiation via a wayfURL
165 pair<bool,const char*> wayfURL=getProperties()->getString("wayfURL");
167 throw ConfigurationException("Session initiator is missing wayfURL property.");
169 pair<bool,const XMLCh*> wayfBinding=getProperties()->getXMLString("wayfBinding");
170 if (!wayfBinding.first || !XMLString::compareString(wayfBinding.second,Constants::SHIB_AUTHNREQUEST_PROFILE_URI))
172 return ShibAuthnRequest(st,ACS,wayfURL.second,resource,app->getString("providerId").second);
173 else if (!XMLString::compareString(wayfBinding.second,Constants::SHIB_LEGACY_AUTHNREQUEST_PROFILE_URI))
175 return ShibAuthnRequest(st,ACS,wayfURL.second,resource,NULL);
176 else if (!strcmp(getProperties()->getString("wayfBinding").second,"urn:mace:shibboleth:1.0:profiles:EAuth")) {
177 // TODO: Finalize E-Auth profile URI
178 pair<bool,bool> localRelayState=st->getConfig()->getPropertySet("InProcess")->getBool("localRelayState");
179 if (!localRelayState.first || !localRelayState.second)
180 throw ConfigurationException("E-Authn requests cannot include relay state, so localRelayState must be enabled.");
182 // Here we store the state in a cookie.
183 pair<string,const char*> shib_cookie=st->getCookieNameProps("_shibstate_");
184 st->setCookie(shib_cookie.first,ShibTarget::url_encode(resource) + shib_cookie.second);
185 return make_pair(true, st->sendRedirect(wayfURL.second));
188 throw UnsupportedProfileException("Unsupported WAYF binding ($1).", params(1,getProperties()->getString("wayfBinding").second));
191 // Handles Shib 1.x AuthnRequest profile.
192 pair<bool,void*> SessionInitiator::ShibAuthnRequest(
194 const IHandler* shire,
197 const char* providerId
200 // Compute the ACS URL. We add the ACS location to the base handlerURL.
201 // Legacy configs will not have the Location property specified, so no suffix will be added.
202 string ACSloc=st->getHandlerURL(target);
203 pair<bool,const char*> loc=shire ? shire->getProperties()->getString("Location") : pair<bool,const char*>(false,NULL);
204 if (loc.first) ACSloc+=loc.second;
207 sprintf(timebuf,"%u",time(NULL));
208 string req=string(dest) + "?shire=" + ShibTarget::url_encode(ACSloc.c_str()) + "&time=" + timebuf;
210 // How should the resource value be preserved?
211 pair<bool,bool> localRelayState=st->getConfig()->getPropertySet("InProcess")->getBool("localRelayState");
212 if (!localRelayState.first || !localRelayState.second) {
213 // The old way, just send it along.
214 req+="&target=" + ShibTarget::url_encode(target);
217 // Here we store the state in a cookie and send a fixed
218 // value to the IdP so we can recognize it on the way back.
219 pair<string,const char*> shib_cookie=st->getCookieNameProps("_shibstate_");
220 st->setCookie(shib_cookie.first,ShibTarget::url_encode(target) + shib_cookie.second);
221 req+="&target=cookie";
224 // Only omitted for 1.1 style requests.
226 req+="&providerId=" + ShibTarget::url_encode(providerId);
228 return make_pair(true, st->sendRedirect(req));
231 SAML1Consumer::SAML1Consumer(const DOMElement* e)
233 m_address += ('A' + (counter++));
234 m_address += "::SAML1Consumer::run";
236 // Register for remoted messages.
237 if (ShibTargetConfig::getConfig().isEnabled(ShibTargetConfig::OutOfProcess)) {
238 IListener* listener=ShibTargetConfig::getConfig().getINI()->getListener();
240 listener->regListener(m_address.c_str(),this);
242 throw ListenerException("Plugin requires a Listener service");
246 SAML1Consumer::~SAML1Consumer()
248 IListener* listener=ShibTargetConfig::getConfig().getINI()->getListener();
249 if (listener && ShibTargetConfig::getConfig().isEnabled(ShibTargetConfig::OutOfProcess))
250 listener->unregListener(m_address.c_str(),this);
255 * IPC message definitions:
257 * [A-Z]::SAML1Consumer::run
263 * SAMLResponse or SAMLart list
269 DDF SAML1Consumer::receive(const DDF& in)
272 saml::NDC ndc("receive");
274 Category& log=Category::getInstance(SHIBT_LOGCAT".SAML1Consumer");
277 const char* aid=in["application_id"].string();
278 const IApplication* app=aid ? ShibTargetConfig::getConfig().getINI()->getApplication(aid) : NULL;
280 // Something's horribly wrong.
281 log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
282 throw SAMLException("Unable to locate application for new session, deleted?");
285 // Check required parameters.
286 const char* client_address=in["client_address"].string();
287 const char* recipient=in["recipient"].string();
288 if (!client_address || !recipient)
289 throw SAMLException("Required parameters missing in call to SAML1Consumer::run");
291 log.debug("processing new assertion for %s", client_address);
292 log.debug("recipient: %s", recipient);
293 log.debug("application: %s", app->getId());
295 // Access the application config. It's already locked behind us.
296 STConfig& stc=static_cast<STConfig&>(ShibTargetConfig::getConfig());
297 IConfig* conf=stc.getINI();
299 auto_ptr_XMLCh wrecipient(recipient);
301 pair<bool,bool> checkAddress=pair<bool,bool>(false,true);
302 pair<bool,bool> checkReplay=pair<bool,bool>(false,true);
303 const IPropertySet* props=app->getPropertySet("Sessions");
305 checkAddress=props->getBool("checkAddress");
306 if (!checkAddress.first)
307 checkAddress.second=true;
308 checkReplay=props->getBool("checkReplay");
309 if (!checkReplay.first)
310 checkReplay.second=true;
313 // Supports either version...
314 pair<bool,unsigned int> version=getProperties()->getUnsignedInt("MinorVersion","urn:oasis:names:tc:SAML:1.0:protocol");
318 const IRoleDescriptor* role=NULL;
319 Metadata m(app->getMetadataProviders());
320 SAMLBrowserProfile::BrowserProfileResponse bpr;
323 const char* samlResponse=in["SAMLResponse"].string();
326 log.debug("executing Browser/POST profile...");
327 bpr=app->getBrowserProfile()->receive(
330 checkReplay.second ? conf->getReplayCache() : NULL,
336 vector<const char*> SAMLart;
337 DDF arts=in["SAMLart"];
338 DDF art=arts.first();
339 while (art.isstring()) {
340 SAMLart.push_back(art.string());
343 auto_ptr<SAMLBrowserProfile::ArtifactMapper> artifactMapper(app->getArtifactMapper());
344 log.debug("executing Browser/Artifact profile...");
345 bpr=app->getBrowserProfile()->receive(
348 artifactMapper.get(),
349 checkReplay.second ? conf->getReplayCache() : NULL,
353 // Blow it away to clear any locks that might be held.
354 delete artifactMapper.release();
357 // Try and map to metadata (again).
358 // Once the metadata layer is in the SAML core, the repetition should be fixed.
359 const IEntityDescriptor* provider=m.lookup(bpr.assertion->getIssuer());
360 if (!provider && bpr.authnStatement->getSubject()->getNameIdentifier() &&
361 bpr.authnStatement->getSubject()->getNameIdentifier()->getNameQualifier())
362 provider=m.lookup(bpr.authnStatement->getSubject()->getNameIdentifier()->getNameQualifier());
364 const IIDPSSODescriptor* IDP=provider->getIDPSSODescriptor(
365 version.second==1 ? saml::XML::SAML11_PROTOCOL_ENUM : saml::XML::SAML10_PROTOCOL_ENUM
370 // This isn't likely, since the profile must have found a role.
372 MetadataException ex("Unable to locate role-specific metadata for identity provider.");
373 annotateException(&ex,provider); // throws it
376 // Maybe verify the client address....
377 if (checkAddress.second) {
378 log.debug("verifying client address");
379 // Verify the client address exists
380 const XMLCh* wip = bpr.authnStatement->getSubjectIP();
382 // Verify the client address matches authentication
383 auto_ptr_char this_ip(wip);
384 if (strcmp(client_address, this_ip.get())) {
385 FatalProfileException ex(
386 SESSION_E_ADDRESSMISMATCH,
387 "Your client's current address ($1) differs from the one used when you authenticated "
388 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
389 "Please contact your local support staff or help desk for assistance.",
390 params(1,client_address)
392 annotateException(&ex,role); // throws it
397 catch (SAMLException&) {
402 log.error("caught unknown exception");
407 SAMLException e("An unexpected error occurred while creating your session.");
408 annotateException(&e,role);
412 // It passes all our tests -- create a new session.
413 log.info("creating new session");
417 // Insert into cache.
418 auto_ptr_char authContext(bpr.authnStatement->getAuthMethod());
419 string key=conf->getSessionCache()->insert(
421 role->getEntityDescriptor(),
423 bpr.authnStatement->getSubject(),
427 // objects owned by cache now
428 log.debug("new session id: %s", key.c_str());
429 auto_ptr_char oname(role->getEntityDescriptor()->getId());
430 out=DDF(NULL).structure();
431 out.addmember("key").string(key.c_str());
432 out.addmember("provider_id").string(oname.get());
438 SAMLException e("An unexpected error occurred while creating your session.");
439 annotateException(&e,role);
446 pair<bool,void*> SAML1Consumer::run(ShibTarget* st, bool isHandler) const
449 DDFJanitor jin(in),jout(out);
451 pair<bool,const XMLCh*> binding=getProperties()->getXMLString("Binding");
452 if (!binding.first || !XMLString::compareString(binding.second,SAMLBrowserProfile::BROWSER_POST)) {
453 #ifdef HAVE_STRCASECMP
454 if (strcasecmp(st->getRequestMethod(), "POST")) {
456 if (_stricmp(st->getRequestMethod(), "POST")) {
458 st->log(ShibTarget::LogLevelInfo, "SAML 1.x Browser/POST handler ignoring non-POST request");
459 return pair<bool,void*>(false,NULL);
461 #ifdef HAVE_STRCASECMP
462 if (!st->getContentType() || strcasecmp(st->getContentType(),"application/x-www-form-urlencoded")) {
464 if (!st->getContentType() || _stricmp(st->getContentType(),"application/x-www-form-urlencoded")) {
466 st->log(ShibTarget::LogLevelInfo, "SAML 1.x Browser/POST handler ignoring submission with unknown content-type.");
467 return pair<bool,void*>(false,NULL);
470 const char* samlResponse = st->getRequestParameter("SAMLResponse");
472 st->log(ShibTarget::LogLevelInfo, "SAML 1.x Browser/POST handler ignoring request with no SAMLResponse parameter.");
473 return pair<bool,void*>(false,NULL);
476 in=DDF(m_address.c_str()).structure();
477 in.addmember("SAMLResponse").string(samlResponse);
479 else if (!XMLString::compareString(binding.second,SAMLBrowserProfile::BROWSER_ARTIFACT)) {
480 #ifdef HAVE_STRCASECMP
481 if (strcasecmp(st->getRequestMethod(), "GET")) {
483 if (_stricmp(st->getRequestMethod(), "GET")) {
485 st->log(ShibTarget::LogLevelInfo, "SAML 1.x Browser/Artifact handler ignoring non-GET request");
486 return pair<bool,void*>(false,NULL);
489 const char* SAMLart=st->getRequestParameter("SAMLart");
491 st->log(ShibTarget::LogLevelInfo, "SAML 1.x Browser/Artifact handler ignoring request with no SAMLart parameter.");
492 return pair<bool,void*>(false,NULL);
495 in=DDF(m_address.c_str()).structure();
496 DDF artlist=in.addmember("SAMLart").list();
499 artlist.add(DDF(NULL).string(SAMLart));
500 SAMLart=st->getRequestParameter("SAMLart",artlist.integer());
504 // Compute the endpoint location.
505 string hURL=st->getHandlerURL(st->getRequestURL());
506 pair<bool,const char*> loc=getProperties()->getString("Location");
507 string recipient=loc.first ? hURL + loc.second : hURL;
508 in.addmember("recipient").string(recipient.c_str());
510 // Add remaining parameters.
511 in.addmember("application_id").string(st->getApplication()->getId());
512 in.addmember("client_address").string(st->getRemoteAddr());
514 out=st->getConfig()->getListener()->send(in);
515 if (!out["key"].isstring())
516 throw FatalProfileException("Remote processing of SAML 1.x Browser profile did not return a usable session key.");
517 string key=out["key"].string();
519 st->log(ShibTarget::LogLevelDebug, string("profile processing succeeded, new session created (") + key + ")");
521 const char* target=st->getRequestParameter("TARGET");
522 if (target && !strcmp(target,"default")) {
523 pair<bool,const char*> homeURL=st->getApplication()->getString("homeURL");
524 target=homeURL.first ? homeURL.second : "/";
526 else if (!target || !strcmp(target,"cookie")) {
527 // Pull the target value from the "relay state" cookie.
528 pair<string,const char*> relay_cookie = st->getCookieNameProps("_shibstate_");
529 const char* relay_state = st->getCookie(relay_cookie.first);
530 if (!relay_state || !*relay_state) {
531 // No apparent relay state value to use, so fall back on the default.
532 pair<bool,const char*> homeURL=st->getApplication()->getString("homeURL");
533 target=homeURL.first ? homeURL.second : "/";
536 char* rscopy=strdup(relay_state);
537 ShibTarget::url_decode(rscopy);
542 st->setCookie(relay_cookie.first,relay_cookie.second);
545 // We've got a good session, set the session cookie.
546 pair<string,const char*> shib_cookie=st->getCookieNameProps("_shibsession_");
547 st->setCookie(shib_cookie.first, key + shib_cookie.second);
549 const char* providerId=out["provider_id"].string();
551 const IPropertySet* sessionProps=st->getApplication()->getPropertySet("Sessions");
552 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
553 if (!idpHistory.first || idpHistory.second) {
554 // Set an IdP history cookie locally (essentially just a CDC).
555 CommonDomainCookie cdc(st->getCookie(CommonDomainCookie::CDCName));
557 // Either leave in memory or set an expiration.
558 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
559 if (!days.first || days.second==0)
560 st->setCookie(CommonDomainCookie::CDCName,string(cdc.set(providerId)) + shib_cookie.second);
562 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
565 struct tm* ptime=gmtime_r(&now,&res);
567 struct tm* ptime=gmtime(&now);
570 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
572 CommonDomainCookie::CDCName,
573 string(cdc.set(providerId)) + shib_cookie.second + "; expires=" + timebuf
579 // Now redirect to the target.
580 return make_pair(true, st->sendRedirect(target));
583 pair<bool,void*> ShibLogout::run(ShibTarget* st, bool isHandler) const
585 // Recover the session key.
586 pair<string,const char*> shib_cookie = st->getCookieNameProps("_shibsession_");
587 const char* session_id = st->getCookie(shib_cookie.first);
589 // Logout is best effort.
590 if (session_id && *session_id) {
592 st->getConfig()->getSessionCache()->remove(session_id,st->getApplication(),st->getRemoteAddr());
594 catch (SAMLException& e) {
595 st->log(ShibTarget::LogLevelError, string("logout processing failed with exception: ") + e.what());
599 st->log(ShibTarget::LogLevelError, "logout processing failed with unknown exception");
602 // We send the cookie property alone, which acts as an empty value.
603 st->setCookie(shib_cookie.first,shib_cookie.second);
606 const char* ret=st->getRequestParameter("return");
608 ret=getProperties()->getString("ResponseLocation").second;
610 ret=st->getApplication()->getString("homeURL").second;
613 return make_pair(true, st->sendRedirect(ret));