Saturday, June 16, 2007

PHP HTTP_X_FORWARDED_FOR versus WPAD

I was working on one of our company's website running on Apache with PHP and MySQL.

I seems that when users are accessing the site thru our company's proxy server, the updates fail to reflect on the MySQL database (IE really sucks!).

So I decided to write a 2 part php function that captures the client's IP Adress and Referrer if the traffic originated from a proxy server and compares it against known Proxy server IP's and Hostname and disallow the clients from accessing the site and prompts a message to remind the user to disable the IE's proxy server settings when accessing to the site.


Code Snippet:

  1. function GetIP()
  2. {
  3. if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
  4. $ip = getenv("HTTP_CLIENT_IP");
  5. else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
  6. $ip = getenv("HTTP_X_FORWARDED_FOR");
  7. else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
  8. $ip = getenv("REMOTE_ADDR");
  9. else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
  10. $ip = $_SERVER['REMOTE_ADDR'];
  11. else
  12. $ip = "unknown";
  13. return($ip);
  14. }
  15. $badreferer=$CompanyProxyServer;
  16. $referer=GetIP();
  17. if ($referer==$badreferer)
  18. {
  19. echo "<br>";
  20. echo "<center><h4>Disable your proxy server settings and clear your IE cache, then return to this page.</h4></center>";
  21. exit;
  22. }


Well, you know... users will be users...

Although the site prompts a reminder to remove the proxy settings when accessing the pages, most of them still find it difficult to click Tools -> Internet Options -> Conenctions Tab -> LAN Settings and un-tick the use proxy server options.

So to put a permanent fix, I relied on WPAD and permanently excluded the site from utilizing the proxy server when accessing the site via the MatchDirect function:

if (MatchDIRECT(host))
{
return "DIRECT";
}

I also added an extra entry to treat the site as Local Intranet Site, since the security settings only allows ActiveX to be installed and executed from Trusted Sites and Local Intranet Sites.

This also helps in another problem that our company's domain is the same as our public internet domain name.

function FindProxy(host, intranet, internet)
{
if (MatchInternet(host))
{
return internet;
}
else if (dnsDomainIs(host, ".ourcompanyname.com")|
(isPlainHostName(host))|
(MatchIntranetIpRange(host))|
(dnsDomainIs(host, ".ourcompanyname.net")))
{
return intranet;
}
else
{
return internet;
}
}


Now all I needed was a GPO that pushes the Automatic Configuration script (http://OurWebServer/WPAD.dat) to the machines.

House the WPAD script on a central Web Server and Voila!

If at first you fail, call it version 1.0

No comments: