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