aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/Security/Normalizer/IpAddress.php
blob: e9232c5fe9f2600a6e2d1122c02a4cd3e7440dea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */
namespace OC\Security\Normalizer;

/**
 * Class IpAddress is used for normalizing IPv4 and IPv6 addresses in security
 * relevant contexts in Nextcloud.
 *
 * @package OC\Security\Normalizer
 */
class IpAddress {
	/**
	 * @param string $ip IP to normalize
	 */
	public function __construct(
		private string $ip,
	) {
	}

	/**
	 * Return the given subnet for an IPv6 address (64 first bits)
	 */
	private function getIPv6Subnet(string $ip): string {
		if ($ip[0] === '[' && $ip[-1] === ']') { // If IP is with brackets, for example [::1]
			$ip = substr($ip, 1, strlen($ip) - 2);
		}
		$pos = strpos($ip, '%'); // if there is an explicit interface added to the IP, e.g. fe80::ae2d:d1e7:fe1e:9a8d%enp2s0
		if ($pos !== false) {
			$ip = substr($ip, 0, $pos - 1);
		}

		$binary = \inet_pton($ip);
		$mask = inet_pton('FFFF:FFFF:FFFF:FFFF::');

		return inet_ntop($binary & $mask) . '/64';
	}

	/**
	 * Returns the IPv4 address embedded in an IPv6 if applicable.
	 * The detected format is "::ffff:x.x.x.x" using the binary form.
	 *
	 * @return string|null embedded IPv4 string or null if none was found
	 */
	private function getEmbeddedIpv4(string $ipv6): ?string {
		$binary = inet_pton($ipv6);
		if (!$binary) {
			return null;
		}

		$mask = inet_pton('::FFFF:FFFF');
		if (($binary & ~$mask) !== inet_pton('::FFFF:0.0.0.0')) {
			return null;
		}

		return inet_ntop(substr($binary, -4));
	}


	/**
	 * Gets either the /32 (IPv4) or the /64 (IPv6) subnet of an IP address
	 */
	public function getSubnet(): string {
		if (filter_var($this->ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
			return $this->ip . '/32';
		}

		$ipv4 = $this->getEmbeddedIpv4($this->ip);
		if ($ipv4 !== null) {
			return $ipv4 . '/32';
		}

		return $this->getIPv6Subnet($this->ip);
	}

	/**
	 * Returns the specified IP address
	 */
	public function __toString(): string {
		return $this->ip;
	}
}