Detect multiple executions of NSAPI function so spoof check doesn't run twice.
[shibboleth/cpp-sp.git] / nsapi_shib / nsapi_shib.cpp
1 /*
2  *  Copyright 2001-2005 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 /* nsapi_shib.cpp - Shibboleth NSAPI filter
18
19    Scott Cantor
20    12/13/04
21 */
22
23 #if defined (_MSC_VER) || defined(__BORLANDC__)
24 # include "config_win32.h"
25 #else
26 # include "config.h"
27 #endif
28
29
30 // SAML Runtime
31 #include <saml/saml.h>
32 #include <shib/shib.h>
33 #include <shib/shib-threads.h>
34 #include <shib-target/shib-target.h>
35
36 #include <ctime>
37 #include <fstream>
38 #include <sstream>
39 #include <stdexcept>
40
41 #ifdef WIN32
42 # include <process.h>
43 # define XP_WIN32
44 #else
45 # define XP_UNIX
46 #endif
47
48 #define MCC_HTTPD
49 #define NET_SSL
50
51 extern "C"
52 {
53 #include <nsapi.h>
54 }
55
56 using namespace std;
57 using namespace saml;
58 using namespace shibboleth;
59 using namespace shibtarget;
60
61 // macros to output text to client
62 #define NET_WRITE(str) \
63     if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
64
65 namespace {
66     ShibTargetConfig* g_Config=NULL;
67     string g_ServerName;
68     string g_ServerScheme;
69     string g_unsetHeaderValue;
70     bool g_checkSpoofing = false;
71     bool g_catchAll = true;
72 }
73
74 PlugManager::Factory SunRequestMapFactory;
75
76 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
77 {
78     if (g_Config)
79         g_Config->shutdown();
80     g_Config = NULL;
81 }
82
83 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, Session* sn, Request* rq)
84 {
85     // Save off a default hostname for this virtual server.
86     char* name=pblock_findval("server-name",pb);
87     if (name)
88         g_ServerName=name;
89     else {
90         name=server_hostname;
91         if (name)
92             g_ServerName=name;
93         else {
94             name=util_hostname();
95             if (name) {
96                 g_ServerName=name;
97                 FREE(name);
98             }
99             else {
100                 pblock_nvinsert("error","unable to determine web server hostname",pb);
101                 return REQ_ABORTED;
102             }
103         }
104     }
105     name=pblock_findval("server-scheme",pb);
106     if (name)
107         g_ServerScheme=name;
108
109     log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
110
111     try {
112         const char* schemadir=pblock_findval("shib-schemas",pb);
113         if (!schemadir)
114             schemadir=getenv("SHIBSCHEMAS");
115         if (!schemadir)
116             schemadir=SHIB_SCHEMAS;
117         const char* config=pblock_findval("shib-config",pb);
118         if (!config)
119             config=getenv("SHIBCONFIG");
120         if (!config)
121             config=SHIB_CONFIG;
122         g_Config=&ShibTargetConfig::getConfig();
123         g_Config->setFeatures(
124             ShibTargetConfig::Listener |
125             ShibTargetConfig::Metadata |
126             ShibTargetConfig::AAP |
127             ShibTargetConfig::RequestMapper |
128             ShibTargetConfig::LocalExtensions |
129             ShibTargetConfig::Logging
130             );
131         if (!g_Config->init(schemadir)) {
132             g_Config=NULL;
133             pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
134             return REQ_ABORTED;
135         }
136
137         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&SunRequestMapFactory);
138         // We hijack the legacy type so that 1.2 config files will load this plugin
139         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&SunRequestMapFactory);
140
141         if (!g_Config->load(config)) {
142             g_Config=NULL;
143             pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
144             return REQ_ABORTED;
145         }
146
147         daemon_atrestart(nsapi_shib_exit,NULL);
148
149         IConfig* conf=g_Config->getINI();
150         Locker locker(conf);
151         const IPropertySet* props=conf->getPropertySet("Local");
152         if (props) {
153             pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
154             if (unsetValue.first)
155                 g_unsetHeaderValue = unsetValue.second;
156             pair<bool,bool> flag=props->getBool("checkSpoofing");
157             g_checkSpoofing = !flag.first || flag.second;
158             flag=props->getBool("catchAll");
159             g_catchAll = !flag.first || flag.second;
160         }
161     }
162     catch (exception&) {
163         g_Config=NULL;
164         pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
165         return REQ_ABORTED;
166     }
167     return REQ_PROCEED;
168 }
169
170 /********************************************************************************/
171 // NSAPI Shib Target Subclass
172
173 class ShibTargetNSAPI : public ShibTarget
174 {
175 public:
176   ShibTargetNSAPI(pblock* pb, Session* sn, Request* rq) : m_pb(pb), m_sn(sn), m_rq(rq), m_firsttime(true) {
177     // Get everything but hostname...
178     const char* uri=pblock_findval("uri", rq->reqpb);
179     const char* qstr=pblock_findval("query", rq->reqpb);
180     int port=server_portnum;
181     const char* scheme=security_active ? "https" : "http";
182     const char* host=NULL;
183
184     string url;
185     if (uri)
186         url=uri;
187     if (qstr)
188         url=url + '?' + qstr;
189     
190 #ifdef vs_is_default_vs
191     // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
192     if (!vs_is_default_vs(request_get_vs(m_rq)))
193         // The beauty here is, a non-default vhost can *only* be accessed if the client
194         // specified the exact name in the Host header. So we can trust the Host header.
195         host=pblock_findval("host", rq->headers);
196     else
197 #endif
198     // In other cases, we're going to rely on the initialization process...
199     host=g_ServerName.c_str();
200
201     char* content_type = "";
202     request_header("content-type", &content_type, sn, rq);
203       
204     const char* remote_ip = pblock_findval("ip", sn->client);
205     const char* method = pblock_findval("method", rq->reqpb);
206
207     init(scheme, host, port, url.c_str(), content_type, remote_ip, method);
208     
209     // See if this is the first time we've run.
210     method = pblock_findval("auth-type", rq->vars);
211     if (method && !strcmp(method, "shibboleth"))
212         m_firsttime = false;
213     if (!m_firsttime)
214         log(LogLevelDebug, "nsapi_shib function running more than once");
215   }
216   ~ShibTargetNSAPI() {
217   }
218
219   virtual void log(ShibLogLevel level, const string &msg) {
220     ShibTarget::log(level,msg);
221     if (level==LogLevelError)
222         log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
223   }
224   virtual string getCookies(void) const {
225     char *cookies = NULL;
226     if (request_header("cookie", &cookies, m_sn, m_rq) == REQ_ABORTED)
227       throw("error accessing cookie header");
228     return string(cookies ? cookies : "");
229   }
230   virtual void setCookie(const string &name, const string &value) {
231     string cookie = name + '=' + value;
232     pblock_nvinsert("Set-Cookie", cookie.c_str(), m_rq->srvhdrs);
233   }
234   virtual string getArgs(void) { 
235     const char *q = pblock_findval("query", m_rq->reqpb);
236     return string(q ? q : "");
237   }
238   virtual string getPostData(void) {
239     char* content_length=NULL;
240     if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
241          atoi(content_length) > 1024*1024) // 1MB?
242       throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
243     else {
244       char ch=IO_EOF+1;
245       int cl=atoi(content_length);
246       string cgistr;
247       while (cl && ch != IO_EOF) {
248         ch=netbuf_getc(m_sn->inbuf);
249       
250         // Check for error.
251         if(ch==IO_ERROR)
252           break;
253         cgistr += ch;
254         cl--;
255       }
256       if (cl)
257         throw FatalProfileException("Error reading profile submission from browser.");
258       return cgistr;
259     }
260   }
261   virtual void clearHeader(const string &name) {
262     if (m_firsttime && g_checkSpoofing && m_allhttp.empty()) {
263       // Populate the set of client-supplied headers for spoof checking.
264       const pb_entry* entry;
265       for (int i=0; i<m_rq->headers->hsize; ++i) {
266           entry = m_rq->headers->ht[i];
267           while (entry) {
268               string cgiversion("HTTP_");
269               const char* pch = entry->param->name;
270               while (*pch) {
271                   cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
272                   pch++;
273               }
274               m_allhttp.insert(cgiversion);
275               entry = entry->next;
276           }
277       }
278     }
279     if (name=="REMOTE_USER") {
280         if (m_firsttime && g_checkSpoofing && m_allhttp.count("HTTP_REMOTE_USER") > 0)
281             throw SAMLException("Attempt to spoof header ($1) was detected.", params(1, name.c_str()));
282         param_free(pblock_remove("auth-user",m_rq->vars));
283         param_free(pblock_remove("remote-user",m_rq->headers));
284     }
285     else {
286         if (m_firsttime && g_checkSpoofing) {
287             // Map to the expected CGI variable name.
288             string transformed("HTTP_");
289             const char* pch = name.c_str();
290             while (*pch) {
291                 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
292                 pch++;
293             }
294             if (m_allhttp.count(transformed) > 0)
295                 throw SAMLException("Attempt to spoof header ($1) was detected.", params(1, name.c_str()));
296         }
297         param_free(pblock_remove(name.c_str(), m_rq->headers));
298         pblock_nvinsert(name.c_str(), g_unsetHeaderValue.c_str(), m_rq->headers);
299     }
300   }
301   virtual void setHeader(const string &name, const string &value) {
302     param_free(pblock_remove(name.c_str(), m_rq->headers));
303     pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
304   }
305   virtual string getHeader(const string &name) {
306     char *hdr = NULL;
307     if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED) {
308       string n;
309       const char* pch = name.c_str();
310       while (*pch)
311           n += tolower(*(pch++));
312       if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
313           return "";
314     }
315     return string(hdr ? hdr : "");
316   }
317   virtual void setRemoteUser(const string &user) {
318     pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
319     pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
320   }
321   virtual string getRemoteUser(void) {
322     const char* ru = pblock_findval("auth-user", m_rq->vars);
323     return ru ? ru : "";
324   }
325
326   virtual void* sendPage(
327     const string& msg,
328     int code=200,
329     const string& content_type="text/html",
330     const saml::Iterator<header_t>& headers=EMPTY(header_t)
331     ) {
332     param_free(pblock_remove("content-type", m_rq->srvhdrs));
333     pblock_nvinsert("content-type", content_type.c_str(), m_rq->srvhdrs);
334     pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
335     pblock_nvinsert("connection","close",m_rq->srvhdrs);
336     while (headers.hasNext()) {
337         const header_t& h=headers.next();
338         pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
339     }
340     protocol_status(m_sn, m_rq, code, NULL);
341     protocol_start_response(m_sn, m_rq);
342     net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
343     return (void*)REQ_EXIT;
344   }
345   virtual void* sendRedirect(const string& url) {
346     param_free(pblock_remove("content-type", m_rq->srvhdrs));
347     pblock_nninsert("content-length", 0, m_rq->srvhdrs);
348     pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
349     pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
350     pblock_nvinsert("location", url.c_str(), m_rq->srvhdrs);
351     pblock_nvinsert("connection","close",m_rq->srvhdrs);
352     protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
353     protocol_start_response(m_sn, m_rq);
354     return (void*)REQ_ABORTED;
355   }
356   virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
357   virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
358
359   pblock* m_pb;
360   Session* m_sn;
361   Request* m_rq;
362   set<string> m_allhttp;
363   bool m_firsttime;
364 };
365
366 /********************************************************************************/
367
368 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
369 {
370     log_error(LOG_FAILURE,func,sn,rq,msg);
371     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
372     return REQ_ABORTED;
373 }
374
375 #undef FUNC
376 #define FUNC "shibboleth"
377 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
378 {
379     ostringstream threadid;
380     threadid << "[" << getpid() << "] nsapi_shib" << '\0';
381     saml::NDC ndc(threadid.str().c_str());
382     
383     try {
384         ShibTargetNSAPI stn(pb, sn, rq);
385     
386         // Check user authentication
387         pair<bool,void*> res = stn.doCheckAuthN();
388         if (res.first) return (int)res.second;
389     
390         // user authN was okay -- export the assertions now
391         param_free(pblock_remove("auth-user",rq->vars));
392         // This seems to be required in order to eventually set
393         // the auth-user var.
394         pblock_nvinsert("auth-type","shibboleth",rq->vars);
395         res = stn.doExportAssertions();
396         if (res.first) return (int)res.second;
397     
398         // Check the Authorization
399         res = stn.doCheckAuthZ();
400         if (res.first) return (int)res.second;
401     
402         // this user is ok.
403         return REQ_PROCEED;
404     }
405     catch (exception& e) {
406         log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
407         return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an exception, see web server log for error.");
408     }
409     catch (...) {
410         if (g_catchAll)
411             return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an uncaught exception.");
412         throw;
413     }
414 }
415
416
417 #undef FUNC
418 #define FUNC "shib_handler"
419 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
420 {
421     ostringstream threadid;
422     threadid << "[" << getpid() << "] shib_handler" << '\0';
423     saml::NDC ndc(threadid.str().c_str());
424     
425     try {
426         ShibTargetNSAPI stn(pb, sn, rq);
427     
428         pair<bool,void*> res = stn.doHandler();
429         if (res.first) return (int)res.second;
430     
431         return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
432     }
433     catch (exception& e) {
434         log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
435         return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
436     }
437     catch (...) {
438         if (g_catchAll)
439             return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
440         throw;
441     }
442 }
443
444
445 class SunRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
446 {
447 public:
448     SunRequestMapper(const DOMElement* e);
449     ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
450     void lock() { m_mapper->lock(); }
451     void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
452     Settings getSettings(ShibTarget* st) const;
453     
454     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
455     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
456     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
457     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
458     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
459     const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
460     const DOMElement* getElement() const;
461
462 private:
463     IRequestMapper* m_mapper;
464     ThreadKey* m_stKey;
465     ThreadKey* m_propsKey;
466 };
467
468 IPlugIn* SunRequestMapFactory(const DOMElement* e)
469 {
470     return new SunRequestMapper(e);
471 }
472
473 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
474 {
475     IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
476     m_mapper=dynamic_cast<IRequestMapper*>(p);
477     if (!m_mapper) {
478         delete p;
479         throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
480     }
481     m_stKey=ThreadKey::create(NULL);
482     m_propsKey=ThreadKey::create(NULL);
483 }
484
485 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
486 {
487     Settings s=m_mapper->getSettings(st);
488     m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
489     m_propsKey->setData((void*)s.first);
490     return pair<const IPropertySet*,IAccessControl*>(this,s.second);
491 }
492
493 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
494 {
495     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
496     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
497     if (stn && !ns && name) {
498         // Override boolean properties.
499         const char* param=pblock_findval(name,stn->m_pb);
500         if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
501             return make_pair(true,true);
502     }
503     return s ? s->getBool(name,ns) : make_pair(false,false);
504 }
505
506 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
507 {
508     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
509     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
510     if (stn && !ns && name) {
511         // Override string properties.
512         if (!strcmp(name,"authType"))
513             return pair<bool,const char*>(true,"shibboleth");
514         else {
515             const char* param=pblock_findval(name,stn->m_pb);
516             if (param)
517                 return make_pair(true,param);
518         }
519     }
520     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
521 }
522
523 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
524 {
525     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
526     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
527 }
528
529 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
530 {
531     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
532     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
533     if (stn && !ns && name) {
534         // Override int properties.
535         const char* param=pblock_findval(name,stn->m_pb);
536         if (param)
537             return pair<bool,unsigned int>(true,strtol(param,NULL,10));
538     }
539     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
540 }
541
542 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
543 {
544     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
545     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
546     if (stn && !ns && name) {
547         // Override int properties.
548         const char* param=pblock_findval(name,stn->m_pb);
549         if (param)
550             return pair<bool,int>(true,atoi(param));
551     }
552     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
553 }
554
555 const IPropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
556 {
557     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
558     return s ? s->getPropertySet(name,ns) : NULL;
559 }
560
561 const DOMElement* SunRequestMapper::getElement() const
562 {
563     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
564     return s ? s->getElement() : NULL;
565 }