2 * Copyright 2001-2009 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * Shibboleth NSAPI filter
25 #if defined (_MSC_VER) || defined(__BORLANDC__)
26 # include "config_win32.h"
32 # define _CRT_NONSTDC_NO_DEPRECATE 1
33 # define _CRT_SECURE_NO_DEPRECATE 1
36 #include <shibsp/AbstractSPRequest.h>
37 #include <shibsp/RequestMapper.h>
38 #include <shibsp/SPConfig.h>
39 #include <shibsp/ServiceProvider.h>
40 #include <xmltooling/XMLToolingConfig.h>
41 #include <xmltooling/util/NDC.h>
42 #include <xmltooling/util/Threads.h>
43 #include <xmltooling/util/XMLConstants.h>
44 #include <xmltooling/util/XMLHelper.h>
45 #include <xercesc/util/XMLUniDefs.hpp>
67 using namespace shibsp;
68 using namespace xmltooling;
71 // macros to output text to client
72 #define NET_WRITE(str) \
73 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
76 SPConfig* g_Config=NULL;
78 string g_unsetHeaderValue;
80 bool g_checkSpoofing = true;
81 bool g_catchAll = false;
83 static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
84 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
87 PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
89 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
96 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
98 // Save off a default hostname for this virtual server.
99 char* name=pblock_findval("server-name",pb);
103 name=server_hostname;
107 name=util_hostname();
113 pblock_nvinsert("error","unable to determine web server hostname",pb);
119 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
121 const char* schemadir=pblock_findval("shib-schemas",pb);
122 const char* prefix=pblock_findval("shib-prefix",pb);
124 g_Config=&SPConfig::getConfig();
125 g_Config->setFeatures(
128 SPConfig::RequestMapping |
129 SPConfig::InProcess |
133 if (!g_Config->init(schemadir,prefix)) {
135 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
139 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&SunRequestMapFactory);
142 if (!g_Config->instantiate(pblock_findval("shib-config",pb), true))
143 throw runtime_error("unknown error");
145 catch (exception& ex) {
146 pblock_nvinsert("error",ex.what(),pb);
152 daemon_atrestart(nsapi_shib_exit,NULL);
154 ServiceProvider* sp=g_Config->getServiceProvider();
156 const PropertySet* props=sp->getPropertySet("InProcess");
158 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
159 if (unsetValue.first)
160 g_unsetHeaderValue = unsetValue.second;
161 pair<bool,bool> flag=props->getBool("checkSpoofing");
162 g_checkSpoofing = !flag.first || flag.second;
163 if (g_checkSpoofing) {
164 unsetValue=props->getString("spoofKey");
165 if (unsetValue.first)
166 g_spoofKey = unsetValue.second;
168 flag=props->getBool("catchAll");
169 g_catchAll = flag.first && flag.second;
174 /********************************************************************************/
175 // NSAPI Shib Target Subclass
177 class ShibTargetNSAPI : public AbstractSPRequest
179 mutable string m_body;
180 mutable bool m_gotBody,m_firsttime;
181 bool m_security_active;
182 int m_server_portnum;
183 mutable vector<string> m_certs;
184 set<string> m_allhttp;
191 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq)
192 : AbstractSPRequest(SHIBSP_LOGCAT".NSAPI"),
193 m_gotBody(false), m_firsttime(true), m_security_active(false), m_server_portnum(0), m_pb(pb), m_sn(sn), m_rq(rq) {
195 // To determine whether SSL is active or not, we're supposed to rely
196 // on the security_active macro. For iPlanet 4.x, this works.
197 // For Sun 7.x, it's useless and appears to be on or off based
198 // on whether ANY SSL support is enabled for a vhost. Sun 6.x is unknown.
199 // As a fix, there's a conf variable called $security that can be mapped
200 // into a function parameter: security_active="$security"
201 // We check for this parameter, and rely on the macro if it isn't set.
202 // This doubles as a scheme virtualizer for load balanced scenarios
203 // since you can set the parameter to 1 or 0 as needed.
204 const char* sa = pblock_findval("security_active", m_pb);
206 m_security_active = (*sa == '1');
207 else if (security_active)
208 m_security_active = true;
210 m_security_active = false;
212 // A similar issue exists for the port. server_portnum is no longer
213 // working on at least Sun 7.x, and returns the first listener's port
214 // rather than whatever port is actually used for the request. Nice job, Sun.
215 sa = pblock_findval("server_portnum", m_pb);
216 m_server_portnum = (sa && *sa) ? atoi(sa) : server_portnum;
218 const char* uri = pblock_findval("uri", rq->reqpb);
219 const char* qstr = pblock_findval("query", rq->reqpb);
222 string temp = string(uri) + '?' + qstr;
223 setRequestURI(temp.c_str());
229 // See if this is the first time we've run.
230 if (!g_spoofKey.empty()) {
231 qstr = pblock_findval("Shib-Spoof-Check", rq->headers);
232 if (qstr && g_spoofKey == qstr)
235 if (!m_firsttime || rq->orig_rq)
236 log(SPDebug, "nsapi_shib function running more than once");
238 ~ShibTargetNSAPI() { }
240 const char* getScheme() const {
241 return m_security_active ? "https" : "http";
243 const char* getHostname() const {
244 #ifdef vs_is_default_vs
245 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
246 if (!vs_is_default_vs(request_get_vs(m_rq)))
247 // The beauty here is, a non-default vhost can *only* be accessed if the client
248 // specified the exact name in the Host header. So we can trust the Host header.
249 return pblock_findval("host", m_rq->headers);
252 // In other cases, we're going to rely on the initialization process...
253 return g_ServerName.c_str();
255 int getPort() const {
256 return m_server_portnum;
258 const char* getMethod() const {
259 return pblock_findval("method", m_rq->reqpb);
261 string getContentType() const {
262 char* content_type = NULL;
263 if (request_header("content-type", &content_type, m_sn, m_rq) != REQ_PROCEED)
265 return content_type ? content_type : "";
267 long getContentLength() const {
269 return m_body.length();
270 char* content_length=NULL;
271 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED)
273 return content_length ? atoi(content_length) : 0;
275 string getRemoteAddr() const {
276 string ret = AbstractSPRequest::getRemoteAddr();
277 return ret.empty() ? pblock_findval("ip", m_sn->client) : ret;
279 void log(SPLogLevel level, const string& msg) const {
280 AbstractSPRequest::log(level,msg);
282 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
284 const char* getQueryString() const {
285 return pblock_findval("query", m_rq->reqpb);
287 const char* getRequestBody() const {
289 return m_body.c_str();
290 char* content_length=NULL;
291 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED || !content_length) {
295 else if (atoi(content_length) > 1024*1024) // 1MB?
296 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
299 int cl=atoi(content_length);
301 while (cl && ch != IO_EOF) {
302 ch=netbuf_getc(m_sn->inbuf);
310 throw IOException("Error reading request body from browser.");
311 return m_body.c_str();
314 void clearHeader(const char* rawname, const char* cginame) {
315 if (g_checkSpoofing && m_firsttime && !m_rq->orig_rq) {
316 if (m_allhttp.empty()) {
317 // Populate the set of client-supplied headers for spoof checking.
318 const pb_entry* entry;
319 for (int i=0; i<m_rq->headers->hsize; ++i) {
320 entry = m_rq->headers->ht[i];
322 string cgiversion("HTTP_");
323 const char* pch = entry->param->name;
325 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
328 m_allhttp.insert(cgiversion);
333 if (m_allhttp.count(cginame) > 0)
334 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
336 if (strcmp(rawname, "REMOTE_USER") == 0) {
337 param_free(pblock_remove("remote-user", m_rq->headers));
338 pblock_nvinsert("remote-user", g_unsetHeaderValue.c_str(), m_rq->headers);
341 param_free(pblock_remove(rawname, m_rq->headers));
342 pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
345 void setHeader(const char* name, const char* value) {
346 param_free(pblock_remove(name, m_rq->headers));
347 pblock_nvinsert(name, value, m_rq->headers);
349 string getHeader(const char* name) const {
350 // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
352 int cookie = strcmp(name, "Cookie");
355 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
356 // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
361 n += tolower(*(name++));
362 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
365 return string(hdr ? hdr : "");
367 void setRemoteUser(const char* user) {
368 pblock_nvinsert("auth-user", user, m_rq->vars);
369 param_free(pblock_remove("remote-user", m_rq->headers));
370 pblock_nvinsert("remote-user", user, m_rq->headers);
372 string getRemoteUser() const {
373 const char* ru = pblock_findval("auth-user", m_rq->vars);
376 void setAuthType(const char* authtype) {
377 param_free(pblock_remove("auth-type", m_rq->vars));
379 pblock_nvinsert("auth-type", authtype, m_rq->vars);
381 string getAuthType() const {
382 const char* at = pblock_findval("auth-type", m_rq->vars);
385 void setContentType(const char* type) {
386 // iPlanet seems to have a case folding problem.
387 param_free(pblock_remove("content-type", m_rq->srvhdrs));
388 setResponseHeader("Content-Type", type);
390 void setResponseHeader(const char* name, const char* value) {
391 pblock_nvinsert(name, value, m_rq->srvhdrs);
394 long sendResponse(istream& in, long status) {
399 msg.append(buf,in.gcount());
401 pblock_nvinsert("connection","close",m_rq->srvhdrs);
402 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
403 protocol_status(m_sn, m_rq, status, NULL);
404 protocol_start_response(m_sn, m_rq);
405 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
408 long sendRedirect(const char* url) {
409 param_free(pblock_remove("content-type", m_rq->srvhdrs));
410 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
411 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
412 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
413 pblock_nvinsert("location", url, m_rq->srvhdrs);
414 pblock_nvinsert("connection","close",m_rq->srvhdrs);
415 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
416 protocol_start_response(m_sn, m_rq);
419 long returnDecline() { return REQ_NOACTION; }
420 long returnOK() { return REQ_PROCEED; }
421 const vector<string>& getClientCertificates() const {
422 if (m_certs.empty()) {
423 const char* cert = pblock_findval("auth-cert", m_rq->vars);
425 m_certs.push_back(cert);
431 /********************************************************************************/
433 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
435 log_error(LOG_FAILURE,func,sn,rq,msg);
436 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
441 #define FUNC "shibboleth"
442 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
444 ostringstream threadid;
445 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
446 xmltooling::NDC ndc(threadid.str().c_str());
449 ShibTargetNSAPI stn(pb, sn, rq);
451 // Check user authentication
452 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
453 // If directed, install a spoof key to recognize when we've already cleared headers.
454 if (!g_spoofKey.empty()) {
455 param_free(pblock_remove("Shib-Spoof-Check", rq->headers));
456 pblock_nvinsert("Shib-Spoof-Check", g_spoofKey.c_str(), rq->headers);
458 if (res.first) return (int)res.second;
460 // user authN was okay -- export the assertions now
461 param_free(pblock_remove("auth-user",rq->vars));
463 res = stn.getServiceProvider().doExport(stn);
464 if (res.first) return (int)res.second;
466 // Check the Authorization
467 res = stn.getServiceProvider().doAuthorization(stn);
468 if (res.first) return (int)res.second;
473 catch (exception& e) {
474 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
475 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
478 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>("Shibboleth module threw an unknown exception."));
480 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
487 #define FUNC "shib_handler"
488 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
490 ostringstream threadid;
491 threadid << "[" << getpid() << "] shib_handler" << '\0';
492 xmltooling::NDC ndc(threadid.str().c_str());
495 ShibTargetNSAPI stn(pb, sn, rq);
497 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
498 if (res.first) return (int)res.second;
500 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
502 catch (exception& e) {
503 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
504 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
507 log_error(LOG_FAILURE,FUNC,sn,rq,"unknown exception caught in Shibboleth handler");
509 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
515 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
518 SunRequestMapper(const xercesc::DOMElement* e);
519 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
520 Lockable* lock() { return m_mapper->lock(); }
521 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
522 Settings getSettings(const HTTPRequest& request) const;
524 const PropertySet* getParent() const { return NULL; }
525 void setParent(const PropertySet*) {}
526 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
527 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
528 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
529 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
530 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
531 void getAll(map<string,const char*>& properties) const;
532 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
533 const xercesc::DOMElement* getElement() const;
536 RequestMapper* m_mapper;
538 ThreadKey* m_propsKey;
541 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
543 return new SunRequestMapper(e);
546 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
548 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
549 m_stKey=ThreadKey::create(NULL);
550 m_propsKey=ThreadKey::create(NULL);
553 RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
555 Settings s=m_mapper->getSettings(request);
556 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
557 m_propsKey->setData((void*)s.first);
558 return pair<const PropertySet*,AccessControl*>(this,s.second);
561 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
563 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
564 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
565 if (stn && !ns && name) {
566 // Override boolean properties.
567 const char* param=pblock_findval(name,stn->m_pb);
568 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
569 return make_pair(true,true);
571 return s ? s->getBool(name,ns) : make_pair(false,false);
574 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
576 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
577 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
578 if (stn && !ns && name) {
579 // Override string properties.
580 if (!strcmp(name,"authType"))
581 return pair<bool,const char*>(true,"shibboleth");
583 const char* param=pblock_findval(name,stn->m_pb);
585 return make_pair(true,param);
588 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
591 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
593 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
594 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
597 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
599 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
600 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
601 if (stn && !ns && name) {
602 // Override int properties.
603 const char* param=pblock_findval(name,stn->m_pb);
605 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
607 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
610 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
612 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
613 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
614 if (stn && !ns && name) {
615 // Override int properties.
616 const char* param=pblock_findval(name,stn->m_pb);
618 return pair<bool,int>(true,atoi(param));
620 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
623 void SunRequestMapper::getAll(map<string,const char*>& properties) const
625 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
626 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
628 s->getAll(properties);
631 properties["authType"] = "shibboleth";
632 const pb_entry* entry;
633 for (int i=0; i<stn->m_pb->hsize; ++i) {
634 entry = stn->m_pb->ht[i];
636 properties[entry->param->name] = entry->param->value;
642 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
644 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
645 return s ? s->getPropertySet(name,ns) : NULL;
648 const xercesc::DOMElement* SunRequestMapper::getElement() const
650 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
651 return s ? s->getElement() : NULL;