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