1
0

DnsPinMiddleware.php 4.5 KB

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