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"
30 # define _CRT_NONSTDC_NO_DEPRECATE 1
31 # define _CRT_SECURE_NO_DEPRECATE 1
36 #include <saml/saml.h>
37 #include <shib/shib.h>
38 #include <shib-target/shib-target.h>
39 #include <shibsp/SPConfig.h>
61 using namespace shibsp;
62 using namespace shibtarget;
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 ShibTargetConfig* g_Config=NULL;
74 string g_ServerScheme;
77 PlugManager::Factory SunRequestMapFactory;
79 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
86 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, Session* sn, Request* rq)
88 // Save off a default hostname for this virtual server.
89 char* name=pblock_findval("server-name",pb);
103 pblock_nvinsert("error","unable to determine web server hostname",pb);
108 name=pblock_findval("server-scheme",pb);
112 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
117 const char* schemadir=pblock_findval("shib-schemas",pb);
119 schemadir=getenv("SHIBSCHEMAS");
121 schemadir=SHIB_SCHEMAS;
122 const char* config=pblock_findval("shib-config",pb);
124 config=getenv("SHIBCONFIG");
127 g_Config=&ShibTargetConfig::getConfig();
128 SPConfig::getConfig().setFeatures(
133 SPConfig::RequestMapper |
134 SPConfig::InProcess |
137 if (!g_Config->init(schemadir)) {
139 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
143 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&SunRequestMapFactory);
144 // We hijack the legacy type so that 1.2 config files will load this plugin
145 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&SunRequestMapFactory);
147 if (!g_Config->load(config)) {
149 pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
153 daemon_atrestart(nsapi_shib_exit,NULL);
158 pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
165 /********************************************************************************/
166 // NSAPI Shib Target Subclass
168 class ShibTargetNSAPI : public ShibTarget
170 mutable string m_body;
171 mutable bool m_gotBody;
173 ShibTargetNSAPI(pblock* pb, Session* sn, Request* rq) : m_gotBody(false) {
178 // Get everything but hostname...
179 const char* uri=pblock_findval("uri", rq->reqpb);
180 const char* qstr=pblock_findval("query", rq->reqpb);
181 int port=server_portnum;
182 const char* scheme=security_active ? "https" : "http";
183 const char* host=NULL;
189 url=url + '?' + qstr;
191 #ifdef vs_is_default_vs
192 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
193 if (!vs_is_default_vs)
194 // The beauty here is, a non-default vhost can *only* be accessed if the client
195 // specified the exact name in the Host header. So we can trust the Host header.
196 host=pblock_findval("host", rq->headers);
199 // In other cases, we're going to rely on the initialization process...
200 host=g_ServerName.c_str();
202 char* content_type = "";
203 request_header("content-type", &content_type, sn, rq);
205 const char *remote_ip = pblock_findval("ip", sn->client);
206 const char *method = pblock_findval("method", rq->reqpb);
208 init(scheme, host, port, url.c_str(), content_type, remote_ip, method);
210 ~ShibTargetNSAPI() {}
212 virtual void log(ShibLogLevel level, const string &msg) {
213 ShibTarget::log(level,msg);
214 if (level==LogLevelError)
215 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
217 virtual string getCookies(void) const {
218 char *cookies = NULL;
219 if (request_header("cookie", &cookies, m_sn, m_rq) == REQ_ABORTED)
220 throw("error accessing cookie header");
221 return string(cookies ? cookies : "");
223 virtual void setCookie(const string &name, const string &value) {
224 string cookie = name + '=' + value;
225 pblock_nvinsert("Set-Cookie", cookie.c_str(), m_rq->srvhdrs);
227 virtual const char* getQueryString() const {
228 return pblock_findval("query", m_rq->reqpb);
230 virtual const char* getRequestBody() const {
232 return m_body.c_str();
233 char* content_length=NULL;
234 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
235 atoi(content_length) > 1024*1024) // 1MB?
236 throw SAMLException("Blocked POST request body exceeding size limit.");
239 int cl=atoi(content_length);
241 while (cl && ch != IO_EOF) {
242 ch=netbuf_getc(m_sn->inbuf);
250 throw SAMLException("Error reading POST request body from browser.");
251 return m_body.c_str();
254 virtual void clearHeader(const string &name) {
255 if (name=="REMOTE_USER") {
256 param_free(pblock_remove("auth-user",m_rq->vars));
257 param_free(pblock_remove("remote-user",m_rq->headers));
260 param_free(pblock_remove(name.c_str(), m_rq->headers));
262 virtual void setHeader(const string &name, const string &value) {
263 pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
265 virtual string getHeader(const string &name) {
267 if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
269 return string(hdr ? hdr : "");
271 virtual void setRemoteUser(const string &user) {
272 pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
273 pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
275 virtual string getRemoteUser(void) {
276 return getHeader("remote-user");
279 virtual void* sendPage(
282 const string& content_type="text/html",
283 const saml::Iterator<header_t>& headers=EMPTY(header_t)
285 param_free(pblock_remove("content-type", m_rq->srvhdrs));
286 pblock_nvinsert("content-type", content_type.c_str(), m_rq->srvhdrs);
287 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
288 pblock_nvinsert("connection","close",m_rq->srvhdrs);
289 while (headers.hasNext()) {
290 const header_t& h=headers.next();
291 pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
293 protocol_status(m_sn, m_rq, code, NULL);
294 protocol_start_response(m_sn, m_rq);
295 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
296 return (void*)REQ_EXIT;
298 virtual void* sendRedirect(const string& url) {
299 param_free(pblock_remove("content-type", m_rq->srvhdrs));
300 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
301 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
302 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
303 pblock_nvinsert("location", url.c_str(), m_rq->srvhdrs);
304 pblock_nvinsert("connection","close",m_rq->srvhdrs);
305 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
306 protocol_start_response(m_sn, m_rq);
307 return (void*)REQ_ABORTED;
309 virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
310 virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
317 /********************************************************************************/
319 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
321 log_error(LOG_FAILURE,func,sn,rq,msg);
322 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
327 #define FUNC "shibboleth"
328 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
330 ostringstream threadid;
331 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
332 saml::NDC ndc(threadid.str().c_str());
335 ShibTargetNSAPI stn(pb, sn, rq);
337 // Check user authentication
338 pair<bool,void*> res = stn.doCheckAuthN();
339 if (res.first) return (int)res.second;
341 // user authN was okay -- export the assertions now
342 param_free(pblock_remove("auth-user",rq->vars));
343 // This seems to be required in order to eventually set
344 // the auth-user var.
345 pblock_nvinsert("auth-type","shibboleth",rq->vars);
346 res = stn.doExportAssertions();
347 if (res.first) return (int)res.second;
349 // Check the Authorization
350 res = stn.doCheckAuthZ();
351 if (res.first) return (int)res.second;
356 catch (SAMLException& e) {
357 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
358 return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an exception, see web server log for error.");
362 return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an uncaught exception.");
369 #define FUNC "shib_handler"
370 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
372 ostringstream threadid;
373 threadid << "[" << getpid() << "] shib_handler" << '\0';
374 saml::NDC ndc(threadid.str().c_str());
377 ShibTargetNSAPI stn(pb, sn, rq);
379 pair<bool,void*> res = stn.doHandler();
380 if (res.first) return (int)res.second;
382 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
384 catch (SAMLException& e) {
385 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
386 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
390 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
396 class SunRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
399 SunRequestMapper(const DOMElement* e);
400 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
401 void lock() { m_mapper->lock(); }
402 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
403 Settings getSettings(ShibTarget* st) const;
405 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
406 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
407 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
408 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
409 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
410 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
411 const DOMElement* getElement() const;
414 IRequestMapper* m_mapper;
416 ThreadKey* m_propsKey;
419 IPlugIn* SunRequestMapFactory(const DOMElement* e)
421 return new SunRequestMapper(e);
424 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
426 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
427 m_mapper=dynamic_cast<IRequestMapper*>(p);
430 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
432 m_stKey=ThreadKey::create(NULL);
433 m_propsKey=ThreadKey::create(NULL);
436 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
438 Settings s=m_mapper->getSettings(st);
439 m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
440 m_propsKey->setData((void*)s.first);
441 return pair<const IPropertySet*,IAccessControl*>(this,s.second);
444 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
446 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
447 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
448 if (stn && !ns && name) {
449 // Override boolean properties.
450 const char* param=pblock_findval(name,stn->m_pb);
451 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
452 return make_pair(true,true);
454 return s ? s->getBool(name,ns) : make_pair(false,false);
457 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
459 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
460 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
461 if (stn && !ns && name) {
462 // Override string properties.
463 if (!strcmp(name,"authType"))
464 return pair<bool,const char*>(true,"shibboleth");
466 const char* param=pblock_findval(name,stn->m_pb);
468 return make_pair(true,param);
471 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
474 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
476 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
477 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
480 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
482 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
483 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
484 if (stn && !ns && name) {
485 // Override int properties.
486 const char* param=pblock_findval(name,stn->m_pb);
488 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
490 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
493 pair<bool,int> SunRequestMapper::getInt(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 int properties.
499 const char* param=pblock_findval(name,stn->m_pb);
501 return pair<bool,int>(true,atoi(param));
503 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
506 const IPropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
508 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
509 return s ? s->getPropertySet(name,ns) : NULL;
512 const DOMElement* SunRequestMapper::getElement() const
514 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
515 return s ? s->getElement() : NULL;