Add hooks for protecting headers and redirects.
[shibboleth/cpp-sp.git] / isapi_shib / isapi_shib.cpp
index b1c1fad..0c6baf5 100644 (file)
@@ -1,6 +1,6 @@
 /*
- *  Copyright 2001-2005 Internet2
- * 
+ *  Copyright 2001-2009 Internet2
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
 
 /**
  * isapi_shib.cpp
- * 
+ *
  * Shibboleth ISAPI filter
  */
 
+#define SHIBSP_LITE
 #include "config_win32.h"
 
 #define _CRT_NONSTDC_NO_DEPRECATE 1
 #define _CRT_SECURE_NO_DEPRECATE 1
+#define _CRT_RAND_S
 
+#include <shibsp/exceptions.h>
 #include <shibsp/AbstractSPRequest.h>
 #include <shibsp/SPConfig.h>
-#include <xmltooling/util/NDC.h>
-
-// SAML Runtime
-#include <saml/saml.h>
-#include <shib/shib.h>
-#include <shib-target/shib-target.h>
+#include <shibsp/ServiceProvider.h>
 
+#include <set>
 #include <sstream>
 #include <fstream>
+#include <stdexcept>
 #include <process.h>
+#include <xmltooling/unicode.h>
+#include <xmltooling/XMLToolingConfig.h>
+#include <xmltooling/util/NDC.h>
+#include <xmltooling/util/XMLConstants.h>
+#include <xmltooling/util/XMLHelper.h>
+#include <xercesc/util/Base64.hpp>
+#include <xercesc/util/XMLUniDefs.hpp>
 
+#include <windows.h>
 #include <httpfilt.h>
 #include <httpext.h>
 
 using namespace shibsp;
 using namespace xmltooling;
+using namespace xercesc;
 using namespace std;
 
 // globals
 namespace {
+    static const XMLCh path[] =             UNICODE_LITERAL_4(p,a,t,h);
+    static const XMLCh validate[] =         UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
     static const XMLCh name[] =             UNICODE_LITERAL_4(n,a,m,e);
     static const XMLCh port[] =             UNICODE_LITERAL_4(p,o,r,t);
     static const XMLCh sslport[] =          UNICODE_LITERAL_7(s,s,l,p,o,r,t);
     static const XMLCh scheme[] =           UNICODE_LITERAL_6(s,c,h,e,m,e);
     static const XMLCh id[] =               UNICODE_LITERAL_2(i,d);
-    static const XMLCh Implementation[] =   UNICODE_LITERAL_14(I,m,p,l,e,m,e,n,t,a,t,i,o,n);
-    static const XMLCh ISAPI[] =            UNICODE_LITERAL_5(I,S,A,P,I);
     static const XMLCh Alias[] =            UNICODE_LITERAL_5(A,l,i,a,s);
-    static const XMLCh normalizeRequest[] = UNICODE_LITERAL_16(n,o,r,m,a,l,i,z,e,R,e,q,u,e,s,t);
     static const XMLCh Site[] =             UNICODE_LITERAL_4(S,i,t,e);
 
     struct site_t {
@@ -81,11 +89,16 @@ namespace {
         string m_scheme,m_port,m_sslport,m_name;
         set<string> m_aliases;
     };
-    
+
     HINSTANCE g_hinstDLL;
-    shibtarget::ShibTargetConfig* g_Config = NULL;
+    SPConfig* g_Config = NULL;
     map<string,site_t> g_Sites;
     bool g_bNormalizeRequest = true;
+    string g_unsetHeaderValue,g_spoofKey;
+    bool g_checkSpoofing = true;
+    bool g_catchAll = false;
+    bool g_bSafeHeaderNames = false;
+    vector<string> g_NoCerts;
 }
 
 BOOL LogEvent(
@@ -96,12 +109,23 @@ BOOL LogEvent(
     LPCSTR  message)
 {
     LPCSTR  messages[] = {message, NULL};
-    
+
     HANDLE hElog = RegisterEventSource(lpUNCServerName, "Shibboleth ISAPI Filter");
     BOOL res = ReportEvent(hElog, wType, 0, dwEventID, lpUserSid, 1, 0, messages, NULL);
     return (DeregisterEventSource(hElog) && res);
 }
 
+void _my_invalid_parameter_handler(
+   const wchar_t * expression,
+   const wchar_t * function,
+   const wchar_t * file,
+   unsigned int line,
+   uintptr_t pReserved
+   )
+{
+    return;
+}
+
 extern "C" __declspec(dllexport) BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID)
 {
     if (fdwReason==DLL_PROCESS_ATTACH)
@@ -113,7 +137,7 @@ extern "C" BOOL WINAPI GetExtensionVersion(HSE_VERSION_INFO* pVer)
 {
     if (!pVer)
         return FALSE;
-        
+
     if (!g_Config) {
         LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
                 "Extension mode startup not possible, is the DLL loaded as a filter?");
@@ -140,65 +164,88 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
         return TRUE;
     }
 
-#ifndef _DEBUG
-    try
-    {
-#endif
-        LPCSTR schemadir=getenv("SHIBSCHEMAS");
-        if (!schemadir)
-            schemadir=SHIB_SCHEMAS;
-        LPCSTR config=getenv("SHIBCONFIG");
-        if (!config)
-            config=SHIB_CONFIG;
-        g_Config=&shibtarget::ShibTargetConfig::getConfig();
-        SPConfig::getConfig().setFeatures(
-            SPConfig::Listener |
-            SPConfig::Caching |
-            SPConfig::Metadata |
-            SPConfig::AAP |
-            SPConfig::RequestMapping |
-            SPConfig::InProcess |
-            SPConfig::Logging
-            );
-        if (!g_Config->init(schemadir)) {
-            g_Config=NULL;
-            LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
-                    "Filter startup failed during library initialization, check native log for help.");
-            return FALSE;
-        }
-        else if (!g_Config->load(config)) {
-            g_Config=NULL;
-            LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
-                    "Filter startup failed to load configuration, check native log for help.");
-            return FALSE;
+    g_Config=&SPConfig::getConfig();
+    g_Config->setFeatures(
+        SPConfig::Listener |
+        SPConfig::Caching |
+        SPConfig::RequestMapping |
+        SPConfig::InProcess |
+        SPConfig::Logging |
+        SPConfig::Handlers
+        );
+    if (!g_Config->init()) {
+        g_Config=NULL;
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+                "Filter startup failed during library initialization, check native log for help.");
+        return FALSE;
+    }
+
+    try {
+        if (!g_Config->instantiate(NULL, true))
+            throw runtime_error("unknown error");
+    }
+    catch (exception& ex) {
+        g_Config->term();
+        g_Config=NULL;
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, ex.what());
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+                "Filter startup failed to load configuration, check native log for details.");
+        return FALSE;
+    }
+
+    // Access implementation-specifics and site mappings.
+    ServiceProvider* sp=g_Config->getServiceProvider();
+    Locker locker(sp);
+    const PropertySet* props=sp->getPropertySet("InProcess");
+    if (props) {
+        pair<bool,bool> flag=props->getBool("checkSpoofing");
+        g_checkSpoofing = !flag.first || flag.second;
+        flag=props->getBool("catchAll");
+        g_catchAll = flag.first && flag.second;
+
+        pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
+        if (unsetValue.first)
+            g_unsetHeaderValue = unsetValue.second;
+        if (g_checkSpoofing) {
+            unsetValue = props->getString("spoofKey");
+            if (unsetValue.first)
+                g_spoofKey = unsetValue.second;
+            else {
+                _invalid_parameter_handler old = _set_invalid_parameter_handler(_my_invalid_parameter_handler);
+                unsigned int randkey=0,randkey2=0,randkey3=0,randkey4=0;
+                if (rand_s(&randkey) == 0 && rand_s(&randkey2) == 0 && rand_s(&randkey3) == 0 && rand_s(&randkey4) == 0) {
+                    _set_invalid_parameter_handler(old);
+                    ostringstream keystr;
+                    keystr << randkey << randkey2 << randkey3 << randkey4;
+                    g_spoofKey = keystr.str();
+                }
+                else {
+                    _set_invalid_parameter_handler(old);
+                    LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+                            "Filter failed to generate a random anti-spoofing key (if this is Windows 2000 set one manually).");
+                    locker.assign();    // pops lock on SP config
+                    g_Config->term();
+                    g_Config=NULL;
+                    return FALSE;
+                }
+            }
         }
-        
-        // Access the implementation-specifics for site mappings.
-        ServiceProvider* conf=SPConfig::getConfig().getServiceProvider();
-        xmltooling::Locker locker(conf);
-        const PropertySet* props=conf->getPropertySet("Local");
+
+        props = props->getPropertySet("ISAPI");
         if (props) {
-            const DOMElement* impl=XMLHelper::getFirstChildElement(props->getElement(),Implementation);
-            if (impl && (impl=XMLHelper::getFirstChildElement(impl,ISAPI))) {
-                const XMLCh* flag=impl->getAttributeNS(NULL,normalizeRequest);
-                g_bNormalizeRequest=(!flag || !*flag || *flag==chDigit_1 || *flag==chLatin_t);
-                impl=XMLHelper::getFirstChildElement(impl,Site);
-                while (impl) {
-                    auto_ptr_char id(impl->getAttributeNS(NULL,id));
-                    if (id.get())
-                        g_Sites.insert(pair<string,site_t>(id.get(),site_t(impl)));
-                    impl=XMLHelper::getNextSiblingElement(impl,Site);
-                }
+            flag = props->getBool("normalizeRequest");
+            g_bNormalizeRequest = !flag.first || flag.second;
+            flag = props->getBool("safeHeaderNames");
+            g_bSafeHeaderNames = flag.first && flag.second;
+            const DOMElement* child = XMLHelper::getFirstChildElement(props->getElement(),Site);
+            while (child) {
+                auto_ptr_char id(child->getAttributeNS(NULL,id));
+                if (id.get())
+                    g_Sites.insert(pair<string,site_t>(id.get(),site_t(child)));
+                child=XMLHelper::getNextSiblingElement(child,Site);
             }
         }
-#ifndef _DEBUG
     }
-    catch (...)
-    {
-        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Filter startup failed with an exception.");
-        return FALSE;
-    }
-#endif
 
     pVer->dwFilterVersion=HTTP_FILTER_REVISION;
     strncpy(pVer->lpszFilterDesc,"Shibboleth ISAPI Filter",SF_MAX_FILTER_DESC_LEN);
@@ -214,7 +261,7 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
 extern "C" BOOL WINAPI TerminateFilter(DWORD)
 {
     if (g_Config)
-        g_Config->shutdown();
+        g_Config->term();
     g_Config = NULL;
     LogEvent(NULL, EVENTLOG_INFORMATION_TYPE, 7701, NULL, "Filter shut down...");
     return TRUE;
@@ -332,22 +379,21 @@ class ShibTargetIsapiF : public AbstractSPRequest
 {
   PHTTP_FILTER_CONTEXT m_pfc;
   PHTTP_FILTER_PREPROC_HEADERS m_pn;
-  map<string,string> m_headers;
-  vector<XSECCryptoX509*> m_certs;
+  multimap<string,string> m_headers;
   int m_port;
-  string m_scheme,m_hostname,m_uri;
+  string m_scheme,m_hostname;
   mutable string m_remote_addr,m_content_type,m_method;
+  dynabuf m_allhttp;
+  bool m_firsttime;
 
 public:
-  ShibTargetIsapiF(PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn, const site_t& site) {
-
-    m_pfc = pfc;
-    m_pn = pn;
+  ShibTargetIsapiF(PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn, const site_t& site)
+      : AbstractSPRequest(SHIBSP_LOGCAT".ISAPI"), m_pfc(pfc), m_pn(pn), m_allhttp(4096), m_firsttime(true) {
 
     // URL path always come from IIS.
     dynabuf var(256);
     GetHeader(pn,pfc,"url",var,256,false);
-    m_uri = var;
+    setRequestURI(var);
 
     // Port may come from IIS or from site def.
     if (!g_bNormalizeRequest || (pfc->fIsSecurePort && site.m_sslport.empty()) || (!pfc->fIsSecurePort && site.m_port.empty())) {
@@ -360,7 +406,7 @@ public:
     else {
         m_port = atoi(site.m_port.c_str());
     }
-    
+
     // Scheme may come from site def or be derived from IIS.
     m_scheme=site.m_scheme;
     if (m_scheme.empty() || !g_bNormalizeRequest)
@@ -372,6 +418,15 @@ public:
     m_hostname = var;
     if (site.m_name!=m_hostname && site.m_aliases.find(m_hostname)==site.m_aliases.end())
         m_hostname=site.m_name;
+
+    if (!g_spoofKey.empty()) {
+        GetHeader(pn, pfc, "ShibSpoofCheck:", var, 32, false);
+        if (!var.empty() && g_spoofKey == (char*)var)
+            m_firsttime = false;
+    }
+
+    if (!m_firsttime)
+        log(SPDebug, "ISAPI filter running more than once");
   }
   ~ShibTargetIsapiF() { }
 
@@ -384,13 +439,15 @@ public:
   int getPort() const {
     return m_port;
   }
-  const char* getRequestURI() const {
-    return m_uri.c_str();
+  const char* getQueryString() const {
+      const char* uri = getRequestURI();
+      uri = (uri ? strchr(uri, '?') : NULL);
+      return uri ? (uri + 1) : NULL;
   }
   const char* getMethod() const {
     if (m_method.empty()) {
         dynabuf var(5);
-        GetServerVariable(m_pfc,"REQUEST_METHOD",var,5,false);
+        GetServerVariable(m_pfc,"HTTP_METHOD",var,5,false);
         if (!var.empty())
             m_method = var;
     }
@@ -399,16 +456,14 @@ public:
   string getContentType() const {
     if (m_content_type.empty()) {
         dynabuf var(32);
-        GetServerVariable(m_pfc,"CONTENT_TYPE",var,32,false);
+        GetServerVariable(m_pfc,"HTTP_CONTENT_TYPE",var,32,false);
         if (!var.empty())
             m_content_type = var;
     }
     return m_content_type;
   }
-  long getContentLength() const {
-      return 0;
-  }
   string getRemoteAddr() const {
+    m_remote_addr = AbstractSPRequest::getRemoteAddr();
     if (m_remote_addr.empty()) {
         dynabuf var(16);
         GetServerVariable(m_pfc,"REMOTE_ADDR",var,16,false);
@@ -419,49 +474,84 @@ public:
   }
   void log(SPLogLevel level, const string& msg) {
     AbstractSPRequest::log(level,msg);
-    if (level >= SPError)
+    if (level >= SPCrit)
         LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg.c_str());
   }
-  void clearHeader(const char* name) {
-    string hdr(!strcmp(name,"REMOTE_USER") ? "remote-user" : name);
-    hdr += ':';
-    m_pn->SetHeader(m_pfc, const_cast<char*>(hdr.c_str()), "");
+  string makeSafeHeader(const char* rawname) const {
+      string hdr;
+      for (; *rawname; ++rawname) {
+          if (isalnum(*rawname))
+              hdr += *rawname;
+      }
+      return (hdr + ':');
+  }
+  void clearHeader(const char* rawname, const char* cginame) {
+    if (g_checkSpoofing && m_firsttime) {
+        if (m_allhttp.empty())
+               GetServerVariable(m_pfc, "ALL_HTTP", m_allhttp, 4096);
+        string hdr = g_bSafeHeaderNames ? ("HTTP_" + makeSafeHeader(cginame + 5)) : (string(cginame) + ':');
+        if (strstr(m_allhttp, hdr.c_str()))
+            throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, hdr.c_str()));
+    }
+    if (g_bSafeHeaderNames) {
+        string hdr = makeSafeHeader(rawname);
+        m_pn->SetHeader(m_pfc, const_cast<char*>(hdr.c_str()), const_cast<char*>(g_unsetHeaderValue.c_str()));
+    }
+    else if (!strcmp(rawname,"REMOTE_USER")) {
+           m_pn->SetHeader(m_pfc, "remote-user:", const_cast<char*>(g_unsetHeaderValue.c_str()));
+        m_pn->SetHeader(m_pfc, "remote_user:", const_cast<char*>(g_unsetHeaderValue.c_str()));
+       }
+       else {
+           string hdr = string(rawname) + ':';
+           m_pn->SetHeader(m_pfc, const_cast<char*>(hdr.c_str()), const_cast<char*>(g_unsetHeaderValue.c_str()));
+       }
   }
   void setHeader(const char* name, const char* value) {
-    string hdr(name);
-    hdr += ':';
+    string hdr = g_bSafeHeaderNames ? makeSafeHeader(name) : (string(name) + ':');
     m_pn->SetHeader(m_pfc, const_cast<char*>(hdr.c_str()), const_cast<char*>(value));
   }
+  string getSecureHeader(const char* name) const {
+    string hdr = g_bSafeHeaderNames ? makeSafeHeader(name) : (string(name) + ':');
+    dynabuf buf(256);
+    GetHeader(m_pn, m_pfc, const_cast<char*>(hdr.c_str()), buf, 256, false);
+    return string(buf.empty() ? "" : buf);
+  }
   string getHeader(const char* name) const {
     string hdr(name);
     hdr += ':';
-    dynabuf buf(1024);
-    GetHeader(m_pn, m_pfc, const_cast<char*>(hdr.c_str()), buf, 1024, false);
-    return string(buf);
+    dynabuf buf(256);
+    GetHeader(m_pn, m_pfc, const_cast<char*>(hdr.c_str()), buf, 256, false);
+    return string(buf.empty() ? "" : buf);
   }
   void setRemoteUser(const char* user) {
     setHeader("remote-user", user);
+    if (!user || !*user)
+        m_pfc->pFilterContext = NULL;
+    else if (m_pfc->pFilterContext = m_pfc->AllocMem(m_pfc, sizeof(char) * (strlen(user) + 1), NULL))
+        strcpy(reinterpret_cast<char*>(m_pfc->pFilterContext), user);
   }
   string getRemoteUser() const {
-    return getHeader("remote-user");
+    return getSecureHeader("remote-user");
   }
   void setResponseHeader(const char* name, const char* value) {
+    AbstractSPRequest::setResponseHeader(name, value);
     // Set for later.
     if (value)
-        m_headers[name] = value;
+        m_headers.insert(make_pair(name,value));
     else
         m_headers.erase(name);
   }
   long sendResponse(istream& in, long status) {
     string hdr = string("Connection: close\r\n");
-    for (map<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
+    for (multimap<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
         hdr += i->first + ": " + i->second + "\r\n";
     hdr += "\r\n";
     const char* codestr="200 OK";
     switch (status) {
-        case SAML_HTTP_STATUS_FORBIDDEN:codestr="403 Forbidden"; break;
-        case SAML_HTTP_STATUS_NOTFOUND: codestr="404 Not Found"; break;
-        case SAML_HTTP_STATUS_ERROR:    codestr="500 Server Error"; break;
+        case XMLTOOLING_HTTP_STATUS_UNAUTHORIZED:   codestr="401 Authorization Required"; break;
+        case XMLTOOLING_HTTP_STATUS_FORBIDDEN:      codestr="403 Forbidden"; break;
+        case XMLTOOLING_HTTP_STATUS_NOTFOUND:       codestr="404 Not Found"; break;
+        case XMLTOOLING_HTTP_STATUS_ERROR:          codestr="500 Server Error"; break;
     }
     m_pfc->ServerSupportFunction(m_pfc, SF_REQ_SEND_RESPONSE_HEADER, (void*)codestr, (DWORD)hdr.c_str(), 0);
     char buf[1024];
@@ -473,13 +563,13 @@ public:
     return SF_STATUS_REQ_FINISHED;
   }
   long sendRedirect(const char* url) {
-    // XXX: Don't support the httpRedirect option, yet.
+    AbstractSPRequest::sendRedirect(url);
     string hdr=string("Location: ") + url + "\r\n"
       "Content-Type: text/html\r\n"
       "Content-Length: 40\r\n"
       "Expires: 01-Jan-1997 12:00:00 GMT\r\n"
       "Cache-Control: private,no-store,no-cache\r\n";
-    for (map<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
+    for (multimap<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
         hdr += i->first + ": " + i->second + "\r\n";
     hdr += "\r\n";
     m_pfc->ServerSupportFunction(m_pfc, SF_REQ_SEND_RESPONSE_HEADER, "302 Please Wait", (DWORD)hdr.c_str(), 0);
@@ -495,13 +585,13 @@ public:
     return SF_STATUS_REQ_NEXT_NOTIFICATION;
   }
 
-  const vector<XSECCryptoX509*>& getClientCertificates() const {
-      return m_certs;
+  const vector<string>& getClientCertificates() const {
+      return g_NoCerts;
   }
-  
+
   // The filter never processes the POST, so stub these methods.
-  const char* getQueryString() const { throw runtime_error("getQueryString not implemented"); }
-  const char* getRequestBody() const { throw runtime_error("getRequestBody not implemented"); }
+  long getContentLength() const { throw IOException("The request's Content-Length is not available to an ISAPI filter."); }
+  const char* getRequestBody() const { throw IOException("The request body is not available to an ISAPI filter."); }
 };
 
 DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const char* msg)
@@ -524,10 +614,9 @@ DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const char* msg)
 extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificationType, LPVOID pvNotification)
 {
     // Is this a log notification?
-    if (notificationType==SF_NOTIFY_LOG)
-    {
+    if (notificationType==SF_NOTIFY_LOG) {
         if (pfc->pFilterContext)
-            ((PHTTP_FILTER_LOG)pvNotification)->pszClientUserName=static_cast<LPCSTR>(pfc->pFilterContext);
+               ((PHTTP_FILTER_LOG)pvNotification)->pszClientUserName=reinterpret_cast<char*>(pfc->pFilterContext);
         return SF_STATUS_REQ_NEXT_NOTIFICATION;
     }
 
@@ -542,7 +631,7 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat
         map<string,site_t>::const_iterator map_i=g_Sites.find(static_cast<char*>(buf));
         if (map_i==g_Sites.end())
             return SF_STATUS_REQ_NEXT_NOTIFICATION;
-            
+
         ostringstream threadid;
         threadid << "[" << getpid() << "] isapi_shib" << '\0';
         xmltooling::NDC ndc(threadid.str().c_str());
@@ -551,6 +640,8 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat
 
         // "false" because we don't override the Shib settings
         pair<bool,long> res = stf.getServiceProvider().doAuthentication(stf);
+        if (!g_spoofKey.empty())
+            pn->SetHeader(pfc, "ShibSpoofCheck:", const_cast<char*>(g_spoofKey.c_str()));
         if (res.first) return res.second;
 
         // "false" because we don't override the Shib settings
@@ -575,15 +666,16 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat
         LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, e.what());
         return WriteClientError(pfc,"Shibboleth Filter caught an exception, check Event Log for details.");
     }
-#ifndef _DEBUG
     catch(...) {
-        return WriteClientError(pfc,"Shibboleth Filter caught an unknown exception.");
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Shibboleth Filter threw an unknown exception.");
+        if (g_catchAll)
+            return WriteClientError(pfc,"Shibboleth Filter threw an unknown exception.");
+        throw;
     }
-#endif
 
     return WriteClientError(pfc,"Shibboleth Filter reached unreachable code, save my walrus!");
 }
-        
+
 
 /****************************************************************************/
 // ISAPI Extension
@@ -608,16 +700,17 @@ DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const char* msg)
 class ShibTargetIsapiE : public AbstractSPRequest
 {
   LPEXTENSION_CONTROL_BLOCK m_lpECB;
-  map<string,string> m_headers;
-  vector<XSECCryptoX509*> m_certs;
+  multimap<string,string> m_headers;
+  mutable vector<string> m_certs;
   mutable string m_body;
   mutable bool m_gotBody;
   int m_port;
   string m_scheme,m_hostname,m_uri;
-  mutable string m_remote_addr;
-  
+  mutable string m_remote_addr,m_remote_user;
+
 public:
-  ShibTargetIsapiE(LPEXTENSION_CONTROL_BLOCK lpECB, const site_t& site) : m_lpECB(lpECB), m_gotBody(false) {
+  ShibTargetIsapiE(LPEXTENSION_CONTROL_BLOCK lpECB, const site_t& site)
+      : AbstractSPRequest(SHIBSP_LOGCAT".ISAPI"), m_lpECB(lpECB), m_gotBody(false) {
     dynabuf ssl(5);
     GetServerVariable(lpECB,"HTTPS",ssl,5);
     bool SSL=(ssl=="on" || ssl=="ON");
@@ -658,34 +751,41 @@ public:
      * the server is set up for proper PATH_INFO handling, or "IIS sucks rabid weasels mode",
      * which is the default. No perfect way to tell, but we can take a good guess by checking
      * whether the URL is a substring of the PATH_INFO:
-     * 
+     *
      * e.g. for /Shibboleth.sso/SAML/POST
-     * 
+     *
      *  Bad mode (default):
      *      URL:        /Shibboleth.sso
      *      PathInfo:   /Shibboleth.sso/SAML/POST
-     * 
+     *
      *  Good mode:
      *      URL:        /Shibboleth.sso
      *      PathInfo:   /SAML/POST
      */
-    
+
+    string uri;
+
     // Clearly we're only in bad mode if path info exists at all.
     if (lpECB->lpszPathInfo && *(lpECB->lpszPathInfo)) {
         if (strstr(lpECB->lpszPathInfo,url))
             // Pretty good chance we're in bad mode, unless the PathInfo repeats the path itself.
-            m_uri = lpECB->lpszPathInfo;
+            uri = lpECB->lpszPathInfo;
         else {
-            m_uri = url;
-            m_uri += lpECB->lpszPathInfo;
+            uri = url;
+            uri += lpECB->lpszPathInfo;
         }
     }
-    
+    else {
+        uri = url;
+    }
+
     // For consistency with Apache, let's add the query string.
     if (lpECB->lpszQueryString && *(lpECB->lpszQueryString)) {
-        m_uri += '?';
-        m_uri += lpECB->lpszQueryString;
+        uri += '?';
+        uri += lpECB->lpszQueryString;
     }
+
+    setRequestURI(uri.c_str());
   }
   ~ShibTargetIsapiE() { }
 
@@ -698,9 +798,6 @@ public:
   int getPort() const {
     return m_port;
   }
-  const char* getRequestURI() const {
-    return m_uri.c_str();
-  }
   const char* getMethod() const {
     return m_lpECB->lpszMethod;
   }
@@ -710,7 +807,17 @@ public:
   long getContentLength() const {
       return m_lpECB->cbTotalBytes;
   }
+  string getRemoteUser() const {
+    if (m_remote_user.empty()) {
+        dynabuf var(16);
+        GetServerVariable(m_lpECB, "REMOTE_USER", var, 32, false);
+        if (!var.empty())
+            m_remote_user = var;
+    }
+    return m_remote_user;
+  }
   string getRemoteAddr() const {
+    m_remote_addr = AbstractSPRequest::getRemoteAddr();
     if (m_remote_addr.empty()) {
         dynabuf var(16);
         GetServerVariable(m_lpECB, "REMOTE_ADDR", var, 16, false);
@@ -719,9 +826,9 @@ public:
     }
     return m_remote_addr;
   }
-  void log(SPLogLevel level, const string& msg) {
+  void log(SPLogLevel level, const string& msg) const {
       AbstractSPRequest::log(level,msg);
-      if (level >= SPError)
+      if (level >= SPCrit)
           LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg.c_str());
   }
   string getHeader(const char* name) const {
@@ -737,9 +844,10 @@ public:
     return buf.empty() ? "" : buf;
   }
   void setResponseHeader(const char* name, const char* value) {
+    AbstractSPRequest::setResponseHeader(name, value);
     // Set for later.
     if (value)
-        m_headers[name] = value;
+        m_headers.insert(make_pair(name,value));
     else
         m_headers.erase(name);
   }
@@ -750,21 +858,27 @@ public:
     if (m_gotBody)
         return m_body.c_str();
     if (m_lpECB->cbTotalBytes > 1024*1024) // 1MB?
-        throw opensaml::BindingException("Size of POST request body exceeded limit.");
-    else if (m_lpECB->cbTotalBytes != m_lpECB->cbAvailable) {
+        throw opensaml::SecurityPolicyException("Size of request body exceeded 1M size limit.");
+    else if (m_lpECB->cbTotalBytes > m_lpECB->cbAvailable) {
       m_gotBody=true;
-      char buf[8192];
       DWORD datalen=m_lpECB->cbTotalBytes;
+      if (m_lpECB->cbAvailable > 0) {
+        m_body.assign(reinterpret_cast<char*>(m_lpECB->lpbData),m_lpECB->cbAvailable);
+        datalen-=m_lpECB->cbAvailable;
+      }
+      char buf[8192];
       while (datalen) {
         DWORD buflen=8192;
         BOOL ret = m_lpECB->ReadClient(m_lpECB->ConnID, buf, &buflen);
-        if (!ret || !buflen)
-            throw saml::SAMLException("Error reading POST request body from browser.");
+        if (!ret)
+            throw IOException("Error reading request body from browser.");
+        else if (!buflen)
+            throw IOException("Socket closed while reading request body from browser.");
         m_body.append(buf, buflen);
         datalen-=buflen;
       }
     }
-    else {
+    else if (m_lpECB->cbAvailable) {
         m_gotBody=true;
         m_body.assign(reinterpret_cast<char*>(m_lpECB->lpbData),m_lpECB->cbAvailable);
     }
@@ -772,14 +886,15 @@ public:
   }
   long sendResponse(istream& in, long status) {
     string hdr = string("Connection: close\r\n");
-    for (map<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
+    for (multimap<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
         hdr += i->first + ": " + i->second + "\r\n";
     hdr += "\r\n";
     const char* codestr="200 OK";
     switch (status) {
-        case SAML_HTTP_STATUS_FORBIDDEN:codestr="403 Forbidden"; break;
-        case SAML_HTTP_STATUS_NOTFOUND: codestr="404 Not Found"; break;
-        case SAML_HTTP_STATUS_ERROR:    codestr="500 Server Error"; break;
+        case XMLTOOLING_HTTP_STATUS_UNAUTHORIZED:   codestr="401 Authorization Required"; break;
+        case XMLTOOLING_HTTP_STATUS_FORBIDDEN:      codestr="403 Forbidden"; break;
+        case XMLTOOLING_HTTP_STATUS_NOTFOUND:       codestr="404 Not Found"; break;
+        case XMLTOOLING_HTTP_STATUS_ERROR:          codestr="500 Server Error"; break;
     }
     m_lpECB->ServerSupportFunction(m_lpECB->ConnID, HSE_REQ_SEND_RESPONSE_HEADER, (void*)codestr, 0, (LPDWORD)hdr.c_str());
     char buf[1024];
@@ -791,12 +906,13 @@ public:
     return HSE_STATUS_SUCCESS;
   }
   long sendRedirect(const char* url) {
+    AbstractSPRequest::sendRedirect(url);
     string hdr=string("Location: ") + url + "\r\n"
       "Content-Type: text/html\r\n"
       "Content-Length: 40\r\n"
       "Expires: 01-Jan-1997 12:00:00 GMT\r\n"
       "Cache-Control: private,no-store,no-cache\r\n";
-    for (map<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
+    for (multimap<string,string>::const_iterator i=m_headers.begin(); i!=m_headers.end(); ++i)
         hdr += i->first + ": " + i->second + "\r\n";
     hdr += "\r\n";
     m_lpECB->ServerSupportFunction(m_lpECB->ConnID, HSE_REQ_SEND_RESPONSE_HEADER, "302 Moved", 0, (LPDWORD)hdr.c_str());
@@ -818,15 +934,34 @@ public:
       return HSE_STATUS_SUCCESS;
   }
 
-  const vector<XSECCryptoX509*>& getClientCertificates() const {
+  const vector<string>& getClientCertificates() const {
+      if (m_certs.empty()) {
+        char CertificateBuf[8192];
+        CERT_CONTEXT_EX ccex;
+        ccex.cbAllocated = sizeof(CertificateBuf);
+        ccex.CertContext.pbCertEncoded = (BYTE*)CertificateBuf;
+        DWORD dwSize = sizeof(ccex);
+
+        if (m_lpECB->ServerSupportFunction(m_lpECB->ConnID, HSE_REQ_GET_CERT_INFO_EX, (LPVOID)&ccex, (LPDWORD)dwSize, NULL)) {
+            if (ccex.CertContext.cbCertEncoded) {
+                xsecsize_t outlen;
+                XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>(CertificateBuf), ccex.CertContext.cbCertEncoded, &outlen);
+                m_certs.push_back(reinterpret_cast<char*>(serialized));
+#ifdef SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE
+                XMLString::release(&serialized);
+#else
+                XMLString::release((char**)&serialized);
+#endif
+            }
+        }
+      }
       return m_certs;
   }
 
   // Not used in the extension.
-  virtual void clearHeader(const char* name) { throw runtime_error("clearHeader not implemented"); }
-  virtual void setHeader(const char* name, const char* value) { throw runtime_error("setHeader not implemented"); }
-  virtual void setRemoteUser(const char* user) { throw runtime_error("setRemoteUser not implemented"); }
-  virtual string getRemoteUser() const { throw runtime_error("getRemoteUser not implemented"); }
+  void clearHeader(const char* rawname, const char* cginame) { throw runtime_error("clearHeader not implemented"); }
+  void setHeader(const char* name, const char* value) { throw runtime_error("setHeader not implemented"); }
+  void setRemoteUser(const char* user) { throw runtime_error("setRemoteUser not implemented"); }
 };
 
 extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
@@ -843,12 +978,12 @@ extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
         // Match site instance to host name, skip if no match.
         map<string,site_t>::const_iterator map_i=g_Sites.find(static_cast<char*>(buf));
         if (map_i==g_Sites.end())
-            return WriteClientError(lpECB, "Shibboleth Extension not configured for this web site.");
+            return WriteClientError(lpECB, "Shibboleth Extension not configured for web site (check <ISAPI> mappings in configuration).");
 
         ShibTargetIsapiE ste(lpECB, map_i->second);
         pair<bool,long> res = ste.getServiceProvider().doHandler(ste);
         if (res.first) return res.second;
-        
+
         return WriteClientError(lpECB, "Shibboleth Extension failed to process request");
 
     }
@@ -865,11 +1000,12 @@ extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB)
         LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, e.what());
         return WriteClientError(lpECB,"Shibboleth Extension caught an exception, check Event Log for details.");
     }
-#ifndef _DEBUG
     catch(...) {
-        return WriteClientError(lpECB,"Shibboleth Extension caught an unknown exception.");
+        LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Shibboleth Extension threw an unknown exception.");
+        if (g_catchAll)
+            return WriteClientError(lpECB,"Shibboleth Extension threw an unknown exception.");
+        throw;
     }
-#endif
 
     // If we get here we've got an error.
     return HSE_STATUS_ERROR;