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