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) {
197 // Get everything but hostname...
198 const char* uri=pblock_findval("uri", rq->reqpb);
199 const char* qstr=pblock_findval("query", rq->reqpb);
200 int port=server_portnum;
201 const char* scheme=security_active ? "https" : "http";
202 const char* host=NULL;
208 url=url + '?' + qstr;
210 #ifdef vs_is_default_vs
211 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
212 if (!vs_is_default_vs)
213 // The beauty here is, a non-default vhost can *only* be accessed if the client
214 // specified the exact name in the Host header. So we can trust the Host header.
215 host=pblock_findval("host", rq->headers);
218 // In other cases, we're going to rely on the initialization process...
219 host=g_ServerName.c_str();
221 char* content_type = "";
222 request_header("content-type", &content_type, sn, rq);
224 const char *remote_ip = pblock_findval("ip", sn->client);
225 const char *method = pblock_findval("method", rq->reqpb);
227 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");
293 virtual void* sendPage(
296 const string& content_type="text/html",
297 const saml::Iterator<header_t>& headers=EMPTY(header_t)
299 pblock_nvinsert("Content-Type", content_type.c_str(), m_rq->srvhdrs);
300 pblock_nninsert("Content-Length", msg.length(), m_rq->srvhdrs);
301 pblock_nvinsert("Connection","close",m_rq->srvhdrs);
302 while (headers.hasNext()) {
303 const header_t& h=headers.next();
304 pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
306 protocol_status(m_sn, m_rq, code, NULL);
307 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
308 return (void*)REQ_EXIT;
310 virtual void* sendRedirect(const string& url) {
311 pblock_nvinsert("Content-Type", "text/html", m_rq->srvhdrs);
312 pblock_nninsert("Content-Length", 40, m_rq->srvhdrs);
313 pblock_nvinsert("Expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
314 pblock_nvinsert("Cache-Control", "private,no-store,no-cache", m_rq->srvhdrs);
315 pblock_nvinsert("Location", url.c_str(), m_rq->srvhdrs);
316 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, "302 Please wait");
317 protocol_start_response(m_sn, m_rq);
318 char* msg="<HTML><BODY>Redirecting...</BODY></HTML>";
319 net_write(m_sn->csd,msg,strlen(msg));
320 return (void*)REQ_EXIT;
322 virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
323 virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
330 /********************************************************************************/
332 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
334 log_error(LOG_FAILURE,func,sn,rq,msg);
335 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
340 #define FUNC "shibboleth"
341 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
343 ostringstream threadid;
344 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
345 saml::NDC ndc(threadid.str().c_str());
350 ShibTargetNSAPI stn(pb, sn, rq);
352 // Check user authentication
353 pair<bool,void*> res = stn.doCheckAuthN();
354 if (res.first) return (int)res.second;
356 // user authN was okay -- export the assertions now
357 param_free(pblock_remove("auth-user",rq->vars));
358 // This seems to be required in order to eventually set
359 // the auth-user var.
360 pblock_nvinsert("auth-type","shibboleth",rq->vars);
361 res = stn.doExportAssertions();
362 if (res.first) return (int)res.second;
364 // Check the Authorization
365 res = stn.doCheckAuthZ();
366 if (res.first) return (int)res.second;
374 return WriteClientError(sn, rq, FUNC, "threw an uncaught exception.");
381 #define FUNC "shib_handler"
382 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
384 ostringstream threadid;
385 threadid << "[" << getpid() << "] shib_handler" << '\0';
386 saml::NDC ndc(threadid.str().c_str());
391 ShibTargetNSAPI stn(pb, sn, rq);
393 pair<bool,void*> res = stn.doHandler();
394 if (res.first) return (int)res.second;
396 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
401 return WriteClientError(sn, rq, FUNC, "Filter threw an unknown exception.");
407 class SunRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
410 SunRequestMapper(const DOMElement* e);
411 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
412 void lock() { m_mapper->lock(); }
413 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
414 Settings getSettings(ShibTarget* st) const;
416 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
417 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
418 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
419 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
420 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
421 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
422 const DOMElement* getElement() const;
425 IRequestMapper* m_mapper;
427 ThreadKey* m_propsKey;
430 IPlugIn* SunRequestMapFactory(const DOMElement* e)
432 return new SunRequestMapper(e);
435 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
437 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
438 m_mapper=dynamic_cast<IRequestMapper*>(p);
441 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
443 m_stKey=ThreadKey::create(NULL);
444 m_propsKey=ThreadKey::create(NULL);
447 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
449 Settings s=m_mapper->getSettings(st);
450 m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
451 m_propsKey->setData((void*)s.first);
452 return pair<const IPropertySet*,IAccessControl*>(this,s.second);
455 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
457 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
458 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
459 if (stn && !ns && name) {
460 // Override boolean properties.
461 const char* param=pblock_findval(name,stn->m_pb);
462 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
463 return make_pair(true,true);
465 return s ? s->getBool(name,ns) : make_pair(false,false);
468 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
470 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
471 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
472 if (stn && !ns && name) {
473 // Override string properties.
474 if (!strcmp(name,"authType"))
475 return pair<bool,const char*>(true,"shibboleth");
477 const char* param=pblock_findval(name,stn->m_pb);
479 return make_pair(true,param);
482 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
485 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
487 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
488 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
491 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
493 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
494 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
497 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
499 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
500 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
503 const IPropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
505 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
506 return s ? s->getPropertySet(name,ns) : NULL;
509 const DOMElement* SunRequestMapper::getElement() const
511 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
512 return s ? s->getElement() : NULL;
518 IRequestMapper::Settings map_request(pblock* pb, Session* sn, Request* rq, IRequestMapper* mapper, string& target)
520 // Get everything but hostname...
521 const char* uri=pblock_findval("uri",rq->reqpb);
522 const char* qstr=pblock_findval("query",rq->reqpb);
523 int port=server_portnum;
524 const char* scheme=security_active ? "https" : "http";
525 const char* host=NULL;
531 url=url + '?' + qstr;
533 #ifdef vs_is_default_vs
534 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
535 if (!vs_is_default_vs)
536 // The beauty here is, a non-default vhost can *only* be accessed if the client
537 // specified the exact name in the Host header. So we can trust the Host header.
538 host=pblock_findval("host", rq->headers);
541 // In other cases, we're going to rely on the initialization process...
542 host=g_ServerName.c_str();
544 target=(g_ServerScheme.empty() ? string(scheme) : g_ServerScheme) + "://" + host;
546 // If port is non-default, append it.
547 if ((!security_active && port!=80) || (security_active && port!=443)) {
549 util_snprintf(portbuf,9,"%d",port);
550 target = target + ':' + portbuf;
555 return mapper->getSettingsFromParsedURL(scheme,host,port,url.c_str());
558 int WriteClientError(Session* sn, Request* rq, const IApplication* app, const char* page, ShibMLP& mlp)
560 const IPropertySet* props=app->getPropertySet("Errors");
562 pair<bool,const char*> p=props->getString(page);
564 ifstream infile(p.second);
565 if (!infile.fail()) {
566 const char* res = mlp.run(infile,props);
568 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
569 pblock_nninsert("Content-Length",strlen(res),rq->srvhdrs);
570 pblock_nvinsert("Connection","close",rq->srvhdrs);
571 protocol_status(sn,rq,PROTOCOL_OK,NULL);
572 NET_WRITE(const_cast<char*>(res));
579 log_error(LOG_FAILURE,"WriteClientError",sn,rq,"Unable to open error template, check settings.");
580 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,"Unable to open error template, check settings.");
584 int WriteRedirectPage(Session* sn, Request* rq, const IApplication* app, const char* file, ShibMLP& mlp)
586 ifstream infile(file);
587 if (!infile.fail()) {
588 const char* res = mlp.run(infile,app->getPropertySet("Errors"));
590 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
591 pblock_nninsert("Content-Length",strlen(res),rq->srvhdrs);
592 protocol_status(sn,rq,PROTOCOL_OK,NULL);
593 NET_WRITE(const_cast<char*>(res));
597 log_error(LOG_FAILURE,"WriteRedirectPage",sn,rq,"Unable to open redirect template, check settings.");
598 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,"Unable to open redirect template, check settings.");
603 #define FUNC "shibboleth"
604 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
608 ostringstream threadid;
609 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
610 saml::NDC ndc(threadid.str().c_str());
612 // We lock the configuration system for the duration.
613 IConfig* conf=g_Config->getINI();
616 // Map request to application and content settings.
618 IRequestMapper* mapper=conf->getRequestMapper();
619 Locker locker2(mapper);
620 IRequestMapper::Settings settings=map_request(pb,sn,rq,mapper,targeturl);
621 pair<bool,const char*> application_id=settings.first->getString("applicationId");
622 const IApplication* application=conf->getApplication(application_id.second);
624 return WriteClientError(sn,rq,FUNC,"Unable to map request to application settings, check configuration.");
626 // Declare SHIRE object for this request.
627 SHIRE shire(application);
629 const char* shireURL=shire.getShireURL(targeturl.c_str());
631 return WriteClientError(sn,rq,FUNC,"Unable to map request to proper shireURL setting, check configuration.");
633 // If the user is accessing the SHIRE acceptance point, pass it on.
634 if (targeturl.find(shireURL)!=string::npos)
637 // Now check the policy for this request.
638 pair<bool,bool> requireSession=settings.first->getBool("requireSession");
639 if (!requireSession.first || !requireSession.second) {
640 const char* param=pblock_findval("require-session",pb);
641 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
642 requireSession.second=true;
644 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();
645 pair<bool,bool> httpRedirects=application->getPropertySet("Sessions")->getBool("httpRedirects");
646 pair<bool,const char*> redirectPage=application->getPropertySet("Sessions")->getString("redirectPage");
647 if (httpRedirects.first && !httpRedirects.second && !redirectPage.first)
648 return WriteClientError(sn,rq,FUNC,"HTML-based redirection requires a redirectPage property.");
650 // Check for session cookie.
651 const char* session_id=NULL;
653 if (request_header("cookie",(char**)&session_id,sn,rq)==REQ_ABORTED)
654 return WriteClientError(sn,rq,FUNC,"error accessing cookie header");
656 Category::getInstance("nsapi_shib."FUNC).debug("cookie header is {%s}",session_id ? session_id : "NULL");
657 if (session_id && (session_id=strstr(session_id,shib_cookie.first))) {
658 session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
659 char* cookieend=strchr(session_id,';');
661 // Chop out just the value portion.
662 cookie.assign(session_id,cookieend-session_id-1);
663 session_id=cookie.c_str();
667 if (!session_id || !*session_id) {
668 // If no session required, bail now.
669 if (!requireSession.second)
672 // No acceptable cookie, and we require a session. Generate an AuthnRequest.
673 const char* areq = shire.getAuthnRequest(targeturl.c_str());
674 if (!httpRedirects.first || httpRedirects.second) {
675 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
676 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
677 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
678 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
679 pblock_nvinsert("Location",areq,rq->srvhdrs);
680 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
681 protocol_start_response(sn,rq);
682 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
686 ShibMLP markupProcessor;
687 markupProcessor.insert("requestURL",areq);
688 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
692 // Make sure this session is still valid.
693 RPCError* status = NULL;
694 ShibMLP markupProcessor;
695 markupProcessor.insert("requestURL", targeturl);
698 status = shire.sessionIsValid(session_id, pblock_findval("ip",sn->client));
700 catch (ShibTargetException &e) {
701 markupProcessor.insert("errorType", "Session Processing Error");
702 markupProcessor.insert("errorText", e.what());
703 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
704 return WriteClientError(sn, rq, application, "shire", markupProcessor);
708 markupProcessor.insert("errorType", "Session Processing Error");
709 markupProcessor.insert("errorText", "Unexpected Exception");
710 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
711 return WriteClientError(sn, rq, application, "shire", markupProcessor);
716 if (status->isError()) {
717 if (!requireSession.second)
719 else if (status->isRetryable()) {
720 // Oops, session is invalid. Generate AuthnRequest.
722 const char* areq = shire.getAuthnRequest(targeturl.c_str());
723 if (!httpRedirects.first || httpRedirects.second) {
724 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
725 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
726 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
727 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
728 pblock_nvinsert("Location",areq,rq->srvhdrs);
729 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
730 protocol_start_response(sn,rq);
731 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
735 markupProcessor.insert("requestURL",areq);
736 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
740 // return the error page to the user
741 markupProcessor.insert(*status);
743 return WriteClientError(sn, rq, application, "shire", markupProcessor);
750 vector<SAMLAssertion*> assertions;
751 SAMLAuthenticationStatement* sso_statement=NULL;
754 status = rm.getAssertions(session_id, pblock_findval("ip",sn->client), assertions, &sso_statement);
756 catch (ShibTargetException &e) {
757 markupProcessor.insert("errorType", "Attribute Processing Error");
758 markupProcessor.insert("errorText", e.what());
759 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
760 return WriteClientError(sn, rq, application, "rm", markupProcessor);
764 markupProcessor.insert("errorType", "Attribute Processing Error");
765 markupProcessor.insert("errorText", "Unexpected Exception");
766 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
767 return WriteClientError(sn, rq, application, "rm", markupProcessor);
771 if (status->isError()) {
772 markupProcessor.insert(*status);
774 return WriteClientError(sn, rq, application, "rm", markupProcessor);
778 // Do we have an access control plugin?
779 if (settings.second) {
780 Locker acllock(settings.second);
781 if (!settings.second->authorized(*sso_statement,assertions)) {
782 for (int k = 0; k < assertions.size(); k++)
783 delete assertions[k];
784 delete sso_statement;
785 return WriteClientError(sn, rq, application, "access", markupProcessor);
789 // Get the AAP providers, which contain the attribute policy info.
790 Iterator<IAAP*> provs=application->getAAPProviders();
792 // Clear out the list of mapped attributes
793 while (provs.hasNext()) {
794 IAAP* aap=provs.next();
797 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
798 while (rules.hasNext()) {
799 const char* header=rules.next()->getHeader();
801 param_free(pblock_remove(header,rq->headers));
806 for (int k = 0; k < assertions.size(); k++)
807 delete assertions[k];
808 delete sso_statement;
809 markupProcessor.insert("errorType", "Attribute Processing Error");
810 markupProcessor.insert("errorText", "Unexpected Exception");
811 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
812 return WriteClientError(sn, rq, application, "rm", markupProcessor);
818 // Maybe export the first assertion.
819 param_free(pblock_remove("remote-user",rq->headers));
820 param_free(pblock_remove("auth-user",rq->vars));
821 param_free(pblock_remove("Shib-Attributes",rq->headers));
822 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
823 if (!exp.first || !exp.second) {
824 const char* param=pblock_findval("export-assertion",pb);
825 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
828 if (exp.second && assertions.size()) {
830 RM::serialize(*(assertions[0]), assertion);
831 string::size_type lfeed;
832 while ((lfeed=assertion.find('\n'))!=string::npos)
833 assertion.erase(lfeed,1);
834 pblock_nvinsert("Shib-Attributes",assertion.c_str(),rq->headers);
837 pblock_nvinsert("auth-type","shibboleth",rq->vars);
838 param_free(pblock_remove("Shib-Origin-Site",rq->headers));
839 param_free(pblock_remove("Shib-Authentication-Method",rq->headers));
840 param_free(pblock_remove("Shib-NameIdentifier-Format",rq->headers));
842 // Export the SAML AuthnMethod and the origin site name.
843 auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
844 auto_ptr_char am(sso_statement->getAuthMethod());
845 pblock_nvinsert("Shib-Origin-Site",os.get(),rq->headers);
846 pblock_nvinsert("Shib-Authentication-Method",am.get(),rq->headers);
849 AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
850 if (!wrapper.fail() && wrapper->getHeader()) {
851 auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
852 auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
853 pblock_nvinsert("Shib-NameIdentifier-Format",form.get(),pb);
854 if (!strcmp(wrapper->getHeader(),"REMOTE_USER")) {
855 pblock_nvinsert("remote-user",nameid.get(),rq->headers);
856 pblock_nvinsert("auth-user",nameid.get(),rq->vars);
859 pblock_nvinsert(wrapper->getHeader(),nameid.get(),rq->headers);
863 param_free(pblock_remove("Shib-Application-ID",rq->headers));
864 pblock_nvinsert("Shib-Application-ID",application_id.second,rq->headers);
866 // Export the attributes.
867 Iterator<SAMLAssertion*> a_iter(assertions);
868 while (a_iter.hasNext()) {
869 SAMLAssertion* assert=a_iter.next();
870 Iterator<SAMLStatement*> statements=assert->getStatements();
871 while (statements.hasNext()) {
872 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
875 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
876 while (attrs.hasNext()) {
877 SAMLAttribute* attr=attrs.next();
879 // Are we supposed to export it?
880 AAP wrapper(provs,attr->getName(),attr->getNamespace());
881 if (wrapper.fail() || !wrapper->getHeader())
884 Iterator<string> vals=attr->getSingleByteValues();
885 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext()) {
886 char* principal=const_cast<char*>(vals.next().c_str());
887 pblock_nvinsert("remote-user",principal,rq->headers);
888 pblock_nvinsert("auth-user",principal,rq->vars);
893 const char* h=pblock_findval(wrapper->getHeader(),rq->headers);
896 param_free(pblock_remove(wrapper->getHeader(),rq->headers));
899 for (; vals.hasNext(); it++) {
900 string value = vals.next();
901 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
903 pos = value.find_first_of(";", pos)) {
904 value.insert(pos, "\\");
910 header=header + ';' + value;
912 pblock_nvinsert(wrapper->getHeader(),header.c_str(),rq->headers);
919 for (int k = 0; k < assertions.size(); k++)
920 delete assertions[k];
921 delete sso_statement;
926 return WriteClientError(sn, rq, FUNC,"Out of Memory");
930 return WriteClientError(sn, rq, FUNC,"Server caught an unknown exception.");
934 return WriteClientError(sn, rq, FUNC,"Server reached unreachable code, save my walrus!");
938 #define FUNC "shib_handler"
939 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
942 const IApplication* application=NULL;
945 ostringstream threadid;
946 threadid << "[" << getpid() << "] shib_handler" << '\0';
947 saml::NDC ndc(threadid.str().c_str());
949 // We lock the configuration system for the duration.
950 IConfig* conf=g_Config->getINI();
953 // Map request to application and content settings.
954 IRequestMapper* mapper=conf->getRequestMapper();
955 Locker locker2(mapper);
956 IRequestMapper::Settings settings=map_request(pb,sn,rq,mapper,targeturl);
957 pair<bool,const char*> application_id=settings.first->getString("applicationId");
958 application=conf->getApplication(application_id.second);
959 const IPropertySet* sessionProps=application ? application->getPropertySet("Sessions") : NULL;
960 if (!application || !sessionProps)
961 return WriteClientError(sn,rq,FUNC,"Unable to map request to application settings, check configuration.");
963 SHIRE shire(application);
965 const char* shireURL=shire.getShireURL(targeturl.c_str());
967 return WriteClientError(sn,rq,FUNC,"Unable to map request to proper shireURL setting, check configuration.");
969 // Make sure we only process the SHIRE requests.
970 if (!strstr(targeturl.c_str(),shireURL))
971 return WriteClientError(sn,rq,FUNC,"NSAPI service function can only be invoked to process incoming sessions."
972 "Make sure the mapped file extension or URL doesn't match actual content.");
974 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();
976 // Make sure this is SSL, if it should be
977 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
978 if (!shireSSL.first || shireSSL.second) {
979 if (!security_active)
980 throw ShibTargetException(SHIBRPC_OK,"blocked non-SSL access to Shibboleth session processor");
983 pair<bool,bool> httpRedirects=sessionProps->getBool("httpRedirects");
984 pair<bool,const char*> redirectPage=sessionProps->getString("redirectPage");
985 if (httpRedirects.first && !httpRedirects.second && !redirectPage.first)
986 return WriteClientError(sn,rq,FUNC,"HTML-based redirection requires a redirectPage property.");
988 // If this is a GET, we manufacture an AuthnRequest.
989 if (!strcasecmp(pblock_findval("method",rq->reqpb),"GET")) {
990 const char* areq=pblock_findval("query",rq->reqpb) ? shire.getLazyAuthnRequest(pblock_findval("query",rq->reqpb)) : NULL;
992 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
993 if (!httpRedirects.first || httpRedirects.second) {
994 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
995 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
996 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
997 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
998 pblock_nvinsert("Location",areq,rq->srvhdrs);
999 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1000 protocol_start_response(sn,rq);
1001 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1005 ShibMLP markupProcessor;
1006 markupProcessor.insert("requestURL",areq);
1007 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1010 else if (strcasecmp(pblock_findval("method",rq->reqpb),"POST"))
1011 throw ShibTargetException(SHIBRPC_OK,"blocked non-POST to Shibboleth session processor");
1013 // Make sure this POST is an appropriate content type
1014 char* content_type=NULL;
1015 if (request_header("content-type",&content_type,sn,rq)!=REQ_PROCEED ||
1016 !content_type || strcasecmp(content_type,"application/x-www-form-urlencoded"))
1017 throw ShibTargetException(SHIBRPC_OK,"blocked bad content-type to Shibboleth session processor");
1020 pair<const char*,const char*> elements=pair<const char*,const char*>(NULL,NULL);
1021 char* content_length=NULL;
1022 if (request_header("content-length",&content_length,sn,rq)!=REQ_PROCEED ||
1023 atoi(content_length) > 1024*1024) // 1MB?
1024 throw ShibTargetException(SHIBRPC_OK,"blocked too-large a post to Shibboleth session processor");
1027 int cl=atoi(content_length);
1029 while (cl && ch!=IO_EOF) {
1030 ch=netbuf_getc(sn->inbuf);
1039 throw ShibTargetException(SHIBRPC_OK,"error reading POST data from browser");
1040 elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
1043 // Make sure the SAML Response parameter exists
1044 if (!elements.first || !*elements.first)
1045 throw ShibTargetException(SHIBRPC_OK, "Shibboleth POST failed to find SAMLResponse form element");
1047 // Make sure the target parameter exists
1048 if (!elements.second || !*elements.second)
1049 throw ShibTargetException(SHIBRPC_OK, "Shibboleth POST failed to find TARGET form element");
1051 // Process the post.
1053 RPCError* status=NULL;
1054 ShibMLP markupProcessor;
1055 markupProcessor.insert("requestURL", targeturl.c_str());
1057 status = shire.sessionCreate(elements.first,pblock_findval("ip",sn->client),cookie);
1059 catch (ShibTargetException &e) {
1060 markupProcessor.insert("errorType", "Session Creation Service Error");
1061 markupProcessor.insert("errorText", e.what());
1062 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1063 return WriteClientError(sn, rq, application, "shire", markupProcessor);
1067 markupProcessor.insert("errorType", "Session Creation Service Error");
1068 markupProcessor.insert("errorText", "Unexpected Exception");
1069 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1070 return WriteClientError(sn, rq, application, "shire", markupProcessor);
1074 if (status->isError()) {
1075 if (status->isRetryable()) {
1077 const char* loc=shire.getAuthnRequest(elements.second);
1078 if (!httpRedirects.first || httpRedirects.second) {
1079 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
1080 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
1081 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
1082 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
1083 pblock_nvinsert("Location",loc,rq->srvhdrs);
1084 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1085 protocol_start_response(sn,rq);
1086 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1090 markupProcessor.insert("requestURL",loc);
1091 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1095 // Return this error to the user.
1096 markupProcessor.insert(*status);
1098 return WriteClientError(sn,rq,application,"shire",markupProcessor);
1102 // We've got a good session, set the cookie and redirect to target.
1103 cookie = string(shib_cookie.first) + '=' + cookie + shib_cookie.second;
1104 pblock_nvinsert("Set-Cookie",cookie.c_str(),rq->srvhdrs);
1105 if (!httpRedirects.first || httpRedirects.second) {
1106 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
1107 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
1108 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
1109 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
1110 pblock_nvinsert("Location",elements.second,rq->srvhdrs);
1111 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1112 protocol_start_response(sn,rq);
1113 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1117 markupProcessor.insert("requestURL",elements.second);
1118 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1121 catch (ShibTargetException &e) {
1123 ShibMLP markupProcessor;
1124 markupProcessor.insert("requestURL", targeturl.c_str());
1125 markupProcessor.insert("errorType", "Session Creation Service Error");
1126 markupProcessor.insert("errorText", e.what());
1127 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1128 return WriteClientError(sn,rq,application,"shire",markupProcessor);
1134 ShibMLP markupProcessor;
1135 markupProcessor.insert("requestURL", targeturl.c_str());
1136 markupProcessor.insert("errorType", "Session Creation Service Error");
1137 markupProcessor.insert("errorText", "Unexpected Exception");
1138 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1139 return WriteClientError(sn,rq,application,"shire",markupProcessor);