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;
73 PlugManager::Factory SunRequestMapFactory;
75 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
82 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, Session* sn, Request* rq)
84 // Save off a default hostname for this virtual server.
85 char* name=pblock_findval("server-name",pb);
99 pblock_nvinsert("error","unable to determine web server hostname",pb);
104 name=pblock_findval("server-scheme",pb);
108 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
113 const char* schemadir=pblock_findval("shib-schemas",pb);
115 schemadir=getenv("SHIBSCHEMAS");
117 schemadir=SHIB_SCHEMAS;
118 const char* config=pblock_findval("shib-config",pb);
120 config=getenv("SHIBCONFIG");
123 g_Config=&ShibTargetConfig::getConfig();
124 g_Config->setFeatures(
125 ShibTargetConfig::Listener |
126 ShibTargetConfig::Metadata |
127 ShibTargetConfig::AAP |
128 ShibTargetConfig::RequestMapper |
129 ShibTargetConfig::LocalExtensions |
130 ShibTargetConfig::Logging
132 if (!g_Config->init(schemadir)) {
134 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
138 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&SunRequestMapFactory);
139 // We hijack the legacy type so that 1.2 config files will load this plugin
140 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&SunRequestMapFactory);
142 if (!g_Config->load(config)) {
144 pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
148 daemon_atrestart(nsapi_shib_exit,NULL);
150 IConfig* conf=g_Config->getINI();
152 const IPropertySet* props=conf->getPropertySet("Local");
154 pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
155 if (unsetValue.first)
156 g_unsetHeaderValue = unsetValue.second;
157 pair<bool,bool> checkSpoofing=props->getBool("checkSpoofing");
158 if (checkSpoofing.first && !checkSpoofing.second)
159 g_checkSpoofing = false;
165 pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
172 /********************************************************************************/
173 // NSAPI Shib Target Subclass
175 class ShibTargetNSAPI : public ShibTarget
178 ShibTargetNSAPI(pblock* pb, Session* sn, Request* rq) {
183 // Get everything but hostname...
184 const char* uri=pblock_findval("uri", rq->reqpb);
185 const char* qstr=pblock_findval("query", rq->reqpb);
186 int port=server_portnum;
187 const char* scheme=security_active ? "https" : "http";
188 const char* host=NULL;
194 url=url + '?' + qstr;
196 #ifdef vs_is_default_vs
197 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
198 if (!vs_is_default_vs(request_get_vs(m_rq)))
199 // The beauty here is, a non-default vhost can *only* be accessed if the client
200 // specified the exact name in the Host header. So we can trust the Host header.
201 host=pblock_findval("host", rq->headers);
204 // In other cases, we're going to rely on the initialization process...
205 host=g_ServerName.c_str();
207 char* content_type = "";
208 request_header("content-type", &content_type, sn, rq);
210 const char *remote_ip = pblock_findval("ip", sn->client);
211 const char *method = pblock_findval("method", rq->reqpb);
213 init(scheme, host, port, url.c_str(), content_type, remote_ip, method);
218 virtual void log(ShibLogLevel level, const string &msg) {
219 ShibTarget::log(level,msg);
220 if (level==LogLevelError)
221 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
223 virtual string getCookies(void) const {
224 char *cookies = NULL;
225 if (request_header("cookie", &cookies, m_sn, m_rq) == REQ_ABORTED)
226 throw("error accessing cookie header");
227 return string(cookies ? cookies : "");
229 virtual void setCookie(const string &name, const string &value) {
230 string cookie = name + '=' + value;
231 pblock_nvinsert("Set-Cookie", cookie.c_str(), m_rq->srvhdrs);
233 virtual string getArgs(void) {
234 const char *q = pblock_findval("query", m_rq->reqpb);
235 return string(q ? q : "");
237 virtual string getPostData(void) {
238 char* content_length=NULL;
239 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
240 atoi(content_length) > 1024*1024) // 1MB?
241 throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
244 int cl=atoi(content_length);
246 while (cl && ch != IO_EOF) {
247 ch=netbuf_getc(m_sn->inbuf);
256 throw FatalProfileException("Error reading profile submission from browser.");
260 virtual void clearHeader(const string &name) {
261 if (g_checkSpoofing && m_allhttp.empty()) {
262 // Populate the set of client-supplied headers for spoof checking.
263 const pb_entry* entry;
264 for (int i=0; i<m_rq->headers->hsize; ++i) {
265 entry = m_rq->headers->ht[i];
267 string cgiversion("HTTP_");
268 const char* pch = entry->param->name;
270 cgiversion += (isalnum(*pch) ? toupper(*pch) : '_');
273 m_allhttp.insert(cgiversion);
278 if (name=="REMOTE_USER") {
279 if (g_checkSpoofing && m_allhttp.count("HTTP_REMOTE_USER") > 0)
280 throw SAMLException("Attempt to spoof header ($1) was detected.", params(1, name.c_str()));
281 param_free(pblock_remove("auth-user",m_rq->vars));
282 param_free(pblock_remove("remote-user",m_rq->headers));
285 if (g_checkSpoofing) {
286 // Map to the expected CGI variable name.
287 string transformed("HTTP_");
288 const char* pch = name.c_str();
290 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
293 if (m_allhttp.count(transformed) > 0)
294 throw SAMLException("Attempt to spoof header ($1) was detected.", params(1, name.c_str()));
296 param_free(pblock_remove(name.c_str(), m_rq->headers));
297 pblock_nvinsert(name.c_str(), g_unsetHeaderValue.c_str(), m_rq->headers);
300 virtual void setHeader(const string &name, const string &value) {
301 param_free(pblock_remove(name.c_str(), m_rq->headers));
302 pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
304 virtual string getHeader(const string &name) {
306 if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED) {
308 const char* pch = name.c_str();
310 n += tolower(*(pch++));
311 if (request_header(const_cast<char*>(n.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
314 return string(hdr ? hdr : "");
316 virtual void setRemoteUser(const string &user) {
317 pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
318 pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
320 virtual string getRemoteUser(void) {
321 const char* ru = pblock_findval("auth-user", m_rq->vars);
325 virtual void* sendPage(
328 const string& content_type="text/html",
329 const saml::Iterator<header_t>& headers=EMPTY(header_t)
331 param_free(pblock_remove("content-type", m_rq->srvhdrs));
332 pblock_nvinsert("content-type", content_type.c_str(), m_rq->srvhdrs);
333 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
334 pblock_nvinsert("connection","close",m_rq->srvhdrs);
335 while (headers.hasNext()) {
336 const header_t& h=headers.next();
337 pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
339 protocol_status(m_sn, m_rq, code, NULL);
340 protocol_start_response(m_sn, m_rq);
341 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
342 return (void*)REQ_EXIT;
344 virtual void* sendRedirect(const string& url) {
345 param_free(pblock_remove("content-type", m_rq->srvhdrs));
346 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
347 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
348 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
349 pblock_nvinsert("location", url.c_str(), m_rq->srvhdrs);
350 pblock_nvinsert("connection","close",m_rq->srvhdrs);
351 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
352 protocol_start_response(m_sn, m_rq);
353 return (void*)REQ_ABORTED;
355 virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
356 virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
361 set<string> m_allhttp;
364 /********************************************************************************/
366 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
368 log_error(LOG_FAILURE,func,sn,rq,msg);
369 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
374 #define FUNC "shibboleth"
375 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
377 ostringstream threadid;
378 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
379 saml::NDC ndc(threadid.str().c_str());
382 ShibTargetNSAPI stn(pb, sn, rq);
384 // Check user authentication
385 pair<bool,void*> res = stn.doCheckAuthN();
386 if (res.first) return (int)res.second;
388 // user authN was okay -- export the assertions now
389 param_free(pblock_remove("auth-user",rq->vars));
390 // This seems to be required in order to eventually set
391 // the auth-user var.
392 pblock_nvinsert("auth-type","shibboleth",rq->vars);
393 res = stn.doExportAssertions();
394 if (res.first) return (int)res.second;
396 // Check the Authorization
397 res = stn.doCheckAuthZ();
398 if (res.first) return (int)res.second;
403 catch (SAMLException& e) {
404 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
405 return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an exception, see web server log for error.");
409 return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an uncaught exception.");
416 #define FUNC "shib_handler"
417 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
419 ostringstream threadid;
420 threadid << "[" << getpid() << "] shib_handler" << '\0';
421 saml::NDC ndc(threadid.str().c_str());
424 ShibTargetNSAPI stn(pb, sn, rq);
426 pair<bool,void*> res = stn.doHandler();
427 if (res.first) return (int)res.second;
429 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
431 catch (SAMLException& e) {
432 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
433 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
437 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
443 class SunRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
446 SunRequestMapper(const DOMElement* e);
447 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
448 void lock() { m_mapper->lock(); }
449 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
450 Settings getSettings(ShibTarget* st) const;
452 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
453 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
454 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
455 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
456 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
457 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
458 const DOMElement* getElement() const;
461 IRequestMapper* m_mapper;
463 ThreadKey* m_propsKey;
466 IPlugIn* SunRequestMapFactory(const DOMElement* e)
468 return new SunRequestMapper(e);
471 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
473 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
474 m_mapper=dynamic_cast<IRequestMapper*>(p);
477 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
479 m_stKey=ThreadKey::create(NULL);
480 m_propsKey=ThreadKey::create(NULL);
483 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
485 Settings s=m_mapper->getSettings(st);
486 m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
487 m_propsKey->setData((void*)s.first);
488 return pair<const IPropertySet*,IAccessControl*>(this,s.second);
491 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
493 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
494 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
495 if (stn && !ns && name) {
496 // Override boolean properties.
497 const char* param=pblock_findval(name,stn->m_pb);
498 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
499 return make_pair(true,true);
501 return s ? s->getBool(name,ns) : make_pair(false,false);
504 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
506 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
507 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
508 if (stn && !ns && name) {
509 // Override string properties.
510 if (!strcmp(name,"authType"))
511 return pair<bool,const char*>(true,"shibboleth");
513 const char* param=pblock_findval(name,stn->m_pb);
515 return make_pair(true,param);
518 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
521 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
523 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
524 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
527 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
529 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
530 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(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,unsigned int>(true,strtol(param,NULL,10));
537 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
540 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
542 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
543 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
544 if (stn && !ns && name) {
545 // Override int properties.
546 const char* param=pblock_findval(name,stn->m_pb);
548 return pair<bool,int>(true,atoi(param));
550 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
553 const IPropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
555 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
556 return s ? s->getPropertySet(name,ns) : NULL;
559 const DOMElement* SunRequestMapper::getElement() const
561 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
562 return s ? s->getElement() : NULL;