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/XMLConstants.h>
42 #include <xmltooling/util/XMLHelper.h>
43 #include <xercesc/util/XMLUniDefs.hpp>
63 using namespace shibsp;
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 SPConfig* g_Config=NULL;
74 string g_ServerScheme;
75 string g_unsetHeaderValue;
77 static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
78 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
81 PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
83 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
90 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
92 // Save off a default hostname for this virtual server.
93 char* name=pblock_findval("server-name",pb);
101 name=util_hostname();
107 pblock_nvinsert("error","unable to determine web server hostname",pb);
112 name=pblock_findval("server-scheme",pb);
116 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("SHIBSP_SCHEMAS");
122 schemadir=SHIBSP_SCHEMAS;
123 const char* config=pblock_findval("shib-config",pb);
125 config=getenv("SHIBSP_CONFIG");
127 config=SHIBSP_CONFIG;
128 g_Config=&SPConfig::getConfig();
129 g_Config->setFeatures(
132 SPConfig::RequestMapping |
133 SPConfig::InProcess |
136 if (!g_Config->init(schemadir)) {
138 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
142 g_Config->RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
145 xercesc::DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
146 XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
147 xercesc::DOMElement* dummy = dummydoc->createElementNS(NULL,path);
148 auto_ptr_XMLCh src(config);
149 dummy->setAttributeNS(NULL,path,src.get());
150 dummy->setAttributeNS(NULL,validate,xmlconstants::XML_ONE);
152 g_Config->setServiceProvider(g_Config->ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER,dummy));
153 g_Config->getServiceProvider()->init();
155 catch (exception& ex) {
156 pblock_nvinsert("error",ex.what(),pb);
162 daemon_atrestart(nsapi_shib_exit,NULL);
164 ServiceProvider* sp=g_Config->getServiceProvider();
166 const PropertySet* props=sp->getPropertySet("Local");
168 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
169 if (unsetValue.first)
170 g_unsetHeaderValue = unsetValue.second;
175 /********************************************************************************/
176 // NSAPI Shib Target Subclass
178 class ShibTargetNSAPI : public AbstractSPRequest
181 mutable string m_body;
182 mutable bool m_gotBody;
183 vector<string> m_certs;
186 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq) : m_gotBody(false) {
191 // Get everything but hostname...
192 const char* uri=pblock_findval("uri", rq->reqpb);
193 const char* qstr=pblock_findval("query", rq->reqpb);
201 url=url + '?' + qstr;
203 const char* host=NULL;
204 #ifdef vs_is_default_vs
205 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
206 if (!vs_is_default_vs)
207 // The beauty here is, a non-default vhost can *only* be accessed if the client
208 // specified the exact name in the Host header. So we can trust the Host header.
209 host=pblock_findval("host", rq->headers);
212 // In other cases, we're going to rely on the initialization process...
213 host=g_ServerName.c_str();
215 ~ShibTargetNSAPI() {}
217 const char* getScheme() const {
218 return security_active ? "https" : "http";
220 const char* getHostname() const {
221 #ifdef vs_is_default_vs
222 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
223 if (!vs_is_default_vs)
224 // The beauty here is, a non-default vhost can *only* be accessed if the client
225 // specified the exact name in the Host header. So we can trust the Host header.
226 return pblock_findval("host", m_rq->headers);
229 // In other cases, we're going to rely on the initialization process...
230 return g_ServerName.c_str();
232 int getPort() const {
233 return server_portnum;
235 const char* getRequestURI() const {
236 return m_uri.c_str();
238 const char* getMethod() const {
239 return pblock_findval("method", m_rq->reqpb);
241 string getContentType() const {
242 char* content_type = "";
243 request_header("content-type", &content_type, m_sn, m_rq);
246 long getContentLength() const {
248 return m_body.length();
249 char* content_length="";
250 request_header("content-length", &content_length, m_sn, m_rq);
251 return atoi(content_length);
253 string getRemoteAddr() const {
254 return pblock_findval("ip", m_sn->client);
256 void log(SPLogLevel level, const string& msg) {
257 AbstractSPRequest::log(level,msg);
259 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
261 const char* getQueryString() const {
262 return pblock_findval("query", m_rq->reqpb);
264 const char* getRequestBody() const {
266 return m_body.c_str();
267 char* content_length=NULL;
268 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED || atoi(content_length) > 1024*1024) // 1MB?
269 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
272 int cl=atoi(content_length);
274 while (cl && ch != IO_EOF) {
275 ch=netbuf_getc(m_sn->inbuf);
283 throw IOException("Error reading 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<string>& 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 xercesc::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 void setParent(const PropertySet*) {}
442 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
443 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
444 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
445 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
446 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
447 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const;
448 const xercesc::DOMElement* getElement() const;
451 RequestMapper* m_mapper;
453 ThreadKey* m_propsKey;
456 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
458 return new SunRequestMapper(e);
461 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
463 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
464 m_stKey=ThreadKey::create(NULL);
465 m_propsKey=ThreadKey::create(NULL);
468 RequestMapper::Settings SunRequestMapper::getSettings(const SPRequest& request) const
470 Settings s=m_mapper->getSettings(request);
471 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
472 m_propsKey->setData((void*)s.first);
473 return pair<const PropertySet*,AccessControl*>(this,s.second);
476 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
478 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
479 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
480 if (stn && !ns && name) {
481 // Override boolean properties.
482 const char* param=pblock_findval(name,stn->m_pb);
483 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
484 return make_pair(true,true);
486 return s ? s->getBool(name,ns) : make_pair(false,false);
489 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
491 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
492 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
493 if (stn && !ns && name) {
494 // Override string properties.
495 if (!strcmp(name,"authType"))
496 return pair<bool,const char*>(true,"shibboleth");
498 const char* param=pblock_findval(name,stn->m_pb);
500 return make_pair(true,param);
503 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
506 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
508 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
509 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
512 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
514 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
515 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
516 if (stn && !ns && name) {
517 // Override int properties.
518 const char* param=pblock_findval(name,stn->m_pb);
520 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
522 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
525 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
527 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
528 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
529 if (stn && !ns && name) {
530 // Override int properties.
531 const char* param=pblock_findval(name,stn->m_pb);
533 return pair<bool,int>(true,atoi(param));
535 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
538 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
540 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
541 return s ? s->getPropertySet(name,ns) : NULL;
544 const xercesc::DOMElement* SunRequestMapper::getElement() const
546 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
547 return s ? s->getElement() : NULL;