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;
80 static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
81 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
84 PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
86 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
93 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
95 // Save off a default hostname for this virtual server.
96 char* name=pblock_findval("server-name",pb);
100 name=server_hostname;
104 name=util_hostname();
110 pblock_nvinsert("error","unable to determine web server hostname",pb);
115 name=pblock_findval("server-scheme",pb);
119 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
121 const char* schemadir=pblock_findval("shib-schemas",pb);
123 schemadir=getenv("SHIBSP_SCHEMAS");
125 schemadir=SHIBSP_SCHEMAS;
126 const char* config=pblock_findval("shib-config",pb);
128 config=getenv("SHIBSP_CONFIG");
130 config=SHIBSP_CONFIG;
131 g_Config=&SPConfig::getConfig();
132 g_Config->setFeatures(
135 SPConfig::RequestMapping |
136 SPConfig::InProcess |
139 if (!g_Config->init(schemadir)) {
141 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
145 g_Config->RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
148 xercesc::DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
149 XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
150 xercesc::DOMElement* dummy = dummydoc->createElementNS(NULL,path);
151 auto_ptr_XMLCh src(config);
152 dummy->setAttributeNS(NULL,path,src.get());
153 dummy->setAttributeNS(NULL,validate,xmlconstants::XML_ONE);
155 g_Config->setServiceProvider(g_Config->ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER,dummy));
156 g_Config->getServiceProvider()->init();
158 catch (exception& ex) {
159 pblock_nvinsert("error",ex.what(),pb);
165 daemon_atrestart(nsapi_shib_exit,NULL);
167 ServiceProvider* sp=g_Config->getServiceProvider();
169 const PropertySet* props=sp->getPropertySet("Local");
171 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
172 if (unsetValue.first)
173 g_unsetHeaderValue = unsetValue.second;
174 pair<bool,bool> checkSpoofing=props->getBool("checkSpoofing");
175 if (checkSpoofing.first && !checkSpoofing.second)
176 g_checkSpoofing = false;
181 /********************************************************************************/
182 // NSAPI Shib Target Subclass
184 class ShibTargetNSAPI : public AbstractSPRequest
187 mutable string m_body;
188 mutable bool m_gotBody;
189 mutable vector<string> m_certs;
190 set<string> m_allhttp;
193 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq) : m_gotBody(false) {
198 const char* uri=pblock_findval("uri", rq->reqpb);
199 const char* qstr=pblock_findval("query", rq->reqpb);
204 m_uri = m_uri + '?' + qstr;
209 const char* getScheme() const {
210 return security_active ? "https" : "http";
212 const char* getHostname() const {
213 #ifdef vs_is_default_vs
214 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
215 if (!vs_is_default_vs(request_get_vs(m_rq)))
216 // The beauty here is, a non-default vhost can *only* be accessed if the client
217 // specified the exact name in the Host header. So we can trust the Host header.
218 return pblock_findval("host", m_rq->headers);
221 // In other cases, we're going to rely on the initialization process...
222 return g_ServerName.c_str();
224 int getPort() const {
225 return server_portnum;
227 const char* getRequestURI() const {
228 return m_uri.c_str();
230 const char* getMethod() const {
231 return pblock_findval("method", m_rq->reqpb);
233 string getContentType() const {
234 char* content_type = "";
235 request_header("content-type", &content_type, m_sn, m_rq);
238 long getContentLength() const {
240 return m_body.length();
241 char* content_length="";
242 request_header("content-length", &content_length, m_sn, m_rq);
243 return atoi(content_length);
245 string getRemoteAddr() const {
246 return pblock_findval("ip", m_sn->client);
248 void log(SPLogLevel level, const string& msg) const {
249 AbstractSPRequest::log(level,msg);
251 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
253 const char* getQueryString() const {
254 return pblock_findval("query", m_rq->reqpb);
256 const char* getRequestBody() const {
258 return m_body.c_str();
259 char* content_length=NULL;
260 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED || atoi(content_length) > 1024*1024) // 1MB?
261 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
264 int cl=atoi(content_length);
266 while (cl && ch != IO_EOF) {
267 ch=netbuf_getc(m_sn->inbuf);
275 throw IOException("Error reading request body from browser.");
276 return m_body.c_str();
279 void clearHeader(const char* rawname, const char* cginame) {
280 if (g_checkSpoofing) {
281 if (m_allhttp.empty()) {
282 // Populate the set of client-supplied headers for spoof checking.
283 const pb_entry* entry;
284 for (int i=0; i<m_rq->headers->hsize; ++i) {
285 entry = m_rq->headers->ht[i];
287 string cgiversion("HTTP_");
288 const char* pch = entry->param->name;
290 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
293 m_allhttp.insert(cgiversion);
298 if (m_allhttp.count(cginame) > 0)
299 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
301 param_free(pblock_remove(rawname, m_rq->headers));
302 pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
304 void setHeader(const char* name, const char* value) {
305 param_free(pblock_remove(name, m_rq->headers));
306 pblock_nvinsert(name, value, m_rq->headers);
308 string getHeader(const char* name) const {
309 // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
311 int cookie = strcmp(name, "Cookie");
314 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
315 // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
320 n += tolower(*(name++));
321 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
324 return string(hdr ? hdr : "");
326 void setRemoteUser(const char* user) {
327 pblock_nvinsert("auth-user", user, m_rq->vars);
329 string getRemoteUser() const {
330 const char* ru = pblock_findval("auth-user", m_rq->vars);
333 void setResponseHeader(const char* name, const char* value) {
334 pblock_nvinsert(name, value, m_rq->srvhdrs);
337 long sendResponse(istream& in, long status) {
342 msg.append(buf,in.gcount());
344 pblock_nvinsert("connection","close",m_rq->srvhdrs);
345 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
346 protocol_status(m_sn, m_rq, status, NULL);
347 protocol_start_response(m_sn, m_rq);
348 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
351 long sendRedirect(const char* url) {
352 param_free(pblock_remove("content-type", m_rq->srvhdrs));
353 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
354 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
355 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
356 pblock_nvinsert("location", url, m_rq->srvhdrs);
357 pblock_nvinsert("connection","close",m_rq->srvhdrs);
358 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
359 protocol_start_response(m_sn, m_rq);
362 long returnDecline() { return REQ_NOACTION; }
363 long returnOK() { return REQ_PROCEED; }
364 const vector<string>& getClientCertificates() const {
365 if (m_certs.empty()) {
366 const char* cert = pblock_findval("auth-cert", m_rq->vars);
368 m_certs.push_back(cert);
378 /********************************************************************************/
380 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
382 log_error(LOG_FAILURE,func,sn,rq,msg);
383 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
388 #define FUNC "shibboleth"
389 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
391 ostringstream threadid;
392 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
393 xmltooling::NDC ndc(threadid.str().c_str());
396 ShibTargetNSAPI stn(pb, sn, rq);
398 // Check user authentication
399 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
400 if (res.first) return (int)res.second;
402 // user authN was okay -- export the assertions now
403 param_free(pblock_remove("auth-user",rq->vars));
404 // This seems to be required in order to eventually set
405 // the auth-user var.
406 pblock_nvinsert("auth-type","shibboleth",rq->vars);
407 res = stn.getServiceProvider().doExport(stn);
408 if (res.first) return (int)res.second;
410 // Check the Authorization
411 res = stn.getServiceProvider().doAuthorization(stn);
412 if (res.first) return (int)res.second;
417 catch (exception& e) {
418 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
419 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
423 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an uncaught exception.");
430 #define FUNC "shib_handler"
431 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
433 ostringstream threadid;
434 threadid << "[" << getpid() << "] shib_handler" << '\0';
435 xmltooling::NDC ndc(threadid.str().c_str());
438 ShibTargetNSAPI stn(pb, sn, rq);
440 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
441 if (res.first) return (int)res.second;
443 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
445 catch (exception& e) {
446 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
447 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
451 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
457 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
460 SunRequestMapper(const xercesc::DOMElement* e);
461 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
462 Lockable* lock() { return m_mapper->lock(); }
463 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
464 Settings getSettings(const SPRequest& request) const;
466 const PropertySet* getParent() const { return NULL; }
467 void setParent(const PropertySet*) {}
468 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
469 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
470 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
471 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
472 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
473 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const;
474 const xercesc::DOMElement* getElement() const;
477 RequestMapper* m_mapper;
479 ThreadKey* m_propsKey;
482 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
484 return new SunRequestMapper(e);
487 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
489 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
490 m_stKey=ThreadKey::create(NULL);
491 m_propsKey=ThreadKey::create(NULL);
494 RequestMapper::Settings SunRequestMapper::getSettings(const SPRequest& request) const
496 Settings s=m_mapper->getSettings(request);
497 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
498 m_propsKey->setData((void*)s.first);
499 return pair<const PropertySet*,AccessControl*>(this,s.second);
502 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
504 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
505 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
506 if (stn && !ns && name) {
507 // Override boolean properties.
508 const char* param=pblock_findval(name,stn->m_pb);
509 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
510 return make_pair(true,true);
512 return s ? s->getBool(name,ns) : make_pair(false,false);
515 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
517 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
518 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
519 if (stn && !ns && name) {
520 // Override string properties.
521 if (!strcmp(name,"authType"))
522 return pair<bool,const char*>(true,"shibboleth");
524 const char* param=pblock_findval(name,stn->m_pb);
526 return make_pair(true,param);
529 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
532 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
534 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
535 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
538 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
540 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
541 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
542 if (stn && !ns && name) {
543 // Override int properties.
544 const char* param=pblock_findval(name,stn->m_pb);
546 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
548 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
551 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
553 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
554 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
555 if (stn && !ns && name) {
556 // Override int properties.
557 const char* param=pblock_findval(name,stn->m_pb);
559 return pair<bool,int>(true,atoi(param));
561 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
564 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
566 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
567 return s ? s->getPropertySet(name,ns) : NULL;
570 const xercesc::DOMElement* SunRequestMapper::getElement() const
572 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
573 return s ? s->getElement() : NULL;