HostnameClassifier.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Net;
  8. use function filter_var;
  9. use function in_array;
  10. use function strrchr;
  11. use function substr;
  12. use function substr_count;
  13. /**
  14. * Classifier for network hostnames
  15. *
  16. * @internal
  17. */
  18. class HostnameClassifier {
  19. private const LOCAL_TOPLEVEL_DOMAINS = [
  20. 'local',
  21. 'localhost',
  22. 'intranet',
  23. 'internal',
  24. 'private',
  25. 'corp',
  26. 'home',
  27. 'lan',
  28. ];
  29. /**
  30. * Check host identifier for local hostname
  31. *
  32. * IP addresses are not considered local. Use the IpAddressClassifier for those.
  33. */
  34. public function isLocalHostname(string $hostname): bool {
  35. // Disallow local network top-level domains from RFC 6762
  36. $topLevelDomain = substr((strrchr($hostname, '.') ?: ''), 1);
  37. if (in_array($topLevelDomain, self::LOCAL_TOPLEVEL_DOMAINS)) {
  38. return true;
  39. }
  40. // Disallow hostname only
  41. if (substr_count($hostname, '.') === 0 && !filter_var($hostname, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
  42. return true;
  43. }
  44. return false;
  45. }
  46. }