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 <xmltooling/XMLToolingConfig.h>
53 #include <xmltooling/util/NDC.h>
54 #include <xmltooling/util/Threads.h>
55 #include <xmltooling/util/XMLConstants.h>
56 #include <xmltooling/util/XMLHelper.h>
57 #include <xercesc/util/XMLUniDefs.hpp>
74 using namespace shibsp;
75 using namespace xmltooling;
76 using namespace boost;
79 // macros to output text to client
80 #define NET_WRITE(str) \
81 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
84 SPConfig* g_Config=nullptr;
86 string g_unsetHeaderValue;
88 bool g_checkSpoofing = true;
89 bool g_catchAll = false;
91 static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
92 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
94 void _my_invalid_parameter_handler(
95 const wchar_t * expression,
96 const wchar_t * function,
105 PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
107 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
114 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
116 // Save off a default hostname for this virtual server.
117 char* name=pblock_findval("server-name",pb);
121 name=server_hostname;
125 name=util_hostname();
131 pblock_nvinsert("error","unable to determine web server hostname",pb);
137 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
139 const char* schemadir=pblock_findval("shib-schemas",pb);
140 const char* prefix=pblock_findval("shib-prefix",pb);
142 g_Config=&SPConfig::getConfig();
143 g_Config->setFeatures(
146 SPConfig::RequestMapping |
147 SPConfig::InProcess |
151 if (!g_Config->init(schemadir,prefix)) {
153 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
157 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&SunRequestMapFactory);
160 if (!g_Config->instantiate(pblock_findval("shib-config",pb), true))
161 throw runtime_error("unknown error");
163 catch (std::exception& ex) {
164 pblock_nvinsert("error",ex.what(),pb);
170 daemon_atrestart(nsapi_shib_exit,nullptr);
172 ServiceProvider* sp=g_Config->getServiceProvider();
174 const PropertySet* props=sp->getPropertySet("InProcess");
176 pair<bool,bool> flag=props->getBool("checkSpoofing");
177 g_checkSpoofing = !flag.first || flag.second;
178 flag=props->getBool("catchAll");
179 g_catchAll = flag.first && flag.second;
181 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
182 if (unsetValue.first)
183 g_unsetHeaderValue = unsetValue.second;
184 if (g_checkSpoofing) {
185 unsetValue=props->getString("spoofKey");
186 if (unsetValue.first)
187 g_spoofKey = unsetValue.second;
190 _invalid_parameter_handler old = _set_invalid_parameter_handler(_my_invalid_parameter_handler);
191 unsigned int randkey=0,randkey2=0,randkey3=0,randkey4=0;
192 if (rand_s(&randkey) == 0 && rand_s(&randkey2) == 0 && rand_s(&randkey3) == 0 && rand_s(&randkey4) == 0) {
193 _set_invalid_parameter_handler(old);
194 g_spoofKey = lexical_cast<string>(randkey) + lexical_cast<string>(randkey2) +
195 lexical_cast<string>(randkey3) + lexical_cast<string>(randkey4);
198 _set_invalid_parameter_handler(old);
199 pblock_nvinsert("error", "module failed to generate a random anti-spoofing key (if this is Windows 2000 set one manually)", pb);
200 locker.assign(); // pops lock on SP config
212 /********************************************************************************/
213 // NSAPI Shib Target Subclass
215 class ShibTargetNSAPI : public AbstractSPRequest
217 mutable string m_body;
218 mutable bool m_gotBody,m_firsttime;
219 bool m_security_active;
220 int m_server_portnum;
221 mutable vector<string> m_certs;
222 set<string> m_allhttp;
229 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq)
230 : AbstractSPRequest(SHIBSP_LOGCAT".NSAPI"),
231 m_gotBody(false), m_firsttime(true), m_security_active(false), m_server_portnum(0), m_pb(pb), m_sn(sn), m_rq(rq) {
233 // To determine whether SSL is active or not, we're supposed to rely
234 // on the security_active macro. For iPlanet 4.x, this works.
235 // For Sun 7.x, it's useless and appears to be on or off based
236 // on whether ANY SSL support is enabled for a vhost. Sun 6.x is unknown.
237 // As a fix, there's a conf variable called $security that can be mapped
238 // into a function parameter: security_active="$security"
239 // We check for this parameter, and rely on the macro if it isn't set.
240 // This doubles as a scheme virtualizer for load balanced scenarios
241 // since you can set the parameter to 1 or 0 as needed.
242 const char* sa = pblock_findval("security_active", m_pb);
244 m_security_active = (*sa == '1');
245 else if (security_active)
246 m_security_active = true;
248 m_security_active = false;
250 // A similar issue exists for the port. server_portnum is no longer
251 // working on at least Sun 7.x, and returns the first listener's port
252 // rather than whatever port is actually used for the request. Nice job, Sun.
253 sa = pblock_findval("server_portnum", m_pb);
254 m_server_portnum = (sa && *sa) ? atoi(sa) : server_portnum;
256 const char* uri = pblock_findval("uri", rq->reqpb);
257 const char* qstr = pblock_findval("query", rq->reqpb);
260 string temp = string(uri) + '?' + qstr;
261 setRequestURI(temp.c_str());
267 // See if this is the first time we've run.
268 if (!g_spoofKey.empty()) {
269 qstr = pblock_findval("Shib-Spoof-Check", rq->headers);
270 if (qstr && g_spoofKey == qstr)
273 if (!m_firsttime || rq->orig_rq)
274 log(SPDebug, "nsapi_shib function running more than once");
276 ~ShibTargetNSAPI() { }
278 const char* getScheme() const {
279 return m_security_active ? "https" : "http";
281 const char* getHostname() const {
282 #ifdef vs_is_default_vs
283 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
284 if (!vs_is_default_vs(request_get_vs(m_rq)))
285 // The beauty here is, a non-default vhost can *only* be accessed if the client
286 // specified the exact name in the Host header. So we can trust the Host header.
287 return pblock_findval("host", m_rq->headers);
290 // In other cases, we're going to rely on the initialization process...
291 return g_ServerName.c_str();
293 int getPort() const {
294 return m_server_portnum;
296 const char* getMethod() const {
297 return pblock_findval("method", m_rq->reqpb);
299 string getContentType() const {
300 char* content_type = nullptr;
301 if (request_header("content-type", &content_type, m_sn, m_rq) != REQ_PROCEED)
303 return content_type ? content_type : "";
305 long getContentLength() const {
307 return m_body.length();
308 char* content_length=nullptr;
309 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED)
311 return content_length ? atoi(content_length) : 0;
313 string getRemoteAddr() const {
314 string ret = AbstractSPRequest::getRemoteAddr();
315 return ret.empty() ? pblock_findval("ip", m_sn->client) : ret;
317 void log(SPLogLevel level, const string& msg) const {
318 AbstractSPRequest::log(level,msg);
320 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
322 const char* getQueryString() const {
323 return pblock_findval("query", m_rq->reqpb);
325 const char* getRequestBody() const {
327 return m_body.c_str();
328 char* content_length=nullptr;
329 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED || !content_length) {
333 else if (atoi(content_length) > 1024*1024) // 1MB?
334 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
337 int cl=atoi(content_length);
339 while (cl && ch != IO_EOF) {
340 ch=netbuf_getc(m_sn->inbuf);
348 throw IOException("Error reading request body from browser.");
349 return m_body.c_str();
352 void clearHeader(const char* rawname, const char* cginame) {
353 if (g_checkSpoofing && m_firsttime && !m_rq->orig_rq) {
354 if (m_allhttp.empty()) {
355 // Populate the set of client-supplied headers for spoof checking.
356 const pb_entry* entry;
357 for (int i=0; i<m_rq->headers->hsize; ++i) {
358 entry = m_rq->headers->ht[i];
360 string cgiversion("HTTP_");
361 const char* pch = entry->param->name;
363 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
366 m_allhttp.insert(cgiversion);
371 if (m_allhttp.count(cginame) > 0)
372 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
374 if (strcmp(rawname, "REMOTE_USER") == 0) {
375 param_free(pblock_remove("remote-user", m_rq->headers));
376 pblock_nvinsert("remote-user", g_unsetHeaderValue.c_str(), m_rq->headers);
379 param_free(pblock_remove(rawname, m_rq->headers));
380 pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
383 void setHeader(const char* name, const char* value) {
384 param_free(pblock_remove(name, m_rq->headers));
385 pblock_nvinsert(name, value, m_rq->headers);
387 string getHeader(const char* name) const {
388 // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
390 int cookie = strcmp(name, "Cookie");
393 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
394 // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
399 n += tolower(*(name++));
400 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
403 return string(hdr ? hdr : "");
405 void setRemoteUser(const char* user) {
406 pblock_nvinsert("auth-user", user, m_rq->vars);
407 param_free(pblock_remove("remote-user", m_rq->headers));
408 pblock_nvinsert("remote-user", user, m_rq->headers);
410 string getRemoteUser() const {
411 const char* ru = pblock_findval("auth-user", m_rq->vars);
414 void setAuthType(const char* authtype) {
415 param_free(pblock_remove("auth-type", m_rq->vars));
417 pblock_nvinsert("auth-type", authtype, m_rq->vars);
419 string getAuthType() const {
420 const char* at = pblock_findval("auth-type", m_rq->vars);
423 void setContentType(const char* type) {
424 // iPlanet seems to have a case folding problem.
425 param_free(pblock_remove("content-type", m_rq->srvhdrs));
426 setResponseHeader("Content-Type", type);
428 void setResponseHeader(const char* name, const char* value) {
429 HTTPResponse::setResponseHeader(name, value);
430 pblock_nvinsert(name, value, m_rq->srvhdrs);
433 long sendResponse(istream& in, long status) {
438 msg.append(buf,in.gcount());
440 pblock_nvinsert("connection","close",m_rq->srvhdrs);
441 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
442 protocol_status(m_sn, m_rq, status, nullptr);
443 protocol_start_response(m_sn, m_rq);
444 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
447 long sendRedirect(const char* url) {
448 HTTPResponse::sendRedirect(url);
449 param_free(pblock_remove("content-type", m_rq->srvhdrs));
450 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
451 pblock_nvinsert("expires", "Wed, 01 Jan 1997 12:00:00 GMT", m_rq->srvhdrs);
452 pblock_nvinsert("cache-control", "private,no-store,no-cache,max-age=0", m_rq->srvhdrs);
453 pblock_nvinsert("location", url, m_rq->srvhdrs);
454 pblock_nvinsert("connection","close",m_rq->srvhdrs);
455 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, nullptr);
456 protocol_start_response(m_sn, m_rq);
459 long returnDecline() { return REQ_NOACTION; }
460 long returnOK() { return REQ_PROCEED; }
461 const vector<string>& getClientCertificates() const {
462 if (m_certs.empty()) {
463 const char* cert = pblock_findval("auth-cert", m_rq->vars);
465 m_certs.push_back(cert);
471 /********************************************************************************/
473 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
475 log_error(LOG_FAILURE,func,sn,rq,msg);
476 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
481 #define FUNC "shibboleth"
482 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
484 string threadid("[");
485 threadid += lexical_cast<string>(getpid()) + "] nsapi_shib";
486 xmltooling::NDC ndc(threadid.c_str());
489 ShibTargetNSAPI stn(pb, sn, rq);
491 // Check user authentication
492 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
493 // If directed, install a spoof key to recognize when we've already cleared headers.
494 if (!g_spoofKey.empty()) {
495 param_free(pblock_remove("Shib-Spoof-Check", rq->headers));
496 pblock_nvinsert("Shib-Spoof-Check", g_spoofKey.c_str(), rq->headers);
498 if (res.first) return (int)res.second;
500 // user authN was okay -- export the assertions now
501 param_free(pblock_remove("auth-user",rq->vars));
503 res = stn.getServiceProvider().doExport(stn);
504 if (res.first) return (int)res.second;
506 // Check the Authorization
507 res = stn.getServiceProvider().doAuthorization(stn);
508 if (res.first) return (int)res.second;
513 catch (std::exception& e) {
514 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
515 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
518 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>("Shibboleth module threw an unknown exception."));
520 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
527 #define FUNC "shib_handler"
528 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
530 string threadid("[");
531 threadid += lexical_cast<string>(getpid()) + "] shib_handler";
532 xmltooling::NDC ndc(threadid.c_str());
535 ShibTargetNSAPI stn(pb, sn, rq);
537 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
538 if (res.first) return (int)res.second;
540 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
542 catch (std::exception& e) {
543 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
544 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
547 log_error(LOG_FAILURE,FUNC,sn,rq,"unknown exception caught in Shibboleth handler");
549 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
555 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
558 SunRequestMapper(const xercesc::DOMElement* e);
559 ~SunRequestMapper() {}
560 Lockable* lock() { return m_mapper->lock(); }
561 void unlock() { m_stKey->setData(nullptr); m_propsKey->setData(nullptr); m_mapper->unlock(); }
562 Settings getSettings(const HTTPRequest& request) const;
564 const PropertySet* getParent() const { return nullptr; }
565 void setParent(const PropertySet*) {}
566 pair<bool,bool> getBool(const char* name, const char* ns=nullptr) const;
567 pair<bool,const char*> getString(const char* name, const char* ns=nullptr) const;
568 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=nullptr) const;
569 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=nullptr) const;
570 pair<bool,int> getInt(const char* name, const char* ns=nullptr) const;
571 void getAll(map<string,const char*>& properties) const;
572 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
573 const xercesc::DOMElement* getElement() const;
576 scoped_ptr<RequestMapper> m_mapper;
577 scoped_ptr<ThreadKey> m_stKey, m_propsKey;
580 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
582 return new SunRequestMapper(e);
585 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e)
586 : m_mapper(SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e)),
587 m_stKey(ThreadKey::create(nullptr)),
588 m_propsKey(ThreadKey::create(nullptr))
592 RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
594 Settings s=m_mapper->getSettings(request);
595 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
596 m_propsKey->setData((void*)s.first);
597 return pair<const PropertySet*,AccessControl*>(this,s.second);
600 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
602 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
603 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
604 if (stn && !ns && name) {
605 // Override boolean properties.
606 const char* param=pblock_findval(name,stn->m_pb);
607 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
608 return make_pair(true,true);
610 return s ? s->getBool(name,ns) : make_pair(false,false);
613 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
615 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
616 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
617 if (stn && !ns && name) {
618 // Override string properties.
619 if (!strcmp(name,"authType"))
620 return pair<bool,const char*>(true,"shibboleth");
622 const char* param=pblock_findval(name,stn->m_pb);
624 return make_pair(true,param);
627 return s ? s->getString(name,ns) : pair<bool,const char*>(false,nullptr);
630 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
632 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
633 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,nullptr);
636 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
638 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
639 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
640 if (stn && !ns && name) {
641 // Override int properties.
642 const char* param=pblock_findval(name,stn->m_pb);
645 return pair<bool,unsigned int>(true,lexical_cast<unsigned int>(param));
647 catch (bad_lexical_cast&) {
648 return pair<bool,unsigned int>(false,0);
652 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
655 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
657 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
658 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
659 if (stn && !ns && name) {
660 // Override int properties.
661 const char* param=pblock_findval(name,stn->m_pb);
663 return pair<bool,int>(true,atoi(param));
665 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
668 void SunRequestMapper::getAll(map<string,const char*>& properties) const
670 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
671 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
673 s->getAll(properties);
676 properties["authType"] = "shibboleth";
677 const pb_entry* entry;
678 for (int i=0; i<stn->m_pb->hsize; ++i) {
679 entry = stn->m_pb->ht[i];
681 properties[entry->param->name] = entry->param->value;
687 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
689 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
690 return s ? s->getPropertySet(name,ns) : nullptr;
693 const xercesc::DOMElement* SunRequestMapper::getElement() const
695 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
696 return s ? s->getElement() : nullptr;