xref: /dokuwiki/inc/Ip.php (revision da569c7faab5733df1c75ed6eaaa93a85453bb0a)
1c7f6b7b7SZebra North<?php
2c7f6b7b7SZebra North
3c7f6b7b7SZebra North/**
4c7f6b7b7SZebra North * DokuWiki IP address functions.
5c7f6b7b7SZebra North *
6c7f6b7b7SZebra North * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
7c7f6b7b7SZebra North * @author     Zebra North <mrzebra@mrzebra.co.uk>
8c7f6b7b7SZebra North */
9c7f6b7b7SZebra North
10c7f6b7b7SZebra Northnamespace dokuwiki;
11c7f6b7b7SZebra North
12e449acd0SAndreas Gohruse dokuwiki\Input\Input;
13c7f6b7b7SZebra Northuse Exception;
14c7f6b7b7SZebra North
15c7f6b7b7SZebra Northclass Ip
16c7f6b7b7SZebra North{
17c7f6b7b7SZebra North    /**
18c7f6b7b7SZebra North     * Determine whether an IP address is within a given CIDR range.
19c7f6b7b7SZebra North     * The needle and haystack may be either IPv4 or IPv6.
20c7f6b7b7SZebra North     *
21c7f6b7b7SZebra North     * Example:
22c7f6b7b7SZebra North     *
23c7f6b7b7SZebra North     * ipInRange('192.168.11.123', '192.168.0.0/16') === true
24c7f6b7b7SZebra North     * ipInRange('192.168.11.123', '::192.168.0.0/80') === true
25c7f6b7b7SZebra North     * ipInRange('::192.168.11.123', '192.168.0.0/16') === true
26c7f6b7b7SZebra North     * ipInRange('::192.168.11.123', '::192.168.0.0/80') === true
27c7f6b7b7SZebra North     *
28e449acd0SAndreas Gohr     * @param string $needle The IP to test, either IPv4 in dotted decimal
29c7f6b7b7SZebra North     *                         notation or IPv6 in colon notation.
30c7f6b7b7SZebra North     * @param string $haystack The CIDR range as an IP followed by a forward
31c7f6b7b7SZebra North     *                         slash and the number of significant bits.
32c7f6b7b7SZebra North     *
33c7f6b7b7SZebra North     * @return bool Returns true if $needle is within the range specified
34c7f6b7b7SZebra North     *              by $haystack, false if it is outside the range.
35c7f6b7b7SZebra North     *
36c7f6b7b7SZebra North     * @throws Exception Thrown if $needle is not a valid IP address.
37c7f6b7b7SZebra North     * @throws Exception Thrown if $haystack is not a valid IP range.
38c7f6b7b7SZebra North     */
39c7f6b7b7SZebra North    public static function ipInRange(string $needle, string $haystack): bool
40c7f6b7b7SZebra North    {
41c7f6b7b7SZebra North        $range = explode('/', $haystack);
42c7f6b7b7SZebra North        $networkIp = Ip::ipToNumber($range[0]);
43c7f6b7b7SZebra North        $maskLength = $range[1];
44c7f6b7b7SZebra North
45c7f6b7b7SZebra North        // For an IPv4 address the top 96 bits must be zero.
46c7f6b7b7SZebra North        if ($networkIp['version'] === 4) {
47c7f6b7b7SZebra North            $maskLength += 96;
48c7f6b7b7SZebra North        }
49c7f6b7b7SZebra North
50c7f6b7b7SZebra North        if ($maskLength > 128) {
51c7f6b7b7SZebra North            throw new Exception('Invalid IP range mask: ' . $haystack);
52c7f6b7b7SZebra North        }
53c7f6b7b7SZebra North
54c7f6b7b7SZebra North        $maskLengthUpper = min($maskLength, 64);
55c7f6b7b7SZebra North        $maskLengthLower = max(0, $maskLength - 64);
56c7f6b7b7SZebra North
57c7f6b7b7SZebra North        $maskUpper = ~0 << intval(64 - $maskLengthUpper);
58c7f6b7b7SZebra North        $maskLower = ~0 << intval(64 - $maskLengthLower);
59c7f6b7b7SZebra North
60c7f6b7b7SZebra North        $needle = Ip::ipToNumber($needle);
61c7f6b7b7SZebra North
62c7f6b7b7SZebra North        return ($needle['upper'] & $maskUpper) === ($networkIp['upper'] & $maskUpper) &&
63c7f6b7b7SZebra North            ($needle['lower'] & $maskLower) === ($networkIp['lower'] & $maskLower);
64c7f6b7b7SZebra North    }
65c7f6b7b7SZebra North
66c7f6b7b7SZebra North    /**
67c7f6b7b7SZebra North     * Convert an IP address from a string to a number.
68c7f6b7b7SZebra North     *
69c7f6b7b7SZebra North     * This splits 128 bit IP addresses into the upper and lower 64 bits, and
70c7f6b7b7SZebra North     * also returns whether the IP given was IPv4 or IPv6.
71c7f6b7b7SZebra North     *
72c7f6b7b7SZebra North     * The returned array contains:
73c7f6b7b7SZebra North     *
74c7f6b7b7SZebra North     *  - version: Either '4' or '6'.
75c7f6b7b7SZebra North     *  - upper: The upper 64 bits of the IP.
76c7f6b7b7SZebra North     *  - lower: The lower 64 bits of the IP.
77c7f6b7b7SZebra North     *
78c7f6b7b7SZebra North     * For an IPv4 address, 'upper' will always be zero.
79c7f6b7b7SZebra North     *
80e449acd0SAndreas Gohr     * @param string $ip The IPv4 or IPv6 address.
81c7f6b7b7SZebra North     *
82c7f6b7b7SZebra North     * @return int[] Returns an array of 'version', 'upper', 'lower'.
83c7f6b7b7SZebra North     *
84c7f6b7b7SZebra North     * @throws Exception Thrown if the IP is not valid.
85c7f6b7b7SZebra North     */
86c7f6b7b7SZebra North    public static function ipToNumber(string $ip): array
87c7f6b7b7SZebra North    {
88c7f6b7b7SZebra North        $binary = inet_pton($ip);
89c7f6b7b7SZebra North
90c7f6b7b7SZebra North        if ($binary === false) {
91c7f6b7b7SZebra North            throw new Exception('Invalid IP: ' . $ip);
92c7f6b7b7SZebra North        }
93c7f6b7b7SZebra North
94c7f6b7b7SZebra North        if (strlen($binary) === 4) {
95c7f6b7b7SZebra North            // IPv4.
96c7f6b7b7SZebra North            return [
97c7f6b7b7SZebra North                'version' => 4,
98c7f6b7b7SZebra North                'upper' => 0,
99c7f6b7b7SZebra North                'lower' => unpack('Nip', $binary)['ip'],
100c7f6b7b7SZebra North            ];
101c7f6b7b7SZebra North        } else {
102*da569c7fSWillForan            // IPv6. strlen==16
103c9e618caSWillForan            if(PHP_INT_SIZE == 8) { // 64-bit arch
104c7f6b7b7SZebra North               $result = unpack('Jupper/Jlower', $binary);
105c9e618caSWillForan            } else { // 32-bit
106*da569c7fSWillForan               $result = Ip::ipv6_upper_lower_32($binary);
107c9e618caSWillForan            }
108c7f6b7b7SZebra North            $result['version'] = 6;
109c7f6b7b7SZebra North            return $result;
110c7f6b7b7SZebra North        }
111c7f6b7b7SZebra North    }
112c7f6b7b7SZebra North
113c7f6b7b7SZebra North    /**
114*da569c7fSWillForan     * conversion of inet_pton ipv6 into 64-bit upper and lower
115*da569c7fSWillForan     * bcmath version for 32-bit architecture
116*da569c7fSWillForan     * w/o no unpack('J') - unsigned long long (always 64 bit, big endian byte order)
117*da569c7fSWillForan     *
118*da569c7fSWillForan     * results match unpack('Jupper/Jlower', $binary)
119*da569c7fSWillForan     *
120*da569c7fSWillForan     * @param string $binary inet_pton's ipv6 16 element binary
121*da569c7fSWillForan     *
122*da569c7fSWillForan     * @return int[] upper 64 and lower 64 for ipToNumber
123*da569c7fSWillForan     */
124*da569c7fSWillForan    public static function ipv6_upper_lower_32(string $binary) {
125*da569c7fSWillForan       // unpack into four 32-bit unsigned ints to recombine as 2 64-bit
126*da569c7fSWillForan       $b32 = 4294967296; // bcpow(2, 32)
127*da569c7fSWillForan       $parts = unpack('N4', $binary);
128*da569c7fSWillForan       $upper = bcadd(bcmul($parts[1], $b32),
129*da569c7fSWillForan                      $parts[2]);
130*da569c7fSWillForan       $lower = bcadd(bcmul($parts[3], $b32),
131*da569c7fSWillForan                      $parts[4]);
132*da569c7fSWillForan       return ['upper' => $upper, 'lower' => $lower];
133*da569c7fSWillForan    }
134*da569c7fSWillForan
135*da569c7fSWillForan    /**
136c7f6b7b7SZebra North     * Determine if an IP address is equal to another IP or within an IP range.
137c7f6b7b7SZebra North     * IPv4 and IPv6 are supported.
138c7f6b7b7SZebra North     *
139c7f6b7b7SZebra North     * @param string $ip The address to test.
140c7f6b7b7SZebra North     * @param string $ipOrRange An IP address or CIDR range.
141c7f6b7b7SZebra North     *
142c7f6b7b7SZebra North     * @return bool Returns true if the IP matches, false if not.
143c7f6b7b7SZebra North     */
144c7f6b7b7SZebra North    public static function ipMatches(string $ip, string $ipOrRange): bool
145c7f6b7b7SZebra North    {
146c7f6b7b7SZebra North        try {
147c7f6b7b7SZebra North            // If it's not a range, compare the addresses directly.
148c7f6b7b7SZebra North            // Addresses are converted to numbers because the same address may be
149c7f6b7b7SZebra North            // represented by different strings, e.g. "::1" and "::0001".
150c7f6b7b7SZebra North            if (strpos($ipOrRange, '/') === false) {
151c7f6b7b7SZebra North                return Ip::ipToNumber($ip) === Ip::ipToNumber($ipOrRange);
152c7f6b7b7SZebra North            }
153c7f6b7b7SZebra North
154c7f6b7b7SZebra North            return Ip::ipInRange($ip, $ipOrRange);
155c7f6b7b7SZebra North        } catch (Exception $ex) {
156c7f6b7b7SZebra North            // The IP address was invalid.
157c7f6b7b7SZebra North            return false;
158c7f6b7b7SZebra North        }
159c7f6b7b7SZebra North    }
160c7f6b7b7SZebra North
161c7f6b7b7SZebra North    /**
162c7f6b7b7SZebra North     * Given the IP address of a proxy server, determine whether it is
163c7f6b7b7SZebra North     * a known and trusted server.
164c7f6b7b7SZebra North     *
16519d5ba27SAndreas Gohr     * This test is performed using the config value `trustedproxies`.
166c7f6b7b7SZebra North     *
167c7f6b7b7SZebra North     * @param string $ip The IP address of the proxy.
168c7f6b7b7SZebra North     *
169c7f6b7b7SZebra North     * @return bool Returns true if the IP is trusted as a proxy.
170c7f6b7b7SZebra North     */
171c7f6b7b7SZebra North    public static function proxyIsTrusted(string $ip): bool
172c7f6b7b7SZebra North    {
173c7f6b7b7SZebra North        global $conf;
174c7f6b7b7SZebra North
175c7f6b7b7SZebra North        // If the configuration is empty then no proxies are trusted.
17619d5ba27SAndreas Gohr        if (empty($conf['trustedproxies'])) {
177c7f6b7b7SZebra North            return false;
178c7f6b7b7SZebra North        }
179c7f6b7b7SZebra North
18019d5ba27SAndreas Gohr        foreach ((array)$conf['trustedproxies'] as $trusted) {
181c7f6b7b7SZebra North            if (Ip::ipMatches($ip, $trusted)) {
182ced0b55fSAndreas Gohr                return true; // The given IP matches one of the trusted proxies.
183c7f6b7b7SZebra North            }
184c7f6b7b7SZebra North        }
185c7f6b7b7SZebra North
186ced0b55fSAndreas Gohr        return false; // none of the proxies matched
187c7f6b7b7SZebra North    }
188c7f6b7b7SZebra North
189c7f6b7b7SZebra North    /**
190c7f6b7b7SZebra North     * Get the originating IP address and the address of every proxy that the
191c7f6b7b7SZebra North     * request has passed through, according to the X-Forwarded-For header.
192c7f6b7b7SZebra North     *
193c7f6b7b7SZebra North     * To prevent spoofing of the client IP, every proxy listed in the
194c7f6b7b7SZebra North     * X-Forwarded-For header must be trusted, as well as the TCP/IP endpoint
195c7f6b7b7SZebra North     * from which the connection was received (i.e. the final proxy).
196c7f6b7b7SZebra North     *
197c7f6b7b7SZebra North     * If the header is not present or contains an untrusted proxy then
198c7f6b7b7SZebra North     * an empty array is returned.
199c7f6b7b7SZebra North     *
200c7f6b7b7SZebra North     * The client IP is the first entry in the returned list, followed by the
201c7f6b7b7SZebra North     * proxies.
202c7f6b7b7SZebra North     *
203c7f6b7b7SZebra North     * @return string[] Returns an array of IP addresses.
204c7f6b7b7SZebra North     */
205c7f6b7b7SZebra North    public static function forwardedFor(): array
206c7f6b7b7SZebra North    {
207c7f6b7b7SZebra North        /* @var Input $INPUT */
208c7f6b7b7SZebra North        global $INPUT, $conf;
209c7f6b7b7SZebra North
210c7f6b7b7SZebra North        $forwardedFor = $INPUT->server->str('HTTP_X_FORWARDED_FOR');
211c7f6b7b7SZebra North
212ced0b55fSAndreas Gohr        if (empty($conf['trustedproxies']) || !$forwardedFor) {
213c7f6b7b7SZebra North            return [];
214c7f6b7b7SZebra North        }
215c7f6b7b7SZebra North
216c7f6b7b7SZebra North        // This is the address from which the header was received.
217c7f6b7b7SZebra North        $remoteAddr = $INPUT->server->str('REMOTE_ADDR');
218c7f6b7b7SZebra North
219c7f6b7b7SZebra North        // Get the client address from the X-Forwarded-For header.
220c7f6b7b7SZebra North        // X-Forwarded-For: <client> [, <proxy>]...
221c7f6b7b7SZebra North        $forwardedFor = explode(',', str_replace(' ', '', $forwardedFor));
222c7f6b7b7SZebra North
223c7f6b7b7SZebra North        // The client address is the first item, remove it from the list.
224c7f6b7b7SZebra North        $clientAddress = array_shift($forwardedFor);
225c7f6b7b7SZebra North
226c7f6b7b7SZebra North        // The remaining items are the proxies through which the X-Forwarded-For
227c7f6b7b7SZebra North        // header has passed.  The final proxy is the connection's remote address.
228c7f6b7b7SZebra North        $proxies = $forwardedFor;
229c7f6b7b7SZebra North        $proxies[] = $remoteAddr;
230c7f6b7b7SZebra North
231c7f6b7b7SZebra North        // Ensure that every proxy is trusted.
232c7f6b7b7SZebra North        foreach ($proxies as $proxy) {
233c7f6b7b7SZebra North            if (!Ip::proxyIsTrusted($proxy)) {
234c7f6b7b7SZebra North                return [];
235c7f6b7b7SZebra North            }
236c7f6b7b7SZebra North        }
237c7f6b7b7SZebra North
238c7f6b7b7SZebra North        // Add the client address before the list of proxies.
239c7f6b7b7SZebra North        return array_merge([$clientAddress], $proxies);
240c7f6b7b7SZebra North    }
241c7f6b7b7SZebra North
242c7f6b7b7SZebra North    /**
243c7f6b7b7SZebra North     * Return the IP of the client.
244c7f6b7b7SZebra North     *
245c7f6b7b7SZebra North     * The IP is sourced from, in order of preference:
246c7f6b7b7SZebra North     *
247c7f6b7b7SZebra North     *   - The X-Real-IP header if $conf[realip] is true.
248c7f6b7b7SZebra North     *   - The X-Forwarded-For header if all the proxies are trusted by $conf[trustedproxy].
249c7f6b7b7SZebra North     *   - The TCP/IP connection remote address.
250c7f6b7b7SZebra North     *   - 0.0.0.0 if all else fails.
251c7f6b7b7SZebra North     *
252c7f6b7b7SZebra North     * The 'realip' config value should only be set to true if the X-Real-IP header
253c7f6b7b7SZebra North     * is being added by the web server, otherwise it may be spoofed by the client.
254c7f6b7b7SZebra North     *
255c7f6b7b7SZebra North     * The 'trustedproxy' setting must not allow any IP, otherwise the X-Forwarded-For
256c7f6b7b7SZebra North     * may be spoofed by the client.
257c7f6b7b7SZebra North     *
258c7f6b7b7SZebra North     * @return string Returns an IPv4 or IPv6 address.
259c7f6b7b7SZebra North     */
260c7f6b7b7SZebra North    public static function clientIp(): string
261c7f6b7b7SZebra North    {
262c7f6b7b7SZebra North        return Ip::clientIps()[0];
263c7f6b7b7SZebra North    }
264c7f6b7b7SZebra North
265c7f6b7b7SZebra North    /**
266c7f6b7b7SZebra North     * Return the IP of the client and the proxies through which the connection has passed.
267c7f6b7b7SZebra North     *
268c7f6b7b7SZebra North     * The IPs are sourced from, in order of preference:
269c7f6b7b7SZebra North     *
270c7f6b7b7SZebra North     *   - The X-Real-IP header if $conf[realip] is true.
27119d5ba27SAndreas Gohr     *   - The X-Forwarded-For header if all the proxies are trusted by $conf[trustedproxies].
272c7f6b7b7SZebra North     *   - The TCP/IP connection remote address.
273c7f6b7b7SZebra North     *   - 0.0.0.0 if all else fails.
274c7f6b7b7SZebra North     *
275c7f6b7b7SZebra North     * @return string[] Returns an array of IPv4 or IPv6 addresses.
276c7f6b7b7SZebra North     */
277c7f6b7b7SZebra North    public static function clientIps(): array
278c7f6b7b7SZebra North    {
279c7f6b7b7SZebra North        /* @var Input $INPUT */
280c7f6b7b7SZebra North        global $INPUT, $conf;
281c7f6b7b7SZebra North
282c7f6b7b7SZebra North        // IPs in order of most to least preferred.
283c7f6b7b7SZebra North        $ips = [];
284c7f6b7b7SZebra North
285c7f6b7b7SZebra North        // Use the X-Real-IP header if it is enabled by the configuration.
286c7f6b7b7SZebra North        if (!empty($conf['realip']) && $INPUT->server->str('HTTP_X_REAL_IP')) {
287c7f6b7b7SZebra North            $ips[] = $INPUT->server->str('HTTP_X_REAL_IP');
288c7f6b7b7SZebra North        }
289c7f6b7b7SZebra North
290c7f6b7b7SZebra North        // Add the X-Forwarded-For addresses if all proxies are trusted.
291c7f6b7b7SZebra North        $ips = array_merge($ips, Ip::forwardedFor());
292c7f6b7b7SZebra North
293c7f6b7b7SZebra North        // Add the TCP/IP connection endpoint.
294c7f6b7b7SZebra North        $ips[] = $INPUT->server->str('REMOTE_ADDR');
295c7f6b7b7SZebra North
296c7f6b7b7SZebra North        // Remove invalid IPs.
297e449acd0SAndreas Gohr        $ips = array_filter($ips, static fn($ip) => filter_var($ip, FILTER_VALIDATE_IP));
298c7f6b7b7SZebra North
299c7f6b7b7SZebra North        // Remove duplicated IPs.
300c7f6b7b7SZebra North        $ips = array_values(array_unique($ips));
301c7f6b7b7SZebra North
302c7f6b7b7SZebra North        // Add a fallback if for some reason there were no valid IPs.
303c7f6b7b7SZebra North        if (!$ips) {
304c7f6b7b7SZebra North            $ips[] = '0.0.0.0';
305c7f6b7b7SZebra North        }
306c7f6b7b7SZebra North
307c7f6b7b7SZebra North        return $ips;
308c7f6b7b7SZebra North    }
309c7f6b7b7SZebra North}
310