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,const 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(
133 SPConfig::RequestMapping |
134 SPConfig::InProcess |
137 if (!g_Config->init(schemadir)) {
139 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
143 g_Config->RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
146 DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
147 XercesJanitor<DOMDocument> docjanitor(dummydoc);
148 DOMElement* dummy = dummydoc->createElementNS(NULL,path);
149 auto_ptr_XMLCh src(config);
150 dummy->setAttributeNS(NULL,path,src.get());
151 dummy->setAttributeNS(NULL,validate,xmlconstants::XML_ONE);
153 g_Config->setServiceProvider(g_Config->ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER,dummy));
154 g_Config->getServiceProvider()->init();
156 catch (exception& ex) {
157 pblock_nvinsert("error",ex.what(),pb);
163 daemon_atrestart(nsapi_shib_exit,NULL);
165 ServiceProvider* sp=g_Config->getServiceProvider();
167 const PropertySet* props=sp->getPropertySet("Local");
169 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
170 if (unsetValue.first)
171 g_unsetHeaderValue = unsetValue.second;
176 /********************************************************************************/
177 // NSAPI Shib Target Subclass
179 class ShibTargetNSAPI : public AbstractSPRequest
182 mutable string m_body;
183 mutable bool m_gotBody;
184 vector<XSECCryptoX509*> m_certs;
187 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq) : m_gotBody(false) {
192 // Get everything but hostname...
193 const char* uri=pblock_findval("uri", rq->reqpb);
194 const char* qstr=pblock_findval("query", rq->reqpb);
202 url=url + '?' + qstr;
204 const char* host=NULL;
205 #ifdef vs_is_default_vs
206 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
207 if (!vs_is_default_vs)
208 // The beauty here is, a non-default vhost can *only* be accessed if the client
209 // specified the exact name in the Host header. So we can trust the Host header.
210 host=pblock_findval("host", rq->headers);
213 // In other cases, we're going to rely on the initialization process...
214 host=g_ServerName.c_str();
216 ~ShibTargetNSAPI() {}
218 const char* getScheme() const {
219 return security_active ? "https" : "http";
221 const char* getHostname() const {
222 #ifdef vs_is_default_vs
223 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
224 if (!vs_is_default_vs)
225 // The beauty here is, a non-default vhost can *only* be accessed if the client
226 // specified the exact name in the Host header. So we can trust the Host header.
227 return pblock_findval("host", m_rq->headers);
230 // In other cases, we're going to rely on the initialization process...
231 return g_ServerName.c_str();
233 int getPort() const {
234 return server_portnum;
236 const char* getRequestURI() const {
237 return m_uri.c_str();
239 const char* getMethod() const {
240 return pblock_findval("method", m_rq->reqpb);
242 string getContentType() const {
243 char* content_type = "";
244 request_header("content-type", &content_type, m_sn, m_rq);
247 long getContentLength() const {
249 return m_body.length();
250 char* content_length="";
251 request_header("content-length", &content_length, m_sn, m_rq);
252 return atoi(content_length);
254 string getRemoteAddr() const {
255 return pblock_findval("ip", m_sn->client);
257 void log(SPLogLevel level, const string& msg) {
258 AbstractSPRequest::log(level,msg);
260 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
262 const char* getQueryString() const {
263 return pblock_findval("query", m_rq->reqpb);
265 const char* getRequestBody() const {
267 return m_body.c_str();
268 char* content_length=NULL;
269 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED || atoi(content_length) > 1024*1024) // 1MB?
270 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
273 int cl=atoi(content_length);
275 while (cl && ch != IO_EOF) {
276 ch=netbuf_getc(m_sn->inbuf);
284 throw IOException("Error reading request body from browser.");
285 return m_body.c_str();
288 void clearHeader(const char* name) {
289 if (!strcmp(name,"REMOTE_USER")) {
290 param_free(pblock_remove("auth-user",m_rq->vars));
291 param_free(pblock_remove("remote-user",m_rq->headers));
294 param_free(pblock_remove(name, m_rq->headers));
295 pblock_nvinsert(name, g_unsetHeaderValue.c_str() ,m_rq->headers);
298 void setHeader(const char* name, const char* value) {
299 pblock_nvinsert(name, value, m_rq->headers);
301 string getHeader(const char* name) const {
303 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED)
305 return string(hdr ? hdr : "");
307 void setRemoteUser(const char* user) {
308 pblock_nvinsert("remote-user", user, m_rq->headers);
309 pblock_nvinsert("auth-user", user, m_rq->vars);
311 string getRemoteUser() const {
312 return getHeader("remote-user");
314 void setResponseHeader(const char* name, const char* value) {
315 pblock_nvinsert(name, value, m_rq->srvhdrs);
318 long sendResponse(istream& in, long status) {
323 msg.append(buf,in.gcount());
325 pblock_nvinsert("connection","close",m_rq->srvhdrs);
326 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
327 protocol_status(m_sn, m_rq, status, NULL);
328 protocol_start_response(m_sn, m_rq);
329 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
332 long sendRedirect(const char* url) {
333 param_free(pblock_remove("content-type", m_rq->srvhdrs));
334 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
335 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
336 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
337 pblock_nvinsert("location", url, m_rq->srvhdrs);
338 pblock_nvinsert("connection","close",m_rq->srvhdrs);
339 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
340 protocol_start_response(m_sn, m_rq);
343 long returnDecline() { return REQ_NOACTION; }
344 long returnOK() { return REQ_PROCEED; }
345 const vector<XSECCryptoX509*>& getClientCertificates() const {
354 /********************************************************************************/
356 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
358 log_error(LOG_FAILURE,func,sn,rq,msg);
359 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
364 #define FUNC "shibboleth"
365 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
367 ostringstream threadid;
368 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
369 xmltooling::NDC ndc(threadid.str().c_str());
372 ShibTargetNSAPI stn(pb, sn, rq);
374 // Check user authentication
375 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
376 if (res.first) return (int)res.second;
378 // user authN was okay -- export the assertions now
379 param_free(pblock_remove("auth-user",rq->vars));
380 // This seems to be required in order to eventually set
381 // the auth-user var.
382 pblock_nvinsert("auth-type","shibboleth",rq->vars);
383 res = stn.getServiceProvider().doExport(stn);
384 if (res.first) return (int)res.second;
386 // Check the Authorization
387 res = stn.getServiceProvider().doAuthorization(stn);
388 if (res.first) return (int)res.second;
393 catch (exception& e) {
394 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
395 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
399 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an uncaught exception.");
406 #define FUNC "shib_handler"
407 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
409 ostringstream threadid;
410 threadid << "[" << getpid() << "] shib_handler" << '\0';
411 xmltooling::NDC ndc(threadid.str().c_str());
414 ShibTargetNSAPI stn(pb, sn, rq);
416 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
417 if (res.first) return (int)res.second;
419 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
421 catch (exception& e) {
422 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
423 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
427 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
433 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
436 SunRequestMapper(const DOMElement* e);
437 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
438 Lockable* lock() { return m_mapper->lock(); }
439 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
440 Settings getSettings(const SPRequest& request) const;
442 void setParent(const PropertySet*) {}
443 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
444 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
445 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
446 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
447 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
448 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
449 const DOMElement* getElement() const;
452 RequestMapper* m_mapper;
454 ThreadKey* m_propsKey;
457 RequestMapper* SunRequestMapFactory(const DOMElement* const & e)
459 return new SunRequestMapper(e);
462 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
464 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
465 m_stKey=ThreadKey::create(NULL);
466 m_propsKey=ThreadKey::create(NULL);
469 RequestMapper::Settings SunRequestMapper::getSettings(const SPRequest& request) const
471 Settings s=m_mapper->getSettings(request);
472 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
473 m_propsKey->setData((void*)s.first);
474 return pair<const PropertySet*,AccessControl*>(this,s.second);
477 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
479 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
480 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
481 if (stn && !ns && name) {
482 // Override boolean properties.
483 const char* param=pblock_findval(name,stn->m_pb);
484 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
485 return make_pair(true,true);
487 return s ? s->getBool(name,ns) : make_pair(false,false);
490 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
492 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
493 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
494 if (stn && !ns && name) {
495 // Override string properties.
496 if (!strcmp(name,"authType"))
497 return pair<bool,const char*>(true,"shibboleth");
499 const char* param=pblock_findval(name,stn->m_pb);
501 return make_pair(true,param);
504 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
507 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
509 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
510 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
513 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
515 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
516 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
517 if (stn && !ns && name) {
518 // Override int properties.
519 const char* param=pblock_findval(name,stn->m_pb);
521 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
523 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
526 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
528 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
529 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
530 if (stn && !ns && name) {
531 // Override int properties.
532 const char* param=pblock_findval(name,stn->m_pb);
534 return pair<bool,int>(true,atoi(param));
536 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
539 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
541 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
542 return s ? s->getPropertySet(name,ns) : NULL;
545 const DOMElement* SunRequestMapper::getElement() const
547 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
548 return s ? s->getElement() : NULL;