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