Path resolution for error templates.
[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     const char* prefix=pblock_findval("shib-prefix",pb);
124
125     g_Config=&SPConfig::getConfig();
126     g_Config->setFeatures(
127         SPConfig::Listener |
128         SPConfig::Caching |
129         SPConfig::RequestMapping |
130         SPConfig::InProcess |
131         SPConfig::Logging |
132         SPConfig::Handlers
133         );
134     if (!g_Config->init(schemadir,prefix)) {
135         g_Config=NULL;
136         pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
137         return REQ_ABORTED;
138     }
139
140     g_Config->RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
141
142     const char* config=pblock_findval("shib-config",pb);
143     if (!config)
144         config=getenv("SHIBSP_CONFIG");
145     if (!config)
146         config=SHIBSP_CONFIG;
147
148     try {
149         xercesc::DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
150         XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
151         xercesc::DOMElement* dummy = dummydoc->createElementNS(NULL,path);
152         auto_ptr_XMLCh src(config);
153         dummy->setAttributeNS(NULL,path,src.get());
154         dummy->setAttributeNS(NULL,validate,xmlconstants::XML_ONE);
155
156         g_Config->setServiceProvider(g_Config->ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER,dummy));
157         g_Config->getServiceProvider()->init();
158     }
159     catch (exception& ex) {
160         pblock_nvinsert("error",ex.what(),pb);
161         g_Config->term();
162         g_Config=NULL;
163         return REQ_ABORTED;
164     }
165
166     daemon_atrestart(nsapi_shib_exit,NULL);
167
168     ServiceProvider* sp=g_Config->getServiceProvider();
169     Locker locker(sp);
170     const PropertySet* props=sp->getPropertySet("Local");
171     if (props) {
172         pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
173         if (unsetValue.first)
174             g_unsetHeaderValue = unsetValue.second;
175         pair<bool,bool> flag=props->getBool("checkSpoofing");
176         g_checkSpoofing = !flag.first || flag.second;
177         flag=props->getBool("catchAll");
178         g_catchAll = flag.first && flag.second;
179     }
180     return REQ_PROCEED;
181 }
182
183 /********************************************************************************/
184 // NSAPI Shib Target Subclass
185
186 class ShibTargetNSAPI : public AbstractSPRequest
187 {
188   mutable string m_body;
189   mutable bool m_gotBody,m_firsttime;
190   mutable vector<string> m_certs;
191   set<string> m_allhttp;
192
193 public:
194   pblock* m_pb;
195   ::Session* m_sn;
196   Request* m_rq;
197
198   ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq)
199       : AbstractSPRequest(SHIBSP_LOGCAT".NSAPI"), m_gotBody(false), m_firsttime(true), m_pb(pb), m_sn(sn), m_rq(rq) {
200
201     const char* uri=pblock_findval("uri", rq->reqpb);
202     const char* qstr=pblock_findval("query", rq->reqpb);
203
204     if (qstr) {
205         string temp = string(uri) + '?' + qstr;
206         setRequestURI(temp.c_str());
207     }
208     else {
209         setRequestURI(uri);
210     }
211
212     // See if this is the first time we've run.
213     qstr = pblock_findval("auth-type", rq->vars);
214     if (qstr && !strcmp(qstr, "shibboleth"))
215         m_firsttime = false;
216     if (!m_firsttime || rq->orig_rq)
217         log(SPDebug, "nsapi_shib function running more than once");
218   }
219   ~ShibTargetNSAPI() { }
220
221   const char* getScheme() const {
222     return security_active ? "https" : "http";
223   }
224   const char* getHostname() const {
225 #ifdef vs_is_default_vs
226     // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
227     if (!vs_is_default_vs(request_get_vs(m_rq)))
228         // The beauty here is, a non-default vhost can *only* be accessed if the client
229         // specified the exact name in the Host header. So we can trust the Host header.
230         return pblock_findval("host", m_rq->headers);
231     else
232 #endif
233     // In other cases, we're going to rely on the initialization process...
234     return g_ServerName.c_str();
235   }
236   int getPort() const {
237     return server_portnum;
238   }
239   const char* getMethod() const {
240     return pblock_findval("method", m_rq->reqpb);
241   }
242   string getContentType() const {
243     char* content_type = "";
244     request_header("content-type", &content_type, m_sn, m_rq);
245     return content_type;
246   }
247   long getContentLength() const {
248     if (m_gotBody)
249         return m_body.length();
250     char* content_length="";
251     request_header("content-length", &content_length, m_sn, m_rq);
252     return atoi(content_length);
253   }
254   string getRemoteAddr() const {
255     return pblock_findval("ip", m_sn->client);
256   }
257   void log(SPLogLevel level, const string& msg) const {
258     AbstractSPRequest::log(level,msg);
259     if (level>=SPError)
260         log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
261   }
262   const char* getQueryString() const { 
263     return pblock_findval("query", m_rq->reqpb);
264   }
265   const char* getRequestBody() const {
266     if (m_gotBody)
267         return m_body.c_str();
268     char* content_length=NULL;
269     if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED || atoi(content_length) > 1024*1024) // 1MB?
270       throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
271     else {
272       char ch=IO_EOF+1;
273       int cl=atoi(content_length);
274       m_gotBody=true;
275       while (cl && ch != IO_EOF) {
276         ch=netbuf_getc(m_sn->inbuf);
277         // Check for error.
278         if(ch==IO_ERROR)
279           break;
280         m_body += ch;
281         cl--;
282       }
283       if (cl)
284         throw IOException("Error reading request body from browser.");
285       return m_body.c_str();
286     }
287   }
288   void clearHeader(const char* rawname, const char* cginame) {
289     if (g_checkSpoofing && m_firsttime && !m_rq->orig_rq) {
290         if (m_allhttp.empty()) {
291             // Populate the set of client-supplied headers for spoof checking.
292             const pb_entry* entry;
293             for (int i=0; i<m_rq->headers->hsize; ++i) {
294                 entry = m_rq->headers->ht[i];
295                 while (entry) {
296                     string cgiversion("HTTP_");
297                     const char* pch = entry->param->name;
298                     while (*pch) {
299                         cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
300                         pch++;
301                     }
302                     m_allhttp.insert(cgiversion);
303                     entry = entry->next;
304                 }
305             }
306         }
307         if (m_allhttp.count(cginame) > 0)
308             throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
309     }
310     param_free(pblock_remove(rawname, m_rq->headers));
311     pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
312   }
313   void setHeader(const char* name, const char* value) {
314     param_free(pblock_remove(name, m_rq->headers));
315     pblock_nvinsert(name, value, m_rq->headers);
316   }
317   string getHeader(const char* name) const {
318     // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
319     char* hdr = NULL;
320     int cookie = strcmp(name, "Cookie");
321     if (cookie == 0)
322         name = "cookie";
323     if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
324       // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
325       if (cookie == 0)
326           return "";
327       string n;
328       while (*name)
329           n += tolower(*(name++));
330       if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
331           return "";
332     }
333     return string(hdr ? hdr : "");
334   }
335   void setRemoteUser(const char* user) {
336     pblock_nvinsert("auth-user", user, m_rq->vars);
337   }
338   string getRemoteUser() const {
339     const char* ru = pblock_findval("auth-user", m_rq->vars);
340     return ru ? ru : "";
341   }
342   void setResponseHeader(const char* name, const char* value) {
343     pblock_nvinsert(name, value, m_rq->srvhdrs);
344   }
345
346   long sendResponse(istream& in, long status) {
347     string msg;
348     char buf[1024];
349     while (in) {
350         in.read(buf,1024);
351         msg.append(buf,in.gcount());
352     }
353     pblock_nvinsert("connection","close",m_rq->srvhdrs);
354     pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
355     protocol_status(m_sn, m_rq, status, NULL);
356     protocol_start_response(m_sn, m_rq);
357     net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
358     return REQ_EXIT;
359   }
360   long sendRedirect(const char* url) {
361     param_free(pblock_remove("content-type", m_rq->srvhdrs));
362     pblock_nninsert("content-length", 0, m_rq->srvhdrs);
363     pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
364     pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
365     pblock_nvinsert("location", url, m_rq->srvhdrs);
366     pblock_nvinsert("connection","close",m_rq->srvhdrs);
367     protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
368     protocol_start_response(m_sn, m_rq);
369     return REQ_ABORTED;
370   }
371   long returnDecline() { return REQ_NOACTION; }
372   long returnOK() { return REQ_PROCEED; }
373   const vector<string>& getClientCertificates() const {
374       if (m_certs.empty()) {
375           const char* cert = pblock_findval("auth-cert", m_rq->vars);
376           if (cert)
377               m_certs.push_back(cert);
378       }
379       return m_certs;
380   }
381 };
382
383 /********************************************************************************/
384
385 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
386 {
387     log_error(LOG_FAILURE,func,sn,rq,msg);
388     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
389     return REQ_ABORTED;
390 }
391
392 #undef FUNC
393 #define FUNC "shibboleth"
394 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
395 {
396   ostringstream threadid;
397   threadid << "[" << getpid() << "] nsapi_shib" << '\0';
398   xmltooling::NDC ndc(threadid.str().c_str());
399
400   try {
401     ShibTargetNSAPI stn(pb, sn, rq);
402
403     // Check user authentication
404     pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
405     if (res.first) return (int)res.second;
406
407     // user authN was okay -- export the assertions now
408     param_free(pblock_remove("auth-user",rq->vars));
409     // This seems to be required in order to eventually set
410     // the auth-user var.
411     pblock_nvinsert("auth-type","shibboleth",rq->vars);
412     res = stn.getServiceProvider().doExport(stn);
413     if (res.first) return (int)res.second;
414
415     // Check the Authorization
416     res = stn.getServiceProvider().doAuthorization(stn);
417     if (res.first) return (int)res.second;
418
419     // this user is ok.
420     return REQ_PROCEED;
421   }
422   catch (exception& e) {
423     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
424     return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
425   }
426   catch (...) {
427     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>("Shibboleth module threw an unknown exception."));
428     if (g_catchAll)
429         return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
430     throw;
431   }
432 }
433
434
435 #undef FUNC
436 #define FUNC "shib_handler"
437 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
438 {
439   ostringstream threadid;
440   threadid << "[" << getpid() << "] shib_handler" << '\0';
441   xmltooling::NDC ndc(threadid.str().c_str());
442
443   try {
444     ShibTargetNSAPI stn(pb, sn, rq);
445
446     pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
447     if (res.first) return (int)res.second;
448
449     return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
450   }
451   catch (exception& e) {
452     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
453     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
454   }
455   catch (...) {
456     if (g_catchAll)
457         return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
458     throw;
459   }
460 }
461
462
463 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
464 {
465 public:
466     SunRequestMapper(const xercesc::DOMElement* e);
467     ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
468     Lockable* lock() { return m_mapper->lock(); }
469     void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
470     Settings getSettings(const HTTPRequest& request) const;
471     
472     const PropertySet* getParent() const { return NULL; }
473     void setParent(const PropertySet*) {}
474     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
475     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
476     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
477     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
478     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
479     void getAll(map<string,const char*>& properties) 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 HTTPRequest& 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 void SunRequestMapper::getAll(map<string,const char*>& properties) 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 (s)
576         s->getAll(properties);
577     if (!stn)
578         return;
579     properties["authType"] = "shibboleth";
580     const pb_entry* entry;
581     for (int i=0; i<stn->m_pb->hsize; ++i) {
582         entry = stn->m_pb->ht[i];
583         while (entry) {
584             properties[entry->param->name] = entry->param->value;
585             entry = entry->next;
586         }
587     }
588 }
589
590 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
591 {
592     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
593     return s ? s->getPropertySet(name,ns) : NULL;
594 }
595
596 const xercesc::DOMElement* SunRequestMapper::getElement() const
597 {
598     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
599     return s ? s->getElement() : NULL;
600 }