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
37 #include <shibsp/AbstractSPRequest.h>
38 #include <shibsp/RequestMapper.h>
39 #include <shibsp/SPConfig.h>
40 #include <shibsp/ServiceProvider.h>
41 #include <xmltooling/XMLToolingConfig.h>
42 #include <xmltooling/util/NDC.h>
43 #include <xmltooling/util/Threads.h>
44 #include <xmltooling/util/XMLConstants.h>
45 #include <xmltooling/util/XMLHelper.h>
46 #include <xercesc/util/XMLUniDefs.hpp>
68 using namespace shibsp;
69 using namespace xmltooling;
72 // macros to output text to client
73 #define NET_WRITE(str) \
74 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
77 SPConfig* g_Config=NULL;
79 string g_unsetHeaderValue;
81 bool g_checkSpoofing = true;
82 bool g_catchAll = false;
84 static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
85 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
87 void _my_invalid_parameter_handler(
88 const wchar_t * expression,
89 const wchar_t * function,
98 PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
100 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
107 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
109 // Save off a default hostname for this virtual server.
110 char* name=pblock_findval("server-name",pb);
114 name=server_hostname;
118 name=util_hostname();
124 pblock_nvinsert("error","unable to determine web server hostname",pb);
130 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
132 const char* schemadir=pblock_findval("shib-schemas",pb);
133 const char* prefix=pblock_findval("shib-prefix",pb);
135 g_Config=&SPConfig::getConfig();
136 g_Config->setFeatures(
139 SPConfig::RequestMapping |
140 SPConfig::InProcess |
144 if (!g_Config->init(schemadir,prefix)) {
146 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
150 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&SunRequestMapFactory);
153 if (!g_Config->instantiate(pblock_findval("shib-config",pb), true))
154 throw runtime_error("unknown error");
156 catch (exception& ex) {
157 pblock_nvinsert("error",ex.what(),pb);
163 daemon_atrestart(nsapi_shib_exit,NULL);
165 ServiceProvider* sp=g_Config->getServiceProvider();
167 const PropertySet* props=sp->getPropertySet("InProcess");
169 pair<bool,bool> flag=props->getBool("checkSpoofing");
170 g_checkSpoofing = !flag.first || flag.second;
171 flag=props->getBool("catchAll");
172 g_catchAll = flag.first && flag.second;
174 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
175 if (unsetValue.first)
176 g_unsetHeaderValue = unsetValue.second;
177 if (g_checkSpoofing) {
178 unsetValue=props->getString("spoofKey");
179 if (unsetValue.first)
180 g_spoofKey = unsetValue.second;
183 _invalid_parameter_handler old = _set_invalid_parameter_handler(_my_invalid_parameter_handler);
184 unsigned int randkey=0,randkey2=0,randkey3=0,randkey4=0;
185 if (rand_s(&randkey) == 0 && rand_s(&randkey2) == 0 && rand_s(&randkey3) == 0 && rand_s(&randkey4) == 0) {
186 _set_invalid_parameter_handler(old);
187 ostringstream keystr;
188 keystr << randkey << randkey2 << randkey3 << randkey4;
189 g_spoofKey = keystr.str();
192 _set_invalid_parameter_handler(old);
193 pblock_nvinsert("error", "module failed to generate a random anti-spoofing key (if this is Windows 2000 set one manually)", pb);
194 locker.assign(); // pops lock on SP config
206 /********************************************************************************/
207 // NSAPI Shib Target Subclass
209 class ShibTargetNSAPI : public AbstractSPRequest
211 mutable string m_body;
212 mutable bool m_gotBody,m_firsttime;
213 bool m_security_active;
214 int m_server_portnum;
215 mutable vector<string> m_certs;
216 set<string> m_allhttp;
223 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq)
224 : AbstractSPRequest(SHIBSP_LOGCAT".NSAPI"),
225 m_gotBody(false), m_firsttime(true), m_security_active(false), m_server_portnum(0), m_pb(pb), m_sn(sn), m_rq(rq) {
227 // To determine whether SSL is active or not, we're supposed to rely
228 // on the security_active macro. For iPlanet 4.x, this works.
229 // For Sun 7.x, it's useless and appears to be on or off based
230 // on whether ANY SSL support is enabled for a vhost. Sun 6.x is unknown.
231 // As a fix, there's a conf variable called $security that can be mapped
232 // into a function parameter: security_active="$security"
233 // We check for this parameter, and rely on the macro if it isn't set.
234 // This doubles as a scheme virtualizer for load balanced scenarios
235 // since you can set the parameter to 1 or 0 as needed.
236 const char* sa = pblock_findval("security_active", m_pb);
238 m_security_active = (*sa == '1');
239 else if (security_active)
240 m_security_active = true;
242 m_security_active = false;
244 // A similar issue exists for the port. server_portnum is no longer
245 // working on at least Sun 7.x, and returns the first listener's port
246 // rather than whatever port is actually used for the request. Nice job, Sun.
247 sa = pblock_findval("server_portnum", m_pb);
248 m_server_portnum = (sa && *sa) ? atoi(sa) : server_portnum;
250 const char* uri = pblock_findval("uri", rq->reqpb);
251 const char* qstr = pblock_findval("query", rq->reqpb);
254 string temp = string(uri) + '?' + qstr;
255 setRequestURI(temp.c_str());
261 // See if this is the first time we've run.
262 if (!g_spoofKey.empty()) {
263 qstr = pblock_findval("Shib-Spoof-Check", rq->headers);
264 if (qstr && g_spoofKey == qstr)
267 if (!m_firsttime || rq->orig_rq)
268 log(SPDebug, "nsapi_shib function running more than once");
270 ~ShibTargetNSAPI() { }
272 const char* getScheme() const {
273 return m_security_active ? "https" : "http";
275 const char* getHostname() const {
276 #ifdef vs_is_default_vs
277 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
278 if (!vs_is_default_vs(request_get_vs(m_rq)))
279 // The beauty here is, a non-default vhost can *only* be accessed if the client
280 // specified the exact name in the Host header. So we can trust the Host header.
281 return pblock_findval("host", m_rq->headers);
284 // In other cases, we're going to rely on the initialization process...
285 return g_ServerName.c_str();
287 int getPort() const {
288 return m_server_portnum;
290 const char* getMethod() const {
291 return pblock_findval("method", m_rq->reqpb);
293 string getContentType() const {
294 char* content_type = NULL;
295 if (request_header("content-type", &content_type, m_sn, m_rq) != REQ_PROCEED)
297 return content_type ? content_type : "";
299 long getContentLength() const {
301 return m_body.length();
302 char* content_length=NULL;
303 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED)
305 return content_length ? atoi(content_length) : 0;
307 string getRemoteAddr() const {
308 string ret = AbstractSPRequest::getRemoteAddr();
309 return ret.empty() ? pblock_findval("ip", m_sn->client) : ret;
311 void log(SPLogLevel level, const string& msg) const {
312 AbstractSPRequest::log(level,msg);
314 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
316 const char* getQueryString() const {
317 return pblock_findval("query", m_rq->reqpb);
319 const char* getRequestBody() const {
321 return m_body.c_str();
322 char* content_length=NULL;
323 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED || !content_length) {
327 else if (atoi(content_length) > 1024*1024) // 1MB?
328 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
331 int cl=atoi(content_length);
333 while (cl && ch != IO_EOF) {
334 ch=netbuf_getc(m_sn->inbuf);
342 throw IOException("Error reading request body from browser.");
343 return m_body.c_str();
346 void clearHeader(const char* rawname, const char* cginame) {
347 if (g_checkSpoofing && m_firsttime && !m_rq->orig_rq) {
348 if (m_allhttp.empty()) {
349 // Populate the set of client-supplied headers for spoof checking.
350 const pb_entry* entry;
351 for (int i=0; i<m_rq->headers->hsize; ++i) {
352 entry = m_rq->headers->ht[i];
354 string cgiversion("HTTP_");
355 const char* pch = entry->param->name;
357 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
360 m_allhttp.insert(cgiversion);
365 if (m_allhttp.count(cginame) > 0)
366 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
368 if (strcmp(rawname, "REMOTE_USER") == 0) {
369 param_free(pblock_remove("remote-user", m_rq->headers));
370 pblock_nvinsert("remote-user", g_unsetHeaderValue.c_str(), m_rq->headers);
373 param_free(pblock_remove(rawname, m_rq->headers));
374 pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
377 void setHeader(const char* name, const char* value) {
378 param_free(pblock_remove(name, m_rq->headers));
379 pblock_nvinsert(name, value, m_rq->headers);
381 string getHeader(const char* name) const {
382 // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
384 int cookie = strcmp(name, "Cookie");
387 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
388 // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
393 n += tolower(*(name++));
394 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
397 return string(hdr ? hdr : "");
399 void setRemoteUser(const char* user) {
400 pblock_nvinsert("auth-user", user, m_rq->vars);
401 param_free(pblock_remove("remote-user", m_rq->headers));
402 pblock_nvinsert("remote-user", user, m_rq->headers);
404 string getRemoteUser() const {
405 const char* ru = pblock_findval("auth-user", m_rq->vars);
408 void setAuthType(const char* authtype) {
409 param_free(pblock_remove("auth-type", m_rq->vars));
411 pblock_nvinsert("auth-type", authtype, m_rq->vars);
413 string getAuthType() const {
414 const char* at = pblock_findval("auth-type", m_rq->vars);
417 void setContentType(const char* type) {
418 // iPlanet seems to have a case folding problem.
419 param_free(pblock_remove("content-type", m_rq->srvhdrs));
420 setResponseHeader("Content-Type", type);
422 void setResponseHeader(const char* name, const char* value) {
423 pblock_nvinsert(name, value, m_rq->srvhdrs);
426 long sendResponse(istream& in, long status) {
431 msg.append(buf,in.gcount());
433 pblock_nvinsert("connection","close",m_rq->srvhdrs);
434 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
435 protocol_status(m_sn, m_rq, status, NULL);
436 protocol_start_response(m_sn, m_rq);
437 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
440 long sendRedirect(const char* url) {
441 param_free(pblock_remove("content-type", m_rq->srvhdrs));
442 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
443 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
444 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
445 pblock_nvinsert("location", url, m_rq->srvhdrs);
446 pblock_nvinsert("connection","close",m_rq->srvhdrs);
447 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
448 protocol_start_response(m_sn, m_rq);
451 long returnDecline() { return REQ_NOACTION; }
452 long returnOK() { return REQ_PROCEED; }
453 const vector<string>& getClientCertificates() const {
454 if (m_certs.empty()) {
455 const char* cert = pblock_findval("auth-cert", m_rq->vars);
457 m_certs.push_back(cert);
463 /********************************************************************************/
465 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
467 log_error(LOG_FAILURE,func,sn,rq,msg);
468 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
473 #define FUNC "shibboleth"
474 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
476 ostringstream threadid;
477 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
478 xmltooling::NDC ndc(threadid.str().c_str());
481 ShibTargetNSAPI stn(pb, sn, rq);
483 // Check user authentication
484 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
485 // If directed, install a spoof key to recognize when we've already cleared headers.
486 if (!g_spoofKey.empty()) {
487 param_free(pblock_remove("Shib-Spoof-Check", rq->headers));
488 pblock_nvinsert("Shib-Spoof-Check", g_spoofKey.c_str(), rq->headers);
490 if (res.first) return (int)res.second;
492 // user authN was okay -- export the assertions now
493 param_free(pblock_remove("auth-user",rq->vars));
495 res = stn.getServiceProvider().doExport(stn);
496 if (res.first) return (int)res.second;
498 // Check the Authorization
499 res = stn.getServiceProvider().doAuthorization(stn);
500 if (res.first) return (int)res.second;
505 catch (exception& e) {
506 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
507 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
510 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>("Shibboleth module threw an unknown exception."));
512 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
519 #define FUNC "shib_handler"
520 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
522 ostringstream threadid;
523 threadid << "[" << getpid() << "] shib_handler" << '\0';
524 xmltooling::NDC ndc(threadid.str().c_str());
527 ShibTargetNSAPI stn(pb, sn, rq);
529 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
530 if (res.first) return (int)res.second;
532 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
534 catch (exception& e) {
535 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
536 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
539 log_error(LOG_FAILURE,FUNC,sn,rq,"unknown exception caught in Shibboleth handler");
541 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
547 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
550 SunRequestMapper(const xercesc::DOMElement* e);
551 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
552 Lockable* lock() { return m_mapper->lock(); }
553 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
554 Settings getSettings(const HTTPRequest& request) const;
556 const PropertySet* getParent() const { return NULL; }
557 void setParent(const PropertySet*) {}
558 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
559 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
560 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
561 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
562 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
563 void getAll(map<string,const char*>& properties) const;
564 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
565 const xercesc::DOMElement* getElement() const;
568 RequestMapper* m_mapper;
570 ThreadKey* m_propsKey;
573 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
575 return new SunRequestMapper(e);
578 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
580 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
581 m_stKey=ThreadKey::create(NULL);
582 m_propsKey=ThreadKey::create(NULL);
585 RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
587 Settings s=m_mapper->getSettings(request);
588 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
589 m_propsKey->setData((void*)s.first);
590 return pair<const PropertySet*,AccessControl*>(this,s.second);
593 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
595 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
596 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
597 if (stn && !ns && name) {
598 // Override boolean properties.
599 const char* param=pblock_findval(name,stn->m_pb);
600 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
601 return make_pair(true,true);
603 return s ? s->getBool(name,ns) : make_pair(false,false);
606 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
608 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
609 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
610 if (stn && !ns && name) {
611 // Override string properties.
612 if (!strcmp(name,"authType"))
613 return pair<bool,const char*>(true,"shibboleth");
615 const char* param=pblock_findval(name,stn->m_pb);
617 return make_pair(true,param);
620 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
623 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
625 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
626 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
629 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
631 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
632 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
633 if (stn && !ns && name) {
634 // Override int properties.
635 const char* param=pblock_findval(name,stn->m_pb);
637 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
639 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
642 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
644 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
645 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
646 if (stn && !ns && name) {
647 // Override int properties.
648 const char* param=pblock_findval(name,stn->m_pb);
650 return pair<bool,int>(true,atoi(param));
652 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
655 void SunRequestMapper::getAll(map<string,const char*>& properties) const
657 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
658 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
660 s->getAll(properties);
663 properties["authType"] = "shibboleth";
664 const pb_entry* entry;
665 for (int i=0; i<stn->m_pb->hsize; ++i) {
666 entry = stn->m_pb->ht[i];
668 properties[entry->param->name] = entry->param->value;
674 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
676 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
677 return s ? s->getPropertySet(name,ns) : NULL;
680 const xercesc::DOMElement* SunRequestMapper::getElement() const
682 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
683 return s ? s->getElement() : NULL;