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>
66 using namespace shibsp;
67 using namespace xmltooling;
70 // macros to output text to client
71 #define NET_WRITE(str) \
72 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
75 SPConfig* g_Config=NULL;
77 string g_ServerScheme;
78 string g_unsetHeaderValue;
79 bool g_checkSpoofing = true;
80 bool g_catchAll = false;
82 static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
83 static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
86 PluginManager<RequestMapper,string,const xercesc::DOMElement*>::Factory SunRequestMapFactory;
88 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
95 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, ::Session* sn, Request* rq)
97 // Save off a default hostname for this virtual server.
98 char* name=pblock_findval("server-name",pb);
102 name=server_hostname;
106 name=util_hostname();
112 pblock_nvinsert("error","unable to determine web server hostname",pb);
117 name=pblock_findval("server-scheme",pb);
121 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
123 const char* schemadir=pblock_findval("shib-schemas",pb);
124 const char* prefix=pblock_findval("shib-prefix",pb);
126 g_Config=&SPConfig::getConfig();
127 g_Config->setFeatures(
130 SPConfig::RequestMapping |
131 SPConfig::InProcess |
135 if (!g_Config->init(schemadir,prefix)) {
137 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
141 g_Config->RequestMapperManager.registerFactory(XML_REQUEST_MAPPER,&SunRequestMapFactory);
144 if (!g_Config->instantiate(pblock_findval("shib-config",pb), true))
145 throw exception("unknown error");
147 catch (exception& ex) {
148 pblock_nvinsert("error",ex.what(),pb);
154 daemon_atrestart(nsapi_shib_exit,NULL);
156 ServiceProvider* sp=g_Config->getServiceProvider();
158 const PropertySet* props=sp->getPropertySet("Local");
160 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
161 if (unsetValue.first)
162 g_unsetHeaderValue = unsetValue.second;
163 pair<bool,bool> flag=props->getBool("checkSpoofing");
164 g_checkSpoofing = !flag.first || flag.second;
165 flag=props->getBool("catchAll");
166 g_catchAll = flag.first && flag.second;
171 /********************************************************************************/
172 // NSAPI Shib Target Subclass
174 class ShibTargetNSAPI : public AbstractSPRequest
176 mutable string m_body;
177 mutable bool m_gotBody,m_firsttime;
178 mutable vector<string> m_certs;
179 set<string> m_allhttp;
186 ShibTargetNSAPI(pblock* pb, ::Session* sn, Request* rq)
187 : AbstractSPRequest(SHIBSP_LOGCAT".NSAPI"), m_gotBody(false), m_firsttime(true), m_pb(pb), m_sn(sn), m_rq(rq) {
189 const char* uri=pblock_findval("uri", rq->reqpb);
190 const char* qstr=pblock_findval("query", rq->reqpb);
193 string temp = string(uri) + '?' + qstr;
194 setRequestURI(temp.c_str());
200 // See if this is the first time we've run.
201 qstr = pblock_findval("auth-type", rq->vars);
202 if (qstr && !strcmp(qstr, "shibboleth"))
204 if (!m_firsttime || rq->orig_rq)
205 log(SPDebug, "nsapi_shib function running more than once");
207 ~ShibTargetNSAPI() { }
209 const char* getScheme() const {
210 return security_active ? "https" : "http";
212 const char* getHostname() const {
213 #ifdef vs_is_default_vs
214 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
215 if (!vs_is_default_vs(request_get_vs(m_rq)))
216 // The beauty here is, a non-default vhost can *only* be accessed if the client
217 // specified the exact name in the Host header. So we can trust the Host header.
218 return pblock_findval("host", m_rq->headers);
221 // In other cases, we're going to rely on the initialization process...
222 return g_ServerName.c_str();
224 int getPort() const {
225 return server_portnum;
227 const char* getMethod() const {
228 return pblock_findval("method", m_rq->reqpb);
230 string getContentType() const {
231 char* content_type = "";
232 request_header("content-type", &content_type, m_sn, m_rq);
235 long getContentLength() const {
237 return m_body.length();
238 char* content_length="";
239 request_header("content-length", &content_length, m_sn, m_rq);
240 return atoi(content_length);
242 string getRemoteAddr() const {
243 return pblock_findval("ip", m_sn->client);
245 void log(SPLogLevel level, const string& msg) const {
246 AbstractSPRequest::log(level,msg);
248 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
250 const char* getQueryString() const {
251 return pblock_findval("query", m_rq->reqpb);
253 const char* getRequestBody() const {
255 return m_body.c_str();
256 char* content_length=NULL;
257 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED || atoi(content_length) > 1024*1024) // 1MB?
258 throw opensaml::SecurityPolicyException("Blocked request body exceeding 1M size limit.");
261 int cl=atoi(content_length);
263 while (cl && ch != IO_EOF) {
264 ch=netbuf_getc(m_sn->inbuf);
272 throw IOException("Error reading request body from browser.");
273 return m_body.c_str();
276 void clearHeader(const char* rawname, const char* cginame) {
277 if (g_checkSpoofing && m_firsttime && !m_rq->orig_rq) {
278 if (m_allhttp.empty()) {
279 // Populate the set of client-supplied headers for spoof checking.
280 const pb_entry* entry;
281 for (int i=0; i<m_rq->headers->hsize; ++i) {
282 entry = m_rq->headers->ht[i];
284 string cgiversion("HTTP_");
285 const char* pch = entry->param->name;
287 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
290 m_allhttp.insert(cgiversion);
295 if (m_allhttp.count(cginame) > 0)
296 throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
298 param_free(pblock_remove(rawname, m_rq->headers));
299 pblock_nvinsert(rawname, g_unsetHeaderValue.c_str(), m_rq->headers);
301 void setHeader(const char* name, const char* value) {
302 param_free(pblock_remove(name, m_rq->headers));
303 pblock_nvinsert(name, value, m_rq->headers);
305 string getHeader(const char* name) const {
306 // NSAPI headers tend to be lower case. We'll special case "cookie" since it's used a lot.
308 int cookie = strcmp(name, "Cookie");
311 if (request_header(const_cast<char*>(name), &hdr, m_sn, m_rq) != REQ_PROCEED) {
312 // We didn't get a hit, so we'll try a lower-casing operation, unless we already did...
317 n += tolower(*(name++));
318 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
321 return string(hdr ? hdr : "");
323 void setRemoteUser(const char* user) {
324 pblock_nvinsert("auth-user", user, m_rq->vars);
326 string getRemoteUser() const {
327 const char* ru = pblock_findval("auth-user", m_rq->vars);
330 void setResponseHeader(const char* name, const char* value) {
331 pblock_nvinsert(name, value, m_rq->srvhdrs);
334 long sendResponse(istream& in, long status) {
339 msg.append(buf,in.gcount());
341 pblock_nvinsert("connection","close",m_rq->srvhdrs);
342 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
343 protocol_status(m_sn, m_rq, status, NULL);
344 protocol_start_response(m_sn, m_rq);
345 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
348 long sendRedirect(const char* url) {
349 param_free(pblock_remove("content-type", m_rq->srvhdrs));
350 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
351 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
352 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
353 pblock_nvinsert("location", url, m_rq->srvhdrs);
354 pblock_nvinsert("connection","close",m_rq->srvhdrs);
355 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
356 protocol_start_response(m_sn, m_rq);
359 long returnDecline() { return REQ_NOACTION; }
360 long returnOK() { return REQ_PROCEED; }
361 const vector<string>& getClientCertificates() const {
362 if (m_certs.empty()) {
363 const char* cert = pblock_findval("auth-cert", m_rq->vars);
365 m_certs.push_back(cert);
371 /********************************************************************************/
373 int WriteClientError(::Session* sn, Request* rq, char* func, char* msg)
375 log_error(LOG_FAILURE,func,sn,rq,msg);
376 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
381 #define FUNC "shibboleth"
382 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, ::Session* sn, Request* rq)
384 ostringstream threadid;
385 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
386 xmltooling::NDC ndc(threadid.str().c_str());
389 ShibTargetNSAPI stn(pb, sn, rq);
391 // Check user authentication
392 pair<bool,long> res = stn.getServiceProvider().doAuthentication(stn);
393 if (res.first) return (int)res.second;
395 // user authN was okay -- export the assertions now
396 param_free(pblock_remove("auth-user",rq->vars));
397 // This seems to be required in order to eventually set
398 // the auth-user var.
399 pblock_nvinsert("auth-type","shibboleth",rq->vars);
400 res = stn.getServiceProvider().doExport(stn);
401 if (res.first) return (int)res.second;
403 // Check the Authorization
404 res = stn.getServiceProvider().doAuthorization(stn);
405 if (res.first) return (int)res.second;
410 catch (exception& e) {
411 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
412 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an exception, see web server log for error.");
415 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>("Shibboleth module threw an unknown exception."));
417 return WriteClientError(sn, rq, FUNC, "Shibboleth module threw an unknown exception.");
424 #define FUNC "shib_handler"
425 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, ::Session* sn, Request* rq)
427 ostringstream threadid;
428 threadid << "[" << getpid() << "] shib_handler" << '\0';
429 xmltooling::NDC ndc(threadid.str().c_str());
432 ShibTargetNSAPI stn(pb, sn, rq);
434 pair<bool,long> res = stn.getServiceProvider().doHandler(stn);
435 if (res.first) return (int)res.second;
437 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
439 catch (exception& e) {
440 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
441 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
445 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
451 class SunRequestMapper : public virtual RequestMapper, public virtual PropertySet
454 SunRequestMapper(const xercesc::DOMElement* e);
455 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
456 Lockable* lock() { return m_mapper->lock(); }
457 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
458 Settings getSettings(const HTTPRequest& request) const;
460 const PropertySet* getParent() const { return NULL; }
461 void setParent(const PropertySet*) {}
462 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
463 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
464 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
465 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
466 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
467 void getAll(map<string,const char*>& properties) const;
468 const PropertySet* getPropertySet(const char* name, const char* ns=shibspconstants::ASCII_SHIB2SPCONFIG_NS) const;
469 const xercesc::DOMElement* getElement() const;
472 RequestMapper* m_mapper;
474 ThreadKey* m_propsKey;
477 RequestMapper* SunRequestMapFactory(const xercesc::DOMElement* const & e)
479 return new SunRequestMapper(e);
482 SunRequestMapper::SunRequestMapper(const xercesc::DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
484 m_mapper = SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
485 m_stKey=ThreadKey::create(NULL);
486 m_propsKey=ThreadKey::create(NULL);
489 RequestMapper::Settings SunRequestMapper::getSettings(const HTTPRequest& request) const
491 Settings s=m_mapper->getSettings(request);
492 m_stKey->setData((void*)dynamic_cast<const ShibTargetNSAPI*>(&request));
493 m_propsKey->setData((void*)s.first);
494 return pair<const PropertySet*,AccessControl*>(this,s.second);
497 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
499 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
500 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
501 if (stn && !ns && name) {
502 // Override boolean properties.
503 const char* param=pblock_findval(name,stn->m_pb);
504 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
505 return make_pair(true,true);
507 return s ? s->getBool(name,ns) : make_pair(false,false);
510 pair<bool,const char*> SunRequestMapper::getString(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 string properties.
516 if (!strcmp(name,"authType"))
517 return pair<bool,const char*>(true,"shibboleth");
519 const char* param=pblock_findval(name,stn->m_pb);
521 return make_pair(true,param);
524 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
527 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
529 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
530 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
533 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
535 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
536 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
537 if (stn && !ns && name) {
538 // Override int properties.
539 const char* param=pblock_findval(name,stn->m_pb);
541 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
543 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
546 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
548 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
549 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
550 if (stn && !ns && name) {
551 // Override int properties.
552 const char* param=pblock_findval(name,stn->m_pb);
554 return pair<bool,int>(true,atoi(param));
556 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
559 void SunRequestMapper::getAll(map<string,const char*>& properties) const
561 const ShibTargetNSAPI* stn=reinterpret_cast<const ShibTargetNSAPI*>(m_stKey->getData());
562 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
564 s->getAll(properties);
567 properties["authType"] = "shibboleth";
568 const pb_entry* entry;
569 for (int i=0; i<stn->m_pb->hsize; ++i) {
570 entry = stn->m_pb->ht[i];
572 properties[entry->param->name] = entry->param->value;
578 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
580 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
581 return s ? s->getPropertySet(name,ns) : NULL;
584 const xercesc::DOMElement* SunRequestMapper::getElement() const
586 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
587 return s ? s->getElement() : NULL;