Copied over mapping and filtering schemas.
[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,string,const xercesc::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::RequestMapping |
133         SPConfig::InProcess |
134         SPConfig::Logging
135         );
136     if (!g_Config->init(schemadir)) {
137         g_Config=NULL;
138         pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
139         return REQ_ABORTED;
140     }
141
142     g_Config->RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
143
144     try {
145         xercesc::DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
146         XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
147         xercesc::DOMElement* dummy = dummydoc->createElementNS(NULL,path);
148         auto_ptr_XMLCh src(config);
149         dummy->setAttributeNS(NULL,path,src.get());
150         dummy->setAttributeNS(NULL,validate,xmlconstants::XML_ONE);
151
152         g_Config->setServiceProvider(g_Config->ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER,dummy));
153         g_Config->getServiceProvider()->init();
154     }
155     catch (exception& ex) {
156         pblock_nvinsert("error",ex.what(),pb);
157         g_Config->term();
158         g_Config=NULL;
159         return REQ_ABORTED;
160     }
161
162     daemon_atrestart(nsapi_shib_exit,NULL);
163
164     ServiceProvider* sp=g_Config->getServiceProvider();
165     Locker locker(sp);
166     const PropertySet* props=sp->getPropertySet("Local");
167     if (props) {
168         pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
169         if (unsetValue.first)
170             g_unsetHeaderValue = unsetValue.second;
171     }
172     return REQ_PROCEED;
173 }
174
175 /********************************************************************************/
176 // NSAPI Shib Target Subclass
177
178 class ShibTargetNSAPI : public AbstractSPRequest
179 {
180   string m_uri;
181   mutable string m_body;
182   mutable bool m_gotBody;
183   vector<XSECCryptoX509*> m_certs;
184
185 public:
186   ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq) : m_gotBody(false) {
187     m_pb = pb;
188     m_sn = sn;
189     m_rq = rq;
190
191     // Get everything but hostname...
192     const char* uri=pblock_findval("uri", rq->reqpb);
193     const char* qstr=pblock_findval("query", rq->reqpb);
194
195     string url;
196     if (uri) {
197         url = uri;
198         m_uri = uri;
199     }
200     if (qstr)
201         url=url + '?' + qstr;
202     
203     const char* host=NULL;
204 #ifdef vs_is_default_vs
205     // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
206     if (!vs_is_default_vs)
207         // The beauty here is, a non-default vhost can *only* be accessed if the client
208         // specified the exact name in the Host header. So we can trust the Host header.
209         host=pblock_findval("host", rq->headers);
210     else
211 #endif
212     // In other cases, we're going to rely on the initialization process...
213     host=g_ServerName.c_str();
214   }
215   ~ShibTargetNSAPI() {}
216
217   const char* getScheme() const {
218     return security_active ? "https" : "http";
219   }
220   const char* getHostname() const {
221 #ifdef vs_is_default_vs
222     // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
223     if (!vs_is_default_vs)
224         // The beauty here is, a non-default vhost can *only* be accessed if the client
225         // specified the exact name in the Host header. So we can trust the Host header.
226         return pblock_findval("host", m_rq->headers);
227     else
228 #endif
229     // In other cases, we're going to rely on the initialization process...
230     return g_ServerName.c_str();
231   }
232   int getPort() const {
233     return server_portnum;
234   }
235   const char* getRequestURI() const {
236     return m_uri.c_str();
237   }
238   const char* getMethod() const {
239     return pblock_findval("method", m_rq->reqpb);
240   }
241   string getContentType() const {
242     char* content_type = "";
243     request_header("content-type", &content_type, m_sn, m_rq);
244     return content_type;
245   }
246   long getContentLength() const {
247     if (m_gotBody)
248         return m_body.length();
249     char* content_length="";
250     request_header("content-length", &content_length, m_sn, m_rq);
251     return atoi(content_length);
252   }
253   string getRemoteAddr() const {
254     return pblock_findval("ip", m_sn->client);
255   }
256   void log(SPLogLevel level, const string& msg) {
257     AbstractSPRequest::log(level,msg);
258     if (level>=SPError)
259         log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
260   }
261   const char* getQueryString() const { 
262     return pblock_findval("query", m_rq->reqpb);
263   }
264   const char* getRequestBody() const {
265     if (m_gotBody)
266         return m_body.c_str();
267     char* content_length=NULL;
268     if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED || atoi(content_length) > 1024*1024) // 1MB?
269       throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M 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 IOException("Error reading 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 xercesc::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     void setParent(const PropertySet*) {}
442     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
443     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
444     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
445     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
446     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
447     const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
448     const xercesc::DOMElement* getElement() const;
449
450 private:
451     RequestMapper* m_mapper;
452     ThreadKey* m_stKey;
453     ThreadKey* m_propsKey;
454 };
455
456 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
457 {
458     return new SunRequestMapper(e);
459 }
460
461 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
462 {
463     m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
464     m_stKey=ThreadKey::create(NULL);
465     m_propsKey=ThreadKey::create(NULL);
466 }
467
468 RequestMapper::Settings SunRequestMapper::getSettings(const SPRequest& request) const
469 {
470     Settings s=m_mapper->getSettings(request);
471     m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
472     m_propsKey->setData((void*)s.first);
473     return pair<const PropertySet*,AccessControl*>(this,s.second);
474 }
475
476 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
477 {
478     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
479     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
480     if (stn && !ns && name) {
481         // Override boolean properties.
482         const char* param=pblock_findval(name,stn->m_pb);
483         if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
484             return make_pair(true,true);
485     }
486     return s ? s->getBool(name,ns) : make_pair(false,false);
487 }
488
489 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
490 {
491     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
492     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
493     if (stn && !ns && name) {
494         // Override string properties.
495         if (!strcmp(name,"authType"))
496             return pair<bool,const char*>(true,"shibboleth");
497         else {
498             const char* param=pblock_findval(name,stn->m_pb);
499             if (param)
500                 return make_pair(true,param);
501         }
502     }
503     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
504 }
505
506 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
507 {
508     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
509     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
510 }
511
512 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
513 {
514     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
515     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
516     if (stn && !ns && name) {
517         // Override int properties.
518         const char* param=pblock_findval(name,stn->m_pb);
519         if (param)
520             return pair<bool,unsigned int>(true,strtol(param,NULL,10));
521     }
522     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
523 }
524
525 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
526 {
527     const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
528     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
529     if (stn && !ns && name) {
530         // Override int properties.
531         const char* param=pblock_findval(name,stn->m_pb);
532         if (param)
533             return pair<bool,int>(true,atoi(param));
534     }
535     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
536 }
537
538 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
539 {
540     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
541     return s ? s->getPropertySet(name,ns) : NULL;
542 }
543
544 const xercesc::DOMElement* SunRequestMapper::getElement() const
545 {
546     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
547     return s ? s->getElement() : NULL;
548 }