DnsPinMiddleware.php 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2021, Lukas Reschke <lukas@statuscode.ch>
  5. *
  6. * @author Lukas Reschke <lukas@statuscode.ch>
  7. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OC\Http\Client;
  25. use OC\Net\IpAddressClassifier;
  26. use OCP\Http\Client\LocalServerException;
  27. use Psr\Http\Message\RequestInterface;
  28. class DnsPinMiddleware {
  29. /** @var NegativeDnsCache */
  30. private $negativeDnsCache;
  31. private IpAddressClassifier $ipAddressClassifier;
  32. public function __construct(
  33. NegativeDnsCache $negativeDnsCache,
  34. IpAddressClassifier $ipAddressClassifier
  35. ) {
  36. $this->negativeDnsCache = $negativeDnsCache;
  37. $this->ipAddressClassifier = $ipAddressClassifier;
  38. }
  39. /**
  40. * Fetch soa record for a target
  41. *
  42. * @param string $target
  43. * @return array|null
  44. */
  45. private function soaRecord(string $target): ?array {
  46. $labels = explode('.', $target);
  47. $top = count($labels) >= 2 ? array_pop($labels) : '';
  48. $second = array_pop($labels);
  49. $hostname = $second . '.' . $top;
  50. $responses = $this->dnsGetRecord($hostname, DNS_SOA);
  51. if ($responses === false || count($responses) === 0) {
  52. return null;
  53. }
  54. return reset($responses);
  55. }
  56. private function dnsResolve(string $target, int $recursionCount) : array {
  57. if ($recursionCount >= 10) {
  58. return [];
  59. }
  60. $recursionCount++;
  61. $targetIps = [];
  62. $soaDnsEntry = $this->soaRecord($target);
  63. $dnsNegativeTtl = $soaDnsEntry['minimum-ttl'] ?? null;
  64. $canHaveCnameRecord = true;
  65. $dnsTypes = [DNS_A, DNS_AAAA, DNS_CNAME];
  66. foreach ($dnsTypes as $dnsType) {
  67. if ($canHaveCnameRecord === false && $dnsType === DNS_CNAME) {
  68. continue;
  69. }
  70. if ($this->negativeDnsCache->isNegativeCached($target, $dnsType)) {
  71. continue;
  72. }
  73. $dnsResponses = $this->dnsGetRecord($target, $dnsType);
  74. if ($dnsResponses !== false && count($dnsResponses) > 0) {
  75. foreach ($dnsResponses as $dnsResponse) {
  76. if (isset($dnsResponse['ip'])) {
  77. $targetIps[] = $dnsResponse['ip'];
  78. $canHaveCnameRecord = false;
  79. } elseif (isset($dnsResponse['ipv6'])) {
  80. $targetIps[] = $dnsResponse['ipv6'];
  81. $canHaveCnameRecord = false;
  82. } elseif (isset($dnsResponse['target']) && $canHaveCnameRecord) {
  83. $targetIps = array_merge($targetIps, $this->dnsResolve($dnsResponse['target'], $recursionCount));
  84. }
  85. }
  86. } elseif ($dnsNegativeTtl !== null) {
  87. $this->negativeDnsCache->setNegativeCacheForDnsType($target, $dnsType, $dnsNegativeTtl);
  88. }
  89. }
  90. return $targetIps;
  91. }
  92. /**
  93. * Wrapper for dns_get_record
  94. */
  95. protected function dnsGetRecord(string $hostname, int $type): array|false {
  96. return \dns_get_record($hostname, $type);
  97. }
  98. public function addDnsPinning() {
  99. return function (callable $handler) {
  100. return function (
  101. RequestInterface $request,
  102. array $options
  103. ) use ($handler) {
  104. if ($options['nextcloud']['allow_local_address'] === true) {
  105. return $handler($request, $options);
  106. }
  107. $hostName = (string)$request->getUri()->getHost();
  108. $port = $request->getUri()->getPort();
  109. $ports = [
  110. '80',
  111. '443',
  112. ];
  113. if ($port !== null) {
  114. $ports[] = (string)$port;
  115. }
  116. $targetIps = $this->dnsResolve(idn_to_utf8($hostName), 0);
  117. if (empty($targetIps)) {
  118. throw new LocalServerException('No DNS record found for ' . $hostName);
  119. }
  120. $curlResolves = [];
  121. foreach ($ports as $port) {
  122. $curlResolves["$hostName:$port"] = [];
  123. foreach ($targetIps as $ip) {
  124. if ($this->ipAddressClassifier->isLocalAddress($ip)) {
  125. // TODO: continue with all non-local IPs?
  126. throw new LocalServerException('Host violates local access rules');
  127. }
  128. $curlResolves["$hostName:$port"][] = $ip;
  129. }
  130. }
  131. // Coalesce the per-host:port ips back into a comma separated list
  132. foreach ($curlResolves as $hostport => $ips) {
  133. $options['curl'][CURLOPT_RESOLVE][] = "$hostport:" . implode(',', $ips);
  134. }
  135. return $handler($request, $options);
  136. };
  137. };
  138. }
  139. }