}
-#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<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);
-
- // 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 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";
- 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<LPCSTR>(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<string,site_t>::const_iterator map_i=g_Sites.find(static_cast<char*>(buf));
- if (map_i==g_Sites.end())
- return SF_STATUS_REQ_NEXT_NOTIFICATION;
-
- ostringstream threadid;
- threadid << "[" << getpid() << "] isapi_shib" << '\0';
- 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 it on.
- if (targeturl.find(shireURL)!=string::npos)
- return SF_STATUS_REQ_NEXT_NOTIFICATION;
-
- // 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.");
-
- // 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);
- }
- }
-
- // 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="<HTML><BODY>Redirecting...</BODY></HTML>";
- 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<SAMLAssertion*> 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<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()));
- }
- }
-
- 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 (!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 {
- 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()));
- }
- }
- }
- }
-
- // 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!");
-}
-#endif // 0
-
/****************************************************************************/
// ISAPI Extension
// 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<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 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;
- }
- }
- }
- }
- 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<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
- 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 (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
const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
return s ? s->getElement() : NULL;
}
-
-
-#if 0
-
-IRequestMapper::Settings map_request(pblock* pb, Session* sn, Request* rq, IRequestMapper* mapper, string& target)
-{
- // Get everything but hostname...
- const char* uri=pblock_findval("uri",rq->reqpb);
- const char* qstr=pblock_findval("query",rq->reqpb);
- int port=server_portnum;
- const char* scheme=security_active ? "https" : "http";
- const char* host=NULL;
-
- string url;
- if (uri)
- url=uri;
- if (qstr)
- url=url + '?' + qstr;
-
-#ifdef vs_is_default_vs
- // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
- if (!vs_is_default_vs)
- // The beauty here is, a non-default vhost can *only* be accessed if the client
- // specified the exact name in the Host header. So we can trust the Host header.
- host=pblock_findval("host", rq->headers);
- else
-#endif
- // In other cases, we're going to rely on the initialization process...
- host=g_ServerName.c_str();
-
- target=(g_ServerScheme.empty() ? string(scheme) : g_ServerScheme) + "://" + host;
-
- // If port is non-default, append it.
- if ((!security_active && port!=80) || (security_active && port!=443)) {
- char portbuf[10];
- util_snprintf(portbuf,9,"%d",port);
- target = target + ':' + portbuf;
- }
-
- target+=url;
-
- return mapper->getSettingsFromParsedURL(scheme,host,port,url.c_str());
-}
-
-int WriteClientError(Session* sn, Request* rq, 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) {
- pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
- pblock_nninsert("Content-Length",strlen(res),rq->srvhdrs);
- pblock_nvinsert("Connection","close",rq->srvhdrs);
- protocol_status(sn,rq,PROTOCOL_OK,NULL);
- NET_WRITE(const_cast<char*>(res));
- return REQ_EXIT;
- }
- }
- }
- }
-
- log_error(LOG_FAILURE,"WriteClientError",sn,rq,"Unable to open error template, check settings.");
- protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,"Unable to open error template, check settings.");
- return REQ_ABORTED;
-}
-
-int WriteRedirectPage(Session* sn, Request* rq, const IApplication* app, const char* file, ShibMLP& mlp)
-{
- ifstream infile(file);
- if (!infile.fail()) {
- const char* res = mlp.run(infile,app->getPropertySet("Errors"));
- if (res) {
- pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
- pblock_nninsert("Content-Length",strlen(res),rq->srvhdrs);
- protocol_status(sn,rq,PROTOCOL_OK,NULL);
- NET_WRITE(const_cast<char*>(res));
- return REQ_EXIT;
- }
- }
- log_error(LOG_FAILURE,"WriteRedirectPage",sn,rq,"Unable to open redirect template, check settings.");
- protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,"Unable to open redirect template, check settings.");
- return REQ_ABORTED;
-}
-
-#undef FUNC
-#define FUNC "shibboleth"
-extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
-{
- try
- {
- ostringstream threadid;
- threadid << "[" << getpid() << "] nsapi_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(pb,sn,rq,mapper,targeturl);
- pair<bool,const char*> application_id=settings.first->getString("applicationId");
- const IApplication* application=conf->getApplication(application_id.second);
- if (!application)
- return WriteClientError(sn,rq,FUNC,"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(sn,rq,FUNC,"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 REQ_PROCEED;
-
- // Now check the policy for this request.
- pair<bool,bool> requireSession=settings.first->getBool("requireSession");
- if (!requireSession.first || !requireSession.second) {
- const char* param=pblock_findval("require-session",pb);
- if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
- requireSession.second=true;
- }
- 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(sn,rq,FUNC,"HTML-based redirection requires a redirectPage property.");
-
- // Check for session cookie.
- const char* session_id=NULL;
- string cookie;
- if (request_header("cookie",(char**)&session_id,sn,rq)==REQ_ABORTED)
- return WriteClientError(sn,rq,FUNC,"error accessing cookie header");
-
- Category::getInstance("nsapi_shib."FUNC).debug("cookie header is {%s}",session_id ? session_id : "NULL");
- if (session_id && (session_id=strstr(session_id,shib_cookie.first))) {
- session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
- char* cookieend=strchr(session_id,';');
- if (cookieend) {
- // Chop out just the value portion.
- cookie.assign(session_id,cookieend-session_id-1);
- session_id=cookie.c_str();
- }
- }
-
- if (!session_id || !*session_id) {
- // If no session required, bail now.
- if (!requireSession.second)
- return REQ_PROCEED;
-
- // No acceptable cookie, and we require a session. Generate an AuthnRequest.
- const char* areq = shire.getAuthnRequest(targeturl.c_str());
- if (!httpRedirects.first || httpRedirects.second) {
- pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
- pblock_nvinsert("Content-Length","40",rq->srvhdrs);
- pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
- pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
- pblock_nvinsert("Location",areq,rq->srvhdrs);
- protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
- protocol_start_response(sn,rq);
- NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
- return REQ_EXIT;
- }
- else {
- ShibMLP markupProcessor;
- markupProcessor.insert("requestURL",areq);
- return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
- }
- }
-
- // Make sure this session is still valid.
- RPCError* status = NULL;
- ShibMLP markupProcessor;
- markupProcessor.insert("requestURL", targeturl);
-
- try {
- status = shire.sessionIsValid(session_id, pblock_findval("ip",sn->client));
- }
- 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(sn, rq, 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(sn, rq, application, "shire", markupProcessor);
- }
-#endif
-
- // Check the status
- if (status->isError()) {
- if (!requireSession.second)
- return REQ_PROCEED;
- 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) {
- pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
- pblock_nvinsert("Content-Length","40",rq->srvhdrs);
- pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
- pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
- pblock_nvinsert("Location",areq,rq->srvhdrs);
- protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
- protocol_start_response(sn,rq);
- NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
- return REQ_EXIT;
- }
- else {
- markupProcessor.insert("requestURL",areq);
- return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
- }
- }
- else {
- // return the error page to the user
- markupProcessor.insert(*status);
- delete status;
- return WriteClientError(sn, rq, application, "shire", markupProcessor);
- }
- }
- delete status;
-
- // Move to RM phase.
- RM rm(application);
- vector<SAMLAssertion*> assertions;
- SAMLAuthenticationStatement* sso_statement=NULL;
-
- try {
- status = rm.getAssertions(session_id, pblock_findval("ip",sn->client), 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(sn, rq, 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(sn, rq, application, "rm", markupProcessor);
- }
- #endif
-
- if (status->isError()) {
- markupProcessor.insert(*status);
- delete status;
- return WriteClientError(sn, rq, 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(sn, rq, application, "access", markupProcessor);
- }
- }
-
- // 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)
- param_free(pblock_remove(header,rq->headers));
- }
- }
- 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(sn, rq, application, "rm", markupProcessor);
- }
- aap->unlock();
- }
- provs.reset();
-
- // Maybe export the first assertion.
- param_free(pblock_remove("remote-user",rq->headers));
- param_free(pblock_remove("auth-user",rq->vars));
- param_free(pblock_remove("Shib-Attributes",rq->headers));
- pair<bool,bool> exp=settings.first->getBool("exportAssertion");
- if (!exp.first || !exp.second) {
- const char* param=pblock_findval("export-assertion",pb);
- if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
- exp.second=true;
- }
- if (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);
- pblock_nvinsert("Shib-Attributes",assertion.c_str(),rq->headers);
- }
-
- pblock_nvinsert("auth-type","shibboleth",rq->vars);
- param_free(pblock_remove("Shib-Origin-Site",rq->headers));
- param_free(pblock_remove("Shib-Authentication-Method",rq->headers));
- param_free(pblock_remove("Shib-NameIdentifier-Format",rq->headers));
-
- // 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());
- pblock_nvinsert("Shib-Origin-Site",os.get(),rq->headers);
- pblock_nvinsert("Shib-Authentication-Method",am.get(),rq->headers);
-
- // 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());
- pblock_nvinsert("Shib-NameIdentifier-Format",form.get(),pb);
- if (!strcmp(wrapper->getHeader(),"REMOTE_USER")) {
- pblock_nvinsert("remote-user",nameid.get(),rq->headers);
- pblock_nvinsert("auth-user",nameid.get(),rq->vars);
- }
- else {
- pblock_nvinsert(wrapper->getHeader(),nameid.get(),rq->headers);
- }
- }
-
- param_free(pblock_remove("Shib-Application-ID",rq->headers));
- pblock_nvinsert("Shib-Application-ID",application_id.second,rq->headers);
-
- // 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 (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext()) {
- char* principal=const_cast<char*>(vals.next().c_str());
- pblock_nvinsert("remote-user",principal,rq->headers);
- pblock_nvinsert("auth-user",principal,rq->vars);
- }
- else {
- int it=0;
- string header;
- const char* h=pblock_findval(wrapper->getHeader(),rq->headers);
- if (h) {
- header=h;
- param_free(pblock_remove(wrapper->getHeader(),rq->headers));
- 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;
- }
- pblock_nvinsert(wrapper->getHeader(),header.c_str(),rq->headers);
- }
- }
- }
- }
-
- // clean up memory
- for (int k = 0; k < assertions.size(); k++)
- delete assertions[k];
- delete sso_statement;
-
- return REQ_PROCEED;
- }
- catch(bad_alloc) {
- return WriteClientError(sn, rq, FUNC,"Out of Memory");
- }
-#ifndef _DEBUG
- catch(...) {
- return WriteClientError(sn, rq, FUNC,"Server caught an unknown exception.");
- }
-#endif
-
- return WriteClientError(sn, rq, FUNC,"Server reached unreachable code, save my walrus!");
-}
-
-#undef FUNC
-#define FUNC "shib_handler"
-extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
-{
- string targeturl;
- const IApplication* application=NULL;
- try
- {
- ostringstream threadid;
- threadid << "[" << getpid() << "] shib_handler" << '\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.
- IRequestMapper* mapper=conf->getRequestMapper();
- Locker locker2(mapper);
- IRequestMapper::Settings settings=map_request(pb,sn,rq,mapper,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(sn,rq,FUNC,"Unable to map request to application settings, check configuration.");
-
- SHIRE shire(application);
-
- const char* shireURL=shire.getShireURL(targeturl.c_str());
- if (!shireURL)
- return WriteClientError(sn,rq,FUNC,"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(sn,rq,FUNC,"NSAPI service function can only be invoked to process incoming sessions."
- "Make sure the mapped file extension or URL 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) {
- if (!security_active)
- throw ShibTargetException(SHIBRPC_OK,"blocked non-SSL access to Shibboleth session 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(sn,rq,FUNC,"HTML-based redirection requires a redirectPage property.");
-
- // If this is a GET, we manufacture an AuthnRequest.
- if (!strcasecmp(pblock_findval("method",rq->reqpb),"GET")) {
- const char* areq=pblock_findval("query",rq->reqpb) ? shire.getLazyAuthnRequest(pblock_findval("query",rq->reqpb)) : NULL;
- if (!areq)
- throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
- if (!httpRedirects.first || httpRedirects.second) {
- pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
- pblock_nvinsert("Content-Length","40",rq->srvhdrs);
- pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
- pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
- pblock_nvinsert("Location",areq,rq->srvhdrs);
- protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
- protocol_start_response(sn,rq);
- NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
- return REQ_EXIT;
- }
- else {
- ShibMLP markupProcessor;
- markupProcessor.insert("requestURL",areq);
- return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
- }
- }
- else if (strcasecmp(pblock_findval("method",rq->reqpb),"POST"))
- throw ShibTargetException(SHIBRPC_OK,"blocked non-POST to Shibboleth session processor");
-
- // Make sure this POST is an appropriate content type
- char* content_type=NULL;
- if (request_header("content-type",&content_type,sn,rq)!=REQ_PROCEED ||
- !content_type || strcasecmp(content_type,"application/x-www-form-urlencoded"))
- throw ShibTargetException(SHIBRPC_OK,"blocked bad content-type to Shibboleth session processor");
-
- // Read the data.
- pair<const char*,const char*> elements=pair<const char*,const char*>(NULL,NULL);
- char* content_length=NULL;
- if (request_header("content-length",&content_length,sn,rq)!=REQ_PROCEED ||
- atoi(content_length) > 1024*1024) // 1MB?
- throw ShibTargetException(SHIBRPC_OK,"blocked too-large a post to Shibboleth session processor");
- else {
- char ch=IO_EOF+1;
- int cl=atoi(content_length);
- string cgistr;
- while (cl && ch!=IO_EOF) {
- ch=netbuf_getc(sn->inbuf);
-
- // Check for error.
- if(ch==IO_ERROR)
- break;
- cgistr+=ch;
- cl--;
- }
- if (cl)
- throw ShibTargetException(SHIBRPC_OK,"error reading POST data from browser");
- elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
- }
-
- // Make sure the SAML Response parameter exists
- if (!elements.first || !*elements.first)
- throw ShibTargetException(SHIBRPC_OK, "Shibboleth POST failed to find SAMLResponse form element");
-
- // Make sure the target parameter exists
- if (!elements.second || !*elements.second)
- throw ShibTargetException(SHIBRPC_OK, "Shibboleth POST failed to find TARGET form element");
-
- // Process the post.
- string cookie;
- RPCError* status=NULL;
- ShibMLP markupProcessor;
- markupProcessor.insert("requestURL", targeturl.c_str());
- try {
- status = shire.sessionCreate(elements.first,pblock_findval("ip",sn->client),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(sn, rq, 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(sn, rq, application, "shire", markupProcessor);
- }
-#endif
-
- if (status->isError()) {
- if (status->isRetryable()) {
- delete status;
- const char* loc=shire.getAuthnRequest(elements.second);
- if (!httpRedirects.first || httpRedirects.second) {
- pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
- pblock_nvinsert("Content-Length","40",rq->srvhdrs);
- pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
- pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
- pblock_nvinsert("Location",loc,rq->srvhdrs);
- protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
- protocol_start_response(sn,rq);
- NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
- return REQ_EXIT;
- }
- else {
- markupProcessor.insert("requestURL",loc);
- return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
- }
- }
-
- // Return this error to the user.
- markupProcessor.insert(*status);
- delete status;
- return WriteClientError(sn,rq,application,"shire",markupProcessor);
- }
- delete status;
-
- // We've got a good session, set the cookie and redirect to target.
- cookie = string(shib_cookie.first) + '=' + cookie + shib_cookie.second;
- pblock_nvinsert("Set-Cookie",cookie.c_str(),rq->srvhdrs);
- if (!httpRedirects.first || httpRedirects.second) {
- pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
- pblock_nvinsert("Content-Length","40",rq->srvhdrs);
- pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
- pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
- pblock_nvinsert("Location",elements.second,rq->srvhdrs);
- protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
- protocol_start_response(sn,rq);
- NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
- return REQ_EXIT;
- }
- else {
- markupProcessor.insert("requestURL",elements.second);
- return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
- }
- }
- 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(sn,rq,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(sn,rq,application,"shire",markupProcessor);
- }
- }
-#endif
- return REQ_EXIT;
-}
-
-#endif