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 = "";
241 request_header("content-type", &content_type, m_sn, m_rq);
244 long getContentLength() const {
246 return m_body.length();
247 char* content_length="";
248 request_header("content-length", &content_length, m_sn, m_rq);
249 return atoi(content_length);
251 string getRemoteAddr() const {
252 return pblock_findval("ip", m_sn->client);
254 void log(SPLogLevel level, const string& msg) const {
255 AbstractSPRequest::log(level,msg);
257 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
259 const char* getQueryString() const {
260 return pblock_findval("query", m_rq->reqpb);
262 const char* getRequestBody() const {
264 return m_body.c_str();
265 char* content_length=NULL;
266 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED || atoi(content_length) > 1024*1024) // 1MB?
267 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
270 int cl=atoi(content_length);
272 while (cl && ch != IO_EOF) {
273 ch=netbuf_getc(m_sn->inbuf);
281 throw IOException("Error reading request body from browser.");
282 return m_body.c_str();
285 void clearHeader(const char* rawname, const char* cginame) {
286 if (g_checkSpoofing && m_firsttime && !m_rq->orig_rq) {
287 if (m_allhttp.empty()) {
288 // Populate the set of client-supplied headers for spoof checking.
289 const pb_entry* entry;
290 for (int i=0; i<m_rq->headers->hsize; ++i) {
291 entry = m_rq->headers->ht[i];
293 string cgiversion("HTTP_");
294 const char* pch = entry->param->name;
296 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
299 m_allhttp.insert(cgiversion);
304 if (m_allhttp.count(cginame) > 0)
305 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
307 if (strcmp(rawname, "REMOTE_USER") == 0) {
308 param_free(pblock_remove("remote-user", m_rq->headers));
309 pblock_nvinsert("remote-user", g_unsetHeaderValue.c_str(), m_rq->headers);
312 param_free(pblock_remove(rawname, m_rq->headers));
313 pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
316 void setHeader(const char* name, const char* value) {
317 param_free(pblock_remove(name, m_rq->headers));
318 pblock_nvinsert(name, value, m_rq->headers);
320 string getHeader(const char* name) const {
321 // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
323 int cookie = strcmp(name, "Cookie");
326 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
327 // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
332 n += tolower(*(name++));
333 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
336 return string(hdr ? hdr : "");
338 void setRemoteUser(const char* user) {
339 pblock_nvinsert("auth-user", user, m_rq->vars);
340 param_free(pblock_remove("remote-user", m_rq->headers));
341 pblock_nvinsert("remote-user", user, m_rq->headers);
343 string getRemoteUser() const {
344 const char* ru = pblock_findval("auth-user", m_rq->vars);
347 void setResponseHeader(const char* name, const char* value) {
348 pblock_nvinsert(name, value, m_rq->srvhdrs);
351 long sendResponse(istream& in, long status) {
356 msg.append(buf,in.gcount());
358 pblock_nvinsert("connection","close",m_rq->srvhdrs);
359 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
360 protocol_status(m_sn, m_rq, status, NULL);
361 protocol_start_response(m_sn, m_rq);
362 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
365 long sendRedirect(const char* url) {
366 param_free(pblock_remove("content-type", m_rq->srvhdrs));
367 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
368 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
369 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
370 pblock_nvinsert("location", url, m_rq->srvhdrs);
371 pblock_nvinsert("connection","close",m_rq->srvhdrs);
372 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
373 protocol_start_response(m_sn, m_rq);
376 long returnDecline() { return REQ_NOACTION; }
377 long returnOK() { return REQ_PROCEED; }
378 const vector<string>& getClientCertificates() const {
379 if (m_certs.empty()) {
380 const char* cert = pblock_findval("auth-cert", m_rq->vars);
382 m_certs.push_back(cert);
388 /********************************************************************************/
390 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
392 log_error(LOG_FAILURE,func,sn,rq,msg);
393 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
398 #define FUNC "shibboleth"
399 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
401 ostringstream threadid;
402 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
403 xmltooling::NDC ndc(threadid.str().c_str());
406 ShibTargetNSAPI stn(pb, sn, rq);
408 // Check user authentication
409 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
410 // If directed, install a spoof key to recognize when we've already cleared headers.
411 if (!g_spoofKey.empty()) {
412 param_free(pblock_remove("Shib-Spoof-Check", rq->headers));
413 pblock_nvinsert("Shib-Spoof-Check", g_spoofKey.c_str(), rq->headers);
415 if (res.first) return (int)res.second;
417 // user authN was okay -- export the assertions now
418 param_free(pblock_remove("auth-user",rq->vars));
420 // This seems to be required in order to eventually set
421 // the auth-user var.
422 pblock_nvinsert("auth-type","shibboleth",rq->vars);
424 res = stn.getServiceProvider().doExport(stn);
425 if (res.first) return (int)res.second;
427 // Check the Authorization
428 res = stn.getServiceProvider().doAuthorization(stn);
429 if (res.first) return (int)res.second;
434 catch (exception& e) {
435 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
436 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
439 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>("Shibboleth module threw an unknown exception."));
441 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
448 #define FUNC "shib_handler"
449 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
451 ostringstream threadid;
452 threadid << "[" << getpid() << "] shib_handler" << '\0';
453 xmltooling::NDC ndc(threadid.str().c_str());
456 ShibTargetNSAPI stn(pb, sn, rq);
458 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
459 if (res.first) return (int)res.second;
461 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
463 catch (exception& e) {
464 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
465 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
468 log_error(LOG_FAILURE,FUNC,sn,rq,"unknown exception caught in Shibboleth handler");
470 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
476 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
479 SunRequestMapper(const xercesc::DOMElement* e);
480 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
481 Lockable* lock() { return m_mapper->lock(); }
482 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
483 Settings getSettings(const HTTPRequest& request) const;
485 const PropertySet* getParent() const { return NULL; }
486 void setParent(const PropertySet*) {}
487 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
488 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
489 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
490 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
491 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
492 void getAll(map<string,const char*>& properties) const;
493 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
494 const xercesc::DOMElement* getElement() const;
497 RequestMapper* m_mapper;
499 ThreadKey* m_propsKey;
502 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
504 return new SunRequestMapper(e);
507 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
509 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
510 m_stKey=ThreadKey::create(NULL);
511 m_propsKey=ThreadKey::create(NULL);
514 RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
516 Settings s=m_mapper->getSettings(request);
517 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
518 m_propsKey->setData((void*)s.first);
519 return pair<const PropertySet*,AccessControl*>(this,s.second);
522 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
524 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
525 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
526 if (stn && !ns && name) {
527 // Override boolean properties.
528 const char* param=pblock_findval(name,stn->m_pb);
529 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
530 return make_pair(true,true);
532 return s ? s->getBool(name,ns) : make_pair(false,false);
535 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
537 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
538 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
539 if (stn && !ns && name) {
540 // Override string properties.
541 if (!strcmp(name,"authType"))
542 return pair<bool,const char*>(true,"shibboleth");
544 const char* param=pblock_findval(name,stn->m_pb);
546 return make_pair(true,param);
549 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
552 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
554 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
555 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
558 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
560 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
561 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
562 if (stn && !ns && name) {
563 // Override int properties.
564 const char* param=pblock_findval(name,stn->m_pb);
566 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
568 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
571 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
573 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
574 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
575 if (stn && !ns && name) {
576 // Override int properties.
577 const char* param=pblock_findval(name,stn->m_pb);
579 return pair<bool,int>(true,atoi(param));
581 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
584 void SunRequestMapper::getAll(map<string,const char*>& properties) const
586 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
587 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
589 s->getAll(properties);
592 properties["authType"] = "shibboleth";
593 const pb_entry* entry;
594 for (int i=0; i<stn->m_pb->hsize; ++i) {
595 entry = stn->m_pb->ht[i];
597 properties[entry->param->name] = entry->param->value;
603 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
605 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
606 return s ? s->getPropertySet(name,ns) : NULL;
609 const xercesc::DOMElement* SunRequestMapper::getElement() const
611 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
612 return s ? s->getElement() : NULL;