Stop setting HTTP_REMOTE_USER.
[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     param_free(pblock_remove(rawname, m_rq->headers));
302     pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
303   }
304   void setHeader(const char* name, const char* value) {
305     param_free(pblock_remove(name, m_rq->headers));
306     pblock_nvinsert(name, value, m_rq->headers);
307   }
308   string getHeader(const char* name) const {
309     // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
310     char* hdr = NULL;
311     int cookie = strcmp(name, "Cookie");
312     if (cookie == 0)
313         name = "cookie";
314     if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
315       // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
316       if (cookie == 0)
317           return "";
318       string n;
319       while (*name)
320           n += tolower(*(name++));
321       if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
322           return "";
323     }
324     return string(hdr ? hdr : "");
325   }
326   void setRemoteUser(const char* user) {
327     pblock_nvinsert("auth-user", user, m_rq->vars);
328   }
329   string getRemoteUser() const {
330     const char* ru = pblock_findval("auth-user", m_rq->vars);
331     return ru ? ru : "";
332   }
333   void setResponseHeader(const char* name, const char* value) {
334     pblock_nvinsert(name, value, m_rq->srvhdrs);
335   }
336
337   long sendResponse(istream& in, long status) {
338     string msg;
339     char buf[1024];
340     while (in) {
341         in.read(buf,1024);
342         msg.append(buf,in.gcount());
343     }
344     pblock_nvinsert("connection","close",m_rq->srvhdrs);
345     pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
346     protocol_status(m_sn, m_rq, status, NULL);
347     protocol_start_response(m_sn, m_rq);
348     net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
349     return REQ_EXIT;
350   }
351   long sendRedirect(const char* url) {
352     param_free(pblock_remove("content-type", m_rq->srvhdrs));
353     pblock_nninsert("content-length", 0, m_rq->srvhdrs);
354     pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
355     pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
356     pblock_nvinsert("location", url, m_rq->srvhdrs);
357     pblock_nvinsert("connection","close",m_rq->srvhdrs);
358     protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
359     protocol_start_response(m_sn, m_rq);
360     return REQ_ABORTED;
361   }
362   long returnDecline() { return REQ_NOACTION; }
363   long returnOK() { return REQ_PROCEED; }
364   const vector<string>& getClientCertificates() const {
365       if (m_certs.empty()) {
366           const char* cert = pblock_findval("auth-cert", m_rq->vars);
367           if (cert)
368               m_certs.push_back(cert);
369       }
370       return m_certs;
371   }
372
373   pblock* m_pb;
374   ::Session* m_sn;
375   Request* m_rq;
376 };
377
378 /********************************************************************************/
379
380 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
381 {
382     log_error(LOG_FAILURE,func,sn,rq,msg);
383     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
384     return REQ_ABORTED;
385 }
386
387 #undef FUNC
388 #define FUNC "shibboleth"
389 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
390 {
391   ostringstream threadid;
392   threadid << "[" << getpid() << "] nsapi_shib" << '\0';
393   xmltooling::NDC ndc(threadid.str().c_str());
394
395   try {
396     ShibTargetNSAPI stn(pb, sn, rq);
397
398     // Check user authentication
399     pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
400     if (res.first) return (int)res.second;
401
402     // user authN was okay -- export the assertions now
403     param_free(pblock_remove("auth-user",rq->vars));
404     // This seems to be required in order to eventually set
405     // the auth-user var.
406     pblock_nvinsert("auth-type","shibboleth",rq->vars);
407     res = stn.getServiceProvider().doExport(stn);
408     if (res.first) return (int)res.second;
409
410     // Check the Authorization
411     res = stn.getServiceProvider().doAuthorization(stn);
412     if (res.first) return (int)res.second;
413
414     // this user is ok.
415     return REQ_PROCEED;
416   }
417   catch (exception& e) {
418     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
419     return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
420   }
421 #ifndef _DEBUG
422   catch (...) {
423     return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an uncaught exception.");
424   }
425 #endif
426 }
427
428
429 #undef FUNC
430 #define FUNC "shib_handler"
431 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
432 {
433   ostringstream threadid;
434   threadid << "[" << getpid() << "] shib_handler" << '\0';
435   xmltooling::NDC ndc(threadid.str().c_str());
436
437   try {
438     ShibTargetNSAPI stn(pb, sn, rq);
439
440     pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
441     if (res.first) return (int)res.second;
442
443     return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
444   }
445   catch (exception& e) {
446     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
447     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
448   }
449 #ifndef _DEBUG
450   catch (...) {
451     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
452   }
453 #endif
454 }
455
456
457 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
458 {
459 public:
460     SunRequestMapper(const xercesc::DOMElement* e);
461     ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
462     Lockable* lock() { return m_mapper->lock(); }
463     void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
464     Settings getSettings(const SPRequest& request) const;
465     
466     const PropertySet* getParent() const { return NULL; }
467     void setParent(const PropertySet*) {}
468     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
469     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
470     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
471     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
472     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
473     const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const;
474     const xercesc::DOMElement* getElement() const;
475
476 private:
477     RequestMapper* m_mapper;
478     ThreadKey* m_stKey;
479     ThreadKey* m_propsKey;
480 };
481
482 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
483 {
484     return new SunRequestMapper(e);
485 }
486
487 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
488 {
489     m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
490     m_stKey=ThreadKey::create(NULL);
491     m_propsKey=ThreadKey::create(NULL);
492 }
493
494 RequestMapper::Settings SunRequestMapper::getSettings(const SPRequest& request) const
495 {
496     Settings s=m_mapper->getSettings(request);
497     m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
498     m_propsKey->setData((void*)s.first);
499     return pair<const PropertySet*,AccessControl*>(this,s.second);
500 }
501
502 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
503 {
504     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
505     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
506     if (stn && !ns && name) {
507         // Override boolean properties.
508         const char* param=pblock_findval(name,stn->m_pb);
509         if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
510             return make_pair(true,true);
511     }
512     return s ? s->getBool(name,ns) : make_pair(false,false);
513 }
514
515 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
516 {
517     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
518     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
519     if (stn && !ns && name) {
520         // Override string properties.
521         if (!strcmp(name,"authType"))
522             return pair<bool,const char*>(true,"shibboleth");
523         else {
524             const char* param=pblock_findval(name,stn->m_pb);
525             if (param)
526                 return make_pair(true,param);
527         }
528     }
529     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
530 }
531
532 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
533 {
534     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
535     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
536 }
537
538 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
539 {
540     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
541     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
542     if (stn && !ns && name) {
543         // Override int properties.
544         const char* param=pblock_findval(name,stn->m_pb);
545         if (param)
546             return pair<bool,unsigned int>(true,strtol(param,NULL,10));
547     }
548     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
549 }
550
551 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
552 {
553     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
554     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
555     if (stn && !ns && name) {
556         // Override int properties.
557         const char* param=pblock_findval(name,stn->m_pb);
558         if (param)
559             return pair<bool,int>(true,atoi(param));
560     }
561     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
562 }
563
564 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
565 {
566     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
567     return s ? s->getPropertySet(name,ns) : NULL;
568 }
569
570 const xercesc::DOMElement* SunRequestMapper::getElement() const
571 {
572     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
573     return s ? s->getElement() : NULL;
574 }