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 <xmltooling/util/NDC.h>
38 #include <xmltooling/util/Threads.h>
40 #include <shib-target/shib-target.h>
60 using namespace shibsp;
61 using namespace xmltooling;
64 // macros to output text to client
65 #define NET_WRITE(str) \
66 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
69 shibtarget::ShibTargetConfig* g_Config=NULL;
71 string g_ServerScheme;
72 string g_unsetHeaderValue;
75 PluginManager<RequestMapper,const DOMElement*>::Factory SunRequestMapFactory;
77 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
84 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
86 // Save off a default hostname for this virtual server.
87 char* name=pblock_findval("server-name",pb);
101 pblock_nvinsert("error","unable to determine web server hostname",pb);
106 name=pblock_findval("server-scheme",pb);
110 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
115 const char* schemadir=pblock_findval("shib-schemas",pb);
117 schemadir=getenv("SHIBSCHEMAS");
119 schemadir=SHIB_SCHEMAS;
120 const char* config=pblock_findval("shib-config",pb);
122 config=getenv("SHIBCONFIG");
125 g_Config=&shibtarget::ShibTargetConfig::getConfig();
126 SPConfig::getConfig().setFeatures(
131 SPConfig::RequestMapping |
132 SPConfig::InProcess |
135 if (!g_Config->init(schemadir)) {
137 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
141 SPConfig::getConfig().RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
143 if (!g_Config->load(config)) {
145 pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
149 daemon_atrestart(nsapi_shib_exit,NULL);
151 ServiceProvider* conf=SPConfig::getConfig().getServiceProvider();
153 const PropertySet* props=conf->getPropertySet("Local");
155 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
156 if (unsetValue.first)
157 g_unsetHeaderValue = unsetValue.second;
163 pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
170 /********************************************************************************/
171 // NSAPI Shib Target Subclass
173 class ShibTargetNSAPI : public AbstractSPRequest
176 mutable string m_body;
177 mutable bool m_gotBody;
178 vector<XSECCryptoX509*> m_certs;
181 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq) : m_gotBody(false) {
186 // Get everything but hostname...
187 const char* uri=pblock_findval("uri", rq->reqpb);
188 const char* qstr=pblock_findval("query", rq->reqpb);
196 url=url + '?' + qstr;
198 const char* host=NULL;
199 #ifdef vs_is_default_vs
200 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
201 if (!vs_is_default_vs)
202 // The beauty here is, a non-default vhost can *only* be accessed if the client
203 // specified the exact name in the Host header. So we can trust the Host header.
204 host=pblock_findval("host", rq->headers);
207 // In other cases, we're going to rely on the initialization process...
208 host=g_ServerName.c_str();
210 ~ShibTargetNSAPI() {}
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)
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) {
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 ||
264 atoi(content_length) > 1024*1024) // 1MB?
265 throw opensaml::BindingException("Blocked POST request body exceeding size limit.");
268 int cl=atoi(content_length);
270 while (cl && ch != IO_EOF) {
271 ch=netbuf_getc(m_sn->inbuf);
279 throw opensaml::BindingException("Error reading POST request body from browser.");
280 return m_body.c_str();
283 void clearHeader(const char* name) {
284 if (!strcmp(name,"REMOTE_USER")) {
285 param_free(pblock_remove("auth-user",m_rq->vars));
286 param_free(pblock_remove("remote-user",m_rq->headers));
289 param_free(pblock_remove(name, m_rq->headers));
290 pblock_nvinsert(name, g_unsetHeaderValue.c_str() ,m_rq->headers);
293 void setHeader(const char* name, const char* value) {
294 pblock_nvinsert(name, value, m_rq->headers);
296 string getHeader(const char* name) const {
298 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED)
300 return string(hdr ? hdr : "");
302 void setRemoteUser(const char* user) {
303 pblock_nvinsert("remote-user", user, m_rq->headers);
304 pblock_nvinsert("auth-user", user, m_rq->vars);
306 string getRemoteUser() const {
307 return getHeader("remote-user");
309 void setResponseHeader(const char* name, const char* value) {
310 pblock_nvinsert(name, value, m_rq->srvhdrs);
313 long sendResponse(istream& in, long status) {
318 msg.append(buf,in.gcount());
320 pblock_nvinsert("connection","close",m_rq->srvhdrs);
321 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
322 protocol_status(m_sn, m_rq, status, NULL);
323 protocol_start_response(m_sn, m_rq);
324 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
327 long sendRedirect(const char* url) {
328 param_free(pblock_remove("content-type", m_rq->srvhdrs));
329 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
330 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
331 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
332 pblock_nvinsert("location", url, m_rq->srvhdrs);
333 pblock_nvinsert("connection","close",m_rq->srvhdrs);
334 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
335 protocol_start_response(m_sn, m_rq);
338 long returnDecline() { return REQ_NOACTION; }
339 long returnOK() { return REQ_PROCEED; }
340 const vector<XSECCryptoX509*>& getClientCertificates() const {
349 /********************************************************************************/
351 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
353 log_error(LOG_FAILURE,func,sn,rq,msg);
354 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
359 #define FUNC "shibboleth"
360 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
362 ostringstream threadid;
363 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
364 xmltooling::NDC ndc(threadid.str().c_str());
367 ShibTargetNSAPI stn(pb, sn, rq);
369 // Check user authentication
370 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
371 if (res.first) return (int)res.second;
373 // user authN was okay -- export the assertions now
374 param_free(pblock_remove("auth-user",rq->vars));
375 // This seems to be required in order to eventually set
376 // the auth-user var.
377 pblock_nvinsert("auth-type","shibboleth",rq->vars);
378 res = stn.getServiceProvider().doExport(stn);
379 if (res.first) return (int)res.second;
381 // Check the Authorization
382 res = stn.getServiceProvider().doAuthorization(stn);
383 if (res.first) return (int)res.second;
388 catch (exception& e) {
389 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
390 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
394 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an uncaught exception.");
401 #define FUNC "shib_handler"
402 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
404 ostringstream threadid;
405 threadid << "[" << getpid() << "] shib_handler" << '\0';
406 xmltooling::NDC ndc(threadid.str().c_str());
409 ShibTargetNSAPI stn(pb, sn, rq);
411 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
412 if (res.first) return (int)res.second;
414 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
416 catch (exception& e) {
417 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
418 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
422 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
428 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
431 SunRequestMapper(const DOMElement* e);
432 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
433 Lockable* lock() { return m_mapper->lock(); }
434 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
435 Settings getSettings(const SPRequest& request) const;
437 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
438 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
439 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
440 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
441 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
442 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
443 const DOMElement* getElement() const;
446 RequestMapper* m_mapper;
448 ThreadKey* m_propsKey;
451 RequestMapper* SunRequestMapFactory(const DOMElement* const & e)
453 return new SunRequestMapper(e);
456 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
458 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
459 m_stKey=ThreadKey::create(NULL);
460 m_propsKey=ThreadKey::create(NULL);
463 RequestMapper::Settings SunRequestMapper::getSettings(const SPRequest& request) const
465 Settings s=m_mapper->getSettings(request);
466 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
467 m_propsKey->setData((void*)s.first);
468 return pair<const PropertySet*,AccessControl*>(this,s.second);
471 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
473 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
474 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
475 if (stn && !ns && name) {
476 // Override boolean properties.
477 const char* param=pblock_findval(name,stn->m_pb);
478 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
479 return make_pair(true,true);
481 return s ? s->getBool(name,ns) : make_pair(false,false);
484 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
486 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
487 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
488 if (stn && !ns && name) {
489 // Override string properties.
490 if (!strcmp(name,"authType"))
491 return pair<bool,const char*>(true,"shibboleth");
493 const char* param=pblock_findval(name,stn->m_pb);
495 return make_pair(true,param);
498 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
501 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
503 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
504 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
507 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(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 int properties.
513 const char* param=pblock_findval(name,stn->m_pb);
515 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
517 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
520 pair<bool,int> SunRequestMapper::getInt(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 int properties.
526 const char* param=pblock_findval(name,stn->m_pb);
528 return pair<bool,int>(true,atoi(param));
530 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
533 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
535 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
536 return s ? s->getPropertySet(name,ns) : NULL;
539 const DOMElement* SunRequestMapper::getElement() const
541 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
542 return s ? s->getElement() : NULL;