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