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);
88 PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
90 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
97 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
99 // Save off a default hostname for this virtual server.
100 char* name=pblock_findval("server-name",pb);
104 name=server_hostname;
108 name=util_hostname();
114 pblock_nvinsert("error","unable to determine web server hostname",pb);
120 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
122 const char* schemadir=pblock_findval("shib-schemas",pb);
123 const char* prefix=pblock_findval("shib-prefix",pb);
125 g_Config=&SPConfig::getConfig();
126 g_Config->setFeatures(
129 SPConfig::RequestMapping |
130 SPConfig::InProcess |
134 if (!g_Config->init(schemadir,prefix)) {
136 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
140 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&SunRequestMapFactory);
143 if (!g_Config->instantiate(pblock_findval("shib-config",pb), true))
144 throw runtime_error("unknown error");
146 catch (exception& ex) {
147 pblock_nvinsert("error",ex.what(),pb);
153 daemon_atrestart(nsapi_shib_exit,NULL);
155 ServiceProvider* sp=g_Config->getServiceProvider();
157 const PropertySet* props=sp->getPropertySet("InProcess");
159 pair<bool,bool> flag=props->getBool("checkSpoofing");
160 g_checkSpoofing = !flag.first || flag.second;
161 flag=props->getBool("catchAll");
162 g_catchAll = flag.first && flag.second;
164 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
165 if (unsetValue.first)
166 g_unsetHeaderValue = unsetValue.second;
167 if (g_checkSpoofing) {
168 unsetValue=props->getString("spoofKey");
169 if (unsetValue.first)
170 g_spoofKey = unsetValue.second;
173 unsigned int randkey=0,randkey2=0,randkey3=0,randkey4=0;
174 if (rand_s(&randkey) == 0 && rand_s(&randkey2) == 0 && rand_s(&randkey3) == 0 && rand_s(&randkey4) == 0) {
175 ostringstream keystr;
176 keystr << randkey << randkey2 << randkey3 << randkey4;
177 g_spoofKey = keystr.str();
180 pblock_nvinsert("error", "module failed to generate a random anti-spoofing key (if this is Windows 2000 set one manually)", pb);
192 /********************************************************************************/
193 // NSAPI Shib Target Subclass
195 class ShibTargetNSAPI : public AbstractSPRequest
197 mutable string m_body;
198 mutable bool m_gotBody,m_firsttime;
199 bool m_security_active;
200 int m_server_portnum;
201 mutable vector<string> m_certs;
202 set<string> m_allhttp;
209 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq)
210 : AbstractSPRequest(SHIBSP_LOGCAT".NSAPI"),
211 m_gotBody(false), m_firsttime(true), m_security_active(false), m_server_portnum(0), m_pb(pb), m_sn(sn), m_rq(rq) {
213 // To determine whether SSL is active or not, we're supposed to rely
214 // on the security_active macro. For iPlanet 4.x, this works.
215 // For Sun 7.x, it's useless and appears to be on or off based
216 // on whether ANY SSL support is enabled for a vhost. Sun 6.x is unknown.
217 // As a fix, there's a conf variable called $security that can be mapped
218 // into a function parameter: security_active="$security"
219 // We check for this parameter, and rely on the macro if it isn't set.
220 // This doubles as a scheme virtualizer for load balanced scenarios
221 // since you can set the parameter to 1 or 0 as needed.
222 const char* sa = pblock_findval("security_active", m_pb);
224 m_security_active = (*sa == '1');
225 else if (security_active)
226 m_security_active = true;
228 m_security_active = false;
230 // A similar issue exists for the port. server_portnum is no longer
231 // working on at least Sun 7.x, and returns the first listener's port
232 // rather than whatever port is actually used for the request. Nice job, Sun.
233 sa = pblock_findval("server_portnum", m_pb);
234 m_server_portnum = (sa && *sa) ? atoi(sa) : server_portnum;
236 const char* uri = pblock_findval("uri", rq->reqpb);
237 const char* qstr = pblock_findval("query", rq->reqpb);
240 string temp = string(uri) + '?' + qstr;
241 setRequestURI(temp.c_str());
247 // See if this is the first time we've run.
248 if (!g_spoofKey.empty()) {
249 qstr = pblock_findval("Shib-Spoof-Check", rq->headers);
250 if (qstr && g_spoofKey == qstr)
253 if (!m_firsttime || rq->orig_rq)
254 log(SPDebug, "nsapi_shib function running more than once");
256 ~ShibTargetNSAPI() { }
258 const char* getScheme() const {
259 return m_security_active ? "https" : "http";
261 const char* getHostname() const {
262 #ifdef vs_is_default_vs
263 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
264 if (!vs_is_default_vs(request_get_vs(m_rq)))
265 // The beauty here is, a non-default vhost can *only* be accessed if the client
266 // specified the exact name in the Host header. So we can trust the Host header.
267 return pblock_findval("host", m_rq->headers);
270 // In other cases, we're going to rely on the initialization process...
271 return g_ServerName.c_str();
273 int getPort() const {
274 return m_server_portnum;
276 const char* getMethod() const {
277 return pblock_findval("method", m_rq->reqpb);
279 string getContentType() const {
280 char* content_type = NULL;
281 if (request_header("content-type", &content_type, m_sn, m_rq) != REQ_PROCEED)
283 return content_type ? content_type : "";
285 long getContentLength() const {
287 return m_body.length();
288 char* content_length=NULL;
289 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED)
291 return content_length ? atoi(content_length) : 0;
293 string getRemoteAddr() const {
294 string ret = AbstractSPRequest::getRemoteAddr();
295 return ret.empty() ? pblock_findval("ip", m_sn->client) : ret;
297 void log(SPLogLevel level, const string& msg) const {
298 AbstractSPRequest::log(level,msg);
300 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
302 const char* getQueryString() const {
303 return pblock_findval("query", m_rq->reqpb);
305 const char* getRequestBody() const {
307 return m_body.c_str();
308 char* content_length=NULL;
309 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED || !content_length) {
313 else if (atoi(content_length) > 1024*1024) // 1MB?
314 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
317 int cl=atoi(content_length);
319 while (cl && ch != IO_EOF) {
320 ch=netbuf_getc(m_sn->inbuf);
328 throw IOException("Error reading request body from browser.");
329 return m_body.c_str();
332 void clearHeader(const char* rawname, const char* cginame) {
333 if (g_checkSpoofing && m_firsttime && !m_rq->orig_rq) {
334 if (m_allhttp.empty()) {
335 // Populate the set of client-supplied headers for spoof checking.
336 const pb_entry* entry;
337 for (int i=0; i<m_rq->headers->hsize; ++i) {
338 entry = m_rq->headers->ht[i];
340 string cgiversion("HTTP_");
341 const char* pch = entry->param->name;
343 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
346 m_allhttp.insert(cgiversion);
351 if (m_allhttp.count(cginame) > 0)
352 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
354 if (strcmp(rawname, "REMOTE_USER") == 0) {
355 param_free(pblock_remove("remote-user", m_rq->headers));
356 pblock_nvinsert("remote-user", g_unsetHeaderValue.c_str(), m_rq->headers);
359 param_free(pblock_remove(rawname, m_rq->headers));
360 pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
363 void setHeader(const char* name, const char* value) {
364 param_free(pblock_remove(name, m_rq->headers));
365 pblock_nvinsert(name, value, m_rq->headers);
367 string getHeader(const char* name) const {
368 // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
370 int cookie = strcmp(name, "Cookie");
373 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
374 // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
379 n += tolower(*(name++));
380 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
383 return string(hdr ? hdr : "");
385 void setRemoteUser(const char* user) {
386 pblock_nvinsert("auth-user", user, m_rq->vars);
387 param_free(pblock_remove("remote-user", m_rq->headers));
388 pblock_nvinsert("remote-user", user, m_rq->headers);
390 string getRemoteUser() const {
391 const char* ru = pblock_findval("auth-user", m_rq->vars);
394 void setAuthType(const char* authtype) {
395 param_free(pblock_remove("auth-type", m_rq->vars));
397 pblock_nvinsert("auth-type", authtype, m_rq->vars);
399 string getAuthType() const {
400 const char* at = pblock_findval("auth-type", m_rq->vars);
403 void setContentType(const char* type) {
404 // iPlanet seems to have a case folding problem.
405 param_free(pblock_remove("content-type", m_rq->srvhdrs));
406 setResponseHeader("Content-Type", type);
408 void setResponseHeader(const char* name, const char* value) {
409 pblock_nvinsert(name, value, m_rq->srvhdrs);
412 long sendResponse(istream& in, long status) {
417 msg.append(buf,in.gcount());
419 pblock_nvinsert("connection","close",m_rq->srvhdrs);
420 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
421 protocol_status(m_sn, m_rq, status, NULL);
422 protocol_start_response(m_sn, m_rq);
423 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
426 long sendRedirect(const char* url) {
427 param_free(pblock_remove("content-type", m_rq->srvhdrs));
428 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
429 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
430 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
431 pblock_nvinsert("location", url, m_rq->srvhdrs);
432 pblock_nvinsert("connection","close",m_rq->srvhdrs);
433 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
434 protocol_start_response(m_sn, m_rq);
437 long returnDecline() { return REQ_NOACTION; }
438 long returnOK() { return REQ_PROCEED; }
439 const vector<string>& getClientCertificates() const {
440 if (m_certs.empty()) {
441 const char* cert = pblock_findval("auth-cert", m_rq->vars);
443 m_certs.push_back(cert);
449 /********************************************************************************/
451 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
453 log_error(LOG_FAILURE,func,sn,rq,msg);
454 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
459 #define FUNC "shibboleth"
460 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
462 ostringstream threadid;
463 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
464 xmltooling::NDC ndc(threadid.str().c_str());
467 ShibTargetNSAPI stn(pb, sn, rq);
469 // Check user authentication
470 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
471 // If directed, install a spoof key to recognize when we've already cleared headers.
472 if (!g_spoofKey.empty()) {
473 param_free(pblock_remove("Shib-Spoof-Check", rq->headers));
474 pblock_nvinsert("Shib-Spoof-Check", g_spoofKey.c_str(), rq->headers);
476 if (res.first) return (int)res.second;
478 // user authN was okay -- export the assertions now
479 param_free(pblock_remove("auth-user",rq->vars));
481 res = stn.getServiceProvider().doExport(stn);
482 if (res.first) return (int)res.second;
484 // Check the Authorization
485 res = stn.getServiceProvider().doAuthorization(stn);
486 if (res.first) return (int)res.second;
491 catch (exception& e) {
492 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
493 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
496 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>("Shibboleth module threw an unknown exception."));
498 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
505 #define FUNC "shib_handler"
506 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
508 ostringstream threadid;
509 threadid << "[" << getpid() << "] shib_handler" << '\0';
510 xmltooling::NDC ndc(threadid.str().c_str());
513 ShibTargetNSAPI stn(pb, sn, rq);
515 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
516 if (res.first) return (int)res.second;
518 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
520 catch (exception& e) {
521 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
522 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
525 log_error(LOG_FAILURE,FUNC,sn,rq,"unknown exception caught in Shibboleth handler");
527 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
533 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
536 SunRequestMapper(const xercesc::DOMElement* e);
537 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
538 Lockable* lock() { return m_mapper->lock(); }
539 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
540 Settings getSettings(const HTTPRequest& request) const;
542 const PropertySet* getParent() const { return NULL; }
543 void setParent(const PropertySet*) {}
544 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
545 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
546 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
547 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
548 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
549 void getAll(map<string,const char*>& properties) const;
550 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
551 const xercesc::DOMElement* getElement() const;
554 RequestMapper* m_mapper;
556 ThreadKey* m_propsKey;
559 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
561 return new SunRequestMapper(e);
564 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
566 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
567 m_stKey=ThreadKey::create(NULL);
568 m_propsKey=ThreadKey::create(NULL);
571 RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
573 Settings s=m_mapper->getSettings(request);
574 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
575 m_propsKey->setData((void*)s.first);
576 return pair<const PropertySet*,AccessControl*>(this,s.second);
579 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
581 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
582 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
583 if (stn && !ns && name) {
584 // Override boolean properties.
585 const char* param=pblock_findval(name,stn->m_pb);
586 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
587 return make_pair(true,true);
589 return s ? s->getBool(name,ns) : make_pair(false,false);
592 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
594 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
595 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
596 if (stn && !ns && name) {
597 // Override string properties.
598 if (!strcmp(name,"authType"))
599 return pair<bool,const char*>(true,"shibboleth");
601 const char* param=pblock_findval(name,stn->m_pb);
603 return make_pair(true,param);
606 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
609 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
611 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
612 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
615 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
617 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
618 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
619 if (stn && !ns && name) {
620 // Override int properties.
621 const char* param=pblock_findval(name,stn->m_pb);
623 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
625 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
628 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
630 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
631 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
632 if (stn && !ns && name) {
633 // Override int properties.
634 const char* param=pblock_findval(name,stn->m_pb);
636 return pair<bool,int>(true,atoi(param));
638 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
641 void SunRequestMapper::getAll(map<string,const char*>& properties) const
643 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
644 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
646 s->getAll(properties);
649 properties["authType"] = "shibboleth";
650 const pb_entry* entry;
651 for (int i=0; i<stn->m_pb->hsize; ++i) {
652 entry = stn->m_pb->ht[i];
654 properties[entry->param->name] = entry->param->value;
660 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
662 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
663 return s ? s->getPropertySet(name,ns) : NULL;
666 const xercesc::DOMElement* SunRequestMapper::getElement() const
668 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
669 return s ? s->getElement() : NULL;