1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\HttpFoundation;
13
14/**
15 * Http utility functions.
16 *
17 * @author Fabien Potencier <fabien@symfony.com>
18 */
19class IpUtils
20{
21    private static $checkedIps = [];
22
23    /**
24     * This class should not be instantiated.
25     */
26    private function __construct()
27    {
28    }
29
30    /**
31     * Checks if an IPv4 or IPv6 address is contained in the list of given IPs or subnets.
32     *
33     * @param string|array $ips List of IPs or subnets (can be a string if only a single one)
34     *
35     * @return bool Whether the IP is valid
36     */
37    public static function checkIp(?string $requestIp, $ips)
38    {
39        if (!\is_array($ips)) {
40            $ips = [$ips];
41        }
42
43        $method = substr_count($requestIp, ':') > 1 ? 'checkIp6' : 'checkIp4';
44
45        foreach ($ips as $ip) {
46            if (self::$method($requestIp, $ip)) {
47                return true;
48            }
49        }
50
51        return false;
52    }
53
54    /**
55     * Compares two IPv4 addresses.
56     * In case a subnet is given, it checks if it contains the request IP.
57     *
58     * @param string $ip IPv4 address or subnet in CIDR notation
59     *
60     * @return bool Whether the request IP matches the IP, or whether the request IP is within the CIDR subnet
61     */
62    public static function checkIp4(?string $requestIp, string $ip)
63    {
64        $cacheKey = $requestIp.'-'.$ip;
65        if (isset(self::$checkedIps[$cacheKey])) {
66            return self::$checkedIps[$cacheKey];
67        }
68
69        if (!filter_var($requestIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
70            return self::$checkedIps[$cacheKey] = false;
71        }
72
73        if (false !== strpos($ip, '/')) {
74            list($address, $netmask) = explode('/', $ip, 2);
75
76            if ('0' === $netmask) {
77                return self::$checkedIps[$cacheKey] = filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
78            }
79
80            if ($netmask < 0 || $netmask > 32) {
81                return self::$checkedIps[$cacheKey] = false;
82            }
83        } else {
84            $address = $ip;
85            $netmask = 32;
86        }
87
88        if (false === ip2long($address)) {
89            return self::$checkedIps[$cacheKey] = false;
90        }
91
92        return self::$checkedIps[$cacheKey] = 0 === substr_compare(sprintf('%032b', ip2long($requestIp)), sprintf('%032b', ip2long($address)), 0, $netmask);
93    }
94
95    /**
96     * Compares two IPv6 addresses.
97     * In case a subnet is given, it checks if it contains the request IP.
98     *
99     * @author David Soria Parra <dsp at php dot net>
100     *
101     * @see https://github.com/dsp/v6tools
102     *
103     * @param string $ip IPv6 address or subnet in CIDR notation
104     *
105     * @return bool Whether the IP is valid
106     *
107     * @throws \RuntimeException When IPV6 support is not enabled
108     */
109    public static function checkIp6(?string $requestIp, string $ip)
110    {
111        $cacheKey = $requestIp.'-'.$ip;
112        if (isset(self::$checkedIps[$cacheKey])) {
113            return self::$checkedIps[$cacheKey];
114        }
115
116        if (!((\extension_loaded('sockets') && \defined('AF_INET6')) || @inet_pton('::1'))) {
117            throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".');
118        }
119
120        if (false !== strpos($ip, '/')) {
121            list($address, $netmask) = explode('/', $ip, 2);
122
123            if ('0' === $netmask) {
124                return (bool) unpack('n*', @inet_pton($address));
125            }
126
127            if ($netmask < 1 || $netmask > 128) {
128                return self::$checkedIps[$cacheKey] = false;
129            }
130        } else {
131            $address = $ip;
132            $netmask = 128;
133        }
134
135        $bytesAddr = unpack('n*', @inet_pton($address));
136        $bytesTest = unpack('n*', @inet_pton($requestIp));
137
138        if (!$bytesAddr || !$bytesTest) {
139            return self::$checkedIps[$cacheKey] = false;
140        }
141
142        for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) {
143            $left = $netmask - 16 * ($i - 1);
144            $left = ($left <= 16) ? $left : 16;
145            $mask = ~(0xffff >> $left) & 0xffff;
146            if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) {
147                return self::$checkedIps[$cacheKey] = false;
148            }
149        }
150
151        return self::$checkedIps[$cacheKey] = true;
152    }
153
154    /**
155     * Anonymizes an IP/IPv6.
156     *
157     * Removes the last byte for v4 and the last 8 bytes for v6 IPs
158     */
159    public static function anonymize(string $ip): string
160    {
161        $wrappedIPv6 = false;
162        if ('[' === substr($ip, 0, 1) && ']' === substr($ip, -1, 1)) {
163            $wrappedIPv6 = true;
164            $ip = substr($ip, 1, -1);
165        }
166
167        $packedAddress = inet_pton($ip);
168        if (4 === \strlen($packedAddress)) {
169            $mask = '255.255.255.0';
170        } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff:ffff'))) {
171            $mask = '::ffff:ffff:ff00';
172        } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff'))) {
173            $mask = '::ffff:ff00';
174        } else {
175            $mask = 'ffff:ffff:ffff:ffff:0000:0000:0000:0000';
176        }
177        $ip = inet_ntop($packedAddress & inet_pton($mask));
178
179        if ($wrappedIPv6) {
180            $ip = '['.$ip.']';
181        }
182
183        return $ip;
184    }
185}
186