55a53dafdfc88619b348658455ab66412e85e20e
[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 #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   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) {
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       return m_certs;
348   }
349
350   pblock* m_pb;
351   ::Session* m_sn;
352   Request* m_rq;
353 };
354
355 /********************************************************************************/
356
357 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
358 {
359     log_error(LOG_FAILURE,func,sn,rq,msg);
360     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
361     return REQ_ABORTED;
362 }
363
364 #undef FUNC
365 #define FUNC "shibboleth"
366 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
367 {
368   ostringstream threadid;
369   threadid << "[" << getpid() << "] nsapi_shib" << '\0';
370   xmltooling::NDC ndc(threadid.str().c_str());
371
372   try {
373     ShibTargetNSAPI stn(pb, sn, rq);
374
375     // Check user authentication
376     pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
377     if (res.first) return (int)res.second;
378
379     // user authN was okay -- export the assertions now
380     param_free(pblock_remove("auth-user",rq->vars));
381     // This seems to be required in order to eventually set
382     // the auth-user var.
383     pblock_nvinsert("auth-type","shibboleth",rq->vars);
384     res = stn.getServiceProvider().doExport(stn);
385     if (res.first) return (int)res.second;
386
387     // Check the Authorization
388     res = stn.getServiceProvider().doAuthorization(stn);
389     if (res.first) return (int)res.second;
390
391     // this user is ok.
392     return REQ_PROCEED;
393   }
394   catch (exception& e) {
395     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
396     return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
397   }
398 #ifndef _DEBUG
399   catch (...) {
400     return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an uncaught exception.");
401   }
402 #endif
403 }
404
405
406 #undef FUNC
407 #define FUNC "shib_handler"
408 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
409 {
410   ostringstream threadid;
411   threadid << "[" << getpid() << "] shib_handler" << '\0';
412   xmltooling::NDC ndc(threadid.str().c_str());
413
414   try {
415     ShibTargetNSAPI stn(pb, sn, rq);
416
417     pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
418     if (res.first) return (int)res.second;
419
420     return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
421   }
422   catch (exception& e) {
423     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
424     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
425   }
426 #ifndef _DEBUG
427   catch (...) {
428     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
429   }
430 #endif
431 }
432
433
434 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
435 {
436 public:
437     SunRequestMapper(const xercesc::DOMElement* e);
438     ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
439     Lockable* lock() { return m_mapper->lock(); }
440     void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
441     Settings getSettings(const SPRequest& request) const;
442     
443     void setParent(const PropertySet*) {}
444     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
445     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
446     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
447     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
448     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
449     const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const;
450     const xercesc::DOMElement* getElement() const;
451
452 private:
453     RequestMapper* m_mapper;
454     ThreadKey* m_stKey;
455     ThreadKey* m_propsKey;
456 };
457
458 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
459 {
460     return new SunRequestMapper(e);
461 }
462
463 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
464 {
465     m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
466     m_stKey=ThreadKey::create(NULL);
467     m_propsKey=ThreadKey::create(NULL);
468 }
469
470 RequestMapper::Settings SunRequestMapper::getSettings(const SPRequest& request) const
471 {
472     Settings s=m_mapper->getSettings(request);
473     m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
474     m_propsKey->setData((void*)s.first);
475     return pair<const PropertySet*,AccessControl*>(this,s.second);
476 }
477
478 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
479 {
480     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
481     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
482     if (stn && !ns && name) {
483         // Override boolean properties.
484         const char* param=pblock_findval(name,stn->m_pb);
485         if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
486             return make_pair(true,true);
487     }
488     return s ? s->getBool(name,ns) : make_pair(false,false);
489 }
490
491 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
492 {
493     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
494     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
495     if (stn && !ns && name) {
496         // Override string properties.
497         if (!strcmp(name,"authType"))
498             return pair<bool,const char*>(true,"shibboleth");
499         else {
500             const char* param=pblock_findval(name,stn->m_pb);
501             if (param)
502                 return make_pair(true,param);
503         }
504     }
505     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
506 }
507
508 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
509 {
510     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
511     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
512 }
513
514 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(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 int properties.
520         const char* param=pblock_findval(name,stn->m_pb);
521         if (param)
522             return pair<bool,unsigned int>(true,strtol(param,NULL,10));
523     }
524     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
525 }
526
527 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
528 {
529     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
530     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
531     if (stn && !ns && name) {
532         // Override int properties.
533         const char* param=pblock_findval(name,stn->m_pb);
534         if (param)
535             return pair<bool,int>(true,atoi(param));
536     }
537     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
538 }
539
540 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
541 {
542     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
543     return s ? s->getPropertySet(name,ns) : NULL;
544 }
545
546 const xercesc::DOMElement* SunRequestMapper::getElement() const
547 {
548     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
549     return s ? s->getElement() : NULL;
550 }