DnsPinMiddleware.php 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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 = dns_get_record($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 = dns_get_record($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. public function addDnsPinning() {
  91. return function (callable $handler) {
  92. return function (
  93. RequestInterface $request,
  94. array $options
  95. ) use ($handler) {
  96. if ($options['nextcloud']['allow_local_address'] === true) {
  97. return $handler($request, $options);
  98. }
  99. $hostName = (string)$request->getUri()->getHost();
  100. $port = $request->getUri()->getPort();
  101. $ports = [
  102. '80',
  103. '443',
  104. ];
  105. if ($port !== null) {
  106. $ports[] = (string)$port;
  107. }
  108. $targetIps = $this->dnsResolve(idn_to_utf8($hostName), 0);
  109. $curlResolves = [];
  110. foreach ($ports as $port) {
  111. $curlResolves["$hostName:$port"] = [];
  112. foreach ($targetIps as $ip) {
  113. if ($this->ipAddressClassifier->isLocalAddress($ip)) {
  114. // TODO: continue with all non-local IPs?
  115. throw new LocalServerException('Host violates local access rules');
  116. }
  117. $curlResolves["$hostName:$port"][] = $ip;
  118. }
  119. }
  120. // Coalesce the per-host:port ips back into a comma separated list
  121. foreach ($curlResolves as $hostport => $ips) {
  122. $options['curl'][CURLOPT_RESOLVE][] = "$hostport:" . implode(',', $ips);
  123. }
  124. return $handler($request, $options);
  125. };
  126. };
  127. }
  128. }