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/shib-threads.h>
39 #include <shib-target/shib-target.h>
63 using namespace shibboleth;
64 using namespace shibtarget;
66 // macros to output text to client
67 #define NET_WRITE(str) \
68 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
71 ShibTargetConfig* g_Config=NULL;
73 string g_ServerScheme;
76 PlugManager::Factory SunRequestMapFactory;
78 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
85 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, Session* sn, Request* rq)
87 // Save off a default hostname for this virtual server.
88 char* name=pblock_findval("server-name",pb);
102 pblock_nvinsert("error","unable to determine web server hostname",pb);
107 name=pblock_findval("server-scheme",pb);
111 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
116 const char* schemadir=pblock_findval("shib-schemas",pb);
118 schemadir=getenv("SHIBSCHEMAS");
120 schemadir=SHIB_SCHEMAS;
121 const char* config=pblock_findval("shib-config",pb);
123 config=getenv("SHIBCONFIG");
126 g_Config=&ShibTargetConfig::getConfig();
127 g_Config->setFeatures(
128 ShibTargetConfig::Listener |
129 ShibTargetConfig::Caching |
130 ShibTargetConfig::Metadata |
131 ShibTargetConfig::AAP |
132 ShibTargetConfig::RequestMapper |
133 ShibTargetConfig::InProcess |
134 ShibTargetConfig::Logging
136 if (!g_Config->init(schemadir)) {
138 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
142 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&SunRequestMapFactory);
143 // We hijack the legacy type so that 1.2 config files will load this plugin
144 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&SunRequestMapFactory);
146 if (!g_Config->load(config)) {
148 pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
152 daemon_atrestart(nsapi_shib_exit,NULL);
157 pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
164 /********************************************************************************/
165 // NSAPI Shib Target Subclass
167 class ShibTargetNSAPI : public ShibTarget
169 mutable string m_body;
170 mutable bool m_gotBody;
172 ShibTargetNSAPI(pblock* pb, Session* sn, Request* rq) : m_gotBody(false) {
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)
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 ~ShibTargetNSAPI() {}
211 virtual void log(ShibLogLevel level, const string &msg) {
212 ShibTarget::log(level,msg);
213 if (level==LogLevelError)
214 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
216 virtual string getCookies(void) const {
217 char *cookies = NULL;
218 if (request_header("cookie", &cookies, m_sn, m_rq) == REQ_ABORTED)
219 throw("error accessing cookie header");
220 return string(cookies ? cookies : "");
222 virtual void setCookie(const string &name, const string &value) {
223 string cookie = name + '=' + value;
224 pblock_nvinsert("Set-Cookie", cookie.c_str(), m_rq->srvhdrs);
226 virtual const char* getQueryString() const {
227 return pblock_findval("query", m_rq->reqpb);
229 virtual const char* getRequestBody() const {
231 return m_body.c_str();
232 char* content_length=NULL;
233 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
234 atoi(content_length) > 1024*1024) // 1MB?
235 throw SAMLException("Blocked POST request body exceeding size limit.");
238 int cl=atoi(content_length);
240 while (cl && ch != IO_EOF) {
241 ch=netbuf_getc(m_sn->inbuf);
249 throw SAMLException("Error reading POST request body from browser.");
250 return m_body.c_str();
253 virtual void clearHeader(const string &name) {
254 if (name=="REMOTE_USER") {
255 param_free(pblock_remove("auth-user",m_rq->vars));
256 param_free(pblock_remove("remote-user",m_rq->headers));
259 param_free(pblock_remove(name.c_str(), m_rq->headers));
261 virtual void setHeader(const string &name, const string &value) {
262 pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
264 virtual string getHeader(const string &name) {
266 if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
268 return string(hdr ? hdr : "");
270 virtual void setRemoteUser(const string &user) {
271 pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
272 pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
274 virtual string getRemoteUser(void) {
275 return getHeader("remote-user");
278 virtual void* sendPage(
281 const string& content_type="text/html",
282 const saml::Iterator<header_t>& headers=EMPTY(header_t)
284 param_free(pblock_remove("content-type", m_rq->srvhdrs));
285 pblock_nvinsert("content-type", content_type.c_str(), m_rq->srvhdrs);
286 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
287 pblock_nvinsert("connection","close",m_rq->srvhdrs);
288 while (headers.hasNext()) {
289 const header_t& h=headers.next();
290 pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
292 protocol_status(m_sn, m_rq, code, NULL);
293 protocol_start_response(m_sn, m_rq);
294 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
295 return (void*)REQ_EXIT;
297 virtual void* sendRedirect(const string& url) {
298 param_free(pblock_remove("content-type", m_rq->srvhdrs));
299 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
300 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
301 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
302 pblock_nvinsert("location", url.c_str(), m_rq->srvhdrs);
303 pblock_nvinsert("connection","close",m_rq->srvhdrs);
304 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
305 protocol_start_response(m_sn, m_rq);
306 return (void*)REQ_ABORTED;
308 virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
309 virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
316 /********************************************************************************/
318 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
320 log_error(LOG_FAILURE,func,sn,rq,msg);
321 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
326 #define FUNC "shibboleth"
327 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
329 ostringstream threadid;
330 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
331 saml::NDC ndc(threadid.str().c_str());
334 ShibTargetNSAPI stn(pb, sn, rq);
336 // Check user authentication
337 pair<bool,void*> res = stn.doCheckAuthN();
338 if (res.first) return (int)res.second;
340 // user authN was okay -- export the assertions now
341 param_free(pblock_remove("auth-user",rq->vars));
342 // This seems to be required in order to eventually set
343 // the auth-user var.
344 pblock_nvinsert("auth-type","shibboleth",rq->vars);
345 res = stn.doExportAssertions();
346 if (res.first) return (int)res.second;
348 // Check the Authorization
349 res = stn.doCheckAuthZ();
350 if (res.first) return (int)res.second;
355 catch (SAMLException& e) {
356 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
357 return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an exception, see web server log for error.");
361 return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an uncaught exception.");
368 #define FUNC "shib_handler"
369 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
371 ostringstream threadid;
372 threadid << "[" << getpid() << "] shib_handler" << '\0';
373 saml::NDC ndc(threadid.str().c_str());
376 ShibTargetNSAPI stn(pb, sn, rq);
378 pair<bool,void*> res = stn.doHandler();
379 if (res.first) return (int)res.second;
381 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
383 catch (SAMLException& e) {
384 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
385 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
389 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
395 class SunRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
398 SunRequestMapper(const DOMElement* e);
399 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
400 void lock() { m_mapper->lock(); }
401 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
402 Settings getSettings(ShibTarget* st) const;
404 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
405 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
406 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
407 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
408 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
409 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
410 const DOMElement* getElement() const;
413 IRequestMapper* m_mapper;
415 ThreadKey* m_propsKey;
418 IPlugIn* SunRequestMapFactory(const DOMElement* e)
420 return new SunRequestMapper(e);
423 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
425 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
426 m_mapper=dynamic_cast<IRequestMapper*>(p);
429 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
431 m_stKey=ThreadKey::create(NULL);
432 m_propsKey=ThreadKey::create(NULL);
435 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
437 Settings s=m_mapper->getSettings(st);
438 m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
439 m_propsKey->setData((void*)s.first);
440 return pair<const IPropertySet*,IAccessControl*>(this,s.second);
443 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
445 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
446 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
447 if (stn && !ns && name) {
448 // Override boolean properties.
449 const char* param=pblock_findval(name,stn->m_pb);
450 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
451 return make_pair(true,true);
453 return s ? s->getBool(name,ns) : make_pair(false,false);
456 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
458 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
459 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
460 if (stn && !ns && name) {
461 // Override string properties.
462 if (!strcmp(name,"authType"))
463 return pair<bool,const char*>(true,"shibboleth");
465 const char* param=pblock_findval(name,stn->m_pb);
467 return make_pair(true,param);
470 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
473 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
475 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
476 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
479 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
481 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
482 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
483 if (stn && !ns && name) {
484 // Override int properties.
485 const char* param=pblock_findval(name,stn->m_pb);
487 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
489 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
492 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
494 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
495 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
496 if (stn && !ns && name) {
497 // Override int properties.
498 const char* param=pblock_findval(name,stn->m_pb);
500 return pair<bool,int>(true,atoi(param));
502 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
505 const IPropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
507 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
508 return s ? s->getPropertySet(name,ns) : NULL;
511 const DOMElement* SunRequestMapper::getElement() const
513 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
514 return s ? s->getElement() : NULL;