bug #19666 Verify explicitly that the request IP is a valid IPv4 address (nesk)
This PR was squashed before being merged into the 2.7 branch (closes #19666).
Discussion
----------
Verify explicitly that the request IP is a valid IPv4 address
| Q | A
| ------------- | ---
| Branch? | 2.7
| Bug fix? | yes
| New feature? | no
| BC breaks? | no
| Deprecations? | no
| Tests pass? | yes
| Fixed tickets | -
| License | MIT
| Doc PR | -
Take the following base code (the array is based on [CloudFlare IP Ranges](https://www.cloudflare.com/ips/)):
```php
use Symfony\Component\HttpFoundation\IpUtils;
$ips = [
"103.21.244.0/22",
"103.22.200.0/22",
"103.31.4.0/22",
"104.16.0.0/12",
"108.162.192.0/18",
"131.0.72.0/22",
"141.101.64.0/18",
"162.158.0.0/15",
"172.64.0.0/13",
"173.245.48.0/20",
"188.114.96.0/20",
"190.93.240.0/20",
"197.234.240.0/22",
"198.41.128.0/17",
"199.27.128.0/21",
"2400:cb00::/32",
"2405:8100::/32",
"2405:b500::/32",
"2606:4700::/32",
"2803:f800::/32",
"2c0f:f248::/32",
"2a06:98c0::/29",
];
```
Before this PR, the following code would have returned `true` instead of the expected `false` value:
```php
IpUtils::checkIp('blablabla', $ips);
```
This due to the `ip2long` function returning `false` for an invalid IP address, thus returning `"00000000000000000000000000000000"` with the following code:
```php
sprintf('%032b', ip2long('blablabla'));
```
To fix this I simply check if the `$requestIp` variable contains a valid IP address.
Commits
-------
17e418c
Verify explicitly that the request IP is a valid IPv4 address
This commit is contained in:
commit
7b383a9788
@ -61,11 +61,14 @@ class IpUtils
|
|||||||
*/
|
*/
|
||||||
public static function checkIp4($requestIp, $ip)
|
public static function checkIp4($requestIp, $ip)
|
||||||
{
|
{
|
||||||
|
if (!filter_var($requestIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if (false !== strpos($ip, '/')) {
|
if (false !== strpos($ip, '/')) {
|
||||||
list($address, $netmask) = explode('/', $ip, 2);
|
list($address, $netmask) = explode('/', $ip, 2);
|
||||||
|
|
||||||
if ($netmask === '0') {
|
if ($netmask === '0') {
|
||||||
// Ensure IP is valid - using ip2long below implicitly validates, but we need to do it manually here
|
|
||||||
return filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
|
return filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -37,6 +37,7 @@ class IpUtilsTest extends \PHPUnit_Framework_TestCase
|
|||||||
array(true, '1.2.3.4', '0.0.0.0/0'),
|
array(true, '1.2.3.4', '0.0.0.0/0'),
|
||||||
array(true, '1.2.3.4', '192.168.1.0/0'),
|
array(true, '1.2.3.4', '192.168.1.0/0'),
|
||||||
array(false, '1.2.3.4', '256.256.256/0'), // invalid CIDR notation
|
array(false, '1.2.3.4', '256.256.256/0'), // invalid CIDR notation
|
||||||
|
array(false, 'an_invalid_ip', '192.168.1.0/24'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user