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