[Request] Ignore invalid IP addresses sent by proxies

Fixes symfony/symfony#15525
This commit is contained in:
Jérôme Tamarelle 2015-11-29 00:02:58 +01:00 committed by Fabien Potencier
parent ec26f6ece0
commit 6578806fc3
2 changed files with 14 additions and 3 deletions

View File

@ -769,8 +769,7 @@ class Request
$clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP])));
$clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from
$ip = $clientIps[0]; // Fallback to this when the client IP falls into the range of trusted proxies
$firstTrustedIp = null;
// Eliminate all IPs from the forwarded IP chain which are trusted proxies
foreach ($clientIps as $key => $clientIp) {
@ -779,13 +778,22 @@ class Request
$clientIps[$key] = $clientIp = $match[1];
}
if (!filter_var($clientIp, FILTER_VALIDATE_IP)) {
unset($clientIps[$key]);
}
if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
unset($clientIps[$key]);
// Fallback to this when the client IP falls into the range of trusted proxies
if (null === $firstTrustedIp) {
$firstTrustedIp = $clientIp;
}
}
}
// Now the IP chain contains only untrusted proxies and the client IP
return $clientIps ? array_reverse($clientIps) : array($ip);
return $clientIps ? array_reverse($clientIps) : array($firstTrustedIp);
}
/**

View File

@ -863,6 +863,9 @@ class RequestTest extends \PHPUnit_Framework_TestCase
// client IP with port
array(array('88.88.88.88'), '127.0.0.1', '88.88.88.88:12345, 127.0.0.1', array('127.0.0.1')),
// invalid forwarded IP is ignored
array(array('88.88.88.88'), '127.0.0.1', 'unknown,88.88.88.88', array('127.0.0.1')),
);
}