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>
65 using namespace shibsp;
66 using namespace xmltooling;
69 // macros to output text to client
70 #define NET_WRITE(str) \
71 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
74 SPConfig* g_Config=NULL;
76 string g_ServerScheme;
77 string g_unsetHeaderValue;
78 bool g_checkSpoofing = true;
79 bool g_catchAll = false;
81 static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
82 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
85 PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
87 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
94 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
96 // Save off a default hostname for this virtual server.
97 char* name=pblock_findval("server-name",pb);
101 name=server_hostname;
105 name=util_hostname();
111 pblock_nvinsert("error","unable to determine web server hostname",pb);
116 name=pblock_findval("server-scheme",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);
124 schemadir=getenv("SHIBSP_SCHEMAS");
126 schemadir=SHIBSP_SCHEMAS;
127 const char* config=pblock_findval("shib-config",pb);
129 config=getenv("SHIBSP_CONFIG");
131 config=SHIBSP_CONFIG;
132 g_Config=&SPConfig::getConfig();
133 g_Config->setFeatures(
136 SPConfig::RequestMapping |
137 SPConfig::InProcess |
141 if (!g_Config->init(schemadir)) {
143 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
147 g_Config->RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
150 xercesc::DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
151 XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
152 xercesc::DOMElement* dummy = dummydoc->createElementNS(NULL,path);
153 auto_ptr_XMLCh src(config);
154 dummy->setAttributeNS(NULL,path,src.get());
155 dummy->setAttributeNS(NULL,validate,xmlconstants::XML_ONE);
157 g_Config->setServiceProvider(g_Config->ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER,dummy));
158 g_Config->getServiceProvider()->init();
160 catch (exception& ex) {
161 pblock_nvinsert("error",ex.what(),pb);
167 daemon_atrestart(nsapi_shib_exit,NULL);
169 ServiceProvider* sp=g_Config->getServiceProvider();
171 const PropertySet* props=sp->getPropertySet("Local");
173 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
174 if (unsetValue.first)
175 g_unsetHeaderValue = unsetValue.second;
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;
184 /********************************************************************************/
185 // NSAPI Shib Target Subclass
187 class ShibTargetNSAPI : public AbstractSPRequest
190 mutable string m_body;
191 mutable bool m_gotBody;
192 mutable vector<string> m_certs;
193 set<string> m_allhttp;
196 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq) : m_gotBody(false) {
201 const char* uri=pblock_findval("uri", rq->reqpb);
202 const char* qstr=pblock_findval("query", rq->reqpb);
207 m_uri = m_uri + '?' + qstr;
212 const char* getScheme() const {
213 return security_active ? "https" : "http";
215 const char* getHostname() const {
216 #ifdef vs_is_default_vs
217 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
218 if (!vs_is_default_vs(request_get_vs(m_rq)))
219 // The beauty here is, a non-default vhost can *only* be accessed if the client
220 // specified the exact name in the Host header. So we can trust the Host header.
221 return pblock_findval("host", m_rq->headers);
224 // In other cases, we're going to rely on the initialization process...
225 return g_ServerName.c_str();
227 int getPort() const {
228 return server_portnum;
230 const char* getRequestURI() const {
231 return m_uri.c_str();
233 const char* getMethod() const {
234 return pblock_findval("method", m_rq->reqpb);
236 string getContentType() const {
237 char* content_type = "";
238 request_header("content-type", &content_type, m_sn, m_rq);
241 long getContentLength() const {
243 return m_body.length();
244 char* content_length="";
245 request_header("content-length", &content_length, m_sn, m_rq);
246 return atoi(content_length);
248 string getRemoteAddr() const {
249 return pblock_findval("ip", m_sn->client);
251 void log(SPLogLevel level, const string& msg) const {
252 AbstractSPRequest::log(level,msg);
254 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
256 const char* getQueryString() const {
257 return pblock_findval("query", m_rq->reqpb);
259 const char* getRequestBody() const {
261 return m_body.c_str();
262 char* content_length=NULL;
263 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED || atoi(content_length) > 1024*1024) // 1MB?
264 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
267 int cl=atoi(content_length);
269 while (cl && ch != IO_EOF) {
270 ch=netbuf_getc(m_sn->inbuf);
278 throw IOException("Error reading request body from browser.");
279 return m_body.c_str();
282 void clearHeader(const char* rawname, const char* cginame) {
283 if (g_checkSpoofing) {
284 if (m_allhttp.empty()) {
285 // Populate the set of client-supplied headers for spoof checking.
286 const pb_entry* entry;
287 for (int i=0; i<m_rq->headers->hsize; ++i) {
288 entry = m_rq->headers->ht[i];
290 string cgiversion("HTTP_");
291 const char* pch = entry->param->name;
293 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
296 m_allhttp.insert(cgiversion);
301 if (m_allhttp.count(cginame) > 0)
302 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
304 param_free(pblock_remove(rawname, m_rq->headers));
305 pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
307 void setHeader(const char* name, const char* value) {
308 param_free(pblock_remove(name, m_rq->headers));
309 pblock_nvinsert(name, value, m_rq->headers);
311 string getHeader(const char* name) const {
312 // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
314 int cookie = strcmp(name, "Cookie");
317 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
318 // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
323 n += tolower(*(name++));
324 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
327 return string(hdr ? hdr : "");
329 void setRemoteUser(const char* user) {
330 pblock_nvinsert("auth-user", user, m_rq->vars);
332 string getRemoteUser() const {
333 const char* ru = pblock_findval("auth-user", m_rq->vars);
336 void setResponseHeader(const char* name, const char* value) {
337 pblock_nvinsert(name, value, m_rq->srvhdrs);
340 long sendResponse(istream& in, long status) {
345 msg.append(buf,in.gcount());
347 pblock_nvinsert("connection","close",m_rq->srvhdrs);
348 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
349 protocol_status(m_sn, m_rq, status, NULL);
350 protocol_start_response(m_sn, m_rq);
351 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
354 long sendRedirect(const char* url) {
355 param_free(pblock_remove("content-type", m_rq->srvhdrs));
356 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
357 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
358 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
359 pblock_nvinsert("location", url, m_rq->srvhdrs);
360 pblock_nvinsert("connection","close",m_rq->srvhdrs);
361 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
362 protocol_start_response(m_sn, m_rq);
365 long returnDecline() { return REQ_NOACTION; }
366 long returnOK() { return REQ_PROCEED; }
367 const vector<string>& getClientCertificates() const {
368 if (m_certs.empty()) {
369 const char* cert = pblock_findval("auth-cert", m_rq->vars);
371 m_certs.push_back(cert);
381 /********************************************************************************/
383 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
385 log_error(LOG_FAILURE,func,sn,rq,msg);
386 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
391 #define FUNC "shibboleth"
392 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
394 ostringstream threadid;
395 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
396 xmltooling::NDC ndc(threadid.str().c_str());
399 ShibTargetNSAPI stn(pb, sn, rq);
401 // Check user authentication
402 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
403 if (res.first) return (int)res.second;
405 // user authN was okay -- export the assertions now
406 param_free(pblock_remove("auth-user",rq->vars));
407 // This seems to be required in order to eventually set
408 // the auth-user var.
409 pblock_nvinsert("auth-type","shibboleth",rq->vars);
410 res = stn.getServiceProvider().doExport(stn);
411 if (res.first) return (int)res.second;
413 // Check the Authorization
414 res = stn.getServiceProvider().doAuthorization(stn);
415 if (res.first) return (int)res.second;
420 catch (exception& e) {
421 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
422 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
425 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>("Shibboleth module threw an unknown exception."));
427 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
434 #define FUNC "shib_handler"
435 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
437 ostringstream threadid;
438 threadid << "[" << getpid() << "] shib_handler" << '\0';
439 xmltooling::NDC ndc(threadid.str().c_str());
442 ShibTargetNSAPI stn(pb, sn, rq);
444 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
445 if (res.first) return (int)res.second;
447 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
449 catch (exception& e) {
450 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
451 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
455 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
461 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
464 SunRequestMapper(const xercesc::DOMElement* e);
465 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
466 Lockable* lock() { return m_mapper->lock(); }
467 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
468 Settings getSettings(const HTTPRequest& request) const;
470 const PropertySet* getParent() const { return NULL; }
471 void setParent(const PropertySet*) {}
472 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
473 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
474 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
475 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
476 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
477 void getAll(map<string,const char*>& properties) const;
478 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const;
479 const xercesc::DOMElement* getElement() const;
482 RequestMapper* m_mapper;
484 ThreadKey* m_propsKey;
487 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
489 return new SunRequestMapper(e);
492 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
494 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
495 m_stKey=ThreadKey::create(NULL);
496 m_propsKey=ThreadKey::create(NULL);
499 RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
501 Settings s=m_mapper->getSettings(request);
502 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
503 m_propsKey->setData((void*)s.first);
504 return pair<const PropertySet*,AccessControl*>(this,s.second);
507 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
509 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
510 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
511 if (stn && !ns && name) {
512 // Override boolean properties.
513 const char* param=pblock_findval(name,stn->m_pb);
514 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
515 return make_pair(true,true);
517 return s ? s->getBool(name,ns) : make_pair(false,false);
520 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
522 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
523 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
524 if (stn && !ns && name) {
525 // Override string properties.
526 if (!strcmp(name,"authType"))
527 return pair<bool,const char*>(true,"shibboleth");
529 const char* param=pblock_findval(name,stn->m_pb);
531 return make_pair(true,param);
534 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
537 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
539 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
540 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
543 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
545 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
546 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
547 if (stn && !ns && name) {
548 // Override int properties.
549 const char* param=pblock_findval(name,stn->m_pb);
551 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
553 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
556 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
558 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
559 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
560 if (stn && !ns && name) {
561 // Override int properties.
562 const char* param=pblock_findval(name,stn->m_pb);
564 return pair<bool,int>(true,atoi(param));
566 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
569 void SunRequestMapper::getAll(map<string,const char*>& properties) const
571 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
572 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
574 s->getAll(properties);
577 properties["authType"] = "shibboleth";
578 const pb_entry* entry;
579 for (int i=0; i<stn->m_pb->hsize; ++i) {
580 entry = stn->m_pb->ht[i];
582 properties[entry->param->name] = entry->param->value;
588 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
590 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
591 return s ? s->getPropertySet(name,ns) : NULL;
594 const xercesc::DOMElement* SunRequestMapper::getElement() const
596 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
597 return s ? s->getElement() : NULL;