6c8618e4b9e2a676a4604bd88b3bc3a6b265e707
[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
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         SPConfig::Handlers
139         );
140     if (!g_Config->init(schemadir)) {
141         g_Config=NULL;
142         pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
143         return REQ_ABORTED;
144     }
145
146     g_Config->RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
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> checkSpoofing=props->getBool("checkSpoofing");
176         if (checkSpoofing.first && !checkSpoofing.second)
177             g_checkSpoofing = false;
178     }
179     return REQ_PROCEED;
180 }
181
182 /********************************************************************************/
183 // NSAPI Shib Target Subclass
184
185 class ShibTargetNSAPI : public AbstractSPRequest
186 {
187   string m_uri;
188   mutable string m_body;
189   mutable bool m_gotBody;
190   mutable vector<string> m_certs;
191   set<string> m_allhttp;
192
193 public:
194   ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq) : m_gotBody(false) {
195     m_pb = pb;
196     m_sn = sn;
197     m_rq = rq;
198
199     const char* uri=pblock_findval("uri", rq->reqpb);
200     const char* qstr=pblock_findval("query", rq->reqpb);
201
202     if (uri)
203         m_uri = uri;
204     if (qstr)
205         m_uri = m_uri + '?' + qstr;
206   }
207   ~ShibTargetNSAPI() {
208   }
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* getRequestURI() const {
229     return m_uri.c_str();
230   }
231   const char* getMethod() const {
232     return pblock_findval("method", m_rq->reqpb);
233   }
234   string getContentType() const {
235     char* content_type = "";
236     request_header("content-type", &content_type, m_sn, m_rq);
237     return content_type;
238   }
239   long getContentLength() const {
240     if (m_gotBody)
241         return m_body.length();
242     char* content_length="";
243     request_header("content-length", &content_length, m_sn, m_rq);
244     return atoi(content_length);
245   }
246   string getRemoteAddr() const {
247     return pblock_findval("ip", m_sn->client);
248   }
249   void log(SPLogLevel level, const string& msg) const {
250     AbstractSPRequest::log(level,msg);
251     if (level>=SPError)
252         log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
253   }
254   const char* getQueryString() const { 
255     return pblock_findval("query", m_rq->reqpb);
256   }
257   const char* getRequestBody() const {
258     if (m_gotBody)
259         return m_body.c_str();
260     char* content_length=NULL;
261     if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED || atoi(content_length) > 1024*1024) // 1MB?
262       throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
263     else {
264       char ch=IO_EOF+1;
265       int cl=atoi(content_length);
266       m_gotBody=true;
267       while (cl && ch != IO_EOF) {
268         ch=netbuf_getc(m_sn->inbuf);
269         // Check for error.
270         if(ch==IO_ERROR)
271           break;
272         m_body += ch;
273         cl--;
274       }
275       if (cl)
276         throw IOException("Error reading request body from browser.");
277       return m_body.c_str();
278     }
279   }
280   void clearHeader(const char* rawname, const char* cginame) {
281     if (g_checkSpoofing) {
282         if (m_allhttp.empty()) {
283             // Populate the set of client-supplied headers for spoof checking.
284             const pb_entry* entry;
285             for (int i=0; i<m_rq->headers->hsize; ++i) {
286                 entry = m_rq->headers->ht[i];
287                 while (entry) {
288                     string cgiversion("HTTP_");
289                     const char* pch = entry->param->name;
290                     while (*pch) {
291                         cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
292                         pch++;
293                     }
294                     m_allhttp.insert(cgiversion);
295                     entry = entry->next;
296                 }
297             }
298         }
299         if (m_allhttp.count(cginame) > 0)
300             throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
301     }
302     param_free(pblock_remove(rawname, m_rq->headers));
303     pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
304   }
305   void setHeader(const char* name, const char* value) {
306     param_free(pblock_remove(name, m_rq->headers));
307     pblock_nvinsert(name, value, m_rq->headers);
308   }
309   string getHeader(const char* name) const {
310     // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
311     char* hdr = NULL;
312     int cookie = strcmp(name, "Cookie");
313     if (cookie == 0)
314         name = "cookie";
315     if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
316       // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
317       if (cookie == 0)
318           return "";
319       string n;
320       while (*name)
321           n += tolower(*(name++));
322       if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
323           return "";
324     }
325     return string(hdr ? hdr : "");
326   }
327   void setRemoteUser(const char* user) {
328     pblock_nvinsert("auth-user", user, m_rq->vars);
329   }
330   string getRemoteUser() const {
331     const char* ru = pblock_findval("auth-user", m_rq->vars);
332     return ru ? ru : "";
333   }
334   void setResponseHeader(const char* name, const char* value) {
335     pblock_nvinsert(name, value, m_rq->srvhdrs);
336   }
337
338   long sendResponse(istream& in, long status) {
339     string msg;
340     char buf[1024];
341     while (in) {
342         in.read(buf,1024);
343         msg.append(buf,in.gcount());
344     }
345     pblock_nvinsert("connection","close",m_rq->srvhdrs);
346     pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
347     protocol_status(m_sn, m_rq, status, NULL);
348     protocol_start_response(m_sn, m_rq);
349     net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
350     return REQ_EXIT;
351   }
352   long sendRedirect(const char* url) {
353     param_free(pblock_remove("content-type", m_rq->srvhdrs));
354     pblock_nninsert("content-length", 0, m_rq->srvhdrs);
355     pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
356     pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
357     pblock_nvinsert("location", url, m_rq->srvhdrs);
358     pblock_nvinsert("connection","close",m_rq->srvhdrs);
359     protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
360     protocol_start_response(m_sn, m_rq);
361     return REQ_ABORTED;
362   }
363   long returnDecline() { return REQ_NOACTION; }
364   long returnOK() { return REQ_PROCEED; }
365   const vector<string>& getClientCertificates() const {
366       if (m_certs.empty()) {
367           const char* cert = pblock_findval("auth-cert", m_rq->vars);
368           if (cert)
369               m_certs.push_back(cert);
370       }
371       return m_certs;
372   }
373
374   pblock* m_pb;
375   ::Session* m_sn;
376   Request* m_rq;
377 };
378
379 /********************************************************************************/
380
381 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
382 {
383     log_error(LOG_FAILURE,func,sn,rq,msg);
384     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
385     return REQ_ABORTED;
386 }
387
388 #undef FUNC
389 #define FUNC "shibboleth"
390 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
391 {
392   ostringstream threadid;
393   threadid << "[" << getpid() << "] nsapi_shib" << '\0';
394   xmltooling::NDC ndc(threadid.str().c_str());
395
396   try {
397     ShibTargetNSAPI stn(pb, sn, rq);
398
399     // Check user authentication
400     pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
401     if (res.first) return (int)res.second;
402
403     // user authN was okay -- export the assertions now
404     param_free(pblock_remove("auth-user",rq->vars));
405     // This seems to be required in order to eventually set
406     // the auth-user var.
407     pblock_nvinsert("auth-type","shibboleth",rq->vars);
408     res = stn.getServiceProvider().doExport(stn);
409     if (res.first) return (int)res.second;
410
411     // Check the Authorization
412     res = stn.getServiceProvider().doAuthorization(stn);
413     if (res.first) return (int)res.second;
414
415     // this user is ok.
416     return REQ_PROCEED;
417   }
418   catch (exception& e) {
419     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
420     return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
421   }
422 #ifndef _DEBUG
423   catch (...) {
424     return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an uncaught exception.");
425   }
426 #endif
427 }
428
429
430 #undef FUNC
431 #define FUNC "shib_handler"
432 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
433 {
434   ostringstream threadid;
435   threadid << "[" << getpid() << "] shib_handler" << '\0';
436   xmltooling::NDC ndc(threadid.str().c_str());
437
438   try {
439     ShibTargetNSAPI stn(pb, sn, rq);
440
441     pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
442     if (res.first) return (int)res.second;
443
444     return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
445   }
446   catch (exception& e) {
447     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
448     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
449   }
450 #ifndef _DEBUG
451   catch (...) {
452     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
453   }
454 #endif
455 }
456
457
458 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
459 {
460 public:
461     SunRequestMapper(const xercesc::DOMElement* e);
462     ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
463     Lockable* lock() { return m_mapper->lock(); }
464     void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
465     Settings getSettings(const HTTPRequest& request) const;
466     
467     const PropertySet* getParent() const { return NULL; }
468     void setParent(const PropertySet*) {}
469     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
470     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
471     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
472     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
473     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
474     void getAll(map<string,const char*>& properties) const;
475     const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const;
476     const xercesc::DOMElement* getElement() const;
477
478 private:
479     RequestMapper* m_mapper;
480     ThreadKey* m_stKey;
481     ThreadKey* m_propsKey;
482 };
483
484 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
485 {
486     return new SunRequestMapper(e);
487 }
488
489 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
490 {
491     m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
492     m_stKey=ThreadKey::create(NULL);
493     m_propsKey=ThreadKey::create(NULL);
494 }
495
496 RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
497 {
498     Settings s=m_mapper->getSettings(request);
499     m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
500     m_propsKey->setData((void*)s.first);
501     return pair<const PropertySet*,AccessControl*>(this,s.second);
502 }
503
504 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
505 {
506     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
507     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
508     if (stn && !ns && name) {
509         // Override boolean properties.
510         const char* param=pblock_findval(name,stn->m_pb);
511         if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
512             return make_pair(true,true);
513     }
514     return s ? s->getBool(name,ns) : make_pair(false,false);
515 }
516
517 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
518 {
519     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
520     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
521     if (stn && !ns && name) {
522         // Override string properties.
523         if (!strcmp(name,"authType"))
524             return pair<bool,const char*>(true,"shibboleth");
525         else {
526             const char* param=pblock_findval(name,stn->m_pb);
527             if (param)
528                 return make_pair(true,param);
529         }
530     }
531     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
532 }
533
534 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
535 {
536     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
537     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
538 }
539
540 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
541 {
542     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
543     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
544     if (stn && !ns && name) {
545         // Override int properties.
546         const char* param=pblock_findval(name,stn->m_pb);
547         if (param)
548             return pair<bool,unsigned int>(true,strtol(param,NULL,10));
549     }
550     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
551 }
552
553 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
554 {
555     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
556     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
557     if (stn && !ns && name) {
558         // Override int properties.
559         const char* param=pblock_findval(name,stn->m_pb);
560         if (param)
561             return pair<bool,int>(true,atoi(param));
562     }
563     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
564 }
565
566 void SunRequestMapper::getAll(map<string,const char*>& properties) const
567 {
568     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
569     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
570     if (s)
571         s->getAll(properties);
572     properties["authType"] = "shibboleth";
573     const pb_entry* entry;
574     for (int i=0; i<stn->m_pb->hsize; ++i) {
575         entry = stn->m_pb->ht[i];
576         while (entry) {
577             properties[entry->param->name] = entry->param->value;
578             entry = entry->next;
579         }
580     }
581 }
582
583 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
584 {
585     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
586     return s ? s->getPropertySet(name,ns) : NULL;
587 }
588
589 const xercesc::DOMElement* SunRequestMapper::getElement() const
590 {
591     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
592     return s ? s->getElement() : NULL;
593 }