Old config class ported, all config files now loading with new parser.
[shibboleth/cpp-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 /* nsapi_shib.cpp - Shibboleth NSAPI filter
18
19    Scott Cantor
20    12/13/04
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/SPConfig.h>
35 #include <xmltooling/util/Threads.h>
36
37 // SAML Runtime
38 #include <saml/saml.h>
39 #include <shib/shib.h>
40 #include <shib-target/shib-target.h>
41
42 #include <ctime>
43 #include <fstream>
44 #include <sstream>
45 #include <stdexcept>
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 saml;
65 using namespace xmltooling;
66 using namespace std;
67
68 // macros to output text to client
69 #define NET_WRITE(str) \
70     if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
71
72 namespace {
73     ShibTargetConfig* g_Config=NULL;
74     string g_ServerName;
75     string g_ServerScheme;
76 }
77
78 PlugManager::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::RequestMapper |
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         SAMLConfig::getConfig().getPlugMgr().regFactory(NATIVE_REQUESTMAP_PROVIDER,&SunRequestMapFactory);
145         // We hijack the legacy type so that 1.2 config files will load this plugin
146         SAMLConfig::getConfig().getPlugMgr().regFactory(LEGACY_REQUESTMAP_PROVIDER,&SunRequestMapFactory);
147
148         if (!g_Config->load(config)) {
149             g_Config=NULL;
150             pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
151             return REQ_ABORTED;
152         }
153
154         daemon_atrestart(nsapi_shib_exit,NULL);
155 #ifndef _DEBUG
156     }
157     catch (...) {
158         g_Config=NULL;
159         pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
160         return REQ_ABORTED;
161     }
162 #endif
163     return REQ_PROCEED;
164 }
165
166 /********************************************************************************/
167 // NSAPI Shib Target Subclass
168
169 class ShibTargetNSAPI : public ShibTarget
170 {
171     mutable string m_body;
172     mutable bool m_gotBody;
173 public:
174   ShibTargetNSAPI(pblock* pb, Session* sn, Request* rq) : m_gotBody(false) {
175     m_pb = pb;
176     m_sn = sn;
177     m_rq = rq;
178
179     // Get everything but hostname...
180     const char* uri=pblock_findval("uri", rq->reqpb);
181     const char* qstr=pblock_findval("query", rq->reqpb);
182     int port=server_portnum;
183     const char* scheme=security_active ? "https" : "http";
184     const char* host=NULL;
185
186     string url;
187     if (uri)
188         url=uri;
189     if (qstr)
190         url=url + '?' + qstr;
191     
192 #ifdef vs_is_default_vs
193     // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
194     if (!vs_is_default_vs)
195         // The beauty here is, a non-default vhost can *only* be accessed if the client
196         // specified the exact name in the Host header. So we can trust the Host header.
197         host=pblock_findval("host", rq->headers);
198     else
199 #endif
200     // In other cases, we're going to rely on the initialization process...
201     host=g_ServerName.c_str();
202
203     char* content_type = "";
204     request_header("content-type", &content_type, sn, rq);
205       
206     const char *remote_ip = pblock_findval("ip", sn->client);
207     const char *method = pblock_findval("method", rq->reqpb);
208
209     init(scheme, host, port, url.c_str(), content_type, remote_ip, method);
210   }
211   ~ShibTargetNSAPI() {}
212
213   virtual void log(ShibLogLevel level, const string &msg) {
214     ShibTarget::log(level,msg);
215     if (level==LogLevelError)
216         log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
217   }
218   virtual string getCookies(void) const {
219     char *cookies = NULL;
220     if (request_header("cookie", &cookies, m_sn, m_rq) == REQ_ABORTED)
221       throw("error accessing cookie header");
222     return string(cookies ? cookies : "");
223   }
224   virtual void setCookie(const string &name, const string &value) {
225     string cookie = name + '=' + value;
226     pblock_nvinsert("Set-Cookie", cookie.c_str(), m_rq->srvhdrs);
227   }
228   virtual const char* getQueryString() const { 
229     return pblock_findval("query", m_rq->reqpb);
230   }
231   virtual const char* getRequestBody() const {
232     if (m_gotBody)
233         return m_body.c_str();
234     char* content_length=NULL;
235     if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
236          atoi(content_length) > 1024*1024) // 1MB?
237       throw SAMLException("Blocked POST request body exceeding size limit.");
238     else {
239       char ch=IO_EOF+1;
240       int cl=atoi(content_length);
241       m_gotBody=true;
242       while (cl && ch != IO_EOF) {
243         ch=netbuf_getc(m_sn->inbuf);
244         // Check for error.
245         if(ch==IO_ERROR)
246           break;
247         m_body += ch;
248         cl--;
249       }
250       if (cl)
251         throw SAMLException("Error reading POST request body from browser.");
252       return m_body.c_str();
253     }
254   }
255   virtual void clearHeader(const string &name) {
256     if (name=="REMOTE_USER") {
257         param_free(pblock_remove("auth-user",m_rq->vars));
258         param_free(pblock_remove("remote-user",m_rq->headers));
259     }
260     else
261         param_free(pblock_remove(name.c_str(), m_rq->headers));
262   }
263   virtual void setHeader(const string &name, const string &value) {
264     pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
265   }
266   virtual string getHeader(const string &name) {
267     char *hdr = NULL;
268     if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
269       hdr = NULL;
270     return string(hdr ? hdr : "");
271   }
272   virtual void setRemoteUser(const string &user) {
273     pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
274     pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
275   }
276   virtual string getRemoteUser(void) {
277     return getHeader("remote-user");
278   }
279
280   virtual void* sendPage(
281     const string& msg,
282     int code=200,
283     const string& content_type="text/html",
284     const saml::Iterator<header_t>& headers=EMPTY(header_t)
285     ) {
286     param_free(pblock_remove("content-type", m_rq->srvhdrs));
287     pblock_nvinsert("content-type", content_type.c_str(), m_rq->srvhdrs);
288     pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
289     pblock_nvinsert("connection","close",m_rq->srvhdrs);
290     while (headers.hasNext()) {
291         const header_t& h=headers.next();
292         pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
293     }
294     protocol_status(m_sn, m_rq, code, NULL);
295     protocol_start_response(m_sn, m_rq);
296     net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
297     return (void*)REQ_EXIT;
298   }
299   virtual void* sendRedirect(const string& url) {
300     param_free(pblock_remove("content-type", m_rq->srvhdrs));
301     pblock_nninsert("content-length", 0, m_rq->srvhdrs);
302     pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
303     pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
304     pblock_nvinsert("location", url.c_str(), m_rq->srvhdrs);
305     pblock_nvinsert("connection","close",m_rq->srvhdrs);
306     protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
307     protocol_start_response(m_sn, m_rq);
308     return (void*)REQ_ABORTED;
309   }
310   virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
311   virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
312
313   pblock* m_pb;
314   Session* m_sn;
315   Request* m_rq;
316 };
317
318 /********************************************************************************/
319
320 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
321 {
322     log_error(LOG_FAILURE,func,sn,rq,msg);
323     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
324     return REQ_ABORTED;
325 }
326
327 #undef FUNC
328 #define FUNC "shibboleth"
329 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
330 {
331   ostringstream threadid;
332   threadid << "[" << getpid() << "] nsapi_shib" << '\0';
333   saml::NDC ndc(threadid.str().c_str());
334
335   try {
336     ShibTargetNSAPI stn(pb, sn, rq);
337
338     // Check user authentication
339     pair<bool,void*> res = stn.doCheckAuthN();
340     if (res.first) return (int)res.second;
341
342     // user authN was okay -- export the assertions now
343     param_free(pblock_remove("auth-user",rq->vars));
344     // This seems to be required in order to eventually set
345     // the auth-user var.
346     pblock_nvinsert("auth-type","shibboleth",rq->vars);
347     res = stn.doExportAssertions();
348     if (res.first) return (int)res.second;
349
350     // Check the Authorization
351     res = stn.doCheckAuthZ();
352     if (res.first) return (int)res.second;
353
354     // this user is ok.
355     return REQ_PROCEED;
356   }
357   catch (SAMLException& e) {
358     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
359     return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an exception, see web server log for error.");
360   }
361 #ifndef _DEBUG
362   catch (...) {
363     return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an uncaught exception.");
364   }
365 #endif
366 }
367
368
369 #undef FUNC
370 #define FUNC "shib_handler"
371 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
372 {
373   ostringstream threadid;
374   threadid << "[" << getpid() << "] shib_handler" << '\0';
375   saml::NDC ndc(threadid.str().c_str());
376
377   try {
378     ShibTargetNSAPI stn(pb, sn, rq);
379
380     pair<bool,void*> res = stn.doHandler();
381     if (res.first) return (int)res.second;
382
383     return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
384   }
385   catch (SAMLException& e) {
386     log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
387     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
388   }
389 #ifndef _DEBUG
390   catch (...) {
391     return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
392   }
393 #endif
394 }
395
396
397 class SunRequestMapper : public virtual IRequestMapper, public virtual PropertySet
398 {
399 public:
400     SunRequestMapper(const DOMElement* e);
401     ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
402     Lockable* lock() { return m_mapper->lock(); }
403     void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
404     Settings getSettings(ShibTarget* st) const;
405     
406     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
407     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
408     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
409     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
410     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
411     const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
412     const DOMElement* getElement() const;
413
414 private:
415     IRequestMapper* m_mapper;
416     ThreadKey* m_stKey;
417     ThreadKey* m_propsKey;
418 };
419
420 IPlugIn* SunRequestMapFactory(const DOMElement* e)
421 {
422     return new SunRequestMapper(e);
423 }
424
425 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
426 {
427     IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(XML_REQUESTMAP_PROVIDER,e);
428     m_mapper=dynamic_cast<IRequestMapper*>(p);
429     if (!m_mapper) {
430         delete p;
431         throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
432     }
433     m_stKey=ThreadKey::create(NULL);
434     m_propsKey=ThreadKey::create(NULL);
435 }
436
437 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
438 {
439     Settings s=m_mapper->getSettings(st);
440     m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
441     m_propsKey->setData((void*)s.first);
442     return pair<const PropertySet*,IAccessControl*>(this,s.second);
443 }
444
445 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
446 {
447     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
448     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
449     if (stn && !ns && name) {
450         // Override boolean properties.
451         const char* param=pblock_findval(name,stn->m_pb);
452         if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
453             return make_pair(true,true);
454     }
455     return s ? s->getBool(name,ns) : make_pair(false,false);
456 }
457
458 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
459 {
460     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
461     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
462     if (stn && !ns && name) {
463         // Override string properties.
464         if (!strcmp(name,"authType"))
465             return pair<bool,const char*>(true,"shibboleth");
466         else {
467             const char* param=pblock_findval(name,stn->m_pb);
468             if (param)
469                 return make_pair(true,param);
470         }
471     }
472     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
473 }
474
475 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
476 {
477     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
478     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
479 }
480
481 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
482 {
483     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
484     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
485     if (stn && !ns && name) {
486         // Override int properties.
487         const char* param=pblock_findval(name,stn->m_pb);
488         if (param)
489             return pair<bool,unsigned int>(true,strtol(param,NULL,10));
490     }
491     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
492 }
493
494 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
495 {
496     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
497     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
498     if (stn && !ns && name) {
499         // Override int properties.
500         const char* param=pblock_findval(name,stn->m_pb);
501         if (param)
502             return pair<bool,int>(true,atoi(param));
503     }
504     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
505 }
506
507 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
508 {
509     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
510     return s ? s->getPropertySet(name,ns) : NULL;
511 }
512
513 const DOMElement* SunRequestMapper::getElement() const
514 {
515     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
516     return s ? s->getElement() : NULL;
517 }