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