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