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 = true;
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) {
181 // Get everything but hostname...
182 const char* uri=pblock_findval("uri", rq->reqpb);
183 const char* qstr=pblock_findval("query", rq->reqpb);
184 int port=server_portnum;
185 const char* scheme=security_active ? "https" : "http";
186 const char* host=NULL;
192 url=url + '?' + qstr;
194 #ifdef vs_is_default_vs
195 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
196 if (!vs_is_default_vs(request_get_vs(m_rq)))
197 // The beauty here is, a non-default vhost can *only* be accessed if the client
198 // specified the exact name in the Host header. So we can trust the Host header.
199 host=pblock_findval("host", rq->headers);
202 // In other cases, we're going to rely on the initialization process...
203 host=g_ServerName.c_str();
205 char* content_type = "";
206 request_header("content-type", &content_type, sn, rq);
208 const char *remote_ip = pblock_findval("ip", sn->client);
209 const char *method = pblock_findval("method", rq->reqpb);
211 init(scheme, host, port, url.c_str(), content_type, remote_ip, method);
216 virtual void log(ShibLogLevel level, const string &msg) {
217 ShibTarget::log(level,msg);
218 if (level==LogLevelError)
219 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
221 virtual string getCookies(void) const {
222 char *cookies = NULL;
223 if (request_header("cookie", &cookies, m_sn, m_rq) == REQ_ABORTED)
224 throw("error accessing cookie header");
225 return string(cookies ? cookies : "");
227 virtual void setCookie(const string &name, const string &value) {
228 string cookie = name + '=' + value;
229 pblock_nvinsert("Set-Cookie", cookie.c_str(), m_rq->srvhdrs);
231 virtual string getArgs(void) {
232 const char *q = pblock_findval("query", m_rq->reqpb);
233 return string(q ? q : "");
235 virtual string getPostData(void) {
236 char* content_length=NULL;
237 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
238 atoi(content_length) > 1024*1024) // 1MB?
239 throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
242 int cl=atoi(content_length);
244 while (cl && ch != IO_EOF) {
245 ch=netbuf_getc(m_sn->inbuf);
254 throw FatalProfileException("Error reading profile submission from browser.");
258 virtual void clearHeader(const string &name) {
259 if (g_checkSpoofing && m_allhttp.empty()) {
260 // Populate the set of client-supplied headers for spoof checking.
261 const pb_entry* entry;
262 for (int i=0; i<m_rq->headers->hsize; ++i) {
263 entry = m_rq->headers->ht[i];
265 string cgiversion("HTTP_");
266 const char* pch = entry->param->name;
268 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
271 m_allhttp.insert(cgiversion);
276 if (name=="REMOTE_USER") {
277 if (g_checkSpoofing && m_allhttp.count("HTTP_REMOTE_USER") > 0)
278 throw SAMLException("Attempt to spoof header ($1) was detected.", params(1, name.c_str()));
279 param_free(pblock_remove("auth-user",m_rq->vars));
280 param_free(pblock_remove("remote-user",m_rq->headers));
283 if (g_checkSpoofing) {
284 // Map to the expected CGI variable name.
285 string transformed("HTTP_");
286 const char* pch = name.c_str();
288 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
291 if (m_allhttp.count(transformed) > 0)
292 throw SAMLException("Attempt to spoof header ($1) was detected.", params(1, name.c_str()));
294 param_free(pblock_remove(name.c_str(), m_rq->headers));
295 pblock_nvinsert(name.c_str(), g_unsetHeaderValue.c_str(), m_rq->headers);
298 virtual void setHeader(const string &name, const string &value) {
299 param_free(pblock_remove(name.c_str(), m_rq->headers));
300 pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
302 virtual string getHeader(const string &name) {
304 if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED) {
306 const char* pch = name.c_str();
308 n += tolower(*(pch++));
309 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
312 return string(hdr ? hdr : "");
314 virtual void setRemoteUser(const string &user) {
315 pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
316 pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
318 virtual string getRemoteUser(void) {
319 const char* ru = pblock_findval("auth-user", m_rq->vars);
323 virtual void* sendPage(
326 const string& content_type="text/html",
327 const saml::Iterator<header_t>& headers=EMPTY(header_t)
329 param_free(pblock_remove("content-type", m_rq->srvhdrs));
330 pblock_nvinsert("content-type", content_type.c_str(), m_rq->srvhdrs);
331 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
332 pblock_nvinsert("connection","close",m_rq->srvhdrs);
333 while (headers.hasNext()) {
334 const header_t& h=headers.next();
335 pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
337 protocol_status(m_sn, m_rq, code, NULL);
338 protocol_start_response(m_sn, m_rq);
339 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
340 return (void*)REQ_EXIT;
342 virtual void* sendRedirect(const string& url) {
343 param_free(pblock_remove("content-type", m_rq->srvhdrs));
344 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
345 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
346 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
347 pblock_nvinsert("location", url.c_str(), m_rq->srvhdrs);
348 pblock_nvinsert("connection","close",m_rq->srvhdrs);
349 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
350 protocol_start_response(m_sn, m_rq);
351 return (void*)REQ_ABORTED;
353 virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
354 virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
359 set<string> m_allhttp;
362 /********************************************************************************/
364 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
366 log_error(LOG_FAILURE,func,sn,rq,msg);
367 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
372 #define FUNC "shibboleth"
373 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
375 ostringstream threadid;
376 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
377 saml::NDC ndc(threadid.str().c_str());
380 ShibTargetNSAPI stn(pb, sn, rq);
382 // Check user authentication
383 pair<bool,void*> res = stn.doCheckAuthN();
384 if (res.first) return (int)res.second;
386 // user authN was okay -- export the assertions now
387 param_free(pblock_remove("auth-user",rq->vars));
388 // This seems to be required in order to eventually set
389 // the auth-user var.
390 pblock_nvinsert("auth-type","shibboleth",rq->vars);
391 res = stn.doExportAssertions();
392 if (res.first) return (int)res.second;
394 // Check the Authorization
395 res = stn.doCheckAuthZ();
396 if (res.first) return (int)res.second;
401 catch (exception& e) {
402 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
403 return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an exception, see web server log for error.");
407 return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an uncaught exception.");
414 #define FUNC "shib_handler"
415 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
417 ostringstream threadid;
418 threadid << "[" << getpid() << "] shib_handler" << '\0';
419 saml::NDC ndc(threadid.str().c_str());
422 ShibTargetNSAPI stn(pb, sn, rq);
424 pair<bool,void*> res = stn.doHandler();
425 if (res.first) return (int)res.second;
427 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
429 catch (exception& e) {
430 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
431 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
435 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
441 class SunRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
444 SunRequestMapper(const DOMElement* e);
445 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
446 void lock() { m_mapper->lock(); }
447 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
448 Settings getSettings(ShibTarget* st) const;
450 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
451 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
452 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
453 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
454 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
455 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
456 const DOMElement* getElement() const;
459 IRequestMapper* m_mapper;
461 ThreadKey* m_propsKey;
464 IPlugIn* SunRequestMapFactory(const DOMElement* e)
466 return new SunRequestMapper(e);
469 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
471 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
472 m_mapper=dynamic_cast<IRequestMapper*>(p);
475 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
477 m_stKey=ThreadKey::create(NULL);
478 m_propsKey=ThreadKey::create(NULL);
481 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
483 Settings s=m_mapper->getSettings(st);
484 m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
485 m_propsKey->setData((void*)s.first);
486 return pair<const IPropertySet*,IAccessControl*>(this,s.second);
489 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
491 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
492 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
493 if (stn && !ns && name) {
494 // Override boolean properties.
495 const char* param=pblock_findval(name,stn->m_pb);
496 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
497 return make_pair(true,true);
499 return s ? s->getBool(name,ns) : make_pair(false,false);
502 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
504 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
505 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
506 if (stn && !ns && name) {
507 // Override string properties.
508 if (!strcmp(name,"authType"))
509 return pair<bool,const char*>(true,"shibboleth");
511 const char* param=pblock_findval(name,stn->m_pb);
513 return make_pair(true,param);
516 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
519 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
521 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
522 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
525 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
527 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
528 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(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,unsigned int>(true,strtol(param,NULL,10));
535 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
538 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
540 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
541 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
542 if (stn && !ns && name) {
543 // Override int properties.
544 const char* param=pblock_findval(name,stn->m_pb);
546 return pair<bool,int>(true,atoi(param));
548 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
551 const IPropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
553 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
554 return s ? s->getPropertySet(name,ns) : NULL;
557 const DOMElement* SunRequestMapper::getElement() const
559 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
560 return s ? s->getElement() : NULL;