asyncresolver.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2003-2017 Nominum, Inc.
  3. #
  4. # Permission to use, copy, modify, and distribute this software and its
  5. # documentation for any purpose with or without fee is hereby granted,
  6. # provided that the above copyright notice and this permission notice
  7. # appear in all copies.
  8. #
  9. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  10. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  12. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """Asynchronous DNS stub resolver."""
  17. import socket
  18. import time
  19. from typing import Any, Dict, List
  20. import dns._ddr
  21. import dns.asyncbackend
  22. import dns.asyncquery
  23. import dns.exception
  24. import dns.inet
  25. import dns.name
  26. import dns.nameserver
  27. import dns.query
  28. import dns.rdataclass
  29. import dns.rdatatype
  30. import dns.resolver # lgtm[py/import-and-import-from]
  31. import dns.reversename
  32. # import some resolver symbols for brevity
  33. from dns.resolver import NXDOMAIN, NoAnswer, NoRootSOA, NotAbsolute
  34. # for indentation purposes below
  35. _udp = dns.asyncquery.udp
  36. _tcp = dns.asyncquery.tcp
  37. class Resolver(dns.resolver.BaseResolver):
  38. """Asynchronous DNS stub resolver."""
  39. async def resolve(
  40. self,
  41. qname: dns.name.Name | str,
  42. rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A,
  43. rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN,
  44. tcp: bool = False,
  45. source: str | None = None,
  46. raise_on_no_answer: bool = True,
  47. source_port: int = 0,
  48. lifetime: float | None = None,
  49. search: bool | None = None,
  50. backend: dns.asyncbackend.Backend | None = None,
  51. ) -> dns.resolver.Answer:
  52. """Query nameservers asynchronously to find the answer to the question.
  53. *backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``,
  54. the default, then dnspython will use the default backend.
  55. See :py:func:`dns.resolver.Resolver.resolve()` for the
  56. documentation of the other parameters, exceptions, and return
  57. type of this method.
  58. """
  59. resolution = dns.resolver._Resolution(
  60. self, qname, rdtype, rdclass, tcp, raise_on_no_answer, search
  61. )
  62. if not backend:
  63. backend = dns.asyncbackend.get_default_backend()
  64. start = time.time()
  65. while True:
  66. (request, answer) = resolution.next_request()
  67. # Note we need to say "if answer is not None" and not just
  68. # "if answer" because answer implements __len__, and python
  69. # will call that. We want to return if we have an answer
  70. # object, including in cases where its length is 0.
  71. if answer is not None:
  72. # cache hit!
  73. return answer
  74. assert request is not None # needed for type checking
  75. done = False
  76. while not done:
  77. (nameserver, tcp, backoff) = resolution.next_nameserver()
  78. if backoff:
  79. await backend.sleep(backoff)
  80. timeout = self._compute_timeout(start, lifetime, resolution.errors)
  81. try:
  82. response = await nameserver.async_query(
  83. request,
  84. timeout=timeout,
  85. source=source,
  86. source_port=source_port,
  87. max_size=tcp,
  88. backend=backend,
  89. )
  90. except Exception as ex:
  91. (_, done) = resolution.query_result(None, ex)
  92. continue
  93. (answer, done) = resolution.query_result(response, None)
  94. # Note we need to say "if answer is not None" and not just
  95. # "if answer" because answer implements __len__, and python
  96. # will call that. We want to return if we have an answer
  97. # object, including in cases where its length is 0.
  98. if answer is not None:
  99. return answer
  100. async def resolve_address(
  101. self, ipaddr: str, *args: Any, **kwargs: Any
  102. ) -> dns.resolver.Answer:
  103. """Use an asynchronous resolver to run a reverse query for PTR
  104. records.
  105. This utilizes the resolve() method to perform a PTR lookup on the
  106. specified IP address.
  107. *ipaddr*, a ``str``, the IPv4 or IPv6 address you want to get
  108. the PTR record for.
  109. All other arguments that can be passed to the resolve() function
  110. except for rdtype and rdclass are also supported by this
  111. function.
  112. """
  113. # We make a modified kwargs for type checking happiness, as otherwise
  114. # we get a legit warning about possibly having rdtype and rdclass
  115. # in the kwargs more than once.
  116. modified_kwargs: Dict[str, Any] = {}
  117. modified_kwargs.update(kwargs)
  118. modified_kwargs["rdtype"] = dns.rdatatype.PTR
  119. modified_kwargs["rdclass"] = dns.rdataclass.IN
  120. return await self.resolve(
  121. dns.reversename.from_address(ipaddr), *args, **modified_kwargs
  122. )
  123. async def resolve_name(
  124. self,
  125. name: dns.name.Name | str,
  126. family: int = socket.AF_UNSPEC,
  127. **kwargs: Any,
  128. ) -> dns.resolver.HostAnswers:
  129. """Use an asynchronous resolver to query for address records.
  130. This utilizes the resolve() method to perform A and/or AAAA lookups on
  131. the specified name.
  132. *qname*, a ``dns.name.Name`` or ``str``, the name to resolve.
  133. *family*, an ``int``, the address family. If socket.AF_UNSPEC
  134. (the default), both A and AAAA records will be retrieved.
  135. All other arguments that can be passed to the resolve() function
  136. except for rdtype and rdclass are also supported by this
  137. function.
  138. """
  139. # We make a modified kwargs for type checking happiness, as otherwise
  140. # we get a legit warning about possibly having rdtype and rdclass
  141. # in the kwargs more than once.
  142. modified_kwargs: Dict[str, Any] = {}
  143. modified_kwargs.update(kwargs)
  144. modified_kwargs.pop("rdtype", None)
  145. modified_kwargs["rdclass"] = dns.rdataclass.IN
  146. if family == socket.AF_INET:
  147. v4 = await self.resolve(name, dns.rdatatype.A, **modified_kwargs)
  148. return dns.resolver.HostAnswers.make(v4=v4)
  149. elif family == socket.AF_INET6:
  150. v6 = await self.resolve(name, dns.rdatatype.AAAA, **modified_kwargs)
  151. return dns.resolver.HostAnswers.make(v6=v6)
  152. elif family != socket.AF_UNSPEC:
  153. raise NotImplementedError(f"unknown address family {family}")
  154. raise_on_no_answer = modified_kwargs.pop("raise_on_no_answer", True)
  155. lifetime = modified_kwargs.pop("lifetime", None)
  156. start = time.time()
  157. v6 = await self.resolve(
  158. name,
  159. dns.rdatatype.AAAA,
  160. raise_on_no_answer=False,
  161. lifetime=self._compute_timeout(start, lifetime),
  162. **modified_kwargs,
  163. )
  164. # Note that setting name ensures we query the same name
  165. # for A as we did for AAAA. (This is just in case search lists
  166. # are active by default in the resolver configuration and
  167. # we might be talking to a server that says NXDOMAIN when it
  168. # wants to say NOERROR no data.
  169. name = v6.qname
  170. v4 = await self.resolve(
  171. name,
  172. dns.rdatatype.A,
  173. raise_on_no_answer=False,
  174. lifetime=self._compute_timeout(start, lifetime),
  175. **modified_kwargs,
  176. )
  177. answers = dns.resolver.HostAnswers.make(
  178. v6=v6, v4=v4, add_empty=not raise_on_no_answer
  179. )
  180. if not answers:
  181. raise NoAnswer(response=v6.response)
  182. return answers
  183. # pylint: disable=redefined-outer-name
  184. async def canonical_name(self, name: dns.name.Name | str) -> dns.name.Name:
  185. """Determine the canonical name of *name*.
  186. The canonical name is the name the resolver uses for queries
  187. after all CNAME and DNAME renamings have been applied.
  188. *name*, a ``dns.name.Name`` or ``str``, the query name.
  189. This method can raise any exception that ``resolve()`` can
  190. raise, other than ``dns.resolver.NoAnswer`` and
  191. ``dns.resolver.NXDOMAIN``.
  192. Returns a ``dns.name.Name``.
  193. """
  194. try:
  195. answer = await self.resolve(name, raise_on_no_answer=False)
  196. canonical_name = answer.canonical_name
  197. except dns.resolver.NXDOMAIN as e:
  198. canonical_name = e.canonical_name
  199. return canonical_name
  200. async def try_ddr(self, lifetime: float = 5.0) -> None:
  201. """Try to update the resolver's nameservers using Discovery of Designated
  202. Resolvers (DDR). If successful, the resolver will subsequently use
  203. DNS-over-HTTPS or DNS-over-TLS for future queries.
  204. *lifetime*, a float, is the maximum time to spend attempting DDR. The default
  205. is 5 seconds.
  206. If the SVCB query is successful and results in a non-empty list of nameservers,
  207. then the resolver's nameservers are set to the returned servers in priority
  208. order.
  209. The current implementation does not use any address hints from the SVCB record,
  210. nor does it resolve addresses for the SCVB target name, rather it assumes that
  211. the bootstrap nameserver will always be one of the addresses and uses it.
  212. A future revision to the code may offer fuller support. The code verifies that
  213. the bootstrap nameserver is in the Subject Alternative Name field of the
  214. TLS certficate.
  215. """
  216. try:
  217. expiration = time.time() + lifetime
  218. answer = await self.resolve(
  219. dns._ddr._local_resolver_name, "svcb", lifetime=lifetime
  220. )
  221. timeout = dns.query._remaining(expiration)
  222. nameservers = await dns._ddr._get_nameservers_async(answer, timeout)
  223. if len(nameservers) > 0:
  224. self.nameservers = nameservers
  225. except Exception:
  226. pass
  227. default_resolver = None
  228. def get_default_resolver() -> Resolver:
  229. """Get the default asynchronous resolver, initializing it if necessary."""
  230. if default_resolver is None:
  231. reset_default_resolver()
  232. assert default_resolver is not None
  233. return default_resolver
  234. def reset_default_resolver() -> None:
  235. """Re-initialize default asynchronous resolver.
  236. Note that the resolver configuration (i.e. /etc/resolv.conf on UNIX
  237. systems) will be re-read immediately.
  238. """
  239. global default_resolver
  240. default_resolver = Resolver()
  241. async def resolve(
  242. qname: dns.name.Name | str,
  243. rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A,
  244. rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN,
  245. tcp: bool = False,
  246. source: str | None = None,
  247. raise_on_no_answer: bool = True,
  248. source_port: int = 0,
  249. lifetime: float | None = None,
  250. search: bool | None = None,
  251. backend: dns.asyncbackend.Backend | None = None,
  252. ) -> dns.resolver.Answer:
  253. """Query nameservers asynchronously to find the answer to the question.
  254. This is a convenience function that uses the default resolver
  255. object to make the query.
  256. See :py:func:`dns.asyncresolver.Resolver.resolve` for more
  257. information on the parameters.
  258. """
  259. return await get_default_resolver().resolve(
  260. qname,
  261. rdtype,
  262. rdclass,
  263. tcp,
  264. source,
  265. raise_on_no_answer,
  266. source_port,
  267. lifetime,
  268. search,
  269. backend,
  270. )
  271. async def resolve_address(
  272. ipaddr: str, *args: Any, **kwargs: Any
  273. ) -> dns.resolver.Answer:
  274. """Use a resolver to run a reverse query for PTR records.
  275. See :py:func:`dns.asyncresolver.Resolver.resolve_address` for more
  276. information on the parameters.
  277. """
  278. return await get_default_resolver().resolve_address(ipaddr, *args, **kwargs)
  279. async def resolve_name(
  280. name: dns.name.Name | str, family: int = socket.AF_UNSPEC, **kwargs: Any
  281. ) -> dns.resolver.HostAnswers:
  282. """Use a resolver to asynchronously query for address records.
  283. See :py:func:`dns.asyncresolver.Resolver.resolve_name` for more
  284. information on the parameters.
  285. """
  286. return await get_default_resolver().resolve_name(name, family, **kwargs)
  287. async def canonical_name(name: dns.name.Name | str) -> dns.name.Name:
  288. """Determine the canonical name of *name*.
  289. See :py:func:`dns.resolver.Resolver.canonical_name` for more
  290. information on the parameters and possible exceptions.
  291. """
  292. return await get_default_resolver().canonical_name(name)
  293. async def try_ddr(timeout: float = 5.0) -> None:
  294. """Try to update the default resolver's nameservers using Discovery of Designated
  295. Resolvers (DDR). If successful, the resolver will subsequently use
  296. DNS-over-HTTPS or DNS-over-TLS for future queries.
  297. See :py:func:`dns.resolver.Resolver.try_ddr` for more information.
  298. """
  299. return await get_default_resolver().try_ddr(timeout)
  300. async def zone_for_name(
  301. name: dns.name.Name | str,
  302. rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
  303. tcp: bool = False,
  304. resolver: Resolver | None = None,
  305. backend: dns.asyncbackend.Backend | None = None,
  306. ) -> dns.name.Name:
  307. """Find the name of the zone which contains the specified name.
  308. See :py:func:`dns.resolver.Resolver.zone_for_name` for more
  309. information on the parameters and possible exceptions.
  310. """
  311. if isinstance(name, str):
  312. name = dns.name.from_text(name, dns.name.root)
  313. if resolver is None:
  314. resolver = get_default_resolver()
  315. if not name.is_absolute():
  316. raise NotAbsolute(name)
  317. while True:
  318. try:
  319. answer = await resolver.resolve(
  320. name, dns.rdatatype.SOA, rdclass, tcp, backend=backend
  321. )
  322. assert answer.rrset is not None
  323. if answer.rrset.name == name:
  324. return name
  325. # otherwise we were CNAMEd or DNAMEd and need to look higher
  326. except (NXDOMAIN, NoAnswer):
  327. pass
  328. try:
  329. name = name.parent()
  330. except dns.name.NoParent: # pragma: no cover
  331. raise NoRootSOA
  332. async def make_resolver_at(
  333. where: dns.name.Name | str,
  334. port: int = 53,
  335. family: int = socket.AF_UNSPEC,
  336. resolver: Resolver | None = None,
  337. ) -> Resolver:
  338. """Make a stub resolver using the specified destination as the full resolver.
  339. *where*, a ``dns.name.Name`` or ``str`` the domain name or IP address of the
  340. full resolver.
  341. *port*, an ``int``, the port to use. If not specified, the default is 53.
  342. *family*, an ``int``, the address family to use. This parameter is used if
  343. *where* is not an address. The default is ``socket.AF_UNSPEC`` in which case
  344. the first address returned by ``resolve_name()`` will be used, otherwise the
  345. first address of the specified family will be used.
  346. *resolver*, a ``dns.asyncresolver.Resolver`` or ``None``, the resolver to use for
  347. resolution of hostnames. If not specified, the default resolver will be used.
  348. Returns a ``dns.resolver.Resolver`` or raises an exception.
  349. """
  350. if resolver is None:
  351. resolver = get_default_resolver()
  352. nameservers: List[str | dns.nameserver.Nameserver] = []
  353. if isinstance(where, str) and dns.inet.is_address(where):
  354. nameservers.append(dns.nameserver.Do53Nameserver(where, port))
  355. else:
  356. answers = await resolver.resolve_name(where, family)
  357. for address in answers.addresses():
  358. nameservers.append(dns.nameserver.Do53Nameserver(address, port))
  359. res = Resolver(configure=False)
  360. res.nameservers = nameservers
  361. return res
  362. async def resolve_at(
  363. where: dns.name.Name | str,
  364. qname: dns.name.Name | str,
  365. rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A,
  366. rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN,
  367. tcp: bool = False,
  368. source: str | None = None,
  369. raise_on_no_answer: bool = True,
  370. source_port: int = 0,
  371. lifetime: float | None = None,
  372. search: bool | None = None,
  373. backend: dns.asyncbackend.Backend | None = None,
  374. port: int = 53,
  375. family: int = socket.AF_UNSPEC,
  376. resolver: Resolver | None = None,
  377. ) -> dns.resolver.Answer:
  378. """Query nameservers to find the answer to the question.
  379. This is a convenience function that calls ``dns.asyncresolver.make_resolver_at()``
  380. to make a resolver, and then uses it to resolve the query.
  381. See ``dns.asyncresolver.Resolver.resolve`` for more information on the resolution
  382. parameters, and ``dns.asyncresolver.make_resolver_at`` for information about the
  383. resolver parameters *where*, *port*, *family*, and *resolver*.
  384. If making more than one query, it is more efficient to call
  385. ``dns.asyncresolver.make_resolver_at()`` and then use that resolver for the queries
  386. instead of calling ``resolve_at()`` multiple times.
  387. """
  388. res = await make_resolver_at(where, port, family, resolver)
  389. return await res.resolve(
  390. qname,
  391. rdtype,
  392. rdclass,
  393. tcp,
  394. source,
  395. raise_on_no_answer,
  396. source_port,
  397. lifetime,
  398. search,
  399. backend,
  400. )