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