RemoteAddress.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Security\Ip;
  8. use OCP\IConfig;
  9. use OCP\IRequest;
  10. use OCP\Security\Ip\IAddress;
  11. use OCP\Security\Ip\IRange;
  12. use OCP\Security\Ip\IRemoteAddress;
  13. class RemoteAddress implements IRemoteAddress, IAddress {
  14. public const SETTING_NAME = 'allowed_admin_ranges';
  15. private readonly ?IAddress $ip;
  16. public function __construct(
  17. private IConfig $config,
  18. IRequest $request,
  19. ) {
  20. $remoteAddress = $request->getRemoteAddress();
  21. $this->ip = $remoteAddress === ''
  22. ? null
  23. : new Address($remoteAddress);
  24. }
  25. public static function isValid(string $ip): bool {
  26. return Address::isValid($ip);
  27. }
  28. public function matches(IRange ... $ranges): bool {
  29. return $this->ip === null
  30. ? true
  31. : $this->ip->matches(... $ranges);
  32. }
  33. public function allowsAdminActions(): bool {
  34. if ($this->ip === null) {
  35. return true;
  36. }
  37. $allowedAdminRanges = $this->config->getSystemValue(self::SETTING_NAME, false);
  38. // Don't apply restrictions on empty or invalid configuration
  39. if (
  40. $allowedAdminRanges === false
  41. || !is_array($allowedAdminRanges)
  42. || empty($allowedAdminRanges)
  43. ) {
  44. return true;
  45. }
  46. foreach ($allowedAdminRanges as $allowedAdminRange) {
  47. if ((new Range($allowedAdminRange))->contains($this->ip)) {
  48. return true;
  49. }
  50. }
  51. return false;
  52. }
  53. public function __toString(): string {
  54. return (string)$this->ip;
  55. }
  56. }