/*
- * The Shibboleth License, Version 1.
- * Copyright (c) 2002
- * University Corporation for Advanced Internet Development, Inc.
- * All rights reserved
+ * Copyright 2001-2007 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
*
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution, if any, must include
- * the following acknowledgment: "This product includes software developed by
- * the University Corporation for Advanced Internet Development
- * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
- * may appear in the software itself, if and wherever such third-party
- * acknowledgments normally appear.
- *
- * Neither the name of Shibboleth nor the names of its contributors, nor
- * Internet2, nor the University Corporation for Advanced Internet Development,
- * Inc., nor UCAID may be used to endorse or promote products derived from this
- * software without specific prior written permission. For written permission,
- * please contact shibboleth@shibboleth.org
- *
- * Products derived from this software may not be called Shibboleth, Internet2,
- * UCAID, or the University Corporation for Advanced Internet Development, nor
- * may Shibboleth appear in their name, without prior written permission of the
- * University Corporation for Advanced Internet Development.
- *
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
- * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
- * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
- * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
*/
-/* isapi_shib.cpp - Shibboleth ISAPI filter
+/**
+ * isapi_shib.cpp
+ *
+ * Shibboleth ISAPI filter
+ */
- Scott Cantor
- 8/23/02
-*/
+#define SHIBSP_LITE
+#include "config_win32.h"
-// SAML Runtime
-#include <saml/saml.h>
-#include <shib/shib.h>
-#include <shib/shib-threads.h>
-#include <shib-target/shib-target.h>
+#define _CRT_NONSTDC_NO_DEPRECATE 1
+#define _CRT_SECURE_NO_DEPRECATE 1
-#include <log4cpp/Category.hh>
+#include <shibsp/AbstractSPRequest.h>
+#include <shibsp/SPConfig.h>
+#include <shibsp/ServiceProvider.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 <ctime>
-#include <fstream>
+#include <set>
#include <sstream>
-#include <stdexcept>
+#include <fstream>
+#include <process.h>
+#include <windows.h>
#include <httpfilt.h>
#include <httpext.h>
-#include <cgiparse.h>
-
+using namespace shibsp;
+using namespace xmltooling;
+using namespace xercesc;
using namespace std;
-using namespace log4cpp;
-using namespace saml;
-using namespace shibboleth;
-using namespace shibtarget;
// 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 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 {
+ site_t(const DOMElement* e)
+ {
+ auto_ptr_char n(e->getAttributeNS(NULL,name));
+ auto_ptr_char s(e->getAttributeNS(NULL,scheme));
+ auto_ptr_char p(e->getAttributeNS(NULL,port));
+ auto_ptr_char p2(e->getAttributeNS(NULL,sslport));
+ if (n.get()) m_name=n.get();
+ if (s.get()) m_scheme=s.get();
+ if (p.get()) m_port=p.get();
+ if (p2.get()) m_sslport=p2.get();
+ e = XMLHelper::getFirstChildElement(e, Alias);
+ while (e) {
+ if (e->hasChildNodes()) {
+ auto_ptr_char alias(e->getFirstChild()->getNodeValue());
+ m_aliases.insert(alias.get());
+ }
+ e = XMLHelper::getNextSiblingElement(e, Alias);
+ }
+ }
+ string m_scheme,m_port,m_sslport,m_name;
+ set<string> m_aliases;
+ };
+
HINSTANCE g_hinstDLL;
- ShibTargetConfig* g_Config = NULL;
- vector<string> g_Sites;
+ SPConfig* g_Config = NULL;
+ map<string,site_t> g_Sites;
+ bool g_bNormalizeRequest = true;
+ string g_unsetHeaderValue;
+ bool g_checkSpoofing = true;
+ bool g_catchAll = false;
+ vector<string> g_NoCerts;
}
BOOL LogEvent(
if (!pVer)
return FALSE;
- if (!g_Config)
- {
+ if (!g_Config) {
LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
"Extension mode startup not possible, is the DLL loaded as a filter?");
return FALSE;
return TRUE;
}
+extern "C" BOOL WINAPI TerminateExtension(DWORD)
+{
+ return TRUE; // cleanup should happen when filter unloads
+}
+
extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
{
if (!pVer)
return FALSE;
+ else if (g_Config) {
+ LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+ "Reentrant filter initialization, ignoring...");
+ return TRUE;
+ }
- try
- {
- ShibTargetConfig::preinit();
- g_Config = &(ShibTargetConfig::init(SHIBTARGET_SHIRE, getenv("SHIBCONFIG")));
- ShibINI& ini = g_Config->getINI();
-
- Category& log=Category::getInstance("isapi_shib.GetFilterVersion");
-
- // Read site-specific settings for each instance ID we can find.
- unsigned short i=1;
- char iid[8];
- sprintf(iid,"%u",i++);
- string hostname;
- while (ini.get_tag("isapi",iid,false,&hostname))
- {
- log.info("configuring for site ID (%d), hostname (%s)",i-1,hostname.empty() ? "null" : hostname.c_str());
+ LPCSTR schemadir=getenv("SHIBSP_SCHEMAS");
+ if (!schemadir)
+ schemadir=SHIBSP_SCHEMAS;
+ LPCSTR config=getenv("SHIBSP_CONFIG");
+ if (!config)
+ config=SHIBSP_CONFIG;
+ g_Config=&SPConfig::getConfig();
+ g_Config->setFeatures(
+ SPConfig::Listener |
+ SPConfig::Caching |
+ SPConfig::RequestMapping |
+ SPConfig::InProcess |
+ SPConfig::Logging |
+ SPConfig::Handlers
+ );
+ 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;
+ }
- // If no section exists for the host, mark it as a "skip" site.
- if (hostname == "skip")
- {
- log.info("skipping site ID (%d)",i-1);
- hostname.erase();
- }
+ try {
+ DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
+ XercesJanitor<DOMDocument> docjanitor(dummydoc);
+ DOMElement* dummy = dummydoc->createElementNS(NULL,path);
+ auto_ptr_XMLCh src(config);
+ dummy->setAttributeNS(NULL,path,src.get());
+ dummy->setAttributeNS(NULL,validate,xmlconstants::XML_ONE);
- g_Sites.push_back(hostname);
- sprintf(iid,"%u",i++);
- hostname.erase();
- }
+ g_Config->setServiceProvider(g_Config->ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER,dummy));
+ g_Config->getServiceProvider()->init();
}
- catch (SAMLException&)
- {
+ 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 with SAML exception, check shire log for help.");
- return FALSE;
- }
- catch (runtime_error& e)
- {
- LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, e.what());
+ "Filter startup failed to load configuration, check native log for details.");
return FALSE;
}
- catch (...)
- {
- LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Filter startup failed with unexpected exception.");
- 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,const char*> unsetValue=props->getString("unsetHeaderValue");
+ if (unsetValue.first)
+ g_unsetHeaderValue = unsetValue.second;
+ pair<bool,bool> flag=props->getBool("checkSpoofing");
+ g_checkSpoofing = !flag.first || flag.second;
+ flag=props->getBool("catchAll");
+ g_catchAll = flag.first && flag.second;
+
+ props = props->getPropertySet("ISAPI");
+ if (props) {
+ flag = props->getBool("normalizeRequest");
+ g_bNormalizeRequest = !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);
+ }
+ }
}
pVer->dwFilterVersion=HTTP_FILTER_REVISION;
return TRUE;
}
-extern "C" BOOL WINAPI TerminateExtension(DWORD)
-{
- return TRUE; // cleanup should happen when filter unloads
-}
-
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;
}
void GetServerVariable(PHTTP_FILTER_CONTEXT pfc, LPSTR lpszVariable, dynabuf& s, DWORD size=80, bool bRequired=true)
- throw (bad_alloc, DWORD)
{
- s.erase();
s.reserve(size);
+ s.erase();
size=s.size();
- while (!pfc->GetServerVariable(pfc,lpszVariable,s,&size))
- {
+ while (!pfc->GetServerVariable(pfc,lpszVariable,s,&size)) {
// Grumble. Check the error.
DWORD e=GetLastError();
if (e==ERROR_INSUFFICIENT_BUFFER)
}
void GetServerVariable(LPEXTENSION_CONTROL_BLOCK lpECB, LPSTR lpszVariable, dynabuf& s, DWORD size=80, bool bRequired=true)
- throw (bad_alloc, DWORD)
{
- s.erase();
s.reserve(size);
+ s.erase();
size=s.size();
- while (lpECB->GetServerVariable(lpECB->ConnID,lpszVariable,s,&size))
- {
+ while (!lpECB->GetServerVariable(lpECB->ConnID,lpszVariable,s,&size)) {
// Grumble. Check the error.
DWORD e=GetLastError();
if (e==ERROR_INSUFFICIENT_BUFFER)
void GetHeader(PHTTP_FILTER_PREPROC_HEADERS pn, PHTTP_FILTER_CONTEXT pfc,
LPSTR lpszName, dynabuf& s, DWORD size=80, bool bRequired=true)
- throw (bad_alloc, DWORD)
{
- s.erase();
s.reserve(size);
+ s.erase();
size=s.size();
- while (!pn->GetHeader(pfc,lpszName,s,&size))
- {
+ while (!pn->GetHeader(pfc,lpszName,s,&size)) {
// Grumble. Check the error.
DWORD e=GetLastError();
if (e==ERROR_INSUFFICIENT_BUFFER)
throw ERROR_NO_DATA;
}
-inline char hexchar(unsigned short s)
-{
- return (s<=9) ? ('0' + s) : ('A' + s - 10);
-}
+/****************************************************************************/
+// ISAPI Filter
-string url_encode(const char* url) throw (bad_alloc)
+class ShibTargetIsapiF : public AbstractSPRequest
{
- static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
- string s;
- for (const char* pch=url; *pch; pch++)
- {
- if (strchr(badchars,*pch)!=NULL || *pch<=0x1F || *pch>=0x7F)
- s=s + '%' + hexchar(*pch >> 4) + hexchar(*pch & 0x0F);
- else
- s+=*pch;
- }
- return s;
-}
+ PHTTP_FILTER_CONTEXT m_pfc;
+ PHTTP_FILTER_PREPROC_HEADERS m_pn;
+ multimap<string,string> m_headers;
+ int m_port;
+ string m_scheme,m_hostname;
+ mutable string m_remote_addr,m_content_type,m_method;
+ dynabuf m_allhttp;
-void get_target_and_appid(
- PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn, const char* hostname, string& target, string& appid
- )
-{
- dynabuf port(10);
- dynabuf url(256);
- GetServerVariable(pfc,"SERVER_PORT",port,10);
- GetHeader(pn,pfc,"url",url,256,false);
+public:
+ 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) {
+
+ // URL path always come from IIS.
+ dynabuf var(256);
+ GetHeader(pn,pfc,"url",var,256,false);
+ 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())) {
+ GetServerVariable(pfc,"SERVER_PORT",var,10);
+ m_port = atoi(var);
+ }
+ else if (pfc->fIsSecurePort) {
+ m_port = atoi(site.m_sslport.c_str());
+ }
+ else {
+ m_port = atoi(site.m_port.c_str());
+ }
- // First get the appid using the normalized hostname.
- ApplicationMapper mapper;
- appid = mapper->getApplicationFromParsedURL((pfc->fIsSecurePort ? "https" : "http"), hostname, atoi(port), url);
-
- target=static_cast<char*>(url);
- if (port!=(pfc->fIsSecurePort ? "443" : "80"))
- target = ':' + static_cast<char*>(port) + target;
-
- // For the target, we use the "normalizeRequest" tag to decide how to set the server's name.
- string tag;
- if (g_Config->getINI().get_tag(appid,"normalizeRequest",true,&tag) && ShibINI::boolean(tag))
- {
- target=string(pfc->fIsSecurePort ? "https://" : "http://") + hostname + target;
+ // Scheme may come from site def or be derived from IIS.
+ m_scheme=site.m_scheme;
+ if (m_scheme.empty() || !g_bNormalizeRequest)
+ m_scheme=pfc->fIsSecurePort ? "https" : "http";
+
+ GetServerVariable(pfc,"SERVER_NAME",var,32);
+
+ // Make sure SERVER_NAME is "authorized" for use on this site. If not, set to canonical name.
+ m_hostname = var;
+ if (site.m_name!=m_hostname && site.m_aliases.find(m_hostname)==site.m_aliases.end())
+ m_hostname=site.m_name;
+ }
+ ~ShibTargetIsapiF() { }
+
+ const char* getScheme() const {
+ return m_scheme.c_str();
+ }
+ const char* getHostname() const {
+ return m_hostname.c_str();
+ }
+ int getPort() const {
+ return m_port;
+ }
+ const char* getMethod() const {
+ if (m_method.empty()) {
+ dynabuf var(5);
+ GetServerVariable(m_pfc,"REQUEST_METHOD",var,5,false);
+ if (!var.empty())
+ m_method = var;
+ }
+ return m_method.c_str();
+ }
+ string getContentType() const {
+ if (m_content_type.empty()) {
+ dynabuf var(32);
+ GetServerVariable(m_pfc,"CONTENT_TYPE",var,32,false);
+ if (!var.empty())
+ m_content_type = var;
+ }
+ return m_content_type;
+ }
+ long getContentLength() const {
+ return 0;
+ }
+ string getRemoteAddr() const {
+ if (m_remote_addr.empty()) {
+ dynabuf var(16);
+ GetServerVariable(m_pfc,"REMOTE_ADDR",var,16,false);
+ if (!var.empty())
+ m_remote_addr = var;
}
+ return m_remote_addr;
+ }
+ void log(SPLogLevel level, const string& msg) {
+ AbstractSPRequest::log(level,msg);
+ if (level >= SPError)
+ LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg.c_str());
+ }
+ void clearHeader(const char* rawname, const char* cginame) {
+ if (g_checkSpoofing) {
+ if (m_allhttp.empty())
+ GetServerVariable(m_pfc,"ALL_HTTP",m_allhttp,4096);
+ if (strstr(m_allhttp, cginame))
+ throw opensaml::SecurityPolicyException("Attempt to spoof header ($1) was detected.", params(1, rawname));
+ }
+ string hdr(!strcmp(rawname,"REMOTE_USER") ? "remote-user" : rawname);
+ hdr += ':';
+ 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 += ':';
+ m_pn->SetHeader(m_pfc, const_cast<char*>(hdr.c_str()), const_cast<char*>(value));
+ }
+ string getHeader(const char* name) const {
+ string hdr(name);
+ hdr += ':';
+ dynabuf buf(256);
+ GetHeader(m_pn, m_pfc, const_cast<char*>(hdr.c_str()), buf, 256, false);
+ return string(buf);
+ }
+ void setRemoteUser(const char* user) {
+ setHeader("remote-user", user);
+ }
+ string getRemoteUser() const {
+ return getHeader("remote-user");
+ }
+ void setResponseHeader(const char* name, const char* value) {
+ // Set for later.
+ if (value)
+ m_headers.insert(make_pair(name,value));
else
- {
- GetServerVariable(pfc,"SERVER_NAME",url);
- target=string(pfc->fIsSecurePort ? "https://" : "http://") + static_cast<char*>(url) + target;
+ m_headers.erase(name);
+ }
+ long sendResponse(istream& in, long status) {
+ string hdr = string("Connection: close\r\n");
+ 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 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;
}
-}
-
-string get_shire_location(const char* application_id, const char* target)
-{
- string shireURL;
- if (g_Config->getINI().get_tag(application_id,"shireURL",true,&shireURL) && !shireURL.empty())
- {
- if (shireURL[0]!='/')
- return shireURL;
- const char* colon=strchr(target,':');
- const char* slash=strchr(colon+3,'/');
- string s(target,slash-target);
- s+=shireURL;
- return s;
- }
- return shireURL;
-}
+ m_pfc->ServerSupportFunction(m_pfc, SF_REQ_SEND_RESPONSE_HEADER, (void*)codestr, (DWORD)hdr.c_str(), 0);
+ char buf[1024];
+ while (in) {
+ in.read(buf,1024);
+ DWORD resplen = in.gcount();
+ m_pfc->WriteClient(m_pfc, buf, &resplen, 0);
+ }
+ return SF_STATUS_REQ_FINISHED;
+ }
+ long sendRedirect(const char* url) {
+ // XXX: Don't support the httpRedirect option, yet.
+ 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 (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);
+ static const char* redmsg="<HTML><BODY>Redirecting...</BODY></HTML>";
+ DWORD resplen=40;
+ m_pfc->WriteClient(m_pfc, (LPVOID)redmsg, &resplen, 0);
+ return SF_STATUS_REQ_FINISHED;
+ }
+ long returnDecline() {
+ return SF_STATUS_REQ_NEXT_NOTIFICATION;
+ }
+ long returnOK() {
+ return SF_STATUS_REQ_NEXT_NOTIFICATION;
+ }
+
+ const vector<string>& getClientCertificates() const {
+ return g_NoCerts;
+ }
+
+ // The filter never processes the POST, so stub these methods.
+ const char* getQueryString() const { throw IOException("getQueryString not implemented"); }
+ const char* getRequestBody() const { throw IOException("getRequestBody not implemented"); }
+};
DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const char* msg)
{
LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg);
- static const char* ctype="Content-Type: text/html\r\n";
- pfc->AddResponseHeaders(pfc,const_cast<char*>(ctype),0);
- pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",0,0);
+ static const char* ctype="Connection: close\r\nContent-Type: text/html\r\n\r\n";
+ pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",(DWORD)ctype,0);
static const char* xmsg="<HTML><HEAD><TITLE>Shibboleth Filter Error</TITLE></HEAD><BODY>"
"<H1>Shibboleth Filter Error</H1>";
DWORD resplen=strlen(xmsg);
return SF_STATUS_REQ_FINISHED;
}
-DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const char* filename, ShibMLP& mlp)
-{
- ifstream infile(filename);
- if (!infile)
- return WriteClientError(pfc,"Unable to open error template, check settings.");
- string res = mlp.run(infile);
-
- static const char* ctype="Content-Type: text/html\r\n";
- pfc->AddResponseHeaders(pfc,const_cast<char*>(ctype),0);
- pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",0,0);
- DWORD resplen=res.length();
- pfc->WriteClient(pfc,(LPVOID)res.c_str(),&resplen,0);
- return SF_STATUS_REQ_FINISHED;
-}
-
extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificationType, LPVOID pvNotification)
{
// Is this a log notification?
{
// Determine web site number. This can't really fail, I don't think.
dynabuf buf(128);
- ULONG site_id=0;
GetServerVariable(pfc,"INSTANCE_ID",buf,10);
- if ((site_id=strtoul(buf,NULL,10))==0)
- return WriteClientError(pfc,"IIS site instance appears to be invalid.");
-
- // Match site instance to site settings.
- if (site_id>g_Sites.size() || g_Sites[site_id-1].length()==0)
- return SF_STATUS_REQ_NEXT_NOTIFICATION;
- string& site=g_Sites[site_id-1];
-
- string application_id;
- string target_url;
- get_target_and_appid(pfc,pn,site.c_str(),target_url,application_id);
- string shire_url=get_shire_location(application_id.c_str(),target_url.c_str());
-
- // If the user is accessing the SHIRE acceptance point, pass it on.
- if (target_url.find(shire_url)!=string::npos)
- return SF_STATUS_REQ_NEXT_NOTIFICATION;
- // Now check the policy for this application.
- string tag;
- ShibINI& ini=g_Config->getINI();
- if (!ini.get_tag(application_id,"requireSession",true,&tag) || !ShibINI::boolean(tag))
+ // 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 SF_STATUS_REQ_NEXT_NOTIFICATION;
-
- // SSL content check.
- if (ini.get_tag(application_id,"contentSSLOnly",true,&tag) && ShibINI::boolean(tag) && !pfc->fIsSecurePort)
- {
- return WriteClientError(pfc,
- "This server is configured to deny non-SSL requests for secure resources. "
- "Try your request again using https instead of http.");
- }
-
+
ostringstream threadid;
- threadid << "[" << getpid() << "] shire" << '\0';
- saml::NDC ndc(threadid.str().c_str());
-
- // Set SHIRE policies.
- SHIREConfig config;
- config.checkIPAddress = (ini.get_tag(application_id,"checkIPAddress",true,&tag) && ShibINI::boolean(tag));
- config.lifetime=config.timeout=0;
- tag.erase();
- if (ini.get_tag(application_id, "authLifetime", true, &tag))
- config.lifetime=strtoul(tag.c_str(),NULL,10);
- tag.erase();
- if (ini.get_tag(application_id, "authTimeout", true, &tag))
- config.timeout=strtoul(tag.c_str(),NULL,10);
-
- // Pull the config data we need to handle the various possible conditions.
- string shib_cookie;
- if (!ini.get_tag(application_id, "cookieName", true, &shib_cookie))
- return WriteClientError(pfc,"The cookieName configuration setting is missing, check configuration.");
-
- string wayfLocation;
- if (!ini.get_tag(application_id, "wayfURL", true, &wayfLocation))
- return WriteClientError(pfc,"The wayfURL configuration setting is missing, check configuration.");
-
- string shireError;
- if (!ini.get_tag(application_id, "shireError", true, &shireError))
- return WriteClientError(pfc,"The shireError configuration setting is missing, check configuration.");
+ threadid << "[" << getpid() << "] isapi_shib" << '\0';
+ xmltooling::NDC ndc(threadid.str().c_str());
- string accessError;
- if (!ini.get_tag(application_id, "accessError", true, &shireError))
- return WriteClientError(pfc,"The accessError configuration setting is missing, check configuration.");
-
- SHIRE shire(config, shire_url.c_str());
+ ShibTargetIsapiF stf(pfc, pn, map_i->second);
- // Check for authentication cookie.
- const char* session_id=NULL;
- GetHeader(pn,pfc,"Cookie:",buf,128,false);
- Category::getInstance("isapi_shib.HttpFilterProc").debug("cookie header is {%s}",(const char*)buf);
- if (buf.empty() || !(session_id=strstr(buf,shib_cookie.c_str())) || *(session_id+shib_cookie.length())!='=')
- {
- // Redirect to WAYF.
- char timebuf[16];
- sprintf(timebuf,"%u",time(NULL));
- string wayf("Location: ");
- wayf+=wayfLocation + "?shire=" + url_encode(shire_url.c_str()) + "&target=" + url_encode(target_url.c_str()) +
- "&time=" + timebuf + "&providerId=" + application_id + "\r\n";
- // Insert the headers.
- pfc->AddResponseHeaders(pfc,const_cast<char*>(wayf.c_str()),0);
- pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"302 Please Wait",0,0);
- return SF_STATUS_REQ_FINISHED;
- }
+ // "false" because we don't override the Shib settings
+ pair<bool,long> res = stf.getServiceProvider().doAuthentication(stf);
+ if (res.first) return res.second;
- session_id+=shib_cookie.length() + 1; /* Skip over the '=' */
- char* cookieend=strchr(session_id,';');
- if (cookieend)
- *cookieend = '\0'; /* Ignore anyting after a ; */
-
- // Make sure this session is still valid.
- RPCError* status = NULL;
- ShibMLP markupProcessor;
- bool has_tag = ini.get_tag(application_id, "supportContact", true, &tag);
- markupProcessor.insert("supportContact", has_tag ? tag : "");
- has_tag = ini.get_tag(application_id, "logoLocation", true, &tag);
- markupProcessor.insert("logoLocation", has_tag ? tag : "");
- markupProcessor.insert("requestURL", target_url);
-
- dynabuf abuf(16);
- GetServerVariable(pfc,"REMOTE_ADDR",abuf,16);
- try {
- status = shire.sessionIsValid(session_id, abuf, application_id.c_str());
- }
- catch (ShibTargetException &e) {
- markupProcessor.insert("errorType", "SHIRE Processing Error");
- markupProcessor.insert("errorText", e.what());
- markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
- return WriteClientError(pfc, shireError.c_str(), markupProcessor);
- }
- catch (...) {
- markupProcessor.insert("errorType", "SHIRE Processing Error");
- markupProcessor.insert("errorText", "Unexpected Exception");
- markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
- return WriteClientError(pfc, shireError.c_str(), markupProcessor);
- }
-
- // Check the status
- if (status->isError()) {
- if (status->isRetryable()) {
- // Redirect to WAYF.
- delete status;
- char timebuf[16];
- sprintf(timebuf,"%u",time(NULL));
- string wayf("Location: ");
- wayf+=wayfLocation + "?shire=" + url_encode(shire_url.c_str()) + "&target=" + url_encode(target_url.c_str()) +
- "&time=" + timebuf + "&providerId=" + application_id + "\r\n";
- // Insert the headers.
- pfc->AddResponseHeaders(pfc,const_cast<char*>(wayf.c_str()),0);
- pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"302 Please Wait",0,0);
- return SF_STATUS_REQ_FINISHED;
- }
- else {
- // return the error page to the user
- markupProcessor.insert(*status);
- delete status;
- return WriteClientError(pfc, shireError.c_str(), markupProcessor);
- }
- }
- delete status;
-
- // Move to RM phase.
- RMConfig rm_config;
- rm_config.checkIPAddress = config.checkIPAddress;
- RM rm(rm_config);
-
- // Get the attributes.
- vector<SAMLAssertion*> assertions;
- SAMLAuthenticationStatement* sso_statement=NULL;
- status = rm.getAssertions(session_id, buf, application_id.c_str(), assertions, &sso_statement);
-
- if (status->isError()) {
- string rmError;
- if (!ini.get_tag(application_id, "rmError", true, &shireError))
- return WriteClientError(pfc,"The rmError configuration setting is missing, check configuration.");
-
- markupProcessor.insert(*status);
- delete status;
- return WriteClientError(pfc, rmError.c_str(), markupProcessor);
- }
- delete status;
-
- // Only allow a single assertion...
- if (assertions.size() > 1) {
- for (int k = 0; k < assertions.size(); k++)
- delete assertions[k];
- delete sso_statement;
- return WriteClientError(pfc, accessError.c_str(), markupProcessor);
- }
-
- // Get the AAP providers, which contain the attribute policy info.
- Iterator<IAAP*> provs=g_Config->getAAPProviders();
-
- // Clear out the list of mapped attributes
- while (provs.hasNext())
- {
- IAAP* aap=provs.next();
- aap->lock();
- try
- {
- Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
- while (rules.hasNext())
- {
- const char* header=rules.next()->getHeader();
- if (header)
- pn->SetHeader(pfc,const_cast<char*>(header),"");
- }
- }
- catch(...)
- {
- aap->unlock();
- for (int k = 0; k < assertions.size(); k++)
- delete assertions[k];
- delete sso_statement;
- throw;
- }
- aap->unlock();
- }
- provs.reset();
+ // "false" because we don't override the Shib settings
+ res = stf.getServiceProvider().doExport(stf);
+ if (res.first) return res.second;
- // Clear relevant headers.
- pn->SetHeader(pfc,"remote-user:","");
- pn->SetHeader(pfc,"Shib-Attributes:","");
- pn->SetHeader(pfc,"Shib-Origin-Site:","");
- pn->SetHeader(pfc,"Shib-Authentication-Method:","");
-
- pn->SetHeader(pfc,"Shib-Application-ID:","");
- pn->SetHeader(pfc,"Shib-Application-ID:",const_cast<char*>(application_id.c_str()));
-
- // Maybe export the assertion.
- if (ini.get_tag(application_id,"exportAssertion",true,&tag) && ShibINI::boolean(tag))
- {
- string assertion;
- RM::serialize(*(assertions[0]), assertion);
- string::size_type lfeed;
- while ((lfeed=assertion.find('\n'))!=string::npos)
- assertion.erase(lfeed,1);
- pn->SetHeader(pfc,"Shib-Attributes:",const_cast<char*>(assertion.c_str()));
- }
-
- if (sso_statement)
- {
- auto_ptr_char os(sso_statement->getSubject()->getNameQualifier());
- auto_ptr_char am(sso_statement->getAuthMethod());
- pn->SetHeader(pfc,"Shib-Origin-Site:", const_cast<char*>(os.get()));
- pn->SetHeader(pfc,"Shib-Authentication-Method:", const_cast<char*>(am.get()));
- }
-
- // Export the attributes.
- Iterator<SAMLAssertion*> a_iter(assertions);
- while (a_iter.hasNext()) {
- SAMLAssertion* assert=a_iter.next();
- Iterator<SAMLStatement*> statements=assert->getStatements();
- while (statements.hasNext()) {
- SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
- if (!astate)
- continue;
- Iterator<SAMLAttribute*> attrs=astate->getAttributes();
- while (attrs.hasNext()) {
- SAMLAttribute* attr=attrs.next();
-
- // Are we supposed to export it?
- AAP wrapper(g_Config->getAAPProviders(),attr->getName(),attr->getNamespace());
- if (wrapper.fail())
- continue;
-
- Iterator<string> vals=attr->getSingleByteValues();
- if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext()) {
- char* principal=const_cast<char*>(vals.next().c_str());
- pn->SetHeader(pfc,"remote-user:",principal);
- pfc->pFilterContext=pfc->AllocMem(pfc,strlen(principal)+1,0);
- if (pfc->pFilterContext)
- strcpy(static_cast<char*>(pfc->pFilterContext),principal);
- }
- else {
- string header;
- for (int it = 0; vals.hasNext(); it++) {
- string value = vals.next();
- for (string::size_type pos = value.find_first_of(";", string::size_type(0)); pos != string::npos; pos = value.find_first_of(";", pos)) {
- value.insert(pos, "\\");
- pos += 2;
- }
- if (it == 0)
- header=value;
- else
- header=header + ';' + value;
- }
- string hname2=string(wrapper->getHeader()) + ':';
- pn->SetHeader(pfc,const_cast<char*>(hname2.c_str()),const_cast<char*>(header.c_str()));
- }
- }
- }
- }
-
- // clean up memory
- for (int k = 0; k < assertions.size(); k++)
- delete assertions[k];
- delete sso_statement;
+ res = stf.getServiceProvider().doAuthorization(stf);
+ if (res.first) return res.second;
return SF_STATUS_REQ_NEXT_NOTIFICATION;
}
- catch(bad_alloc)
- {
+ catch(bad_alloc) {
return WriteClientError(pfc,"Out of Memory");
}
- catch(DWORD e)
- {
+ catch(long e) {
if (e==ERROR_NO_DATA)
return WriteClientError(pfc,"A required variable or header was empty.");
else
- return WriteClientError(pfc,"Server detected unexpected IIS error.");
+ return WriteClientError(pfc,"Shibboleth Filter detected unexpected IIS error.");
}
- catch(...)
- {
- return WriteClientError(pfc,"Server caught an unknown exception.");
+ catch (exception& e) {
+ LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, e.what());
+ return WriteClientError(pfc,"Shibboleth Filter caught an exception, check Event Log for details.");
+ }
+ catch(...) {
+ 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;
}
- return WriteClientError(pfc,"Server reached unreachable code!");
+ return WriteClientError(pfc,"Shibboleth Filter reached unreachable code, save my walrus!");
}
+
-void get_target_and_appid(LPEXTENSION_CONTROL_BLOCK lpECB, const char* hostname, string& target, string& appid)
-{
- dynabuf ssl(5);
- dynabuf port(10);
- dynabuf url(256);
- GetServerVariable(lpECB,"HTTPS",ssl,5);
- GetServerVariable(lpECB,"SERVER_PORT",port,10);
- GetServerVariable(lpECB,"URL",url,255);
- bool SSL=(ssl=="on");
-
- // First get the appid using the normalized hostname.
- ApplicationMapper mapper;
- appid = mapper->getApplicationFromParsedURL((SSL ? "https" : "http"), hostname, atoi(port), url);
-
- target=static_cast<char*>(url);
- if (port!=(SSL ? "443" : "80"))
- target = ':' + static_cast<char*>(port) + target;
-
- // For the target, we use the "normalizeRequest" tag to decide how to set the server's name.
- string tag;
- if (g_Config->getINI().get_tag(appid,"normalizeRequest",true,&tag) && ShibINI::boolean(tag))
- {
- target=string(SSL ? "https://" : "http://") + hostname + target;
- }
- else
- {
- GetServerVariable(lpECB,"SERVER_NAME",url);
- target=string(SSL ? "https://" : "http://") + static_cast<char*>(url) + target;
- }
-}
+/****************************************************************************/
+// ISAPI Extension
DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const char* msg)
{
LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg);
- static const char* ctype="Content-Type: text/html\r\n";
+ static const char* ctype="Connection: close\r\nContent-Type: text/html\r\n\r\n";
lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"200 OK",0,(LPDWORD)ctype);
static const char* xmsg="<HTML><HEAD><TITLE>Shibboleth Error</TITLE></HEAD><BODY><H1>Shibboleth Error</H1>";
DWORD resplen=strlen(xmsg);
return HSE_STATUS_SUCCESS;
}
-DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const char* filename, ShibMLP& mlp)
+
+class ShibTargetIsapiE : public AbstractSPRequest
{
- ifstream infile(filename);
- if (!infile)
- return WriteClientError(lpECB,"Unable to open error template, check settings.");
+ LPEXTENSION_CONTROL_BLOCK m_lpECB;
+ 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,m_remote_user;
+
+public:
+ 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");
- string res = mlp.run(infile);
- static const char* ctype="Content-Type: text/html\r\n";
- lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"200 OK",0,(LPDWORD)ctype);
- DWORD resplen=res.length();
- lpECB->WriteClient(lpECB->ConnID,(LPVOID)res.c_str(),&resplen,0);
+ // Scheme may come from site def or be derived from IIS.
+ m_scheme=site.m_scheme;
+ if (m_scheme.empty() || !g_bNormalizeRequest)
+ m_scheme = SSL ? "https" : "http";
+
+ // URL path always come from IIS.
+ dynabuf url(256);
+ GetServerVariable(lpECB,"URL",url,255);
+
+ // Port may come from IIS or from site def.
+ dynabuf port(11);
+ if (!g_bNormalizeRequest || (SSL && site.m_sslport.empty()) || (!SSL && site.m_port.empty()))
+ GetServerVariable(lpECB,"SERVER_PORT",port,10);
+ else if (SSL) {
+ strncpy(port,site.m_sslport.c_str(),10);
+ static_cast<char*>(port)[10]=0;
+ }
+ else {
+ strncpy(port,site.m_port.c_str(),10);
+ static_cast<char*>(port)[10]=0;
+ }
+ m_port = atoi(port);
+
+ dynabuf var(32);
+ GetServerVariable(lpECB, "SERVER_NAME", var, 32);
+
+ // Make sure SERVER_NAME is "authorized" for use on this site. If not, set to canonical name.
+ m_hostname=var;
+ if (site.m_name!=m_hostname && site.m_aliases.find(m_hostname)==site.m_aliases.end())
+ m_hostname=site.m_name;
+
+ /*
+ * IIS screws us over on PATH_INFO (the hits keep on coming). We need to figure out if
+ * 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.
+ uri = lpECB->lpszPathInfo;
+ else {
+ uri = url;
+ uri += lpECB->lpszPathInfo;
+ }
+ }
+ else {
+ uri = url;
+ }
+
+ // For consistency with Apache, let's add the query string.
+ if (lpECB->lpszQueryString && *(lpECB->lpszQueryString)) {
+ uri += '?';
+ uri += lpECB->lpszQueryString;
+ }
+
+ setRequestURI(uri.c_str());
+ }
+ ~ShibTargetIsapiE() { }
+
+ const char* getScheme() const {
+ return m_scheme.c_str();
+ }
+ const char* getHostname() const {
+ return m_hostname.c_str();
+ }
+ int getPort() const {
+ return m_port;
+ }
+ const char* getMethod() const {
+ return m_lpECB->lpszMethod;
+ }
+ string getContentType() const {
+ return m_lpECB->lpszContentType ? m_lpECB->lpszContentType : "";
+ }
+ 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 {
+ if (m_remote_addr.empty()) {
+ dynabuf var(16);
+ GetServerVariable(m_lpECB, "REMOTE_ADDR", var, 16, false);
+ if (!var.empty())
+ m_remote_addr = var;
+ }
+ return m_remote_addr;
+ }
+ void log(SPLogLevel level, const string& msg) const {
+ AbstractSPRequest::log(level,msg);
+ if (level >= SPError)
+ LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg.c_str());
+ }
+ string getHeader(const char* name) const {
+ string hdr("HTTP_");
+ for (; *name; ++name) {
+ if (*name=='-')
+ hdr += '_';
+ else
+ hdr += toupper(*name);
+ }
+ dynabuf buf(128);
+ GetServerVariable(m_lpECB, const_cast<char*>(hdr.c_str()), buf, 128, false);
+ return buf.empty() ? "" : buf;
+ }
+ void setResponseHeader(const char* name, const char* value) {
+ // Set for later.
+ if (value)
+ m_headers.insert(make_pair(name,value));
+ else
+ m_headers.erase(name);
+ }
+ const char* getQueryString() const {
+ return m_lpECB->lpszQueryString;
+ }
+ const char* getRequestBody() const {
+ if (m_gotBody)
+ return m_body.c_str();
+ if (m_lpECB->cbTotalBytes > 1024*1024) // 1MB?
+ 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;
+ while (datalen) {
+ DWORD buflen=8192;
+ BOOL ret = m_lpECB->ReadClient(m_lpECB->ConnID, buf, &buflen);
+ if (!ret || !buflen)
+ throw IOException("Error reading request body from browser.");
+ m_body.append(buf, buflen);
+ datalen-=buflen;
+ }
+ }
+ else if (m_lpECB->cbAvailable) {
+ m_gotBody=true;
+ m_body.assign(reinterpret_cast<char*>(m_lpECB->lpbData),m_lpECB->cbAvailable);
+ }
+ return m_body.c_str();
+ }
+ long sendResponse(istream& in, long status) {
+ string hdr = string("Connection: close\r\n");
+ 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 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];
+ while (in) {
+ in.read(buf,1024);
+ DWORD resplen = in.gcount();
+ m_lpECB->WriteClient(m_lpECB->ConnID, buf, &resplen, HSE_IO_SYNC);
+ }
return HSE_STATUS_SUCCESS;
-}
+ }
+ long sendRedirect(const char* 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 (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());
+ static const char* redmsg="<HTML><BODY>Redirecting...</BODY></HTML>";
+ DWORD resplen=40;
+ m_lpECB->WriteClient(m_lpECB->ConnID, (LPVOID)redmsg, &resplen, HSE_IO_SYNC);
+ return HSE_STATUS_SUCCESS;
+ }
+ // Decline happens in the POST processor if this isn't the shire url
+ // Note that it can also happen with HTAccess, but we don't support that, yet.
+ long returnDecline() {
+ return WriteClientError(
+ m_lpECB,
+ "ISAPI extension can only be invoked to process Shibboleth protocol requests."
+ "Make sure the mapped file extension doesn't match actual content."
+ );
+ }
+ long returnOK() {
+ return HSE_STATUS_SUCCESS;
+ }
+
+ 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) {
+ unsigned int outlen;
+ XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>(CertificateBuf), ccex.CertContext.cbCertEncoded, &outlen);
+ m_certs.push_back(reinterpret_cast<char*>(serialized));
+ XMLString::release(&serialized);
+ }
+ }
+ }
+ return m_certs;
+ }
+
+ // Not used in the extension.
+ 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)
{
- ostringstream threadid;
- threadid << "[" << getpid() << "] shire" << '\0';
- saml::NDC ndc(threadid.str().c_str());
-
- ShibINI& ini = g_Config->getINI();
- string shireError;
- ShibMLP markupProcessor;
+ try {
+ ostringstream threadid;
+ threadid << "[" << getpid() << "] isapi_shib_extension" << '\0';
+ xmltooling::NDC ndc(threadid.str().c_str());
- try
- {
// Determine web site number. This can't really fail, I don't think.
dynabuf buf(128);
- ULONG site_id=0;
GetServerVariable(lpECB,"INSTANCE_ID",buf,10);
- if ((site_id=strtoul(buf,NULL,10))==0)
- return WriteClientError(lpECB,"IIS site instance appears to be invalid.");
-
- // Match site instance to site settings.
- if (site_id>g_Sites.size() || g_Sites[site_id-1].length()==0)
- return WriteClientError(lpECB,"Shibboleth filter not configured for this web site.");
- string& site=g_Sites[site_id-1];
-
- string target_url,application_id;
- get_target_and_appid(lpECB,site.c_str(),target_url,application_id);
-
- if (!ini.get_tag(application_id, "shireError", true, &shireError))
- return WriteClientError(lpECB,"The shireError configuration setting is missing, check configuration.");
-
- string shire_url = target_url;
-
- // Set SHIRE policies.
- SHIREConfig config;
- string tag;
- config.checkIPAddress = (ini.get_tag(application_id,"checkIPAddress",true,&tag) && ShibINI::boolean(tag));
- config.lifetime=config.timeout=0;
- tag.erase();
- if (ini.get_tag(application_id, "authLifetime", true, &tag))
- config.lifetime=strtoul(tag.c_str(),NULL,10);
- tag.erase();
- if (ini.get_tag(application_id, "authTimeout", true, &tag))
- config.timeout=strtoul(tag.c_str(),NULL,10);
-
- // Pull the config data we need to handle the various possible conditions.
- string shib_cookie;
- if (!ini.get_tag(application_id, "cookieName", true, &shib_cookie))
- return WriteClientError(lpECB,"The cookieName configuration setting is missing, check configuration.");
-
- string wayfLocation;
- if (!ini.get_tag(application_id, "wayfURL", true, &wayfLocation))
- return WriteClientError(lpECB,"The wayfURL configuration setting is missing, check configuration.");
-
- bool has_tag = ini.get_tag(application_id, "supportContact", true, &tag);
- markupProcessor.insert("supportContact", has_tag ? tag : "");
- has_tag = ini.get_tag(application_id, "logoLocation", true, &tag);
- markupProcessor.insert("logoLocation", has_tag ? tag : "");
- markupProcessor.insert("requestURL", target_url.c_str());
-
- SHIRE shire(config, shire_url.c_str());
-
- // Process SHIRE POST
- if (ini.get_tag(application_id, "shireSSLOnly", true, &tag) && ShibINI::boolean(tag))
- {
- // Make sure this is SSL, if it should be.
- GetServerVariable(lpECB,"HTTPS",buf,10);
- if (buf!="on")
- throw ShibTargetException(SHIBRPC_OK,"blocked non-SSL access to SHIRE POST processor");
- }
-
- // Make sure this is a POST
- if (stricmp(lpECB->lpszMethod,"POST"))
- throw ShibTargetException(SHIBRPC_OK,"blocked non-POST to SHIRE POST processor");
- // Sure sure this POST is an appropriate content type
- if (!lpECB->lpszContentType || stricmp(lpECB->lpszContentType,"application/x-www-form-urlencoded"))
- throw ShibTargetException(SHIBRPC_OK,"blocked bad content-type to SHIRE POST processor");
-
- // Make sure the "bytes sent" is a reasonable number and that we have all of it.
- if (lpECB->cbTotalBytes > 1024*1024) // 1MB?
- throw ShibTargetException (SHIBRPC_OK,"blocked too-large a post to SHIRE POST processor");
- else if (lpECB->cbTotalBytes>lpECB->cbAvailable)
- throw ShibTargetException (SHIBRPC_OK,"blocked incomplete post to SHIRE POST processor");
-
- // Parse the incoming data.
- HQUERY params=ParseQuery(lpECB);
- if (!params)
- throw ShibTargetException (SHIBRPC_OK,"unable to parse form data");
-
- // Make sure the TARGET parameter exists
- const char* target = QueryValue(params,"TARGET");
- if (!target || *target == '\0')
- throw ShibTargetException(SHIBRPC_OK,"SHIRE POST failed to find TARGET parameter");
-
- // Make sure the SAMLResponse parameter exists
- const char* post = QueryValue(params,"SAMLResponse");
- if (!post || *post == '\0')
- throw ShibTargetException (SHIBRPC_OK,"SHIRE POST failed to find SAMLResponse parameter");
+ // 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.");
- GetServerVariable(lpECB,"REMOTE_ADDR",buf,16);
+ 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");
- // Process the post.
- string cookie;
- RPCError* status = shire.sessionCreate(post,buf,application_id.c_str(),cookie);
-
- if (status->isError()) {
- if (status->isRetryable()) {
- delete status;
- char timebuf[16];
- sprintf(timebuf,"%u",time(NULL));
- string wayf=wayfLocation + "?shire=" + url_encode(shire_url.c_str()) + "&target=" + url_encode(target) +
- "&time=" + timebuf + "&providerId=" + application_id;
- DWORD len=wayf.length();
- if (lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_URL_REDIRECT_RESP,(LPVOID)wayf.c_str(),&len,0))
- return HSE_STATUS_SUCCESS;
- return HSE_STATUS_ERROR;
- }
-
- // Return this error to the user.
- markupProcessor.insert(*status);
- delete status;
- return WriteClientError(lpECB,shireError.c_str(),markupProcessor);
- }
- delete status;
-
- // We've got a good session, set the cookie and redirect to target.
- shib_cookie = "Set-Cookie: " + shib_cookie + '=' + cookie + "; path=/\r\n"
- "Location: " + target + "\r\n"
- "Expires: 01-Jan-1997 12:00:00 GMT\r\n"
- "Cache-Control: private,no-store,no-cache\r\n"
- "Connection: close\r\n";
- HSE_SEND_HEADER_EX_INFO hinfo;
- hinfo.pszStatus="302 Moved";
- hinfo.pszHeader=shib_cookie.c_str();
- hinfo.cchStatus=9;
- hinfo.cchHeader=shib_cookie.length();
- hinfo.fKeepConn=FALSE;
- if (lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER_EX,&hinfo,0,0))
- return HSE_STATUS_SUCCESS;
- }
- catch (ShibTargetException &e) {
- markupProcessor.insert ("errorType", "SHIRE Processing Error");
- markupProcessor.insert ("errorText", e.what());
- markupProcessor.insert ("errorDesc", "An error occurred while processing your request.");
- return WriteClientError(lpECB,shireError.c_str(),markupProcessor);
- }
- catch (...) {
- markupProcessor.insert ("errorType", "SHIRE Processing Error");
- markupProcessor.insert ("errorText", "Unexpected Exception");
- markupProcessor.insert ("errorDesc", "An error occurred while processing your request.");
- return WriteClientError(lpECB,shireError.c_str(),markupProcessor);
}
-
+ catch(bad_alloc) {
+ return WriteClientError(lpECB,"Out of Memory");
+ }
+ catch(long e) {
+ if (e==ERROR_NO_DATA)
+ return WriteClientError(lpECB,"A required variable or header was empty.");
+ else
+ return WriteClientError(lpECB,"Server detected unexpected IIS error.");
+ }
+ catch (exception& e) {
+ LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, e.what());
+ return WriteClientError(lpECB,"Shibboleth Extension caught an exception, check Event Log for details.");
+ }
+ catch(...) {
+ 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;
+ }
+
+ // If we get here we've got an error.
return HSE_STATUS_ERROR;
}
-