Search code examples
phpsecurityipxsshtmlspecialchars

XSS attack in client's IP address


I want to count unique visitors on my webpage. I get client's IP using following function:

$ipaddress = '';
    if ($_SERVER['HTTP_CLIENT_IP'])
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if($_SERVER['HTTP_X_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if($_SERVER['HTTP_X_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if($_SERVER['HTTP_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if($_SERVER['HTTP_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if($_SERVER['REMOTE_ADDR'])
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;

Should I call the htmlspecialchars() function on it, before inserting it into database? I have heard it is possible to manipulate headers and change IP address to add to it XSS or SQL Injection (I already call real_escape_string() function) attack.


Solution

  • Considering the data type you're expecting is an IP, you should simply validate for that specific data type Add the following to your code

    if(filter_var($ipaddress, FILTER_VALIDATE_IP)) return $ipaddress;
    else return "Unknown";
    

    This basically validates that it's an actual IP so that no SQL Injection attack vectors or even XSS could pass through it.