aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/Security/Ip/RemoteAddress.php
blob: 4eef88138985539c2f3149685b9345179945f542 (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
<?php

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace OC\Security\Ip;

use OCP\IConfig;
use OCP\IRequest;
use OCP\Security\Ip\IAddress;
use OCP\Security\Ip\IRange;
use OCP\Security\Ip\IRemoteAddress;

class RemoteAddress implements IRemoteAddress, IAddress {
	public const SETTING_NAME = 'allowed_admin_ranges';

	private readonly ?IAddress $ip;

	public function __construct(
		private IConfig $config,
		IRequest $request,
	) {
		$remoteAddress = $request->getRemoteAddress();
		$this->ip = $remoteAddress === ''
			? null
			: new Address($remoteAddress);
	}

	public static function isValid(string $ip): bool {
		return Address::isValid($ip);
	}

	public function matches(IRange ... $ranges): bool {
		return $this->ip === null
			? true
			: $this->ip->matches(... $ranges);
	}

	public function allowsAdminActions(): bool {
		if ($this->ip === null) {
			return true;
		}

		$allowedAdminRanges = $this->config->getSystemValue(self::SETTING_NAME, false);

		// Don't apply restrictions on empty or invalid configuration
		if (
			$allowedAdminRanges === false
			|| !is_array($allowedAdminRanges)
			|| empty($allowedAdminRanges)
		) {
			return true;
		}

		foreach ($allowedAdminRanges as $allowedAdminRange) {
			if ((new Range($allowedAdminRange))->contains($this->ip)) {
				return true;
			}
		}

		return false;
	}

	public function __toString(): string {
		return (string)$this->ip;
	}
}