2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
24 * Shibboleth NSAPI filter.
29 #if defined (_MSC_VER) || defined(__BORLANDC__)
30 # include "config_win32.h"
36 # define _CRT_NONSTDC_NO_DEPRECATE 1
37 # define _CRT_SECURE_NO_DEPRECATE 1
41 #include <shibsp/exceptions.h>
42 #include <shibsp/AbstractSPRequest.h>
43 #include <shibsp/RequestMapper.h>
44 #include <shibsp/SPConfig.h>
45 #include <shibsp/ServiceProvider.h>
51 #include <boost/lexical_cast.hpp>
52 #include <boost/scoped_ptr.hpp>
53 #include <xmltooling/XMLToolingConfig.h>
54 #include <xmltooling/util/NDC.h>
55 #include <xmltooling/util/Threads.h>
56 #include <xmltooling/util/XMLConstants.h>
57 #include <xmltooling/util/XMLHelper.h>
58 #include <xercesc/util/XMLUniDefs.hpp>
75 using namespace shibsp;
76 using namespace xmltooling;
77 using namespace boost;
80 // macros to output text to client
81 #define NET_WRITE(str) \
82 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
85 SPConfig* g_Config=nullptr;
87 string g_unsetHeaderValue;
89 bool g_checkSpoofing = true;
90 bool g_catchAll = false;
92 static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
93 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
95 void _my_invalid_parameter_handler(
96 const wchar_t * expression,
97 const wchar_t * function,
106 PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
108 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
115 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
117 // Save off a default hostname for this virtual server.
118 char* name=pblock_findval("server-name",pb);
122 name=server_hostname;
126 name=util_hostname();
132 pblock_nvinsert("error","unable to determine web server hostname",pb);
138 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
140 const char* schemadir=pblock_findval("shib-schemas",pb);
141 const char* prefix=pblock_findval("shib-prefix",pb);
143 g_Config=&SPConfig::getConfig();
144 g_Config->setFeatures(
147 SPConfig::RequestMapping |
148 SPConfig::InProcess |
152 if (!g_Config->init(schemadir,prefix)) {
154 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
158 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&SunRequestMapFactory);
161 if (!g_Config->instantiate(pblock_findval("shib-config",pb), true))
162 throw runtime_error("unknown error");
164 catch (std::exception& ex) {
165 pblock_nvinsert("error",ex.what(),pb);
171 daemon_atrestart(nsapi_shib_exit,nullptr);
173 ServiceProvider* sp=g_Config->getServiceProvider();
175 const PropertySet* props=sp->getPropertySet("InProcess");
177 pair<bool,bool> flag=props->getBool("checkSpoofing");
178 g_checkSpoofing = !flag.first || flag.second;
179 flag=props->getBool("catchAll");
180 g_catchAll = flag.first && flag.second;
182 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
183 if (unsetValue.first)
184 g_unsetHeaderValue = unsetValue.second;
185 if (g_checkSpoofing) {
186 unsetValue=props->getString("spoofKey");
187 if (unsetValue.first)
188 g_spoofKey = unsetValue.second;
191 _invalid_parameter_handler old = _set_invalid_parameter_handler(_my_invalid_parameter_handler);
192 unsigned int randkey=0,randkey2=0,randkey3=0,randkey4=0;
193 if (rand_s(&randkey) == 0 && rand_s(&randkey2) == 0 && rand_s(&randkey3) == 0 && rand_s(&randkey4) == 0) {
194 _set_invalid_parameter_handler(old);
195 g_spoofKey = lexical_cast<string>(randkey) + lexical_cast<string>(randkey2) +
196 lexical_cast<string>(randkey3) + lexical_cast<string>(randkey4);
199 _set_invalid_parameter_handler(old);
200 pblock_nvinsert("error", "module failed to generate a random anti-spoofing key (if this is Windows 2000 set one manually)", pb);
201 locker.assign(); // pops lock on SP config
213 /********************************************************************************/
214 // NSAPI Shib Target Subclass
216 class ShibTargetNSAPI : public AbstractSPRequest
218 mutable string m_body;
219 mutable bool m_gotBody,m_firsttime;
220 bool m_security_active;
221 int m_server_portnum;
222 mutable vector<string> m_certs;
223 set<string> m_allhttp;
230 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq)
231 : AbstractSPRequest(SHIBSP_LOGCAT".NSAPI"),
232 m_gotBody(false), m_firsttime(true), m_security_active(false), m_server_portnum(0), m_pb(pb), m_sn(sn), m_rq(rq) {
234 // To determine whether SSL is active or not, we're supposed to rely
235 // on the security_active macro. For iPlanet 4.x, this works.
236 // For Sun 7.x, it's useless and appears to be on or off based
237 // on whether ANY SSL support is enabled for a vhost. Sun 6.x is unknown.
238 // As a fix, there's a conf variable called $security that can be mapped
239 // into a function parameter: security_active="$security"
240 // We check for this parameter, and rely on the macro if it isn't set.
241 // This doubles as a scheme virtualizer for load balanced scenarios
242 // since you can set the parameter to 1 or 0 as needed.
243 const char* sa = pblock_findval("security_active", m_pb);
245 m_security_active = (*sa == '1');
246 else if (security_active)
247 m_security_active = true;
249 m_security_active = false;
251 // A similar issue exists for the port. server_portnum is no longer
252 // working on at least Sun 7.x, and returns the first listener's port
253 // rather than whatever port is actually used for the request. Nice job, Sun.
254 sa = pblock_findval("server_portnum", m_pb);
255 m_server_portnum = (sa && *sa) ? atoi(sa) : server_portnum;
257 const char* uri = pblock_findval("uri", rq->reqpb);
258 const char* qstr = pblock_findval("query", rq->reqpb);
261 string temp = string(uri) + '?' + qstr;
262 setRequestURI(temp.c_str());
268 // See if this is the first time we've run.
269 if (!g_spoofKey.empty()) {
270 qstr = pblock_findval("Shib-Spoof-Check", rq->headers);
271 if (qstr && g_spoofKey == qstr)
274 if (!m_firsttime || rq->orig_rq)
275 log(SPDebug, "nsapi_shib function running more than once");
277 ~ShibTargetNSAPI() { }
279 const char* getScheme() const {
280 return m_security_active ? "https" : "http";
282 const char* getHostname() const {
283 #ifdef vs_is_default_vs
284 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
285 if (!vs_is_default_vs(request_get_vs(m_rq)))
286 // The beauty here is, a non-default vhost can *only* be accessed if the client
287 // specified the exact name in the Host header. So we can trust the Host header.
288 return pblock_findval("host", m_rq->headers);
291 // In other cases, we're going to rely on the initialization process...
292 return g_ServerName.c_str();
294 int getPort() const {
295 return m_server_portnum;
297 const char* getMethod() const {
298 return pblock_findval("method", m_rq->reqpb);
300 string getContentType() const {
301 char* content_type = nullptr;
302 if (request_header("content-type", &content_type, m_sn, m_rq) != REQ_PROCEED)
304 return content_type ? content_type : "";
306 long getContentLength() const {
308 return m_body.length();
309 char* content_length=nullptr;
310 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED)
312 return content_length ? atoi(content_length) : 0;
314 string getRemoteAddr() const {
315 string ret = AbstractSPRequest::getRemoteAddr();
316 return ret.empty() ? pblock_findval("ip", m_sn->client) : ret;
318 void log(SPLogLevel level, const string& msg) const {
319 AbstractSPRequest::log(level,msg);
321 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
323 const char* getQueryString() const {
324 return pblock_findval("query", m_rq->reqpb);
326 const char* getRequestBody() const {
328 return m_body.c_str();
329 char* content_length=nullptr;
330 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED || !content_length) {
334 else if (atoi(content_length) > 1024*1024) // 1MB?
335 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
338 int cl=atoi(content_length);
340 while (cl && ch != IO_EOF) {
341 ch=netbuf_getc(m_sn->inbuf);
349 throw IOException("Error reading request body from browser.");
350 return m_body.c_str();
353 void clearHeader(const char* rawname, const char* cginame) {
354 if (g_checkSpoofing && m_firsttime && !m_rq->orig_rq) {
355 if (m_allhttp.empty()) {
356 // Populate the set of client-supplied headers for spoof checking.
357 const pb_entry* entry;
358 for (int i=0; i<m_rq->headers->hsize; ++i) {
359 entry = m_rq->headers->ht[i];
361 string cgiversion("HTTP_");
362 const char* pch = entry->param->name;
364 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
367 m_allhttp.insert(cgiversion);
372 if (m_allhttp.count(cginame) > 0)
373 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
375 if (strcmp(rawname, "REMOTE_USER") == 0) {
376 param_free(pblock_remove("remote-user", m_rq->headers));
377 pblock_nvinsert("remote-user", g_unsetHeaderValue.c_str(), m_rq->headers);
380 param_free(pblock_remove(rawname, m_rq->headers));
381 pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
384 void setHeader(const char* name, const char* value) {
385 param_free(pblock_remove(name, m_rq->headers));
386 pblock_nvinsert(name, value, m_rq->headers);
388 string getHeader(const char* name) const {
389 // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
391 int cookie = strcmp(name, "Cookie");
394 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
395 // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
400 n += tolower(*(name++));
401 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
404 return string(hdr ? hdr : "");
406 void setRemoteUser(const char* user) {
407 pblock_nvinsert("auth-user", user, m_rq->vars);
408 param_free(pblock_remove("remote-user", m_rq->headers));
409 pblock_nvinsert("remote-user", user, m_rq->headers);
411 string getRemoteUser() const {
412 const char* ru = pblock_findval("auth-user", m_rq->vars);
415 void setAuthType(const char* authtype) {
416 param_free(pblock_remove("auth-type", m_rq->vars));
418 pblock_nvinsert("auth-type", authtype, m_rq->vars);
420 string getAuthType() const {
421 const char* at = pblock_findval("auth-type", m_rq->vars);
424 void setContentType(const char* type) {
425 // iPlanet seems to have a case folding problem.
426 param_free(pblock_remove("content-type", m_rq->srvhdrs));
427 setResponseHeader("Content-Type", type);
429 void setResponseHeader(const char* name, const char* value) {
430 HTTPResponse::setResponseHeader(name, value);
431 pblock_nvinsert(name, value, m_rq->srvhdrs);
434 long sendResponse(istream& in, long status) {
439 msg.append(buf,in.gcount());
441 pblock_nvinsert("connection","close",m_rq->srvhdrs);
442 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
443 protocol_status(m_sn, m_rq, status, nullptr);
444 protocol_start_response(m_sn, m_rq);
445 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
448 long sendRedirect(const char* url) {
449 HTTPResponse::sendRedirect(url);
450 param_free(pblock_remove("content-type", m_rq->srvhdrs));
451 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
452 pblock_nvinsert("expires", "Wed, 01 Jan 1997 12:00:00 GMT", m_rq->srvhdrs);
453 pblock_nvinsert("cache-control", "private,no-store,no-cache,max-age=0", m_rq->srvhdrs);
454 pblock_nvinsert("location", url, m_rq->srvhdrs);
455 pblock_nvinsert("connection","close",m_rq->srvhdrs);
456 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, nullptr);
457 protocol_start_response(m_sn, m_rq);
460 long returnDecline() { return REQ_NOACTION; }
461 long returnOK() { return REQ_PROCEED; }
462 const vector<string>& getClientCertificates() const {
463 if (m_certs.empty()) {
464 const char* cert = pblock_findval("auth-cert", m_rq->vars);
466 m_certs.push_back(cert);
472 /********************************************************************************/
474 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
476 log_error(LOG_FAILURE,func,sn,rq,msg);
477 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
482 #define FUNC "shibboleth"
483 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
485 string threadid("[");
486 threadid += lexical_cast<string>(getpid()) + "] nsapi_shib";
487 xmltooling::NDC ndc(threadid.c_str());
490 ShibTargetNSAPI stn(pb, sn, rq);
492 // Check user authentication
493 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
494 // If directed, install a spoof key to recognize when we've already cleared headers.
495 if (!g_spoofKey.empty()) {
496 param_free(pblock_remove("Shib-Spoof-Check", rq->headers));
497 pblock_nvinsert("Shib-Spoof-Check", g_spoofKey.c_str(), rq->headers);
499 if (res.first) return (int)res.second;
501 // user authN was okay -- export the assertions now
502 param_free(pblock_remove("auth-user",rq->vars));
504 res = stn.getServiceProvider().doExport(stn);
505 if (res.first) return (int)res.second;
507 // Check the Authorization
508 res = stn.getServiceProvider().doAuthorization(stn);
509 if (res.first) return (int)res.second;
514 catch (std::exception& e) {
515 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
516 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
519 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>("Shibboleth module threw an unknown exception."));
521 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
528 #define FUNC "shib_handler"
529 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
531 string threadid("[");
532 threadid += lexical_cast<string>(getpid()) + "] shib_handler";
533 xmltooling::NDC ndc(threadid.c_str());
536 ShibTargetNSAPI stn(pb, sn, rq);
538 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
539 if (res.first) return (int)res.second;
541 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
543 catch (std::exception& e) {
544 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
545 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
548 log_error(LOG_FAILURE,FUNC,sn,rq,"unknown exception caught in Shibboleth handler");
550 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
556 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
559 SunRequestMapper(const xercesc::DOMElement* e);
560 ~SunRequestMapper() {}
561 Lockable* lock() { return m_mapper->lock(); }
562 void unlock() { m_stKey->setData(nullptr); m_propsKey->setData(nullptr); m_mapper->unlock(); }
563 Settings getSettings(const HTTPRequest& request) const;
565 const PropertySet* getParent() const { return nullptr; }
566 void setParent(const PropertySet*) {}
567 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const;
568 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const;
569 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const;
570 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const;
571 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const;
572 void getAll(map<string,const char*>& properties) const;
573 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
574 const xercesc::DOMElement* getElement() const;
577 scoped_ptr<RequestMapper> m_mapper;
578 scoped_ptr<ThreadKey> m_stKey, m_propsKey;
581 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
583 return new SunRequestMapper(e);
586 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e)
587 : m_mapper(SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e)),
588 m_stKey(ThreadKey::create(nullptr)),
589 m_propsKey(ThreadKey::create(nullptr))
593 RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
595 Settings s=m_mapper->getSettings(request);
596 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
597 m_propsKey->setData((void*)s.first);
598 return pair<const PropertySet*,AccessControl*>(this,s.second);
601 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
603 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
604 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
605 if (stn && !ns && name) {
606 // Override boolean properties.
607 const char* param=pblock_findval(name,stn->m_pb);
608 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
609 return make_pair(true,true);
611 return s ? s->getBool(name,ns) : make_pair(false,false);
614 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
616 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
617 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
618 if (stn && !ns && name) {
619 // Override string properties.
620 if (!strcmp(name,"authType"))
621 return pair<bool,const char*>(true,"shibboleth");
623 const char* param=pblock_findval(name,stn->m_pb);
625 return make_pair(true,param);
628 return s ? s->getString(name,ns) : pair<bool,const char*>(false,nullptr);
631 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
633 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
634 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,nullptr);
637 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
639 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
640 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
641 if (stn && !ns && name) {
642 // Override int properties.
643 const char* param=pblock_findval(name,stn->m_pb);
646 return pair<bool,unsigned int>(true,lexical_cast<unsigned int>(param));
648 catch (bad_lexical_cast&) {
649 return pair<bool,unsigned int>(false,0);
653 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
656 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
658 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
659 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
660 if (stn && !ns && name) {
661 // Override int properties.
662 const char* param=pblock_findval(name,stn->m_pb);
664 return pair<bool,int>(true,atoi(param));
666 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
669 void SunRequestMapper::getAll(map<string,const char*>& properties) const
671 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
672 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
674 s->getAll(properties);
677 properties["authType"] = "shibboleth";
678 const pb_entry* entry;
679 for (int i=0; i<stn->m_pb->hsize; ++i) {
680 entry = stn->m_pb->ht[i];
682 properties[entry->param->name] = entry->param->value;
688 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
690 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
691 return s ? s->getPropertySet(name,ns) : nullptr;
694 const xercesc::DOMElement* SunRequestMapper::getElement() const
696 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
697 return s ? s->getElement() : nullptr;