2fd66d94387c3bb704f67fd21271f70c3893e44d
[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 = true;
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) {
177     m_pb = pb;
178     m_sn = sn;
179     m_rq = rq;
180
181     // Get everything but hostname...
182     const char* uri=pblock_findval("uri", rq->reqpb);
183     const char* qstr=pblock_findval("query", rq->reqpb);
184     int port=server_portnum;
185     const char* scheme=security_active ? "https" : "http";
186     const char* host=NULL;
187
188     string url;
189     if (uri)
190         url=uri;
191     if (qstr)
192         url=url + '?' + qstr;
193     
194 #ifdef vs_is_default_vs
195     // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
196     if (!vs_is_default_vs(request_get_vs(m_rq)))
197         // The beauty here is, a non-default vhost can *only* be accessed if the client
198         // specified the exact name in the Host header. So we can trust the Host header.
199         host=pblock_findval("host", rq->headers);
200     else
201 #endif
202     // In other cases, we're going to rely on the initialization process...
203     host=g_ServerName.c_str();
204
205     char* content_type = "";
206     request_header("content-type", &content_type, sn, rq);
207       
208     const char *remote_ip = pblock_findval("ip", sn->client);
209     const char *method = pblock_findval("method", rq->reqpb);
210
211     init(scheme, host, port, url.c_str(), content_type, remote_ip, method);
212   }
213   ~ShibTargetNSAPI() {
214   }
215
216   virtual void log(ShibLogLevel level, const string &msg) {
217     ShibTarget::log(level,msg);
218     if (level==LogLevelError)
219         log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
220   }
221   virtual string getCookies(void) const {
222     char *cookies = NULL;
223     if (request_header("cookie", &cookies, m_sn, m_rq) == REQ_ABORTED)
224       throw("error accessing cookie header");
225     return string(cookies ? cookies : "");
226   }
227   virtual void setCookie(const string &name, const string &value) {
228     string cookie = name + '=' + value;
229     pblock_nvinsert("Set-Cookie", cookie.c_str(), m_rq->srvhdrs);
230   }
231   virtual string getArgs(void) { 
232     const char *q = pblock_findval("query", m_rq->reqpb);
233     return string(q ? q : "");
234   }
235   virtual string getPostData(void) {
236     char* content_length=NULL;
237     if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
238          atoi(content_length) > 1024*1024) // 1MB?
239       throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
240     else {
241       char ch=IO_EOF+1;
242       int cl=atoi(content_length);
243       string cgistr;
244       while (cl && ch != IO_EOF) {
245         ch=netbuf_getc(m_sn->inbuf);
246       
247         // Check for error.
248         if(ch==IO_ERROR)
249           break;
250         cgistr += ch;
251         cl--;
252       }
253       if (cl)
254         throw FatalProfileException("Error reading profile submission from browser.");
255       return cgistr;
256     }
257   }
258   virtual void clearHeader(const string &name) {
259     if (g_checkSpoofing && m_allhttp.empty()) {
260       // Populate the set of client-supplied headers for spoof checking.
261       const pb_entry* entry;
262       for (int i=0; i<m_rq->headers->hsize; ++i) {
263           entry = m_rq->headers->ht[i];
264           while (entry) {
265               string cgiversion("HTTP_");
266               const char* pch = entry->param->name;
267               while (*pch) {
268                   cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
269                   pch++;
270               }
271               m_allhttp.insert(cgiversion);
272               entry = entry->next;
273           }
274       }
275     }
276     if (name=="REMOTE_USER") {
277         if (g_checkSpoofing && m_allhttp.count("HTTP_REMOTE_USER") > 0)
278             throw SAMLException("Attempt to spoof header ($1) was detected.", params(1, name.c_str()));
279         param_free(pblock_remove("auth-user",m_rq->vars));
280         param_free(pblock_remove("remote-user",m_rq->headers));
281     }
282     else {
283         if (g_checkSpoofing) {
284             // Map to the expected CGI variable name.
285             string transformed("HTTP_");
286             const char* pch = name.c_str();
287             while (*pch) {
288                 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
289                 pch++;
290             }
291             if (m_allhttp.count(transformed) > 0)
292                 throw SAMLException("Attempt to spoof header ($1) was detected.", params(1, name.c_str()));
293         }
294         param_free(pblock_remove(name.c_str(), m_rq->headers));
295         pblock_nvinsert(name.c_str(), g_unsetHeaderValue.c_str(), m_rq->headers);
296     }
297   }
298   virtual void setHeader(const string &name, const string &value) {
299     param_free(pblock_remove(name.c_str(), m_rq->headers));
300     pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
301   }
302   virtual string getHeader(const string &name) {
303     char *hdr = NULL;
304     if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED) {
305       string n;
306       const char* pch = name.c_str();
307       while (*pch)
308           n += tolower(*(pch++));
309       if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
310           return "";
311     }
312     return string(hdr ? hdr : "");
313   }
314   virtual void setRemoteUser(const string &user) {
315     pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
316     pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
317   }
318   virtual string getRemoteUser(void) {
319     const char* ru = pblock_findval("auth-user", m_rq->vars);
320     return ru ? ru : "";
321   }
322
323   virtual void* sendPage(
324     const string& msg,
325     int code=200,
326     const string& content_type="text/html",
327     const saml::Iterator<header_t>& headers=EMPTY(header_t)
328     ) {
329     param_free(pblock_remove("content-type", m_rq->srvhdrs));
330     pblock_nvinsert("content-type", content_type.c_str(), m_rq->srvhdrs);
331     pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
332     pblock_nvinsert("connection","close",m_rq->srvhdrs);
333     while (headers.hasNext()) {
334         const header_t& h=headers.next();
335         pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
336     }
337     protocol_status(m_sn, m_rq, code, NULL);
338     protocol_start_response(m_sn, m_rq);
339     net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
340     return (void*)REQ_EXIT;
341   }
342   virtual void* sendRedirect(const string& url) {
343     param_free(pblock_remove("content-type", m_rq->srvhdrs));
344     pblock_nninsert("content-length", 0, m_rq->srvhdrs);
345     pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
346     pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
347     pblock_nvinsert("location", url.c_str(), m_rq->srvhdrs);
348     pblock_nvinsert("connection","close",m_rq->srvhdrs);
349     protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
350     protocol_start_response(m_sn, m_rq);
351     return (void*)REQ_ABORTED;
352   }
353   virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
354   virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
355
356   pblock* m_pb;
357   Session* m_sn;
358   Request* m_rq;
359   set<string> m_allhttp;
360 };
361
362 /********************************************************************************/
363
364 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
365 {
366     log_error(LOG_FAILURE,func,sn,rq,msg);
367     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
368     return REQ_ABORTED;
369 }
370
371 #undef FUNC
372 #define FUNC "shibboleth"
373 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
374 {
375     ostringstream threadid;
376     threadid << "[" << getpid() << "] nsapi_shib" << '\0';
377     saml::NDC ndc(threadid.str().c_str());
378     
379     try {
380         ShibTargetNSAPI stn(pb, sn, rq);
381     
382         // Check user authentication
383         pair<bool,void*> res = stn.doCheckAuthN();
384         if (res.first) return (int)res.second;
385     
386         // user authN was okay -- export the assertions now
387         param_free(pblock_remove("auth-user",rq->vars));
388         // This seems to be required in order to eventually set
389         // the auth-user var.
390         pblock_nvinsert("auth-type","shibboleth",rq->vars);
391         res = stn.doExportAssertions();
392         if (res.first) return (int)res.second;
393     
394         // Check the Authorization
395         res = stn.doCheckAuthZ();
396         if (res.first) return (int)res.second;
397     
398         // this user is ok.
399         return REQ_PROCEED;
400     }
401     catch (exception& e) {
402         log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
403         return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an exception, see web server log for error.");
404     }
405     catch (...) {
406         if (g_catchAll)
407             return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an uncaught exception.");
408         throw;
409     }
410 }
411
412
413 #undef FUNC
414 #define FUNC "shib_handler"
415 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
416 {
417     ostringstream threadid;
418     threadid << "[" << getpid() << "] shib_handler" << '\0';
419     saml::NDC ndc(threadid.str().c_str());
420     
421     try {
422         ShibTargetNSAPI stn(pb, sn, rq);
423     
424         pair<bool,void*> res = stn.doHandler();
425         if (res.first) return (int)res.second;
426     
427         return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
428     }
429     catch (exception& e) {
430         log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
431         return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
432     }
433     catch (...) {
434         if (g_catchAll)
435             return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
436         throw;
437     }
438 }
439
440
441 class SunRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
442 {
443 public:
444     SunRequestMapper(const DOMElement* e);
445     ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
446     void lock() { m_mapper->lock(); }
447     void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
448     Settings getSettings(ShibTarget* st) const;
449     
450     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
451     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
452     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
453     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
454     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
455     const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
456     const DOMElement* getElement() const;
457
458 private:
459     IRequestMapper* m_mapper;
460     ThreadKey* m_stKey;
461     ThreadKey* m_propsKey;
462 };
463
464 IPlugIn* SunRequestMapFactory(const DOMElement* e)
465 {
466     return new SunRequestMapper(e);
467 }
468
469 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
470 {
471     IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
472     m_mapper=dynamic_cast<IRequestMapper*>(p);
473     if (!m_mapper) {
474         delete p;
475         throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
476     }
477     m_stKey=ThreadKey::create(NULL);
478     m_propsKey=ThreadKey::create(NULL);
479 }
480
481 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
482 {
483     Settings s=m_mapper->getSettings(st);
484     m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
485     m_propsKey->setData((void*)s.first);
486     return pair<const IPropertySet*,IAccessControl*>(this,s.second);
487 }
488
489 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
490 {
491     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
492     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
493     if (stn && !ns && name) {
494         // Override boolean properties.
495         const char* param=pblock_findval(name,stn->m_pb);
496         if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
497             return make_pair(true,true);
498     }
499     return s ? s->getBool(name,ns) : make_pair(false,false);
500 }
501
502 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
503 {
504     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
505     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
506     if (stn && !ns && name) {
507         // Override string properties.
508         if (!strcmp(name,"authType"))
509             return pair<bool,const char*>(true,"shibboleth");
510         else {
511             const char* param=pblock_findval(name,stn->m_pb);
512             if (param)
513                 return make_pair(true,param);
514         }
515     }
516     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
517 }
518
519 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
520 {
521     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
522     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
523 }
524
525 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
526 {
527     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
528     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
529     if (stn && !ns && name) {
530         // Override int properties.
531         const char* param=pblock_findval(name,stn->m_pb);
532         if (param)
533             return pair<bool,unsigned int>(true,strtol(param,NULL,10));
534     }
535     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
536 }
537
538 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
539 {
540     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
541     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(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,int>(true,atoi(param));
547     }
548     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
549 }
550
551 const IPropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
552 {
553     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
554     return s ? s->getPropertySet(name,ns) : NULL;
555 }
556
557 const DOMElement* SunRequestMapper::getElement() const
558 {
559     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
560     return s ? s->getElement() : NULL;
561 }