2 * Copyright 2001-2007 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
36 #include <shibsp/AbstractSPRequest.h>
37 #include <shibsp/RequestMapper.h>
38 #include <shibsp/SPConfig.h>
39 #include <shibsp/ServiceProvider.h>
40 #include <xmltooling/XMLToolingConfig.h>
41 #include <xmltooling/util/NDC.h>
42 #include <xmltooling/util/Threads.h>
43 #include <xmltooling/util/XMLConstants.h>
44 #include <xmltooling/util/XMLHelper.h>
45 #include <xercesc/util/XMLUniDefs.hpp>
67 using namespace shibsp;
68 using namespace xmltooling;
71 // macros to output text to client
72 #define NET_WRITE(str) \
73 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
76 SPConfig* g_Config=NULL;
78 string g_ServerScheme;
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);
119 name=pblock_findval("server-scheme",pb);
123 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
125 const char* schemadir=pblock_findval("shib-schemas",pb);
126 const char* prefix=pblock_findval("shib-prefix",pb);
128 g_Config=&SPConfig::getConfig();
129 g_Config->setFeatures(
132 SPConfig::RequestMapping |
133 SPConfig::InProcess |
137 if (!g_Config->init(schemadir,prefix)) {
139 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
143 g_Config->RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&SunRequestMapFactory);
146 if (!g_Config->instantiate(pblock_findval("shib-config",pb), true))
147 throw runtime_error("unknown error");
149 catch (exception& ex) {
150 pblock_nvinsert("error",ex.what(),pb);
156 daemon_atrestart(nsapi_shib_exit,NULL);
158 ServiceProvider* sp=g_Config->getServiceProvider();
160 const PropertySet* props=sp->getPropertySet("InProcess");
162 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
163 if (unsetValue.first)
164 g_unsetHeaderValue = unsetValue.second;
165 pair<bool,bool> flag=props->getBool("checkSpoofing");
166 g_checkSpoofing = !flag.first || flag.second;
167 if (g_checkSpoofing) {
168 unsetValue=props->getString("spoofKey");
169 if (unsetValue.first)
170 g_spoofKey = unsetValue.second;
172 flag=props->getBool("catchAll");
173 g_catchAll = flag.first && flag.second;
178 /********************************************************************************/
179 // NSAPI Shib Target Subclass
181 class ShibTargetNSAPI : public AbstractSPRequest
183 mutable string m_body;
184 mutable bool m_gotBody,m_firsttime;
185 mutable vector<string> m_certs;
186 set<string> m_allhttp;
193 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq)
194 : AbstractSPRequest(SHIBSP_LOGCAT".NSAPI"), m_gotBody(false), m_firsttime(true), m_pb(pb), m_sn(sn), m_rq(rq) {
196 const char* uri=pblock_findval("uri", rq->reqpb);
197 const char* qstr=pblock_findval("query", rq->reqpb);
200 string temp = string(uri) + '?' + qstr;
201 setRequestURI(temp.c_str());
207 // See if this is the first time we've run.
208 if (!g_spoofKey.empty()) {
209 qstr = pblock_findval("Shib-Spoof-Check", rq->headers);
210 if (qstr && g_spoofKey == qstr)
213 if (!m_firsttime || rq->orig_rq)
214 log(SPDebug, "nsapi_shib function running more than once");
216 ~ShibTargetNSAPI() { }
218 const char* getScheme() const {
219 return security_active ? "https" : "http";
221 const char* getHostname() const {
222 #ifdef vs_is_default_vs
223 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
224 if (!vs_is_default_vs(request_get_vs(m_rq)))
225 // The beauty here is, a non-default vhost can *only* be accessed if the client
226 // specified the exact name in the Host header. So we can trust the Host header.
227 return pblock_findval("host", m_rq->headers);
230 // In other cases, we're going to rely on the initialization process...
231 return g_ServerName.c_str();
233 int getPort() const {
234 return server_portnum;
236 const char* getMethod() const {
237 return pblock_findval("method", m_rq->reqpb);
239 string getContentType() const {
240 char* content_type = NULL;
241 if (request_header("content-type", &content_type, m_sn, m_rq) != REQ_PROCEED)
243 return content_type ? content_type : "";
245 long getContentLength() const {
247 return m_body.length();
248 char* content_length=NULL;
249 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED)
251 return content_length ? atoi(content_length) : 0;
253 string getRemoteAddr() const {
254 string ret = AbstractSPRequest::getRemoteAddr();
255 return ret.empty() ? pblock_findval("ip", m_sn->client) : ret;
257 void log(SPLogLevel level, const string& msg) const {
258 AbstractSPRequest::log(level,msg);
260 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
262 const char* getQueryString() const {
263 return pblock_findval("query", m_rq->reqpb);
265 const char* getRequestBody() const {
267 return m_body.c_str();
268 char* content_length=NULL;
269 if (request_header("content-length", &content_length, m_sn, m_rq) != REQ_PROCEED || !content_length) {
273 else if (atoi(content_length) > 1024*1024) // 1MB?
274 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
277 int cl=atoi(content_length);
279 while (cl && ch != IO_EOF) {
280 ch=netbuf_getc(m_sn->inbuf);
288 throw IOException("Error reading request body from browser.");
289 return m_body.c_str();
292 void clearHeader(const char* rawname, const char* cginame) {
293 if (g_checkSpoofing && m_firsttime && !m_rq->orig_rq) {
294 if (m_allhttp.empty()) {
295 // Populate the set of client-supplied headers for spoof checking.
296 const pb_entry* entry;
297 for (int i=0; i<m_rq->headers->hsize; ++i) {
298 entry = m_rq->headers->ht[i];
300 string cgiversion("HTTP_");
301 const char* pch = entry->param->name;
303 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
306 m_allhttp.insert(cgiversion);
311 if (m_allhttp.count(cginame) > 0)
312 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
314 if (strcmp(rawname, "REMOTE_USER") == 0) {
315 param_free(pblock_remove("remote-user", m_rq->headers));
316 pblock_nvinsert("remote-user", g_unsetHeaderValue.c_str(), m_rq->headers);
319 param_free(pblock_remove(rawname, m_rq->headers));
320 pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
323 void setHeader(const char* name, const char* value) {
324 param_free(pblock_remove(name, m_rq->headers));
325 pblock_nvinsert(name, value, m_rq->headers);
327 string getHeader(const char* name) const {
328 // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
330 int cookie = strcmp(name, "Cookie");
333 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
334 // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
339 n += tolower(*(name++));
340 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
343 return string(hdr ? hdr : "");
345 void setRemoteUser(const char* user) {
346 pblock_nvinsert("auth-user", user, m_rq->vars);
347 param_free(pblock_remove("remote-user", m_rq->headers));
348 pblock_nvinsert("remote-user", user, m_rq->headers);
350 string getRemoteUser() const {
351 const char* ru = pblock_findval("auth-user", m_rq->vars);
354 void setResponseHeader(const char* name, const char* value) {
355 pblock_nvinsert(name, value, m_rq->srvhdrs);
358 long sendResponse(istream& in, long status) {
363 msg.append(buf,in.gcount());
365 pblock_nvinsert("connection","close",m_rq->srvhdrs);
366 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
367 protocol_status(m_sn, m_rq, status, NULL);
368 protocol_start_response(m_sn, m_rq);
369 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
372 long sendRedirect(const char* url) {
373 param_free(pblock_remove("content-type", m_rq->srvhdrs));
374 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
375 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
376 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
377 pblock_nvinsert("location", url, m_rq->srvhdrs);
378 pblock_nvinsert("connection","close",m_rq->srvhdrs);
379 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
380 protocol_start_response(m_sn, m_rq);
383 long returnDecline() { return REQ_NOACTION; }
384 long returnOK() { return REQ_PROCEED; }
385 const vector<string>& getClientCertificates() const {
386 if (m_certs.empty()) {
387 const char* cert = pblock_findval("auth-cert", m_rq->vars);
389 m_certs.push_back(cert);
395 /********************************************************************************/
397 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
399 log_error(LOG_FAILURE,func,sn,rq,msg);
400 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
405 #define FUNC "shibboleth"
406 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
408 ostringstream threadid;
409 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
410 xmltooling::NDC ndc(threadid.str().c_str());
413 ShibTargetNSAPI stn(pb, sn, rq);
415 // Check user authentication
416 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
417 // If directed, install a spoof key to recognize when we've already cleared headers.
418 if (!g_spoofKey.empty()) {
419 param_free(pblock_remove("Shib-Spoof-Check", rq->headers));
420 pblock_nvinsert("Shib-Spoof-Check", g_spoofKey.c_str(), rq->headers);
422 if (res.first) return (int)res.second;
424 // user authN was okay -- export the assertions now
425 param_free(pblock_remove("auth-user",rq->vars));
427 // This seems to be required in order to eventually set
428 // the auth-user var.
429 pblock_nvinsert("auth-type","shibboleth",rq->vars);
431 res = stn.getServiceProvider().doExport(stn);
432 if (res.first) return (int)res.second;
434 // Check the Authorization
435 res = stn.getServiceProvider().doAuthorization(stn);
436 if (res.first) return (int)res.second;
441 catch (exception& e) {
442 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
443 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
446 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>("Shibboleth module threw an unknown exception."));
448 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
455 #define FUNC "shib_handler"
456 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
458 ostringstream threadid;
459 threadid << "[" << getpid() << "] shib_handler" << '\0';
460 xmltooling::NDC ndc(threadid.str().c_str());
463 ShibTargetNSAPI stn(pb, sn, rq);
465 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
466 if (res.first) return (int)res.second;
468 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
470 catch (exception& e) {
471 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
472 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
475 log_error(LOG_FAILURE,FUNC,sn,rq,"unknown exception caught in Shibboleth handler");
477 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
483 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
486 SunRequestMapper(const xercesc::DOMElement* e);
487 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
488 Lockable* lock() { return m_mapper->lock(); }
489 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
490 Settings getSettings(const HTTPRequest& request) const;
492 const PropertySet* getParent() const { return NULL; }
493 void setParent(const PropertySet*) {}
494 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
495 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
496 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
497 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
498 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
499 void getAll(map<string,const char*>& properties) const;
500 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
501 const xercesc::DOMElement* getElement() const;
504 RequestMapper* m_mapper;
506 ThreadKey* m_propsKey;
509 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
511 return new SunRequestMapper(e);
514 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
516 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
517 m_stKey=ThreadKey::create(NULL);
518 m_propsKey=ThreadKey::create(NULL);
521 RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
523 Settings s=m_mapper->getSettings(request);
524 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
525 m_propsKey->setData((void*)s.first);
526 return pair<const PropertySet*,AccessControl*>(this,s.second);
529 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
531 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
532 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
533 if (stn && !ns && name) {
534 // Override boolean properties.
535 const char* param=pblock_findval(name,stn->m_pb);
536 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
537 return make_pair(true,true);
539 return s ? s->getBool(name,ns) : make_pair(false,false);
542 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
544 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
545 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
546 if (stn && !ns && name) {
547 // Override string properties.
548 if (!strcmp(name,"authType"))
549 return pair<bool,const char*>(true,"shibboleth");
551 const char* param=pblock_findval(name,stn->m_pb);
553 return make_pair(true,param);
556 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
559 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
561 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
562 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
565 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
567 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
568 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
569 if (stn && !ns && name) {
570 // Override int properties.
571 const char* param=pblock_findval(name,stn->m_pb);
573 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
575 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
578 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
580 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
581 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
582 if (stn && !ns && name) {
583 // Override int properties.
584 const char* param=pblock_findval(name,stn->m_pb);
586 return pair<bool,int>(true,atoi(param));
588 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
591 void SunRequestMapper::getAll(map<string,const char*>& properties) const
593 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
594 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
596 s->getAll(properties);
599 properties["authType"] = "shibboleth";
600 const pb_entry* entry;
601 for (int i=0; i<stn->m_pb->hsize; ++i) {
602 entry = stn->m_pb->ht[i];
604 properties[entry->param->name] = entry->param->value;
610 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
612 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
613 return s ? s->getPropertySet(name,ns) : NULL;
616 const xercesc::DOMElement* SunRequestMapper::getElement() const
618 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
619 return s ? s->getElement() : NULL;