Debian Codegraph @

dns/query.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 # Copyright (C) 2003-2017 Nominum, Inc.
4 #
5 # Permission to use, copy, modify, and distribute this software and its
6 # documentation for any purpose with or without fee is hereby granted,
7 # provided that the above copyright notice and this permission notice
8 # appear in all copies.
9 #
10 # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
11 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
13 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
16 # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
18 """Talk to a DNS server."""
19
20 import base64
21 import contextlib
22 import enum
23 import errno
24 import os
25 import random
26 import selectors
27 import socket
28 import struct
29 import time
30 import urllib.parse
31 from typing import Any, Callable, Dict, Optional, Tuple, cast
32
33 import dns._features
34 import dns._tls_util
35 import dns.exception
36 import dns.inet
37 import dns.message
38 import dns.name
39 import dns.quic
40 import dns.rdata
41 import dns.rdataclass
42 import dns.rdatatype
43 import dns.transaction
44 import dns.tsig
45 import dns.xfr
46
47 try:
48 import ssl
49 except ImportError:
50 import dns._no_ssl as ssl # type: ignore
51
52
53 def _remaining(expiration):
54 if expiration is None:
55 return None
56 timeout = expiration - time.time()
57 if timeout <= 0.0:
58 raise dns.exception.Timeout
59 return timeout
60
61
62 def _expiration_for_this_attempt(timeout, expiration):
63 if expiration is None:
64 return None
65 return min(time.time() + timeout, expiration)
66
67
68 _have_httpx = dns._features.have("doh")
69 if _have_httpx:
70 import httpcore._backends.sync
71 import httpx
72
73 _CoreNetworkBackend = httpcore.NetworkBackend
74 _CoreSyncStream = httpcore._backends.sync.SyncStream
75
76 class _NetworkBackend(_CoreNetworkBackend):
77 def __init__(self, resolver, local_port, bootstrap_address, family):
78 super().__init__()
79 self._local_port = local_port
80 self._resolver = resolver
81 self._bootstrap_address = bootstrap_address
82 self._family = family
83
84 def connect_tcp(
85 self, host, port, timeout=None, local_address=None, socket_options=None
86 ): # pylint: disable=signature-differs
87 addresses = []
88 _, expiration = _compute_times(timeout)
89 if dns.inet.is_address(host):
90 addresses.append(host)
91 elif self._bootstrap_address is not None:
92 addresses.append(self._bootstrap_address)
93 else:
94 timeout = _remaining(expiration)
95 family = self._family
96 if local_address:
97 family = dns.inet.af_for_address(local_address)
98 answers = self._resolver.resolve_name(
99 host, family=family, lifetime=timeout
100 )
101 addresses = answers.addresses()
102 for address in addresses:
103 af = dns.inet.af_for_address(address)
104 if local_address is not None or self._local_port != 0:
105 if local_address is None:
106 local_address = "0.0.0.0"
107 source = dns.inet.low_level_address_tuple(
108 (local_address, self._local_port), af
109 )
110 else:
111 source = None
112 try:
113 sock = make_socket(af, socket.SOCK_STREAM, source)
114 attempt_expiration = _expiration_for_this_attempt(2.0, expiration)
115 _connect(
116 sock,
117 dns.inet.low_level_address_tuple((address, port), af),
118 attempt_expiration,
119 )
120 return _CoreSyncStream(sock)
121 except Exception:
122 pass
123 raise httpcore.ConnectError
124
125 def connect_unix_socket(
126 self, path, timeout=None, socket_options=None
127 ): # pylint: disable=signature-differs
128 raise NotImplementedError
129
130 class _HTTPTransport(httpx.HTTPTransport): # pyright: ignore
131 def __init__(
132 self,
133 *args,
134 local_port=0,
135 bootstrap_address=None,
136 resolver=None,
137 family=socket.AF_UNSPEC,
138 **kwargs,
139 ):
140 if resolver is None and bootstrap_address is None:
141 # pylint: disable=import-outside-toplevel,redefined-outer-name
142 import dns.resolver
143
144 resolver = dns.resolver.Resolver()
145 super().__init__(*args, **kwargs)
146 self._pool._network_backend = _NetworkBackend(
147 resolver, local_port, bootstrap_address, family
148 )
149
150 else:
151
152 class _HTTPTransport: # type: ignore
153 def __init__(
154 self,
155 *args,
156 local_port=0,
157 bootstrap_address=None,
158 resolver=None,
159 family=socket.AF_UNSPEC,
160 **kwargs,
161 ):
162 pass
163
164 def connect_tcp(self, host, port, timeout, local_address):
165 raise NotImplementedError
166
167
168 have_doh = _have_httpx
169
170
171 def default_socket_factory(
172 af: socket.AddressFamily | int,
173 kind: socket.SocketKind,
174 proto: int,
175 ) -> socket.socket:
176 return socket.socket(af, kind, proto)
177
178
179 # Function used to create a socket. Can be overridden if needed in special
180 # situations.
181 socket_factory: Callable[
182 [socket.AddressFamily | int, socket.SocketKind, int], socket.socket
183 ] = default_socket_factory
184
185
186 class UnexpectedSource(dns.exception.DNSException):
187 """A DNS query response came from an unexpected address or port."""
188
189
190 class BadResponse(dns.exception.FormError):
191 """A DNS query response does not respond to the question asked."""
192
193
194 class NoDOH(dns.exception.DNSException):
195 """DNS over HTTPS (DOH) was requested but the httpx module is not
196 available."""
197
198
199 class NoDOQ(dns.exception.DNSException):
200 """DNS over QUIC (DOQ) was requested but the aioquic module is not
201 available."""
202
203
204 # for backwards compatibility
205 TransferError = dns.xfr.TransferError
206
207
208 def _compute_times(timeout):
209 now = time.time()
210 if timeout is None:
211 return (now, None)
212 else:
213 return (now, now + timeout)
214
215
216 def _wait_for(fd, readable, writable, _, expiration):
217 # Use the selected selector class to wait for any of the specified
218 # events. An "expiration" absolute time is converted into a relative
219 # timeout.
220 #
221 # The unused parameter is 'error', which is always set when
222 # selecting for read or write, and we have no error-only selects.
223
224 if readable and isinstance(fd, ssl.SSLSocket) and fd.pending() > 0:
225 return True
226 with selectors.DefaultSelector() as sel:
227 events = 0
228 if readable:
229 events |= selectors.EVENT_READ
230 if writable:
231 events |= selectors.EVENT_WRITE
232 if events:
233 sel.register(fd, events) # pyright: ignore
234 if expiration is None:
235 timeout = None
236 else:
237 timeout = expiration - time.time()
238 if timeout <= 0.0:
239 raise dns.exception.Timeout
240 if not sel.select(timeout):
241 raise dns.exception.Timeout
242
243
244 def _wait_for_readable(s, expiration):
245 _wait_for(s, True, False, True, expiration)
246
247
248 def _wait_for_writable(s, expiration):
249 _wait_for(s, False, True, True, expiration)
250
251
252 def _addresses_equal(af, a1, a2):
253 # Convert the first value of the tuple, which is a textual format
254 # address into binary form, so that we are not confused by different
255 # textual representations of the same address
256 try:
257 n1 = dns.inet.inet_pton(af, a1[0])
258 n2 = dns.inet.inet_pton(af, a2[0])
259 except dns.exception.SyntaxError:
260 return False
261 return n1 == n2 and a1[1:] == a2[1:]
262
263
264 def _matches_destination(af, from_address, destination, ignore_unexpected):
265 # Check that from_address is appropriate for a response to a query
266 # sent to destination.
267 if not destination:
268 return True
269 if _addresses_equal(af, from_address, destination) or (
270 dns.inet.is_multicast(destination[0]) and from_address[1:] == destination[1:]
271 ):
272 return True
273 elif ignore_unexpected:
274 return False
275 raise UnexpectedSource(
276 f"got a response from {from_address} instead of " f"{destination}"
277 )
278
279
280 def _destination_and_source(
281 where, port, source, source_port, where_must_be_address=True
282 ):
283 # Apply defaults and compute destination and source tuples
284 # suitable for use in connect(), sendto(), or bind().
285 af = None
286 destination = None
287 try:
288 af = dns.inet.af_for_address(where)
289 destination = where
290 except Exception:
291 if where_must_be_address:
292 raise
293 # URLs are ok so eat the exception
294 if source:
295 saf = dns.inet.af_for_address(source)
296 if af:
297 # We know the destination af, so source had better agree!
298 if saf != af:
299 raise ValueError(
300 "different address families for source and destination"
301 )
302 else:
303 # We didn't know the destination af, but we know the source,
304 # so that's our af.
305 af = saf
306 if source_port and not source:
307 # Caller has specified a source_port but not an address, so we
308 # need to return a source, and we need to use the appropriate
309 # wildcard address as the address.
310 try:
311 source = dns.inet.any_for_af(af)
312 except Exception:
313 # we catch this and raise ValueError for backwards compatibility
314 raise ValueError("source_port specified but address family is unknown")
315 # Convert high-level (address, port) tuples into low-level address
316 # tuples.
317 if destination:
318 destination = dns.inet.low_level_address_tuple((destination, port), af)
319 if source:
320 source = dns.inet.low_level_address_tuple((source, source_port), af)
321 return (af, destination, source)
322
323
324 def make_socket(
325 af: socket.AddressFamily | int,
326 type: socket.SocketKind,
327 source: Any | None = None,
328 ) -> socket.socket:
329 """Make a socket.
330
331 This function uses the module's ``socket_factory`` to make a socket of the
332 specified address family and type.
333
334 *af*, a ``socket.AddressFamily`` or ``int`` is the address family, either
335 ``socket.AF_INET`` or ``socket.AF_INET6``.
336
337 *type*, a ``socket.SocketKind`` is the type of socket, e.g. ``socket.SOCK_DGRAM``,
338 a datagram socket, or ``socket.SOCK_STREAM``, a stream socket. Note that the
339 ``proto`` attribute of a socket is always zero with this API, so a datagram socket
340 will always be a UDP socket, and a stream socket will always be a TCP socket.
341
342 *source* is the source address and port to bind to, if any. The default is
343 ``None`` which will bind to the wildcard address and a randomly chosen port.
344 If not ``None``, it should be a (low-level) address tuple appropriate for *af*.
345 """
346 s = socket_factory(af, type, 0)
347 try:
348 s.setblocking(False)
349 if source is not None:
350 s.bind(source)
351 return s
352 except Exception:
353 s.close()
354 raise
355
356
357 def make_ssl_socket(
358 af: socket.AddressFamily | int,
359 type: socket.SocketKind,
360 ssl_context: ssl.SSLContext,
361 server_hostname: dns.name.Name | str | None = None,
362 source: Any | None = None,
363 ) -> ssl.SSLSocket:
364 """Make a socket.
365
366 This function uses the module's ``socket_factory`` to make a socket of the
367 specified address family and type.
368
369 *af*, a ``socket.AddressFamily`` or ``int`` is the address family, either
370 ``socket.AF_INET`` or ``socket.AF_INET6``.
371
372 *type*, a ``socket.SocketKind`` is the type of socket, e.g. ``socket.SOCK_DGRAM``,
373 a datagram socket, or ``socket.SOCK_STREAM``, a stream socket. Note that the
374 ``proto`` attribute of a socket is always zero with this API, so a datagram socket
375 will always be a UDP socket, and a stream socket will always be a TCP socket.
376
377 If *ssl_context* is not ``None``, then it specifies the SSL context to use,
378 typically created with ``make_ssl_context()``.
379
380 If *server_hostname* is not ``None``, then it is the hostname to use for server
381 certificate validation. A valid hostname must be supplied if *ssl_context*
382 requires hostname checking.
383
384 *source* is the source address and port to bind to, if any. The default is
385 ``None`` which will bind to the wildcard address and a randomly chosen port.
386 If not ``None``, it should be a (low-level) address tuple appropriate for *af*.
387 """
388 sock = make_socket(af, type, source)
389 if isinstance(server_hostname, dns.name.Name):
390 server_hostname = server_hostname.to_text()
391 # LGTM gets a false positive here, as our default context is OK
392 return ssl_context.wrap_socket(
393 sock,
394 do_handshake_on_connect=False, # lgtm[py/insecure-protocol]
395 server_hostname=server_hostname,
396 )
397
398
399 # for backwards compatibility
400 def _make_socket(
401 af,
402 type,
403 source,
404 ssl_context,
405 server_hostname,
406 ):
407 if ssl_context is not None:
408 return make_ssl_socket(af, type, ssl_context, server_hostname, source)
409 else:
410 return make_socket(af, type, source)
411
412
413 def _maybe_get_resolver(
414 resolver: Optional["dns.resolver.Resolver"], # pyright: ignore
415 ) -> "dns.resolver.Resolver": # pyright: ignore
416 # We need a separate method for this to avoid overriding the global
417 # variable "dns" with the as-yet undefined local variable "dns"
418 # in https().
419 if resolver is None:
420 # pylint: disable=import-outside-toplevel,redefined-outer-name
421 import dns.resolver
422
423 resolver = dns.resolver.Resolver()
424 return resolver
425
426
427 class HTTPVersion(enum.IntEnum):
428 """Which version of HTTP should be used?
429
430 DEFAULT will select the first version from the list [2, 1.1, 3] that
431 is available.
432 """
433
434 DEFAULT = 0
435 HTTP_1 = 1
436 H1 = 1
437 HTTP_2 = 2
438 H2 = 2
439 HTTP_3 = 3
440 H3 = 3
441
442
443 def https(
444 q: dns.message.Message,
445 where: str,
446 timeout: float | None = None,
447 port: int = 443,
448 source: str | None = None,
449 source_port: int = 0,
450 one_rr_per_rrset: bool = False,
451 ignore_trailing: bool = False,
452 session: Any | None = None,
453 path: str = "/dns-query",
454 post: bool = True,
455 bootstrap_address: str | None = None,
456 verify: bool | str | ssl.SSLContext = True,
457 resolver: Optional["dns.resolver.Resolver"] = None, # pyright: ignore
458 family: int = socket.AF_UNSPEC,
459 http_version: HTTPVersion = HTTPVersion.DEFAULT,
460 ) -> dns.message.Message:
461 """Return the response obtained after sending a query via DNS-over-HTTPS.
462
463 *q*, a ``dns.message.Message``, the query to send.
464
465 *where*, a ``str``, the nameserver IP address or the full URL. If an IP address is
466 given, the URL will be constructed using the following schema:
467 https://<IP-address>:<port>/<path>.
468
469 *timeout*, a ``float`` or ``None``, the number of seconds to wait before the query
470 times out. If ``None``, the default, wait forever.
471
472 *port*, a ``int``, the port to send the query to. The default is 443.
473
474 *source*, a ``str`` containing an IPv4 or IPv6 address, specifying the source
475 address. The default is the wildcard address.
476
477 *source_port*, an ``int``, the port from which to send the message. The default is
478 0.
479
480 *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset.
481
482 *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the
483 received message.
484
485 *session*, an ``httpx.Client``. If provided, the client session to use to send the
486 queries.
487
488 *path*, a ``str``. If *where* is an IP address, then *path* will be used to
489 construct the URL to send the DNS query to.
490
491 *post*, a ``bool``. If ``True``, the default, POST method will be used.
492
493 *bootstrap_address*, a ``str``, the IP address to use to bypass resolution.
494
495 *verify*, a ``bool`` or ``str``. If a ``True``, then TLS certificate verification
496 of the server is done using the default CA bundle; if ``False``, then no
497 verification is done; if a `str` then it specifies the path to a certificate file or
498 directory which will be used for verification.
499
500 *resolver*, a ``dns.resolver.Resolver`` or ``None``, the resolver to use for
501 resolution of hostnames in URLs. If not specified, a new resolver with a default
502 configuration will be used; note this is *not* the default resolver as that resolver
503 might have been configured to use DoH causing a chicken-and-egg problem. This
504 parameter only has an effect if the HTTP library is httpx.
505
506 *family*, an ``int``, the address family. If socket.AF_UNSPEC (the default), both A
507 and AAAA records will be retrieved.
508
509 *http_version*, a ``dns.query.HTTPVersion``, indicating which HTTP version to use.
510
511 Returns a ``dns.message.Message``.
512 """
513
514 (af, _, the_source) = _destination_and_source(
515 where, port, source, source_port, False
516 )
517 # we bind url and then override as pyright can't figure out all paths bind.
518 url = where
519 if af is not None and dns.inet.is_address(where):
520 if af == socket.AF_INET:
521 url = f"https://{where}:{port}{path}"
522 elif af == socket.AF_INET6:
523 url = f"https://[{where}]:{port}{path}"
524
525 extensions = {}
526 if bootstrap_address is None:
527 # pylint: disable=possibly-used-before-assignment
528 parsed = urllib.parse.urlparse(url)
529 if parsed.hostname is None:
530 raise ValueError("no hostname in URL")
531 if dns.inet.is_address(parsed.hostname):
532 bootstrap_address = parsed.hostname
533 extensions["sni_hostname"] = parsed.hostname
534 if parsed.port is not None:
535 port = parsed.port
536
537 if http_version == HTTPVersion.H3 or (
538 http_version == HTTPVersion.DEFAULT and not have_doh
539 ):
540 if bootstrap_address is None:
541 resolver = _maybe_get_resolver(resolver)
542 assert parsed.hostname is not None # pyright: ignore
543 answers = resolver.resolve_name(parsed.hostname, family) # pyright: ignore
544 bootstrap_address = random.choice(list(answers.addresses()))
545 if session and not isinstance(
546 session, dns.quic.SyncQuicConnection
547 ): # pyright: ignore
548 raise ValueError("session parameter must be a dns.quic.SyncQuicConnection.")
549 return _http3(
550 q,
551 bootstrap_address,
552 url, # pyright: ignore
553 timeout,
554 port,
555 source,
556 source_port,
557 one_rr_per_rrset,
558 ignore_trailing,
559 verify=verify,
560 post=post,
561 connection=session,
562 )
563
564 if not have_doh:
565 raise NoDOH # pragma: no cover
566 if session and not isinstance(session, httpx.Client): # pyright: ignore
567 raise ValueError("session parameter must be an httpx.Client")
568
569 wire = q.to_wire()
570 headers = {"accept": "application/dns-message"}
571
572 h1 = http_version in (HTTPVersion.H1, HTTPVersion.DEFAULT)
573 h2 = http_version in (HTTPVersion.H2, HTTPVersion.DEFAULT)
574
575 # set source port and source address
576
577 if the_source is None:
578 local_address = None
579 local_port = 0
580 else:
581 local_address = the_source[0]
582 local_port = the_source[1]
583
584 if session:
585 cm: contextlib.AbstractContextManager = contextlib.nullcontext(session)
586 else:
587 transport = _HTTPTransport(
588 local_address=local_address,
589 http1=h1,
590 http2=h2,
591 verify=verify,
592 local_port=local_port,
593 bootstrap_address=bootstrap_address,
594 resolver=resolver,
595 family=family, # pyright: ignore
596 )
597
598 cm = httpx.Client( # type: ignore
599 http1=h1, http2=h2, verify=verify, transport=transport # type: ignore
600 )
601 with cm as session:
602 # see https://tools.ietf.org/html/rfc8484#section-4.1.1 for DoH
603 # GET and POST examples
604 assert session is not None
605 if post:
606 headers.update(
607 {
608 "content-type": "application/dns-message",
609 "content-length": str(len(wire)),
610 }
611 )
612 response = session.post(
613 url,
614 headers=headers,
615 content=wire,
616 timeout=timeout,
617 extensions=extensions,
618 )
619 else:
620 wire = base64.urlsafe_b64encode(wire).rstrip(b"=")
621 twire = wire.decode() # httpx does a repr() if we give it bytes
622 response = session.get(
623 url,
624 headers=headers,
625 timeout=timeout,
626 params={"dns": twire},
627 extensions=extensions,
628 )
629
630 # see https://tools.ietf.org/html/rfc8484#section-4.2.1 for info about DoH
631 # status codes
632 if response.status_code < 200 or response.status_code > 299:
633 raise ValueError(
634 f"{where} responded with status code {response.status_code}"
635 f"\nResponse body: {response.content}"
636 )
637 r = dns.message.from_wire(
638 response.content,
639 keyring=q.keyring,
640 request_mac=q.request_mac,
641 one_rr_per_rrset=one_rr_per_rrset,
642 ignore_trailing=ignore_trailing,
643 )
644 r.time = response.elapsed.total_seconds()
645 if not q.is_response(r):
646 raise BadResponse
647 return r
648
649
650 def _find_header(headers: dns.quic.Headers, name: bytes) -> bytes:
651 if headers is None:
652 raise KeyError
653 for header, value in headers:
654 if header == name:
655 return value
656 raise KeyError
657
658
659 def _check_status(headers: dns.quic.Headers, peer: str, wire: bytes) -> None:
660 value = _find_header(headers, b":status")
661 if value is None:
662 raise SyntaxError("no :status header in response")
663 status = int(value)
664 if status < 0:
665 raise SyntaxError("status is negative")
666 if status < 200 or status > 299:
667 error = ""
668 if len(wire) > 0:
669 try:
670 error = ": " + wire.decode()
671 except Exception:
672 pass
673 raise ValueError(f"{peer} responded with status code {status}{error}")
674
675
676 def _http3(
677 q: dns.message.Message,
678 where: str,
679 url: str,
680 timeout: float | None = None,
681 port: int = 443,
682 source: str | None = None,
683 source_port: int = 0,
684 one_rr_per_rrset: bool = False,
685 ignore_trailing: bool = False,
686 verify: bool | str | ssl.SSLContext = True,
687 post: bool = True,
688 connection: dns.quic.SyncQuicConnection | None = None,
689 ) -> dns.message.Message:
690 if not dns.quic.have_quic:
691 raise NoDOH("DNS-over-HTTP3 is not available.") # pragma: no cover
692
693 url_parts = urllib.parse.urlparse(url)
694 hostname = url_parts.hostname
695 assert hostname is not None
696 if url_parts.port is not None:
697 port = url_parts.port
698
699 q.id = 0
700 wire = q.to_wire()
701 the_connection: dns.quic.SyncQuicConnection
702 the_manager: dns.quic.SyncQuicManager
703 if connection:
704 manager: contextlib.AbstractContextManager = contextlib.nullcontext(None)
705 else:
706 manager = dns.quic.SyncQuicManager(
707 verify_mode=verify, server_name=hostname, h3=True # pyright: ignore
708 )
709 the_manager = manager # for type checking happiness
710
711 with manager:
712 if connection:
713 the_connection = connection
714 else:
715 the_connection = the_manager.connect( # pyright: ignore
716 where, port, source, source_port
717 )
718 (start, expiration) = _compute_times(timeout)
719 with the_connection.make_stream(timeout) as stream: # pyright: ignore
720 stream.send_h3(url, wire, post)
721 wire = stream.receive(_remaining(expiration))
722 _check_status(stream.headers(), where, wire)
723 finish = time.time()
724 r = dns.message.from_wire(
725 wire,
726 keyring=q.keyring,
727 request_mac=q.request_mac,
728 one_rr_per_rrset=one_rr_per_rrset,
729 ignore_trailing=ignore_trailing,
730 )
731 r.time = max(finish - start, 0.0)
732 if not q.is_response(r):
733 raise BadResponse
734 return r
735
736
737 def _udp_recv(sock, max_size, expiration):
738 """Reads a datagram from the socket.
739 A Timeout exception will be raised if the operation is not completed
740 by the expiration time.
741 """
742 while True:
743 try:
744 return sock.recvfrom(max_size)
745 except BlockingIOError:
746 _wait_for_readable(sock, expiration)
747
748
749 def _udp_send(sock, data, destination, expiration):
750 """Sends the specified datagram to destination over the socket.
751 A Timeout exception will be raised if the operation is not completed
752 by the expiration time.
753 """
754 while True:
755 try:
756 if destination:
757 return sock.sendto(data, destination)
758 else:
759 return sock.send(data)
760 except BlockingIOError: # pragma: no cover
761 _wait_for_writable(sock, expiration)
762
763
764 def send_udp(
765 sock: Any,
766 what: dns.message.Message | bytes,
767 destination: Any,
768 expiration: float | None = None,
769 ) -> Tuple[int, float]:
770 """Send a DNS message to the specified UDP socket.
771
772 *sock*, a ``socket``.
773
774 *what*, a ``bytes`` or ``dns.message.Message``, the message to send.
775
776 *destination*, a destination tuple appropriate for the address family
777 of the socket, specifying where to send the query.
778
779 *expiration*, a ``float`` or ``None``, the absolute time at which
780 a timeout exception should be raised. If ``None``, no timeout will
781 occur.
782
783 Returns an ``(int, float)`` tuple of bytes sent and the sent time.
784 """
785
786 if isinstance(what, dns.message.Message):
787 what = what.to_wire()
788 sent_time = time.time()
789 n = _udp_send(sock, what, destination, expiration)
790 return (n, sent_time)
791
792
793 def receive_udp(
794 sock: Any,
795 destination: Any | None = None,
796 expiration: float | None = None,
797 ignore_unexpected: bool = False,
798 one_rr_per_rrset: bool = False,
799 keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None,
800 request_mac: bytes | None = b"",
801 ignore_trailing: bool = False,
802 raise_on_truncation: bool = False,
803 ignore_errors: bool = False,
804 query: dns.message.Message | None = None,
805 ) -> Any:
806 """Read a DNS message from a UDP socket.
807
808 *sock*, a ``socket``.
809
810 *destination*, a destination tuple appropriate for the address family
811 of the socket, specifying where the message is expected to arrive from.
812 When receiving a response, this would be where the associated query was
813 sent.
814
815 *expiration*, a ``float`` or ``None``, the absolute time at which
816 a timeout exception should be raised. If ``None``, no timeout will
817 occur.
818
819 *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from
820 unexpected sources.
821
822 *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
823 RRset.
824
825 *keyring*, a ``dict``, the keyring to use for TSIG.
826
827 *request_mac*, a ``bytes`` or ``None``, the MAC of the request (for TSIG).
828
829 *ignore_trailing*, a ``bool``. If ``True``, ignore trailing
830 junk at end of the received message.
831
832 *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if
833 the TC bit is set.
834
835 Raises if the message is malformed, if network errors occur, of if
836 there is a timeout.
837
838 If *destination* is not ``None``, returns a ``(dns.message.Message, float)``
839 tuple of the received message and the received time.
840
841 If *destination* is ``None``, returns a
842 ``(dns.message.Message, float, tuple)``
843 tuple of the received message, the received time, and the address where
844 the message arrived from.
845
846 *ignore_errors*, a ``bool``. If various format errors or response
847 mismatches occur, ignore them and keep listening for a valid response.
848 The default is ``False``.
849
850 *query*, a ``dns.message.Message`` or ``None``. If not ``None`` and
851 *ignore_errors* is ``True``, check that the received message is a response
852 to this query, and if not keep listening for a valid response.
853 """
854
855 wire = b""
856 while True:
857 (wire, from_address) = _udp_recv(sock, 65535, expiration)
858 if not _matches_destination(
859 sock.family, from_address, destination, ignore_unexpected
860 ):
861 continue
862 received_time = time.time()
863 try:
864 r = dns.message.from_wire(
865 wire,
866 keyring=keyring,
867 request_mac=request_mac,
868 one_rr_per_rrset=one_rr_per_rrset,
869 ignore_trailing=ignore_trailing,
870 raise_on_truncation=raise_on_truncation,
871 )
872 except dns.message.Truncated as e:
873 # If we got Truncated and not FORMERR, we at least got the header with TC
874 # set, and very likely the question section, so we'll re-raise if the
875 # message seems to be a response as we need to know when truncation happens.
876 # We need to check that it seems to be a response as we don't want a random
877 # injected message with TC set to cause us to bail out.
878 if (
879 ignore_errors
880 and query is not None
881 and not query.is_response(e.message())
882 ):
883 continue
884 else:
885 raise
886 except Exception:
887 if ignore_errors:
888 continue
889 else:
890 raise
891 if ignore_errors and query is not None and not query.is_response(r):
892 continue
893 if destination:
894 return (r, received_time)
895 else:
896 return (r, received_time, from_address)
897
898
899 def udp(
900 q: dns.message.Message,
901 where: str,
902 timeout: float | None = None,
903 port: int = 53,
904 source: str | None = None,
905 source_port: int = 0,
906 ignore_unexpected: bool = False,
907 one_rr_per_rrset: bool = False,
908 ignore_trailing: bool = False,
909 raise_on_truncation: bool = False,
910 sock: Any | None = None,
911 ignore_errors: bool = False,
912 ) -> dns.message.Message:
913 """Return the response obtained after sending a query via UDP.
914
915 *q*, a ``dns.message.Message``, the query to send
916
917 *where*, a ``str`` containing an IPv4 or IPv6 address, where
918 to send the message.
919
920 *timeout*, a ``float`` or ``None``, the number of seconds to wait before the
921 query times out. If ``None``, the default, wait forever.
922
923 *port*, an ``int``, the port send the message to. The default is 53.
924
925 *source*, a ``str`` containing an IPv4 or IPv6 address, specifying
926 the source address. The default is the wildcard address.
927
928 *source_port*, an ``int``, the port from which to send the message.
929 The default is 0.
930
931 *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from
932 unexpected sources.
933
934 *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
935 RRset.
936
937 *ignore_trailing*, a ``bool``. If ``True``, ignore trailing
938 junk at end of the received message.
939
940 *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if
941 the TC bit is set.
942
943 *sock*, a ``socket.socket``, or ``None``, the socket to use for the
944 query. If ``None``, the default, a socket is created. Note that
945 if a socket is provided, it must be a nonblocking datagram socket,
946 and the *source* and *source_port* are ignored.
947
948 *ignore_errors*, a ``bool``. If various format errors or response
949 mismatches occur, ignore them and keep listening for a valid response.
950 The default is ``False``.
951
952 Returns a ``dns.message.Message``.
953 """
954
955 wire = q.to_wire()
956 (af, destination, source) = _destination_and_source(
957 where, port, source, source_port, True
958 )
959 (begin_time, expiration) = _compute_times(timeout)
960 if sock:
961 cm: contextlib.AbstractContextManager = contextlib.nullcontext(sock)
962 else:
963 assert af is not None
964 cm = make_socket(af, socket.SOCK_DGRAM, source)
965 with cm as s:
966 send_udp(s, wire, destination, expiration)
967 (r, received_time) = receive_udp(
968 s,
969 destination,
970 expiration,
971 ignore_unexpected,
972 one_rr_per_rrset,
973 q.keyring,
974 q.mac,
975 ignore_trailing,
976 raise_on_truncation,
977 ignore_errors,
978 q,
979 )
980 r.time = received_time - begin_time
981 # We don't need to check q.is_response() if we are in ignore_errors mode
982 # as receive_udp() will have checked it.
983 if not (ignore_errors or q.is_response(r)):
984 raise BadResponse
985 return r
986 assert (
987 False # help mypy figure out we can't get here lgtm[py/unreachable-statement]
988 )
989
990
991 def udp_with_fallback(
992 q: dns.message.Message,
993 where: str,
994 timeout: float | None = None,
995 port: int = 53,
996 source: str | None = None,
997 source_port: int = 0,
998 ignore_unexpected: bool = False,
999 one_rr_per_rrset: bool = False,
1000 ignore_trailing: bool = False,
1001 udp_sock: Any | None = None,
1002 tcp_sock: Any | None = None,
1003 ignore_errors: bool = False,
1004 ) -> Tuple[dns.message.Message, bool]:
1005 """Return the response to the query, trying UDP first and falling back
1006 to TCP if UDP results in a truncated response.
1007
1008 *q*, a ``dns.message.Message``, the query to send
1009
1010 *where*, a ``str`` containing an IPv4 or IPv6 address, where to send the message.
1011
1012 *timeout*, a ``float`` or ``None``, the number of seconds to wait before the query
1013 times out. If ``None``, the default, wait forever.
1014
1015 *port*, an ``int``, the port send the message to. The default is 53.
1016
1017 *source*, a ``str`` containing an IPv4 or IPv6 address, specifying the source
1018 address. The default is the wildcard address.
1019
1020 *source_port*, an ``int``, the port from which to send the message. The default is
1021 0.
1022
1023 *ignore_unexpected*, a ``bool``. If ``True``, ignore responses from unexpected
1024 sources.
1025
1026 *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset.
1027
1028 *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the
1029 received message.
1030
1031 *udp_sock*, a ``socket.socket``, or ``None``, the socket to use for the UDP query.
1032 If ``None``, the default, a socket is created. Note that if a socket is provided,
1033 it must be a nonblocking datagram socket, and the *source* and *source_port* are
1034 ignored for the UDP query.
1035
1036 *tcp_sock*, a ``socket.socket``, or ``None``, the connected socket to use for the
1037 TCP query. If ``None``, the default, a socket is created. Note that if a socket is
1038 provided, it must be a nonblocking connected stream socket, and *where*, *source*
1039 and *source_port* are ignored for the TCP query.
1040
1041 *ignore_errors*, a ``bool``. If various format errors or response mismatches occur
1042 while listening for UDP, ignore them and keep listening for a valid response. The
1043 default is ``False``.
1044
1045 Returns a (``dns.message.Message``, tcp) tuple where tcp is ``True`` if and only if
1046 TCP was used.
1047 """
1048 try:
1049 response = udp(
1050 q,
1051 where,
1052 timeout,
1053 port,
1054 source,
1055 source_port,
1056 ignore_unexpected,
1057 one_rr_per_rrset,
1058 ignore_trailing,
1059 True,
1060 udp_sock,
1061 ignore_errors,
1062 )
1063 return (response, False)
1064 except dns.message.Truncated:
1065 response = tcp(
1066 q,
1067 where,
1068 timeout,
1069 port,
1070 source,
1071 source_port,
1072 one_rr_per_rrset,
1073 ignore_trailing,
1074 tcp_sock,
1075 )
1076 return (response, True)
1077
1078
1079 def _net_read(sock, count, expiration):
1080 """Read the specified number of bytes from sock. Keep trying until we
1081 either get the desired amount, or we hit EOF.
1082 A Timeout exception will be raised if the operation is not completed
1083 by the expiration time.
1084 """
1085 s = b""
1086 while count > 0:
1087 try:
1088 n = sock.recv(count)
1089 if n == b"":
1090 raise EOFError("EOF")
1091 count -= len(n)
1092 s += n
1093 except (BlockingIOError, ssl.SSLWantReadError):
1094 _wait_for_readable(sock, expiration)
1095 except ssl.SSLWantWriteError: # pragma: no cover
1096 _wait_for_writable(sock, expiration)
1097 return s
1098
1099
1100 def _net_write(sock, data, expiration):
1101 """Write the specified data to the socket.
1102 A Timeout exception will be raised if the operation is not completed
1103 by the expiration time.
1104 """
1105 current = 0
1106 l = len(data)
1107 while current < l:
1108 try:
1109 current += sock.send(data[current:])
1110 except (BlockingIOError, ssl.SSLWantWriteError):
1111 _wait_for_writable(sock, expiration)
1112 except ssl.SSLWantReadError: # pragma: no cover
1113 _wait_for_readable(sock, expiration)
1114
1115
1116 def send_tcp(
1117 sock: Any,
1118 what: dns.message.Message | bytes,
1119 expiration: float | None = None,
1120 ) -> Tuple[int, float]:
1121 """Send a DNS message to the specified TCP socket.
1122
1123 *sock*, a ``socket``.
1124
1125 *what*, a ``bytes`` or ``dns.message.Message``, the message to send.
1126
1127 *expiration*, a ``float`` or ``None``, the absolute time at which
1128 a timeout exception should be raised. If ``None``, no timeout will
1129 occur.
1130
1131 Returns an ``(int, float)`` tuple of bytes sent and the sent time.
1132 """
1133
1134 if isinstance(what, dns.message.Message):
1135 tcpmsg = what.to_wire(prepend_length=True)
1136 else:
1137 # copying the wire into tcpmsg is inefficient, but lets us
1138 # avoid writev() or doing a short write that would get pushed
1139 # onto the net
1140 tcpmsg = len(what).to_bytes(2, "big") + what
1141 sent_time = time.time()
1142 _net_write(sock, tcpmsg, expiration)
1143 return (len(tcpmsg), sent_time)
1144
1145
1146 def receive_tcp(
1147 sock: Any,
1148 expiration: float | None = None,
1149 one_rr_per_rrset: bool = False,
1150 keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None,
1151 request_mac: bytes | None = b"",
1152 ignore_trailing: bool = False,
1153 ) -> Tuple[dns.message.Message, float]:
1154 """Read a DNS message from a TCP socket.
1155
1156 *sock*, a ``socket``.
1157
1158 *expiration*, a ``float`` or ``None``, the absolute time at which
1159 a timeout exception should be raised. If ``None``, no timeout will
1160 occur.
1161
1162 *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
1163 RRset.
1164
1165 *keyring*, a ``dict``, the keyring to use for TSIG.
1166
1167 *request_mac*, a ``bytes`` or ``None``, the MAC of the request (for TSIG).
1168
1169 *ignore_trailing*, a ``bool``. If ``True``, ignore trailing
1170 junk at end of the received message.
1171
1172 Raises if the message is malformed, if network errors occur, of if
1173 there is a timeout.
1174
1175 Returns a ``(dns.message.Message, float)`` tuple of the received message
1176 and the received time.
1177 """
1178
1179 ldata = _net_read(sock, 2, expiration)
1180 (l,) = struct.unpack("!H", ldata)
1181 wire = _net_read(sock, l, expiration)
1182 received_time = time.time()
1183 r = dns.message.from_wire(
1184 wire,
1185 keyring=keyring,
1186 request_mac=request_mac,
1187 one_rr_per_rrset=one_rr_per_rrset,
1188 ignore_trailing=ignore_trailing,
1189 )
1190 return (r, received_time)
1191
1192
1193 def _connect(s, address, expiration):
1194 err = s.connect_ex(address)
1195 if err == 0:
1196 return
1197 if err in (errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY):
1198 _wait_for_writable(s, expiration)
1199 err = s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
1200 if err != 0:
1201 raise OSError(err, os.strerror(err))
1202
1203
1204 def tcp(
1205 q: dns.message.Message,
1206 where: str,
1207 timeout: float | None = None,
1208 port: int = 53,
1209 source: str | None = None,
1210 source_port: int = 0,
1211 one_rr_per_rrset: bool = False,
1212 ignore_trailing: bool = False,
1213 sock: Any | None = None,
1214 ) -> dns.message.Message:
1215 """Return the response obtained after sending a query via TCP.
1216
1217 *q*, a ``dns.message.Message``, the query to send
1218
1219 *where*, a ``str`` containing an IPv4 or IPv6 address, where
1220 to send the message.
1221
1222 *timeout*, a ``float`` or ``None``, the number of seconds to wait before the
1223 query times out. If ``None``, the default, wait forever.
1224
1225 *port*, an ``int``, the port send the message to. The default is 53.
1226
1227 *source*, a ``str`` containing an IPv4 or IPv6 address, specifying
1228 the source address. The default is the wildcard address.
1229
1230 *source_port*, an ``int``, the port from which to send the message.
1231 The default is 0.
1232
1233 *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
1234 RRset.
1235
1236 *ignore_trailing*, a ``bool``. If ``True``, ignore trailing
1237 junk at end of the received message.
1238
1239 *sock*, a ``socket.socket``, or ``None``, the connected socket to use for the
1240 query. If ``None``, the default, a socket is created. Note that
1241 if a socket is provided, it must be a nonblocking connected stream
1242 socket, and *where*, *port*, *source* and *source_port* are ignored.
1243
1244 Returns a ``dns.message.Message``.
1245 """
1246
1247 wire = q.to_wire()
1248 (begin_time, expiration) = _compute_times(timeout)
1249 if sock:
1250 cm: contextlib.AbstractContextManager = contextlib.nullcontext(sock)
1251 else:
1252 (af, destination, source) = _destination_and_source(
1253 where, port, source, source_port, True
1254 )
1255 assert af is not None
1256 cm = make_socket(af, socket.SOCK_STREAM, source)
1257 with cm as s:
1258 if not sock:
1259 # pylint: disable=possibly-used-before-assignment
1260 _connect(s, destination, expiration) # pyright: ignore
1261 send_tcp(s, wire, expiration)
1262 (r, received_time) = receive_tcp(
1263 s, expiration, one_rr_per_rrset, q.keyring, q.mac, ignore_trailing
1264 )
1265 r.time = received_time - begin_time
1266 if not q.is_response(r):
1267 raise BadResponse
1268 return r
1269 assert (
1270 False # help mypy figure out we can't get here lgtm[py/unreachable-statement]
1271 )
1272
1273
1274 def _tls_handshake(s, expiration):
1275 while True:
1276 try:
1277 s.do_handshake()
1278 return
1279 except ssl.SSLWantReadError:
1280 _wait_for_readable(s, expiration)
1281 except ssl.SSLWantWriteError: # pragma: no cover
1282 _wait_for_writable(s, expiration)
1283
1284
1285 def make_ssl_context(
1286 verify: bool | str = True,
1287 check_hostname: bool = True,
1288 alpns: list[str] | None = None,
1289 ) -> ssl.SSLContext:
1290 """Make an SSL context
1291
1292 If *verify* is ``True``, the default, then certificate verification will occur using
1293 the standard CA roots. If *verify* is ``False``, then certificate verification will
1294 be disabled. If *verify* is a string which is a valid pathname, then if the
1295 pathname is a regular file, the CA roots will be taken from the file, otherwise if
1296 the pathname is a directory roots will be taken from the directory.
1297
1298 If *check_hostname* is ``True``, the default, then the hostname of the server must
1299 be specified when connecting and the server's certificate must authorize the
1300 hostname. If ``False``, then hostname checking is disabled.
1301
1302 *aplns* is ``None`` or a list of TLS ALPN (Application Layer Protocol Negotiation)
1303 strings to use in negotiation. For DNS-over-TLS, the right value is `["dot"]`.
1304 """
1305 cafile, capath = dns._tls_util.convert_verify_to_cafile_and_capath(verify)
1306 ssl_context = ssl.create_default_context(cafile=cafile, capath=capath)
1307 # the pyright ignores below are because it gets confused between the
1308 # _no_ssl compatibility types and the real ones.
1309 ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2 # type: ignore
1310 ssl_context.check_hostname = check_hostname
1311 if verify is False:
1312 ssl_context.verify_mode = ssl.CERT_NONE # type: ignore
1313 if alpns is not None:
1314 ssl_context.set_alpn_protocols(alpns)
1315 return ssl_context # type: ignore
1316
1317
1318 # for backwards compatibility
1319 def _make_dot_ssl_context(
1320 server_hostname: str | None, verify: bool | str
1321 ) -> ssl.SSLContext:
1322 return make_ssl_context(verify, server_hostname is not None, ["dot"])
1323
1324
1325 def tls(
1326 q: dns.message.Message,
1327 where: str,
1328 timeout: float | None = None,
1329 port: int = 853,
1330 source: str | None = None,
1331 source_port: int = 0,
1332 one_rr_per_rrset: bool = False,
1333 ignore_trailing: bool = False,
1334 sock: ssl.SSLSocket | None = None,
1335 ssl_context: ssl.SSLContext | None = None,
1336 server_hostname: str | None = None,
1337 verify: bool | str = True,
1338 ) -> dns.message.Message:
1339 """Return the response obtained after sending a query via TLS.
1340
1341 *q*, a ``dns.message.Message``, the query to send
1342
1343 *where*, a ``str`` containing an IPv4 or IPv6 address, where
1344 to send the message.
1345
1346 *timeout*, a ``float`` or ``None``, the number of seconds to wait before the
1347 query times out. If ``None``, the default, wait forever.
1348
1349 *port*, an ``int``, the port send the message to. The default is 853.
1350
1351 *source*, a ``str`` containing an IPv4 or IPv6 address, specifying
1352 the source address. The default is the wildcard address.
1353
1354 *source_port*, an ``int``, the port from which to send the message.
1355 The default is 0.
1356
1357 *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
1358 RRset.
1359
1360 *ignore_trailing*, a ``bool``. If ``True``, ignore trailing
1361 junk at end of the received message.
1362
1363 *sock*, an ``ssl.SSLSocket``, or ``None``, the socket to use for
1364 the query. If ``None``, the default, a socket is created. Note
1365 that if a socket is provided, it must be a nonblocking connected
1366 SSL stream socket, and *where*, *port*, *source*, *source_port*,
1367 and *ssl_context* are ignored.
1368
1369 *ssl_context*, an ``ssl.SSLContext``, the context to use when establishing
1370 a TLS connection. If ``None``, the default, creates one with the default
1371 configuration.
1372
1373 *server_hostname*, a ``str`` containing the server's hostname. The
1374 default is ``None``, which means that no hostname is known, and if an
1375 SSL context is created, hostname checking will be disabled.
1376
1377 *verify*, a ``bool`` or ``str``. If a ``True``, then TLS certificate verification
1378 of the server is done using the default CA bundle; if ``False``, then no
1379 verification is done; if a `str` then it specifies the path to a certificate file or
1380 directory which will be used for verification.
1381
1382 Returns a ``dns.message.Message``.
1383
1384 """
1385
1386 if sock:
1387 #
1388 # If a socket was provided, there's no special TLS handling needed.
1389 #
1390 return tcp(
1391 q,
1392 where,
1393 timeout,
1394 port,
1395 source,
1396 source_port,
1397 one_rr_per_rrset,
1398 ignore_trailing,
1399 sock,
1400 )
1401
1402 wire = q.to_wire()
1403 (begin_time, expiration) = _compute_times(timeout)
1404 (af, destination, source) = _destination_and_source(
1405 where, port, source, source_port, True
1406 )
1407 assert af is not None # where must be an address
1408 if ssl_context is None:
1409 ssl_context = make_ssl_context(verify, server_hostname is not None, ["dot"])
1410
1411 with make_ssl_socket(
1412 af,
1413 socket.SOCK_STREAM,
1414 ssl_context=ssl_context,
1415 server_hostname=server_hostname,
1416 source=source,
1417 ) as s:
1418 _connect(s, destination, expiration)
1419 _tls_handshake(s, expiration)
1420 send_tcp(s, wire, expiration)
1421 (r, received_time) = receive_tcp(
1422 s, expiration, one_rr_per_rrset, q.keyring, q.mac, ignore_trailing
1423 )
1424 r.time = received_time - begin_time
1425 if not q.is_response(r):
1426 raise BadResponse
1427 return r
1428 assert (
1429 False # help mypy figure out we can't get here lgtm[py/unreachable-statement]
1430 )
1431
1432
1433 def quic(
1434 q: dns.message.Message,
1435 where: str,
1436 timeout: float | None = None,
1437 port: int = 853,
1438 source: str | None = None,
1439 source_port: int = 0,
1440 one_rr_per_rrset: bool = False,
1441 ignore_trailing: bool = False,
1442 connection: dns.quic.SyncQuicConnection | None = None,
1443 verify: bool | str = True,
1444 hostname: str | None = None,
1445 server_hostname: str | None = None,
1446 ) -> dns.message.Message:
1447 """Return the response obtained after sending a query via DNS-over-QUIC.
1448
1449 *q*, a ``dns.message.Message``, the query to send.
1450
1451 *where*, a ``str``, the nameserver IP address.
1452
1453 *timeout*, a ``float`` or ``None``, the number of seconds to wait before the query
1454 times out. If ``None``, the default, wait forever.
1455
1456 *port*, a ``int``, the port to send the query to. The default is 853.
1457
1458 *source*, a ``str`` containing an IPv4 or IPv6 address, specifying the source
1459 address. The default is the wildcard address.
1460
1461 *source_port*, an ``int``, the port from which to send the message. The default is
1462 0.
1463
1464 *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset.
1465
1466 *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the
1467 received message.
1468
1469 *connection*, a ``dns.quic.SyncQuicConnection``. If provided, the connection to use
1470 to send the query.
1471
1472 *verify*, a ``bool`` or ``str``. If a ``True``, then TLS certificate verification
1473 of the server is done using the default CA bundle; if ``False``, then no
1474 verification is done; if a `str` then it specifies the path to a certificate file or
1475 directory which will be used for verification.
1476
1477 *hostname*, a ``str`` containing the server's hostname or ``None``. The default is
1478 ``None``, which means that no hostname is known, and if an SSL context is created,
1479 hostname checking will be disabled. This value is ignored if *url* is not
1480 ``None``.
1481
1482 *server_hostname*, a ``str`` or ``None``. This item is for backwards compatibility
1483 only, and has the same meaning as *hostname*.
1484
1485 Returns a ``dns.message.Message``.
1486 """
1487
1488 if not dns.quic.have_quic:
1489 raise NoDOQ("DNS-over-QUIC is not available.") # pragma: no cover
1490
1491 if server_hostname is not None and hostname is None:
1492 hostname = server_hostname
1493
1494 q.id = 0
1495 wire = q.to_wire()
1496 the_connection: dns.quic.SyncQuicConnection
1497 the_manager: dns.quic.SyncQuicManager
1498 if connection:
1499 manager: contextlib.AbstractContextManager = contextlib.nullcontext(None)
1500 the_connection = connection
1501 else:
1502 manager = dns.quic.SyncQuicManager(
1503 verify_mode=verify, server_name=hostname # pyright: ignore
1504 )
1505 the_manager = manager # for type checking happiness
1506
1507 with manager:
1508 if not connection:
1509 the_connection = the_manager.connect( # pyright: ignore
1510 where, port, source, source_port
1511 )
1512 (start, expiration) = _compute_times(timeout)
1513 with the_connection.make_stream(timeout) as stream: # pyright: ignore
1514 stream.send(wire, True)
1515 wire = stream.receive(_remaining(expiration))
1516 finish = time.time()
1517 r = dns.message.from_wire(
1518 wire,
1519 keyring=q.keyring,
1520 request_mac=q.request_mac,
1521 one_rr_per_rrset=one_rr_per_rrset,
1522 ignore_trailing=ignore_trailing,
1523 )
1524 r.time = max(finish - start, 0.0)
1525 if not q.is_response(r):
1526 raise BadResponse
1527 return r
1528
1529
1530 class UDPMode(enum.IntEnum):
1531 """How should UDP be used in an IXFR from :py:func:`inbound_xfr()`?
1532
1533 NEVER means "never use UDP; always use TCP"
1534 TRY_FIRST means "try to use UDP but fall back to TCP if needed"
1535 ONLY means "raise ``dns.xfr.UseTCP`` if trying UDP does not succeed"
1536 """
1537
1538 NEVER = 0
1539 TRY_FIRST = 1
1540 ONLY = 2
1541
1542
1543 def _inbound_xfr(
1544 txn_manager: dns.transaction.TransactionManager,
1545 s: socket.socket | ssl.SSLSocket,
1546 query: dns.message.Message,
1547 serial: int | None,
1548 timeout: float | None,
1549 expiration: float | None,
1550 ) -> Any:
1551 """Given a socket, does the zone transfer."""
1552 rdtype = query.question[0].rdtype
1553 is_ixfr = rdtype == dns.rdatatype.IXFR
1554 origin = txn_manager.from_wire_origin()
1555 wire = query.to_wire()
1556 is_udp = isinstance(s, socket.socket) and s.type == socket.SOCK_DGRAM
1557 if is_udp:
1558 _udp_send(s, wire, None, expiration)
1559 else:
1560 tcpmsg = struct.pack("!H", len(wire)) + wire
1561 _net_write(s, tcpmsg, expiration)
1562 with dns.xfr.Inbound(txn_manager, rdtype, serial, is_udp) as inbound:
1563 done = False
1564 tsig_ctx = None
1565 r: dns.message.Message | None = None
1566 while not done:
1567 (_, mexpiration) = _compute_times(timeout)
1568 if mexpiration is None or (
1569 expiration is not None and mexpiration > expiration
1570 ):
1571 mexpiration = expiration
1572 if is_udp:
1573 (rwire, _) = _udp_recv(s, 65535, mexpiration)
1574 else:
1575 ldata = _net_read(s, 2, mexpiration)
1576 (l,) = struct.unpack("!H", ldata)
1577 rwire = _net_read(s, l, mexpiration)
1578 r = dns.message.from_wire(
1579 rwire,
1580 keyring=query.keyring,
1581 request_mac=query.mac,
1582 xfr=True,
1583 origin=origin,
1584 tsig_ctx=tsig_ctx,
1585 multi=(not is_udp),
1586 one_rr_per_rrset=is_ixfr,
1587 )
1588 done = inbound.process_message(r)
1589 yield r
1590 tsig_ctx = r.tsig_ctx
1591 if query.keyring and r is not None and not r.had_tsig:
1592 raise dns.exception.FormError("missing TSIG")
1593
1594
1595 def xfr(
1596 where: str,
1597 zone: dns.name.Name | str,
1598 rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.AXFR,
1599 rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN,
1600 timeout: float | None = None,
1601 port: int = 53,
1602 keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None,
1603 keyname: dns.name.Name | str | None = None,
1604 relativize: bool = True,
1605 lifetime: float | None = None,
1606 source: str | None = None,
1607 source_port: int = 0,
1608 serial: int = 0,
1609 use_udp: bool = False,
1610 keyalgorithm: dns.name.Name | str = dns.tsig.default_algorithm,
1611 ) -> Any:
1612 """Return a generator for the responses to a zone transfer.
1613
1614 *where*, a ``str`` containing an IPv4 or IPv6 address, where
1615 to send the message.
1616
1617 *zone*, a ``dns.name.Name`` or ``str``, the name of the zone to transfer.
1618
1619 *rdtype*, an ``int`` or ``str``, the type of zone transfer. The
1620 default is ``dns.rdatatype.AXFR``. ``dns.rdatatype.IXFR`` can be
1621 used to do an incremental transfer instead.
1622
1623 *rdclass*, an ``int`` or ``str``, the class of the zone transfer.
1624 The default is ``dns.rdataclass.IN``.
1625
1626 *timeout*, a ``float``, the number of seconds to wait for each
1627 response message. If None, the default, wait forever.
1628
1629 *port*, an ``int``, the port send the message to. The default is 53.
1630
1631 *keyring*, a ``dict``, the keyring to use for TSIG.
1632
1633 *keyname*, a ``dns.name.Name`` or ``str``, the name of the TSIG
1634 key to use.
1635
1636 *relativize*, a ``bool``. If ``True``, all names in the zone will be
1637 relativized to the zone origin. It is essential that the
1638 relativize setting matches the one specified to
1639 ``dns.zone.from_xfr()`` if using this generator to make a zone.
1640
1641 *lifetime*, a ``float``, the total number of seconds to spend
1642 doing the transfer. If ``None``, the default, then there is no
1643 limit on the time the transfer may take.
1644
1645 *source*, a ``str`` containing an IPv4 or IPv6 address, specifying
1646 the source address. The default is the wildcard address.
1647
1648 *source_port*, an ``int``, the port from which to send the message.
1649 The default is 0.
1650
1651 *serial*, an ``int``, the SOA serial number to use as the base for
1652 an IXFR diff sequence (only meaningful if *rdtype* is
1653 ``dns.rdatatype.IXFR``).
1654
1655 *use_udp*, a ``bool``. If ``True``, use UDP (only meaningful for IXFR).
1656
1657 *keyalgorithm*, a ``dns.name.Name`` or ``str``, the TSIG algorithm to use.
1658
1659 Raises on errors, and so does the generator.
1660
1661 Returns a generator of ``dns.message.Message`` objects.
1662 """
1663
1664 class DummyTransactionManager(dns.transaction.TransactionManager):
1665 def __init__(self, origin, relativize):
1666 self.info = (origin, relativize, dns.name.empty if relativize else origin)
1667
1668 def origin_information(self):
1669 return self.info
1670
1671 def get_class(self) -> dns.rdataclass.RdataClass:
1672 raise NotImplementedError # pragma: no cover
1673
1674 def reader(self):
1675 raise NotImplementedError # pragma: no cover
1676
1677 def writer(self, replacement: bool = False) -> dns.transaction.Transaction:
1678 class DummyTransaction:
1679 def nop(self, *args, **kw):
1680 pass
1681
1682 def __getattr__(self, _):
1683 return self.nop
1684
1685 return cast(dns.transaction.Transaction, DummyTransaction())
1686
1687 if isinstance(zone, str):
1688 zone = dns.name.from_text(zone)
1689 rdtype = dns.rdatatype.RdataType.make(rdtype)
1690 q = dns.message.make_query(zone, rdtype, rdclass)
1691 if rdtype == dns.rdatatype.IXFR:
1692 rrset = q.find_rrset(
1693 q.authority, zone, dns.rdataclass.IN, dns.rdatatype.SOA, create=True
1694 )
1695 soa = dns.rdata.from_text("IN", "SOA", f". . {serial} 0 0 0 0")
1696 rrset.add(soa, 0)
1697 if keyring is not None:
1698 q.use_tsig(keyring, keyname, algorithm=keyalgorithm)
1699 (af, destination, source) = _destination_and_source(
1700 where, port, source, source_port, True
1701 )
1702 assert af is not None
1703 (_, expiration) = _compute_times(lifetime)
1704 tm = DummyTransactionManager(zone, relativize)
1705 if use_udp and rdtype != dns.rdatatype.IXFR:
1706 raise ValueError("cannot do a UDP AXFR")
1707 sock_type = socket.SOCK_DGRAM if use_udp else socket.SOCK_STREAM
1708 with make_socket(af, sock_type, source) as s:
1709 _connect(s, destination, expiration)
1710 yield from _inbound_xfr(tm, s, q, serial, timeout, expiration)
1711
1712
1713 def inbound_xfr(
1714 where: str,
1715 txn_manager: dns.transaction.TransactionManager,
1716 query: dns.message.Message | None = None,
1717 port: int = 53,
1718 timeout: float | None = None,
1719 lifetime: float | None = None,
1720 source: str | None = None,
1721 source_port: int = 0,
1722 udp_mode: UDPMode = UDPMode.NEVER,
1723 ) -> None:
1724 """Conduct an inbound transfer and apply it via a transaction from the
1725 txn_manager.
1726
1727 *where*, a ``str`` containing an IPv4 or IPv6 address, where
1728 to send the message.
1729
1730 *txn_manager*, a ``dns.transaction.TransactionManager``, the txn_manager
1731 for this transfer (typically a ``dns.zone.Zone``).
1732
1733 *query*, the query to send. If not supplied, a default query is
1734 constructed using information from the *txn_manager*.
1735
1736 *port*, an ``int``, the port send the message to. The default is 53.
1737
1738 *timeout*, a ``float``, the number of seconds to wait for each
1739 response message. If None, the default, wait forever.
1740
1741 *lifetime*, a ``float``, the total number of seconds to spend
1742 doing the transfer. If ``None``, the default, then there is no
1743 limit on the time the transfer may take.
1744
1745 *source*, a ``str`` containing an IPv4 or IPv6 address, specifying
1746 the source address. The default is the wildcard address.
1747
1748 *source_port*, an ``int``, the port from which to send the message.
1749 The default is 0.
1750
1751 *udp_mode*, a ``dns.query.UDPMode``, determines how UDP is used
1752 for IXFRs. The default is ``dns.query.UDPMode.NEVER``, i.e. only use
1753 TCP. Other possibilities are ``dns.query.UDPMode.TRY_FIRST``, which
1754 means "try UDP but fallback to TCP if needed", and
1755 ``dns.query.UDPMode.ONLY``, which means "try UDP and raise
1756 ``dns.xfr.UseTCP`` if it does not succeed.
1757
1758 Raises on errors.
1759 """
1760 if query is None:
1761 (query, serial) = dns.xfr.make_query(txn_manager)
1762 else:
1763 serial = dns.xfr.extract_serial_from_query(query)
1764
1765 (af, destination, source) = _destination_and_source(
1766 where, port, source, source_port, True
1767 )
1768 assert af is not None
1769 (_, expiration) = _compute_times(lifetime)
1770 if query.question[0].rdtype == dns.rdatatype.IXFR and udp_mode != UDPMode.NEVER:
1771 with make_socket(af, socket.SOCK_DGRAM, source) as s:
1772 _connect(s, destination, expiration)
1773 try:
1774 for _ in _inbound_xfr(
1775 txn_manager, s, query, serial, timeout, expiration
1776 ):
1777 pass
1778 return
1779 except dns.xfr.UseTCP:
1780 if udp_mode == UDPMode.ONLY:
1781 raise
1782
1783 with make_socket(af, socket.SOCK_STREAM, source) as s:
1784 _connect(s, destination, expiration)
1785 for _ in _inbound_xfr(txn_manager, s, query, serial, timeout, expiration):
1786 pass