1
0

DnsPinMiddleware.php 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. $dnsTypes = \defined('AF_INET6') || @inet_pton('::1')
  48. ? [DNS_A, DNS_AAAA, DNS_CNAME]
  49. : [DNS_A, DNS_CNAME];
  50. foreach ($dnsTypes as $dnsType) {
  51. if ($this->negativeDnsCache->isNegativeCached($target, $dnsType)) {
  52. continue;
  53. }
  54. $dnsResponses = $this->dnsGetRecord($target, $dnsType);
  55. $canHaveCnameRecord = true;
  56. if ($dnsResponses !== false && count($dnsResponses) > 0) {
  57. foreach ($dnsResponses as $dnsResponse) {
  58. if (isset($dnsResponse['ip'])) {
  59. $targetIps[] = $dnsResponse['ip'];
  60. $canHaveCnameRecord = false;
  61. } elseif (isset($dnsResponse['ipv6'])) {
  62. $targetIps[] = $dnsResponse['ipv6'];
  63. $canHaveCnameRecord = false;
  64. } elseif (isset($dnsResponse['target']) && $canHaveCnameRecord) {
  65. $targetIps = array_merge($targetIps, $this->dnsResolve($dnsResponse['target'], $recursionCount));
  66. $canHaveCnameRecord = true;
  67. }
  68. }
  69. } elseif ($dnsNegativeTtl !== null) {
  70. $this->negativeDnsCache->setNegativeCacheForDnsType($target, $dnsType, $dnsNegativeTtl);
  71. }
  72. }
  73. return $targetIps;
  74. }
  75. /**
  76. * Wrapper for dns_get_record
  77. */
  78. protected function dnsGetRecord(string $hostname, int $type): array|false {
  79. return \dns_get_record($hostname, $type);
  80. }
  81. public function addDnsPinning() {
  82. return function (callable $handler) {
  83. return function (
  84. RequestInterface $request,
  85. array $options
  86. ) use ($handler) {
  87. if ($options['nextcloud']['allow_local_address'] === true) {
  88. return $handler($request, $options);
  89. }
  90. $hostName = (string)$request->getUri()->getHost();
  91. $port = $request->getUri()->getPort();
  92. $ports = [
  93. '80',
  94. '443',
  95. ];
  96. if ($port !== null) {
  97. $ports[] = (string)$port;
  98. }
  99. $targetIps = $this->dnsResolve(idn_to_utf8($hostName), 0);
  100. if (empty($targetIps)) {
  101. throw new LocalServerException('No DNS record found for ' . $hostName);
  102. }
  103. $curlResolves = [];
  104. foreach ($ports as $port) {
  105. $curlResolves["$hostName:$port"] = [];
  106. foreach ($targetIps as $ip) {
  107. if ($this->ipAddressClassifier->isLocalAddress($ip)) {
  108. // TODO: continue with all non-local IPs?
  109. throw new LocalServerException('Host "'.$ip.'" ('.$hostName.':'.$port.') violates local access rules');
  110. }
  111. $curlResolves["$hostName:$port"][] = $ip;
  112. }
  113. }
  114. // Coalesce the per-host:port ips back into a comma separated list
  115. foreach ($curlResolves as $hostport => $ips) {
  116. $options['curl'][CURLOPT_RESOLVE][] = "$hostport:" . implode(',', $ips);
  117. }
  118. return $handler($request, $options);
  119. };
  120. };
  121. }
  122. }