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.
17 /* nsapi_shib.cpp - Shibboleth NSAPI filter
23 #if defined (_MSC_VER) || defined(__BORLANDC__)
24 # include "config_win32.h"
31 #include <saml/saml.h>
32 #include <shib/shib.h>
33 #include <shib/shib-threads.h>
34 #include <shib-target/shib-target.h>
58 using namespace shibboleth;
59 using namespace shibtarget;
61 // macros to output text to client
62 #define NET_WRITE(str) \
63 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
66 ShibTargetConfig* g_Config=NULL;
68 string g_ServerScheme;
69 string g_unsetHeaderValue;
70 bool g_checkSpoofing = false;
71 bool g_catchAll = true;
74 PlugManager::Factory SunRequestMapFactory;
76 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
83 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, Session* sn, Request* rq)
85 // Save off a default hostname for this virtual server.
86 char* name=pblock_findval("server-name",pb);
100 pblock_nvinsert("error","unable to determine web server hostname",pb);
105 name=pblock_findval("server-scheme",pb);
109 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
112 const char* schemadir=pblock_findval("shib-schemas",pb);
114 schemadir=getenv("SHIBSCHEMAS");
116 schemadir=SHIB_SCHEMAS;
117 const char* config=pblock_findval("shib-config",pb);
119 config=getenv("SHIBCONFIG");
122 g_Config=&ShibTargetConfig::getConfig();
123 g_Config->setFeatures(
124 ShibTargetConfig::Listener |
125 ShibTargetConfig::Metadata |
126 ShibTargetConfig::AAP |
127 ShibTargetConfig::RequestMapper |
128 ShibTargetConfig::LocalExtensions |
129 ShibTargetConfig::Logging
131 if (!g_Config->init(schemadir)) {
133 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
137 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&SunRequestMapFactory);
138 // We hijack the legacy type so that 1.2 config files will load this plugin
139 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&SunRequestMapFactory);
141 if (!g_Config->load(config)) {
143 pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
147 daemon_atrestart(nsapi_shib_exit,NULL);
149 IConfig* conf=g_Config->getINI();
151 const IPropertySet* props=conf->getPropertySet("Local");
153 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
154 if (unsetValue.first)
155 g_unsetHeaderValue = unsetValue.second;
156 pair<bool,bool> flag=props->getBool("checkSpoofing");
157 g_checkSpoofing = !flag.first || flag.second;
158 flag=props->getBool("catchAll");
159 g_catchAll = !flag.first || flag.second;
164 pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
170 /********************************************************************************/
171 // NSAPI Shib Target Subclass
173 class ShibTargetNSAPI : public ShibTarget
176 ShibTargetNSAPI(pblock* pb, Session* sn, Request* rq) : m_pb(pb), m_sn(sn), m_rq(rq), m_firsttime(true) {
177 // Get everything but hostname...
178 const char* uri=pblock_findval("uri", rq->reqpb);
179 const char* qstr=pblock_findval("query", rq->reqpb);
180 int port=server_portnum;
181 const char* scheme=security_active ? "https" : "http";
182 const char* host=NULL;
188 url=url + '?' + qstr;
190 #ifdef vs_is_default_vs
191 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
192 if (!vs_is_default_vs(request_get_vs(m_rq)))
193 // The beauty here is, a non-default vhost can *only* be accessed if the client
194 // specified the exact name in the Host header. So we can trust the Host header.
195 host=pblock_findval("host", rq->headers);
198 // In other cases, we're going to rely on the initialization process...
199 host=g_ServerName.c_str();
201 char* content_type = "";
202 request_header("content-type", &content_type, sn, rq);
204 const char* remote_ip = pblock_findval("ip", sn->client);
205 const char* method = pblock_findval("method", rq->reqpb);
207 init(scheme, host, port, url.c_str(), content_type, remote_ip, method);
209 // See if this is the first time we've run.
210 method = pblock_findval("auth-type", rq->vars);
211 if (method && !strcmp(method, "shibboleth"))
214 log(LogLevelDebug, "nsapi_shib function running more than once");
219 virtual void log(ShibLogLevel level, const string &msg) {
220 ShibTarget::log(level,msg);
221 if (level==LogLevelError)
222 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
224 virtual string getCookies(void) const {
225 char *cookies = NULL;
226 if (request_header("cookie", &cookies, m_sn, m_rq) == REQ_ABORTED)
227 throw("error accessing cookie header");
228 return string(cookies ? cookies : "");
230 virtual void setCookie(const string &name, const string &value) {
231 string cookie = name + '=' + value;
232 pblock_nvinsert("Set-Cookie", cookie.c_str(), m_rq->srvhdrs);
234 virtual string getArgs(void) {
235 const char *q = pblock_findval("query", m_rq->reqpb);
236 return string(q ? q : "");
238 virtual string getPostData(void) {
239 char* content_length=NULL;
240 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
241 atoi(content_length) > 1024*1024) // 1MB?
242 throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
245 int cl=atoi(content_length);
247 while (cl && ch != IO_EOF) {
248 ch=netbuf_getc(m_sn->inbuf);
257 throw FatalProfileException("Error reading profile submission from browser.");
261 virtual void clearHeader(const string &name) {
262 if (m_firsttime && g_checkSpoofing && m_allhttp.empty()) {
263 // Populate the set of client-supplied headers for spoof checking.
264 const pb_entry* entry;
265 for (int i=0; i<m_rq->headers->hsize; ++i) {
266 entry = m_rq->headers->ht[i];
268 string cgiversion("HTTP_");
269 const char* pch = entry->param->name;
271 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
274 m_allhttp.insert(cgiversion);
279 if (name=="REMOTE_USER") {
280 if (m_firsttime && g_checkSpoofing && m_allhttp.count("HTTP_REMOTE_USER") > 0)
281 throw SAMLException("Attempt to spoof header ($1) was detected.", params(1, name.c_str()));
282 param_free(pblock_remove("auth-user",m_rq->vars));
283 param_free(pblock_remove("remote-user",m_rq->headers));
286 if (m_firsttime && g_checkSpoofing) {
287 // Map to the expected CGI variable name.
288 string transformed("HTTP_");
289 const char* pch = name.c_str();
291 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
294 if (m_allhttp.count(transformed) > 0)
295 throw SAMLException("Attempt to spoof header ($1) was detected.", params(1, name.c_str()));
297 param_free(pblock_remove(name.c_str(), m_rq->headers));
298 pblock_nvinsert(name.c_str(), g_unsetHeaderValue.c_str(), m_rq->headers);
301 virtual void setHeader(const string &name, const string &value) {
302 param_free(pblock_remove(name.c_str(), m_rq->headers));
303 pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
305 virtual string getHeader(const string &name) {
307 if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED) {
309 const char* pch = name.c_str();
311 n += tolower(*(pch++));
312 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
315 return string(hdr ? hdr : "");
317 virtual void setRemoteUser(const string &user) {
318 pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
319 pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
321 virtual string getRemoteUser(void) {
322 const char* ru = pblock_findval("auth-user", m_rq->vars);
326 virtual void* sendPage(
329 const string& content_type="text/html",
330 const saml::Iterator<header_t>& headers=EMPTY(header_t)
332 param_free(pblock_remove("content-type", m_rq->srvhdrs));
333 pblock_nvinsert("content-type", content_type.c_str(), m_rq->srvhdrs);
334 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
335 pblock_nvinsert("connection","close",m_rq->srvhdrs);
336 while (headers.hasNext()) {
337 const header_t& h=headers.next();
338 pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
340 protocol_status(m_sn, m_rq, code, NULL);
341 protocol_start_response(m_sn, m_rq);
342 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
343 return (void*)REQ_EXIT;
345 virtual void* sendRedirect(const string& url) {
346 param_free(pblock_remove("content-type", m_rq->srvhdrs));
347 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
348 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
349 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
350 pblock_nvinsert("location", url.c_str(), m_rq->srvhdrs);
351 pblock_nvinsert("connection","close",m_rq->srvhdrs);
352 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
353 protocol_start_response(m_sn, m_rq);
354 return (void*)REQ_ABORTED;
356 virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
357 virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
362 set<string> m_allhttp;
366 /********************************************************************************/
368 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
370 log_error(LOG_FAILURE,func,sn,rq,msg);
371 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
376 #define FUNC "shibboleth"
377 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
379 ostringstream threadid;
380 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
381 saml::NDC ndc(threadid.str().c_str());
384 ShibTargetNSAPI stn(pb, sn, rq);
386 // Check user authentication
387 pair<bool,void*> res = stn.doCheckAuthN();
388 if (res.first) return (int)res.second;
390 // user authN was okay -- export the assertions now
391 param_free(pblock_remove("auth-user",rq->vars));
392 // This seems to be required in order to eventually set
393 // the auth-user var.
394 pblock_nvinsert("auth-type","shibboleth",rq->vars);
395 res = stn.doExportAssertions();
396 if (res.first) return (int)res.second;
398 // Check the Authorization
399 res = stn.doCheckAuthZ();
400 if (res.first) return (int)res.second;
405 catch (exception& e) {
406 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
407 return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an exception, see web server log for error.");
411 return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an uncaught exception.");
418 #define FUNC "shib_handler"
419 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
421 ostringstream threadid;
422 threadid << "[" << getpid() << "] shib_handler" << '\0';
423 saml::NDC ndc(threadid.str().c_str());
426 ShibTargetNSAPI stn(pb, sn, rq);
428 pair<bool,void*> res = stn.doHandler();
429 if (res.first) return (int)res.second;
431 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
433 catch (exception& e) {
434 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
435 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
439 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
445 class SunRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
448 SunRequestMapper(const DOMElement* e);
449 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
450 void lock() { m_mapper->lock(); }
451 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
452 Settings getSettings(ShibTarget* st) const;
454 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
455 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
456 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
457 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
458 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
459 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
460 const DOMElement* getElement() const;
463 IRequestMapper* m_mapper;
465 ThreadKey* m_propsKey;
468 IPlugIn* SunRequestMapFactory(const DOMElement* e)
470 return new SunRequestMapper(e);
473 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
475 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
476 m_mapper=dynamic_cast<IRequestMapper*>(p);
479 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
481 m_stKey=ThreadKey::create(NULL);
482 m_propsKey=ThreadKey::create(NULL);
485 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
487 Settings s=m_mapper->getSettings(st);
488 m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
489 m_propsKey->setData((void*)s.first);
490 return pair<const IPropertySet*,IAccessControl*>(this,s.second);
493 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
495 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
496 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
497 if (stn && !ns && name) {
498 // Override boolean properties.
499 const char* param=pblock_findval(name,stn->m_pb);
500 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
501 return make_pair(true,true);
503 return s ? s->getBool(name,ns) : make_pair(false,false);
506 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
508 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
509 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
510 if (stn && !ns && name) {
511 // Override string properties.
512 if (!strcmp(name,"authType"))
513 return pair<bool,const char*>(true,"shibboleth");
515 const char* param=pblock_findval(name,stn->m_pb);
517 return make_pair(true,param);
520 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
523 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
525 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
526 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
529 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
531 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
532 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
533 if (stn && !ns && name) {
534 // Override int properties.
535 const char* param=pblock_findval(name,stn->m_pb);
537 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
539 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
542 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
544 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
545 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
546 if (stn && !ns && name) {
547 // Override int properties.
548 const char* param=pblock_findval(name,stn->m_pb);
550 return pair<bool,int>(true,atoi(param));
552 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
555 const IPropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
557 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
558 return s ? s->getPropertySet(name,ns) : NULL;
561 const DOMElement* SunRequestMapper::getElement() const
563 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
564 return s ? s->getElement() : NULL;