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