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>
69 using namespace shibsp;
70 using namespace xmltooling;
73 // macros to output text to client
74 #define NET_WRITE(str) \
75 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
78 SPConfig* g_Config=NULL;
80 string g_unsetHeaderValue;
82 bool g_checkSpoofing = true;
83 bool g_catchAll = false;
85 static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
86 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
88 void _my_invalid_parameter_handler(
89 const wchar_t * expression,
90 const wchar_t * function,
99 PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
101 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
108 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
110 // Save off a default hostname for this virtual server.
111 char* name=pblock_findval("server-name",pb);
115 name=server_hostname;
119 name=util_hostname();
125 pblock_nvinsert("error","unable to determine web server hostname",pb);
131 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
133 const char* schemadir=pblock_findval("shib-schemas",pb);
134 const char* prefix=pblock_findval("shib-prefix",pb);
136 g_Config=&SPConfig::getConfig();
137 g_Config->setFeatures(
140 SPConfig::RequestMapping |
141 SPConfig::InProcess |
145 if (!g_Config->init(schemadir,prefix)) {
147 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
151 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&SunRequestMapFactory);
154 if (!g_Config->instantiate(pblock_findval("shib-config",pb), true))
155 throw runtime_error("unknown error");
157 catch (exception& ex) {
158 pblock_nvinsert("error",ex.what(),pb);
164 daemon_atrestart(nsapi_shib_exit,NULL);
166 ServiceProvider* sp=g_Config->getServiceProvider();
168 const PropertySet* props=sp->getPropertySet("InProcess");
170 pair<bool,bool> flag=props->getBool("checkSpoofing");
171 g_checkSpoofing = !flag.first || flag.second;
172 flag=props->getBool("catchAll");
173 g_catchAll = flag.first && flag.second;
175 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
176 if (unsetValue.first)
177 g_unsetHeaderValue = unsetValue.second;
178 if (g_checkSpoofing) {
179 unsetValue=props->getString("spoofKey");
180 if (unsetValue.first)
181 g_spoofKey = unsetValue.second;
184 _invalid_parameter_handler old = _set_invalid_parameter_handler(_my_invalid_parameter_handler);
185 unsigned int randkey=0,randkey2=0,randkey3=0,randkey4=0;
186 if (rand_s(&randkey) == 0 && rand_s(&randkey2) == 0 && rand_s(&randkey3) == 0 && rand_s(&randkey4) == 0) {
187 _set_invalid_parameter_handler(old);
188 ostringstream keystr;
189 keystr << randkey << randkey2 << randkey3 << randkey4;
190 g_spoofKey = keystr.str();
193 _set_invalid_parameter_handler(old);
194 pblock_nvinsert("error", "module failed to generate a random anti-spoofing key (if this is Windows 2000 set one manually)", pb);
195 locker.assign(); // pops lock on SP config
207 /********************************************************************************/
208 // NSAPI Shib Target Subclass
210 class ShibTargetNSAPI : public AbstractSPRequest
212 mutable string m_body;
213 mutable bool m_gotBody,m_firsttime;
214 bool m_security_active;
215 int m_server_portnum;
216 mutable vector<string> m_certs;
217 set<string> m_allhttp;
224 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq)
225 : AbstractSPRequest(SHIBSP_LOGCAT".NSAPI"),
226 m_gotBody(false), m_firsttime(true), m_security_active(false), m_server_portnum(0), m_pb(pb), m_sn(sn), m_rq(rq) {
228 // To determine whether SSL is active or not, we're supposed to rely
229 // on the security_active macro. For iPlanet 4.x, this works.
230 // For Sun 7.x, it's useless and appears to be on or off based
231 // on whether ANY SSL support is enabled for a vhost. Sun 6.x is unknown.
232 // As a fix, there's a conf variable called $security that can be mapped
233 // into a function parameter: security_active="$security"
234 // We check for this parameter, and rely on the macro if it isn't set.
235 // This doubles as a scheme virtualizer for load balanced scenarios
236 // since you can set the parameter to 1 or 0 as needed.
237 const char* sa = pblock_findval("security_active", m_pb);
239 m_security_active = (*sa == '1');
240 else if (security_active)
241 m_security_active = true;
243 m_security_active = false;
245 // A similar issue exists for the port. server_portnum is no longer
246 // working on at least Sun 7.x, and returns the first listener's port
247 // rather than whatever port is actually used for the request. Nice job, Sun.
248 sa = pblock_findval("server_portnum", m_pb);
249 m_server_portnum = (sa && *sa) ? atoi(sa) : server_portnum;
251 const char* uri = pblock_findval("uri", rq->reqpb);
252 const char* qstr = pblock_findval("query", rq->reqpb);
255 string temp = string(uri) + '?' + qstr;
256 setRequestURI(temp.c_str());
262 // See if this is the first time we've run.
263 if (!g_spoofKey.empty()) {
264 qstr = pblock_findval("Shib-Spoof-Check", rq->headers);
265 if (qstr && g_spoofKey == qstr)
268 if (!m_firsttime || rq->orig_rq)
269 log(SPDebug, "nsapi_shib function running more than once");
271 ~ShibTargetNSAPI() { }
273 const char* getScheme() const {
274 return m_security_active ? "https" : "http";
276 const char* getHostname() const {
277 #ifdef vs_is_default_vs
278 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
279 if (!vs_is_default_vs(request_get_vs(m_rq)))
280 // The beauty here is, a non-default vhost can *only* be accessed if the client
281 // specified the exact name in the Host header. So we can trust the Host header.
282 return pblock_findval("host", m_rq->headers);
285 // In other cases, we're going to rely on the initialization process...
286 return g_ServerName.c_str();
288 int getPort() const {
289 return m_server_portnum;
291 const char* getMethod() const {
292 return pblock_findval("method", m_rq->reqpb);
294 string getContentType() const {
295 char* content_type = NULL;
296 if (request_header("content-type", &content_type, m_sn, m_rq) != REQ_PROCEED)
298 return content_type ? content_type : "";
300 long getContentLength() const {
302 return m_body.length();
303 char* content_length=NULL;
304 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED)
306 return content_length ? atoi(content_length) : 0;
308 string getRemoteAddr() const {
309 string ret = AbstractSPRequest::getRemoteAddr();
310 return ret.empty() ? pblock_findval("ip", m_sn->client) : ret;
312 void log(SPLogLevel level, const string& msg) const {
313 AbstractSPRequest::log(level,msg);
315 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
317 const char* getQueryString() const {
318 return pblock_findval("query", m_rq->reqpb);
320 const char* getRequestBody() const {
322 return m_body.c_str();
323 char* content_length=NULL;
324 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED || !content_length) {
328 else if (atoi(content_length) > 1024*1024) // 1MB?
329 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
332 int cl=atoi(content_length);
334 while (cl && ch != IO_EOF) {
335 ch=netbuf_getc(m_sn->inbuf);
343 throw IOException("Error reading request body from browser.");
344 return m_body.c_str();
347 void clearHeader(const char* rawname, const char* cginame) {
348 if (g_checkSpoofing && m_firsttime && !m_rq->orig_rq) {
349 if (m_allhttp.empty()) {
350 // Populate the set of client-supplied headers for spoof checking.
351 const pb_entry* entry;
352 for (int i=0; i<m_rq->headers->hsize; ++i) {
353 entry = m_rq->headers->ht[i];
355 string cgiversion("HTTP_");
356 const char* pch = entry->param->name;
358 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
361 m_allhttp.insert(cgiversion);
366 if (m_allhttp.count(cginame) > 0)
367 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
369 if (strcmp(rawname, "REMOTE_USER") == 0) {
370 param_free(pblock_remove("remote-user", m_rq->headers));
371 pblock_nvinsert("remote-user", g_unsetHeaderValue.c_str(), m_rq->headers);
374 param_free(pblock_remove(rawname, m_rq->headers));
375 pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
378 void setHeader(const char* name, const char* value) {
379 param_free(pblock_remove(name, m_rq->headers));
380 pblock_nvinsert(name, value, m_rq->headers);
382 string getHeader(const char* name) const {
383 // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
385 int cookie = strcmp(name, "Cookie");
388 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
389 // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
394 n += tolower(*(name++));
395 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
398 return string(hdr ? hdr : "");
400 void setRemoteUser(const char* user) {
401 pblock_nvinsert("auth-user", user, m_rq->vars);
402 param_free(pblock_remove("remote-user", m_rq->headers));
403 pblock_nvinsert("remote-user", user, m_rq->headers);
405 string getRemoteUser() const {
406 const char* ru = pblock_findval("auth-user", m_rq->vars);
409 void setAuthType(const char* authtype) {
410 param_free(pblock_remove("auth-type", m_rq->vars));
412 pblock_nvinsert("auth-type", authtype, m_rq->vars);
414 string getAuthType() const {
415 const char* at = pblock_findval("auth-type", m_rq->vars);
418 void setContentType(const char* type) {
419 // iPlanet seems to have a case folding problem.
420 param_free(pblock_remove("content-type", m_rq->srvhdrs));
421 setResponseHeader("Content-Type", type);
423 void setResponseHeader(const char* name, const char* value) {
424 pblock_nvinsert(name, value, m_rq->srvhdrs);
427 long sendResponse(istream& in, long status) {
432 msg.append(buf,in.gcount());
434 pblock_nvinsert("connection","close",m_rq->srvhdrs);
435 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
436 protocol_status(m_sn, m_rq, status, NULL);
437 protocol_start_response(m_sn, m_rq);
438 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
441 long sendRedirect(const char* url) {
442 param_free(pblock_remove("content-type", m_rq->srvhdrs));
443 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
444 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
445 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
446 pblock_nvinsert("location", url, m_rq->srvhdrs);
447 pblock_nvinsert("connection","close",m_rq->srvhdrs);
448 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
449 protocol_start_response(m_sn, m_rq);
452 long returnDecline() { return REQ_NOACTION; }
453 long returnOK() { return REQ_PROCEED; }
454 const vector<string>& getClientCertificates() const {
455 if (m_certs.empty()) {
456 const char* cert = pblock_findval("auth-cert", m_rq->vars);
458 m_certs.push_back(cert);
464 /********************************************************************************/
466 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
468 log_error(LOG_FAILURE,func,sn,rq,msg);
469 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
474 #define FUNC "shibboleth"
475 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
477 ostringstream threadid;
478 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
479 xmltooling::NDC ndc(threadid.str().c_str());
482 ShibTargetNSAPI stn(pb, sn, rq);
484 // Check user authentication
485 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
486 // If directed, install a spoof key to recognize when we've already cleared headers.
487 if (!g_spoofKey.empty()) {
488 param_free(pblock_remove("Shib-Spoof-Check", rq->headers));
489 pblock_nvinsert("Shib-Spoof-Check", g_spoofKey.c_str(), rq->headers);
491 if (res.first) return (int)res.second;
493 // user authN was okay -- export the assertions now
494 param_free(pblock_remove("auth-user",rq->vars));
496 res = stn.getServiceProvider().doExport(stn);
497 if (res.first) return (int)res.second;
499 // Check the Authorization
500 res = stn.getServiceProvider().doAuthorization(stn);
501 if (res.first) return (int)res.second;
506 catch (exception& e) {
507 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
508 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
511 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>("Shibboleth module threw an unknown exception."));
513 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
520 #define FUNC "shib_handler"
521 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
523 ostringstream threadid;
524 threadid << "[" << getpid() << "] shib_handler" << '\0';
525 xmltooling::NDC ndc(threadid.str().c_str());
528 ShibTargetNSAPI stn(pb, sn, rq);
530 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
531 if (res.first) return (int)res.second;
533 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
535 catch (exception& e) {
536 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
537 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
540 log_error(LOG_FAILURE,FUNC,sn,rq,"unknown exception caught in Shibboleth handler");
542 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
548 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
551 SunRequestMapper(const xercesc::DOMElement* e);
552 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
553 Lockable* lock() { return m_mapper->lock(); }
554 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
555 Settings getSettings(const HTTPRequest& request) const;
557 const PropertySet* getParent() const { return NULL; }
558 void setParent(const PropertySet*) {}
559 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
560 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
561 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
562 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
563 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
564 void getAll(map<string,const char*>& properties) const;
565 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
566 const xercesc::DOMElement* getElement() const;
569 RequestMapper* m_mapper;
571 ThreadKey* m_propsKey;
574 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
576 return new SunRequestMapper(e);
579 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
581 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
582 m_stKey=ThreadKey::create(NULL);
583 m_propsKey=ThreadKey::create(NULL);
586 RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
588 Settings s=m_mapper->getSettings(request);
589 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
590 m_propsKey->setData((void*)s.first);
591 return pair<const PropertySet*,AccessControl*>(this,s.second);
594 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
596 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
597 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
598 if (stn && !ns && name) {
599 // Override boolean properties.
600 const char* param=pblock_findval(name,stn->m_pb);
601 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
602 return make_pair(true,true);
604 return s ? s->getBool(name,ns) : make_pair(false,false);
607 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
609 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
610 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
611 if (stn && !ns && name) {
612 // Override string properties.
613 if (!strcmp(name,"authType"))
614 return pair<bool,const char*>(true,"shibboleth");
616 const char* param=pblock_findval(name,stn->m_pb);
618 return make_pair(true,param);
621 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
624 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
626 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
627 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
630 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
632 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
633 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
634 if (stn && !ns && name) {
635 // Override int properties.
636 const char* param=pblock_findval(name,stn->m_pb);
638 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
640 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
643 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
645 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
646 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
647 if (stn && !ns && name) {
648 // Override int properties.
649 const char* param=pblock_findval(name,stn->m_pb);
651 return pair<bool,int>(true,atoi(param));
653 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
656 void SunRequestMapper::getAll(map<string,const char*>& properties) const
658 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
659 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
661 s->getAll(properties);
664 properties["authType"] = "shibboleth";
665 const pb_entry* entry;
666 for (int i=0; i<stn->m_pb->hsize; ++i) {
667 entry = stn->m_pb->ht[i];
669 properties[entry->param->name] = entry->param->value;
675 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
677 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
678 return s ? s->getPropertySet(name,ns) : NULL;
681 const xercesc::DOMElement* SunRequestMapper::getElement() const
683 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
684 return s ? s->getElement() : NULL;