X-Git-Url: http://www.project-moonshot.org/gitweb/?a=blobdiff_plain;f=isapi_shib%2Fisapi_shib.cpp;h=f30cab66aa29b5519d74a55a884d6e17b4da5ae1;hb=3ea5b63fd99233bc4aaff07397c5fec840e5a750;hp=f51b0f5ac71a639a9266f75296d3e48b985df5ec;hpb=e29d593e3afe3a1a0a925ab0f5e673a105599014;p=shibboleth%2Fcpp-sp.git diff --git a/isapi_shib/isapi_shib.cpp b/isapi_shib/isapi_shib.cpp index f51b0f5..f30cab6 100644 --- a/isapi_shib/isapi_shib.cpp +++ b/isapi_shib/isapi_shib.cpp @@ -1,50 +1,17 @@ /* - * The Shibboleth License, Version 1. - * Copyright (c) 2002 - * University Corporation for Advanced Internet Development, Inc. - * All rights reserved + * 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 * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * 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 - * 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 @@ -65,6 +32,7 @@ #include #include #include +#include #include #include @@ -89,6 +57,10 @@ namespace { { chLatin_n, chLatin_o, chLatin_r, chLatin_m, chLatin_a, chLatin_l, chLatin_i, chLatin_z, chLatin_e, chLatin_R, chLatin_e, chLatin_q, chLatin_u, chLatin_e, chLatin_s, chLatin_t, chNull }; + static const XMLCh safeHeaderNames[] = + { chLatin_s, chLatin_a, chLatin_f, chLatin_e, chLatin_H, chLatin_e, chLatin_a, chLatin_d, chLatin_e, chLatin_r, + chLatin_N, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chNull + }; static const XMLCh Site[] = { chLatin_S, chLatin_i, chLatin_t, chLatin_e, chNull }; struct site_t { @@ -113,11 +85,16 @@ namespace { string m_scheme,m_port,m_sslport,m_name; set m_aliases; }; - + HINSTANCE g_hinstDLL; ShibTargetConfig* g_Config = NULL; map g_Sites; bool g_bNormalizeRequest = true; + string g_unsetHeaderValue,g_spoofKey; + set g_allowedSchemes; + bool g_checkSpoofing = true; + bool g_catchAll = true; + bool g_bSafeHeaderNames = false; } BOOL LogEvent( @@ -128,7 +105,7 @@ 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); @@ -145,7 +122,7 @@ extern "C" BOOL WINAPI GetExtensionVersion(HSE_VERSION_INFO* pVer) { if (!pVer) return FALSE; - + if (!g_Config) { LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, @@ -173,10 +150,7 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer) return TRUE; } -#ifndef _DEBUG - try - { -#endif + try { LPCSTR schemadir=getenv("SHIBSCHEMAS"); if (!schemadir) schemadir=SHIB_SCHEMAS; @@ -192,24 +166,68 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer) ShibTargetConfig::LocalExtensions | ShibTargetConfig::Logging ); - if (!g_Config->init(schemadir) || !g_Config->load(config)) { + 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 during initialization, check shire log for help."); + "Filter startup failed to load configuration, check native log for help."); return FALSE; } - + // Access the implementation-specifics for site mappings. IConfig* conf=g_Config->getINI(); Locker locker(conf); const IPropertySet* props=conf->getPropertySet("Local"); if (props) { + pair flag=props->getBool("checkSpoofing"); + g_checkSpoofing = !flag.first || flag.second; + flag=props->getBool("catchAll"); + g_catchAll = !flag.first || flag.second; + + pair str=props->getString("unsetHeaderValue"); + if (str.first) + g_unsetHeaderValue = str.second; + + str=props->getString("allowedSchemes"); + if (str.first) { + string schemes=str.second; + unsigned int j=0; + for (unsigned int i=0; i < schemes.length(); i++) { + if (schemes.at(i)==' ') { + g_allowedSchemes.insert(schemes.substr(j, i-j)); + j = i+1; + } + } + g_allowedSchemes.insert(schemes.substr(j, schemes.length()-j)); + } + + if (g_checkSpoofing) { + str = props->getString("spoofKey"); + if (str.first) + g_spoofKey = str.second; + else { + LogEvent(NULL, EVENTLOG_WARNING_TYPE, 2100, NULL, + "Filter generating a pseudorandom anti-spoofing key, consider setting spoofKey yourself."); + srand(time(NULL)); + ostringstream keystr; + keystr << rand() << rand() << rand() << rand(); + g_spoofKey = keystr.str(); + } + } + const DOMElement* impl=saml::XML::getFirstChildElement( props->getElement(),shibtarget::XML::SHIBTARGET_NS,Implementation ); if (impl && (impl=saml::XML::getFirstChildElement(impl,shibtarget::XML::SHIBTARGET_NS,ISAPI))) { - const XMLCh* flag=impl->getAttributeNS(NULL,normalizeRequest); - g_bNormalizeRequest=(!flag || !*flag || *flag==chDigit_1 || *flag==chLatin_t); + const XMLCh* ch=impl->getAttributeNS(NULL,normalizeRequest); + g_bNormalizeRequest=(!ch || !*ch || *ch==chDigit_1 || *ch==chLatin_t); + ch=impl->getAttributeNS(NULL,safeHeaderNames); + g_bSafeHeaderNames=(ch && (*ch==chDigit_1 || *ch==chLatin_t)); impl=saml::XML::getFirstChildElement(impl,shibtarget::XML::SHIBTARGET_NS,Site); while (impl) { auto_ptr_char id(impl->getAttributeNS(NULL,id)); @@ -219,14 +237,15 @@ extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer) } } } -#ifndef _DEBUG + if (g_allowedSchemes.empty()) { + g_allowedSchemes.insert("https"); + g_allowedSchemes.insert("http"); + } } - catch (...) - { + catch (exception&) { 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); @@ -367,8 +386,20 @@ class ShibTargetIsapiF : public ShibTarget PHTTP_FILTER_CONTEXT m_pfc; PHTTP_FILTER_PREPROC_HEADERS m_pn; string m_cookie; + dynabuf m_allhttp; + bool m_firsttime; + + void checkString(const string& s, const char* msg) { + string::const_iterator e = s.end(); + for (string::const_iterator i=s.begin(); i!=e; ++i) { + if (iscntrl(*i)) + throw FatalProfileException(msg); + } + } + public: - ShibTargetIsapiF(PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn, const site_t& site) { + ShibTargetIsapiF(PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn, const site_t& site) + : m_pfc(pfc), m_pn(pn), m_allhttp(4096), m_firsttime(true) { // URL path always come from IIS. dynabuf url(256); @@ -386,7 +417,7 @@ public: strncpy(port,site.m_port.c_str(),10); static_cast(port)[10]=0; } - + // Scheme may come from site def or be derived from IIS. const char* scheme=site.m_scheme.c_str(); if (!scheme || !*scheme || !g_bNormalizeRequest) @@ -404,41 +435,89 @@ public: if (site.m_name!=host && site.m_aliases.find(host)==site.m_aliases.end()) host=site.m_name.c_str(); - init(scheme, host, atoi(port), url, content_type, remote_addr, method); + init(scheme, host, atoi(port), url, content_type, remote_addr, method); + + if (!g_spoofKey.empty()) { + GetHeader(pn, pfc, "ShibSpoofCheck:", url, 32, false); + if (!url.empty() && g_spoofKey == (char*)url) + m_firsttime = false; + } - m_pfc = pfc; - m_pn = pn; + if (!m_firsttime) + log(LogLevelDebug, "ISAPI filter running more than once"); } - ~ShibTargetIsapiF() { } + ~ShibTargetIsapiF() {} virtual void log(ShibLogLevel level, const string &msg) { ShibTarget::log(level,msg); - if (level == LogLevelError) - LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg.c_str()); } virtual string getCookies() const { dynabuf buf(128); GetHeader(m_pn, m_pfc, "Cookie:", buf, 128, false); return buf.empty() ? "" : buf; } - + string makeSafeHeader(const char* rawname) const { + string hdr; + for (; *rawname; ++rawname) { + if (isalnum(*rawname)) + hdr += *rawname; + } + return hdr + ':'; + } virtual void clearHeader(const string &name) { - string hdr = name + ":"; - m_pn->SetHeader(m_pfc, const_cast(hdr.c_str()), ""); + if (g_checkSpoofing && m_firsttime) { + if (m_allhttp.empty()) + GetServerVariable(m_pfc,"ALL_HTTP",m_allhttp,4096); + + // Map to the expected CGI variable name. + string transformed("HTTP_"); + if (g_bSafeHeaderNames) { + string temp = makeSafeHeader(name.c_str()); + for (const char* pch = temp.c_str(); *pch; ++pch) { + if (isalnum(*pch)) + transformed += toupper(*pch); + } + } + else { + for (const char* pch = name.c_str(); *pch; ++pch) + transformed += (isalnum(*pch) ? toupper(*pch) : '_'); + transformed += ':'; + } + + if (strstr(m_allhttp, transformed.c_str())) + throw SAMLException("Attempt to spoof header ($1) was detected.", params(1, transformed.c_str())); + } + if (g_bSafeHeaderNames) { + string hdr = makeSafeHeader(name.c_str()); + m_pn->SetHeader(m_pfc, const_cast(hdr.c_str()), const_cast(g_unsetHeaderValue.c_str())); + } + else if (name == "REMOTE_USER") { + m_pn->SetHeader(m_pfc, "remote-user:", const_cast(g_unsetHeaderValue.c_str())); + m_pn->SetHeader(m_pfc, "remote_user:", const_cast(g_unsetHeaderValue.c_str())); + } + else { + string hdr = name + ':'; + m_pn->SetHeader(m_pfc, const_cast(hdr.c_str()), const_cast(g_unsetHeaderValue.c_str())); + } } virtual void setHeader(const string &name, const string &value) { - string hdr = name + ":"; - m_pn->SetHeader(m_pfc, const_cast(hdr.c_str()), - const_cast(value.c_str())); + string hdr = g_bSafeHeaderNames ? makeSafeHeader(name.c_str()) : (name + ':'); + m_pn->SetHeader(m_pfc, const_cast(hdr.c_str()), const_cast(value.c_str())); } virtual string getHeader(const string &name) { - string hdr = name + ":"; - dynabuf buf(1024); + string hdr = g_bSafeHeaderNames ? makeSafeHeader(name.c_str()) : (name + ':'); + dynabuf buf(256); GetHeader(m_pn, m_pfc, const_cast(hdr.c_str()), buf, 1024, false); - return string(buf); + return string(buf.empty() ? "" : buf); } virtual void setRemoteUser(const string &user) { setHeader(string("remote-user"), user); + if (m_pfc->pFilterContext) { + if (user.empty()) + m_pfc->pFilterContext = NULL; + else if (m_pfc->pFilterContext = m_pfc->AllocMem(m_pfc, sizeof(char) * (user.length() + 1), NULL)) + strcpy(reinterpret_cast(m_pfc->pFilterContext), user.c_str()); + } } virtual string getRemoteUser(void) { return getHeader(string("remote-user")); @@ -448,9 +527,12 @@ public: int code=200, const string& content_type="text/html", const Iterator& headers=EMPTY(header_t)) { + checkString(content_type, "Detected control character in a response header."); string hdr = string ("Connection: close\r\nContent-type: ") + content_type + "\r\n"; while (headers.hasNext()) { const header_t& h=headers.next(); + checkString(h.first, "Detected control character in a response header."); + checkString(h.second, "Detected control character in a response header."); hdr += h.first + ": " + h.second + "\r\n"; } hdr += "\r\n"; @@ -466,6 +548,9 @@ public: return (void*)SF_STATUS_REQ_FINISHED; } virtual void* sendRedirect(const string& url) { + checkString(url, "Detected control character in an attempted redirect."); + if (g_allowedSchemes.find(url.substr(0, url.find(':'))) == g_allowedSchemes.end()) + throw FatalProfileException("Invalid scheme in attempted redirect."); // XXX: Don't support the httpRedirect option, yet. string hdrs=m_cookie + string("Location: ") + url + "\r\n" "Content-Type: text/html\r\n" @@ -512,16 +597,14 @@ 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(pfc->pFilterContext); + ((PHTTP_FILTER_LOG)pvNotification)->pszClientUserName=reinterpret_cast(pfc->pFilterContext); return SF_STATUS_REQ_NEXT_NOTIFICATION; } PHTTP_FILTER_PREPROC_HEADERS pn=(PHTTP_FILTER_PREPROC_HEADERS)pvNotification; - try - { + try { // Determine web site number. This can't really fail, I don't think. dynabuf buf(128); GetServerVariable(pfc,"INSTANCE_ID",buf,10); @@ -530,7 +613,7 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat map::const_iterator map_i=g_Sites.find(static_cast(buf)); if (map_i==g_Sites.end()) return SF_STATUS_REQ_NEXT_NOTIFICATION; - + ostringstream threadid; threadid << "[" << getpid() << "] isapi_shib" << '\0'; saml::NDC ndc(threadid.str().c_str()); @@ -539,6 +622,8 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat // "false" because we don't override the Shib settings pair res = stf.doCheckAuthN(); + if (!g_spoofKey.empty()) + pn->SetHeader(pfc, "ShibSpoofCheck:", const_cast(g_spoofKey.c_str())); if (res.first) return (DWORD)res.second; // "false" because we don't override the Shib settings @@ -557,461 +642,21 @@ extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificat if (e==ERROR_NO_DATA) return WriteClientError(pfc,"A required variable or header was empty."); else - return WriteClientError(pfc,"Server detected unexpected IIS error."); - } -#ifndef _DEBUG - catch(...) { - return WriteClientError(pfc,"Server caught an unknown exception."); - } -#endif - - return WriteClientError(pfc,"Server reached unreachable code, save my walrus!"); -} - - -#if 0 -IRequestMapper::Settings map_request( - PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn, IRequestMapper* mapper, const site_t& site, string& target - ) -{ - // URL path always come from IIS. - dynabuf url(256); - GetHeader(pn,pfc,"url",url,256,false); - - // Port may come from IIS or from site def. - dynabuf port(11); - if (site.m_port.empty() || !g_bNormalizeRequest) - GetServerVariable(pfc,"SERVER_PORT",port,10); - else { - strncpy(port,site.m_port.c_str(),10); - static_cast(port)[10]=0; + return WriteClientError(pfc,"Shibboleth Filter detected unexpected IIS error."); } - - // Scheme may come from site def or be derived from IIS. - const char* scheme=site.m_scheme.c_str(); - if (!scheme || !*scheme || !g_bNormalizeRequest) - scheme=pfc->fIsSecurePort ? "https" : "http"; - - // Start with scheme and hostname. - if (g_bNormalizeRequest) { - target = string(scheme) + "://" + site.m_name; - } - else { - dynabuf name(64); - GetServerVariable(pfc,"SERVER_NAME",name,64); - target = string(scheme) + "://" + static_cast(name); + catch (exception& e) { + LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, e.what()); + return WriteClientError(pfc,"Shibboleth Filter caught an exception, ask administrator to check Event Log for details."); } - - // If port is non-default, append it. - if ((!strcmp(scheme,"http") && port!="80") || (!strcmp(scheme,"https") && port!="443")) - target = target + ':' + static_cast(port); - - // Append path. - if (!url.empty()) - target+=static_cast(url); - - return mapper->getSettingsFromParsedURL(scheme,site.m_name.c_str(),strtoul(port,NULL,10),url); -} - -DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const IApplication* app, const char* page, ShibMLP& mlp) -{ - const IPropertySet* props=app->getPropertySet("Errors"); - if (props) { - pair p=props->getString(page); - if (p.first) { - ifstream infile(p.second); - if (!infile.fail()) { - const char* res = mlp.run(infile,props); - if (res) { - 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); - DWORD resplen=strlen(res); - pfc->WriteClient(pfc,(LPVOID)res,&resplen,0); - return SF_STATUS_REQ_FINISHED; - } - } - } - } - - LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Filter unable to open error template."); - return WriteClientError(pfc,"Unable to open error template, check settings."); -} - -DWORD WriteRedirectPage(PHTTP_FILTER_CONTEXT pfc, const IApplication* app, const char* file, ShibMLP& mlp, const char* headers=NULL) -{ - ifstream infile(file); - if (!infile.fail()) { - const char* res = mlp.run(infile,app->getPropertySet("Errors")); - if (res) { - char buf[255]; - sprintf(buf,"Content-Length: %u\r\nContent-Type: text/html\r\n\r\n",strlen(res)); - if (headers) { - string h(headers); - h+=buf; - pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",(DWORD)h.c_str(),0); - } - else - pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",(DWORD)buf,0); - DWORD resplen=strlen(res); - pfc->WriteClient(pfc,(LPVOID)res,&resplen,0); - return SF_STATUS_REQ_FINISHED; - } - } - LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Extension unable to open redirect template."); - return WriteClientError(pfc,"Unable to open redirect template, check settings."); -} - -extern "C" DWORD WINAPI HttpFilterProc(PHTTP_FILTER_CONTEXT pfc, DWORD notificationType, LPVOID pvNotification) -{ - // Is this a log notification? - if (notificationType==SF_NOTIFY_LOG) - { - if (pfc->pFilterContext) - ((PHTTP_FILTER_LOG)pvNotification)->pszClientUserName=static_cast(pfc->pFilterContext); - return SF_STATUS_REQ_NEXT_NOTIFICATION; - } - - PHTTP_FILTER_PREPROC_HEADERS pn=(PHTTP_FILTER_PREPROC_HEADERS)pvNotification; - try - { - // Determine web site number. This can't really fail, I don't think. - dynabuf buf(128); - GetServerVariable(pfc,"INSTANCE_ID",buf,10); - - // Match site instance to host name, skip if no match. - map::const_iterator map_i=g_Sites.find(static_cast(buf)); - if (map_i==g_Sites.end()) - return SF_STATUS_REQ_NEXT_NOTIFICATION; - - ostringstream threadid; - threadid << "[" << getpid() << "] isapi_shib" << '\0'; - saml::NDC ndc(threadid.str().c_str()); - - // We lock the configuration system for the duration. - IConfig* conf=g_Config->getINI(); - Locker locker(conf); - - // Map request to application and content settings. - string targeturl; - IRequestMapper* mapper=conf->getRequestMapper(); - Locker locker2(mapper); - IRequestMapper::Settings settings=map_request(pfc,pn,mapper,map_i->second,targeturl); - pair application_id=settings.first->getString("applicationId"); - const IApplication* application=conf->getApplication(application_id.second); - if (!application) - return WriteClientError(pfc,"Unable to map request to application settings, check configuration."); - - // Declare SHIRE object for this request. - SHIRE shire(application); - - const char* shireURL=shire.getShireURL(targeturl.c_str()); - if (!shireURL) - return WriteClientError(pfc,"Unable to map request to proper shireURL setting, check configuration."); - - // If the user is accessing the SHIRE acceptance point, pass it on. - if (targeturl.find(shireURL)!=string::npos) - return SF_STATUS_REQ_NEXT_NOTIFICATION; - - // Now check the policy for this request. - pair requireSession=settings.first->getBool("requireSession"); - pair shib_cookie=shire.getCookieNameProps(); - pair httpRedirects=application->getPropertySet("Sessions")->getBool("httpRedirects"); - pair redirectPage=application->getPropertySet("Sessions")->getString("redirectPage"); - if (httpRedirects.first && !httpRedirects.second && !redirectPage.first) - return WriteClientError(pfc,"HTML-based redirection requires a redirectPage property."); - - // Check for session 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.first))) { - session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */ - char* cookieend=strchr(session_id,';'); - if (cookieend) - *cookieend = '\0'; /* Ignore anyting after a ; */ - } - - if (!session_id || !*session_id) { - // If no session required, bail now. - if (!requireSession.second) - return SF_STATUS_REQ_NEXT_NOTIFICATION; - - // No acceptable cookie, and we require a session. Generate an AuthnRequest. - const char* areq = shire.getAuthnRequest(targeturl.c_str()); - if (!httpRedirects.first || httpRedirects.second) { - string hdrs=string("Location: ") + areq + "\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\r\n"; - pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"302 Please Wait",(DWORD)hdrs.c_str(),0); - static const char* redmsg="Redirecting..."; - DWORD resplen=40; - pfc->WriteClient(pfc,(LPVOID)redmsg,&resplen,0); - return SF_STATUS_REQ_FINISHED; - } - else { - ShibMLP markupProcessor; - markupProcessor.insert("requestURL",areq); - return WriteRedirectPage(pfc, application, redirectPage.second, markupProcessor); - } - } - - // Make sure this session is still valid. - RPCError* status = NULL; - ShibMLP markupProcessor; - markupProcessor.insert("requestURL", targeturl); - - dynabuf abuf(16); - GetServerVariable(pfc,"REMOTE_ADDR",abuf,16); - try { - status = shire.sessionIsValid(session_id, abuf); - } - catch (ShibTargetException &e) { - markupProcessor.insert("errorType", "Session Processing Error"); - markupProcessor.insert("errorText", e.what()); - markupProcessor.insert("errorDesc", "An error occurred while processing your request."); - return WriteClientError(pfc, application, "shire", markupProcessor); - } -#ifndef _DEBUG - catch (...) { - markupProcessor.insert("errorType", "Session Processing Error"); - markupProcessor.insert("errorText", "Unexpected Exception"); - markupProcessor.insert("errorDesc", "An error occurred while processing your request."); - return WriteClientError(pfc, application, "shire", markupProcessor); - } -#endif - - // Check the status - if (status->isError()) { - if (!requireSession.second) - return SF_STATUS_REQ_NEXT_NOTIFICATION; - else if (status->isRetryable()) { - // Oops, session is invalid. Generate AuthnRequest. - delete status; - const char* areq = shire.getAuthnRequest(targeturl.c_str()); - if (!httpRedirects.first || httpRedirects.second) { - string hdrs=string("Location: ") + areq + "\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\r\n"; - pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"302 Please Wait",(DWORD)hdrs.c_str(),0); - static const char* redmsg="Redirecting..."; - DWORD resplen=40; - pfc->WriteClient(pfc,(LPVOID)redmsg,&resplen,0); - return SF_STATUS_REQ_FINISHED; - } - else { - markupProcessor.insert("requestURL",areq); - return WriteRedirectPage(pfc, application, redirectPage.second, markupProcessor); - } - } - else { - // return the error page to the user - markupProcessor.insert(*status); - delete status; - return WriteClientError(pfc, application, "shire", markupProcessor); - } - } - delete status; - - // Move to RM phase. - RM rm(application); - vector assertions; - SAMLAuthenticationStatement* sso_statement=NULL; - - try { - status = rm.getAssertions(session_id, abuf, assertions, &sso_statement); - } - catch (ShibTargetException &e) { - markupProcessor.insert("errorType", "Attribute Processing Error"); - markupProcessor.insert("errorText", e.what()); - markupProcessor.insert("errorDesc", "An error occurred while processing your request."); - return WriteClientError(pfc, application, "rm", markupProcessor); - } - #ifndef _DEBUG - catch (...) { - markupProcessor.insert("errorType", "Attribute Processing Error"); - markupProcessor.insert("errorText", "Unexpected Exception"); - markupProcessor.insert("errorDesc", "An error occurred while processing your request."); - return WriteClientError(pfc, application, "rm", markupProcessor); - } - #endif - - if (status->isError()) { - markupProcessor.insert(*status); - delete status; - return WriteClientError(pfc, application, "rm", markupProcessor); - } - delete status; - - // Do we have an access control plugin? - if (settings.second) { - Locker acllock(settings.second); - if (!settings.second->authorized(*sso_statement,assertions)) { - for (int k = 0; k < assertions.size(); k++) - delete assertions[k]; - delete sso_statement; - return WriteClientError(pfc, application, "access", markupProcessor); - } - } - - // Get the AAP providers, which contain the attribute policy info. - Iterator provs=application->getAAPProviders(); - - // Clear out the list of mapped attributes - while (provs.hasNext()) { - IAAP* aap=provs.next(); - aap->lock(); - try { - Iterator rules=aap->getAttributeRules(); - while (rules.hasNext()) { - const char* header=rules.next()->getHeader(); - if (header) { - string hname=string(header) + ':'; - pn->SetHeader(pfc,const_cast(hname.c_str()),""); - } - } - } - catch(...) { - aap->unlock(); - for (int k = 0; k < assertions.size(); k++) - delete assertions[k]; - delete sso_statement; - markupProcessor.insert("errorType", "Attribute Processing Error"); - markupProcessor.insert("errorText", "Unexpected Exception"); - markupProcessor.insert("errorDesc", "An error occurred while processing your request."); - return WriteClientError(pfc, application, "rm", markupProcessor); - } - aap->unlock(); - } - provs.reset(); - - // Maybe export the first assertion. - pn->SetHeader(pfc,"remote-user:",""); - pn->SetHeader(pfc,"Shib-Attributes:",""); - pair exp=settings.first->getBool("exportAssertion"); - if (exp.first && exp.second && assertions.size()) { - 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(assertion.c_str())); - } - - pn->SetHeader(pfc,"Shib-Origin-Site:",""); - pn->SetHeader(pfc,"Shib-Authentication-Method:",""); - pn->SetHeader(pfc,"Shib-NameIdentifier-Format:",""); - - // Export the SAML AuthnMethod and the origin site name. - auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier()); - auto_ptr_char am(sso_statement->getAuthMethod()); - pn->SetHeader(pfc,"Shib-Origin-Site:", const_cast(os.get())); - pn->SetHeader(pfc,"Shib-Authentication-Method:", const_cast(am.get())); - - // Export NameID? - AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI); - if (!wrapper.fail() && wrapper->getHeader()) { - auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat()); - auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName()); - pn->SetHeader(pfc,"Shib-NameIdentifier-Format:",const_cast(form.get())); - if (!strcmp(wrapper->getHeader(),"REMOTE_USER")) { - char* principal=const_cast(nameid.get()); - pn->SetHeader(pfc,"remote-user:",principal); - pfc->pFilterContext=pfc->AllocMem(pfc,strlen(principal)+1,0); - if (pfc->pFilterContext) - strcpy(static_cast(pfc->pFilterContext),principal); - } - else { - string hname=string(wrapper->getHeader()) + ':'; - pn->SetHeader(pfc,const_cast(wrapper->getHeader()),const_cast(nameid.get())); - } - } - - pn->SetHeader(pfc,"Shib-Application-ID:",""); - pn->SetHeader(pfc,"Shib-Application-ID:",const_cast(application_id.second)); - - // Export the attributes. - Iterator a_iter(assertions); - while (a_iter.hasNext()) { - SAMLAssertion* assert=a_iter.next(); - Iterator statements=assert->getStatements(); - while (statements.hasNext()) { - SAMLAttributeStatement* astate=dynamic_cast(statements.next()); - if (!astate) - continue; - Iterator attrs=astate->getAttributes(); - while (attrs.hasNext()) { - SAMLAttribute* attr=attrs.next(); - - // Are we supposed to export it? - AAP wrapper(provs,attr->getName(),attr->getNamespace()); - if (wrapper.fail() || !wrapper->getHeader()) - continue; - - Iterator vals=attr->getSingleByteValues(); - if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext()) { - char* principal=const_cast(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(pfc->pFilterContext),principal); - } - else { - int it=0; - string header; - string hname=string(wrapper->getHeader()) + ':'; - GetHeader(pn,pfc,const_cast(hname.c_str()),buf,256,false); - if (!buf.empty()) { - header=buf; - it++; - } - for (; 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; - } - pn->SetHeader(pfc,const_cast(hname.c_str()),const_cast(header.c_str())); - } - } - } - } - - // clean up memory - for (int k = 0; k < assertions.size(); k++) - delete assertions[k]; - delete sso_statement; - - return SF_STATUS_REQ_NEXT_NOTIFICATION; - } - catch(bad_alloc) { - return WriteClientError(pfc,"Out of Memory"); - } - catch(DWORD 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."); - } -#ifndef _DEBUG catch(...) { - return WriteClientError(pfc,"Server caught an unknown exception."); + if (g_catchAll) + return WriteClientError(pfc,"Shibboleth Filter caught an unknown exception."); + throw; } -#endif - return WriteClientError(pfc,"Server reached unreachable code, save my walrus!"); + return WriteClientError(pfc,"Shibboleth Filter reached unreachable code, save my walrus!"); } -#endif // 0 + /****************************************************************************/ // ISAPI Extension @@ -1037,7 +682,15 @@ class ShibTargetIsapiE : public ShibTarget { LPEXTENSION_CONTROL_BLOCK m_lpECB; string m_cookie; - + + void checkString(const string& s, const char* msg) { + string::const_iterator e = s.end(); + for (string::const_iterator i=s.begin(); i!=e; ++i) { + if (iscntrl(*i)) + throw FatalProfileException(msg); + } + } + public: ShibTargetIsapiE(LPEXTENSION_CONTROL_BLOCK lpECB, const site_t& site) { dynabuf ssl(5); @@ -1082,31 +735,34 @@ 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 fullurl; - + // 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. fullurl=lpECB->lpszPathInfo; else { - fullurl+=url; + fullurl = url; fullurl+=lpECB->lpszPathInfo; } } - + else { + fullurl = url; + } + // For consistency with Apache, let's add the query string. if (lpECB->lpszQueryString && *(lpECB->lpszQueryString)) { fullurl+='?'; @@ -1120,8 +776,6 @@ public: virtual void log(ShibLogLevel level, const string &msg) { ShibTarget::log(level,msg); - if (level == LogLevelError) - LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg.c_str()); } virtual string getCookies() const { dynabuf buf(128); @@ -1138,10 +792,10 @@ public: virtual string getPostData(void) { if (m_lpECB->cbTotalBytes > 1024*1024) // 1MB? throw FatalProfileException("Blocked too-large a submission to profile endpoint."); - else if (m_lpECB->cbTotalBytes != m_lpECB->cbAvailable) { - string cgistr; + else if (m_lpECB->cbTotalBytes > m_lpECB->cbAvailable) { + string cgistr(reinterpret_cast(m_lpECB->lpbData),m_lpECB->cbAvailable); char buf[8192]; - DWORD datalen=m_lpECB->cbTotalBytes; + DWORD datalen=m_lpECB->cbTotalBytes - m_lpECB->cbAvailable; while (datalen) { DWORD buflen=8192; BOOL ret = m_lpECB->ReadClient(m_lpECB->ConnID, buf, &buflen); @@ -1152,16 +806,20 @@ public: } return cgistr; } - else + else { return string(reinterpret_cast(m_lpECB->lpbData),m_lpECB->cbAvailable); + } } virtual void* sendPage( const string &msg, int code=200, const string& content_type="text/html", const Iterator& headers=EMPTY(header_t)) { - string hdr = string ("Connection: close\r\nContent-type: ") + content_type + "\r\n"; + checkString(content_type, "Detected control character in a response header."); + string hdr = m_cookie + "Connection: close\r\nContent-type: " + content_type + "\r\n"; for (int k = 0; k < headers.size(); k++) { + checkString(headers[k].first, "Detected control character in a response header."); + checkString(headers[k].second, "Detected control character in a response header."); hdr += headers[k].first + ": " + headers[k].second + "\r\n"; } hdr += "\r\n"; @@ -1178,6 +836,9 @@ public: } virtual void* sendRedirect(const string& url) { // XXX: Don't support the httpRedirect option, yet. + checkString(url, "Detected control character in an attempted redirect."); + if (g_allowedSchemes.find(url.substr(0, url.find(':'))) == g_allowedSchemes.end()) + throw FatalProfileException("Invalid scheme in attempted redirect."); string hdrs = m_cookie + "Location: " + url + "\r\n" "Content-Type: text/html\r\n" "Content-Length: 40\r\n" @@ -1209,8 +870,6 @@ public: extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB) { - string targeturl; - const IApplication* application=NULL; try { ostringstream threadid; threadid << "[" << getpid() << "] isapi_shib_extension" << '\0'; @@ -1228,7 +887,7 @@ extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB) ShibTargetIsapiE ste(lpECB, map_i->second); pair res = ste.doHandler(); if (res.first) return (DWORD)res.second; - + return WriteClientError(lpECB, "Shibboleth Extension failed to process request"); } @@ -1241,333 +900,16 @@ extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB) else return WriteClientError(lpECB,"Server detected unexpected IIS error."); } -#ifndef _DEBUG + 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(...) { - return WriteClientError(lpECB,"Server caught an unknown exception."); + if (g_catchAll) + return WriteClientError(lpECB,"Shibboleth Extension caught an unknown exception."); + throw; } -#endif // If we get here we've got an error. return HSE_STATUS_ERROR; } - -#if 0 -IRequestMapper::Settings map_request( - LPEXTENSION_CONTROL_BLOCK lpECB, IRequestMapper* mapper, const site_t& site, string& target - ) -{ - dynabuf ssl(5); - GetServerVariable(lpECB,"HTTPS",ssl,5); - bool SSL=(ssl=="on" || ssl=="ON"); - - // 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 (site.m_port.empty() || !g_bNormalizeRequest) - GetServerVariable(lpECB,"SERVER_PORT",port,10); - else { - strncpy(port,site.m_port.c_str(),10); - static_cast(port)[10]=0; - } - - // Scheme may come from site def or be derived from IIS. - const char* scheme=site.m_scheme.c_str(); - if (!scheme || !*scheme || !g_bNormalizeRequest) { - scheme = SSL ? "https" : "http"; - } - - // Start with scheme and hostname. - if (g_bNormalizeRequest) { - target = string(scheme) + "://" + site.m_name; - } - else { - dynabuf name(64); - GetServerVariable(lpECB,"SERVER_NAME",name,64); - target = string(scheme) + "://" + static_cast(name); - } - - // If port is non-default, append it. - if ((!strcmp(scheme,"http") && port!="80") || (!strcmp(scheme,"https") && port!="443")) - target = target + ':' + static_cast(port); - - // Append path. - if (!url.empty()) - target+=static_cast(url); - - return mapper->getSettingsFromParsedURL(scheme,site.m_name.c_str(),strtoul(port,NULL,10),url); -} - -DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const IApplication* app, const char* page, ShibMLP& mlp) -{ - const IPropertySet* props=app->getPropertySet("Errors"); - if (props) { - pair p=props->getString(page); - if (p.first) { - ifstream infile(p.second); - if (!infile.fail()) { - const char* res = mlp.run(infile,props); - if (res) { - 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); - DWORD resplen=strlen(res); - lpECB->WriteClient(lpECB->ConnID,(LPVOID)res,&resplen,0); - return HSE_STATUS_SUCCESS; - } - } - } - } - LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Extension unable to open error template."); - return WriteClientError(lpECB,"Unable to open error template, check settings."); -} - -DWORD WriteRedirectPage(LPEXTENSION_CONTROL_BLOCK lpECB, const IApplication* app, const char* file, ShibMLP& mlp, const char* headers=NULL) -{ - ifstream infile(file); - if (!infile.fail()) { - const char* res = mlp.run(infile,app->getPropertySet("Errors")); - if (res) { - char buf[255]; - sprintf(buf,"Content-Length: %u\r\nContent-Type: text/html\r\n\r\n",strlen(res)); - if (headers) { - string h(headers); - h+=buf; - lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"200 OK",0,(LPDWORD)h.c_str()); - } - else - lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"200 OK",0,(LPDWORD)buf); - DWORD resplen=strlen(res); - lpECB->WriteClient(lpECB->ConnID,(LPVOID)res,&resplen,0); - return HSE_STATUS_SUCCESS; - } - } - LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Extension unable to open redirect template."); - return WriteClientError(lpECB,"Unable to open redirect template, check settings."); -} - -extern "C" DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK lpECB) -{ - string targeturl; - const IApplication* application=NULL; - try - { - ostringstream threadid; - threadid << "[" << getpid() << "] shire_handler" << '\0'; - saml::NDC ndc(threadid.str().c_str()); - - // Determine web site number. This can't really fail, I don't think. - dynabuf buf(128); - GetServerVariable(lpECB,"INSTANCE_ID",buf,10); - - // Match site instance to host name, skip if no match. - map::const_iterator map_i=g_Sites.find(static_cast(buf)); - if (map_i==g_Sites.end()) - return WriteClientError(lpECB,"Shibboleth filter not configured for this web site."); - - // We lock the configuration system for the duration. - IConfig* conf=g_Config->getINI(); - Locker locker(conf); - - // Map request to application and content settings. - IRequestMapper* mapper=conf->getRequestMapper(); - Locker locker2(mapper); - IRequestMapper::Settings settings=map_request(lpECB,mapper,map_i->second,targeturl); - pair application_id=settings.first->getString("applicationId"); - application=conf->getApplication(application_id.second); - const IPropertySet* sessionProps=application ? application->getPropertySet("Sessions") : NULL; - if (!application || !sessionProps) - return WriteClientError(lpECB,"Unable to map request to application session settings, check configuration."); - - SHIRE shire(application); - - const char* shireURL=shire.getShireURL(targeturl.c_str()); - if (!shireURL) - return WriteClientError(lpECB,"Unable to map request to proper shireURL setting, check configuration."); - - // Make sure we only process the SHIRE requests. - if (!strstr(targeturl.c_str(),shireURL)) - return WriteClientError(lpECB,"ISAPI extension can only be invoked to process incoming sessions." - "Make sure the mapped file extension doesn't match actual content."); - - pair shib_cookie=shire.getCookieNameProps(); - - // Make sure this is SSL, if it should be - pair shireSSL=sessionProps->getBool("shireSSL"); - if (!shireSSL.first || shireSSL.second) { - GetServerVariable(lpECB,"HTTPS",buf,10); - if (buf!="on") - throw ShibTargetException(SHIBRPC_OK,"blocked non-SSL access to SHIRE POST processor"); - } - - pair httpRedirects=sessionProps->getBool("httpRedirects"); - pair redirectPage=sessionProps->getString("redirectPage"); - if (httpRedirects.first && !httpRedirects.second && !redirectPage.first) - return WriteClientError(lpECB,"HTML-based redirection requires a redirectPage property."); - - // Check for Mac web browser - /* - bool bSafari=false; - dynabuf agent(64); - GetServerVariable(lpECB,"HTTP_USER_AGENT",agent,64); - if (strstr(agent,"AppleWebKit/")) - bSafari=true; - */ - - // If this is a GET, we manufacture an AuthnRequest. - if (!stricmp(lpECB->lpszMethod,"GET")) { - const char* areq=lpECB->lpszQueryString ? shire.getLazyAuthnRequest(lpECB->lpszQueryString) : NULL; - if (!areq) - throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session"); - if (!httpRedirects.first || httpRedirects.second) { - string hdrs=string("Location: ") + areq + "\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\r\n"; - lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"302 Moved",0,(LPDWORD)hdrs.c_str()); - static const char* redmsg="Redirecting..."; - DWORD resplen=40; - lpECB->WriteClient(lpECB->ConnID,(LPVOID)redmsg,&resplen,HSE_IO_SYNC); - return HSE_STATUS_SUCCESS; - } - else { - ShibMLP markupProcessor; - markupProcessor.insert("requestURL",areq); - return WriteRedirectPage(lpECB, application, redirectPage.second, markupProcessor); - } - } - else 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"); - - // Read the data. - pair elements=pair(NULL,NULL); - 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) { - string cgistr; - char buf[8192]; - DWORD datalen=lpECB->cbTotalBytes; - while (datalen) { - DWORD buflen=8192; - BOOL ret=lpECB->ReadClient(lpECB->ConnID,buf,&buflen); - if (!ret || !buflen) - throw ShibTargetException(SHIBRPC_OK,"error reading POST data from browser"); - cgistr.append(buf,buflen); - datalen-=buflen; - } - elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length()); - } - else - elements=shire.getFormSubmission(reinterpret_cast(lpECB->lpbData),lpECB->cbAvailable); - - // Make sure the SAML Response parameter exists - if (!elements.first || !*elements.first) - throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element"); - - // Make sure the target parameter exists - if (!elements.second || !*elements.second) - throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element"); - - GetServerVariable(lpECB,"REMOTE_ADDR",buf,16); - - // Process the post. - string cookie; - RPCError* status=NULL; - ShibMLP markupProcessor; - markupProcessor.insert("requestURL", targeturl.c_str()); - try { - status = shire.sessionCreate(elements.first,buf,cookie); - } - catch (ShibTargetException &e) { - markupProcessor.insert("errorType", "Session Creation Service Error"); - markupProcessor.insert("errorText", e.what()); - markupProcessor.insert("errorDesc", "An error occurred while processing your request."); - return WriteClientError(lpECB, application, "shire", markupProcessor); - } -#ifndef _DEBUG - catch (...) { - markupProcessor.insert("errorType", "Session Creation Service Error"); - markupProcessor.insert("errorText", "Unexpected Exception"); - markupProcessor.insert("errorDesc", "An error occurred while processing your request."); - return WriteClientError(lpECB, application, "shire", markupProcessor); - } -#endif - - if (status->isError()) { - if (status->isRetryable()) { - delete status; - const char* loc=shire.getAuthnRequest(elements.second); - if (!httpRedirects.first || httpRedirects.second) { - string hdrs=string("Location: ") + loc + "\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\r\n"; - lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"302 Moved",0,(LPDWORD)hdrs.c_str()); - static const char* redmsg="Redirecting..."; - DWORD resplen=40; - lpECB->WriteClient(lpECB->ConnID,(LPVOID)redmsg,&resplen,HSE_IO_SYNC); - return HSE_STATUS_SUCCESS; - } - else { - markupProcessor.insert("requestURL",loc); - return WriteRedirectPage(lpECB, application, redirectPage.second, markupProcessor); - } - } - - // Return this error to the user. - markupProcessor.insert(*status); - delete status; - return WriteClientError(lpECB,application,"shire",markupProcessor); - } - delete status; - - // We've got a good session, set the cookie and redirect to target. - cookie = string("Set-Cookie: ") + shib_cookie.first + '=' + cookie + shib_cookie.second + "\r\n" - "Expires: 01-Jan-1997 12:00:00 GMT\r\n" - "Cache-Control: private,no-store,no-cache\r\n"; - if (!httpRedirects.first || httpRedirects.second) { - cookie=cookie + "Content-Type: text/html\r\nLocation: " + elements.second + "\r\nContent-Length: 40\r\n\r\n"; - lpECB->ServerSupportFunction(lpECB->ConnID,HSE_REQ_SEND_RESPONSE_HEADER,"302 Moved",0,(LPDWORD)cookie.c_str()); - static const char* redmsg="Redirecting..."; - DWORD resplen=40; - lpECB->WriteClient(lpECB->ConnID,(LPVOID)redmsg,&resplen,HSE_IO_SYNC); - return HSE_STATUS_SUCCESS; - } - else { - markupProcessor.insert("requestURL",elements.second); - return WriteRedirectPage(lpECB, application, redirectPage.second, markupProcessor, cookie.c_str()); - } - } - catch (ShibTargetException &e) { - if (application) { - ShibMLP markupProcessor; - markupProcessor.insert("requestURL", targeturl.c_str()); - markupProcessor.insert("errorType", "Session Creation Service Error"); - markupProcessor.insert("errorText", e.what()); - markupProcessor.insert("errorDesc", "An error occurred while processing your request."); - return WriteClientError(lpECB,application,"shire",markupProcessor); - } - } -#ifndef _DEBUG - catch (...) { - if (application) { - ShibMLP markupProcessor; - markupProcessor.insert("requestURL", targeturl.c_str()); - markupProcessor.insert("errorType", "Session Creation Service Error"); - markupProcessor.insert("errorText", "Unexpected Exception"); - markupProcessor.insert("errorDesc", "An error occurred while processing your request."); - return WriteClientError(lpECB,application,"shire",markupProcessor); - } - } -#endif - - return HSE_STATUS_ERROR; -} -#endif // 0