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 IConfig* conf=g_Config->getINI();
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();
214 security_active ? "https" : "http",
220 ~ShibTargetNSAPI() {}
222 const char* getScheme() const {
223 return security_active ? "https" : "http";
225 const char* getHostname() const {
226 #ifdef vs_is_default_vs
227 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
228 if (!vs_is_default_vs)
229 // The beauty here is, a non-default vhost can *only* be accessed if the client
230 // specified the exact name in the Host header. So we can trust the Host header.
231 return pblock_findval("host", m_rq->headers);
234 // In other cases, we're going to rely on the initialization process...
235 return g_ServerName.c_str();
237 int getPort() const {
238 return server_portnum;
240 const char* getRequestURI() const {
241 return m_uri.c_str();
243 const char* getMethod() const {
244 return pblock_findval("method", m_rq->reqpb);
246 string getContentType() const {
247 char* content_type = "";
248 request_header("content-type", &content_type, m_sn, m_rq);
251 long getContentLength() const {
253 return m_body.length();
254 char* content_length="";
255 request_header("content-length", &content_length, m_sn, m_rq);
256 return atoi(content_length);
258 string getRemoteAddr() const {
259 return pblock_findval("ip", m_sn->client);
261 void log(SPLogLevel level, const string& msg) {
262 AbstractSPRequest::log(level,msg);
264 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
266 const char* getQueryString() const {
267 return pblock_findval("query", m_rq->reqpb);
269 const char* getRequestBody() const {
271 return m_body.c_str();
272 char* content_length=NULL;
273 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
274 atoi(content_length) > 1024*1024) // 1MB?
275 throw opensaml::BindingException("Blocked POST request body exceeding size limit.");
278 int cl=atoi(content_length);
280 while (cl && ch != IO_EOF) {
281 ch=netbuf_getc(m_sn->inbuf);
289 throw opensaml::BindingException("Error reading POST request body from browser.");
290 return m_body.c_str();
293 void clearHeader(const char* name) {
294 if (!strcmp(name,"REMOTE_USER")) {
295 param_free(pblock_remove("auth-user",m_rq->vars));
296 param_free(pblock_remove("remote-user",m_rq->headers));
299 param_free(pblock_remove(name, m_rq->headers));
300 pblock_nvinsert(name, g_unsetHeaderValue.c_str() ,m_rq->headers);
303 void setHeader(const char* name, const char* value) {
304 pblock_nvinsert(name, value, m_rq->headers);
306 string getHeader(const char* name) const {
308 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED)
310 return string(hdr ? hdr : "");
312 void setRemoteUser(const char* user) {
313 pblock_nvinsert("remote-user", user, m_rq->headers);
314 pblock_nvinsert("auth-user", user, m_rq->vars);
316 string getRemoteUser() const {
317 return getHeader("remote-user");
319 void setResponseHeader(const char* name, const char* value) {
320 pblock_nvinsert(name, value, m_rq->srvhdrs);
323 long sendResponse(istream& in, long status) {
328 msg.append(buf,in.gcount());
330 pblock_nvinsert("connection","close",m_rq->srvhdrs);
331 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
332 protocol_status(m_sn, m_rq, status, NULL);
333 protocol_start_response(m_sn, m_rq);
334 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
337 long sendRedirect(const char* url) {
338 param_free(pblock_remove("content-type", m_rq->srvhdrs));
339 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
340 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
341 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
342 pblock_nvinsert("location", url, m_rq->srvhdrs);
343 pblock_nvinsert("connection","close",m_rq->srvhdrs);
344 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
345 protocol_start_response(m_sn, m_rq);
348 long returnDecline() { return REQ_NOACTION; }
349 long returnOK() { return REQ_PROCEED; }
350 const vector<XSECCryptoX509*>& getClientCertificates() const {
359 /********************************************************************************/
361 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
363 log_error(LOG_FAILURE,func,sn,rq,msg);
364 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
369 #define FUNC "shibboleth"
370 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
372 ostringstream threadid;
373 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
374 xmltooling::NDC ndc(threadid.str().c_str());
377 ShibTargetNSAPI stn(pb, sn, rq);
379 // Check user authentication
380 pair<bool,long> res = stn.doCheckAuthN();
381 if (res.first) return (int)res.second;
383 // user authN was okay -- export the assertions now
384 param_free(pblock_remove("auth-user",rq->vars));
385 // This seems to be required in order to eventually set
386 // the auth-user var.
387 pblock_nvinsert("auth-type","shibboleth",rq->vars);
388 res = stn.doExportAssertions();
389 if (res.first) return (int)res.second;
391 // Check the Authorization
392 res = stn.doCheckAuthZ();
393 if (res.first) return (int)res.second;
398 catch (exception& e) {
399 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
400 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
404 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an uncaught exception.");
411 #define FUNC "shib_handler"
412 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
414 ostringstream threadid;
415 threadid << "[" << getpid() << "] shib_handler" << '\0';
416 xmltooling::NDC ndc(threadid.str().c_str());
419 ShibTargetNSAPI stn(pb, sn, rq);
421 pair<bool,long> res = stn.doHandler();
422 if (res.first) return (int)res.second;
424 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
426 catch (exception& e) {
427 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
428 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
432 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
438 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
441 SunRequestMapper(const DOMElement* e);
442 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
443 Lockable* lock() { return m_mapper->lock(); }
444 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
445 Settings getSettings(const SPRequest& request) const;
447 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
448 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
449 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
450 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
451 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
452 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
453 const DOMElement* getElement() const;
456 RequestMapper* m_mapper;
458 ThreadKey* m_propsKey;
461 RequestMapper* SunRequestMapFactory(const DOMElement* const & e)
463 return new SunRequestMapper(e);
466 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
468 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
469 m_stKey=ThreadKey::create(NULL);
470 m_propsKey=ThreadKey::create(NULL);
473 RequestMapper::Settings SunRequestMapper::getSettings(const SPRequest& request) const
475 Settings s=m_mapper->getSettings(request);
476 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
477 m_propsKey->setData((void*)s.first);
478 return pair<const PropertySet*,AccessControl*>(this,s.second);
481 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
483 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
484 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
485 if (stn && !ns && name) {
486 // Override boolean properties.
487 const char* param=pblock_findval(name,stn->m_pb);
488 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
489 return make_pair(true,true);
491 return s ? s->getBool(name,ns) : make_pair(false,false);
494 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
496 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
497 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
498 if (stn && !ns && name) {
499 // Override string properties.
500 if (!strcmp(name,"authType"))
501 return pair<bool,const char*>(true,"shibboleth");
503 const char* param=pblock_findval(name,stn->m_pb);
505 return make_pair(true,param);
508 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
511 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
513 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
514 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
517 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
519 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
520 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
521 if (stn && !ns && name) {
522 // Override int properties.
523 const char* param=pblock_findval(name,stn->m_pb);
525 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
527 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
530 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
532 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
533 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
534 if (stn && !ns && name) {
535 // Override int properties.
536 const char* param=pblock_findval(name,stn->m_pb);
538 return pair<bool,int>(true,atoi(param));
540 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
543 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
545 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
546 return s ? s->getPropertySet(name,ns) : NULL;
549 const DOMElement* SunRequestMapper::getElement() const
551 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
552 return s ? s->getElement() : NULL;