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