Log uncaught exceptions in handler.
[shibboleth/cpp-sp.git] / nsapi_shib / nsapi_shib.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * nsapi_shib.cpp
19  *
20  * Shibboleth NSAPI filter
21  */
22
23 #define SHIBSP_LITE
24
25 #if defined (_MSC_VER) || defined(__BORLANDC__)
26 # include "config_win32.h"
27 #else
28 # include "config.h"
29 #endif
30
31 #ifdef WIN32
32 # define _CRT_NONSTDC_NO_DEPRECATE 1
33 # define _CRT_SECURE_NO_DEPRECATE 1
34 #endif
35
36 #include <shibsp/AbstractSPRequest.h>
37 #include <shibsp/RequestMapper.h>
38 #include <shibsp/SPConfig.h>
39 #include <shibsp/ServiceProvider.h>
40 #include <xmltooling/XMLToolingConfig.h>
41 #include <xmltooling/util/NDC.h>
42 #include <xmltooling/util/Threads.h>
43 #include <xmltooling/util/XMLConstants.h>
44 #include <xmltooling/util/XMLHelper.h>
45 #include <xercesc/util/XMLUniDefs.hpp>
46
47 #include <memory>
48 #include <fstream>
49 #include <sstream>
50 #include <stdexcept>
51
52 #ifdef WIN32
53 # include <process.h>
54 # define XP_WIN32
55 #else
56 # define XP_UNIX
57 #endif
58
59 #define MCC_HTTPD
60 #define NET_SSL
61
62 extern "C"
63 {
64 #include <nsapi.h>
65 }
66
67 using namespace shibsp;
68 using namespace xmltooling;
69 using namespace std;
70
71 // macros to output text to client
72 #define NET_WRITE(str) \
73     if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
74
75 namespace {
76     SPConfig* g_Config=NULL;
77     string g_ServerName;
78     string g_ServerScheme;
79     string g_unsetHeaderValue;
80     string g_spoofKey;
81     bool g_checkSpoofing = true;
82     bool g_catchAll = false;
83
84     static const XMLCh path[] =     UNICODE_LITERAL_4(p,a,t,h);
85     static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
86 }
87
88 PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
89
90 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
91 {
92     if (g_Config)
93         g_Config->term();
94     g_Config = NULL;
95 }
96
97 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
98 {
99     // Save off a default hostname for this virtual server.
100     char* name=pblock_findval("server-name",pb);
101     if (name)
102         g_ServerName=name;
103     else {
104         name=server_hostname;
105         if (name)
106             g_ServerName=name;
107         else {
108             name=util_hostname();
109             if (name) {
110                 g_ServerName=name;
111                 FREE(name);
112             }
113             else {
114                 pblock_nvinsert("error","unable to determine web server hostname",pb);
115                 return REQ_ABORTED;
116             }
117         }
118     }
119     name=pblock_findval("server-scheme",pb);
120     if (name)
121         g_ServerScheme=name;
122
123     log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
124
125     const char* schemadir=pblock_findval("shib-schemas",pb);
126     const char* prefix=pblock_findval("shib-prefix",pb);
127
128     g_Config=&SPConfig::getConfig();
129     g_Config->setFeatures(
130         SPConfig::Listener |
131         SPConfig::Caching |
132         SPConfig::RequestMapping |
133         SPConfig::InProcess |
134         SPConfig::Logging |
135         SPConfig::Handlers
136         );
137     if (!g_Config->init(schemadir,prefix)) {
138         g_Config=NULL;
139         pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
140         return REQ_ABORTED;
141     }
142
143     g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&SunRequestMapFactory);
144
145     try {
146         if (!g_Config->instantiate(pblock_findval("shib-config",pb), true))
147             throw runtime_error("unknown error");
148     }
149     catch (exception& ex) {
150         pblock_nvinsert("error",ex.what(),pb);
151         g_Config->term();
152         g_Config=NULL;
153         return REQ_ABORTED;
154     }
155
156     daemon_atrestart(nsapi_shib_exit,NULL);
157
158     ServiceProvider* sp=g_Config->getServiceProvider();
159     Locker locker(sp);
160     const PropertySet* props=sp->getPropertySet("InProcess");
161     if (props) {
162         pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
163         if (unsetValue.first)
164             g_unsetHeaderValue = unsetValue.second;
165         pair<bool,bool> flag=props->getBool("checkSpoofing");
166         g_checkSpoofing = !flag.first || flag.second;
167         if (g_checkSpoofing) {
168             unsetValue=props->getString("spoofKey");
169             if (unsetValue.first)
170                 g_spoofKey = unsetValue.second;
171         }
172         flag=props->getBool("catchAll");
173         g_catchAll = flag.first && flag.second;
174     }
175     return REQ_PROCEED;
176 }
177
178 /********************************************************************************/
179 // NSAPI Shib Target Subclass
180
181 class ShibTargetNSAPI : public AbstractSPRequest
182 {
183   mutable string m_body;
184   mutable bool m_gotBody,m_firsttime;
185   mutable vector<string> m_certs;
186   set<string> m_allhttp;
187
188 public:
189   pblock* m_pb;
190   ::Session* m_sn;
191   Request* m_rq;
192
193   ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq)
194       : AbstractSPRequest(SHIBSP_LOGCAT".NSAPI"), m_gotBody(false), m_firsttime(true), m_pb(pb), m_sn(sn), m_rq(rq) {
195
196     const char* uri=pblock_findval("uri", rq->reqpb);
197     const char* qstr=pblock_findval("query", rq->reqpb);
198
199     if (qstr) {
200         string temp = string(uri) + '?' + qstr;
201         setRequestURI(temp.c_str());
202     }
203     else {
204         setRequestURI(uri);
205     }
206
207     // See if this is the first time we've run.
208     if (!g_spoofKey.empty()) {
209         qstr = pblock_findval("Shib-Spoof-Check", rq->headers);
210         if (qstr && g_spoofKey == qstr)
211             m_firsttime = false;
212     }
213     if (!m_firsttime || rq->orig_rq)
214         log(SPDebug, "nsapi_shib function running more than once");
215   }
216   ~ShibTargetNSAPI() { }
217
218   const char* getScheme() const {
219     return security_active ? "https" : "http";
220   }
221   const char* getHostname() const {
222 #ifdef vs_is_default_vs
223     // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
224     if (!vs_is_default_vs(request_get_vs(m_rq)))
225         // The beauty here is, a non-default vhost can *only* be accessed if the client
226         // specified the exact name in the Host header. So we can trust the Host header.
227         return pblock_findval("host", m_rq->headers);
228     else
229 #endif
230     // In other cases, we're going to rely on the initialization process...
231     return g_ServerName.c_str();
232   }
233   int getPort() const {
234     return server_portnum;
235   }
236   const char* getMethod() const {
237     return pblock_findval("method", m_rq->reqpb);
238   }
239   string getContentType() const {
240     char* content_type = "";
241     request_header("content-type", &content_type, m_sn, m_rq);
242     return content_type;
243   }
244   long getContentLength() const {
245     if (m_gotBody)
246         return m_body.length();
247     char* content_length="";
248     request_header("content-length", &content_length, m_sn, m_rq);
249     return atoi(content_length);
250   }
251   string getRemoteAddr() const {
252     return pblock_findval("ip", m_sn->client);
253   }
254   void log(SPLogLevel level, const string& msg) const {
255     AbstractSPRequest::log(level,msg);
256     if (level>=SPError)
257         log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
258   }
259   const char* getQueryString() const {
260     return pblock_findval("query", m_rq->reqpb);
261   }
262   const char* getRequestBody() const {
263     if (m_gotBody)
264         return m_body.c_str();
265     char* content_length=NULL;
266     if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED || atoi(content_length) > 1024*1024) // 1MB?
267       throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
268     else {
269       char ch=IO_EOF+1;
270       int cl=atoi(content_length);
271       m_gotBody=true;
272       while (cl && ch != IO_EOF) {
273         ch=netbuf_getc(m_sn->inbuf);
274         // Check for error.
275         if(ch==IO_ERROR)
276           break;
277         m_body += ch;
278         cl--;
279       }
280       if (cl)
281         throw IOException("Error reading request body from browser.");
282       return m_body.c_str();
283     }
284   }
285   void clearHeader(const char* rawname, const char* cginame) {
286     if (g_checkSpoofing && m_firsttime && !m_rq->orig_rq) {
287         if (m_allhttp.empty()) {
288             // Populate the set of client-supplied headers for spoof checking.
289             const pb_entry* entry;
290             for (int i=0; i<m_rq->headers->hsize; ++i) {
291                 entry = m_rq->headers->ht[i];
292                 while (entry) {
293                     string cgiversion("HTTP_");
294                     const char* pch = entry->param->name;
295                     while (*pch) {
296                         cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
297                         pch++;
298                     }
299                     m_allhttp.insert(cgiversion);
300                     entry = entry->next;
301                 }
302             }
303         }
304         if (m_allhttp.count(cginame) > 0)
305             throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
306     }
307     if (strcmp(rawname, "REMOTE_USER") == 0) {
308         param_free(pblock_remove("remote-user", m_rq->headers));
309         pblock_nvinsert("remote-user", g_unsetHeaderValue.c_str(), m_rq->headers);
310     }
311     else {
312         param_free(pblock_remove(rawname, m_rq->headers));
313         pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
314     }
315   }
316   void setHeader(const char* name, const char* value) {
317     param_free(pblock_remove(name, m_rq->headers));
318     pblock_nvinsert(name, value, m_rq->headers);
319   }
320   string getHeader(const char* name) const {
321     // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
322     char* hdr = NULL;
323     int cookie = strcmp(name, "Cookie");
324     if (cookie == 0)
325         name = "cookie";
326     if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
327       // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
328       if (cookie == 0)
329           return "";
330       string n;
331       while (*name)
332           n += tolower(*(name++));
333       if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
334           return "";
335     }
336     return string(hdr ? hdr : "");
337   }
338   void setRemoteUser(const char* user) {
339     pblock_nvinsert("auth-user", user, m_rq->vars);
340     param_free(pblock_remove("remote-user", m_rq->headers));
341     pblock_nvinsert("remote-user", user, m_rq->headers);
342   }
343   string getRemoteUser() const {
344     const char* ru = pblock_findval("auth-user", m_rq->vars);
345     return ru ? ru : "";
346   }
347   void setResponseHeader(const char* name, const char* value) {
348     pblock_nvinsert(name, value, m_rq->srvhdrs);
349   }
350
351   long sendResponse(istream& in, long status) {
352     string msg;
353     char buf[1024];
354     while (in) {
355         in.read(buf,1024);
356         msg.append(buf,in.gcount());
357     }
358     pblock_nvinsert("connection","close",m_rq->srvhdrs);
359     pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
360     protocol_status(m_sn, m_rq, status, NULL);
361     protocol_start_response(m_sn, m_rq);
362     net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
363     return REQ_EXIT;
364   }
365   long sendRedirect(const char* url) {
366     param_free(pblock_remove("content-type", m_rq->srvhdrs));
367     pblock_nninsert("content-length", 0, m_rq->srvhdrs);
368     pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
369     pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
370     pblock_nvinsert("location", url, m_rq->srvhdrs);
371     pblock_nvinsert("connection","close",m_rq->srvhdrs);
372     protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
373     protocol_start_response(m_sn, m_rq);
374     return REQ_ABORTED;
375   }
376   long returnDecline() { return REQ_NOACTION; }
377   long returnOK() { return REQ_PROCEED; }
378   const vector<string>& getClientCertificates() const {
379       if (m_certs.empty()) {
380           const char* cert = pblock_findval("auth-cert", m_rq->vars);
381           if (cert)
382               m_certs.push_back(cert);
383       }
384       return m_certs;
385   }
386 };
387
388 /********************************************************************************/
389
390 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
391 {
392     log_error(LOG_FAILURE,func,sn,rq,msg);
393     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
394     return REQ_ABORTED;
395 }
396
397 #undef FUNC
398 #define FUNC "shibboleth"
399 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
400 {
401   ostringstream threadid;
402   threadid << "[" << getpid() << "] nsapi_shib" << '\0';
403   xmltooling::NDC ndc(threadid.str().c_str());
404
405   try {
406     ShibTargetNSAPI stn(pb, sn, rq);
407
408     // Check user authentication
409     pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
410     // If directed, install a spoof key to recognize when we've already cleared headers.
411     if (!g_spoofKey.empty()) {
412       param_free(pblock_remove("Shib-Spoof-Check", rq->headers));
413       pblock_nvinsert("Shib-Spoof-Check", g_spoofKey.c_str(), rq->headers);
414     }
415     if (res.first) return (int)res.second;
416
417     // user authN was okay -- export the assertions now
418     param_free(pblock_remove("auth-user",rq->vars));
419
420     // This seems to be required in order to eventually set
421     // the auth-user var.
422     pblock_nvinsert("auth-type","shibboleth",rq->vars);
423
424     res = stn.getServiceProvider().doExport(stn);
425     if (res.first) return (int)res.second;
426
427     // Check the Authorization
428     res = stn.getServiceProvider().doAuthorization(stn);
429     if (res.first) return (int)res.second;
430
431     // this user is ok.
432     return REQ_PROCEED;
433   }
434   catch (exception& e) {
435     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
436     return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
437   }
438   catch (...) {
439     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>("Shibboleth module threw an unknown exception."));
440     if (g_catchAll)
441         return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
442     throw;
443   }
444 }
445
446
447 #undef FUNC
448 #define FUNC "shib_handler"
449 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
450 {
451   ostringstream threadid;
452   threadid << "[" << getpid() << "] shib_handler" << '\0';
453   xmltooling::NDC ndc(threadid.str().c_str());
454
455   try {
456     ShibTargetNSAPI stn(pb, sn, rq);
457
458     pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
459     if (res.first) return (int)res.second;
460
461     return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
462   }
463   catch (exception& e) {
464     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
465     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
466   }
467   catch (...) {
468     log_error(LOG_FAILURE,FUNC,sn,rq,"unknown exception caught in Shibboleth handler");
469     if (g_catchAll)
470         return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
471     throw;
472   }
473 }
474
475
476 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
477 {
478 public:
479     SunRequestMapper(const xercesc::DOMElement* e);
480     ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
481     Lockable* lock() { return m_mapper->lock(); }
482     void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
483     Settings getSettings(const HTTPRequest& request) const;
484
485     const PropertySet* getParent() const { return NULL; }
486     void setParent(const PropertySet*) {}
487     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
488     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
489     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
490     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
491     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
492     void getAll(map<string,const char*>& properties) const;
493     const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
494     const xercesc::DOMElement* getElement() const;
495
496 private:
497     RequestMapper* m_mapper;
498     ThreadKey* m_stKey;
499     ThreadKey* m_propsKey;
500 };
501
502 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
503 {
504     return new SunRequestMapper(e);
505 }
506
507 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
508 {
509     m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
510     m_stKey=ThreadKey::create(NULL);
511     m_propsKey=ThreadKey::create(NULL);
512 }
513
514 RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
515 {
516     Settings s=m_mapper->getSettings(request);
517     m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
518     m_propsKey->setData((void*)s.first);
519     return pair<const PropertySet*,AccessControl*>(this,s.second);
520 }
521
522 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
523 {
524     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
525     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
526     if (stn && !ns && name) {
527         // Override boolean properties.
528         const char* param=pblock_findval(name,stn->m_pb);
529         if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
530             return make_pair(true,true);
531     }
532     return s ? s->getBool(name,ns) : make_pair(false,false);
533 }
534
535 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
536 {
537     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
538     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
539     if (stn && !ns && name) {
540         // Override string properties.
541         if (!strcmp(name,"authType"))
542             return pair<bool,const char*>(true,"shibboleth");
543         else {
544             const char* param=pblock_findval(name,stn->m_pb);
545             if (param)
546                 return make_pair(true,param);
547         }
548     }
549     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
550 }
551
552 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
553 {
554     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
555     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
556 }
557
558 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
559 {
560     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
561     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
562     if (stn && !ns && name) {
563         // Override int properties.
564         const char* param=pblock_findval(name,stn->m_pb);
565         if (param)
566             return pair<bool,unsigned int>(true,strtol(param,NULL,10));
567     }
568     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
569 }
570
571 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
572 {
573     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
574     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
575     if (stn && !ns && name) {
576         // Override int properties.
577         const char* param=pblock_findval(name,stn->m_pb);
578         if (param)
579             return pair<bool,int>(true,atoi(param));
580     }
581     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
582 }
583
584 void SunRequestMapper::getAll(map<string,const char*>& properties) const
585 {
586     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
587     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
588     if (s)
589         s->getAll(properties);
590     if (!stn)
591         return;
592     properties["authType"] = "shibboleth";
593     const pb_entry* entry;
594     for (int i=0; i<stn->m_pb->hsize; ++i) {
595         entry = stn->m_pb->ht[i];
596         while (entry) {
597             properties[entry->param->name] = entry->param->value;
598             entry = entry->next;
599         }
600     }
601 }
602
603 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
604 {
605     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
606     return s ? s->getPropertySet(name,ns) : NULL;
607 }
608
609 const xercesc::DOMElement* SunRequestMapper::getElement() const
610 {
611     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
612     return s ? s->getElement() : NULL;
613 }