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>
60 using namespace shibtarget;
62 using namespace xmltooling;
65 // macros to output text to client
66 #define NET_WRITE(str) \
67 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
70 ShibTargetConfig* g_Config=NULL;
72 string g_ServerScheme;
75 PlugManager::Factory SunRequestMapFactory;
77 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
84 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, Session* sn, Request* rq)
86 // Save off a default hostname for this virtual server.
87 char* name=pblock_findval("server-name",pb);
101 pblock_nvinsert("error","unable to determine web server hostname",pb);
106 name=pblock_findval("server-scheme",pb);
110 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
115 const char* schemadir=pblock_findval("shib-schemas",pb);
117 schemadir=getenv("SHIBSCHEMAS");
119 schemadir=SHIB_SCHEMAS;
120 const char* config=pblock_findval("shib-config",pb);
122 config=getenv("SHIBCONFIG");
125 g_Config=&ShibTargetConfig::getConfig();
126 g_Config->setFeatures(
127 ShibTargetConfig::Listener |
128 ShibTargetConfig::Caching |
129 ShibTargetConfig::Metadata |
130 ShibTargetConfig::AAP |
131 ShibTargetConfig::RequestMapper |
132 ShibTargetConfig::InProcess |
133 ShibTargetConfig::Logging
135 if (!g_Config->init(schemadir)) {
137 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
141 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&SunRequestMapFactory);
142 // We hijack the legacy type so that 1.2 config files will load this plugin
143 SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&SunRequestMapFactory);
145 if (!g_Config->load(config)) {
147 pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
151 daemon_atrestart(nsapi_shib_exit,NULL);
156 pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
163 /********************************************************************************/
164 // NSAPI Shib Target Subclass
166 class ShibTargetNSAPI : public ShibTarget
168 mutable string m_body;
169 mutable bool m_gotBody;
171 ShibTargetNSAPI(pblock* pb, Session* sn, Request* rq) : m_gotBody(false) {
176 // Get everything but hostname...
177 const char* uri=pblock_findval("uri", rq->reqpb);
178 const char* qstr=pblock_findval("query", rq->reqpb);
179 int port=server_portnum;
180 const char* scheme=security_active ? "https" : "http";
181 const char* host=NULL;
187 url=url + '?' + qstr;
189 #ifdef vs_is_default_vs
190 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
191 if (!vs_is_default_vs)
192 // The beauty here is, a non-default vhost can *only* be accessed if the client
193 // specified the exact name in the Host header. So we can trust the Host header.
194 host=pblock_findval("host", rq->headers);
197 // In other cases, we're going to rely on the initialization process...
198 host=g_ServerName.c_str();
200 char* content_type = "";
201 request_header("content-type", &content_type, sn, rq);
203 const char *remote_ip = pblock_findval("ip", sn->client);
204 const char *method = pblock_findval("method", rq->reqpb);
206 init(scheme, host, port, url.c_str(), content_type, remote_ip, method);
208 ~ShibTargetNSAPI() {}
210 virtual void log(ShibLogLevel level, const string &msg) {
211 ShibTarget::log(level,msg);
212 if (level==LogLevelError)
213 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
215 virtual string getCookies(void) const {
216 char *cookies = NULL;
217 if (request_header("cookie", &cookies, m_sn, m_rq) == REQ_ABORTED)
218 throw("error accessing cookie header");
219 return string(cookies ? cookies : "");
221 virtual void setCookie(const string &name, const string &value) {
222 string cookie = name + '=' + value;
223 pblock_nvinsert("Set-Cookie", cookie.c_str(), m_rq->srvhdrs);
225 virtual const char* getQueryString() const {
226 return pblock_findval("query", m_rq->reqpb);
228 virtual const char* getRequestBody() const {
230 return m_body.c_str();
231 char* content_length=NULL;
232 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
233 atoi(content_length) > 1024*1024) // 1MB?
234 throw SAMLException("Blocked POST request body exceeding size limit.");
237 int cl=atoi(content_length);
239 while (cl && ch != IO_EOF) {
240 ch=netbuf_getc(m_sn->inbuf);
248 throw SAMLException("Error reading POST request body from browser.");
249 return m_body.c_str();
252 virtual void clearHeader(const string &name) {
253 if (name=="REMOTE_USER") {
254 param_free(pblock_remove("auth-user",m_rq->vars));
255 param_free(pblock_remove("remote-user",m_rq->headers));
258 param_free(pblock_remove(name.c_str(), m_rq->headers));
260 virtual void setHeader(const string &name, const string &value) {
261 pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
263 virtual string getHeader(const string &name) {
265 if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
267 return string(hdr ? hdr : "");
269 virtual void setRemoteUser(const string &user) {
270 pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
271 pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
273 virtual string getRemoteUser(void) {
274 return getHeader("remote-user");
277 virtual void* sendPage(
280 const string& content_type="text/html",
281 const saml::Iterator<header_t>& headers=EMPTY(header_t)
283 param_free(pblock_remove("content-type", m_rq->srvhdrs));
284 pblock_nvinsert("content-type", content_type.c_str(), m_rq->srvhdrs);
285 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
286 pblock_nvinsert("connection","close",m_rq->srvhdrs);
287 while (headers.hasNext()) {
288 const header_t& h=headers.next();
289 pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
291 protocol_status(m_sn, m_rq, code, NULL);
292 protocol_start_response(m_sn, m_rq);
293 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
294 return (void*)REQ_EXIT;
296 virtual void* sendRedirect(const string& url) {
297 param_free(pblock_remove("content-type", m_rq->srvhdrs));
298 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
299 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
300 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
301 pblock_nvinsert("location", url.c_str(), m_rq->srvhdrs);
302 pblock_nvinsert("connection","close",m_rq->srvhdrs);
303 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
304 protocol_start_response(m_sn, m_rq);
305 return (void*)REQ_ABORTED;
307 virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
308 virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
315 /********************************************************************************/
317 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
319 log_error(LOG_FAILURE,func,sn,rq,msg);
320 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
325 #define FUNC "shibboleth"
326 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
328 ostringstream threadid;
329 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
330 saml::NDC ndc(threadid.str().c_str());
333 ShibTargetNSAPI stn(pb, sn, rq);
335 // Check user authentication
336 pair<bool,void*> res = stn.doCheckAuthN();
337 if (res.first) return (int)res.second;
339 // user authN was okay -- export the assertions now
340 param_free(pblock_remove("auth-user",rq->vars));
341 // This seems to be required in order to eventually set
342 // the auth-user var.
343 pblock_nvinsert("auth-type","shibboleth",rq->vars);
344 res = stn.doExportAssertions();
345 if (res.first) return (int)res.second;
347 // Check the Authorization
348 res = stn.doCheckAuthZ();
349 if (res.first) return (int)res.second;
354 catch (SAMLException& e) {
355 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
356 return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an exception, see web server log for error.");
360 return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an uncaught exception.");
367 #define FUNC "shib_handler"
368 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
370 ostringstream threadid;
371 threadid << "[" << getpid() << "] shib_handler" << '\0';
372 saml::NDC ndc(threadid.str().c_str());
375 ShibTargetNSAPI stn(pb, sn, rq);
377 pair<bool,void*> res = stn.doHandler();
378 if (res.first) return (int)res.second;
380 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
382 catch (SAMLException& e) {
383 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
384 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
388 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
394 class SunRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
397 SunRequestMapper(const DOMElement* e);
398 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
399 void lock() { m_mapper->lock(); }
400 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
401 Settings getSettings(ShibTarget* st) const;
403 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
404 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
405 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
406 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
407 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
408 const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
409 const DOMElement* getElement() const;
412 IRequestMapper* m_mapper;
414 ThreadKey* m_propsKey;
417 IPlugIn* SunRequestMapFactory(const DOMElement* e)
419 return new SunRequestMapper(e);
422 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
424 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
425 m_mapper=dynamic_cast<IRequestMapper*>(p);
428 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
430 m_stKey=ThreadKey::create(NULL);
431 m_propsKey=ThreadKey::create(NULL);
434 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
436 Settings s=m_mapper->getSettings(st);
437 m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
438 m_propsKey->setData((void*)s.first);
439 return pair<const IPropertySet*,IAccessControl*>(this,s.second);
442 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
444 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
445 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
446 if (stn && !ns && name) {
447 // Override boolean properties.
448 const char* param=pblock_findval(name,stn->m_pb);
449 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
450 return make_pair(true,true);
452 return s ? s->getBool(name,ns) : make_pair(false,false);
455 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
457 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
458 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
459 if (stn && !ns && name) {
460 // Override string properties.
461 if (!strcmp(name,"authType"))
462 return pair<bool,const char*>(true,"shibboleth");
464 const char* param=pblock_findval(name,stn->m_pb);
466 return make_pair(true,param);
469 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
472 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
474 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
475 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
478 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
480 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
481 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
482 if (stn && !ns && name) {
483 // Override int properties.
484 const char* param=pblock_findval(name,stn->m_pb);
486 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
488 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
491 pair<bool,int> SunRequestMapper::getInt(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 int properties.
497 const char* param=pblock_findval(name,stn->m_pb);
499 return pair<bool,int>(true,atoi(param));
501 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
504 const IPropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
506 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
507 return s ? s->getPropertySet(name,ns) : NULL;
510 const DOMElement* SunRequestMapper::getElement() const
512 const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
513 return s ? s->getElement() : NULL;