1
0

DnsPinMiddleware.php 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Http\Client;
  8. use OC\Net\IpAddressClassifier;
  9. use OCP\Http\Client\LocalServerException;
  10. use Psr\Http\Message\RequestInterface;
  11. class DnsPinMiddleware {
  12. /** @var NegativeDnsCache */
  13. private $negativeDnsCache;
  14. private IpAddressClassifier $ipAddressClassifier;
  15. public function __construct(
  16. NegativeDnsCache $negativeDnsCache,
  17. IpAddressClassifier $ipAddressClassifier,
  18. ) {
  19. $this->negativeDnsCache = $negativeDnsCache;
  20. $this->ipAddressClassifier = $ipAddressClassifier;
  21. }
  22. /**
  23. * Fetch soa record for a target
  24. *
  25. * @param string $target
  26. * @return array|null
  27. */
  28. private function soaRecord(string $target): ?array {
  29. $labels = explode('.', $target);
  30. $top = count($labels) >= 2 ? array_pop($labels) : '';
  31. $second = array_pop($labels);
  32. $hostname = $second . '.' . $top;
  33. $responses = $this->dnsGetRecord($hostname, DNS_SOA);
  34. if ($responses === false || count($responses) === 0) {
  35. return null;
  36. }
  37. return reset($responses);
  38. }
  39. private function dnsResolve(string $target, int $recursionCount) : array {
  40. if ($recursionCount >= 10) {
  41. return [];
  42. }
  43. $recursionCount++;
  44. $targetIps = [];
  45. $soaDnsEntry = $this->soaRecord($target);
  46. $dnsNegativeTtl = $soaDnsEntry['minimum-ttl'] ?? null;
  47. $canHaveCnameRecord = true;
  48. $dnsTypes = \defined('AF_INET6') || @inet_pton('::1')
  49. ? [DNS_A, DNS_AAAA, DNS_CNAME]
  50. : [DNS_A, DNS_CNAME];
  51. foreach ($dnsTypes as $dnsType) {
  52. if ($canHaveCnameRecord === false && $dnsType === DNS_CNAME) {
  53. continue;
  54. }
  55. if ($this->negativeDnsCache->isNegativeCached($target, $dnsType)) {
  56. continue;
  57. }
  58. $dnsResponses = $this->dnsGetRecord($target, $dnsType);
  59. if ($dnsResponses !== false && count($dnsResponses) > 0) {
  60. foreach ($dnsResponses as $dnsResponse) {
  61. if (isset($dnsResponse['ip'])) {
  62. $targetIps[] = $dnsResponse['ip'];
  63. $canHaveCnameRecord = false;
  64. } elseif (isset($dnsResponse['ipv6'])) {
  65. $targetIps[] = $dnsResponse['ipv6'];
  66. $canHaveCnameRecord = false;
  67. } elseif (isset($dnsResponse['target']) && $canHaveCnameRecord) {
  68. $targetIps = array_merge($targetIps, $this->dnsResolve($dnsResponse['target'], $recursionCount));
  69. }
  70. }
  71. } elseif ($dnsNegativeTtl !== null) {
  72. $this->negativeDnsCache->setNegativeCacheForDnsType($target, $dnsType, $dnsNegativeTtl);
  73. }
  74. }
  75. return $targetIps;
  76. }
  77. /**
  78. * Wrapper for dns_get_record
  79. */
  80. protected function dnsGetRecord(string $hostname, int $type): array|false {
  81. return \dns_get_record($hostname, $type);
  82. }
  83. public function addDnsPinning() {
  84. return function (callable $handler) {
  85. return function (
  86. RequestInterface $request,
  87. array $options,
  88. ) use ($handler) {
  89. if ($options['nextcloud']['allow_local_address'] === true) {
  90. return $handler($request, $options);
  91. }
  92. $hostName = (string)$request->getUri()->getHost();
  93. $port = $request->getUri()->getPort();
  94. $ports = [
  95. '80',
  96. '443',
  97. ];
  98. if ($port !== null) {
  99. $ports[] = (string)$port;
  100. }
  101. $targetIps = $this->dnsResolve(idn_to_utf8($hostName), 0);
  102. if (empty($targetIps)) {
  103. throw new LocalServerException('No DNS record found for ' . $hostName);
  104. }
  105. $curlResolves = [];
  106. foreach ($ports as $port) {
  107. $curlResolves["$hostName:$port"] = [];
  108. foreach ($targetIps as $ip) {
  109. if ($this->ipAddressClassifier->isLocalAddress($ip)) {
  110. // TODO: continue with all non-local IPs?
  111. throw new LocalServerException('Host "' . $ip . '" (' . $hostName . ':' . $port . ') violates local access rules');
  112. }
  113. $curlResolves["$hostName:$port"][] = $ip;
  114. }
  115. }
  116. // Coalesce the per-host:port ips back into a comma separated list
  117. foreach ($curlResolves as $hostport => $ips) {
  118. $options['curl'][CURLOPT_RESOLVE][] = "$hostport:" . implode(',', $ips);
  119. }
  120. return $handler($request, $options);
  121. };
  122. };
  123. }
  124. }