dns-over-https/lib/Rfc8484StubResolver.php

466 lines
17 KiB
PHP
Raw Normal View History

2019-06-10 19:32:28 +02:00
<?php
namespace Amp\DoH;
use Amp\Cache\Cache;
2022-10-29 20:03:07 +02:00
use Amp\Cancellation;
use Amp\CompositeException;
2019-06-12 13:03:38 +02:00
use Amp\Dns\Config;
2019-06-11 20:07:46 +02:00
use Amp\Dns\ConfigException;
2022-10-29 20:03:07 +02:00
use Amp\Dns\ConfigLoader;
2019-06-10 19:32:28 +02:00
use Amp\Dns\DnsException;
use Amp\Dns\NoRecordException;
2019-06-11 19:07:51 +02:00
use Amp\Dns\Record;
use Amp\Dns\Resolver;
2022-10-29 20:03:07 +02:00
use Amp\Dns\Rfc1035StubResolver;
2019-06-11 19:07:51 +02:00
use Amp\Dns\TimeoutException;
2022-10-29 20:03:07 +02:00
use Amp\Future;
use Amp\Http\Client\DelegateHttpClient;
use Amp\Http\Client\Request;
use Amp\NullCancellation;
use danog\LibDNSJson\JsonDecoder;
use danog\LibDNSJson\JsonDecoderFactory;
use danog\LibDNSJson\QueryEncoderFactory;
use LibDNS\Decoder\Decoder;
use LibDNS\Decoder\DecoderFactory;
use LibDNS\Encoder\Encoder;
use LibDNS\Encoder\EncoderFactory;
2019-06-10 19:32:28 +02:00
use LibDNS\Messages\Message;
2022-10-29 20:03:07 +02:00
use LibDNS\Messages\MessageFactory;
use LibDNS\Messages\MessageTypes;
2019-06-10 19:32:28 +02:00
use LibDNS\Records\Question;
use LibDNS\Records\QuestionFactory;
2022-10-29 20:03:07 +02:00
use function Amp\async;
2019-06-11 20:07:46 +02:00
use function Amp\Dns\normalizeName;
2019-06-10 19:32:28 +02:00
final class Rfc8484StubResolver implements Resolver
{
const CACHE_PREFIX = "amphp.doh.";
2022-10-29 20:03:07 +02:00
private ConfigLoader $configLoader;
private QuestionFactory $questionFactory;
private ?Config $config = null;
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
private ?Future $pendingConfig = null;
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
private Cache $cache;
2019-06-10 19:32:28 +02:00
2022-10-30 20:47:30 +01:00
/** @var Future[] */
2022-10-29 20:03:07 +02:00
private array $pendingQueries = [];
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
private Rfc1035StubResolver $subResolver;
private Encoder $encoder;
private Decoder $decoder;
2022-10-30 20:47:30 +01:00
private Encoder $encoderJson;
2022-10-29 20:03:07 +02:00
private JsonDecoder $decoderJson;
private MessageFactory $messageFactory;
private DelegateHttpClient $httpClient;
2019-06-10 21:04:10 +02:00
2022-10-29 20:03:07 +02:00
public function __construct(private DoHConfig $dohConfig)
2019-06-10 19:32:28 +02:00
{
2022-10-29 20:03:07 +02:00
$this->cache = $dohConfig->getCache();
$this->configLoader = $dohConfig->getConfigLoader();
$this->subResolver = $dohConfig->getSubResolver();
2019-06-10 19:32:28 +02:00
$this->questionFactory = new QuestionFactory;
2022-10-29 20:03:07 +02:00
$this->encoder = (new EncoderFactory)->create();
$this->decoder = (new DecoderFactory)->create();
$this->encoderJson = (new QueryEncoderFactory)->create();
$this->decoderJson = (new JsonDecoderFactory)->create();
$this->httpClient = $dohConfig->getHttpClient();
$this->messageFactory = new MessageFactory;
2019-06-10 19:32:28 +02:00
}
/** @inheritdoc */
2022-10-29 20:03:07 +02:00
public function resolve(string $name, int $typeRestriction = null, ?Cancellation $cancellation = null): array
2019-06-10 19:32:28 +02:00
{
if ($typeRestriction !== null && $typeRestriction !== Record::A && $typeRestriction !== Record::AAAA) {
throw new \Error("Invalid value for parameter 2: null|Record::A|Record::AAAA expected");
}
2022-10-29 20:03:07 +02:00
if (!$this->config) {
try {
$this->reloadConfig();
} catch (ConfigException $e) {
$this->config = new Config(['0.0.0.0'], []);
2019-06-10 19:32:28 +02:00
}
2022-10-29 20:03:07 +02:00
}
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
switch ($typeRestriction) {
case Record::A:
if (\filter_var($name, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return [new Record($name, Record::A, null)];
2022-10-29 20:07:24 +02:00
}
if (\filter_var($name, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
2022-10-29 20:03:07 +02:00
throw new DnsException("Got an IPv6 address, but type is restricted to IPv4");
}
break;
case Record::AAAA:
if (\filter_var($name, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
return [new Record($name, Record::AAAA, null)];
2022-10-29 20:07:24 +02:00
}
if (\filter_var($name, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
2022-10-29 20:03:07 +02:00
throw new DnsException("Got an IPv4 address, but type is restricted to IPv6");
}
break;
default:
if (\filter_var($name, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return [new Record($name, Record::A, null)];
2022-10-29 20:07:24 +02:00
}
if (\filter_var($name, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
2022-10-29 20:03:07 +02:00
return [new Record($name, Record::AAAA, null)];
}
break;
}
2019-06-10 19:32:28 +02:00
2022-10-29 20:07:24 +02:00
$dots = \substr_count($name, ".");
$trailingDot = $name[-1] === ".";
2022-10-29 20:03:07 +02:00
$name = normalizeName($name);
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
if ($records = $this->queryHosts($name, $typeRestriction)) {
return $records;
}
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
// Follow RFC 6761 and never send queries for localhost to the caching DNS server
// Usually, these queries are already resolved via queryHosts()
if ($name === 'localhost') {
return $typeRestriction === Record::AAAA
2019-06-10 19:32:28 +02:00
? [new Record('::1', Record::AAAA, null)]
: [new Record('127.0.0.1', Record::A, null)];
2022-10-29 20:03:07 +02:00
}
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
if ($this->dohConfig->isNameserver($name)) {
return $this->subResolver->resolve($name, $typeRestriction, $cancellation);
}
2022-10-29 20:07:24 +02:00
\assert($this->config !== null);
2019-06-11 19:07:51 +02:00
2022-10-29 20:07:24 +02:00
$searchList = [null];
if (!$trailingDot && $dots < $this->config->getNdots()) {
$searchList = \array_merge($this->config->getSearchList(), $searchList);
}
foreach ($searchList as $searchIndex => $search) {
for ($redirects = 0; $redirects < 5; $redirects++) {
$searchName = $name;
if ($search !== null) {
$searchName = $name . "." . $search;
2022-10-29 20:03:07 +02:00
}
2019-06-10 21:04:10 +02:00
2022-10-29 20:07:24 +02:00
try {
if ($typeRestriction) {
return $this->query($searchName, $typeRestriction, $cancellation);
}
2022-10-29 20:03:07 +02:00
2022-10-29 20:07:24 +02:00
[$exceptions, $records] = Future\awaitAll([
async(fn () => $this->query($searchName, Record::A, $cancellation)),
async(fn () => $this->query($searchName, Record::AAAA, $cancellation)),
]);
if (\count($exceptions) === 2) {
$errors = [];
foreach ($exceptions as $reason) {
if ($reason instanceof NoRecordException) {
throw $reason;
}
if ($searchIndex < \count($searchList) - 1 && \in_array($reason->getCode(), [2, 3], true)) {
continue 2;
}
2022-10-29 20:03:07 +02:00
2022-10-29 20:07:24 +02:00
$errors[] = $reason->getMessage();
2022-10-29 20:03:07 +02:00
}
2022-10-29 20:07:24 +02:00
throw new DnsException(
"All query attempts failed for {$searchName}: " . \implode(", ", $errors),
0,
new CompositeException($exceptions)
);
2019-06-10 19:32:28 +02:00
}
2022-10-29 20:03:07 +02:00
2022-10-29 20:07:24 +02:00
return \array_merge(...$records);
2022-10-29 20:03:07 +02:00
} catch (NoRecordException) {
2022-10-29 20:07:24 +02:00
try {
$cnameRecords = $this->query($searchName, Record::CNAME, $cancellation);
$name = $cnameRecords[0]->getValue();
continue;
} catch (NoRecordException) {
$dnameRecords = $this->query($searchName, Record::DNAME, $cancellation);
$name = $dnameRecords[0]->getValue();
continue;
}
} catch (DnsException $e) {
if ($searchIndex < \count($searchList) - 1 && \in_array($e->getCode(), [2, 3], true)) {
continue 2;
}
throw $e;
2019-06-10 19:32:28 +02:00
}
}
2022-10-29 20:03:07 +02:00
}
2019-06-10 19:32:28 +02:00
2022-10-29 20:07:24 +02:00
\assert(isset($searchName));
throw new DnsException("Giving up resolution of '{$searchName}', too many redirects");
2019-06-10 19:32:28 +02:00
}
/**
* Reloads the configuration in the background.
*
* Once it's finished, the configuration will be used for new requests.
*/
2022-10-29 20:03:07 +02:00
public function reloadConfig(): void
2019-06-10 19:32:28 +02:00
{
2022-10-29 20:03:07 +02:00
if (!$this->pendingConfig) {
2022-10-29 20:44:35 +02:00
$promise = async(function () {
2022-10-29 20:03:07 +02:00
try {
$this->subResolver->reloadConfig();
$this->config = $this->configLoader->loadConfig();
} finally {
$this->pendingConfig = null;
}
});
2022-10-29 20:44:35 +02:00
$this->pendingConfig = $promise;
2019-06-10 19:32:28 +02:00
}
2022-10-29 20:03:07 +02:00
$this->pendingConfig->await();
2019-06-10 19:32:28 +02:00
}
private function queryHosts(string $name, int $typeRestriction = null): array
{
2022-10-30 20:47:30 +01:00
\assert($this->config !== null);
2019-06-10 19:32:28 +02:00
$hosts = $this->config->getKnownHosts();
$records = [];
$returnIPv4 = $typeRestriction === null || $typeRestriction === Record::A;
$returnIPv6 = $typeRestriction === null || $typeRestriction === Record::AAAA;
if ($returnIPv4 && isset($hosts[Record::A][$name])) {
$records[] = new Record($hosts[Record::A][$name], Record::A, null);
}
if ($returnIPv6 && isset($hosts[Record::AAAA][$name])) {
$records[] = new Record($hosts[Record::AAAA][$name], Record::AAAA, null);
}
return $records;
}
/** @inheritdoc */
2022-10-29 20:03:07 +02:00
public function query(string $name, int $type, ?Cancellation $cancellation = null): array
2019-06-10 19:32:28 +02:00
{
2022-10-29 20:03:07 +02:00
$cancellation ??= new NullCancellation;
2019-06-10 19:32:28 +02:00
$pendingQueryKey = $type." ".$name;
if (isset($this->pendingQueries[$pendingQueryKey])) {
2022-10-29 20:44:35 +02:00
return $this->pendingQueries[$pendingQueryKey]->await($cancellation);
2019-06-10 19:32:28 +02:00
}
2022-10-29 20:03:07 +02:00
$promise = async(function () use ($name, $type, $cancellation, $pendingQueryKey) {
try {
if (!$this->config) {
try {
$this->reloadConfig();
} catch (ConfigException $e) {
$this->config = new Config(['0.0.0.0'], []);
}
2019-06-12 13:03:38 +02:00
}
2019-06-10 19:32:28 +02:00
2022-10-30 20:47:30 +01:00
\assert($this->config !== null);
2022-10-29 20:03:07 +02:00
$name = $this->normalizeName($name, $type);
$question = $this->createQuestion($name, $type);
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
if (null !== $cachedValue = $this->cache->get($this->getCacheKey($name, $type))) {
return $this->decodeCachedResult($name, $type, $cachedValue);
}
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
$nameservers = $this->dohConfig->getNameservers();
$attempts = $this->config->getAttempts() * \count($nameservers);
$attempt = 0;
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
$nameserver = $nameservers[0];
2019-12-13 00:18:38 +01:00
2022-10-29 20:03:07 +02:00
$attemptDescription = [];
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
while ($attempt < $attempts) {
2019-06-12 13:48:57 +02:00
try {
2022-10-29 20:03:07 +02:00
$attemptDescription[] = $nameserver;
2019-06-12 13:48:57 +02:00
2022-10-29 20:03:07 +02:00
$response = $this->ask($nameserver, $question, $cancellation);
$this->assertAcceptableResponse($response);
2019-06-12 13:48:57 +02:00
2022-10-29 20:03:07 +02:00
if ($response->isTruncated()) {
throw new DnsException("Server returned a truncated response for '{$name}' (".Record::getName($type).")");
}
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
$answers = $response->getAnswerRecords();
$result = [];
$ttls = [];
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
foreach ($answers as $record) {
$recordType = $record->getType();
$result[$recordType][] = (string) $record->getData();
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
// Cache for max one day
$ttls[$recordType] = \min($ttls[$recordType] ?? 86400, $record->getTTL());
}
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
foreach ($result as $recordType => $records) {
// We don't care here whether storing in the cache fails
$this->cache->set($this->getCacheKey($name, $recordType), \json_encode($records), $ttls[$recordType]);
}
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
if (!isset($result[$type])) {
// "it MUST NOT cache it for longer than five (5) minutes" per RFC 2308 section 7.1
$this->cache->set($this->getCacheKey($name, $type), \json_encode([]), 300);
throw new NoRecordException("No records returned for '{$name}' (".Record::getName($type).")");
}
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
return \array_map(function ($data) use ($type, $ttls) {
return new Record($data, $type, $ttls[$type]);
}, $result[$type]);
} catch (TimeoutException) {
$i = ++$attempt % \count($nameservers);
$nameserver = $nameservers[$i];
2019-06-10 19:32:28 +02:00
}
}
2022-10-29 20:03:07 +02:00
throw new TimeoutException(\sprintf(
"No response for '%s' (%s) from any nameserver within %d ms after %d attempts, tried %s",
$name,
Record::getName($type),
$this->config->getTimeout(),
$attempts,
\implode(", ", $attemptDescription)
));
} finally {
unset($this->pendingQueries[$pendingQueryKey]);
2019-12-12 22:27:22 +01:00
}
2019-06-10 19:32:28 +02:00
});
2022-10-29 20:03:07 +02:00
$this->pendingQueries[$pendingQueryKey] = $promise;
return $promise->await($cancellation);
}
private function ask(Nameserver $nameserver, Question $question, Cancellation $cancellation): Message
{
$message = $this->createMessage($question, \random_int(0, 0xffff));
2022-10-30 20:47:30 +01:00
$request = null;
2022-10-29 20:03:07 +02:00
switch ($nameserver->getType()) {
case NameserverType::RFC8484_GET:
$data = $this->encoder->encode($message);
$request = new Request($nameserver->getUri().'?'.\http_build_query(['dns' => \base64_encode($data), 'ct' => 'application/dns-message']), "GET");
$request->setHeader('accept', 'application/dns-message');
$request->setHeaders($nameserver->getHeaders());
break;
case NameserverType::RFC8484_POST:
$data = $this->encoder->encode($message);
$request = new Request($nameserver->getUri(), "POST");
$request->setBody($data);
$request->setHeader('content-type', 'application/dns-message');
$request->setHeader('accept', 'application/dns-message');
2022-10-30 20:47:30 +01:00
$request->setHeader('content-length', (string) \strlen($data));
2022-10-29 20:03:07 +02:00
$request->setHeaders($nameserver->getHeaders());
break;
case NameserverType::GOOGLE_JSON:
$data = $this->encoderJson->encode($message);
$request = new Request($nameserver->getUri().'?'.$data, "GET");
$request->setHeader('accept', 'application/dns-json');
$request->setHeaders($nameserver->getHeaders());
break;
}
2022-10-30 20:47:30 +01:00
\assert($request !== null);
2019-06-10 19:32:28 +02:00
2022-10-29 20:03:07 +02:00
$response = $this->httpClient->request($request, $cancellation);
if ($response->getStatus() !== 200) {
throw new DoHException("HTTP result !== 200: ".$response->getStatus()." ".$response->getReason(), $response->getStatus());
}
$response = $response->getBody()->buffer();
switch ($nameserver->getType()) {
case NameserverType::RFC8484_GET:
case NameserverType::RFC8484_POST:
return $this->decoder->decode($response);
case NameserverType::GOOGLE_JSON:
return $this->decoderJson->decode($response, $message->getID());
}
2019-06-10 19:32:28 +02:00
}
2022-10-30 20:47:30 +01:00
private function normalizeName(string $name, int $type): string
2019-06-10 19:32:28 +02:00
{
if ($type === Record::PTR) {
if (($packedIp = @\inet_pton($name)) !== false) {
if (isset($packedIp[4])) { // IPv6
$name = \wordwrap(\strrev(\bin2hex($packedIp)), 1, ".", true).".ip6.arpa";
} else { // IPv4
$name = \inet_ntop(\strrev($packedIp)).".in-addr.arpa";
}
}
} elseif (\in_array($type, [Record::A, Record::AAAA])) {
$name = normalizeName($name);
}
return $name;
}
private function createQuestion(string $name, int $type): Question
{
if (0 > $type || 0xffff < $type) {
$message = \sprintf('%d does not correspond to a valid record type (must be between 0 and 65535).', $type);
throw new \Error($message);
}
$question = $this->questionFactory->create($type);
$question->setName($name);
return $question;
}
2022-10-29 20:03:07 +02:00
private function createMessage(Question $question, int $id): Message
{
$request = $this->messageFactory->create(MessageTypes::QUERY);
$request->getQuestionRecords()->add($question);
$request->isRecursionDesired(true);
$request->setID($id);
return $request;
}
2019-06-10 19:32:28 +02:00
private function getCacheKey(string $name, int $type): string
{
return self::CACHE_PREFIX.$name."#".$type;
}
2022-10-30 20:47:30 +01:00
/**
* @return list<Record>
*/
private function decodeCachedResult(string $name, int $type, string $encoded): array
2019-06-10 19:32:28 +02:00
{
$decoded = \json_decode($encoded, true);
if (!$decoded) {
throw new NoRecordException("No records returned for {$name} (cached result)");
}
$result = [];
foreach ($decoded as $data) {
$result[] = new Record($data, $type);
}
return $result;
}
2022-10-29 20:03:07 +02:00
private function assertAcceptableResponse(Message $response): void
2019-06-10 19:32:28 +02:00
{
if ($response->getResponseCode() !== 0) {
throw new DnsException(\sprintf("Server returned error code: %d", $response->getResponseCode()));
}
}
}