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