2 * Copyright 2001-2005 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/RequestMapper.h>
35 #include <shibsp/SPConfig.h>
36 #include <xmltooling/util/NDC.h>
37 #include <xmltooling/util/Threads.h>
40 #include <saml/saml.h>
41 #include <shib/shib.h>
42 #include <shib-target/shib-target.h>
62 using namespace shibsp;
63 using namespace shibtarget;
64 using namespace xmltooling;
67 // macros to output text to client
68 #define NET_WRITE(str) \
69 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
72 ShibTargetConfig* g_Config=NULL;
74 string g_ServerScheme;
75 string g_unsetHeaderValue;
78 PluginManager<RequestMapper,const DOMElement*>::Factory SunRequestMapFactory;
80 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
87 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
89 // Save off a default hostname for this virtual server.
90 char* name=pblock_findval("server-name",pb);
104 pblock_nvinsert("error","unable to determine web server hostname",pb);
109 name=pblock_findval("server-scheme",pb);
113 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
118 const char* schemadir=pblock_findval("shib-schemas",pb);
120 schemadir=getenv("SHIBSCHEMAS");
122 schemadir=SHIB_SCHEMAS;
123 const char* config=pblock_findval("shib-config",pb);
125 config=getenv("SHIBCONFIG");
128 g_Config=&ShibTargetConfig::getConfig();
129 SPConfig::getConfig().setFeatures(
134 SPConfig::RequestMapping |
135 SPConfig::InProcess |
138 if (!g_Config->init(schemadir)) {
140 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
144 SPConfig::getConfig().RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
146 if (!g_Config->load(config)) {
148 pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
152 daemon_atrestart(nsapi_shib_exit,NULL);
154 ServiceProvider* conf=SPConfig::getConfig().getServiceProvider();
156 const PropertySet* props=conf->getPropertySet("Local");
158 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
159 if (unsetValue.first)
160 g_unsetHeaderValue = unsetValue.second;
166 pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
173 /********************************************************************************/
174 // NSAPI Shib Target Subclass
176 class ShibTargetNSAPI : public ShibTarget
179 mutable string m_body;
180 mutable bool m_gotBody;
181 vector<XSECCryptoX509*> m_certs;
184 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq) : m_gotBody(false) {
189 // Get everything but hostname...
190 const char* uri=pblock_findval("uri", rq->reqpb);
191 const char* qstr=pblock_findval("query", rq->reqpb);
199 url=url + '?' + qstr;
201 const char* host=NULL;
202 #ifdef vs_is_default_vs
203 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
204 if (!vs_is_default_vs)
205 // The beauty here is, a non-default vhost can *only* be accessed if the client
206 // specified the exact name in the Host header. So we can trust the Host header.
207 host=pblock_findval("host", rq->headers);
210 // In other cases, we're going to rely on the initialization process...
211 host=g_ServerName.c_str();
213 ~ShibTargetNSAPI() {}
215 const char* getScheme() const {
216 return security_active ? "https" : "http";
218 const char* getHostname() const {
219 #ifdef vs_is_default_vs
220 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
221 if (!vs_is_default_vs)
222 // The beauty here is, a non-default vhost can *only* be accessed if the client
223 // specified the exact name in the Host header. So we can trust the Host header.
224 return pblock_findval("host", m_rq->headers);
227 // In other cases, we're going to rely on the initialization process...
228 return g_ServerName.c_str();
230 int getPort() const {
231 return server_portnum;
233 const char* getRequestURI() const {
234 return m_uri.c_str();
236 const char* getMethod() const {
237 return pblock_findval("method", m_rq->reqpb);
239 string getContentType() const {
240 char* content_type = "";
241 request_header("content-type", &content_type, m_sn, m_rq);
244 long getContentLength() const {
246 return m_body.length();
247 char* content_length="";
248 request_header("content-length", &content_length, m_sn, m_rq);
249 return atoi(content_length);
251 string getRemoteAddr() const {
252 return pblock_findval("ip", m_sn->client);
254 void log(SPLogLevel level, const string& msg) {
255 AbstractSPRequest::log(level,msg);
257 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
259 const char* getQueryString() const {
260 return pblock_findval("query", m_rq->reqpb);
262 const char* getRequestBody() const {
264 return m_body.c_str();
265 char* content_length=NULL;
266 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
267 atoi(content_length) > 1024*1024) // 1MB?
268 throw opensaml::BindingException("Blocked POST request body exceeding size limit.");
271 int cl=atoi(content_length);
273 while (cl && ch != IO_EOF) {
274 ch=netbuf_getc(m_sn->inbuf);
282 throw opensaml::BindingException("Error reading POST request body from browser.");
283 return m_body.c_str();
286 void clearHeader(const char* name) {
287 if (!strcmp(name,"REMOTE_USER")) {
288 param_free(pblock_remove("auth-user",m_rq->vars));
289 param_free(pblock_remove("remote-user",m_rq->headers));
292 param_free(pblock_remove(name, m_rq->headers));
293 pblock_nvinsert(name, g_unsetHeaderValue.c_str() ,m_rq->headers);
296 void setHeader(const char* name, const char* value) {
297 pblock_nvinsert(name, value, m_rq->headers);
299 string getHeader(const char* name) const {
301 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED)
303 return string(hdr ? hdr : "");
305 void setRemoteUser(const char* user) {
306 pblock_nvinsert("remote-user", user, m_rq->headers);
307 pblock_nvinsert("auth-user", user, m_rq->vars);
309 string getRemoteUser() const {
310 return getHeader("remote-user");
312 void setResponseHeader(const char* name, const char* value) {
313 pblock_nvinsert(name, value, m_rq->srvhdrs);
316 long sendResponse(istream& in, long status) {
321 msg.append(buf,in.gcount());
323 pblock_nvinsert("connection","close",m_rq->srvhdrs);
324 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
325 protocol_status(m_sn, m_rq, status, NULL);
326 protocol_start_response(m_sn, m_rq);
327 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
330 long sendRedirect(const char* url) {
331 param_free(pblock_remove("content-type", m_rq->srvhdrs));
332 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
333 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
334 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
335 pblock_nvinsert("location", url, m_rq->srvhdrs);
336 pblock_nvinsert("connection","close",m_rq->srvhdrs);
337 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
338 protocol_start_response(m_sn, m_rq);
341 long returnDecline() { return REQ_NOACTION; }
342 long returnOK() { return REQ_PROCEED; }
343 const vector<XSECCryptoX509*>& getClientCertificates() const {
352 /********************************************************************************/
354 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
356 log_error(LOG_FAILURE,func,sn,rq,msg);
357 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
362 #define FUNC "shibboleth"
363 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
365 ostringstream threadid;
366 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
367 xmltooling::NDC ndc(threadid.str().c_str());
370 ShibTargetNSAPI stn(pb, sn, rq);
372 // Check user authentication
373 pair<bool,long> res = stn.doCheckAuthN();
374 if (res.first) return (int)res.second;
376 // user authN was okay -- export the assertions now
377 param_free(pblock_remove("auth-user",rq->vars));
378 // This seems to be required in order to eventually set
379 // the auth-user var.
380 pblock_nvinsert("auth-type","shibboleth",rq->vars);
381 res = stn.doExportAssertions();
382 if (res.first) return (int)res.second;
384 // Check the Authorization
385 res = stn.doCheckAuthZ();
386 if (res.first) return (int)res.second;
391 catch (exception& e) {
392 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
393 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
397 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an uncaught exception.");
404 #define FUNC "shib_handler"
405 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
407 ostringstream threadid;
408 threadid << "[" << getpid() << "] shib_handler" << '\0';
409 xmltooling::NDC ndc(threadid.str().c_str());
412 ShibTargetNSAPI stn(pb, sn, rq);
414 pair<bool,long> res = stn.doHandler();
415 if (res.first) return (int)res.second;
417 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
419 catch (exception& e) {
420 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
421 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
425 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
431 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
434 SunRequestMapper(const DOMElement* e);
435 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
436 Lockable* lock() { return m_mapper->lock(); }
437 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
438 Settings getSettings(const SPRequest& request) const;
440 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
441 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
442 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
443 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
444 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
445 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
446 const DOMElement* getElement() const;
449 RequestMapper* m_mapper;
451 ThreadKey* m_propsKey;
454 RequestMapper* SunRequestMapFactory(const DOMElement* const & e)
456 return new SunRequestMapper(e);
459 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
461 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
462 m_stKey=ThreadKey::create(NULL);
463 m_propsKey=ThreadKey::create(NULL);
466 RequestMapper::Settings SunRequestMapper::getSettings(const SPRequest& request) const
468 Settings s=m_mapper->getSettings(request);
469 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
470 m_propsKey->setData((void*)s.first);
471 return pair<const PropertySet*,AccessControl*>(this,s.second);
474 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
476 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
477 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
478 if (stn && !ns && name) {
479 // Override boolean properties.
480 const char* param=pblock_findval(name,stn->m_pb);
481 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
482 return make_pair(true,true);
484 return s ? s->getBool(name,ns) : make_pair(false,false);
487 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
489 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
490 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
491 if (stn && !ns && name) {
492 // Override string properties.
493 if (!strcmp(name,"authType"))
494 return pair<bool,const char*>(true,"shibboleth");
496 const char* param=pblock_findval(name,stn->m_pb);
498 return make_pair(true,param);
501 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
504 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
506 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
507 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
510 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
512 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
513 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
514 if (stn && !ns && name) {
515 // Override int properties.
516 const char* param=pblock_findval(name,stn->m_pb);
518 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
520 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
523 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
525 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
526 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
527 if (stn && !ns && name) {
528 // Override int properties.
529 const char* param=pblock_findval(name,stn->m_pb);
531 return pair<bool,int>(true,atoi(param));
533 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
536 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
538 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
539 return s ? s->getPropertySet(name,ns) : NULL;
542 const DOMElement* SunRequestMapper::getElement() const
544 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
545 return s ? s->getElement() : NULL;