xref: /dokuwiki/inc/Ip.php (revision 19d5ba27782e35d8c5d7e3db41e9834c96868bbb)
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            $result = unpack('Jupper/Jlower', $binary);
104            $result['version'] = 6;
105            return $result;
106        }
107    }
108
109    /**
110     * Determine if an IP address is equal to another IP or within an IP range.
111     * IPv4 and IPv6 are supported.
112     *
113     * @param string $ip The address to test.
114     * @param string $ipOrRange An IP address or CIDR range.
115     *
116     * @return bool Returns true if the IP matches, false if not.
117     */
118    public static function ipMatches(string $ip, string $ipOrRange): bool
119    {
120        try {
121            // If it's not a range, compare the addresses directly.
122            // Addresses are converted to numbers because the same address may be
123            // represented by different strings, e.g. "::1" and "::0001".
124            if (strpos($ipOrRange, '/') === false) {
125                return Ip::ipToNumber($ip) === Ip::ipToNumber($ipOrRange);
126            }
127
128            return Ip::ipInRange($ip, $ipOrRange);
129        } catch (Exception $ex) {
130            // The IP address was invalid.
131            return false;
132        }
133    }
134
135    /**
136     * Given the IP address of a proxy server, determine whether it is
137     * a known and trusted server.
138     *
139     * This test is performed using the config value `trustedproxies`.
140     *
141     * @param string $ip The IP address of the proxy.
142     *
143     * @return bool Returns true if the IP is trusted as a proxy.
144     */
145    public static function proxyIsTrusted(string $ip): bool
146    {
147        global $conf;
148
149        // If the configuration is empty then no proxies are trusted.
150        if (empty($conf['trustedproxies'])) {
151            return false;
152        }
153
154        foreach ((array) $conf['trustedproxies'] as $trusted) {
155            if (Ip::ipMatches($ip, $trusted)) {
156                return true;
157            }
158        }
159
160        Logger::error('Invalid value for $conf[trustedproxies]');
161        return false;
162    }
163
164    /**
165     * Get the originating IP address and the address of every proxy that the
166     * request has passed through, according to the X-Forwarded-For header.
167     *
168     * To prevent spoofing of the client IP, every proxy listed in the
169     * X-Forwarded-For header must be trusted, as well as the TCP/IP endpoint
170     * from which the connection was received (i.e. the final proxy).
171     *
172     * If the header is not present or contains an untrusted proxy then
173     * an empty array is returned.
174     *
175     * The client IP is the first entry in the returned list, followed by the
176     * proxies.
177     *
178     * @return string[] Returns an array of IP addresses.
179     */
180    public static function forwardedFor(): array
181    {
182        /* @var Input $INPUT */
183        global $INPUT, $conf;
184
185        $forwardedFor = $INPUT->server->str('HTTP_X_FORWARDED_FOR');
186
187        if (empty($conf['trustedproxy']) || !$forwardedFor) {
188            return [];
189        }
190
191        // This is the address from which the header was received.
192        $remoteAddr = $INPUT->server->str('REMOTE_ADDR');
193
194        // Get the client address from the X-Forwarded-For header.
195        // X-Forwarded-For: <client> [, <proxy>]...
196        $forwardedFor = explode(',', str_replace(' ', '', $forwardedFor));
197
198        // The client address is the first item, remove it from the list.
199        $clientAddress = array_shift($forwardedFor);
200
201        // The remaining items are the proxies through which the X-Forwarded-For
202        // header has passed.  The final proxy is the connection's remote address.
203        $proxies = $forwardedFor;
204        $proxies[] = $remoteAddr;
205
206        // Ensure that every proxy is trusted.
207        foreach ($proxies as $proxy) {
208            if (!Ip::proxyIsTrusted($proxy)) {
209                return [];
210            }
211        }
212
213        // Add the client address before the list of proxies.
214        return array_merge([$clientAddress], $proxies);
215    }
216
217    /**
218     * Return the IP of the client.
219     *
220     * The IP is sourced from, in order of preference:
221     *
222     *   - The X-Real-IP header if $conf[realip] is true.
223     *   - The X-Forwarded-For header if all the proxies are trusted by $conf[trustedproxy].
224     *   - The TCP/IP connection remote address.
225     *   - 0.0.0.0 if all else fails.
226     *
227     * The 'realip' config value should only be set to true if the X-Real-IP header
228     * is being added by the web server, otherwise it may be spoofed by the client.
229     *
230     * The 'trustedproxy' setting must not allow any IP, otherwise the X-Forwarded-For
231     * may be spoofed by the client.
232     *
233     * @return string Returns an IPv4 or IPv6 address.
234     */
235    public static function clientIp(): string
236    {
237        return Ip::clientIps()[0];
238    }
239
240    /**
241     * Return the IP of the client and the proxies through which the connection has passed.
242     *
243     * The IPs are sourced from, in order of preference:
244     *
245     *   - The X-Real-IP header if $conf[realip] is true.
246     *   - The X-Forwarded-For header if all the proxies are trusted by $conf[trustedproxies].
247     *   - The TCP/IP connection remote address.
248     *   - 0.0.0.0 if all else fails.
249     *
250     * @return string[] Returns an array of IPv4 or IPv6 addresses.
251     */
252    public static function clientIps(): array
253    {
254        /* @var Input $INPUT */
255        global $INPUT, $conf;
256
257        // IPs in order of most to least preferred.
258        $ips = [];
259
260        // Use the X-Real-IP header if it is enabled by the configuration.
261        if (!empty($conf['realip']) && $INPUT->server->str('HTTP_X_REAL_IP')) {
262            $ips[] = $INPUT->server->str('HTTP_X_REAL_IP');
263        }
264
265        // Add the X-Forwarded-For addresses if all proxies are trusted.
266        $ips = array_merge($ips, Ip::forwardedFor());
267
268        // Add the TCP/IP connection endpoint.
269        $ips[] = $INPUT->server->str('REMOTE_ADDR');
270
271        // Remove invalid IPs.
272        $ips = array_filter($ips, static fn($ip) => filter_var($ip, FILTER_VALIDATE_IP));
273
274        // Remove duplicated IPs.
275        $ips = array_values(array_unique($ips));
276
277        // Add a fallback if for some reason there were no valid IPs.
278        if (!$ips) {
279            $ips[] = '0.0.0.0';
280        }
281
282        return $ips;
283    }
284}
285