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;
193 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq) : m_gotBody(false), m_env(NULL) {
198 // Get everything but hostname...
199 const char* uri=pblock_findval("uri", rq->reqpb);
200 const char* qstr=pblock_findval("query", rq->reqpb);
208 url=url + '?' + qstr;
210 const char* host=NULL;
211 #ifdef vs_is_default_vs
212 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
213 if (!vs_is_default_vs)
214 // The beauty here is, a non-default vhost can *only* be accessed if the client
215 // specified the exact name in the Host header. So we can trust the Host header.
216 host=pblock_findval("host", rq->headers);
219 // In other cases, we're going to rely on the initialization process...
220 host=g_ServerName.c_str();
224 util_env_free(m_env);
227 const char* getScheme() const {
228 return security_active ? "https" : "http";
230 const char* getHostname() const {
231 #ifdef vs_is_default_vs
232 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
233 if (!vs_is_default_vs)
234 // The beauty here is, a non-default vhost can *only* be accessed if the client
235 // specified the exact name in the Host header. So we can trust the Host header.
236 return pblock_findval("host", m_rq->headers);
239 // In other cases, we're going to rely on the initialization process...
240 return g_ServerName.c_str();
242 int getPort() const {
243 return server_portnum;
245 const char* getRequestURI() const {
246 return m_uri.c_str();
248 const char* getMethod() const {
249 return pblock_findval("method", m_rq->reqpb);
251 string getContentType() const {
252 char* content_type = "";
253 request_header("content-type", &content_type, m_sn, m_rq);
256 long getContentLength() const {
258 return m_body.length();
259 char* content_length="";
260 request_header("content-length", &content_length, m_sn, m_rq);
261 return atoi(content_length);
263 string getRemoteAddr() const {
264 return pblock_findval("ip", m_sn->client);
266 void log(SPLogLevel level, const string& msg) const {
267 AbstractSPRequest::log(level,msg);
269 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
271 const char* getQueryString() const {
272 return pblock_findval("query", m_rq->reqpb);
274 const char* getRequestBody() const {
276 return m_body.c_str();
277 char* content_length=NULL;
278 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED || atoi(content_length) > 1024*1024) // 1MB?
279 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
282 int cl=atoi(content_length);
284 while (cl && ch != IO_EOF) {
285 ch=netbuf_getc(m_sn->inbuf);
293 throw IOException("Error reading request body from browser.");
294 return m_body.c_str();
297 void clearHeader(const char* rawname, const char* cginame) {
298 if (g_checkSpoofing) {
300 // Populate the set of client-supplied headers for spoof checking.
301 //m_env = util_env_create();
302 m_env = pblock_pb2env(m_rq->headers, NULL);
304 if (util_env_find(m_env, const_cast<char*>(cginame)))
305 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
307 if (!strcmp(rawname,"REMOTE_USER")) {
308 param_free(pblock_remove("auth-user",m_rq->vars));
309 param_free(pblock_remove("remote-user",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 pblock_nvinsert(name, value, m_rq->headers);
319 string getHeader(const char* name) const {
321 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED)
323 return string(hdr ? hdr : "");
325 void setRemoteUser(const char* user) {
326 pblock_nvinsert("remote-user", user, m_rq->headers);
327 pblock_nvinsert("auth-user", user, m_rq->vars);
329 string getRemoteUser() const {
330 return getHeader("remote-user");
332 void setResponseHeader(const char* name, const char* value) {
333 pblock_nvinsert(name, value, m_rq->srvhdrs);
336 long sendResponse(istream& in, long status) {
341 msg.append(buf,in.gcount());
343 pblock_nvinsert("connection","close",m_rq->srvhdrs);
344 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
345 protocol_status(m_sn, m_rq, status, NULL);
346 protocol_start_response(m_sn, m_rq);
347 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
350 long sendRedirect(const char* url) {
351 param_free(pblock_remove("content-type", m_rq->srvhdrs));
352 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
353 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
354 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
355 pblock_nvinsert("location", url, m_rq->srvhdrs);
356 pblock_nvinsert("connection","close",m_rq->srvhdrs);
357 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
358 protocol_start_response(m_sn, m_rq);
361 long returnDecline() { return REQ_NOACTION; }
362 long returnOK() { return REQ_PROCEED; }
363 const vector<string>& getClientCertificates() const {
364 if (m_certs.empty()) {
365 const char* cert = pblock_findval("auth-cert", m_rq->vars);
367 m_certs.push_back(cert);
377 /********************************************************************************/
379 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
381 log_error(LOG_FAILURE,func,sn,rq,msg);
382 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
387 #define FUNC "shibboleth"
388 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
390 ostringstream threadid;
391 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
392 xmltooling::NDC ndc(threadid.str().c_str());
395 ShibTargetNSAPI stn(pb, sn, rq);
397 // Check user authentication
398 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
399 if (res.first) return (int)res.second;
401 // user authN was okay -- export the assertions now
402 param_free(pblock_remove("auth-user",rq->vars));
403 // This seems to be required in order to eventually set
404 // the auth-user var.
405 pblock_nvinsert("auth-type","shibboleth",rq->vars);
406 res = stn.getServiceProvider().doExport(stn);
407 if (res.first) return (int)res.second;
409 // Check the Authorization
410 res = stn.getServiceProvider().doAuthorization(stn);
411 if (res.first) return (int)res.second;
416 catch (exception& e) {
417 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
418 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
422 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an uncaught exception.");
429 #define FUNC "shib_handler"
430 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
432 ostringstream threadid;
433 threadid << "[" << getpid() << "] shib_handler" << '\0';
434 xmltooling::NDC ndc(threadid.str().c_str());
437 ShibTargetNSAPI stn(pb, sn, rq);
439 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
440 if (res.first) return (int)res.second;
442 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
444 catch (exception& e) {
445 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
446 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
450 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
456 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
459 SunRequestMapper(const xercesc::DOMElement* e);
460 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
461 Lockable* lock() { return m_mapper->lock(); }
462 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
463 Settings getSettings(const SPRequest& request) const;
465 const PropertySet* getParent() const { return NULL; }
466 void setParent(const PropertySet*) {}
467 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
468 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
469 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
470 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
471 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
472 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const;
473 const xercesc::DOMElement* getElement() const;
476 RequestMapper* m_mapper;
478 ThreadKey* m_propsKey;
481 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
483 return new SunRequestMapper(e);
486 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
488 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
489 m_stKey=ThreadKey::create(NULL);
490 m_propsKey=ThreadKey::create(NULL);
493 RequestMapper::Settings SunRequestMapper::getSettings(const SPRequest& request) const
495 Settings s=m_mapper->getSettings(request);
496 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
497 m_propsKey->setData((void*)s.first);
498 return pair<const PropertySet*,AccessControl*>(this,s.second);
501 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
503 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
504 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
505 if (stn && !ns && name) {
506 // Override boolean properties.
507 const char* param=pblock_findval(name,stn->m_pb);
508 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
509 return make_pair(true,true);
511 return s ? s->getBool(name,ns) : make_pair(false,false);
514 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
516 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
517 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
518 if (stn && !ns && name) {
519 // Override string properties.
520 if (!strcmp(name,"authType"))
521 return pair<bool,const char*>(true,"shibboleth");
523 const char* param=pblock_findval(name,stn->m_pb);
525 return make_pair(true,param);
528 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
531 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
533 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
534 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
537 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
539 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
540 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
541 if (stn && !ns && name) {
542 // Override int properties.
543 const char* param=pblock_findval(name,stn->m_pb);
545 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
547 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
550 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
552 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
553 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
554 if (stn && !ns && name) {
555 // Override int properties.
556 const char* param=pblock_findval(name,stn->m_pb);
558 return pair<bool,int>(true,atoi(param));
560 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
563 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
565 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
566 return s ? s->getPropertySet(name,ns) : NULL;
569 const xercesc::DOMElement* SunRequestMapper::getElement() const
571 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
572 return s ? s->getElement() : NULL;