Friday, June 8, 2012

What is the most accurate way to retrieve a user"s correct IP address in PHP?


I know there are a plethora of $_SERVER variables headers available for IP address retrieval. I was wondering if there is a general consensus as to how to most accurately retrieve a user's real IP address (well knowing no method is perfect) using said variables?



I spent some time trying to find an in depth solution and came up with the following code based on a number of sources. I would love it if somebody could please poke holes in the answer or shed some light on something perhaps more accurate.



edit includes optimizations from @Alix




/**
* Retrieves the best guess of the client's actual IP address.
* Takes into account numerous HTTP proxy headers due to variations
* in how different ISPs handle IP addresses in headers between hops.
*/
public function get_ip_address() {
// check for shared internet/ISP IP
if (!empty($_SERVER['HTTP_CLIENT_IP']) && $this->validate_ip($_SERVER['HTTP_CLIENT_IP']))
return $_SERVER['HTTP_CLIENT_IP'];

// check for IPs passing through proxies
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// check if multiple ips exist in var
$iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
foreach ($iplist as $ip) {
if ($this->validate_ip($ip))
return $ip;
}
}
}
if (!empty($_SERVER['HTTP_X_FORWARDED']) && $this->validate_ip($_SERVER['HTTP_X_FORWARDED']))
return $_SERVER['HTTP_X_FORWARDED'];
if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && $this->validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && $this->validate_ip($_SERVER['HTTP_FORWARDED_FOR']))
return $_SERVER['HTTP_FORWARDED_FOR'];
if (!empty($_SERVER['HTTP_FORWARDED']) && $this->validate_ip($_SERVER['HTTP_FORWARDED']))
return $_SERVER['HTTP_FORWARDED'];

// return unreliable ip since all else failed
return $_SERVER['REMOTE_ADDR'];
}

/**
* Ensures an ip address is both a valid IP and does not fall within
* a private network range.
*
* @access public
* @param string $ip
*/
public function validate_ip($ip) {
if (filter_var($ip, FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4 |
FILTER_FLAG_IPV6 |
FILTER_FLAG_NO_PRIV_RANGE |
FILTER_FLAG_NO_RES_RANGE) === false)
return false;
self::$ip = $ip;
return true;
}



Words of Warning (update)



REMOTE_ADDR still represents the most reliable source of an IP address. The other $_SERVER variables mentioned here can be spoofed by a remote client very easily. The purpose of this solution is to attempt to determine the IP address of a client sitting behind a proxy. For your general purposes, you might consider using this in combination with the IP returned directly from $_SERVER['REMOTE_ADDR'] and storing both.



For 99.9% of users this solution will suit your needs perfectly. It will not protect you from the 0.1% of malicious users looking to abuse your system by injecting their own request headers. If relying on IP addresses for something mission critical, resort to REMOTE_ADDR and don't bother catering to those behind a proxy.


Source: Tips4all

8 comments:

  1. Here is a shorter, cleaner way to get the IP address:

    function get_ip_address(){
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
    if (array_key_exists($key, $_SERVER) === true){
    foreach (explode(',', $_SERVER[$key]) as $ip){
    $ip = trim($ip); // just to be safe

    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
    return $ip;
    }
    }
    }
    }
    }


    I hope it helps!



    Your code seems to be pretty complete already, I cannot see any possible bugs in it (aside from the usual IP caveats), I would change the validate_ip() function to rely on the filter extension though:

    public function validate_ip($ip)
    {
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false)
    {
    return false;
    }

    self::$ip = sprintf('%u', ip2long($ip)); // you seem to want this

    return true;
    }


    Also your HTTP_X_FORWARDED_FOR snippet can be simplified from this:

    // check for IPs passing through proxies
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
    // check if multiple ips exist in var
    if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false)
    {
    $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

    foreach ($iplist as $ip)
    {
    if ($this->validate_ip($ip))
    return $ip;
    }
    }

    else
    {
    if ($this->validate_ip($_SERVER['HTTP_X_FORWARDED_FOR']))
    return $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    }


    To this:

    // check for IPs passing through proxies
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
    $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

    foreach ($iplist as $ip)
    {
    if ($this->validate_ip($ip))
    return $ip;
    }
    }


    You may also want to validate IPv6 addresses.

    ReplyDelete
  2. Even then however, getting a user's real Ip address is going to be unreliable. All they need do is use an anonymous proxy server (one that doesn't honor the headers for http_x_forwarded_for or http_forwarded etc) and all you get is their proxy server's ip. You can then see if there is a list of proxy server ips that are anonymous, but there is no way to be sure that is 100% accurate as well and the most it'd do is let you know it is a proxy server. And if someone is being clever, they can spoof headers for http forwards. Let's say I don't like the local college. I figure out what IP's they registered, and get their ip banned on your site by doing bad things because I figure out you honor the http forwards. The list is endless. Then there is, as you guessed internal IPs such as the college network I metioned before. A lot use a 10.x.x.x format. So all you would know is that it was forwarded for a shared network.
    Then I won't start much into it, but dynamic ips are the way of broadband anymore. So. Even if you get a user IP, expect it to change in 2 - 3 months, longest.

    ReplyDelete
  3. The biggest question is for what purpose?

    Your code is nearly as comprehensive as it could be - but I see that if you spot what looks like a proxy added header, you use that INSTEAD of the CLIENT_IP, however if you want this information for audit purposes then be warned - its very easy to fake.

    Certainly you should never use IP addresses for any sort of authentication - even these can be spoofed.

    You could get a better measurement of the client ip address by pushing out a flash or java applet which connects back to the server via a non-http port (which would therefore reveal transparent proxies or cases where the proxy-injected headers are false - but bear in mind that, where the client can ONLY connect via a web proxy or the outgoing port is blocked, there will be no connection from the applet.

    C.

    ReplyDelete
  4. We use:

    /**
    * Get the customer's IP address.
    *
    * @return string
    */
    public function getIpAddress() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    return $_SERVER['HTTP_CLIENT_IP'];
    } else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
    return trim($ips[count($ips) - 1]);
    } else {
    return $_SERVER['REMOTE_ADDR'];
    }
    }


    Edit: Just wanted to clarify, the explode on HTTP_X_FORWARDED_FOR is because of weird issues we had detecting IP's when Squid was used.

    ReplyDelete
  5. I do wonder if perhaps you should iterate over the exploded HTTP_X_FORWARDED_FOR in reverse order, since my experience has been that the user's IP address ends up at the end of the comma-separated list, so starting at the start of the header, you're more likely to get the ip address of one of the proxies returned, which could potentially still allow session hijacking as many users may come through that proxy.

    ReplyDelete
  6. Thanks for this, very useful.

    It would help though if the code were syntactically correct. As it is there's a { too many around line 20. Which I'm afraid means nobody actually tried this out.

    I may be crazy, but after trying it on a few valid and invalid addresses, the only version of validate_ip() that worked was this:

    public function validate_ip($ip)
    {
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) === false)
    return false;
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) === false)
    return false;
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false && filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false)
    return false;

    return true;
    }

    ReplyDelete
  7. You pretty much answered your own question! :)

    function getRealIpAddr() {
    if(!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
    {
    $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
    {
    $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
    $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip; }


    Source

    ReplyDelete
  8. /**
    * Sanitizes IPv4 address according to Ilia Alshanetsky's book
    * "php|architect?s Guide to PHP Security", chapter 2, page 67.
    *
    * @param string $ip An IPv4 address
    */
    public static function sanitizeIpAddress($ip = '')
    {
    if ($ip == '')
    {
    $rtnStr = '0.0.0.0';
    }
    else
    {
    $rtnStr = long2ip(ip2long($ip));
    }

    return $rtnStr;
    }

    //---------------------------------------------------

    /**
    * Returns the sanitized HTTP_X_FORWARDED_FOR server variable.
    *
    */
    public static function getXForwardedFor()
    {
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
    $rtnStr = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    elseif (isset($HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR']))
    {
    $rtnStr = $HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR'];
    }
    elseif (getenv('HTTP_X_FORWARDED_FOR'))
    {
    $rtnStr = getenv('HTTP_X_FORWARDED_FOR');
    }
    else
    {
    $rtnStr = '';
    }

    // Sanitize IPv4 address (Ilia Alshanetsky):
    if ($rtnStr != '')
    {
    $rtnStr = explode(', ', $rtnStr);
    $rtnStr = self::sanitizeIpAddress($rtnStr[0]);
    }

    return $rtnStr;
    }

    //---------------------------------------------------

    /**
    * Returns the sanitized REMOTE_ADDR server variable.
    *
    */
    public static function getRemoteAddr()
    {
    if (isset($_SERVER['REMOTE_ADDR']))
    {
    $rtnStr = $_SERVER['REMOTE_ADDR'];
    }
    elseif (isset($HTTP_SERVER_VARS['REMOTE_ADDR']))
    {
    $rtnStr = $HTTP_SERVER_VARS['REMOTE_ADDR'];
    }
    elseif (getenv('REMOTE_ADDR'))
    {
    $rtnStr = getenv('REMOTE_ADDR');
    }
    else
    {
    $rtnStr = '';
    }

    // Sanitize IPv4 address (Ilia Alshanetsky):
    if ($rtnStr != '')
    {
    $rtnStr = explode(', ', $rtnStr);
    $rtnStr = self::sanitizeIpAddress($rtnStr[0]);
    }

    return $rtnStr;
    }

    //---------------------------------------------------

    /**
    * Returns the sanitized remote user and proxy IP addresses.
    *
    */
    public static function getIpAndProxy()
    {
    $xForwarded = self::getXForwardedFor();
    $remoteAddr = self::getRemoteAddr();

    if ($xForwarded != '')
    {
    $ip = $xForwarded;
    $proxy = $remoteAddr;
    }
    else
    {
    $ip = $remoteAddr;
    $proxy = '';
    }

    return array($ip, $proxy);
    }

    ReplyDelete