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