Some Unix fixes.
[shibboleth/cpp-sp.git] / nsapi_shib / nsapi_shib.cpp
1 /*
2  * The Shibboleth License, Version 1.
3  * Copyright (c) 2002
4  * University Corporation for Advanced Internet Development, Inc.
5  * All rights reserved
6  *
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * Redistributions of source code must retain the above copyright notice, this
12  * list of conditions and the following disclaimer.
13  *
14  * Redistributions in binary form must reproduce the above copyright notice,
15  * this list of conditions and the following disclaimer in the documentation
16  * and/or other materials provided with the distribution, if any, must include
17  * the following acknowledgment: "This product includes software developed by
18  * the University Corporation for Advanced Internet Development
19  * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
20  * may appear in the software itself, if and wherever such third-party
21  * acknowledgments normally appear.
22  *
23  * Neither the name of Shibboleth nor the names of its contributors, nor
24  * Internet2, nor the University Corporation for Advanced Internet Development,
25  * Inc., nor UCAID may be used to endorse or promote products derived from this
26  * software without specific prior written permission. For written permission,
27  * please contact shibboleth@shibboleth.org
28  *
29  * Products derived from this software may not be called Shibboleth, Internet2,
30  * UCAID, or the University Corporation for Advanced Internet Development, nor
31  * may Shibboleth appear in their name, without prior written permission of the
32  * University Corporation for Advanced Internet Development.
33  *
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
38  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
39  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
40  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
41  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 /* nsapi_shib.cpp - Shibboleth NSAPI filter
51
52    Scott Cantor
53    12/13/04
54 */
55
56 #include "config_win32.h"
57
58 // SAML Runtime
59 #include <saml/saml.h>
60 #include <shib/shib.h>
61 #include <shib/shib-threads.h>
62 #include <shib-target/shib-target.h>
63
64 #include <ctime>
65 #include <fstream>
66 #include <sstream>
67 #include <stdexcept>
68
69 #ifdef WIN32
70 # include <process.h>
71 # define XP_WIN32
72 #else
73 # define XP_UNIX
74 #endif
75
76 #define MCC_HTTPD
77 #define NET_SSL
78
79 extern "C"
80 {
81 #include <nsapi.h>
82 }
83
84 using namespace std;
85 using namespace saml;
86 using namespace shibboleth;
87 using namespace shibtarget;
88
89 // macros to output text to client
90 #define NET_WRITE(str) \
91     if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
92
93 namespace {
94     ShibTargetConfig* g_Config=NULL;
95     string g_ServerName;
96     string g_ServerScheme;
97 }
98
99 PlugManager::Factory SunRequestMapFactory;
100
101 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
102 {
103     if (g_Config)
104         g_Config->shutdown();
105     g_Config = NULL;
106 }
107
108 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, Session* sn, Request* rq)
109 {
110     // Save off a default hostname for this virtual server.
111     char* name=pblock_findval("server-name",pb);
112     if (name)
113         g_ServerName=name;
114     else {
115         name=server_hostname;
116         if (name)
117             g_ServerName=name;
118         else {
119             name=util_hostname();
120             if (name) {
121                 g_ServerName=name;
122                 FREE(name);
123             }
124             else {
125                 pblock_nvinsert("error","unable to determine web server hostname",pb);
126                 return REQ_ABORTED;
127             }
128         }
129     }
130     name=pblock_findval("server-scheme",pb);
131     if (name)
132         g_ServerScheme=name;
133
134     log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
135
136 #ifndef _DEBUG
137     try {
138 #endif
139         const char* schemadir=pblock_findval("shib-schemas",pb);
140         if (!schemadir)
141             schemadir=getenv("SHIBSCHEMAS");
142         if (!schemadir)
143             schemadir=SHIB_SCHEMAS;
144         const char* config=pblock_findval("shib-config",pb);
145         if (!config)
146             config=getenv("SHIBCONFIG");
147         if (!config)
148             config=SHIB_CONFIG;
149         g_Config=&ShibTargetConfig::getConfig();
150         g_Config->setFeatures(
151             ShibTargetConfig::Listener |
152             ShibTargetConfig::Metadata |
153             ShibTargetConfig::AAP |
154             ShibTargetConfig::RequestMapper |
155             ShibTargetConfig::LocalExtensions |
156             ShibTargetConfig::Logging
157             );
158         if (!g_Config->init(schemadir)) {
159             g_Config=NULL;
160             pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
161             return REQ_ABORTED;
162         }
163
164         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&SunRequestMapFactory);
165         // We hijack the legacy type so that 1.2 config files will load this plugin
166         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&SunRequestMapFactory);
167
168         if (!g_Config->load(config)) {
169             g_Config=NULL;
170             pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
171             return REQ_ABORTED;
172         }
173
174         daemon_atrestart(nsapi_shib_exit,NULL);
175 #ifndef _DEBUG
176     }
177     catch (...) {
178         g_Config=NULL;
179         pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
180         return REQ_ABORTED;
181     }
182 #endif
183     return REQ_PROCEED;
184 }
185
186 /********************************************************************************/
187 // NSAPI Shib Target Subclass
188
189 class ShibTargetNSAPI : public ShibTarget
190 {
191 public:
192   ShibTargetNSAPI(pblock* pb, Session* sn, Request* rq) {
193     m_pb = pb;
194     m_sn = sn;
195     m_rq = rq;
196
197     // Get everything but hostname...
198     const char* uri=pblock_findval("uri", rq->reqpb);
199     const char* qstr=pblock_findval("query", rq->reqpb);
200     int port=server_portnum;
201     const char* scheme=security_active ? "https" : "http";
202     const char* host=NULL;
203
204     string url;
205     if (uri)
206         url=uri;
207     if (qstr)
208         url=url + '?' + qstr;
209     
210 #ifdef vs_is_default_vs
211     // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
212     if (!vs_is_default_vs)
213         // The beauty here is, a non-default vhost can *only* be accessed if the client
214         // specified the exact name in the Host header. So we can trust the Host header.
215         host=pblock_findval("host", rq->headers);
216     else
217 #endif
218     // In other cases, we're going to rely on the initialization process...
219     host=g_ServerName.c_str();
220
221     char* content_type = "";
222     request_header("content-type", &content_type, sn, rq);
223       
224     const char *remote_ip = pblock_findval("ip", sn->client);
225     const char *method = pblock_findval("method", rq->reqpb);
226
227     init(scheme, host, port, url.c_str(), content_type, remote_ip, method);
228   }
229   ~ShibTargetNSAPI() {}
230
231   virtual void log(ShibLogLevel level, const string &msg) {
232     ShibTarget::log(level,msg);
233     if (level==LogLevelError)
234         log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
235   }
236   virtual string getCookies(void) const {
237     char *cookies = NULL;
238     if (request_header("cookie", &cookies, m_sn, m_rq) == REQ_ABORTED)
239       throw("error accessing cookie header");
240     return string(cookies ? cookies : "");
241   }
242   virtual void setCookie(const string &name, const string &value) {
243     string cookie = name + '=' + value;
244     pblock_nvinsert("Set-Cookie", cookie.c_str(), m_rq->srvhdrs);
245   }
246   virtual string getArgs(void) { 
247     const char *q = pblock_findval("query", m_rq->reqpb);
248     return string(q ? q : "");
249   }
250   virtual string getPostData(void) {
251     char* content_length=NULL;
252     if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
253          atoi(content_length) > 1024*1024) // 1MB?
254       throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
255     else {
256       char ch=IO_EOF+1;
257       int cl=atoi(content_length);
258       string cgistr;
259       while (cl && ch != IO_EOF) {
260         ch=netbuf_getc(m_sn->inbuf);
261       
262         // Check for error.
263         if(ch==IO_ERROR)
264           break;
265         cgistr += ch;
266         cl--;
267       }
268       if (cl)
269         throw FatalProfileException("Error reading profile submission from browser.");
270       return cgistr;
271     }
272   }
273   virtual void clearHeader(const string &name) {
274     param_free(pblock_remove(name.c_str(), m_rq->headers));
275   }
276   virtual void setHeader(const string &name, const string &value) {
277     pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
278   }
279   virtual string getHeader(const string &name) {
280     char *hdr = NULL;
281     if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
282       hdr = NULL;
283     return string(hdr ? hdr : "");
284   }
285   virtual void setRemoteUser(const string &user) {
286     pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
287     pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
288   }
289   virtual string getRemoteUser(void) {
290     return getHeader("remote-user");
291   }
292
293   virtual void* sendPage(
294     const string& msg,
295     int code=200,
296     const string& content_type="text/html",
297     const saml::Iterator<header_t>& headers=EMPTY(header_t)
298     ) {
299     pblock_nvinsert("Content-Type", content_type.c_str(), m_rq->srvhdrs);
300     pblock_nninsert("Content-Length", msg.length(), m_rq->srvhdrs);
301     pblock_nvinsert("Connection","close",m_rq->srvhdrs);
302     while (headers.hasNext()) {
303         const header_t& h=headers.next();
304         pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
305     }
306     protocol_status(m_sn, m_rq, code, NULL);
307     net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
308     return (void*)REQ_EXIT;
309   }
310   virtual void* sendRedirect(const string& url) {
311     pblock_nvinsert("Content-Type", "text/html", m_rq->srvhdrs);
312     pblock_nninsert("Content-Length", 40, m_rq->srvhdrs);
313     pblock_nvinsert("Expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
314     pblock_nvinsert("Cache-Control", "private,no-store,no-cache", m_rq->srvhdrs);
315     pblock_nvinsert("Location", url.c_str(), m_rq->srvhdrs);
316     protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, "302 Please wait");
317     protocol_start_response(m_sn, m_rq);
318     char* msg="<HTML><BODY>Redirecting...</BODY></HTML>";
319     net_write(m_sn->csd,msg,strlen(msg));
320     return (void*)REQ_EXIT;
321   }
322   virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
323   virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
324
325   pblock* m_pb;
326   Session* m_sn;
327   Request* m_rq;
328 };
329
330 /********************************************************************************/
331
332 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
333 {
334     log_error(LOG_FAILURE,func,sn,rq,msg);
335     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
336     return REQ_ABORTED;
337 }
338
339 #undef FUNC
340 #define FUNC "shibboleth"
341 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
342 {
343   ostringstream threadid;
344   threadid << "[" << getpid() << "] nsapi_shib" << '\0';
345   saml::NDC ndc(threadid.str().c_str());
346
347 #ifndef _DEBUG
348   try {
349 #endif
350     ShibTargetNSAPI stn(pb, sn, rq);
351
352     // Check user authentication
353     pair<bool,void*> res = stn.doCheckAuthN();
354     if (res.first) return (int)res.second;
355
356     // user authN was okay -- export the assertions now
357     param_free(pblock_remove("auth-user",rq->vars));
358     // This seems to be required in order to eventually set
359     // the auth-user var.
360     pblock_nvinsert("auth-type","shibboleth",rq->vars);
361     res = stn.doExportAssertions();
362     if (res.first) return (int)res.second;
363
364     // Check the Authorization
365     res = stn.doCheckAuthZ();
366     if (res.first) return (int)res.second;
367
368     // this user is ok.
369     return REQ_PROCEED;
370
371 #ifndef _DEBUG
372   }
373   catch (...) {
374     return WriteClientError(sn, rq, FUNC, "threw an uncaught exception.");
375   }
376 #endif
377 }
378
379
380 #undef FUNC
381 #define FUNC "shib_handler"
382 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
383 {
384   ostringstream threadid;
385   threadid << "[" << getpid() << "] shib_handler" << '\0';
386   saml::NDC ndc(threadid.str().c_str());
387
388 #ifndef _DEBUG
389   try {
390 #endif
391     ShibTargetNSAPI stn(pb, sn, rq);
392
393     pair<bool,void*> res = stn.doHandler();
394     if (res.first) return (int)res.second;
395
396     return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
397
398 #ifndef _DEBUG
399   }
400   catch (...) {
401     return WriteClientError(sn, rq, FUNC, "Filter threw an unknown exception.");
402   }
403 #endif
404 }
405
406
407 class SunRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
408 {
409 public:
410     SunRequestMapper(const DOMElement* e);
411     ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
412     void lock() { m_mapper->lock(); }
413     void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
414     Settings getSettings(ShibTarget* st) const;
415     
416     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
417     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
418     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
419     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
420     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
421     const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
422     const DOMElement* getElement() const;
423
424 private:
425     IRequestMapper* m_mapper;
426     ThreadKey* m_stKey;
427     ThreadKey* m_propsKey;
428 };
429
430 IPlugIn* SunRequestMapFactory(const DOMElement* e)
431 {
432     return new SunRequestMapper(e);
433 }
434
435 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
436 {
437     IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
438     m_mapper=dynamic_cast<IRequestMapper*>(p);
439     if (!m_mapper) {
440         delete p;
441         throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
442     }
443     m_stKey=ThreadKey::create(NULL);
444     m_propsKey=ThreadKey::create(NULL);
445 }
446
447 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
448 {
449     Settings s=m_mapper->getSettings(st);
450     m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
451     m_propsKey->setData((void*)s.first);
452     return pair<const IPropertySet*,IAccessControl*>(this,s.second);
453 }
454
455 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
456 {
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 boolean properties.
461         const char* param=pblock_findval(name,stn->m_pb);
462         if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
463             return make_pair(true,true);
464     }
465     return s ? s->getBool(name,ns) : make_pair(false,false);
466 }
467
468 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
469 {
470     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
471     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
472     if (stn && !ns && name) {
473         // Override string properties.
474         if (!strcmp(name,"authType"))
475             return pair<bool,const char*>(true,"shibboleth");
476         else {
477             const char* param=pblock_findval(name,stn->m_pb);
478             if (param)
479                 return make_pair(true,param);
480         }
481     }
482     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
483 }
484
485 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
486 {
487     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
488     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
489 }
490
491 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
492 {
493     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
494     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
495 }
496
497 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
498 {
499     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
500     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
501 }
502
503 const IPropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
504 {
505     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
506     return s ? s->getPropertySet(name,ns) : NULL;
507 }
508
509 const DOMElement* SunRequestMapper::getElement() const
510 {
511     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
512     return s ? s->getElement() : NULL;
513 }
514
515
516 #if 0
517
518 IRequestMapper::Settings map_request(pblock* pb, Session* sn, Request* rq, IRequestMapper* mapper, string& target)
519 {
520     // Get everything but hostname...
521     const char* uri=pblock_findval("uri",rq->reqpb);
522     const char* qstr=pblock_findval("query",rq->reqpb);
523     int port=server_portnum;
524     const char* scheme=security_active ? "https" : "http";
525     const char* host=NULL;
526
527     string url;
528     if (uri)
529         url=uri;
530     if (qstr)
531         url=url + '?' + qstr;
532     
533 #ifdef vs_is_default_vs
534     // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
535     if (!vs_is_default_vs)
536         // The beauty here is, a non-default vhost can *only* be accessed if the client
537         // specified the exact name in the Host header. So we can trust the Host header.
538         host=pblock_findval("host", rq->headers);
539     else
540 #endif
541     // In other cases, we're going to rely on the initialization process...
542     host=g_ServerName.c_str();
543         
544     target=(g_ServerScheme.empty() ? string(scheme) : g_ServerScheme) + "://" + host;
545     
546     // If port is non-default, append it.
547     if ((!security_active && port!=80) || (security_active && port!=443)) {
548         char portbuf[10];
549         util_snprintf(portbuf,9,"%d",port);
550         target = target + ':' + portbuf;
551     }
552
553     target+=url;
554         
555     return mapper->getSettingsFromParsedURL(scheme,host,port,url.c_str());
556 }
557
558 int WriteClientError(Session* sn, Request* rq, const IApplication* app, const char* page, ShibMLP& mlp)
559 {
560     const IPropertySet* props=app->getPropertySet("Errors");
561     if (props) {
562         pair<bool,const char*> p=props->getString(page);
563         if (p.first) {
564             ifstream infile(p.second);
565             if (!infile.fail()) {
566                 const char* res = mlp.run(infile,props);
567                 if (res) {
568                     pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
569                     pblock_nninsert("Content-Length",strlen(res),rq->srvhdrs);
570                     pblock_nvinsert("Connection","close",rq->srvhdrs);
571                     protocol_status(sn,rq,PROTOCOL_OK,NULL);
572                     NET_WRITE(const_cast<char*>(res));
573                     return REQ_EXIT;
574                 }
575             }
576         }
577     }
578
579     log_error(LOG_FAILURE,"WriteClientError",sn,rq,"Unable to open error template, check settings.");
580     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,"Unable to open error template, check settings.");
581     return REQ_ABORTED;
582 }
583
584 int WriteRedirectPage(Session* sn, Request* rq, const IApplication* app, const char* file, ShibMLP& mlp)
585 {
586     ifstream infile(file);
587     if (!infile.fail()) {
588         const char* res = mlp.run(infile,app->getPropertySet("Errors"));
589         if (res) {
590             pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
591             pblock_nninsert("Content-Length",strlen(res),rq->srvhdrs);
592             protocol_status(sn,rq,PROTOCOL_OK,NULL);
593             NET_WRITE(const_cast<char*>(res));
594             return REQ_EXIT;
595         }
596     }
597     log_error(LOG_FAILURE,"WriteRedirectPage",sn,rq,"Unable to open redirect template, check settings.");
598     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,"Unable to open redirect template, check settings.");
599     return REQ_ABORTED;
600 }
601
602 #undef FUNC
603 #define FUNC "shibboleth"
604 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
605 {
606     try
607     {
608         ostringstream threadid;
609         threadid << "[" << getpid() << "] nsapi_shib" << '\0';
610         saml::NDC ndc(threadid.str().c_str());
611         
612         // We lock the configuration system for the duration.
613         IConfig* conf=g_Config->getINI();
614         Locker locker(conf);
615         
616         // Map request to application and content settings.
617         string targeturl;
618         IRequestMapper* mapper=conf->getRequestMapper();
619         Locker locker2(mapper);
620         IRequestMapper::Settings settings=map_request(pb,sn,rq,mapper,targeturl);
621         pair<bool,const char*> application_id=settings.first->getString("applicationId");
622         const IApplication* application=conf->getApplication(application_id.second);
623         if (!application)
624             return WriteClientError(sn,rq,FUNC,"Unable to map request to application settings, check configuration.");
625         
626         // Declare SHIRE object for this request.
627         SHIRE shire(application);
628         
629         const char* shireURL=shire.getShireURL(targeturl.c_str());
630         if (!shireURL)
631             return WriteClientError(sn,rq,FUNC,"Unable to map request to proper shireURL setting, check configuration.");
632
633         // If the user is accessing the SHIRE acceptance point, pass it on.
634         if (targeturl.find(shireURL)!=string::npos)
635             return REQ_PROCEED;
636
637         // Now check the policy for this request.
638         pair<bool,bool> requireSession=settings.first->getBool("requireSession");
639         if (!requireSession.first || !requireSession.second) {
640             const char* param=pblock_findval("require-session",pb);
641             if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
642                 requireSession.second=true;
643         }
644         pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();
645         pair<bool,bool> httpRedirects=application->getPropertySet("Sessions")->getBool("httpRedirects");
646         pair<bool,const char*> redirectPage=application->getPropertySet("Sessions")->getString("redirectPage");
647         if (httpRedirects.first && !httpRedirects.second && !redirectPage.first)
648             return WriteClientError(sn,rq,FUNC,"HTML-based redirection requires a redirectPage property.");
649
650         // Check for session cookie.
651         const char* session_id=NULL;
652         string cookie;
653         if (request_header("cookie",(char**)&session_id,sn,rq)==REQ_ABORTED)
654             return WriteClientError(sn,rq,FUNC,"error accessing cookie header");
655
656         Category::getInstance("nsapi_shib."FUNC).debug("cookie header is {%s}",session_id ? session_id : "NULL");
657         if (session_id && (session_id=strstr(session_id,shib_cookie.first))) {
658             session_id+=strlen(shib_cookie.first) + 1;   /* Skip over the '=' */
659             char* cookieend=strchr(session_id,';');
660             if (cookieend) {
661                 // Chop out just the value portion.
662                 cookie.assign(session_id,cookieend-session_id-1);
663                 session_id=cookie.c_str();
664             }
665         }
666         
667         if (!session_id || !*session_id) {
668             // If no session required, bail now.
669             if (!requireSession.second)
670                 return REQ_PROCEED;
671     
672             // No acceptable cookie, and we require a session.  Generate an AuthnRequest.
673             const char* areq = shire.getAuthnRequest(targeturl.c_str());
674             if (!httpRedirects.first || httpRedirects.second) {
675                 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
676                 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
677                 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
678                 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
679                 pblock_nvinsert("Location",areq,rq->srvhdrs);
680                 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
681                 protocol_start_response(sn,rq);
682                 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
683                 return REQ_EXIT;
684             }
685             else {
686                 ShibMLP markupProcessor;
687                 markupProcessor.insert("requestURL",areq);
688                 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
689             }
690         }
691
692         // Make sure this session is still valid.
693         RPCError* status = NULL;
694         ShibMLP markupProcessor;
695         markupProcessor.insert("requestURL", targeturl);
696     
697         try {
698             status = shire.sessionIsValid(session_id, pblock_findval("ip",sn->client));
699         }
700         catch (ShibTargetException &e) {
701             markupProcessor.insert("errorType", "Session Processing Error");
702             markupProcessor.insert("errorText", e.what());
703             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
704             return WriteClientError(sn, rq, application, "shire", markupProcessor);
705         }
706 #ifndef _DEBUG
707         catch (...) {
708             markupProcessor.insert("errorType", "Session Processing Error");
709             markupProcessor.insert("errorText", "Unexpected Exception");
710             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
711             return WriteClientError(sn, rq, application, "shire", markupProcessor);
712         }
713 #endif
714
715         // Check the status
716         if (status->isError()) {
717             if (!requireSession.second)
718                 return REQ_PROCEED;
719             else if (status->isRetryable()) {
720                 // Oops, session is invalid. Generate AuthnRequest.
721                 delete status;
722                 const char* areq = shire.getAuthnRequest(targeturl.c_str());
723                 if (!httpRedirects.first || httpRedirects.second) {
724                     pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
725                     pblock_nvinsert("Content-Length","40",rq->srvhdrs);
726                     pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
727                     pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
728                     pblock_nvinsert("Location",areq,rq->srvhdrs);
729                     protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
730                     protocol_start_response(sn,rq);
731                     NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
732                     return REQ_EXIT;
733                 }
734                 else {
735                     markupProcessor.insert("requestURL",areq);
736                     return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
737                 }
738             }
739             else {
740                 // return the error page to the user
741                 markupProcessor.insert(*status);
742                 delete status;
743                 return WriteClientError(sn, rq, application, "shire", markupProcessor);
744             }
745         }
746         delete status;
747     
748         // Move to RM phase.
749         RM rm(application);
750         vector<SAMLAssertion*> assertions;
751         SAMLAuthenticationStatement* sso_statement=NULL;
752
753         try {
754             status = rm.getAssertions(session_id, pblock_findval("ip",sn->client), assertions, &sso_statement);
755         }
756         catch (ShibTargetException &e) {
757             markupProcessor.insert("errorType", "Attribute Processing Error");
758             markupProcessor.insert("errorText", e.what());
759             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
760             return WriteClientError(sn, rq, application, "rm", markupProcessor);
761         }
762     #ifndef _DEBUG
763         catch (...) {
764             markupProcessor.insert("errorType", "Attribute Processing Error");
765             markupProcessor.insert("errorText", "Unexpected Exception");
766             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
767             return WriteClientError(sn, rq, application, "rm", markupProcessor);
768         }
769     #endif
770     
771         if (status->isError()) {
772             markupProcessor.insert(*status);
773             delete status;
774             return WriteClientError(sn, rq, application, "rm", markupProcessor);
775         }
776         delete status;
777
778         // Do we have an access control plugin?
779         if (settings.second) {
780             Locker acllock(settings.second);
781             if (!settings.second->authorized(*sso_statement,assertions)) {
782                 for (int k = 0; k < assertions.size(); k++)
783                     delete assertions[k];
784                 delete sso_statement;
785                 return WriteClientError(sn, rq, application, "access", markupProcessor);
786             }
787         }
788
789         // Get the AAP providers, which contain the attribute policy info.
790         Iterator<IAAP*> provs=application->getAAPProviders();
791     
792         // Clear out the list of mapped attributes
793         while (provs.hasNext()) {
794             IAAP* aap=provs.next();
795             aap->lock();
796             try {
797                 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
798                 while (rules.hasNext()) {
799                     const char* header=rules.next()->getHeader();
800                     if (header)
801                         param_free(pblock_remove(header,rq->headers));
802                 }
803             }
804             catch(...) {
805                 aap->unlock();
806                 for (int k = 0; k < assertions.size(); k++)
807                   delete assertions[k];
808                 delete sso_statement;
809                 markupProcessor.insert("errorType", "Attribute Processing Error");
810                 markupProcessor.insert("errorText", "Unexpected Exception");
811                 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
812                 return WriteClientError(sn, rq, application, "rm", markupProcessor);
813             }
814             aap->unlock();
815         }
816         provs.reset();
817
818         // Maybe export the first assertion.
819         param_free(pblock_remove("remote-user",rq->headers));
820         param_free(pblock_remove("auth-user",rq->vars));
821         param_free(pblock_remove("Shib-Attributes",rq->headers));
822         pair<bool,bool> exp=settings.first->getBool("exportAssertion");
823         if (!exp.first || !exp.second) {
824             const char* param=pblock_findval("export-assertion",pb);
825             if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
826                 exp.second=true;
827         }
828         if (exp.second && assertions.size()) {
829             string assertion;
830             RM::serialize(*(assertions[0]), assertion);
831             string::size_type lfeed;
832             while ((lfeed=assertion.find('\n'))!=string::npos)
833                 assertion.erase(lfeed,1);
834             pblock_nvinsert("Shib-Attributes",assertion.c_str(),rq->headers);
835         }
836         
837         pblock_nvinsert("auth-type","shibboleth",rq->vars);
838         param_free(pblock_remove("Shib-Origin-Site",rq->headers));
839         param_free(pblock_remove("Shib-Authentication-Method",rq->headers));
840         param_free(pblock_remove("Shib-NameIdentifier-Format",rq->headers));
841
842         // Export the SAML AuthnMethod and the origin site name.
843         auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
844         auto_ptr_char am(sso_statement->getAuthMethod());
845         pblock_nvinsert("Shib-Origin-Site",os.get(),rq->headers);
846         pblock_nvinsert("Shib-Authentication-Method",am.get(),rq->headers);
847
848         // Export NameID?
849         AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
850         if (!wrapper.fail() && wrapper->getHeader()) {
851             auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
852             auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
853             pblock_nvinsert("Shib-NameIdentifier-Format",form.get(),pb);
854             if (!strcmp(wrapper->getHeader(),"REMOTE_USER")) {
855                 pblock_nvinsert("remote-user",nameid.get(),rq->headers);
856                 pblock_nvinsert("auth-user",nameid.get(),rq->vars);
857             }
858             else {
859                 pblock_nvinsert(wrapper->getHeader(),nameid.get(),rq->headers);
860             }
861         }
862
863         param_free(pblock_remove("Shib-Application-ID",rq->headers));
864         pblock_nvinsert("Shib-Application-ID",application_id.second,rq->headers);
865
866         // Export the attributes.
867         Iterator<SAMLAssertion*> a_iter(assertions);
868         while (a_iter.hasNext()) {
869             SAMLAssertion* assert=a_iter.next();
870             Iterator<SAMLStatement*> statements=assert->getStatements();
871             while (statements.hasNext()) {
872                 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
873                 if (!astate)
874                     continue;
875                 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
876                 while (attrs.hasNext()) {
877                     SAMLAttribute* attr=attrs.next();
878         
879                     // Are we supposed to export it?
880                     AAP wrapper(provs,attr->getName(),attr->getNamespace());
881                     if (wrapper.fail() || !wrapper->getHeader())
882                         continue;
883                 
884                     Iterator<string> vals=attr->getSingleByteValues();
885                     if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext()) {
886                         char* principal=const_cast<char*>(vals.next().c_str());
887                         pblock_nvinsert("remote-user",principal,rq->headers);
888                         pblock_nvinsert("auth-user",principal,rq->vars);
889                     }
890                     else {
891                         int it=0;
892                         string header;
893                         const char* h=pblock_findval(wrapper->getHeader(),rq->headers);
894                         if (h) {
895                             header=h;
896                             param_free(pblock_remove(wrapper->getHeader(),rq->headers));
897                             it++;
898                         }
899                         for (; vals.hasNext(); it++) {
900                             string value = vals.next();
901                             for (string::size_type pos = value.find_first_of(";", string::size_type(0));
902                                     pos != string::npos;
903                                     pos = value.find_first_of(";", pos)) {
904                                 value.insert(pos, "\\");
905                                 pos += 2;
906                             }
907                             if (it == 0)
908                                 header=value;
909                             else
910                                 header=header + ';' + value;
911                         }
912                         pblock_nvinsert(wrapper->getHeader(),header.c_str(),rq->headers);
913                         }
914                 }
915             }
916         }
917     
918         // clean up memory
919         for (int k = 0; k < assertions.size(); k++)
920           delete assertions[k];
921         delete sso_statement;
922
923         return REQ_PROCEED;
924     }
925     catch(bad_alloc) {
926         return WriteClientError(sn, rq, FUNC,"Out of Memory");
927     }
928 #ifndef _DEBUG
929     catch(...) {
930         return WriteClientError(sn, rq, FUNC,"Server caught an unknown exception.");
931     }
932 #endif
933
934     return WriteClientError(sn, rq, FUNC,"Server reached unreachable code, save my walrus!");
935 }
936
937 #undef FUNC
938 #define FUNC "shib_handler"
939 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
940 {
941     string targeturl;
942     const IApplication* application=NULL;
943     try
944     {
945         ostringstream threadid;
946         threadid << "[" << getpid() << "] shib_handler" << '\0';
947         saml::NDC ndc(threadid.str().c_str());
948
949         // We lock the configuration system for the duration.
950         IConfig* conf=g_Config->getINI();
951         Locker locker(conf);
952         
953         // Map request to application and content settings.
954         IRequestMapper* mapper=conf->getRequestMapper();
955         Locker locker2(mapper);
956         IRequestMapper::Settings settings=map_request(pb,sn,rq,mapper,targeturl);
957         pair<bool,const char*> application_id=settings.first->getString("applicationId");
958         application=conf->getApplication(application_id.second);
959         const IPropertySet* sessionProps=application ? application->getPropertySet("Sessions") : NULL;
960         if (!application || !sessionProps)
961             return WriteClientError(sn,rq,FUNC,"Unable to map request to application settings, check configuration.");
962
963         SHIRE shire(application);
964         
965         const char* shireURL=shire.getShireURL(targeturl.c_str());
966         if (!shireURL)
967             return WriteClientError(sn,rq,FUNC,"Unable to map request to proper shireURL setting, check configuration.");
968
969         // Make sure we only process the SHIRE requests.
970         if (!strstr(targeturl.c_str(),shireURL))
971             return WriteClientError(sn,rq,FUNC,"NSAPI service function can only be invoked to process incoming sessions."
972                 "Make sure the mapped file extension or URL doesn't match actual content.");
973
974         pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();
975
976         // Make sure this is SSL, if it should be
977         pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
978         if (!shireSSL.first || shireSSL.second) {
979             if (!security_active)
980                 throw ShibTargetException(SHIBRPC_OK,"blocked non-SSL access to Shibboleth session processor");
981         }
982         
983         pair<bool,bool> httpRedirects=sessionProps->getBool("httpRedirects");
984         pair<bool,const char*> redirectPage=sessionProps->getString("redirectPage");
985         if (httpRedirects.first && !httpRedirects.second && !redirectPage.first)
986             return WriteClientError(sn,rq,FUNC,"HTML-based redirection requires a redirectPage property.");
987                 
988         // If this is a GET, we manufacture an AuthnRequest.
989         if (!strcasecmp(pblock_findval("method",rq->reqpb),"GET")) {
990             const char* areq=pblock_findval("query",rq->reqpb) ? shire.getLazyAuthnRequest(pblock_findval("query",rq->reqpb)) : NULL;
991             if (!areq)
992                 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
993             if (!httpRedirects.first || httpRedirects.second) {
994                 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
995                 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
996                 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
997                 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
998                 pblock_nvinsert("Location",areq,rq->srvhdrs);
999                 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1000                 protocol_start_response(sn,rq);
1001                 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1002                 return REQ_EXIT;
1003             }
1004             else {
1005                 ShibMLP markupProcessor;
1006                 markupProcessor.insert("requestURL",areq);
1007                 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1008             }
1009         }
1010         else if (strcasecmp(pblock_findval("method",rq->reqpb),"POST"))
1011             throw ShibTargetException(SHIBRPC_OK,"blocked non-POST to Shibboleth session processor");
1012
1013         // Make sure this POST is an appropriate content type
1014         char* content_type=NULL;
1015         if (request_header("content-type",&content_type,sn,rq)!=REQ_PROCEED ||
1016                 !content_type || strcasecmp(content_type,"application/x-www-form-urlencoded"))
1017             throw ShibTargetException(SHIBRPC_OK,"blocked bad content-type to Shibboleth session processor");
1018     
1019         // Read the data.
1020         pair<const char*,const char*> elements=pair<const char*,const char*>(NULL,NULL);
1021         char* content_length=NULL;
1022         if (request_header("content-length",&content_length,sn,rq)!=REQ_PROCEED ||
1023                 atoi(content_length) > 1024*1024) // 1MB?
1024             throw ShibTargetException(SHIBRPC_OK,"blocked too-large a post to Shibboleth session processor");
1025         else {
1026             char ch=IO_EOF+1;
1027             int cl=atoi(content_length);
1028             string cgistr;
1029             while (cl && ch!=IO_EOF) {
1030                 ch=netbuf_getc(sn->inbuf);
1031         
1032                 // Check for error.
1033                 if(ch==IO_ERROR)
1034                     break;
1035                 cgistr+=ch;
1036                 cl--;
1037             }
1038             if (cl)
1039                 throw ShibTargetException(SHIBRPC_OK,"error reading POST data from browser");
1040             elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
1041         }
1042     
1043         // Make sure the SAML Response parameter exists
1044         if (!elements.first || !*elements.first)
1045             throw ShibTargetException(SHIBRPC_OK, "Shibboleth POST failed to find SAMLResponse form element");
1046     
1047         // Make sure the target parameter exists
1048         if (!elements.second || !*elements.second)
1049             throw ShibTargetException(SHIBRPC_OK, "Shibboleth POST failed to find TARGET form element");
1050             
1051         // Process the post.
1052         string cookie;
1053         RPCError* status=NULL;
1054         ShibMLP markupProcessor;
1055         markupProcessor.insert("requestURL", targeturl.c_str());
1056         try {
1057             status = shire.sessionCreate(elements.first,pblock_findval("ip",sn->client),cookie);
1058         }
1059         catch (ShibTargetException &e) {
1060             markupProcessor.insert("errorType", "Session Creation Service Error");
1061             markupProcessor.insert("errorText", e.what());
1062             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1063             return WriteClientError(sn, rq, application, "shire", markupProcessor);
1064         }
1065 #ifndef _DEBUG
1066         catch (...) {
1067             markupProcessor.insert("errorType", "Session Creation Service Error");
1068             markupProcessor.insert("errorText", "Unexpected Exception");
1069             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1070             return WriteClientError(sn, rq, application, "shire", markupProcessor);
1071         }
1072 #endif
1073
1074         if (status->isError()) {
1075             if (status->isRetryable()) {
1076                 delete status;
1077                 const char* loc=shire.getAuthnRequest(elements.second);
1078                 if (!httpRedirects.first || httpRedirects.second) {
1079                     pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
1080                     pblock_nvinsert("Content-Length","40",rq->srvhdrs);
1081                     pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
1082                     pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
1083                     pblock_nvinsert("Location",loc,rq->srvhdrs);
1084                     protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1085                     protocol_start_response(sn,rq);
1086                     NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1087                     return REQ_EXIT;
1088                 }
1089                 else {
1090                     markupProcessor.insert("requestURL",loc);
1091                     return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1092                 }
1093             }
1094     
1095             // Return this error to the user.
1096             markupProcessor.insert(*status);
1097             delete status;
1098             return WriteClientError(sn,rq,application,"shire",markupProcessor);
1099         }
1100         delete status;
1101     
1102         // We've got a good session, set the cookie and redirect to target.
1103         cookie = string(shib_cookie.first) + '=' + cookie + shib_cookie.second;
1104         pblock_nvinsert("Set-Cookie",cookie.c_str(),rq->srvhdrs);
1105         if (!httpRedirects.first || httpRedirects.second) {
1106             pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
1107             pblock_nvinsert("Content-Length","40",rq->srvhdrs);
1108             pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
1109             pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
1110             pblock_nvinsert("Location",elements.second,rq->srvhdrs);
1111             protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1112             protocol_start_response(sn,rq);
1113             NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1114             return REQ_EXIT;
1115         }
1116         else {
1117             markupProcessor.insert("requestURL",elements.second);
1118             return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1119         }
1120     }
1121     catch (ShibTargetException &e) {
1122         if (application) {
1123             ShibMLP markupProcessor;
1124             markupProcessor.insert("requestURL", targeturl.c_str());
1125             markupProcessor.insert("errorType", "Session Creation Service Error");
1126             markupProcessor.insert("errorText", e.what());
1127             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1128             return WriteClientError(sn,rq,application,"shire",markupProcessor);
1129         }
1130     }
1131 #ifndef _DEBUG
1132     catch (...) {
1133         if (application) {
1134             ShibMLP markupProcessor;
1135             markupProcessor.insert("requestURL", targeturl.c_str());
1136             markupProcessor.insert("errorType", "Session Creation Service Error");
1137             markupProcessor.insert("errorText", "Unexpected Exception");
1138             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1139             return WriteClientError(sn,rq,application,"shire",markupProcessor);
1140         }
1141     }
1142 #endif    
1143     return REQ_EXIT;
1144 }
1145
1146 #endif