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