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>
85 using namespace shibboleth;
86 using namespace shibtarget;
88 // macros to output text to client
89 #define NET_WRITE(str) \
90 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
93 ShibTargetConfig* g_Config=NULL;
95 string g_ServerScheme;
98 PlugManager::Factory SunRequestMapFactory;
100 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
103 g_Config->shutdown();
107 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, Session* sn, Request* rq)
109 // Save off a default hostname for this virtual server.
110 char* name=pblock_findval("server-name",pb);
114 name=server_hostname;
118 name=util_hostname();
124 pblock_nvinsert("error","unable to determine web server hostname",pb);
129 name=pblock_findval("server-scheme",pb);
133 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
138 const char* schemadir=pblock_findval("shib-schemas",pb);
140 schemadir=getenv("SHIBSCHEMAS");
142 schemadir=SHIB_SCHEMAS;
143 const char* config=pblock_findval("shib-config",pb);
145 config=getenv("SHIBCONFIG");
148 g_Config=&ShibTargetConfig::getConfig();
149 g_Config->setFeatures(
150 ShibTargetConfig::Listener |
151 ShibTargetConfig::Metadata |
152 ShibTargetConfig::AAP |
153 ShibTargetConfig::RequestMapper |
154 ShibTargetConfig::LocalExtensions |
155 ShibTargetConfig::Logging
157 if (!g_Config->init(schemadir)) {
159 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
163 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&SunRequestMapFactory);
164 // We hijack the legacy type so that 1.2 config files will load this plugin
165 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&SunRequestMapFactory);
167 if (!g_Config->load(config)) {
169 pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
173 daemon_atrestart(nsapi_shib_exit,NULL);
178 pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
185 /********************************************************************************/
186 // NSAPI Shib Target Subclass
188 class ShibTargetNSAPI : public ShibTarget
191 ShibTargetNSAPI(pblock* pb, Session* sn, Request* rq) {
192 // Get everything but hostname...
193 const char* uri=pblock_findval("uri", rq->reqpb);
194 const char* qstr=pblock_findval("query", rq->reqpb);
195 int port=server_portnum;
196 const char* scheme=security_active ? "https" : "http";
197 const char* host=NULL;
203 url=url + '?' + qstr;
205 #ifdef vs_is_default_vs
206 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
207 if (!vs_is_default_vs)
208 // The beauty here is, a non-default vhost can *only* be accessed if the client
209 // specified the exact name in the Host header. So we can trust the Host header.
210 host=pblock_findval("host", rq->headers);
213 // In other cases, we're going to rely on the initialization process...
214 host=g_ServerName.c_str();
216 char* content_type = "";
217 request_header("content-type", &content_type, sn, rq);
219 const char *remote_ip = pblock_findval("ip", sn->client);
220 const char *method = pblock_findval("method", rq->reqpb);
222 init(scheme, host, port, url.c_str(), content_type, remote_ip, method);
228 ~ShibTargetNSAPI() {}
230 virtual void log(ShibLogLevel level, const string &msg) {
231 ShibTarget::log(level,msg);
232 if (level==LogLevelError)
233 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
235 virtual string getCookies(void) const {
236 char *cookies = NULL;
237 if (request_header("cookie", &cookies, m_sn, m_rq) == REQ_ABORTED)
238 throw("error accessing cookie header");
239 return string(cookies ? cookies : "");
241 virtual void setCookie(const string &name, const string &value) {
242 string cookie = name + '=' + value;
243 pblock_nvinsert("Set-Cookie", cookie.c_str(), m_rq->srvhdrs);
245 virtual string getArgs(void) {
246 const char *q = pblock_findval("query", m_rq->reqpb);
247 return string(q ? q : "");
249 virtual string getPostData(void) {
250 char* content_length=NULL;
251 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
252 atoi(content_length) > 1024*1024) // 1MB?
253 throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
256 int cl=atoi(content_length);
258 while (cl && ch != IO_EOF) {
259 ch=netbuf_getc(m_sn->inbuf);
268 throw FatalProfileException("Error reading profile submission from browser.");
272 virtual void clearHeader(const string &name) {
273 param_free(pblock_remove(name.c_str(), m_rq->headers));
275 virtual void setHeader(const string &name, const string &value) {
276 pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
278 virtual string getHeader(const string &name) {
280 if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
282 return string(hdr ? hdr : "");
284 virtual void setRemoteUser(const string &user) {
285 pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
286 pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
288 virtual string getRemoteUser(void) {
289 return getHeader("remote-user");
291 // Override this function because we want to add the NSAPI Directory override
293 virtual pair<bool,bool> getRequireSession(IRequestMapper::Settings &settings) {
294 pair<bool,bool> requireSession=settings.first->getBool("requireSession");
295 if (!requireSession.first || !requireSession.second) {
296 const char* param=pblock_findval("require-session",pb);
297 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
298 requireSession.second=true;
300 return requireSession;
304 virtual void* sendPage(
307 const string& content_type="text/html",
308 const saml::Iterator<header_t>& headers=EMPTY(header_t)
310 pblock_nvinsert("Content-Type", content_type.c_str(), m_rq->srvhdrs);
311 pblock_nninsert("Content-Length", msg.length(), m_rq->srvhdrs);
312 pblock_nvinsert("Connection","close",m_rq->srvhdrs);
313 while (headers.hasNext()) {
314 const header_t& h=headers.next();
315 pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
317 protocol_status(m_sn, m_rq, code, NULL);
318 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
319 return (void*)REQ_EXIT;
321 virtual void* sendRedirect(const string& url) {
322 pblock_nvinsert("Content-Type", "text/html", m_rq->srvhdrs);
323 pblock_nninsert("Content-Length", 40, m_rq->srvhdrs);
324 pblock_nvinsert("Expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
325 pblock_nvinsert("Cache-Control", "private,no-store,no-cache", m_rq->srvhdrs);
326 pblock_nvinsert("Location", url.c_str(), m_rq->srvhdrs);
327 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, "302 Please wait");
328 protocol_start_response(m_sn, m_rq);
329 char* msg="<HTML><BODY>Redirecting...</BODY></HTML>";
330 net_write(m_sn->csd,msg,strlen(msg));
331 return (void*)REQ_EXIT;
333 virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
334 virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
341 /********************************************************************************/
343 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
345 log_error(LOG_FAILURE,func,sn,rq,msg);
346 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
351 #define FUNC "shibboleth"
352 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
354 ostringstream threadid;
355 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
356 saml::NDC ndc(threadid.str().c_str());
361 ShibTargetNSAPI stn(pb, sn, rq);
363 // Check user authentication
364 pair<bool,void*> res = stn.doCheckAuthN();
365 if (res.first) return (int)res.second;
367 // user authN was okay -- export the assertions now
369 const char* param=pblock_findval("export-assertion", pb);
370 bool doExportAssn = false;
371 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
374 res = stn.doExportAssertions();
375 if (res.first) return (int)res.second;
377 // Check the Authorization
378 res = stn.doCheckAuthZ();
379 if (res.first) return (int)res.second;
387 return WriteClientError(sn, rq, FUNC, "threw an uncaught exception.");
394 #define FUNC "shib_handler"
395 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
397 ostringstream threadid;
398 threadid << "[" << getpid() << "] shib_handler" << '\0';
399 saml::NDC ndc(threadid.str().c_str());
404 ShibTargetNSAPI stn(pb, sn, rq);
406 pair<bool,void*> res = stn.doHandler();
407 if (res.first) return (int)res.second;
409 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
414 return WriteClientError(sn, rq, FUNC, "Filter threw an unknown exception.");
420 class SunRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
423 SunRequestMapper(const DOMElement* e);
424 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
425 void lock() { m_mapper->lock(); }
426 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
427 Settings getSettings(ShibTarget* st) const;
429 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
430 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
431 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
432 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
433 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
434 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
435 const DOMElement* getElement() const;
438 IRequestMapper* m_mapper;
440 ThreadKey* m_propsKey;
443 IPlugIn* SunRequestMapFactory(const DOMElement* e)
445 return new SunRequestMapper(e);
448 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
450 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
451 m_mapper=dynamic_cast<IRequestMapper*>(p);
454 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
456 m_stKey=ThreadKey::create(NULL);
457 m_propsKey=ThreadKey::create(NULL);
460 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
462 Settings s=m_mapper->getSettings(st);
463 m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
464 m_propsKey->setData((void*)s.first);
465 return pair<const IPropertySet*,IAccessControl*>(this,s.second);
468 pair<bool,bool> SunRequestMapper::getBool(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 boolean properties.
474 const char* param=pblock_findval(name,stn->m_pb);
475 if (param && (!strcmp(param,"1") || !util_strcasecmp(param,"true")))
476 return make_pair(true,true);
478 return s ? s->getBool(name,ns) : make_pair(false,false);
481 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
483 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
484 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
485 if (stn && !ns && name) {
486 // Override string properties.
487 if (!strcmp(name,"authType"))
488 return pair<bool,const char*>(true,"shibboleth");
490 const char* param=pblock_findval(name,stn->m_pb);
492 return make_pair(true,param);
495 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
498 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
500 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
501 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
504 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
506 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
507 return s ? s->getUnsignedInt(name,ns) : make_pair(false,0);
510 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
512 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
513 return s ? s->getInt(name,ns) : make_pair(false,0);
516 const IPropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
518 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
519 return s ? s->getPropertySet(name,ns) : NULL;
522 const DOMElement* SunRequestMapper::getElement() const
524 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
525 return s ? s->getElement() : NULL;
531 IRequestMapper::Settings map_request(pblock* pb, Session* sn, Request* rq, IRequestMapper* mapper, string& target)
533 // Get everything but hostname...
534 const char* uri=pblock_findval("uri",rq->reqpb);
535 const char* qstr=pblock_findval("query",rq->reqpb);
536 int port=server_portnum;
537 const char* scheme=security_active ? "https" : "http";
538 const char* host=NULL;
544 url=url + '?' + qstr;
546 #ifdef vs_is_default_vs
547 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
548 if (!vs_is_default_vs)
549 // The beauty here is, a non-default vhost can *only* be accessed if the client
550 // specified the exact name in the Host header. So we can trust the Host header.
551 host=pblock_findval("host", rq->headers);
554 // In other cases, we're going to rely on the initialization process...
555 host=g_ServerName.c_str();
557 target=(g_ServerScheme.empty() ? string(scheme) : g_ServerScheme) + "://" + host;
559 // If port is non-default, append it.
560 if ((!security_active && port!=80) || (security_active && port!=443)) {
562 util_snprintf(portbuf,9,"%d",port);
563 target = target + ':' + portbuf;
568 return mapper->getSettingsFromParsedURL(scheme,host,port,url.c_str());
571 int WriteClientError(Session* sn, Request* rq, const IApplication* app, const char* page, ShibMLP& mlp)
573 const IPropertySet* props=app->getPropertySet("Errors");
575 pair<bool,const char*> p=props->getString(page);
577 ifstream infile(p.second);
578 if (!infile.fail()) {
579 const char* res = mlp.run(infile,props);
581 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
582 pblock_nninsert("Content-Length",strlen(res),rq->srvhdrs);
583 pblock_nvinsert("Connection","close",rq->srvhdrs);
584 protocol_status(sn,rq,PROTOCOL_OK,NULL);
585 NET_WRITE(const_cast<char*>(res));
592 log_error(LOG_FAILURE,"WriteClientError",sn,rq,"Unable to open error template, check settings.");
593 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,"Unable to open error template, check settings.");
597 int WriteRedirectPage(Session* sn, Request* rq, const IApplication* app, const char* file, ShibMLP& mlp)
599 ifstream infile(file);
600 if (!infile.fail()) {
601 const char* res = mlp.run(infile,app->getPropertySet("Errors"));
603 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
604 pblock_nninsert("Content-Length",strlen(res),rq->srvhdrs);
605 protocol_status(sn,rq,PROTOCOL_OK,NULL);
606 NET_WRITE(const_cast<char*>(res));
610 log_error(LOG_FAILURE,"WriteRedirectPage",sn,rq,"Unable to open redirect template, check settings.");
611 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,"Unable to open redirect template, check settings.");
616 #define FUNC "shibboleth"
617 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
621 ostringstream threadid;
622 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
623 saml::NDC ndc(threadid.str().c_str());
625 // We lock the configuration system for the duration.
626 IConfig* conf=g_Config->getINI();
629 // Map request to application and content settings.
631 IRequestMapper* mapper=conf->getRequestMapper();
632 Locker locker2(mapper);
633 IRequestMapper::Settings settings=map_request(pb,sn,rq,mapper,targeturl);
634 pair<bool,const char*> application_id=settings.first->getString("applicationId");
635 const IApplication* application=conf->getApplication(application_id.second);
637 return WriteClientError(sn,rq,FUNC,"Unable to map request to application settings, check configuration.");
639 // Declare SHIRE object for this request.
640 SHIRE shire(application);
642 const char* shireURL=shire.getShireURL(targeturl.c_str());
644 return WriteClientError(sn,rq,FUNC,"Unable to map request to proper shireURL setting, check configuration.");
646 // If the user is accessing the SHIRE acceptance point, pass it on.
647 if (targeturl.find(shireURL)!=string::npos)
650 // Now check the policy for this request.
651 pair<bool,bool> requireSession=settings.first->getBool("requireSession");
652 if (!requireSession.first || !requireSession.second) {
653 const char* param=pblock_findval("require-session",pb);
654 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
655 requireSession.second=true;
657 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();
658 pair<bool,bool> httpRedirects=application->getPropertySet("Sessions")->getBool("httpRedirects");
659 pair<bool,const char*> redirectPage=application->getPropertySet("Sessions")->getString("redirectPage");
660 if (httpRedirects.first && !httpRedirects.second && !redirectPage.first)
661 return WriteClientError(sn,rq,FUNC,"HTML-based redirection requires a redirectPage property.");
663 // Check for session cookie.
664 const char* session_id=NULL;
666 if (request_header("cookie",(char**)&session_id,sn,rq)==REQ_ABORTED)
667 return WriteClientError(sn,rq,FUNC,"error accessing cookie header");
669 Category::getInstance("nsapi_shib."FUNC).debug("cookie header is {%s}",session_id ? session_id : "NULL");
670 if (session_id && (session_id=strstr(session_id,shib_cookie.first))) {
671 session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
672 char* cookieend=strchr(session_id,';');
674 // Chop out just the value portion.
675 cookie.assign(session_id,cookieend-session_id-1);
676 session_id=cookie.c_str();
680 if (!session_id || !*session_id) {
681 // If no session required, bail now.
682 if (!requireSession.second)
685 // No acceptable cookie, and we require a session. Generate an AuthnRequest.
686 const char* areq = shire.getAuthnRequest(targeturl.c_str());
687 if (!httpRedirects.first || httpRedirects.second) {
688 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
689 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
690 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
691 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
692 pblock_nvinsert("Location",areq,rq->srvhdrs);
693 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
694 protocol_start_response(sn,rq);
695 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
699 ShibMLP markupProcessor;
700 markupProcessor.insert("requestURL",areq);
701 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
705 // Make sure this session is still valid.
706 RPCError* status = NULL;
707 ShibMLP markupProcessor;
708 markupProcessor.insert("requestURL", targeturl);
711 status = shire.sessionIsValid(session_id, pblock_findval("ip",sn->client));
713 catch (ShibTargetException &e) {
714 markupProcessor.insert("errorType", "Session Processing Error");
715 markupProcessor.insert("errorText", e.what());
716 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
717 return WriteClientError(sn, rq, application, "shire", markupProcessor);
721 markupProcessor.insert("errorType", "Session Processing Error");
722 markupProcessor.insert("errorText", "Unexpected Exception");
723 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
724 return WriteClientError(sn, rq, application, "shire", markupProcessor);
729 if (status->isError()) {
730 if (!requireSession.second)
732 else if (status->isRetryable()) {
733 // Oops, session is invalid. Generate AuthnRequest.
735 const char* areq = shire.getAuthnRequest(targeturl.c_str());
736 if (!httpRedirects.first || httpRedirects.second) {
737 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
738 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
739 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
740 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
741 pblock_nvinsert("Location",areq,rq->srvhdrs);
742 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
743 protocol_start_response(sn,rq);
744 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
748 markupProcessor.insert("requestURL",areq);
749 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
753 // return the error page to the user
754 markupProcessor.insert(*status);
756 return WriteClientError(sn, rq, application, "shire", markupProcessor);
763 vector<SAMLAssertion*> assertions;
764 SAMLAuthenticationStatement* sso_statement=NULL;
767 status = rm.getAssertions(session_id, pblock_findval("ip",sn->client), assertions, &sso_statement);
769 catch (ShibTargetException &e) {
770 markupProcessor.insert("errorType", "Attribute Processing Error");
771 markupProcessor.insert("errorText", e.what());
772 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
773 return WriteClientError(sn, rq, application, "rm", markupProcessor);
777 markupProcessor.insert("errorType", "Attribute Processing Error");
778 markupProcessor.insert("errorText", "Unexpected Exception");
779 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
780 return WriteClientError(sn, rq, application, "rm", markupProcessor);
784 if (status->isError()) {
785 markupProcessor.insert(*status);
787 return WriteClientError(sn, rq, application, "rm", markupProcessor);
791 // Do we have an access control plugin?
792 if (settings.second) {
793 Locker acllock(settings.second);
794 if (!settings.second->authorized(*sso_statement,assertions)) {
795 for (int k = 0; k < assertions.size(); k++)
796 delete assertions[k];
797 delete sso_statement;
798 return WriteClientError(sn, rq, application, "access", markupProcessor);
802 // Get the AAP providers, which contain the attribute policy info.
803 Iterator<IAAP*> provs=application->getAAPProviders();
805 // Clear out the list of mapped attributes
806 while (provs.hasNext()) {
807 IAAP* aap=provs.next();
810 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
811 while (rules.hasNext()) {
812 const char* header=rules.next()->getHeader();
814 param_free(pblock_remove(header,rq->headers));
819 for (int k = 0; k < assertions.size(); k++)
820 delete assertions[k];
821 delete sso_statement;
822 markupProcessor.insert("errorType", "Attribute Processing Error");
823 markupProcessor.insert("errorText", "Unexpected Exception");
824 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
825 return WriteClientError(sn, rq, application, "rm", markupProcessor);
831 // Maybe export the first assertion.
832 param_free(pblock_remove("remote-user",rq->headers));
833 param_free(pblock_remove("auth-user",rq->vars));
834 param_free(pblock_remove("Shib-Attributes",rq->headers));
835 pair<bool,bool> exp=settings.first->getBool("exportAssertion");
836 if (!exp.first || !exp.second) {
837 const char* param=pblock_findval("export-assertion",pb);
838 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
841 if (exp.second && assertions.size()) {
843 RM::serialize(*(assertions[0]), assertion);
844 string::size_type lfeed;
845 while ((lfeed=assertion.find('\n'))!=string::npos)
846 assertion.erase(lfeed,1);
847 pblock_nvinsert("Shib-Attributes",assertion.c_str(),rq->headers);
850 pblock_nvinsert("auth-type","shibboleth",rq->vars);
851 param_free(pblock_remove("Shib-Origin-Site",rq->headers));
852 param_free(pblock_remove("Shib-Authentication-Method",rq->headers));
853 param_free(pblock_remove("Shib-NameIdentifier-Format",rq->headers));
855 // Export the SAML AuthnMethod and the origin site name.
856 auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
857 auto_ptr_char am(sso_statement->getAuthMethod());
858 pblock_nvinsert("Shib-Origin-Site",os.get(),rq->headers);
859 pblock_nvinsert("Shib-Authentication-Method",am.get(),rq->headers);
862 AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
863 if (!wrapper.fail() && wrapper->getHeader()) {
864 auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
865 auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
866 pblock_nvinsert("Shib-NameIdentifier-Format",form.get(),pb);
867 if (!strcmp(wrapper->getHeader(),"REMOTE_USER")) {
868 pblock_nvinsert("remote-user",nameid.get(),rq->headers);
869 pblock_nvinsert("auth-user",nameid.get(),rq->vars);
872 pblock_nvinsert(wrapper->getHeader(),nameid.get(),rq->headers);
876 param_free(pblock_remove("Shib-Application-ID",rq->headers));
877 pblock_nvinsert("Shib-Application-ID",application_id.second,rq->headers);
879 // Export the attributes.
880 Iterator<SAMLAssertion*> a_iter(assertions);
881 while (a_iter.hasNext()) {
882 SAMLAssertion* assert=a_iter.next();
883 Iterator<SAMLStatement*> statements=assert->getStatements();
884 while (statements.hasNext()) {
885 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
888 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
889 while (attrs.hasNext()) {
890 SAMLAttribute* attr=attrs.next();
892 // Are we supposed to export it?
893 AAP wrapper(provs,attr->getName(),attr->getNamespace());
894 if (wrapper.fail() || !wrapper->getHeader())
897 Iterator<string> vals=attr->getSingleByteValues();
898 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext()) {
899 char* principal=const_cast<char*>(vals.next().c_str());
900 pblock_nvinsert("remote-user",principal,rq->headers);
901 pblock_nvinsert("auth-user",principal,rq->vars);
906 const char* h=pblock_findval(wrapper->getHeader(),rq->headers);
909 param_free(pblock_remove(wrapper->getHeader(),rq->headers));
912 for (; vals.hasNext(); it++) {
913 string value = vals.next();
914 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
916 pos = value.find_first_of(";", pos)) {
917 value.insert(pos, "\\");
923 header=header + ';' + value;
925 pblock_nvinsert(wrapper->getHeader(),header.c_str(),rq->headers);
932 for (int k = 0; k < assertions.size(); k++)
933 delete assertions[k];
934 delete sso_statement;
939 return WriteClientError(sn, rq, FUNC,"Out of Memory");
943 return WriteClientError(sn, rq, FUNC,"Server caught an unknown exception.");
947 return WriteClientError(sn, rq, FUNC,"Server reached unreachable code, save my walrus!");
951 #define FUNC "shib_handler"
952 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
955 const IApplication* application=NULL;
958 ostringstream threadid;
959 threadid << "[" << getpid() << "] shib_handler" << '\0';
960 saml::NDC ndc(threadid.str().c_str());
962 // We lock the configuration system for the duration.
963 IConfig* conf=g_Config->getINI();
966 // Map request to application and content settings.
967 IRequestMapper* mapper=conf->getRequestMapper();
968 Locker locker2(mapper);
969 IRequestMapper::Settings settings=map_request(pb,sn,rq,mapper,targeturl);
970 pair<bool,const char*> application_id=settings.first->getString("applicationId");
971 application=conf->getApplication(application_id.second);
972 const IPropertySet* sessionProps=application ? application->getPropertySet("Sessions") : NULL;
973 if (!application || !sessionProps)
974 return WriteClientError(sn,rq,FUNC,"Unable to map request to application settings, check configuration.");
976 SHIRE shire(application);
978 const char* shireURL=shire.getShireURL(targeturl.c_str());
980 return WriteClientError(sn,rq,FUNC,"Unable to map request to proper shireURL setting, check configuration.");
982 // Make sure we only process the SHIRE requests.
983 if (!strstr(targeturl.c_str(),shireURL))
984 return WriteClientError(sn,rq,FUNC,"NSAPI service function can only be invoked to process incoming sessions."
985 "Make sure the mapped file extension or URL doesn't match actual content.");
987 pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();
989 // Make sure this is SSL, if it should be
990 pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
991 if (!shireSSL.first || shireSSL.second) {
992 if (!security_active)
993 throw ShibTargetException(SHIBRPC_OK,"blocked non-SSL access to Shibboleth session processor");
996 pair<bool,bool> httpRedirects=sessionProps->getBool("httpRedirects");
997 pair<bool,const char*> redirectPage=sessionProps->getString("redirectPage");
998 if (httpRedirects.first && !httpRedirects.second && !redirectPage.first)
999 return WriteClientError(sn,rq,FUNC,"HTML-based redirection requires a redirectPage property.");
1001 // If this is a GET, we manufacture an AuthnRequest.
1002 if (!strcasecmp(pblock_findval("method",rq->reqpb),"GET")) {
1003 const char* areq=pblock_findval("query",rq->reqpb) ? shire.getLazyAuthnRequest(pblock_findval("query",rq->reqpb)) : NULL;
1005 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
1006 if (!httpRedirects.first || httpRedirects.second) {
1007 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
1008 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
1009 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
1010 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
1011 pblock_nvinsert("Location",areq,rq->srvhdrs);
1012 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1013 protocol_start_response(sn,rq);
1014 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1018 ShibMLP markupProcessor;
1019 markupProcessor.insert("requestURL",areq);
1020 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1023 else if (strcasecmp(pblock_findval("method",rq->reqpb),"POST"))
1024 throw ShibTargetException(SHIBRPC_OK,"blocked non-POST to Shibboleth session processor");
1026 // Make sure this POST is an appropriate content type
1027 char* content_type=NULL;
1028 if (request_header("content-type",&content_type,sn,rq)!=REQ_PROCEED ||
1029 !content_type || strcasecmp(content_type,"application/x-www-form-urlencoded"))
1030 throw ShibTargetException(SHIBRPC_OK,"blocked bad content-type to Shibboleth session processor");
1033 pair<const char*,const char*> elements=pair<const char*,const char*>(NULL,NULL);
1034 char* content_length=NULL;
1035 if (request_header("content-length",&content_length,sn,rq)!=REQ_PROCEED ||
1036 atoi(content_length) > 1024*1024) // 1MB?
1037 throw ShibTargetException(SHIBRPC_OK,"blocked too-large a post to Shibboleth session processor");
1040 int cl=atoi(content_length);
1042 while (cl && ch!=IO_EOF) {
1043 ch=netbuf_getc(sn->inbuf);
1052 throw ShibTargetException(SHIBRPC_OK,"error reading POST data from browser");
1053 elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
1056 // Make sure the SAML Response parameter exists
1057 if (!elements.first || !*elements.first)
1058 throw ShibTargetException(SHIBRPC_OK, "Shibboleth POST failed to find SAMLResponse form element");
1060 // Make sure the target parameter exists
1061 if (!elements.second || !*elements.second)
1062 throw ShibTargetException(SHIBRPC_OK, "Shibboleth POST failed to find TARGET form element");
1064 // Process the post.
1066 RPCError* status=NULL;
1067 ShibMLP markupProcessor;
1068 markupProcessor.insert("requestURL", targeturl.c_str());
1070 status = shire.sessionCreate(elements.first,pblock_findval("ip",sn->client),cookie);
1072 catch (ShibTargetException &e) {
1073 markupProcessor.insert("errorType", "Session Creation Service Error");
1074 markupProcessor.insert("errorText", e.what());
1075 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1076 return WriteClientError(sn, rq, application, "shire", markupProcessor);
1080 markupProcessor.insert("errorType", "Session Creation Service Error");
1081 markupProcessor.insert("errorText", "Unexpected Exception");
1082 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1083 return WriteClientError(sn, rq, application, "shire", markupProcessor);
1087 if (status->isError()) {
1088 if (status->isRetryable()) {
1090 const char* loc=shire.getAuthnRequest(elements.second);
1091 if (!httpRedirects.first || httpRedirects.second) {
1092 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
1093 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
1094 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
1095 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
1096 pblock_nvinsert("Location",loc,rq->srvhdrs);
1097 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1098 protocol_start_response(sn,rq);
1099 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1103 markupProcessor.insert("requestURL",loc);
1104 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1108 // Return this error to the user.
1109 markupProcessor.insert(*status);
1111 return WriteClientError(sn,rq,application,"shire",markupProcessor);
1115 // We've got a good session, set the cookie and redirect to target.
1116 cookie = string(shib_cookie.first) + '=' + cookie + shib_cookie.second;
1117 pblock_nvinsert("Set-Cookie",cookie.c_str(),rq->srvhdrs);
1118 if (!httpRedirects.first || httpRedirects.second) {
1119 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
1120 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
1121 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
1122 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
1123 pblock_nvinsert("Location",elements.second,rq->srvhdrs);
1124 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1125 protocol_start_response(sn,rq);
1126 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1130 markupProcessor.insert("requestURL",elements.second);
1131 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1134 catch (ShibTargetException &e) {
1136 ShibMLP markupProcessor;
1137 markupProcessor.insert("requestURL", targeturl.c_str());
1138 markupProcessor.insert("errorType", "Session Creation Service Error");
1139 markupProcessor.insert("errorText", e.what());
1140 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1141 return WriteClientError(sn,rq,application,"shire",markupProcessor);
1147 ShibMLP markupProcessor;
1148 markupProcessor.insert("requestURL", targeturl.c_str());
1149 markupProcessor.insert("errorType", "Session Creation Service Error");
1150 markupProcessor.insert("errorText", "Unexpected Exception");
1151 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1152 return WriteClientError(sn,rq,application,"shire",markupProcessor);