2 * Copyright 2001-2010 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/exceptions.h>
38 #include <shibsp/AbstractSPRequest.h>
39 #include <shibsp/RequestMapper.h>
40 #include <shibsp/SPConfig.h>
41 #include <shibsp/ServiceProvider.h>
48 #include <xmltooling/XMLToolingConfig.h>
49 #include <xmltooling/util/NDC.h>
50 #include <xmltooling/util/Threads.h>
51 #include <xmltooling/util/XMLConstants.h>
52 #include <xmltooling/util/XMLHelper.h>
53 #include <xercesc/util/XMLUniDefs.hpp>
70 using namespace shibsp;
71 using namespace xmltooling;
74 // macros to output text to client
75 #define NET_WRITE(str) \
76 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
79 SPConfig* g_Config=nullptr;
81 string g_unsetHeaderValue;
83 bool g_checkSpoofing = true;
84 bool g_catchAll = false;
86 static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
87 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
89 void _my_invalid_parameter_handler(
90 const wchar_t * expression,
91 const wchar_t * function,
100 PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
102 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
109 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
111 // Save off a default hostname for this virtual server.
112 char* name=pblock_findval("server-name",pb);
116 name=server_hostname;
120 name=util_hostname();
126 pblock_nvinsert("error","unable to determine web server hostname",pb);
132 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
134 const char* schemadir=pblock_findval("shib-schemas",pb);
135 const char* prefix=pblock_findval("shib-prefix",pb);
137 g_Config=&SPConfig::getConfig();
138 g_Config->setFeatures(
141 SPConfig::RequestMapping |
142 SPConfig::InProcess |
146 if (!g_Config->init(schemadir,prefix)) {
148 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
152 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&SunRequestMapFactory);
155 if (!g_Config->instantiate(pblock_findval("shib-config",pb), true))
156 throw runtime_error("unknown error");
158 catch (exception& ex) {
159 pblock_nvinsert("error",ex.what(),pb);
165 daemon_atrestart(nsapi_shib_exit,nullptr);
167 ServiceProvider* sp=g_Config->getServiceProvider();
169 const PropertySet* props=sp->getPropertySet("InProcess");
171 pair<bool,bool> flag=props->getBool("checkSpoofing");
172 g_checkSpoofing = !flag.first || flag.second;
173 flag=props->getBool("catchAll");
174 g_catchAll = flag.first && flag.second;
176 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
177 if (unsetValue.first)
178 g_unsetHeaderValue = unsetValue.second;
179 if (g_checkSpoofing) {
180 unsetValue=props->getString("spoofKey");
181 if (unsetValue.first)
182 g_spoofKey = unsetValue.second;
185 _invalid_parameter_handler old = _set_invalid_parameter_handler(_my_invalid_parameter_handler);
186 unsigned int randkey=0,randkey2=0,randkey3=0,randkey4=0;
187 if (rand_s(&randkey) == 0 && rand_s(&randkey2) == 0 && rand_s(&randkey3) == 0 && rand_s(&randkey4) == 0) {
188 _set_invalid_parameter_handler(old);
189 ostringstream keystr;
190 keystr << randkey << randkey2 << randkey3 << randkey4;
191 g_spoofKey = keystr.str();
194 _set_invalid_parameter_handler(old);
195 pblock_nvinsert("error", "module failed to generate a random anti-spoofing key (if this is Windows 2000 set one manually)", pb);
196 locker.assign(); // pops lock on SP config
208 /********************************************************************************/
209 // NSAPI Shib Target Subclass
211 class ShibTargetNSAPI : public AbstractSPRequest
213 mutable string m_body;
214 mutable bool m_gotBody,m_firsttime;
215 bool m_security_active;
216 int m_server_portnum;
217 mutable vector<string> m_certs;
218 set<string> m_allhttp;
225 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq)
226 : AbstractSPRequest(SHIBSP_LOGCAT".NSAPI"),
227 m_gotBody(false), m_firsttime(true), m_security_active(false), m_server_portnum(0), m_pb(pb), m_sn(sn), m_rq(rq) {
229 // To determine whether SSL is active or not, we're supposed to rely
230 // on the security_active macro. For iPlanet 4.x, this works.
231 // For Sun 7.x, it's useless and appears to be on or off based
232 // on whether ANY SSL support is enabled for a vhost. Sun 6.x is unknown.
233 // As a fix, there's a conf variable called $security that can be mapped
234 // into a function parameter: security_active="$security"
235 // We check for this parameter, and rely on the macro if it isn't set.
236 // This doubles as a scheme virtualizer for load balanced scenarios
237 // since you can set the parameter to 1 or 0 as needed.
238 const char* sa = pblock_findval("security_active", m_pb);
240 m_security_active = (*sa == '1');
241 else if (security_active)
242 m_security_active = true;
244 m_security_active = false;
246 // A similar issue exists for the port. server_portnum is no longer
247 // working on at least Sun 7.x, and returns the first listener's port
248 // rather than whatever port is actually used for the request. Nice job, Sun.
249 sa = pblock_findval("server_portnum", m_pb);
250 m_server_portnum = (sa && *sa) ? atoi(sa) : server_portnum;
252 const char* uri = pblock_findval("uri", rq->reqpb);
253 const char* qstr = pblock_findval("query", rq->reqpb);
256 string temp = string(uri) + '?' + qstr;
257 setRequestURI(temp.c_str());
263 // See if this is the first time we've run.
264 if (!g_spoofKey.empty()) {
265 qstr = pblock_findval("Shib-Spoof-Check", rq->headers);
266 if (qstr && g_spoofKey == qstr)
269 if (!m_firsttime || rq->orig_rq)
270 log(SPDebug, "nsapi_shib function running more than once");
272 ~ShibTargetNSAPI() { }
274 const char* getScheme() const {
275 return m_security_active ? "https" : "http";
277 const char* getHostname() const {
278 #ifdef vs_is_default_vs
279 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
280 if (!vs_is_default_vs(request_get_vs(m_rq)))
281 // The beauty here is, a non-default vhost can *only* be accessed if the client
282 // specified the exact name in the Host header. So we can trust the Host header.
283 return pblock_findval("host", m_rq->headers);
286 // In other cases, we're going to rely on the initialization process...
287 return g_ServerName.c_str();
289 int getPort() const {
290 return m_server_portnum;
292 const char* getMethod() const {
293 return pblock_findval("method", m_rq->reqpb);
295 string getContentType() const {
296 char* content_type = nullptr;
297 if (request_header("content-type", &content_type, m_sn, m_rq) != REQ_PROCEED)
299 return content_type ? content_type : "";
301 long getContentLength() const {
303 return m_body.length();
304 char* content_length=nullptr;
305 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED)
307 return content_length ? atoi(content_length) : 0;
309 string getRemoteAddr() const {
310 string ret = AbstractSPRequest::getRemoteAddr();
311 return ret.empty() ? pblock_findval("ip", m_sn->client) : ret;
313 void log(SPLogLevel level, const string& msg) const {
314 AbstractSPRequest::log(level,msg);
316 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
318 const char* getQueryString() const {
319 return pblock_findval("query", m_rq->reqpb);
321 const char* getRequestBody() const {
323 return m_body.c_str();
324 char* content_length=nullptr;
325 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED || !content_length) {
329 else if (atoi(content_length) > 1024*1024) // 1MB?
330 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
333 int cl=atoi(content_length);
335 while (cl && ch != IO_EOF) {
336 ch=netbuf_getc(m_sn->inbuf);
344 throw IOException("Error reading request body from browser.");
345 return m_body.c_str();
348 void clearHeader(const char* rawname, const char* cginame) {
349 if (g_checkSpoofing && m_firsttime && !m_rq->orig_rq) {
350 if (m_allhttp.empty()) {
351 // Populate the set of client-supplied headers for spoof checking.
352 const pb_entry* entry;
353 for (int i=0; i<m_rq->headers->hsize; ++i) {
354 entry = m_rq->headers->ht[i];
356 string cgiversion("HTTP_");
357 const char* pch = entry->param->name;
359 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
362 m_allhttp.insert(cgiversion);
367 if (m_allhttp.count(cginame) > 0)
368 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
370 if (strcmp(rawname, "REMOTE_USER") == 0) {
371 param_free(pblock_remove("remote-user", m_rq->headers));
372 pblock_nvinsert("remote-user", g_unsetHeaderValue.c_str(), m_rq->headers);
375 param_free(pblock_remove(rawname, m_rq->headers));
376 pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
379 void setHeader(const char* name, const char* value) {
380 param_free(pblock_remove(name, m_rq->headers));
381 pblock_nvinsert(name, value, m_rq->headers);
383 string getHeader(const char* name) const {
384 // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
386 int cookie = strcmp(name, "Cookie");
389 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
390 // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
395 n += tolower(*(name++));
396 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
399 return string(hdr ? hdr : "");
401 void setRemoteUser(const char* user) {
402 pblock_nvinsert("auth-user", user, m_rq->vars);
403 param_free(pblock_remove("remote-user", m_rq->headers));
404 pblock_nvinsert("remote-user", user, m_rq->headers);
406 string getRemoteUser() const {
407 const char* ru = pblock_findval("auth-user", m_rq->vars);
410 void setAuthType(const char* authtype) {
411 param_free(pblock_remove("auth-type", m_rq->vars));
413 pblock_nvinsert("auth-type", authtype, m_rq->vars);
415 string getAuthType() const {
416 const char* at = pblock_findval("auth-type", m_rq->vars);
419 void setContentType(const char* type) {
420 // iPlanet seems to have a case folding problem.
421 param_free(pblock_remove("content-type", m_rq->srvhdrs));
422 setResponseHeader("Content-Type", type);
424 void setResponseHeader(const char* name, const char* value) {
425 HTTPResponse::setResponseHeader(name, value);
426 pblock_nvinsert(name, value, m_rq->srvhdrs);
429 long sendResponse(istream& in, long status) {
434 msg.append(buf,in.gcount());
436 pblock_nvinsert("connection","close",m_rq->srvhdrs);
437 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
438 protocol_status(m_sn, m_rq, status, nullptr);
439 protocol_start_response(m_sn, m_rq);
440 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
443 long sendRedirect(const char* url) {
444 HTTPResponse::sendRedirect(url);
445 param_free(pblock_remove("content-type", m_rq->srvhdrs));
446 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
447 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
448 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
449 pblock_nvinsert("location", url, m_rq->srvhdrs);
450 pblock_nvinsert("connection","close",m_rq->srvhdrs);
451 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, nullptr);
452 protocol_start_response(m_sn, m_rq);
455 long returnDecline() { return REQ_NOACTION; }
456 long returnOK() { return REQ_PROCEED; }
457 const vector<string>& getClientCertificates() const {
458 if (m_certs.empty()) {
459 const char* cert = pblock_findval("auth-cert", m_rq->vars);
461 m_certs.push_back(cert);
467 /********************************************************************************/
469 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
471 log_error(LOG_FAILURE,func,sn,rq,msg);
472 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
477 #define FUNC "shibboleth"
478 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
480 ostringstream threadid;
481 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
482 xmltooling::NDC ndc(threadid.str().c_str());
485 ShibTargetNSAPI stn(pb, sn, rq);
487 // Check user authentication
488 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
489 // If directed, install a spoof key to recognize when we've already cleared headers.
490 if (!g_spoofKey.empty()) {
491 param_free(pblock_remove("Shib-Spoof-Check", rq->headers));
492 pblock_nvinsert("Shib-Spoof-Check", g_spoofKey.c_str(), rq->headers);
494 if (res.first) return (int)res.second;
496 // user authN was okay -- export the assertions now
497 param_free(pblock_remove("auth-user",rq->vars));
499 res = stn.getServiceProvider().doExport(stn);
500 if (res.first) return (int)res.second;
502 // Check the Authorization
503 res = stn.getServiceProvider().doAuthorization(stn);
504 if (res.first) return (int)res.second;
509 catch (exception& e) {
510 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
511 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
514 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>("Shibboleth module threw an unknown exception."));
516 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
523 #define FUNC "shib_handler"
524 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
526 ostringstream threadid;
527 threadid << "[" << getpid() << "] shib_handler" << '\0';
528 xmltooling::NDC ndc(threadid.str().c_str());
531 ShibTargetNSAPI stn(pb, sn, rq);
533 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
534 if (res.first) return (int)res.second;
536 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
538 catch (exception& e) {
539 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
540 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
543 log_error(LOG_FAILURE,FUNC,sn,rq,"unknown exception caught in Shibboleth handler");
545 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
551 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
554 SunRequestMapper(const xercesc::DOMElement* e);
555 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
556 Lockable* lock() { return m_mapper->lock(); }
557 void unlock() { m_stKey->setData(nullptr); m_propsKey->setData(nullptr); m_mapper->unlock(); }
558 Settings getSettings(const HTTPRequest& request) const;
560 const PropertySet* getParent() const { return nullptr; }
561 void setParent(const PropertySet*) {}
562 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const;
563 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const;
564 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const;
565 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const;
566 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const;
567 void getAll(map<string,const char*>& properties) const;
568 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
569 const xercesc::DOMElement* getElement() const;
572 RequestMapper* m_mapper;
574 ThreadKey* m_propsKey;
577 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
579 return new SunRequestMapper(e);
582 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(nullptr), m_stKey(nullptr), m_propsKey(nullptr)
584 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
585 m_stKey=ThreadKey::create(nullptr);
586 m_propsKey=ThreadKey::create(nullptr);
589 RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
591 Settings s=m_mapper->getSettings(request);
592 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
593 m_propsKey->setData((void*)s.first);
594 return pair<const PropertySet*,AccessControl*>(this,s.second);
597 pair<bool,bool> SunRequestMapper::getBool(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 boolean properties.
603 const char* param=pblock_findval(name,stn->m_pb);
604 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
605 return make_pair(true,true);
607 return s ? s->getBool(name,ns) : make_pair(false,false);
610 pair<bool,const char*> SunRequestMapper::getString(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 string properties.
616 if (!strcmp(name,"authType"))
617 return pair<bool,const char*>(true,"shibboleth");
619 const char* param=pblock_findval(name,stn->m_pb);
621 return make_pair(true,param);
624 return s ? s->getString(name,ns) : pair<bool,const char*>(false,nullptr);
627 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
629 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
630 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,nullptr);
633 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
635 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
636 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
637 if (stn && !ns && name) {
638 // Override int properties.
639 const char* param=pblock_findval(name,stn->m_pb);
641 return pair<bool,unsigned int>(true,strtol(param,nullptr,10));
643 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
646 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
648 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
649 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
650 if (stn && !ns && name) {
651 // Override int properties.
652 const char* param=pblock_findval(name,stn->m_pb);
654 return pair<bool,int>(true,atoi(param));
656 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
659 void SunRequestMapper::getAll(map<string,const char*>& properties) const
661 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
662 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
664 s->getAll(properties);
667 properties["authType"] = "shibboleth";
668 const pb_entry* entry;
669 for (int i=0; i<stn->m_pb->hsize; ++i) {
670 entry = stn->m_pb->ht[i];
672 properties[entry->param->name] = entry->param->value;
678 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
680 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
681 return s ? s->getPropertySet(name,ns) : nullptr;
684 const xercesc::DOMElement* SunRequestMapper::getElement() const
686 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
687 return s ? s->getElement() : nullptr;