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
23 #if defined (_MSC_VER) || defined(__BORLANDC__)
24 # include "config_win32.h"
30 # define _CRT_NONSTDC_NO_DEPRECATE 1
31 # define _CRT_SECURE_NO_DEPRECATE 1
34 #include <shibsp/AbstractSPRequest.h>
35 #include <shibsp/RequestMapper.h>
36 #include <shibsp/SPConfig.h>
37 #include <shibsp/ServiceProvider.h>
38 #include <xmltooling/XMLToolingConfig.h>
39 #include <xmltooling/util/NDC.h>
40 #include <xmltooling/util/Threads.h>
41 #include <xmltooling/util/XMLHelper.h>
42 #include <xercesc/util/XMLUniDefs.hpp>
62 using namespace shibsp;
63 using namespace xmltooling;
66 // macros to output text to client
67 #define NET_WRITE(str) \
68 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
71 SPConfig* g_Config=NULL;
73 string g_ServerScheme;
74 string g_unsetHeaderValue;
76 static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
77 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
80 PluginManager<RequestMapper,const DOMElement*>::Factory SunRequestMapFactory;
82 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
89 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
91 // Save off a default hostname for this virtual server.
92 char* name=pblock_findval("server-name",pb);
100 name=util_hostname();
106 pblock_nvinsert("error","unable to determine web server hostname",pb);
111 name=pblock_findval("server-scheme",pb);
115 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
117 const char* schemadir=pblock_findval("shib-schemas",pb);
119 schemadir=getenv("SHIBSCHEMAS");
121 schemadir=SHIBSP_SCHEMAS;
122 const char* config=pblock_findval("shib-config",pb);
124 config=getenv("SHIBCONFIG");
126 config=SHIBSP_CONFIG;
127 g_Config=&SPConfig::getConfig();
128 g_Config->setFeatures(
131 SPConfig::RequestMapping |
132 SPConfig::InProcess |
135 if (!g_Config->init(schemadir)) {
137 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
141 g_Config->RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
144 DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
145 XercesJanitor<DOMDocument> docjanitor(dummydoc);
146 DOMElement* dummy = dummydoc->createElementNS(NULL,path);
147 auto_ptr_XMLCh src(config);
148 dummy->setAttributeNS(NULL,path,src.get());
149 dummy->setAttributeNS(NULL,validate,xmlconstants::XML_ONE);
151 g_Config->setServiceProvider(g_Config->ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER,dummy));
152 g_Config->getServiceProvider()->init();
154 catch (exception& ex) {
155 pblock_nvinsert("error",ex.what(),pb);
161 daemon_atrestart(nsapi_shib_exit,NULL);
163 ServiceProvider* sp=g_Config->getServiceProvider();
165 const PropertySet* props=sp->getPropertySet("Local");
167 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
168 if (unsetValue.first)
169 g_unsetHeaderValue = unsetValue.second;
174 /********************************************************************************/
175 // NSAPI Shib Target Subclass
177 class ShibTargetNSAPI : public AbstractSPRequest
180 mutable string m_body;
181 mutable bool m_gotBody;
182 vector<XSECCryptoX509*> m_certs;
185 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq) : m_gotBody(false) {
190 // Get everything but hostname...
191 const char* uri=pblock_findval("uri", rq->reqpb);
192 const char* qstr=pblock_findval("query", rq->reqpb);
200 url=url + '?' + qstr;
202 const char* host=NULL;
203 #ifdef vs_is_default_vs
204 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
205 if (!vs_is_default_vs)
206 // The beauty here is, a non-default vhost can *only* be accessed if the client
207 // specified the exact name in the Host header. So we can trust the Host header.
208 host=pblock_findval("host", rq->headers);
211 // In other cases, we're going to rely on the initialization process...
212 host=g_ServerName.c_str();
214 ~ShibTargetNSAPI() {}
216 const char* getScheme() const {
217 return security_active ? "https" : "http";
219 const char* getHostname() const {
220 #ifdef vs_is_default_vs
221 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
222 if (!vs_is_default_vs)
223 // The beauty here is, a non-default vhost can *only* be accessed if the client
224 // specified the exact name in the Host header. So we can trust the Host header.
225 return pblock_findval("host", m_rq->headers);
228 // In other cases, we're going to rely on the initialization process...
229 return g_ServerName.c_str();
231 int getPort() const {
232 return server_portnum;
234 const char* getRequestURI() const {
235 return m_uri.c_str();
237 const char* getMethod() const {
238 return pblock_findval("method", m_rq->reqpb);
240 string getContentType() const {
241 char* content_type = "";
242 request_header("content-type", &content_type, m_sn, m_rq);
245 long getContentLength() const {
247 return m_body.length();
248 char* content_length="";
249 request_header("content-length", &content_length, m_sn, m_rq);
250 return atoi(content_length);
252 string getRemoteAddr() const {
253 return pblock_findval("ip", m_sn->client);
255 void log(SPLogLevel level, const string& msg) {
256 AbstractSPRequest::log(level,msg);
258 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
260 const char* getQueryString() const {
261 return pblock_findval("query", m_rq->reqpb);
263 const char* getRequestBody() const {
265 return m_body.c_str();
266 char* content_length=NULL;
267 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
268 atoi(content_length) > 1024*1024) // 1MB?
269 throw opensaml::BindingException("Blocked POST request body exceeding size limit.");
272 int cl=atoi(content_length);
274 while (cl && ch != IO_EOF) {
275 ch=netbuf_getc(m_sn->inbuf);
283 throw opensaml::BindingException("Error reading POST request body from browser.");
284 return m_body.c_str();
287 void clearHeader(const char* name) {
288 if (!strcmp(name,"REMOTE_USER")) {
289 param_free(pblock_remove("auth-user",m_rq->vars));
290 param_free(pblock_remove("remote-user",m_rq->headers));
293 param_free(pblock_remove(name, m_rq->headers));
294 pblock_nvinsert(name, g_unsetHeaderValue.c_str() ,m_rq->headers);
297 void setHeader(const char* name, const char* value) {
298 pblock_nvinsert(name, value, m_rq->headers);
300 string getHeader(const char* name) const {
302 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED)
304 return string(hdr ? hdr : "");
306 void setRemoteUser(const char* user) {
307 pblock_nvinsert("remote-user", user, m_rq->headers);
308 pblock_nvinsert("auth-user", user, m_rq->vars);
310 string getRemoteUser() const {
311 return getHeader("remote-user");
313 void setResponseHeader(const char* name, const char* value) {
314 pblock_nvinsert(name, value, m_rq->srvhdrs);
317 long sendResponse(istream& in, long status) {
322 msg.append(buf,in.gcount());
324 pblock_nvinsert("connection","close",m_rq->srvhdrs);
325 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
326 protocol_status(m_sn, m_rq, status, NULL);
327 protocol_start_response(m_sn, m_rq);
328 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
331 long sendRedirect(const char* url) {
332 param_free(pblock_remove("content-type", m_rq->srvhdrs));
333 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
334 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
335 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
336 pblock_nvinsert("location", url, m_rq->srvhdrs);
337 pblock_nvinsert("connection","close",m_rq->srvhdrs);
338 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
339 protocol_start_response(m_sn, m_rq);
342 long returnDecline() { return REQ_NOACTION; }
343 long returnOK() { return REQ_PROCEED; }
344 const vector<XSECCryptoX509*>& getClientCertificates() const {
353 /********************************************************************************/
355 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
357 log_error(LOG_FAILURE,func,sn,rq,msg);
358 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
363 #define FUNC "shibboleth"
364 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
366 ostringstream threadid;
367 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
368 xmltooling::NDC ndc(threadid.str().c_str());
371 ShibTargetNSAPI stn(pb, sn, rq);
373 // Check user authentication
374 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
375 if (res.first) return (int)res.second;
377 // user authN was okay -- export the assertions now
378 param_free(pblock_remove("auth-user",rq->vars));
379 // This seems to be required in order to eventually set
380 // the auth-user var.
381 pblock_nvinsert("auth-type","shibboleth",rq->vars);
382 res = stn.getServiceProvider().doExport(stn);
383 if (res.first) return (int)res.second;
385 // Check the Authorization
386 res = stn.getServiceProvider().doAuthorization(stn);
387 if (res.first) return (int)res.second;
392 catch (exception& e) {
393 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
394 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
398 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an uncaught exception.");
405 #define FUNC "shib_handler"
406 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
408 ostringstream threadid;
409 threadid << "[" << getpid() << "] shib_handler" << '\0';
410 xmltooling::NDC ndc(threadid.str().c_str());
413 ShibTargetNSAPI stn(pb, sn, rq);
415 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
416 if (res.first) return (int)res.second;
418 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
420 catch (exception& e) {
421 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
422 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
426 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
432 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
435 SunRequestMapper(const DOMElement* e);
436 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
437 Lockable* lock() { return m_mapper->lock(); }
438 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
439 Settings getSettings(const SPRequest& request) const;
441 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
442 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
443 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
444 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
445 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
446 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
447 const DOMElement* getElement() const;
450 RequestMapper* m_mapper;
452 ThreadKey* m_propsKey;
455 RequestMapper* SunRequestMapFactory(const DOMElement* const & e)
457 return new SunRequestMapper(e);
460 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
462 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
463 m_stKey=ThreadKey::create(NULL);
464 m_propsKey=ThreadKey::create(NULL);
467 RequestMapper::Settings SunRequestMapper::getSettings(const SPRequest& request) const
469 Settings s=m_mapper->getSettings(request);
470 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
471 m_propsKey->setData((void*)s.first);
472 return pair<const PropertySet*,AccessControl*>(this,s.second);
475 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
477 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
478 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
479 if (stn && !ns && name) {
480 // Override boolean properties.
481 const char* param=pblock_findval(name,stn->m_pb);
482 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
483 return make_pair(true,true);
485 return s ? s->getBool(name,ns) : make_pair(false,false);
488 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
490 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
491 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
492 if (stn && !ns && name) {
493 // Override string properties.
494 if (!strcmp(name,"authType"))
495 return pair<bool,const char*>(true,"shibboleth");
497 const char* param=pblock_findval(name,stn->m_pb);
499 return make_pair(true,param);
502 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
505 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
507 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
508 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
511 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
513 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
514 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
515 if (stn && !ns && name) {
516 // Override int properties.
517 const char* param=pblock_findval(name,stn->m_pb);
519 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
521 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
524 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
526 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
527 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
528 if (stn && !ns && name) {
529 // Override int properties.
530 const char* param=pblock_findval(name,stn->m_pb);
532 return pair<bool,int>(true,atoi(param));
534 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
537 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
539 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
540 return s ? s->getPropertySet(name,ns) : NULL;
543 const DOMElement* SunRequestMapper::getElement() const
545 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
546 return s ? s->getElement() : NULL;