8/23/02
*/
-#include <windows.h>
-#include <httpfilt.h>
+#include "config_win32.h"
// SAML Runtime
-#include <saml.h>
-#include <shib.h>
-#include <eduPerson.h>
+#include <saml/saml.h>
+#include <shib/shib.h>
+#include <shib/shib-threads.h>
+#include <shib-target/shib-target.h>
#include <log4cpp/Category.hh>
-#include <log4cpp/PropertyConfigurator.hh>
-#include <xercesc/util/Base64.hpp>
#include <ctime>
-#include <strstream>
+#include <fstream>
+#include <sstream>
#include <stdexcept>
+#include <httpfilt.h>
+#include <httpext.h>
+
using namespace std;
using namespace log4cpp;
using namespace saml;
using namespace shibboleth;
-using namespace eduPerson;
-
-class CCacheEntry;
-class CCache
-{
-public:
- CCache();
- ~CCache();
-
- SAMLBinding* getBinding(const XMLCh* bindingProt);
- CCacheEntry* find(const char* key);
- void insert(const char* key, CCacheEntry* entry);
- void remove(const char* key);
- void sweep(time_t lifetime);
-
- bool lock() { EnterCriticalSection(&m_lock); return true; }
- void unlock() { LeaveCriticalSection(&m_lock); }
-
-private:
- SAMLBinding* m_SAMLBinding;
- map<string,CCacheEntry*> m_hashtable;
- CRITICAL_SECTION m_lock;
-};
-
-// Per-website global structure
-struct settings_t
-{
- settings_t();
- string g_CookieName; // name of authentication token
- string g_WAYFLocation; // URL of WAYF service
- string g_GarbageCollector; // URL of cache garbage collection service
- string g_SHIRELocation; // URL of SHIRE acceptance point
- string g_SHIRESessionPath; // path to storage for sessions
- vector<string> g_MustContain; // simple URL matching string array
- bool g_bSSLOnly; // only over SSL?
- time_t g_Lifetime; // maximum token lifetime
- time_t g_Timeout; // maximum time between uses
- bool g_bCheckAddress; // validate IP addresses?
- bool g_bExportAssertion; // export SAML assertion to header?
- CCache g_AuthCache; // local auth cache
-};
-
-settings_t::settings_t()
-{
- g_bSSLOnly=true;
- g_Lifetime=7200;
- g_Timeout=3600;
- g_bCheckAddress=true;
- g_bExportAssertion=false;
-}
-
-class CCacheEntry
-{
-public:
- CCacheEntry(const char* sessionFile);
- ~CCacheEntry();
-
- SAMLAuthorityBinding* getBinding() { return m_binding; }
- Iterator<SAMLAttribute*> getAttributes(const char* resource_url, settings_t* pSite);
- const XMLByte* getSerializedAssertion(const char* resource_url, settings_t* pSite);
- bool isSessionValid(time_t lifetime, time_t timeout);
- const XMLCh* getHandle() { return m_handle.c_str(); }
- const XMLCh* getOriginSite() { return m_originSite.c_str(); }
- const char* getClientAddress() { return m_clientAddress.c_str(); }
-
-private:
- void populate(const char* resource_url, settings_t* pSite);
-
- xstring m_originSite;
- xstring m_handle;
- SAMLAuthorityBinding* m_binding;
- string m_clientAddress;
- SAMLResponse* m_response;
- SAMLAssertion* m_assertion;
- time_t m_sessionCreated;
- time_t m_lastAccess;
- XMLByte* m_serialized;
-
- static saml::QName g_authorityKind;
- static saml::QName g_respondWith;
- friend class CCache;
-};
-
-// static members
-saml::QName CCacheEntry::g_authorityKind(saml::XML::SAMLP_NS,L(AttributeQuery));
-saml::QName CCacheEntry::g_respondWith(saml::XML::SAML_NS,L(AttributeStatement));
-
-CCache::CCache()
-{
- m_SAMLBinding=SAMLBindingFactory::getInstance();
- InitializeCriticalSection(&m_lock);
-}
-
-CCache::~CCache()
-{
- DeleteCriticalSection(&m_lock);
- delete m_SAMLBinding;
- for (map<string,CCacheEntry*>::iterator i=m_hashtable.begin(); i!=m_hashtable.end(); i++)
- delete i->second;
-}
-
-SAMLBinding* CCache::getBinding(const XMLCh* bindingProt)
-{
- if (!XMLString::compareString(bindingProt,SAMLBinding::SAML_SOAP_HTTPS))
- return m_SAMLBinding;
- return NULL;
-}
-
-CCacheEntry* CCache::find(const char* key)
-{
- map<string,CCacheEntry*>::const_iterator i=m_hashtable.find(key);
- if (i==m_hashtable.end())
- return NULL;
- return i->second;
-}
-
-void CCache::insert(const char* key, CCacheEntry* entry)
-{
- m_hashtable[key]=entry;
-}
-
-void CCache::remove(const char* key)
-{
- m_hashtable.erase(key);
-}
-
-void CCache::sweep(time_t lifetime)
-{
- time_t now=time(NULL);
- for (map<string,CCacheEntry*>::iterator i=m_hashtable.begin(); i!=m_hashtable.end();)
- {
- if (lifetime > 0 && now > i->second->m_sessionCreated+lifetime)
- {
- delete i->second;
- i=m_hashtable.erase(i);
- }
- else
- i++;
- }
-}
-
-CCacheEntry::CCacheEntry(const char* sessionFile)
- : m_binding(NULL), m_assertion(NULL), m_response(NULL), m_lastAccess(0), m_sessionCreated(0), m_serialized(NULL)
-{
- FILE* f;
- char line[1024];
- const char* token = NULL;
- char* w = NULL;
- auto_ptr<XMLCh> binding,location;
+using namespace shibtarget;
- if (!(f=fopen(sessionFile,"r")))
- {
- fprintf(stderr,"CCacheEntry() could not open session file: %s",sessionFile);
- throw runtime_error("CCacheEntry() could not open session file");
- }
-
- while (fgets(line,1024,f))
- {
- if ((*line=='#') || (!*line))
- continue;
- token = line;
- w=strchr(token,'=');
- if (!w)
- continue;
- *w++=0;
- if (w[strlen(w)-1]=='\n')
- w[strlen(w)-1]=0;
-
- if (!strcmp("Domain",token))
- {
- auto_ptr<XMLCh> origin(XMLString::transcode(w));
- m_originSite=origin.get();
- }
- else if (!strcmp("Handle",token))
+// globals
+namespace {
+ static const XMLCh name[] = { chLatin_n, chLatin_a, chLatin_m, chLatin_e, chNull };
+ static const XMLCh port[] = { chLatin_p, chLatin_o, chLatin_r, chLatin_t, chNull };
+ static const XMLCh scheme[] = { chLatin_s, chLatin_c, chLatin_h, chLatin_e, chLatin_m, chLatin_e, chNull };
+ static const XMLCh id[] = { chLatin_i, chLatin_d, chNull };
+ static const XMLCh Implementation[] =
+ { chLatin_I, chLatin_m, chLatin_p, chLatin_l, chLatin_e, chLatin_m, chLatin_e, chLatin_n, chLatin_t, chLatin_a, chLatin_t, chLatin_i, chLatin_o, chLatin_n, chNull };
+ static const XMLCh ISAPI[] = { chLatin_I, chLatin_S, chLatin_A, chLatin_P, chLatin_I, chNull };
+ static const XMLCh normalizeRequest[] =
+ { 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 Site[] = { chLatin_S, chLatin_i, chLatin_t, chLatin_e, chNull };
+
+ struct site_t {
+ site_t(const DOMElement* e)
{
- auto_ptr<XMLCh> handle(XMLString::transcode(w));
- m_handle=handle.get();
+ auto_ptr_char n(e->getAttributeNS(NULL,name));
+ auto_ptr_char s(e->getAttributeNS(NULL,scheme));
+ auto_ptr_char p(e->getAttributeNS(NULL,port));
+ if (n.get()) m_name=n.get();
+ if (s.get()) m_scheme=s.get();
+ if (p.get()) m_port=p.get();
}
- else if (!strcmp("PBinding0",token))
- binding=auto_ptr<XMLCh>(XMLString::transcode(w));
- else if (!strcmp("LBinding0",token))
- location=auto_ptr<XMLCh>(XMLString::transcode(w));
- else if (!strcmp("Time",token))
- m_sessionCreated=atoi(w);
- else if (!strcmp("ClientAddress",token))
- m_clientAddress=w;
- else if (!strcmp("EOF",token))
- break;
- }
- fclose(f);
+ string m_scheme,m_name,m_port;
+ };
- if (binding.get()!=NULL && location.get()!=NULL)
- m_binding=new SAMLAuthorityBinding(g_authorityKind,binding.get(),location.get());
-
- m_lastAccess=time(NULL);
- if (!m_sessionCreated)
- m_sessionCreated=m_lastAccess;
-}
-
-CCacheEntry::~CCacheEntry()
-{
- delete m_binding;
- delete m_response;
- delete[] m_serialized;
+ HINSTANCE g_hinstDLL;
+ ShibTargetConfig* g_Config = NULL;
+ map<string,site_t> g_Sites;
+ bool g_bNormalizeRequest = true;
}
-bool CCacheEntry::isSessionValid(time_t lifetime, time_t timeout)
+BOOL LogEvent(
+ LPCSTR lpUNCServerName,
+ WORD wType,
+ DWORD dwEventID,
+ PSID lpUserSid,
+ LPCSTR message)
{
- time_t now=time(NULL);
- if (lifetime > 0 && now > m_sessionCreated+lifetime)
- return false;
- if (timeout > 0 && now-m_lastAccess >= timeout)
- return false;
- m_lastAccess=now;
- return true;
-}
-
-Iterator<SAMLAttribute*> CCacheEntry::getAttributes(const char* resource_url, settings_t* pSite)
-{
- populate(resource_url,pSite);
- if (m_assertion)
- {
- Iterator<SAMLStatement*> i=m_assertion->getStatements();
- if (i.hasNext())
- {
- SAMLAttributeStatement* s=dynamic_cast<SAMLAttributeStatement*>(i.next());
- if (s)
- return s->getAttributes();
- }
- }
- return Iterator<SAMLAttribute*>();
-}
-
-const XMLByte* CCacheEntry::getSerializedAssertion(const char* resource_url, settings_t* pSite)
-{
- populate(resource_url,pSite);
- if (m_serialized)
- return m_serialized;
- if (!m_assertion)
- return NULL;
- ostrstream os;
- os << *m_assertion;
- unsigned int outlen;
- return m_serialized=Base64::encode(reinterpret_cast<XMLByte*>(os.str()),os.pcount(),&outlen);
+ LPCSTR messages[] = {message, NULL};
+
+ HANDLE hElog = RegisterEventSource(lpUNCServerName, "Shibboleth ISAPI Filter");
+ BOOL res = ReportEvent(hElog, wType, 0, dwEventID, lpUserSid, 1, 0, messages, NULL);
+ return (DeregisterEventSource(hElog) && res);
}
-void CCacheEntry::populate(const char* resource_url, settings_t* pSite)
+extern "C" __declspec(dllexport) BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID)
{
-#undef FUNC
-#define FUNC populate
- Category& log=Category::getInstance("isapi_shib.CCacheEntry");
-
- // Can we use what we have?
- if (m_assertion && m_assertion->getNotOnOrAfter())
- {
- // This is awful, but the XMLDateTime class is truly horrible.
- time_t now=time(NULL);
- struct tm* ptime=gmtime(&now);
- char timebuf[32];
- strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
- auto_ptr<XMLCh> timeptr(XMLString::transcode(timebuf));
- XMLDateTime curDateTime(timeptr.get());
- int result=XMLDateTime::compareOrder(&curDateTime,m_assertion->getNotOnOrAfter());
- if (XMLDateTime::LESS_THAN)
- return;
-
- delete m_response;
- delete[] m_serialized;
- m_assertion=NULL;
- m_response=NULL;
- m_serialized=NULL;
-
- log.info("%s: cached attributes have expired",FUNC);
- }
-
- if (!m_binding)
- return;
-
- auto_ptr<XMLCh> resource(XMLString::transcode(resource_url));
-
- // Build a SAML Request and send it to the AA.
- SAMLSubject* subject=new SAMLSubject(m_handle.c_str(),m_originSite.c_str());
- SAMLAttributeQuery* q=new SAMLAttributeQuery(subject,resource.get());
- SAMLRequest* req=new SAMLRequest(q,ArrayIterator<saml::QName>(&g_respondWith));
- SAMLBinding* pBinding=pSite->g_AuthCache.getBinding(m_binding->getBinding());
- m_response=pBinding->send(*m_binding,*req);
- delete req;
-
- // Store off the assertion for quick access. Memory mgmt is based on the response pointer.
- Iterator<SAMLAssertion*> i=m_response->getAssertions();
- if (i.hasNext())
- m_assertion=i.next();
-
- auto_ptr<char> h(XMLString::transcode(m_handle.c_str()));
- auto_ptr<char> d(XMLString::transcode(m_originSite.c_str()));
- log.info("%s: fetched and stored SAML response for %s@%s",FUNC,h.get(),d.get());
+ if (fdwReason==DLL_PROCESS_ATTACH)
+ g_hinstDLL=hinstDLL;
+ return TRUE;
}
-class DummyMapper : public IOriginSiteMapper
-{
-public:
- DummyMapper() { InitializeCriticalSection(&m_lock); }
- ~DummyMapper();
- virtual Iterator<xstring> getHandleServiceNames(const XMLCh* originSite) { return Iterator<xstring>(); }
- virtual Key* getHandleServiceKey(const XMLCh* handleService) { return NULL; }
- virtual Iterator<xstring> getSecurityDomains(const XMLCh* originSite);
- virtual Iterator<X509Certificate*> getTrustedRoots() { return Iterator<X509Certificate*>(); }
-
-private:
- typedef map<xstring,vector<xstring>*> domains_t;
- domains_t m_domains;
- CRITICAL_SECTION m_lock;
-};
-
-Iterator<xstring> DummyMapper::getSecurityDomains(const XMLCh* originSite)
+extern "C" BOOL WINAPI GetExtensionVersion(HSE_VERSION_INFO* pVer)
{
- EnterCriticalSection(&m_lock);
- vector<xstring>* pv=NULL;
- domains_t::iterator i=m_domains.find(originSite);
- if (i==m_domains.end())
+ if (!pVer)
+ return FALSE;
+
+ if (!g_Config)
{
- pv=new vector<xstring>();
- pv->push_back(originSite);
- pair<domains_t::iterator,bool> p=m_domains.insert(domains_t::value_type(originSite,pv));
- i=p.first;
+ LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+ "Extension mode startup not possible, is the DLL loaded as a filter?");
+ return FALSE;
}
- else
- pv=i->second;
- LeaveCriticalSection(&m_lock);
- return Iterator<xstring>(*pv);
-}
-DummyMapper::~DummyMapper()
-{
- for (domains_t::iterator i=m_domains.begin(); i!=m_domains.end(); i++)
- delete i->second;
- DeleteCriticalSection(&m_lock);
+ pVer->dwExtensionVersion=HSE_VERSION;
+ strncpy(pVer->lpszExtensionDesc,"Shibboleth ISAPI Extension",HSE_MAX_EXT_DLL_NAME_LEN-1);
+ return TRUE;
}
-// globals
-HINSTANCE g_hinstDLL;
-ULONG g_ulMaxSite=1; // max IIS site instance to handle
-settings_t* g_Sites=NULL; // array of site settings
-map<string,string> g_mapAttribNameToHeader; // attribute mapping
-map<xstring,string> g_mapAttribNames;
-
-
-extern "C" __declspec(dllexport) BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID)
+extern "C" BOOL WINAPI TerminateExtension(DWORD)
{
- if (fdwReason==DLL_PROCESS_ATTACH)
- g_hinstDLL=hinstDLL;
- return TRUE;
+ return TRUE; // cleanup should happen when filter unloads
}
extern "C" BOOL WINAPI GetFilterVersion(PHTTP_FILTER_VERSION pVer)
{
if (!pVer)
return FALSE;
-
- // Get module pathname and replace file name with ini file name.
- char inifile[MAX_PATH+1];
- if (GetModuleFileName(g_hinstDLL,inifile,MAX_PATH+1)==0)
- return FALSE;
- char* pch=strrchr(inifile,'\\');
- if (pch==NULL)
- return FALSE;
- pch++;
- *pch=0;
- strcat(inifile,"isapi_shib.ini");
-
- // Read system-wide parameters from isapi_shib.ini.
- char buf[1024];
- char buf3[48];
+ else if (g_Config) {
+ LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+ "Reentrant filter initialization, ignoring...");
+ return TRUE;
+ }
try
{
- SAMLConfig& SAMLconf=SAMLConfig::getConfig();
-
- GetPrivateProfileString("shibboleth","ShibLogConfig","",buf,sizeof(buf),inifile);
- if (*buf)
- PropertyConfigurator::configure(buf);
- Category& log=Category::getInstance("isapi_shib.GetFilterVersion");
- log.info("using INI file: %s",inifile);
-
- GetPrivateProfileString("shibboleth","ShibSchemaPath","",buf,sizeof(buf),inifile);
- if (!*buf)
- {
- log.fatal("ShibSchemaPath missing");
+ LPCSTR schemadir=getenv("SHIBSCHEMAS");
+ if (!schemadir)
+ schemadir=SHIB_SCHEMAS;
+ LPCSTR config=getenv("SHIBCONFIG");
+ if (!config)
+ config=SHIB_CONFIG;
+ g_Config=&ShibTargetConfig::getConfig();
+ g_Config->setFeatures(
+ ShibTargetConfig::Listener |
+ ShibTargetConfig::Metadata |
+ ShibTargetConfig::AAP |
+ ShibTargetConfig::RequestMapper |
+ ShibTargetConfig::SHIREExtensions |
+ ShibTargetConfig::Logging
+ );
+ if (!g_Config->init(schemadir,config)) {
+ g_Config=NULL;
+ LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL,
+ "Filter startup failed during initialization, check shire log for help.");
return FALSE;
}
- SAMLconf.schema_dir=buf;
- if (*SAMLconf.schema_dir.end()!='\\')
- SAMLconf.schema_dir+='\\';
-
- GetPrivateProfileString("shibboleth","ShibSSLCertFile","",buf,sizeof(buf),inifile);
- if (!*buf)
- {
- log.fatal("ShibSSLCertFile missing");
- return FALSE;
- }
- SAMLconf.ssl_certfile=buf;
-
- GetPrivateProfileString("shibboleth","ShibSSLKeyFile","",buf,sizeof(buf),inifile);
- if (!*buf)
- {
- log.fatal("ShibSSLKeyFile missing");
- return FALSE;
- }
- SAMLconf.ssl_keyfile=buf;
-
- GetPrivateProfileString("shibboleth","ShibSSLKeyPass","",buf,sizeof(buf),inifile);
- SAMLconf.ssl_keypass=buf;
-
- GetPrivateProfileString("shibboleth","ShibSSLCAList","",buf,sizeof(buf),inifile);
- SAMLconf.ssl_calist=buf;
-
- // Read site count and allocate site array.
- g_ulMaxSite=GetPrivateProfileInt("shibboleth","max-site",0,inifile);
- if (g_ulMaxSite==0)
- {
- log.fatal("max-site was 0 or invalid");
- return FALSE;
- }
- log.debug("max-site is %d",g_ulMaxSite);
- g_Sites=new settings_t[g_ulMaxSite];
-
- // Read site-specific settings for each site.
- for (ULONG i=0; i<g_ulMaxSite; i++)
- {
- ultoa(i+1,buf3,10);
- GetPrivateProfileString(buf3,"ShibSiteName","X",buf,sizeof(buf),inifile);
- if (!strcmp(buf,"X"))
- {
- log.info("skipping site %d (no ShibSiteName)",i);
- continue;
- }
-
- GetPrivateProfileString(buf3,"ShibCookieName","",buf,sizeof(buf),inifile);
- if (!*buf)
- {
- delete[] g_Sites;
- log.fatal("ShibCookieName missing in site %d",i);
- return FALSE;
- }
- g_Sites[i].g_CookieName=buf;
-
- GetPrivateProfileString(buf3,"WAYFLocation","",buf,sizeof(buf),inifile);
- if (!*buf)
- {
- delete[] g_Sites;
- log.fatal("WAYFLocation missing in site %d",i);
- return FALSE;
- }
- g_Sites[i].g_WAYFLocation=buf;
-
- GetPrivateProfileString(buf3,"GarbageCollector","",buf,sizeof(buf),inifile);
- if (!*buf)
- {
- delete[] g_Sites;
- log.fatal("GarbageCollector missing in site %d",i);
- return FALSE;
- }
- g_Sites[i].g_GarbageCollector=buf;
-
- GetPrivateProfileString(buf3,"SHIRELocation","",buf,sizeof(buf),inifile);
- if (!*buf)
- {
- delete[] g_Sites;
- log.fatal("SHIRELocation missing in site %d",i);
- return FALSE;
- }
- g_Sites[i].g_SHIRELocation=buf;
-
- GetPrivateProfileString(buf3,"SHIRESessionPath","",buf,sizeof(buf),inifile);
- if (!*buf)
- {
- delete[] g_Sites;
- log.fatal("SHIRESessionPath missing in site %d",i);
- return FALSE;
- }
- g_Sites[i].g_SHIRESessionPath=buf;
- if (g_Sites[i].g_SHIRESessionPath[g_Sites[i].g_SHIRESessionPath.length()]!='\\')
- g_Sites[i].g_SHIRESessionPath+='\\';
-
- // Old-style matching string.
- GetPrivateProfileString(buf3,"ShibMustContain","",buf,sizeof(buf),inifile);
- _strupr(buf);
- char* start=buf;
- while (char* sep=strchr(start,';'))
- {
- *sep='\0';
- if (*start)
- {
- g_Sites[i].g_MustContain.push_back(start);
- log.info("site %d told to match against %s",i,start);
+
+ // Access the implementation-specifics for site mappings.
+ IConfig* conf=g_Config->getINI();
+ Locker locker(conf);
+ const IPropertySet* props=conf->getPropertySet("SHIRE");
+ if (props) {
+ const DOMElement* impl=saml::XML::getFirstChildElement(
+ props->getElement(),ShibTargetConfig::SHIBTARGET_NS,Implementation
+ );
+ if (impl && (impl=saml::XML::getFirstChildElement(impl,ShibTargetConfig::SHIBTARGET_NS,ISAPI))) {
+ const XMLCh* flag=impl->getAttributeNS(NULL,normalizeRequest);
+ g_bNormalizeRequest=(!flag || !*flag || *flag==chDigit_1 || *flag==chLatin_t);
+ impl=saml::XML::getFirstChildElement(impl,ShibTargetConfig::SHIBTARGET_NS,Site);
+ while (impl) {
+ auto_ptr_char id(impl->getAttributeNS(NULL,id));
+ if (id.get())
+ g_Sites.insert(pair<string,site_t>(id.get(),site_t(impl)));
+ impl=saml::XML::getNextSiblingElement(impl,ShibTargetConfig::SHIBTARGET_NS,Site);
}
- start=sep+1;
}
- if (*start)
- {
- g_Sites[i].g_MustContain.push_back(start);
- log.info("site %d told to match against %s",i,start);
- }
-
- if (GetPrivateProfileInt(buf3,"ShibSSLOnly",1,inifile)==0)
- g_Sites[i].g_bSSLOnly=false;
- if (GetPrivateProfileInt(buf3,"ShibCheckAddress",1,inifile)==0)
- g_Sites[i].g_bCheckAddress=false;
- if (GetPrivateProfileInt(buf3,"ShibExportAssertion",0,inifile)==1)
- g_Sites[i].g_bExportAssertion=true;
- g_Sites[i].g_Lifetime=GetPrivateProfileInt(buf3,"ShibAuthLifetime",7200,inifile);
- if (g_Sites[i].g_Lifetime<=0)
- g_Sites[i].g_Lifetime=7200;
- g_Sites[i].g_Timeout=GetPrivateProfileInt(buf3,"ShibAuthTimeout",3600,inifile);
- if (g_Sites[i].g_Timeout<=0)
- g_Sites[i].g_Timeout=3600;
- log.info("configuration of site %d complete",i);
- }
-
- ShibConfig& Shibconf=ShibConfig::getConfig();
- static DummyMapper mapper;
-
- if (!SAMLconf.init())
- {
- delete[] g_Sites;
- log.fatal("SAML initialization failed");
- return FALSE;
- }
-
- Shibconf.origin_mapper=&mapper;
- if (!Shibconf.init())
- {
- delete[] g_Sites;
- log.fatal("Shibboleth initialization failed");
- return FALSE;
- }
-
- char buf2[32767];
- DWORD res=GetPrivateProfileSection("ShibMapAttributes",buf2,sizeof(buf2),inifile);
- if (res==sizeof(buf2)-2)
- {
- delete[] g_Sites;
- log.fatal("ShibMapAttributes INI section was larger than 32k");
- return FALSE;
- }
-
- for (char* attr=buf2; *attr; attr++)
- {
- char* delim=strchr(attr,'=');
- if (!delim)
- {
- delete[] g_Sites;
- log.fatal("unrecognizable ShibMapAttributes directive: %s",attr);
- return FALSE;
- }
- *delim++=0;
- g_mapAttribNameToHeader[attr]=(string(delim) + ':');
- log.info("mapping attribute %s to request header %s",attr,delim);
- attr=delim + strlen(delim);
- }
-
- log.info("configuration of attributes complete");
-
- // Transcode the attribute names we know about for quick handling map access.
- for (map<string,string>::const_iterator j=g_mapAttribNameToHeader.begin();
- j!=g_mapAttribNameToHeader.end(); j++)
- {
- auto_ptr<XMLCh> temp(XMLString::transcode(j->first.c_str()));
- g_mapAttribNames[temp.get()]=j->first;
}
-
- res=GetPrivateProfileSection("ShibExtensions",buf2,sizeof(buf2),inifile);
- if (res==sizeof(buf2)-2)
- {
- delete[] g_Sites;
- log.fatal("ShibExtensions INI section was larger than 32k");
- return FALSE;
- }
-
- for (char* libpath=buf2; *libpath; libpath+=strlen(libpath)+1)
- SAMLconf.saml_register_extension(libpath);
-
- log.info("completed loading of extension libraries");
- }
- catch (bad_alloc)
- {
- delete[] g_Sites;
- Category::getInstance("isapi_shib.GetFilterVersion").fatal("out of memory");
- return FALSE;
- }
- catch (log4cpp::ConfigureFailure& ex)
- {
- delete[] g_Sites;
- WritePrivateProfileString("startlog","bailed-at","log4cpp exception caught",inifile);
- WritePrivateProfileString("startlog","log4cpp",ex.what(),inifile);
- return FALSE;
}
- catch (SAMLException& ex)
+ catch (...)
{
- delete[] g_Sites;
- Category::getInstance("isapi_shib.GetFilterVersion").fatal("caught SAML exception: %s",ex.what());
+ LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Filter startup failed with an exception.");
+#ifdef _DEBUG
+ throw;
+#endif
return FALSE;
}
SF_NOTIFY_NONSECURE_PORT |
SF_NOTIFY_PREPROC_HEADERS |
SF_NOTIFY_LOG);
+ LogEvent(NULL, EVENTLOG_INFORMATION_TYPE, 7701, NULL, "Filter initialized...");
return TRUE;
}
-extern "C" BOOL WINAPI TerminateFilter(DWORD dwFlags)
+extern "C" BOOL WINAPI TerminateFilter(DWORD)
{
- Category::getInstance("isapi_shib.TerminateFilter").info("shutting down...");
- delete[] g_Sites;
- g_Sites=NULL;
- ShibConfig::getConfig().term();
- SAMLConfig::getConfig().term();
- Category::getInstance("isapi_shib.TerminateFilter").info("shut down complete");
+ if (g_Config)
+ g_Config->shutdown();
+ g_Config = NULL;
+ LogEvent(NULL, EVENTLOG_INFORMATION_TYPE, 7701, NULL, "Filter shut down...");
return TRUE;
}
size_t size() const { return buflen; }
bool empty() const { return length()==0; }
void reserve(size_t s, bool keep=false);
- void erase() { if (bufptr) *bufptr=0; }
+ void erase() { if (bufptr) memset(bufptr,0,buflen); }
operator char*() { return bufptr; }
bool operator ==(const char* s) const;
bool operator !=(const char* s) const { return !(*this==s); }
return strcmp(bufptr,s)==0;
}
-void GetServerVariable(PHTTP_FILTER_CONTEXT pfc,
- LPSTR lpszVariable, dynabuf& s, DWORD size=80, bool bRequired=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))
throw ERROR_NO_DATA;
}
-void GetHeader(PHTTP_FILTER_PREPROC_HEADERS pn, PHTTP_FILTER_CONTEXT pfc,
- LPSTR lpszName, dynabuf& s, DWORD size=80, bool bRequired=true)
+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 (!pn->GetHeader(pfc,lpszName,s,&size))
+ while (lpECB->GetServerVariable(lpECB->ConnID,lpszVariable,s,&size))
{
// Grumble. Check the error.
DWORD e=GetLastError();
throw ERROR_NO_DATA;
}
-inline char hexchar(unsigned short s)
+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)
{
- return (s<=9) ? ('0' + s) : ('A' + s - 10);
-}
+ s.reserve(size);
+ s.erase();
+ size=s.size();
-string url_encode(const char* url) throw (bad_alloc)
-{
- static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
- string s;
- for (const char* pch=url; *pch; pch++)
+ while (!pn->GetHeader(pfc,lpszName,s,&size))
{
- if (strchr(badchars,*pch)!=NULL || *pch<=0x1F || *pch>=0x7F)
- s=s + '%' + hexchar(*pch >> 4) + hexchar(*pch & 0x0F);
+ // Grumble. Check the error.
+ DWORD e=GetLastError();
+ if (e==ERROR_INSUFFICIENT_BUFFER)
+ s.reserve(size);
else
- s+=*pch;
+ break;
}
- return s;
+ if (bRequired && s.empty())
+ throw ERROR_NO_DATA;
}
-string get_target(PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn, settings_t* pSite)
+IRequestMapper::Settings map_request(
+ PHTTP_FILTER_CONTEXT pfc, PHTTP_FILTER_PREPROC_HEADERS pn, IRequestMapper* mapper, const site_t& site, string& target
+ )
{
- // Reconstructing the requested URL is not fun. Apparently, the PREPROC_HEADERS
- // event means way pre. As in, none of the usual CGI headers are in place yet.
- // It's actually almost easier, in a way, because all the path-info and query
- // stuff is in one place, the requested URL, which we can get. But we have to
- // reconstruct the protocol/host pair using tweezers.
- string s;
- if (pfc->fIsSecurePort)
- s="https://";
- else
- s="http://";
-
- dynabuf buf(256);
- GetServerVariable(pfc,"SERVER_NAME",buf);
- s+=buf;
-
- GetServerVariable(pfc,"SERVER_PORT",buf,10);
- if (buf!=(pfc->fIsSecurePort ? "443" : "80"))
- s=s + ':' + static_cast<char*>(buf);
-
- GetHeader(pn,pfc,"url",buf,256,false);
- s+=buf;
-
- return s;
-}
+ // 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<char*>(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=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<char*>(name);
+ }
+
+ // If port is non-default, append it.
+ if ((!strcmp(scheme,"http") && port!="80") || (!strcmp(scheme,"https") && port!="443"))
+ target = target + ':' + static_cast<char*>(port);
-string get_shire_location(PHTTP_FILTER_CONTEXT pfc, settings_t* pSite, const char* target)
-{
- if (pSite->g_SHIRELocation[0]!='/')
- return url_encode(pSite->g_SHIRELocation.c_str());
- const char* colon=strchr(target,':');
- const char* slash=strchr(colon+3,'/');
- string s(target,slash-target);
- s+=pSite->g_SHIRELocation;
- return url_encode(s.c_str());
+ // Append path.
+ if (!url.empty())
+ target+=static_cast<char*>(url);
+
+ return mapper->getSettingsFromParsedURL(scheme,site.m_name.c_str(),strtoul(port,NULL,10),url);
}
DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const char* msg)
{
- Category::getInstance("isapi_shib.WriteClientError").error("sending error page to browser: %s",msg);
-
- pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",0,0);
+ LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg);
+ 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 shib_shar_error(PHTTP_FILTER_CONTEXT pfc, SAMLException& e)
+DWORD WriteClientError(PHTTP_FILTER_CONTEXT pfc, const IApplication* app, const char* page, ShibMLP& mlp)
{
- Category::getInstance("isapi_shib.shib_shar_error").errorStream()
- << "exception during SHAR request: " << e;
-
- pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",0,0);
-
- static const char* msg="<HTML><HEAD><TITLE>Shibboleth Attribute Exchange Failed</TITLE></HEAD>\n"
- "<BODY><H3>Shibboleth Attribute Exchange Failed</H3>\n"
- "While attempting to securely contact your origin site to obtain "
- "information about you, an error occurred:<BR><BLOCKQUOTE>";
- DWORD resplen=strlen(msg);
- pfc->WriteClient(pfc,(LPVOID)msg,&resplen,0);
-
- const char* msg2=e.what();
- resplen=strlen(msg2);
- pfc->WriteClient(pfc,(LPVOID)msg2,&resplen,0);
+ const IPropertySet* props=app->getPropertySet("Errors");
+ if (props) {
+ pair<bool,const char*> 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;
+ }
+ }
+ }
+ }
- bool origin=true;
- Iterator<saml::QName> i=e.getCodes();
- if (i.hasNext() && XMLString::compareString(L(Responder),i.next().getLocalName()))
- origin=false;
+ LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, "Filter unable to open error template.");
+ return WriteClientError(pfc,"Unable to open error template, check settings.");
+}
- const char* msg4=(origin ? "</BLOCKQUOTE><P>The error appears to be located at your origin site.<BR>" :
- "</BLOCKQUOTE><P>The error appears to be located at the resource provider's site.<BR>");
- resplen=strlen(msg4);
- pfc->WriteClient(pfc,(LPVOID)msg4,&resplen,0);
-
- static const char* msg5="<P>Try restarting your browser and accessing the site again to make "
- "sure the problem isn't temporary. Please contact the administrator "
- "of that site if this problem recurs. If possible, provide him/her "
- "with the error message shown above.</BODY></HTML>";
- resplen=strlen(msg5);
- pfc->WriteClient(pfc,(LPVOID)msg5,&resplen,0);
- return SF_STATUS_REQ_FINISHED;
+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)
return SF_STATUS_REQ_NEXT_NOTIFICATION;
}
- char* xmsg=NULL;
- settings_t* pSite=NULL;
- bool bLocked=false;
PHTTP_FILTER_PREPROC_HEADERS pn=(PHTTP_FILTER_PREPROC_HEADERS)pvNotification;
- Category& log=Category::getInstance("isapi_shib.HttpFilterProc");
try
{
- // Determine web site number.
+ // 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 pointer.
- if (site_id>g_ulMaxSite || g_Sites[site_id-1].g_CookieName.empty())
+ // 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;
- pSite=&g_Sites[site_id-1];
-
- string targeturl=get_target(pfc,pn,pSite);
+
+ 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<bool,const char*> 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 on.
- if (targeturl.find(pSite->g_SHIRELocation)!=string::npos)
- {
- log.debug("passing on SHIRE acceptance request");
+ // If the user is accessing the SHIRE acceptance point, pass it on.
+ if (targeturl.find(shireURL)!=string::npos)
return SF_STATUS_REQ_NEXT_NOTIFICATION;
- }
- // If this is the garbage collection service, do a cache sweep.
- if (targeturl==pSite->g_GarbageCollector)
- {
- log.notice("garbage collector triggered");
- pSite->g_AuthCache.lock();
- bLocked=true;
- pSite->g_AuthCache.sweep(pSite->g_Lifetime);
- pSite->g_AuthCache.unlock();
- bLocked=false;
- return WriteClientError(pfc,"The cache was swept for expired sessions.");
- }
+ // Now check the policy for this request.
+ pair<bool,bool> requireSession=settings.first->getBool("requireSession");
+ pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();
+ pair<bool,bool> httpRedirects=application->getPropertySet("Sessions")->getBool("httpRedirects");
+ pair<bool,const char*> redirectPage=application->getPropertySet("Sessions")->getString("redirectPage");
+ if (httpRedirects.first && !httpRedirects.second && !redirectPage.first)
+ return WriteClientError(pfc,"HTML-based redirection requires a redirectPage property.");
- // Get the url request and scan for the must-contain string.
- if (!pSite->g_MustContain.empty())
- {
- char* upcased=new char[targeturl.length()+1];
- strcpy(upcased,targeturl.c_str());
- _strupr(upcased);
- for (vector<string>::const_iterator index=pSite->g_MustContain.begin(); index!=pSite->g_MustContain.end(); index++)
- if (strstr(upcased,index->c_str()))
- break;
- delete[] upcased;
- if (index==pSite->g_MustContain.end())
+ // 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="<HTML><BODY>Redirecting...</BODY></HTML>";
+ 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);
+ }
}
- // SSL check.
- if (pSite->g_bSSLOnly && !pfc->fIsSecurePort)
- {
- log.warn("blocking non-SSL request");
- xmsg="<HTML><HEAD><TITLE>Access Denied</TITLE></HEAD><BODY>"
- "<H1>Access Denied</H1>"
- "This server is configured to deny non-SSL requests for secure resources. "
- "Try your request again using https instead of http."
- "</BODY></HTML>";
- DWORD resplen=strlen(xmsg);
- pfc->ServerSupportFunction(pfc,SF_REQ_SEND_RESPONSE_HEADER,"200 OK",0,0);
- pfc->WriteClient(pfc,xmsg,&resplen,0);
- return SF_STATUS_REQ_FINISHED;
+ // 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);
}
-
- // Check for authentication cookie.
- const char* session_id=NULL;
- GetHeader(pn,pfc,"Cookie:",buf,128,false);
- if (buf.empty() || !(session_id=strstr(buf,pSite->g_CookieName.c_str())) ||
- *(session_id+pSite->g_CookieName.length())!='=')
- {
- log.info("session cookie not found, redirecting to WAYF");
-
- // Redirect to WAYF.
- string wayf("Location: ");
- wayf+=pSite->g_WAYFLocation + "?shire=" + get_shire_location(pfc,pSite,targeturl.c_str()) +
- "&target=" + url_encode(targeturl.c_str()) + "\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;
+ 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
- session_id+=pSite->g_CookieName.length() + 1; /* Skip over the '=' */
- char* cookieend=strchr(session_id,';');
- if (cookieend)
- *cookieend = '\0'; /* Ignore anyting after a ; */
-
- pSite->g_AuthCache.lock(); // ---> Get cache lock
- bLocked=true;
-
- // The caching logic is the heart of the "SHAR".
- CCacheEntry* entry=pSite->g_AuthCache.find(session_id);
- try
- {
- if (!entry)
- {
- pSite->g_AuthCache.unlock(); // ---> Release cache lock
- bLocked=false;
-
- // Construct the path to the session file
- string sessionFile=pSite->g_SHIRESessionPath + session_id;
- try
- {
- entry=new CCacheEntry(sessionFile.c_str());
- }
- catch (runtime_error e)
- {
- log.info("unable to load session from file '%s', redirecting to WAYF",sessionFile.c_str());
-
- // Redirect to WAYF.
- string wayf("Location: ");
- wayf+=pSite->g_WAYFLocation + "?shire=" + get_shire_location(pfc,pSite,targeturl.c_str()) +
- "&target=" + url_encode(targeturl.c_str()) + "\r\n";
- wayf+="Set-Cookie: " + pSite->g_CookieName + "=; path=/; expires=19-Mar-1971 08:23:00 GMT\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);
+ // 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="<HTML><BODY>Redirecting...</BODY></HTML>";
+ DWORD resplen=40;
+ pfc->WriteClient(pfc,(LPVOID)redmsg,&resplen,0);
return SF_STATUS_REQ_FINISHED;
}
- pSite->g_AuthCache.lock(); // ---> Get cache lock
- bLocked=true;
- pSite->g_AuthCache.insert(session_id,entry);
- log.info("new session established: %s",session_id);
+ else {
+ markupProcessor.insert("requestURL",areq);
+ return WriteRedirectPage(pfc, application, redirectPage.second, markupProcessor);
+ }
}
-
- if (!entry->isSessionValid(pSite->g_Lifetime,pSite->g_Timeout))
- {
- pSite->g_AuthCache.remove(session_id);
- pSite->g_AuthCache.unlock(); // ---> Release cache lock
- bLocked=false;
- delete entry;
-
- log.warn("invalidating session because of timeout, redirecting to WAYF");
-
- // Redirect to WAYF.
- string wayf("Location: ");
- wayf+=pSite->g_WAYFLocation + "?shire=" + get_shire_location(pfc,pSite,targeturl.c_str()) +
- "&target=" + url_encode(targeturl.c_str()) + "\r\n";
- wayf+="Set-Cookie: " + pSite->g_CookieName + "=; path=/; expires=19-Mar-1971 08:23:00 GMT\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, application, "shire", markupProcessor);
}
+ }
+ delete status;
+
+ // Move to RM phase.
+ RM rm(application);
+ vector<SAMLAssertion*> assertions;
+ SAMLAuthenticationStatement* sso_statement=NULL;
- if (pSite->g_bCheckAddress && entry->getClientAddress())
- {
- GetServerVariable(pfc,"REMOTE_ADDR",buf,16);
- if (strcmp(entry->getClientAddress(),buf))
- {
- pSite->g_AuthCache.remove(session_id);
- delete entry;
- pSite->g_AuthCache.unlock(); // ---> Release cache lock
- bLocked=false;
-
- log.warn("IP address mismatch detected, clearing session");
-
- string clearcookie("Set-Cookie: ");
- clearcookie+=pSite->g_CookieName + "=; path=/; expires=19-Mar-1971 08:23:00 GMT\r\n";
- pfc->AddResponseHeaders(pfc,const_cast<char*>(clearcookie.c_str()),0);
- return WriteClientError(pfc,
- "Your session was terminated because the network address associated "
- "with it does not match your current address. This is usually caused "
- "by a firewall or proxy of some sort.");
- }
+ 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);
}
+ }
- // Clear relevant headers.
- pn->SetHeader(pfc,"Shib-Attributes:","");
- pn->SetHeader(pfc,"remote-user:","");
- for (map<string,string>::const_iterator h_iter=g_mapAttribNameToHeader.begin(); h_iter!=g_mapAttribNameToHeader.end(); h_iter++)
- if (h_iter->second!="REMOTE_USER:")
- pn->SetHeader(pfc,const_cast<char*>(h_iter->second.c_str()),"");
-
- if (pSite->g_bExportAssertion)
- {
- string exp((char*)entry->getSerializedAssertion(targeturl.c_str(),pSite));
- string::size_type lfeed;
- while ((lfeed=exp.find('\n'))!=string::npos)
- exp.erase(lfeed,1);
- pn->SetHeader(pfc,"Shib-Attributes:",const_cast<char*>(exp.c_str()));
+ // Get the AAP providers, which contain the attribute policy info.
+ Iterator<IAAP*> provs=application->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) {
+ string hname=string(header) + ':';
+ pn->SetHeader(pfc,const_cast<char*>(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<bool,bool> 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<char*>(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<char*>(os.get()));
+ pn->SetHeader(pfc,"Shib-Authentication-Method:", const_cast<char*>(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<char*>(form.get()));
+ if (!strcmp(wrapper->getHeader(),"REMOTE_USER")) {
+ char* principal=const_cast<char*>(nameid.get());
+ 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 hname=string(wrapper->getHeader()) + ':';
+ pn->SetHeader(pfc,const_cast<char*>(wrapper->getHeader()),const_cast<char*>(nameid.get()));
}
- Iterator<SAMLAttribute*> i=entry->getAttributes(targeturl.c_str(),pSite);
-
- while (i.hasNext())
- {
- SAMLAttribute* attr=i.next();
-
- // Are we supposed to export it?
- map<xstring,string>::const_iterator iname=g_mapAttribNames.find(attr->getName());
- if (iname!=g_mapAttribNames.end())
- {
- string hname=g_mapAttribNameToHeader[iname->second];
+ }
+
+ pn->SetHeader(pfc,"Shib-Application-ID:","");
+ pn->SetHeader(pfc,"Shib-Application-ID:",const_cast<char*>(application_id.second));
+
+ // 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(provs,attr->getName(),attr->getNamespace());
+ if (wrapper.fail() || !wrapper->getHeader())
+ continue;
+
Iterator<string> vals=attr->getSingleByteValues();
- if (hname=="REMOTE_USER:" && vals.hasNext())
- {
+ 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(" ");
- while (vals.hasNext())
- header+=vals.next() + " ";
- pn->SetHeader(pfc,const_cast<char*>(hname.c_str()),const_cast<char*>(header.c_str()));
}
+ else {
+ int it=0;
+ string header;
+ string hname=string(wrapper->getHeader()) + ':';
+ GetHeader(pn,pfc,const_cast<char*>(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<char*>(hname.c_str()),const_cast<char*>(header.c_str()));
+ }
}
}
-
- pSite->g_AuthCache.unlock(); // ---> Release cache lock
- bLocked=false;
- return SF_STATUS_REQ_NEXT_NOTIFICATION;
}
- catch (SAMLException& e)
- {
- Iterator<saml::QName> i=e.getCodes();
- int c=0;
- while (i.hasNext())
- {
- c++;
- saml::QName q=i.next();
- if (c==1 && !XMLString::compareString(q.getNamespaceURI(),saml::XML::SAMLP_NS) &&
- !XMLString::compareString(q.getLocalName(),L(Requester)))
- continue;
- else if (c==2 && !XMLString::compareString(q.getNamespaceURI(),shibboleth::XML::SHIB_NS) &&
- !XMLString::compareString(q.getLocalName(),shibboleth::XML::Literals::InvalidHandle))
- {
- if (!bLocked)
- pSite->g_AuthCache.lock(); // ---> Grab cache lock
- pSite->g_AuthCache.remove(session_id);
- pSite->g_AuthCache.unlock(); // ---> Release cache lock
- delete entry;
-
- log.info("invaliding session due to shib:InvalidHandle code from AA");
-
- // Redirect to WAYF.
- string wayf("Location: ");
- wayf+=pSite->g_WAYFLocation + "?shire=" + get_shire_location(pfc,pSite,targeturl.c_str()) +
- "&target=" + url_encode(targeturl.c_str()) + "\r\n";
- wayf+="Set-Cookie: " + pSite->g_CookieName + "=; path=/; expires=19-Mar-1971 08:23:00 GMT\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;
+
+ // 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.");
+ }
+#endif
+
+ return WriteClientError(pfc,"Server reached unreachable code, save my walrus!");
+}
+
+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<char*>(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<char*>(name);
+ }
+
+ // If port is non-default, append it.
+ if ((!strcmp(scheme,"http") && port!="80") || (!strcmp(scheme,"https") && port!="443"))
+ target = target + ':' + static_cast<char*>(port);
+
+ // Append path.
+ if (!url.empty())
+ target+=static_cast<char*>(url);
+
+ return mapper->getSettingsFromParsedURL(scheme,site.m_name.c_str(),strtoul(port,NULL,10),url);
+}
+
+DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const char* msg)
+{
+ LogEvent(NULL, EVENTLOG_ERROR_TYPE, 2100, NULL, msg);
+ 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);
+ lpECB->WriteClient(lpECB->ConnID,(LPVOID)xmsg,&resplen,HSE_IO_SYNC);
+ resplen=strlen(msg);
+ lpECB->WriteClient(lpECB->ConnID,(LPVOID)msg,&resplen,HSE_IO_SYNC);
+ static const char* xmsg2="</BODY></HTML>";
+ resplen=strlen(xmsg2);
+ lpECB->WriteClient(lpECB->ConnID,(LPVOID)xmsg2,&resplen,HSE_IO_SYNC);
+ return HSE_STATUS_SUCCESS;
+}
+
+DWORD WriteClientError(LPEXTENSION_CONTROL_BLOCK lpECB, const IApplication* app, const char* page, ShibMLP& mlp)
+{
+ const IPropertySet* props=app->getPropertySet("Errors");
+ if (props) {
+ pair<bool,const char*> 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;
}
- break;
}
- if (bLocked)
- pSite->g_AuthCache.unlock();
- return shib_shar_error(pfc,e);
- }
- catch (XMLException& e)
- {
- if (bLocked)
- pSite->g_AuthCache.unlock();
- auto_ptr<char> msg(XMLString::transcode(e.getMessage()));
- SAMLException ex(SAMLException::RESPONDER,msg.get());
- return shib_shar_error(pfc,ex);
}
}
- catch(bad_alloc)
- {
- xmsg="Out of memory.";
- log.error("out of memory");
+ 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;
+ }
}
- catch(DWORD e)
+ 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
{
- if (e==ERROR_NO_DATA)
- xmsg="A required variable or header was empty.";
+ 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<string,site_t>::const_iterator map_i=g_Sites.find(static_cast<char*>(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<bool,const char*> 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<const char*,const char*> shib_cookie=shire.getCookieNameProps();
+
+ // Make sure this is SSL, if it should be
+ pair<bool,bool> 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<bool,bool> httpRedirects=sessionProps->getBool("httpRedirects");
+ pair<bool,const char*> 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="<HTML><BODY>Redirecting...</BODY></HTML>";
+ 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<const char*,const char*> elements=pair<const char*,const char*>(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
- xmsg="Server detected unexpected IIS error.";
+ elements=shire.getFormSubmission(reinterpret_cast<char*>(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="<HTML><BODY>Redirecting...</BODY></HTML>";
+ 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="<HTML><BODY>Redirecting...</BODY></HTML>";
+ 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(...)
- {
- xmsg="Server caught an unknown exception.";
+ 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);
+ }
}
-
- // If we drop here, the exception handler set the proper message.
- if (bLocked)
- pSite->g_AuthCache.unlock();
- return WriteClientError(pfc,xmsg);
+#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;
}