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
34 #include <shibsp/SPConfig.h>
35 #include <xmltooling/util/Threads.h>
38 #include <saml/saml.h>
39 #include <shib/shib.h>
40 #include <shib-target/shib-target.h>
62 using namespace shibsp;
63 using namespace shibtarget;
65 using namespace xmltooling;
68 // macros to output text to client
69 #define NET_WRITE(str) \
70 if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
73 ShibTargetConfig* g_Config=NULL;
75 string g_ServerScheme;
78 PlugManager::Factory SunRequestMapFactory;
80 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
87 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, Session* sn, Request* rq)
89 // Save off a default hostname for this virtual server.
90 char* name=pblock_findval("server-name",pb);
104 pblock_nvinsert("error","unable to determine web server hostname",pb);
109 name=pblock_findval("server-scheme",pb);
113 log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
118 const char* schemadir=pblock_findval("shib-schemas",pb);
120 schemadir=getenv("SHIBSCHEMAS");
122 schemadir=SHIB_SCHEMAS;
123 const char* config=pblock_findval("shib-config",pb);
125 config=getenv("SHIBCONFIG");
128 g_Config=&ShibTargetConfig::getConfig();
129 SPConfig::getConfig().setFeatures(
134 SPConfig::RequestMapper |
135 SPConfig::InProcess |
138 if (!g_Config->init(schemadir)) {
140 pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
144 SAMLConfig::getConfig().getPlugMgr().regFactory(NATIVE_REQUESTMAP_PROVIDER,&SunRequestMapFactory);
145 // We hijack the legacy type so that 1.2 config files will load this plugin
146 SAMLConfig::getConfig().getPlugMgr().regFactory(LEGACY_REQUESTMAP_PROVIDER,&SunRequestMapFactory);
148 if (!g_Config->load(config)) {
150 pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
154 daemon_atrestart(nsapi_shib_exit,NULL);
159 pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
166 /********************************************************************************/
167 // NSAPI Shib Target Subclass
169 class ShibTargetNSAPI : public ShibTarget
171 mutable string m_body;
172 mutable bool m_gotBody;
174 ShibTargetNSAPI(pblock* pb, Session* sn, Request* rq) : m_gotBody(false) {
179 // Get everything but hostname...
180 const char* uri=pblock_findval("uri", rq->reqpb);
181 const char* qstr=pblock_findval("query", rq->reqpb);
182 int port=server_portnum;
183 const char* scheme=security_active ? "https" : "http";
184 const char* host=NULL;
190 url=url + '?' + qstr;
192 #ifdef vs_is_default_vs
193 // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
194 if (!vs_is_default_vs)
195 // The beauty here is, a non-default vhost can *only* be accessed if the client
196 // specified the exact name in the Host header. So we can trust the Host header.
197 host=pblock_findval("host", rq->headers);
200 // In other cases, we're going to rely on the initialization process...
201 host=g_ServerName.c_str();
203 char* content_type = "";
204 request_header("content-type", &content_type, sn, rq);
206 const char *remote_ip = pblock_findval("ip", sn->client);
207 const char *method = pblock_findval("method", rq->reqpb);
209 init(scheme, host, port, url.c_str(), content_type, remote_ip, method);
211 ~ShibTargetNSAPI() {}
213 virtual void log(ShibLogLevel level, const string &msg) {
214 ShibTarget::log(level,msg);
215 if (level==LogLevelError)
216 log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
218 virtual string getCookies(void) const {
219 char *cookies = NULL;
220 if (request_header("cookie", &cookies, m_sn, m_rq) == REQ_ABORTED)
221 throw("error accessing cookie header");
222 return string(cookies ? cookies : "");
224 virtual void setCookie(const string &name, const string &value) {
225 string cookie = name + '=' + value;
226 pblock_nvinsert("Set-Cookie", cookie.c_str(), m_rq->srvhdrs);
228 virtual const char* getQueryString() const {
229 return pblock_findval("query", m_rq->reqpb);
231 virtual const char* getRequestBody() const {
233 return m_body.c_str();
234 char* content_length=NULL;
235 if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
236 atoi(content_length) > 1024*1024) // 1MB?
237 throw SAMLException("Blocked POST request body exceeding size limit.");
240 int cl=atoi(content_length);
242 while (cl && ch != IO_EOF) {
243 ch=netbuf_getc(m_sn->inbuf);
251 throw SAMLException("Error reading POST request body from browser.");
252 return m_body.c_str();
255 virtual void clearHeader(const string &name) {
256 if (name=="REMOTE_USER") {
257 param_free(pblock_remove("auth-user",m_rq->vars));
258 param_free(pblock_remove("remote-user",m_rq->headers));
261 param_free(pblock_remove(name.c_str(), m_rq->headers));
263 virtual void setHeader(const string &name, const string &value) {
264 pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
266 virtual string getHeader(const string &name) {
268 if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
270 return string(hdr ? hdr : "");
272 virtual void setRemoteUser(const string &user) {
273 pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
274 pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
276 virtual string getRemoteUser(void) {
277 return getHeader("remote-user");
280 virtual void* sendPage(
283 const string& content_type="text/html",
284 const saml::Iterator<header_t>& headers=EMPTY(header_t)
286 param_free(pblock_remove("content-type", m_rq->srvhdrs));
287 pblock_nvinsert("content-type", content_type.c_str(), m_rq->srvhdrs);
288 pblock_nninsert("content-length", msg.length(), m_rq->srvhdrs);
289 pblock_nvinsert("connection","close",m_rq->srvhdrs);
290 while (headers.hasNext()) {
291 const header_t& h=headers.next();
292 pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
294 protocol_status(m_sn, m_rq, code, NULL);
295 protocol_start_response(m_sn, m_rq);
296 net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
297 return (void*)REQ_EXIT;
299 virtual void* sendRedirect(const string& url) {
300 param_free(pblock_remove("content-type", m_rq->srvhdrs));
301 pblock_nninsert("content-length", 0, m_rq->srvhdrs);
302 pblock_nvinsert("expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
303 pblock_nvinsert("cache-control", "private,no-store,no-cache", m_rq->srvhdrs);
304 pblock_nvinsert("location", url.c_str(), m_rq->srvhdrs);
305 pblock_nvinsert("connection","close",m_rq->srvhdrs);
306 protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, NULL);
307 protocol_start_response(m_sn, m_rq);
308 return (void*)REQ_ABORTED;
310 virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
311 virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
318 /********************************************************************************/
320 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
322 log_error(LOG_FAILURE,func,sn,rq,msg);
323 protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
328 #define FUNC "shibboleth"
329 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
331 ostringstream threadid;
332 threadid << "[" << getpid() << "] nsapi_shib" << '\0';
333 saml::NDC ndc(threadid.str().c_str());
336 ShibTargetNSAPI stn(pb, sn, rq);
338 // Check user authentication
339 pair<bool,void*> res = stn.doCheckAuthN();
340 if (res.first) return (int)res.second;
342 // user authN was okay -- export the assertions now
343 param_free(pblock_remove("auth-user",rq->vars));
344 // This seems to be required in order to eventually set
345 // the auth-user var.
346 pblock_nvinsert("auth-type","shibboleth",rq->vars);
347 res = stn.doExportAssertions();
348 if (res.first) return (int)res.second;
350 // Check the Authorization
351 res = stn.doCheckAuthZ();
352 if (res.first) return (int)res.second;
357 catch (SAMLException& e) {
358 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
359 return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an exception, see web server log for error.");
363 return WriteClientError(sn, rq, FUNC, "Shibboleth filter threw an uncaught exception.");
370 #define FUNC "shib_handler"
371 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
373 ostringstream threadid;
374 threadid << "[" << getpid() << "] shib_handler" << '\0';
375 saml::NDC ndc(threadid.str().c_str());
378 ShibTargetNSAPI stn(pb, sn, rq);
380 pair<bool,void*> res = stn.doHandler();
381 if (res.first) return (int)res.second;
383 return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
385 catch (SAMLException& e) {
386 log_error(LOG_FAILURE,FUNC,sn,rq,const_cast<char*>(e.what()));
387 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an exception, see web server log for error.");
391 return WriteClientError(sn, rq, FUNC, "Shibboleth handler threw an unknown exception.");
397 class SunRequestMapper : public virtual IRequestMapper, public virtual PropertySet
400 SunRequestMapper(const DOMElement* e);
401 ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
402 Lockable* lock() { return m_mapper->lock(); }
403 void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
404 Settings getSettings(ShibTarget* st) const;
406 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
407 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
408 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
409 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
410 pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
411 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
412 const DOMElement* getElement() const;
415 IRequestMapper* m_mapper;
417 ThreadKey* m_propsKey;
420 IPlugIn* SunRequestMapFactory(const DOMElement* e)
422 return new SunRequestMapper(e);
425 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
427 IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(XML_REQUESTMAP_PROVIDER,e);
428 m_mapper=dynamic_cast<IRequestMapper*>(p);
431 throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
433 m_stKey=ThreadKey::create(NULL);
434 m_propsKey=ThreadKey::create(NULL);
437 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
439 Settings s=m_mapper->getSettings(st);
440 m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
441 m_propsKey->setData((void*)s.first);
442 return pair<const PropertySet*,IAccessControl*>(this,s.second);
445 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
447 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
448 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
449 if (stn && !ns && name) {
450 // Override boolean properties.
451 const char* param=pblock_findval(name,stn->m_pb);
452 if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
453 return make_pair(true,true);
455 return s ? s->getBool(name,ns) : make_pair(false,false);
458 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
460 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
461 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
462 if (stn && !ns && name) {
463 // Override string properties.
464 if (!strcmp(name,"authType"))
465 return pair<bool,const char*>(true,"shibboleth");
467 const char* param=pblock_findval(name,stn->m_pb);
469 return make_pair(true,param);
472 return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
475 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
477 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
478 return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
481 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
483 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
484 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
485 if (stn && !ns && name) {
486 // Override int properties.
487 const char* param=pblock_findval(name,stn->m_pb);
489 return pair<bool,unsigned int>(true,strtol(param,NULL,10));
491 return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
494 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
496 ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
497 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
498 if (stn && !ns && name) {
499 // Override int properties.
500 const char* param=pblock_findval(name,stn->m_pb);
502 return pair<bool,int>(true,atoi(param));
504 return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
507 const PropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
509 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
510 return s ? s->getPropertySet(name,ns) : NULL;
513 const DOMElement* SunRequestMapper::getElement() const
515 const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
516 return s ? s->getElement() : NULL;