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