d9f49002e5b2118bc19e8565c967d3ef62b0811a
[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 || rq->orig_rq)
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 (g_checkSpoofing && m_firsttime && !m_rq->orig_rq && 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 (g_checkSpoofing && m_firsttime && !m_rq->orig_rq && 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         pblock_nvinsert("remote-user", g_unsetHeaderValue.c_str(), m_rq->headers);
285     }
286     else {
287         if (g_checkSpoofing && m_firsttime && !m_rq->orig_rq) {
288             // Map to the expected CGI variable name.
289             string transformed("HTTP_");
290             const char* pch = name.c_str();
291             while (*pch) {
292                 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
293                 pch++;
294             }
295             if (m_allhttp.count(transformed) > 0)
296                 throw SAMLException("Attempt to spoof header ($1) was detected.", params(1, name.c_str()));
297         }
298         param_free(pblock_remove(name.c_str(), m_rq->headers));
299         pblock_nvinsert(name.c_str(), g_unsetHeaderValue.c_str(), m_rq->headers);
300     }
301   }
302   virtual void setHeader(const string &name, const string &value) {
303     param_free(pblock_remove(name.c_str(), m_rq->headers));
304     pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
305   }
306   virtual string getHeader(const string &name) {
307     char *hdr = NULL;
308     if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED) {
309       string n;
310       const char* pch = name.c_str();
311       while (*pch)
312           n += tolower(*(pch++));
313       if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
314           return "";
315     }
316     return string(hdr ? hdr : "");
317   }
318   virtual void setRemoteUser(const string &user) {
319     param_free(pblock_remove("remote-user",m_rq->headers));
320     pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
321     pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
322   }
323   virtual string getRemoteUser(void) {
324     const char* ru = pblock_findval("auth-user", m_rq->vars);
325     return ru ? ru : "";
326   }
327
328   virtual void* sendPage(
329     const string& msg,
330     int code=200,
331     const string& content_type="text/html",
332     const saml::Iterator<header_t>& headers=EMPTY(header_t)
333     ) {
334     param_free(pblock_remove("content-type", m_rq->srvhdrs));
335     pblock_nvinsert("content-type", content_type.c_str(), m_rq->srvhdrs);
336     pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
337     pblock_nvinsert("connection","close",m_rq->srvhdrs);
338     while (headers.hasNext()) {
339         const header_t& h=headers.next();
340         pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
341     }
342     protocol_status(m_sn, m_rq, code, NULL);
343     protocol_start_response(m_sn, m_rq);
344     net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
345     return (void*)REQ_EXIT;
346   }
347   virtual void* sendRedirect(const string& url) {
348     param_free(pblock_remove("content-type", m_rq->srvhdrs));
349     pblock_nninsert("content-length", 0, m_rq->srvhdrs);
350     pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
351     pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
352     pblock_nvinsert("location", url.c_str(), m_rq->srvhdrs);
353     pblock_nvinsert("connection","close",m_rq->srvhdrs);
354     protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
355     protocol_start_response(m_sn, m_rq);
356     return (void*)REQ_ABORTED;
357   }
358   virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
359   virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
360
361   pblock* m_pb;
362   Session* m_sn;
363   Request* m_rq;
364   set<string> m_allhttp;
365   bool m_firsttime;
366 };
367
368 /********************************************************************************/
369
370 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
371 {
372     log_error(LOG_FAILURE,func,sn,rq,msg);
373     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
374     return REQ_ABORTED;
375 }
376
377 #undef FUNC
378 #define FUNC "shibboleth"
379 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
380 {
381     ostringstream threadid;
382     threadid << "[" << getpid() << "] nsapi_shib" << '\0';
383     saml::NDC ndc(threadid.str().c_str());
384
385     try {
386         ShibTargetNSAPI stn(pb, sn, rq);
387
388         // Check user authentication
389         pair<bool,void*> res = stn.doCheckAuthN();
390         if (res.first) return (int)res.second;
391
392         // user authN was okay -- export the assertions now
393         param_free(pblock_remove("auth-user",rq->vars));
394         // This seems to be required in order to eventually set
395         // the auth-user var.
396         pblock_nvinsert("auth-type","shibboleth",rq->vars);
397         res = stn.doExportAssertions();
398         if (res.first) return (int)res.second;
399
400         // Check the Authorization
401         res = stn.doCheckAuthZ();
402         if (res.first) return (int)res.second;
403
404         // this user is ok.
405         return REQ_PROCEED;
406     }
407     catch (exception& e) {
408         log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
409         return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an exception, see web server log for error.");
410     }
411     catch (...) {
412         if (g_catchAll)
413             return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an uncaught exception.");
414         throw;
415     }
416 }
417
418
419 #undef FUNC
420 #define FUNC "shib_handler"
421 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
422 {
423     ostringstream threadid;
424     threadid << "[" << getpid() << "] shib_handler" << '\0';
425     saml::NDC ndc(threadid.str().c_str());
426
427     try {
428         ShibTargetNSAPI stn(pb, sn, rq);
429
430         pair<bool,void*> res = stn.doHandler();
431         if (res.first) return (int)res.second;
432
433         return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
434     }
435     catch (exception& e) {
436         log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
437         return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
438     }
439     catch (...) {
440         if (g_catchAll)
441             return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
442         throw;
443     }
444 }
445
446
447 class SunRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
448 {
449 public:
450     SunRequestMapper(const DOMElement* e);
451     ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
452     void lock() { m_mapper->lock(); }
453     void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
454     Settings getSettings(ShibTarget* st) const;
455
456     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
457     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
458     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
459     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
460     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
461     const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
462     const DOMElement* getElement() const;
463
464 private:
465     IRequestMapper* m_mapper;
466     ThreadKey* m_stKey;
467     ThreadKey* m_propsKey;
468 };
469
470 IPlugIn* SunRequestMapFactory(const DOMElement* e)
471 {
472     return new SunRequestMapper(e);
473 }
474
475 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
476 {
477     IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
478     m_mapper=dynamic_cast<IRequestMapper*>(p);
479     if (!m_mapper) {
480         delete p;
481         throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
482     }
483     m_stKey=ThreadKey::create(NULL);
484     m_propsKey=ThreadKey::create(NULL);
485 }
486
487 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
488 {
489     Settings s=m_mapper->getSettings(st);
490     m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
491     m_propsKey->setData((void*)s.first);
492     return pair<const IPropertySet*,IAccessControl*>(this,s.second);
493 }
494
495 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
496 {
497     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
498     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
499     if (stn && !ns && name) {
500         // Override boolean properties.
501         const char* param=pblock_findval(name,stn->m_pb);
502         if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
503             return make_pair(true,true);
504     }
505     return s ? s->getBool(name,ns) : make_pair(false,false);
506 }
507
508 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
509 {
510     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
511     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
512     if (stn && !ns && name) {
513         // Override string properties.
514         if (!strcmp(name,"authType"))
515             return pair<bool,const char*>(true,"shibboleth");
516         else {
517             const char* param=pblock_findval(name,stn->m_pb);
518             if (param)
519                 return make_pair(true,param);
520         }
521     }
522     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
523 }
524
525 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
526 {
527     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
528     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
529 }
530
531 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
532 {
533     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
534     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
535     if (stn && !ns && name) {
536         // Override int properties.
537         const char* param=pblock_findval(name,stn->m_pb);
538         if (param)
539             return pair<bool,unsigned int>(true,strtol(param,NULL,10));
540     }
541     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
542 }
543
544 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
545 {
546     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
547     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
548     if (stn && !ns && name) {
549         // Override int properties.
550         const char* param=pblock_findval(name,stn->m_pb);
551         if (param)
552             return pair<bool,int>(true,atoi(param));
553     }
554     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
555 }
556
557 const IPropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
558 {
559     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
560     return s ? s->getPropertySet(name,ns) : NULL;
561 }
562
563 const DOMElement* SunRequestMapper::getElement() const
564 {
565     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
566     return s ? s->getElement() : NULL;
567 }