2 * The Shibboleth License, Version 1.
4 * University Corporation for Advanced Internet Development, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
11 * Redistributions of source code must retain the above copyright notice, this
12 * list of conditions and the following disclaimer.
14 * Redistributions in binary form must reproduce the above copyright notice,
15 * this list of conditions and the following disclaimer in the documentation
16 * and/or other materials provided with the distribution, if any, must include
17 * the following acknowledgment: "This product includes software developed by
18 * the University Corporation for Advanced Internet Development
19 * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
20 * may appear in the software itself, if and wherever such third-party
21 * acknowledgments normally appear.
23 * Neither the name of Shibboleth nor the names of its contributors, nor
24 * Internet2, nor the University Corporation for Advanced Internet Development,
25 * Inc., nor UCAID may be used to endorse or promote products derived from this
26 * software without specific prior written permission. For written permission,
27 * please contact shibboleth@shibboleth.org
29 * Products derived from this software may not be called Shibboleth, Internet2,
30 * UCAID, or the University Corporation for Advanced Internet Development, nor
31 * may Shibboleth appear in their name, without prior written permission of the
32 * University Corporation for Advanced Internet Development.
35 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36 * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
38 * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
39 * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
40 * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
41 * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
42 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
43 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
50 /* nsapi_shib.cpp - Shibboleth NSAPI filter
56 #include "config_win32.h"
59 #include <saml/saml.h>
60 #include <shib/shib.h>
61 #include <shib/shib-threads.h>
62 #include <shib-target/shib-target.h>
86 using namespace shibboleth;
87 using namespace shibtarget;
89 // macros to output text to client
90 #define NET_WRITE(str) \
91 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
94 ShibTargetConfig* g_Config=NULL;
96 string g_ServerScheme;
99 PlugManager::Factory SunRequestMapFactory;
101 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
104 g_Config->shutdown();
108 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, Session* sn, Request* rq)
110 // Save off a default hostname for this virtual server.
111 char* name=pblock_findval("server-name",pb);
115 name=server_hostname;
119 name=util_hostname();
125 pblock_nvinsert("error","unable to determine web server hostname",pb);
130 name=pblock_findval("server-scheme",pb);
134 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
139 const char* schemadir=pblock_findval("shib-schemas",pb);
141 schemadir=getenv("SHIBSCHEMAS");
143 schemadir=SHIB_SCHEMAS;
144 const char* config=pblock_findval("shib-config",pb);
146 config=getenv("SHIBCONFIG");
149 g_Config=&ShibTargetConfig::getConfig();
150 g_Config->setFeatures(
151 ShibTargetConfig::Listener |
152 ShibTargetConfig::Metadata |
153 ShibTargetConfig::AAP |
154 ShibTargetConfig::RequestMapper |
155 ShibTargetConfig::LocalExtensions |
156 ShibTargetConfig::Logging
158 if (!g_Config->init(schemadir)) {
160 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
164 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&SunRequestMapFactory);
165 // We hijack the legacy type so that 1.2 config files will load this plugin
166 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&SunRequestMapFactory);
168 if (!g_Config->load(config)) {
170 pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
174 daemon_atrestart(nsapi_shib_exit,NULL);
179 pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
186 /********************************************************************************/
187 // NSAPI Shib Target Subclass
189 class ShibTargetNSAPI : public ShibTarget
192 ShibTargetNSAPI(pblock* pb, Session* sn, Request* rq) {
193 // Get everything but hostname...
194 const char* uri=pblock_findval("uri", rq->reqpb);
195 const char* qstr=pblock_findval("query", rq->reqpb);
196 int port=server_portnum;
197 const char* scheme=security_active ? "https" : "http";
198 const char* host=NULL;
204 url=url + '?' + qstr;
206 #ifdef vs_is_default_vs
207 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
208 if (!vs_is_default_vs)
209 // The beauty here is, a non-default vhost can *only* be accessed if the client
210 // specified the exact name in the Host header. So we can trust the Host header.
211 host=pblock_findval("host", rq->headers);
214 // In other cases, we're going to rely on the initialization process...
215 host=g_ServerName.c_str();
217 char* content_type = "";
218 request_header("content-type", &content_type, sn, rq);
220 const char *remote_ip = pblock_findval("ip", sn->client);
221 const char *method = pblock_findval("method", rq->reqpb);
223 init(scheme, host, port, url.c_str(), content_type, remote_ip, method);
229 ~ShibTargetNSAPI() {}
231 virtual void log(ShibLogLevel level, const string &msg) {
232 ShibTarget::log(level,msg);
233 if (level==LogLevelError)
234 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
236 virtual string getCookies(void) const {
237 char *cookies = NULL;
238 if (request_header("cookie", &cookies, m_sn, m_rq) == REQ_ABORTED)
239 throw("error accessing cookie header");
240 return string(cookies ? cookies : "");
242 virtual void setCookie(const string &name, const string &value) {
243 string cookie = name + '=' + value;
244 pblock_nvinsert("Set-Cookie", cookie.c_str(), m_rq->srvhdrs);
246 virtual string getArgs(void) {
247 const char *q = pblock_findval("query", m_rq->reqpb);
248 return string(q ? q : "");
250 virtual string getPostData(void) {
251 char* content_length=NULL;
252 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
253 atoi(content_length) > 1024*1024) // 1MB?
254 throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
257 int cl=atoi(content_length);
259 while (cl && ch != IO_EOF) {
260 ch=netbuf_getc(m_sn->inbuf);
269 throw FatalProfileException("Error reading profile submission from browser.");
273 virtual void clearHeader(const string &name) {
274 param_free(pblock_remove(name.c_str(), m_rq->headers));
276 virtual void setHeader(const string &name, const string &value) {
277 pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
279 virtual string getHeader(const string &name) {
281 if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
283 return string(hdr ? hdr : "");
285 virtual void setRemoteUser(const string &user) {
286 pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
287 pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
289 virtual string getRemoteUser(void) {
290 return getHeader("remote-user");
292 // Override this function because we want to add the NSAPI Directory override
294 virtual pair<bool,bool> getRequireSession(IRequestMapper::Settings &settings) {
295 pair<bool,bool> requireSession=settings.first->getBool("requireSession");
296 if (!requireSession.first || !requireSession.second) {
297 const char* param=pblock_findval("require-session",pb);
298 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
299 requireSession.second=true;
301 return requireSession;
305 virtual void* sendPage(
308 const string& content_type="text/html",
309 const saml::Iterator<header_t>& headers=EMPTY(header_t)
311 pblock_nvinsert("Content-Type", content_type.c_str(), m_rq->srvhdrs);
312 pblock_nninsert("Content-Length", msg.length(), m_rq->srvhdrs);
313 pblock_nvinsert("Connection","close",m_rq->srvhdrs);
314 while (headers.hasNext()) {
315 const header_t& h=headers.next();
316 pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
318 protocol_status(m_sn, m_rq, code, NULL);
319 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
320 return (void*)REQ_EXIT;
322 virtual void* sendRedirect(const string& url) {
323 pblock_nvinsert("Content-Type", "text/html", m_rq->srvhdrs);
324 pblock_nninsert("Content-Length", 40, m_rq->srvhdrs);
325 pblock_nvinsert("Expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
326 pblock_nvinsert("Cache-Control", "private,no-store,no-cache", m_rq->srvhdrs);
327 pblock_nvinsert("Location", url.c_str(), m_rq->srvhdrs);
328 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, "302 Please wait");
329 protocol_start_response(m_sn, m_rq);
330 char* msg="<HTML><BODY>Redirecting...</BODY></HTML>";
331 net_write(m_sn->csd,msg,strlen(msg));
332 return (void*)REQ_EXIT;
334 virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
335 virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
342 /********************************************************************************/
344 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
346 log_error(LOG_FAILURE,func,sn,rq,msg);
347 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
352 #define FUNC "shibboleth"
353 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
355 ostringstream threadid;
356 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
357 saml::NDC ndc(threadid.str().c_str());
362 ShibTargetNSAPI stn(pb, sn, rq);
364 // Check user authentication
365 pair<bool,void*> res = stn.doCheckAuthN();
366 if (res.first) return (int)res.second;
368 // user authN was okay -- export the assertions now
370 const char* param=pblock_findval("export-assertion", pb);
371 bool doExportAssn = false;
372 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
375 res = stn.doExportAssertions();
376 if (res.first) return (int)res.second;
378 // Check the Authorization
379 res = stn.doCheckAuthZ();
380 if (res.first) return (int)res.second;
388 return WriteClientError(sn, rq, FUNC, "threw an uncaught exception.");
395 #define FUNC "shib_handler"
396 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
398 ostringstream threadid;
399 threadid << "[" << getpid() << "] shib_handler" << '\0';
400 saml::NDC ndc(threadid.str().c_str());
405 ShibTargetNSAPI stn(pb, sn, rq);
407 pair<bool,void*> res = stn.doHandler();
408 if (res.first) return (int)res.second;
410 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
415 return WriteClientError(sn, rq, FUNC, "Filter threw an unknown exception.");
421 class SunRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
424 SunRequestMapper(const DOMElement* e);
425 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
426 void lock() { m_mapper->lock(); }
427 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
428 Settings getSettings(ShibTarget* st) const;
430 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
431 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
432 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
433 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
434 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
435 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
436 const DOMElement* getElement() const;
439 IRequestMapper* m_mapper;
441 ThreadKey* m_propsKey;
444 IPlugIn* SunRequestMapFactory(const DOMElement* e)
446 return new SunRequestMapper(e);
449 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
451 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
452 m_mapper=dynamic_cast<IRequestMapper*>(p);
455 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
457 m_stKey=ThreadKey::create(NULL);
458 m_propsKey=ThreadKey::create(NULL);
461 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
463 Settings s=m_mapper->getSettings(st);
464 m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
465 m_propsKey->setData((void*)s.first);
466 return pair<const IPropertySet*,IAccessControl*>(this,s.second);
469 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
471 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
472 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
473 if (stn && !ns && name) {
474 // Override boolean properties.
475 const char* param=pblock_findval(name,stn->m_pb);
476 if (param && (!strcmp(param,"1") || !util_strcasecmp(param,"true")))
477 return make_pair(true,true);
479 return s ? s->getBool(name,ns) : make_pair(false,false);
482 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
484 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
485 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
486 if (stn && !ns && name) {
487 // Override string properties.
488 if (!strcmp(name,"authType"))
489 return pair<bool,const char*>(true,"shibboleth");
491 const char* param=pblock_findval(name,stn->m_pb);
493 return make_pair(true,param);
496 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
499 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
501 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
502 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
505 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
507 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
508 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
511 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
513 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
514 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
517 const IPropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
519 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
520 return s ? s->getPropertySet(name,ns) : NULL;
523 const DOMElement* SunRequestMapper::getElement() const
525 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
526 return s ? s->getElement() : NULL;
532 IRequestMapper::Settings map_request(pblock* pb, Session* sn, Request* rq, IRequestMapper* mapper, string& target)
534 // Get everything but hostname...
535 const char* uri=pblock_findval("uri",rq->reqpb);
536 const char* qstr=pblock_findval("query",rq->reqpb);
537 int port=server_portnum;
538 const char* scheme=security_active ? "https" : "http";
539 const char* host=NULL;
545 url=url + '?' + qstr;
547 #ifdef vs_is_default_vs
548 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
549 if (!vs_is_default_vs)
550 // The beauty here is, a non-default vhost can *only* be accessed if the client
551 // specified the exact name in the Host header. So we can trust the Host header.
552 host=pblock_findval("host", rq->headers);
555 // In other cases, we're going to rely on the initialization process...
556 host=g_ServerName.c_str();
558 target=(g_ServerScheme.empty() ? string(scheme) : g_ServerScheme) + "://" + host;
560 // If port is non-default, append it.
561 if ((!security_active && port!=80) || (security_active && port!=443)) {
563 util_snprintf(portbuf,9,"%d",port);
564 target = target + ':' + portbuf;
569 return mapper->getSettingsFromParsedURL(scheme,host,port,url.c_str());
572 int WriteClientError(Session* sn, Request* rq, const IApplication* app, const char* page, ShibMLP& mlp)
574 const IPropertySet* props=app->getPropertySet("Errors");
576 pair<bool,const char*> p=props->getString(page);
578 ifstream infile(p.second);
579 if (!infile.fail()) {
580 const char* res = mlp.run(infile,props);
582 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
583 pblock_nninsert("Content-Length",strlen(res),rq->srvhdrs);
584 pblock_nvinsert("Connection","close",rq->srvhdrs);
585 protocol_status(sn,rq,PROTOCOL_OK,NULL);
586 NET_WRITE(const_cast<char*>(res));
593 log_error(LOG_FAILURE,"WriteClientError",sn,rq,"Unable to open error template, check settings.");
594 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,"Unable to open error template, check settings.");
598 int WriteRedirectPage(Session* sn, Request* rq, const IApplication* app, const char* file, ShibMLP& mlp)
600 ifstream infile(file);
601 if (!infile.fail()) {
602 const char* res = mlp.run(infile,app->getPropertySet("Errors"));
604 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
605 pblock_nninsert("Content-Length",strlen(res),rq->srvhdrs);
606 protocol_status(sn,rq,PROTOCOL_OK,NULL);
607 NET_WRITE(const_cast<char*>(res));
611 log_error(LOG_FAILURE,"WriteRedirectPage",sn,rq,"Unable to open redirect template, check settings.");
612 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,"Unable to open redirect template, check settings.");
617 #define FUNC "shibboleth"
618 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
622 ostringstream threadid;
623 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
624 saml::NDC ndc(threadid.str().c_str());
626 // We lock the configuration system for the duration.
627 IConfig* conf=g_Config->getINI();
630 // Map request to application and content settings.
632 IRequestMapper* mapper=conf->getRequestMapper();
633 Locker locker2(mapper);
634 IRequestMapper::Settings settings=map_request(pb,sn,rq,mapper,targeturl);
635 pair<bool,const char*> application_id=settings.first->getString("applicationId");
636 const IApplication* application=conf->getApplication(application_id.second);
638 return WriteClientError(sn,rq,FUNC,"Unable to map request to application settings, check configuration.");
640 // Declare SHIRE object for this request.
641 SHIRE shire(application);
643 const char* shireURL=shire.getShireURL(targeturl.c_str());
645 return WriteClientError(sn,rq,FUNC,"Unable to map request to proper shireURL setting, check configuration.");
647 // If the user is accessing the SHIRE acceptance point, pass it on.
648 if (targeturl.find(shireURL)!=string::npos)
651 // Now check the policy for this request.
652 pair<bool,bool> requireSession=settings.first->getBool("requireSession");
653 if (!requireSession.first || !requireSession.second) {
654 const char* param=pblock_findval("require-session",pb);
655 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
656 requireSession.second=true;
658 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();
659 pair<bool,bool> httpRedirects=application->getPropertySet("Sessions")->getBool("httpRedirects");
660 pair<bool,const char*> redirectPage=application->getPropertySet("Sessions")->getString("redirectPage");
661 if (httpRedirects.first && !httpRedirects.second && !redirectPage.first)
662 return WriteClientError(sn,rq,FUNC,"HTML-based redirection requires a redirectPage property.");
664 // Check for session cookie.
665 const char* session_id=NULL;
667 if (request_header("cookie",(char**)&session_id,sn,rq)==REQ_ABORTED)
668 return WriteClientError(sn,rq,FUNC,"error accessing cookie header");
670 Category::getInstance("nsapi_shib."FUNC).debug("cookie header is {%s}",session_id ? session_id : "NULL");
671 if (session_id && (session_id=strstr(session_id,shib_cookie.first))) {
672 session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
673 char* cookieend=strchr(session_id,';');
675 // Chop out just the value portion.
676 cookie.assign(session_id,cookieend-session_id-1);
677 session_id=cookie.c_str();
681 if (!session_id || !*session_id) {
682 // If no session required, bail now.
683 if (!requireSession.second)
686 // No acceptable cookie, and we require a session. Generate an AuthnRequest.
687 const char* areq = shire.getAuthnRequest(targeturl.c_str());
688 if (!httpRedirects.first || httpRedirects.second) {
689 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
690 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
691 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
692 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
693 pblock_nvinsert("Location",areq,rq->srvhdrs);
694 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
695 protocol_start_response(sn,rq);
696 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
700 ShibMLP markupProcessor;
701 markupProcessor.insert("requestURL",areq);
702 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
706 // Make sure this session is still valid.
707 RPCError* status = NULL;
708 ShibMLP markupProcessor;
709 markupProcessor.insert("requestURL", targeturl);
712 status = shire.sessionIsValid(session_id, pblock_findval("ip",sn->client));
714 catch (ShibTargetException &e) {
715 markupProcessor.insert("errorType", "Session Processing Error");
716 markupProcessor.insert("errorText", e.what());
717 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
718 return WriteClientError(sn, rq, application, "shire", markupProcessor);
722 markupProcessor.insert("errorType", "Session Processing Error");
723 markupProcessor.insert("errorText", "Unexpected Exception");
724 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
725 return WriteClientError(sn, rq, application, "shire", markupProcessor);
730 if (status->isError()) {
731 if (!requireSession.second)
733 else if (status->isRetryable()) {
734 // Oops, session is invalid. Generate AuthnRequest.
736 const char* areq = shire.getAuthnRequest(targeturl.c_str());
737 if (!httpRedirects.first || httpRedirects.second) {
738 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
739 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
740 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
741 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
742 pblock_nvinsert("Location",areq,rq->srvhdrs);
743 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
744 protocol_start_response(sn,rq);
745 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
749 markupProcessor.insert("requestURL",areq);
750 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
754 // return the error page to the user
755 markupProcessor.insert(*status);
757 return WriteClientError(sn, rq, application, "shire", markupProcessor);
764 vector<SAMLAssertion*> assertions;
765 SAMLAuthenticationStatement* sso_statement=NULL;
768 status = rm.getAssertions(session_id, pblock_findval("ip",sn->client), assertions, &sso_statement);
770 catch (ShibTargetException &e) {
771 markupProcessor.insert("errorType", "Attribute Processing Error");
772 markupProcessor.insert("errorText", e.what());
773 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
774 return WriteClientError(sn, rq, application, "rm", markupProcessor);
778 markupProcessor.insert("errorType", "Attribute Processing Error");
779 markupProcessor.insert("errorText", "Unexpected Exception");
780 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
781 return WriteClientError(sn, rq, application, "rm", markupProcessor);
785 if (status->isError()) {
786 markupProcessor.insert(*status);
788 return WriteClientError(sn, rq, application, "rm", markupProcessor);
792 // Do we have an access control plugin?
793 if (settings.second) {
794 Locker acllock(settings.second);
795 if (!settings.second->authorized(*sso_statement,assertions)) {
796 for (int k = 0; k < assertions.size(); k++)
797 delete assertions[k];
798 delete sso_statement;
799 return WriteClientError(sn, rq, application, "access", markupProcessor);
803 // Get the AAP providers, which contain the attribute policy info.
804 Iterator<IAAP*> provs=application->getAAPProviders();
806 // Clear out the list of mapped attributes
807 while (provs.hasNext()) {
808 IAAP* aap=provs.next();
811 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
812 while (rules.hasNext()) {
813 const char* header=rules.next()->getHeader();
815 param_free(pblock_remove(header,rq->headers));
820 for (int k = 0; k < assertions.size(); k++)
821 delete assertions[k];
822 delete sso_statement;
823 markupProcessor.insert("errorType", "Attribute Processing Error");
824 markupProcessor.insert("errorText", "Unexpected Exception");
825 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
826 return WriteClientError(sn, rq, application, "rm", markupProcessor);
832 // Maybe export the first assertion.
833 param_free(pblock_remove("remote-user",rq->headers));
834 param_free(pblock_remove("auth-user",rq->vars));
835 param_free(pblock_remove("Shib-Attributes",rq->headers));
836 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
837 if (!exp.first || !exp.second) {
838 const char* param=pblock_findval("export-assertion",pb);
839 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
842 if (exp.second && assertions.size()) {
844 RM::serialize(*(assertions[0]), assertion);
845 string::size_type lfeed;
846 while ((lfeed=assertion.find('\n'))!=string::npos)
847 assertion.erase(lfeed,1);
848 pblock_nvinsert("Shib-Attributes",assertion.c_str(),rq->headers);
851 pblock_nvinsert("auth-type","shibboleth",rq->vars);
852 param_free(pblock_remove("Shib-Origin-Site",rq->headers));
853 param_free(pblock_remove("Shib-Authentication-Method",rq->headers));
854 param_free(pblock_remove("Shib-NameIdentifier-Format",rq->headers));
856 // Export the SAML AuthnMethod and the origin site name.
857 auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
858 auto_ptr_char am(sso_statement->getAuthMethod());
859 pblock_nvinsert("Shib-Origin-Site",os.get(),rq->headers);
860 pblock_nvinsert("Shib-Authentication-Method",am.get(),rq->headers);
863 AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
864 if (!wrapper.fail() && wrapper->getHeader()) {
865 auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
866 auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
867 pblock_nvinsert("Shib-NameIdentifier-Format",form.get(),pb);
868 if (!strcmp(wrapper->getHeader(),"REMOTE_USER")) {
869 pblock_nvinsert("remote-user",nameid.get(),rq->headers);
870 pblock_nvinsert("auth-user",nameid.get(),rq->vars);
873 pblock_nvinsert(wrapper->getHeader(),nameid.get(),rq->headers);
877 param_free(pblock_remove("Shib-Application-ID",rq->headers));
878 pblock_nvinsert("Shib-Application-ID",application_id.second,rq->headers);
880 // Export the attributes.
881 Iterator<SAMLAssertion*> a_iter(assertions);
882 while (a_iter.hasNext()) {
883 SAMLAssertion* assert=a_iter.next();
884 Iterator<SAMLStatement*> statements=assert->getStatements();
885 while (statements.hasNext()) {
886 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
889 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
890 while (attrs.hasNext()) {
891 SAMLAttribute* attr=attrs.next();
893 // Are we supposed to export it?
894 AAP wrapper(provs,attr->getName(),attr->getNamespace());
895 if (wrapper.fail() || !wrapper->getHeader())
898 Iterator<string> vals=attr->getSingleByteValues();
899 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext()) {
900 char* principal=const_cast<char*>(vals.next().c_str());
901 pblock_nvinsert("remote-user",principal,rq->headers);
902 pblock_nvinsert("auth-user",principal,rq->vars);
907 const char* h=pblock_findval(wrapper->getHeader(),rq->headers);
910 param_free(pblock_remove(wrapper->getHeader(),rq->headers));
913 for (; vals.hasNext(); it++) {
914 string value = vals.next();
915 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
917 pos = value.find_first_of(";", pos)) {
918 value.insert(pos, "\\");
924 header=header + ';' + value;
926 pblock_nvinsert(wrapper->getHeader(),header.c_str(),rq->headers);
933 for (int k = 0; k < assertions.size(); k++)
934 delete assertions[k];
935 delete sso_statement;
940 return WriteClientError(sn, rq, FUNC,"Out of Memory");
944 return WriteClientError(sn, rq, FUNC,"Server caught an unknown exception.");
948 return WriteClientError(sn, rq, FUNC,"Server reached unreachable code, save my walrus!");
952 #define FUNC "shib_handler"
953 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
956 const IApplication* application=NULL;
959 ostringstream threadid;
960 threadid << "[" << getpid() << "] shib_handler" << '\0';
961 saml::NDC ndc(threadid.str().c_str());
963 // We lock the configuration system for the duration.
964 IConfig* conf=g_Config->getINI();
967 // Map request to application and content settings.
968 IRequestMapper* mapper=conf->getRequestMapper();
969 Locker locker2(mapper);
970 IRequestMapper::Settings settings=map_request(pb,sn,rq,mapper,targeturl);
971 pair<bool,const char*> application_id=settings.first->getString("applicationId");
972 application=conf->getApplication(application_id.second);
973 const IPropertySet* sessionProps=application ? application->getPropertySet("Sessions") : NULL;
974 if (!application || !sessionProps)
975 return WriteClientError(sn,rq,FUNC,"Unable to map request to application settings, check configuration.");
977 SHIRE shire(application);
979 const char* shireURL=shire.getShireURL(targeturl.c_str());
981 return WriteClientError(sn,rq,FUNC,"Unable to map request to proper shireURL setting, check configuration.");
983 // Make sure we only process the SHIRE requests.
984 if (!strstr(targeturl.c_str(),shireURL))
985 return WriteClientError(sn,rq,FUNC,"NSAPI service function can only be invoked to process incoming sessions."
986 "Make sure the mapped file extension or URL doesn't match actual content.");
988 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();
990 // Make sure this is SSL, if it should be
991 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
992 if (!shireSSL.first || shireSSL.second) {
993 if (!security_active)
994 throw ShibTargetException(SHIBRPC_OK,"blocked non-SSL access to Shibboleth session processor");
997 pair<bool,bool> httpRedirects=sessionProps->getBool("httpRedirects");
998 pair<bool,const char*> redirectPage=sessionProps->getString("redirectPage");
999 if (httpRedirects.first && !httpRedirects.second && !redirectPage.first)
1000 return WriteClientError(sn,rq,FUNC,"HTML-based redirection requires a redirectPage property.");
1002 // If this is a GET, we manufacture an AuthnRequest.
1003 if (!strcasecmp(pblock_findval("method",rq->reqpb),"GET")) {
1004 const char* areq=pblock_findval("query",rq->reqpb) ? shire.getLazyAuthnRequest(pblock_findval("query",rq->reqpb)) : NULL;
1006 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
1007 if (!httpRedirects.first || httpRedirects.second) {
1008 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
1009 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
1010 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
1011 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
1012 pblock_nvinsert("Location",areq,rq->srvhdrs);
1013 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1014 protocol_start_response(sn,rq);
1015 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1019 ShibMLP markupProcessor;
1020 markupProcessor.insert("requestURL",areq);
1021 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1024 else if (strcasecmp(pblock_findval("method",rq->reqpb),"POST"))
1025 throw ShibTargetException(SHIBRPC_OK,"blocked non-POST to Shibboleth session processor");
1027 // Make sure this POST is an appropriate content type
1028 char* content_type=NULL;
1029 if (request_header("content-type",&content_type,sn,rq)!=REQ_PROCEED ||
1030 !content_type || strcasecmp(content_type,"application/x-www-form-urlencoded"))
1031 throw ShibTargetException(SHIBRPC_OK,"blocked bad content-type to Shibboleth session processor");
1034 pair<const char*,const char*> elements=pair<const char*,const char*>(NULL,NULL);
1035 char* content_length=NULL;
1036 if (request_header("content-length",&content_length,sn,rq)!=REQ_PROCEED ||
1037 atoi(content_length) > 1024*1024) // 1MB?
1038 throw ShibTargetException(SHIBRPC_OK,"blocked too-large a post to Shibboleth session processor");
1041 int cl=atoi(content_length);
1043 while (cl && ch!=IO_EOF) {
1044 ch=netbuf_getc(sn->inbuf);
1053 throw ShibTargetException(SHIBRPC_OK,"error reading POST data from browser");
1054 elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
1057 // Make sure the SAML Response parameter exists
1058 if (!elements.first || !*elements.first)
1059 throw ShibTargetException(SHIBRPC_OK, "Shibboleth POST failed to find SAMLResponse form element");
1061 // Make sure the target parameter exists
1062 if (!elements.second || !*elements.second)
1063 throw ShibTargetException(SHIBRPC_OK, "Shibboleth POST failed to find TARGET form element");
1065 // Process the post.
1067 RPCError* status=NULL;
1068 ShibMLP markupProcessor;
1069 markupProcessor.insert("requestURL", targeturl.c_str());
1071 status = shire.sessionCreate(elements.first,pblock_findval("ip",sn->client),cookie);
1073 catch (ShibTargetException &e) {
1074 markupProcessor.insert("errorType", "Session Creation Service Error");
1075 markupProcessor.insert("errorText", e.what());
1076 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1077 return WriteClientError(sn, rq, application, "shire", markupProcessor);
1081 markupProcessor.insert("errorType", "Session Creation Service Error");
1082 markupProcessor.insert("errorText", "Unexpected Exception");
1083 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1084 return WriteClientError(sn, rq, application, "shire", markupProcessor);
1088 if (status->isError()) {
1089 if (status->isRetryable()) {
1091 const char* loc=shire.getAuthnRequest(elements.second);
1092 if (!httpRedirects.first || httpRedirects.second) {
1093 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
1094 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
1095 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
1096 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
1097 pblock_nvinsert("Location",loc,rq->srvhdrs);
1098 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1099 protocol_start_response(sn,rq);
1100 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1104 markupProcessor.insert("requestURL",loc);
1105 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1109 // Return this error to the user.
1110 markupProcessor.insert(*status);
1112 return WriteClientError(sn,rq,application,"shire",markupProcessor);
1116 // We've got a good session, set the cookie and redirect to target.
1117 cookie = string(shib_cookie.first) + '=' + cookie + shib_cookie.second;
1118 pblock_nvinsert("Set-Cookie",cookie.c_str(),rq->srvhdrs);
1119 if (!httpRedirects.first || httpRedirects.second) {
1120 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
1121 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
1122 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
1123 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
1124 pblock_nvinsert("Location",elements.second,rq->srvhdrs);
1125 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1126 protocol_start_response(sn,rq);
1127 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1131 markupProcessor.insert("requestURL",elements.second);
1132 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1135 catch (ShibTargetException &e) {
1137 ShibMLP markupProcessor;
1138 markupProcessor.insert("requestURL", targeturl.c_str());
1139 markupProcessor.insert("errorType", "Session Creation Service Error");
1140 markupProcessor.insert("errorText", e.what());
1141 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1142 return WriteClientError(sn,rq,application,"shire",markupProcessor);
1148 ShibMLP markupProcessor;
1149 markupProcessor.insert("requestURL", targeturl.c_str());
1150 markupProcessor.insert("errorType", "Session Creation Service Error");
1151 markupProcessor.insert("errorText", "Unexpected Exception");
1152 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1153 return WriteClientError(sn,rq,application,"shire",markupProcessor);