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