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
25 #if defined (_MSC_VER) || defined(__BORLANDC__)
26 # include "config_win32.h"
32 # define _CRT_NONSTDC_NO_DEPRECATE 1
33 # define _CRT_SECURE_NO_DEPRECATE 1
36 #include <shibsp/AbstractSPRequest.h>
37 #include <shibsp/RequestMapper.h>
38 #include <shibsp/SPConfig.h>
39 #include <shibsp/ServiceProvider.h>
40 #include <xmltooling/XMLToolingConfig.h>
41 #include <xmltooling/util/NDC.h>
42 #include <xmltooling/util/Threads.h>
43 #include <xmltooling/util/XMLConstants.h>
44 #include <xmltooling/util/XMLHelper.h>
45 #include <xercesc/util/XMLUniDefs.hpp>
65 using namespace shibsp;
66 using namespace xmltooling;
69 // macros to output text to client
70 #define NET_WRITE(str) \
71 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
74 SPConfig* g_Config=NULL;
76 string g_ServerScheme;
77 string g_unsetHeaderValue;
79 static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
80 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
83 PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
85 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
92 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
94 // Save off a default hostname for this virtual server.
95 char* name=pblock_findval("server-name",pb);
103 name=util_hostname();
109 pblock_nvinsert("error","unable to determine web server hostname",pb);
114 name=pblock_findval("server-scheme",pb);
118 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
120 const char* schemadir=pblock_findval("shib-schemas",pb);
122 schemadir=getenv("SHIBSP_SCHEMAS");
124 schemadir=SHIBSP_SCHEMAS;
125 const char* config=pblock_findval("shib-config",pb);
127 config=getenv("SHIBSP_CONFIG");
129 config=SHIBSP_CONFIG;
130 g_Config=&SPConfig::getConfig();
131 g_Config->setFeatures(
134 SPConfig::RequestMapping |
135 SPConfig::InProcess |
138 if (!g_Config->init(schemadir)) {
140 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
144 g_Config->RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
147 xercesc::DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
148 XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
149 xercesc::DOMElement* dummy = dummydoc->createElementNS(NULL,path);
150 auto_ptr_XMLCh src(config);
151 dummy->setAttributeNS(NULL,path,src.get());
152 dummy->setAttributeNS(NULL,validate,xmlconstants::XML_ONE);
154 g_Config->setServiceProvider(g_Config->ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER,dummy));
155 g_Config->getServiceProvider()->init();
157 catch (exception& ex) {
158 pblock_nvinsert("error",ex.what(),pb);
164 daemon_atrestart(nsapi_shib_exit,NULL);
166 ServiceProvider* sp=g_Config->getServiceProvider();
168 const PropertySet* props=sp->getPropertySet("Local");
170 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
171 if (unsetValue.first)
172 g_unsetHeaderValue = unsetValue.second;
177 /********************************************************************************/
178 // NSAPI Shib Target Subclass
180 class ShibTargetNSAPI : public AbstractSPRequest
183 mutable string m_body;
184 mutable bool m_gotBody;
185 vector<string> m_certs;
188 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq) : m_gotBody(false) {
193 // Get everything but hostname...
194 const char* uri=pblock_findval("uri", rq->reqpb);
195 const char* qstr=pblock_findval("query", rq->reqpb);
203 url=url + '?' + qstr;
205 const char* host=NULL;
206 #ifdef vs_is_default_vs
207 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
208 if (!vs_is_default_vs)
209 // The beauty here is, a non-default vhost can *only* be accessed if the client
210 // specified the exact name in the Host header. So we can trust the Host header.
211 host=pblock_findval("host", rq->headers);
214 // In other cases, we're going to rely on the initialization process...
215 host=g_ServerName.c_str();
217 ~ShibTargetNSAPI() {}
219 const char* getScheme() const {
220 return security_active ? "https" : "http";
222 const char* getHostname() const {
223 #ifdef vs_is_default_vs
224 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
225 if (!vs_is_default_vs)
226 // The beauty here is, a non-default vhost can *only* be accessed if the client
227 // specified the exact name in the Host header. So we can trust the Host header.
228 return pblock_findval("host", m_rq->headers);
231 // In other cases, we're going to rely on the initialization process...
232 return g_ServerName.c_str();
234 int getPort() const {
235 return server_portnum;
237 const char* getRequestURI() const {
238 return m_uri.c_str();
240 const char* getMethod() const {
241 return pblock_findval("method", m_rq->reqpb);
243 string getContentType() const {
244 char* content_type = "";
245 request_header("content-type", &content_type, m_sn, m_rq);
248 long getContentLength() const {
250 return m_body.length();
251 char* content_length="";
252 request_header("content-length", &content_length, m_sn, m_rq);
253 return atoi(content_length);
255 string getRemoteAddr() const {
256 return pblock_findval("ip", m_sn->client);
258 void log(SPLogLevel level, const string& msg) const {
259 AbstractSPRequest::log(level,msg);
261 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
263 const char* getQueryString() const {
264 return pblock_findval("query", m_rq->reqpb);
266 const char* getRequestBody() const {
268 return m_body.c_str();
269 char* content_length=NULL;
270 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED || atoi(content_length) > 1024*1024) // 1MB?
271 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
274 int cl=atoi(content_length);
276 while (cl && ch != IO_EOF) {
277 ch=netbuf_getc(m_sn->inbuf);
285 throw IOException("Error reading request body from browser.");
286 return m_body.c_str();
289 void clearHeader(const char* name) {
290 if (!strcmp(name,"REMOTE_USER")) {
291 param_free(pblock_remove("auth-user",m_rq->vars));
292 param_free(pblock_remove("remote-user",m_rq->headers));
295 param_free(pblock_remove(name, m_rq->headers));
296 pblock_nvinsert(name, g_unsetHeaderValue.c_str() ,m_rq->headers);
299 void setHeader(const char* name, const char* value) {
300 pblock_nvinsert(name, value, m_rq->headers);
302 string getHeader(const char* name) const {
304 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED)
306 return string(hdr ? hdr : "");
308 void setRemoteUser(const char* user) {
309 pblock_nvinsert("remote-user", user, m_rq->headers);
310 pblock_nvinsert("auth-user", user, m_rq->vars);
312 string getRemoteUser() const {
313 return getHeader("remote-user");
315 void setResponseHeader(const char* name, const char* value) {
316 pblock_nvinsert(name, value, m_rq->srvhdrs);
319 long sendResponse(istream& in, long status) {
324 msg.append(buf,in.gcount());
326 pblock_nvinsert("connection","close",m_rq->srvhdrs);
327 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
328 protocol_status(m_sn, m_rq, status, NULL);
329 protocol_start_response(m_sn, m_rq);
330 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
333 long sendRedirect(const char* url) {
334 param_free(pblock_remove("content-type", m_rq->srvhdrs));
335 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
336 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
337 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
338 pblock_nvinsert("location", url, m_rq->srvhdrs);
339 pblock_nvinsert("connection","close",m_rq->srvhdrs);
340 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
341 protocol_start_response(m_sn, m_rq);
344 long returnDecline() { return REQ_NOACTION; }
345 long returnOK() { return REQ_PROCEED; }
346 const vector<string>& getClientCertificates() const {
355 /********************************************************************************/
357 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
359 log_error(LOG_FAILURE,func,sn,rq,msg);
360 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
365 #define FUNC "shibboleth"
366 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
368 ostringstream threadid;
369 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
370 xmltooling::NDC ndc(threadid.str().c_str());
373 ShibTargetNSAPI stn(pb, sn, rq);
375 // Check user authentication
376 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
377 if (res.first) return (int)res.second;
379 // user authN was okay -- export the assertions now
380 param_free(pblock_remove("auth-user",rq->vars));
381 // This seems to be required in order to eventually set
382 // the auth-user var.
383 pblock_nvinsert("auth-type","shibboleth",rq->vars);
384 res = stn.getServiceProvider().doExport(stn);
385 if (res.first) return (int)res.second;
387 // Check the Authorization
388 res = stn.getServiceProvider().doAuthorization(stn);
389 if (res.first) return (int)res.second;
394 catch (exception& e) {
395 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
396 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
400 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an uncaught exception.");
407 #define FUNC "shib_handler"
408 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
410 ostringstream threadid;
411 threadid << "[" << getpid() << "] shib_handler" << '\0';
412 xmltooling::NDC ndc(threadid.str().c_str());
415 ShibTargetNSAPI stn(pb, sn, rq);
417 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
418 if (res.first) return (int)res.second;
420 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
422 catch (exception& e) {
423 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
424 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
428 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
434 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
437 SunRequestMapper(const xercesc::DOMElement* e);
438 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
439 Lockable* lock() { return m_mapper->lock(); }
440 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
441 Settings getSettings(const SPRequest& request) const;
443 void setParent(const PropertySet*) {}
444 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
445 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
446 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
447 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
448 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
449 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const;
450 const xercesc::DOMElement* getElement() const;
453 RequestMapper* m_mapper;
455 ThreadKey* m_propsKey;
458 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
460 return new SunRequestMapper(e);
463 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
465 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
466 m_stKey=ThreadKey::create(NULL);
467 m_propsKey=ThreadKey::create(NULL);
470 RequestMapper::Settings SunRequestMapper::getSettings(const SPRequest& request) const
472 Settings s=m_mapper->getSettings(request);
473 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
474 m_propsKey->setData((void*)s.first);
475 return pair<const PropertySet*,AccessControl*>(this,s.second);
478 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
480 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
481 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
482 if (stn && !ns && name) {
483 // Override boolean properties.
484 const char* param=pblock_findval(name,stn->m_pb);
485 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
486 return make_pair(true,true);
488 return s ? s->getBool(name,ns) : make_pair(false,false);
491 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
493 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
494 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
495 if (stn && !ns && name) {
496 // Override string properties.
497 if (!strcmp(name,"authType"))
498 return pair<bool,const char*>(true,"shibboleth");
500 const char* param=pblock_findval(name,stn->m_pb);
502 return make_pair(true,param);
505 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
508 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
510 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
511 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
514 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
516 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
517 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
518 if (stn && !ns && name) {
519 // Override int properties.
520 const char* param=pblock_findval(name,stn->m_pb);
522 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
524 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
527 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
529 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
530 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
531 if (stn && !ns && name) {
532 // Override int properties.
533 const char* param=pblock_findval(name,stn->m_pb);
535 return pair<bool,int>(true,atoi(param));
537 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
540 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
542 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
543 return s ? s->getPropertySet(name,ns) : NULL;
546 const xercesc::DOMElement* SunRequestMapper::getElement() const
548 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
549 return s ? s->getElement() : NULL;