1b3891f8ac4fc52233e893fd6391803b06af6cf0
[shibboleth/cpp-sp.git] / nsapi_shib / nsapi_shib.cpp
1 /*
2  *  Copyright 2001-2007 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 /**
18  * nsapi_shib.cpp
19  * 
20  * Shibboleth NSAPI filter
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 #include <shibsp/AbstractSPRequest.h>
35 #include <shibsp/RequestMapper.h>
36 #include <shibsp/SPConfig.h>
37 #include <xmltooling/util/NDC.h>
38 #include <xmltooling/util/Threads.h>
39
40 #include <shib-target/shib-target.h>
41
42 #include <fstream>
43 #include <sstream>
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 shibsp;
61 using namespace xmltooling;
62 using namespace std;
63
64 // macros to output text to client
65 #define NET_WRITE(str) \
66     if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
67
68 namespace {
69     shibtarget::ShibTargetConfig* g_Config=NULL;
70     string g_ServerName;
71     string g_ServerScheme;
72     string g_unsetHeaderValue;
73 }
74
75 PluginManager<RequestMapper,const DOMElement*>::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=&shibtarget::ShibTargetConfig::getConfig();
126         SPConfig::getConfig().setFeatures(
127             SPConfig::Listener |
128             SPConfig::Caching |
129             SPConfig::Metadata |
130             SPConfig::AAP |
131             SPConfig::RequestMapping |
132             SPConfig::InProcess |
133             SPConfig::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         SPConfig::getConfig().RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
142
143         if (!g_Config->load(config)) {
144             g_Config=NULL;
145             pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
146             return REQ_ABORTED;
147         }
148
149         daemon_atrestart(nsapi_shib_exit,NULL);
150
151         ServiceProvider* conf=SPConfig::getConfig().getServiceProvider();
152         Locker locker(conf);
153         const PropertySet* props=conf->getPropertySet("Local");
154         if (props) {
155             pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
156             if (unsetValue.first)
157                 g_unsetHeaderValue = unsetValue.second;
158         }
159 #ifndef _DEBUG
160     }
161     catch (...) {
162         g_Config=NULL;
163         pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
164         return REQ_ABORTED;
165     }
166 #endif
167     return REQ_PROCEED;
168 }
169
170 /********************************************************************************/
171 // NSAPI Shib Target Subclass
172
173 class ShibTargetNSAPI : public AbstractSPRequest
174 {
175   string m_uri;
176   mutable string m_body;
177   mutable bool m_gotBody;
178   vector<XSECCryptoX509*> m_certs;
179
180 public:
181   ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq) : m_gotBody(false) {
182     m_pb = pb;
183     m_sn = sn;
184     m_rq = rq;
185
186     // Get everything but hostname...
187     const char* uri=pblock_findval("uri", rq->reqpb);
188     const char* qstr=pblock_findval("query", rq->reqpb);
189
190     string url;
191     if (uri) {
192         url = uri;
193         m_uri = uri;
194     }
195     if (qstr)
196         url=url + '?' + qstr;
197     
198     const char* host=NULL;
199 #ifdef vs_is_default_vs
200     // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
201     if (!vs_is_default_vs)
202         // The beauty here is, a non-default vhost can *only* be accessed if the client
203         // specified the exact name in the Host header. So we can trust the Host header.
204         host=pblock_findval("host", rq->headers);
205     else
206 #endif
207     // In other cases, we're going to rely on the initialization process...
208     host=g_ServerName.c_str();
209   }
210   ~ShibTargetNSAPI() {}
211
212   const char* getScheme() const {
213     return security_active ? "https" : "http";
214   }
215   const char* getHostname() const {
216 #ifdef vs_is_default_vs
217     // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
218     if (!vs_is_default_vs)
219         // The beauty here is, a non-default vhost can *only* be accessed if the client
220         // specified the exact name in the Host header. So we can trust the Host header.
221         return pblock_findval("host", m_rq->headers);
222     else
223 #endif
224     // In other cases, we're going to rely on the initialization process...
225     return g_ServerName.c_str();
226   }
227   int getPort() const {
228     return server_portnum;
229   }
230   const char* getRequestURI() const {
231     return m_uri.c_str();
232   }
233   const char* getMethod() const {
234     return pblock_findval("method", m_rq->reqpb);
235   }
236   string getContentType() const {
237     char* content_type = "";
238     request_header("content-type", &content_type, m_sn, m_rq);
239     return content_type;
240   }
241   long getContentLength() const {
242     if (m_gotBody)
243         return m_body.length();
244     char* content_length="";
245     request_header("content-length", &content_length, m_sn, m_rq);
246     return atoi(content_length);
247   }
248   string getRemoteAddr() const {
249     return pblock_findval("ip", m_sn->client);
250   }
251   void log(SPLogLevel level, const string& msg) {
252     AbstractSPRequest::log(level,msg);
253     if (level>=SPError)
254         log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
255   }
256   const char* getQueryString() const { 
257     return pblock_findval("query", m_rq->reqpb);
258   }
259   const char* getRequestBody() const {
260     if (m_gotBody)
261         return m_body.c_str();
262     char* content_length=NULL;
263     if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
264          atoi(content_length) > 1024*1024) // 1MB?
265       throw opensaml::BindingException("Blocked POST request body exceeding size limit.");
266     else {
267       char ch=IO_EOF+1;
268       int cl=atoi(content_length);
269       m_gotBody=true;
270       while (cl && ch != IO_EOF) {
271         ch=netbuf_getc(m_sn->inbuf);
272         // Check for error.
273         if(ch==IO_ERROR)
274           break;
275         m_body += ch;
276         cl--;
277       }
278       if (cl)
279         throw opensaml::BindingException("Error reading POST request body from browser.");
280       return m_body.c_str();
281     }
282   }
283   void clearHeader(const char* name) {
284     if (!strcmp(name,"REMOTE_USER")) {
285         param_free(pblock_remove("auth-user",m_rq->vars));
286         param_free(pblock_remove("remote-user",m_rq->headers));
287     }
288     else {
289         param_free(pblock_remove(name, m_rq->headers));
290         pblock_nvinsert(name, g_unsetHeaderValue.c_str() ,m_rq->headers);
291     }
292   }
293   void setHeader(const char* name, const char* value) {
294     pblock_nvinsert(name, value, m_rq->headers);
295   }
296   string getHeader(const char* name) const {
297     char* hdr = NULL;
298     if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED)
299       hdr = NULL;
300     return string(hdr ? hdr : "");
301   }
302   void setRemoteUser(const char* user) {
303     pblock_nvinsert("remote-user", user, m_rq->headers);
304     pblock_nvinsert("auth-user", user, m_rq->vars);
305   }
306   string getRemoteUser() const {
307     return getHeader("remote-user");
308   }
309   void setResponseHeader(const char* name, const char* value) {
310     pblock_nvinsert(name, value, m_rq->srvhdrs);
311   }
312
313   long sendResponse(istream& in, long status) {
314     string msg;
315     char buf[1024];
316     while (in) {
317         in.read(buf,1024);
318         msg.append(buf,in.gcount());
319     }
320     pblock_nvinsert("connection","close",m_rq->srvhdrs);
321     pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
322     protocol_status(m_sn, m_rq, status, NULL);
323     protocol_start_response(m_sn, m_rq);
324     net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
325     return REQ_EXIT;
326   }
327   long sendRedirect(const char* url) {
328     param_free(pblock_remove("content-type", m_rq->srvhdrs));
329     pblock_nninsert("content-length", 0, m_rq->srvhdrs);
330     pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
331     pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
332     pblock_nvinsert("location", url, m_rq->srvhdrs);
333     pblock_nvinsert("connection","close",m_rq->srvhdrs);
334     protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
335     protocol_start_response(m_sn, m_rq);
336     return REQ_ABORTED;
337   }
338   long returnDecline() { return REQ_NOACTION; }
339   long returnOK() { return REQ_PROCEED; }
340   const vector<XSECCryptoX509*>& getClientCertificates() const {
341       return m_certs;
342   }
343
344   pblock* m_pb;
345   ::Session* m_sn;
346   Request* m_rq;
347 };
348
349 /********************************************************************************/
350
351 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
352 {
353     log_error(LOG_FAILURE,func,sn,rq,msg);
354     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
355     return REQ_ABORTED;
356 }
357
358 #undef FUNC
359 #define FUNC "shibboleth"
360 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
361 {
362   ostringstream threadid;
363   threadid << "[" << getpid() << "] nsapi_shib" << '\0';
364   xmltooling::NDC ndc(threadid.str().c_str());
365
366   try {
367     ShibTargetNSAPI stn(pb, sn, rq);
368
369     // Check user authentication
370     pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
371     if (res.first) return (int)res.second;
372
373     // user authN was okay -- export the assertions now
374     param_free(pblock_remove("auth-user",rq->vars));
375     // This seems to be required in order to eventually set
376     // the auth-user var.
377     pblock_nvinsert("auth-type","shibboleth",rq->vars);
378     res = stn.getServiceProvider().doExport(stn);
379     if (res.first) return (int)res.second;
380
381     // Check the Authorization
382     res = stn.getServiceProvider().doAuthorization(stn);
383     if (res.first) return (int)res.second;
384
385     // this user is ok.
386     return REQ_PROCEED;
387   }
388   catch (exception& e) {
389     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
390     return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
391   }
392 #ifndef _DEBUG
393   catch (...) {
394     return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an uncaught exception.");
395   }
396 #endif
397 }
398
399
400 #undef FUNC
401 #define FUNC "shib_handler"
402 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
403 {
404   ostringstream threadid;
405   threadid << "[" << getpid() << "] shib_handler" << '\0';
406   xmltooling::NDC ndc(threadid.str().c_str());
407
408   try {
409     ShibTargetNSAPI stn(pb, sn, rq);
410
411     pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
412     if (res.first) return (int)res.second;
413
414     return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
415   }
416   catch (exception& e) {
417     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
418     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
419   }
420 #ifndef _DEBUG
421   catch (...) {
422     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
423   }
424 #endif
425 }
426
427
428 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
429 {
430 public:
431     SunRequestMapper(const DOMElement* e);
432     ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
433     Lockable* lock() { return m_mapper->lock(); }
434     void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
435     Settings getSettings(const SPRequest& request) const;
436     
437     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
438     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
439     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
440     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
441     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
442     const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
443     const DOMElement* getElement() const;
444
445 private:
446     RequestMapper* m_mapper;
447     ThreadKey* m_stKey;
448     ThreadKey* m_propsKey;
449 };
450
451 RequestMapper* SunRequestMapFactory(const DOMElement* const & e)
452 {
453     return new SunRequestMapper(e);
454 }
455
456 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
457 {
458     m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
459     m_stKey=ThreadKey::create(NULL);
460     m_propsKey=ThreadKey::create(NULL);
461 }
462
463 RequestMapper::Settings SunRequestMapper::getSettings(const SPRequest& request) const
464 {
465     Settings s=m_mapper->getSettings(request);
466     m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
467     m_propsKey->setData((void*)s.first);
468     return pair<const PropertySet*,AccessControl*>(this,s.second);
469 }
470
471 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
472 {
473     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
474     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
475     if (stn && !ns && name) {
476         // Override boolean properties.
477         const char* param=pblock_findval(name,stn->m_pb);
478         if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
479             return make_pair(true,true);
480     }
481     return s ? s->getBool(name,ns) : make_pair(false,false);
482 }
483
484 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
485 {
486     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
487     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
488     if (stn && !ns && name) {
489         // Override string properties.
490         if (!strcmp(name,"authType"))
491             return pair<bool,const char*>(true,"shibboleth");
492         else {
493             const char* param=pblock_findval(name,stn->m_pb);
494             if (param)
495                 return make_pair(true,param);
496         }
497     }
498     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
499 }
500
501 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
502 {
503     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
504     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
505 }
506
507 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
508 {
509     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
510     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
511     if (stn && !ns && name) {
512         // Override int properties.
513         const char* param=pblock_findval(name,stn->m_pb);
514         if (param)
515             return pair<bool,unsigned int>(true,strtol(param,NULL,10));
516     }
517     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
518 }
519
520 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
521 {
522     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
523     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
524     if (stn && !ns && name) {
525         // Override int properties.
526         const char* param=pblock_findval(name,stn->m_pb);
527         if (param)
528             return pair<bool,int>(true,atoi(param));
529     }
530     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
531 }
532
533 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
534 {
535     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
536     return s ? s->getPropertySet(name,ns) : NULL;
537 }
538
539 const DOMElement* SunRequestMapper::getElement() const
540 {
541     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
542     return s ? s->getElement() : NULL;
543 }