Debian Codegraph @

dns/message.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 # Copyright (C) 2001-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 """DNS Messages"""
19
20 import contextlib
21 import enum
22 import io
23 import time
24 from typing import Any, Dict, List, Tuple, cast
25
26 import dns.edns
27 import dns.entropy
28 import dns.enum
29 import dns.exception
30 import dns.flags
31 import dns.name
32 import dns.opcode
33 import dns.rcode
34 import dns.rdata
35 import dns.rdataclass
36 import dns.rdatatype
37 import dns.rdtypes.ANY.OPT
38 import dns.rdtypes.ANY.SOA
39 import dns.rdtypes.ANY.TSIG
40 import dns.renderer
41 import dns.rrset
42 import dns.tokenizer
43 import dns.tsig
44 import dns.ttl
45 import dns.wire
46
47
48 class ShortHeader(dns.exception.FormError):
49 """The DNS packet passed to from_wire() is too short."""
50
51
52 class TrailingJunk(dns.exception.FormError):
53 """The DNS packet passed to from_wire() has extra junk at the end of it."""
54
55
56 class UnknownHeaderField(dns.exception.DNSException):
57 """The header field name was not recognized when converting from text
58 into a message."""
59
60
61 class BadEDNS(dns.exception.FormError):
62 """An OPT record occurred somewhere other than
63 the additional data section."""
64
65
66 class BadTSIG(dns.exception.FormError):
67 """A TSIG record occurred somewhere other than the end of
68 the additional data section."""
69
70
71 class UnknownTSIGKey(dns.exception.DNSException):
72 """A TSIG with an unknown key was received."""
73
74
75 class Truncated(dns.exception.DNSException):
76 """The truncated flag is set."""
77
78 supp_kwargs = {"message"}
79
80 # We do this as otherwise mypy complains about unexpected keyword argument
81 # idna_exception
82 def __init__(self, *args, **kwargs):
83 super().__init__(*args, **kwargs)
84
85 def message(self):
86 """As much of the message as could be processed.
87
88 Returns a ``dns.message.Message``.
89 """
90 return self.kwargs["message"]
91
92
93 class NotQueryResponse(dns.exception.DNSException):
94 """Message is not a response to a query."""
95
96
97 class ChainTooLong(dns.exception.DNSException):
98 """The CNAME chain is too long."""
99
100
101 class AnswerForNXDOMAIN(dns.exception.DNSException):
102 """The rcode is NXDOMAIN but an answer was found."""
103
104
105 class NoPreviousName(dns.exception.SyntaxError):
106 """No previous name was known."""
107
108
109 class MessageSection(dns.enum.IntEnum):
110 """Message sections"""
111
112 QUESTION = 0
113 ANSWER = 1
114 AUTHORITY = 2
115 ADDITIONAL = 3
116
117 @classmethod
118 def _maximum(cls):
119 return 3
120
121
122 class MessageError:
123 def __init__(self, exception: Exception, offset: int):
124 self.exception = exception
125 self.offset = offset
126
127
128 DEFAULT_EDNS_PAYLOAD = 1232
129 MAX_CHAIN = 16
130
131 IndexKeyType = Tuple[
132 int,
133 dns.name.Name,
134 dns.rdataclass.RdataClass,
135 dns.rdatatype.RdataType,
136 dns.rdatatype.RdataType | None,
137 dns.rdataclass.RdataClass | None,
138 ]
139 IndexType = Dict[IndexKeyType, dns.rrset.RRset]
140 SectionType = int | str | List[dns.rrset.RRset]
141
142
143 class Message:
144 """A DNS message."""
145
146 _section_enum = MessageSection
147
148 def __init__(self, id: int | None = None):
149 if id is None:
150 self.id = dns.entropy.random_16()
151 else:
152 self.id = id
153 self.flags = 0
154 self.sections: List[List[dns.rrset.RRset]] = [[], [], [], []]
155 self.opt: dns.rrset.RRset | None = None
156 self.request_payload = 0
157 self.pad = 0
158 self.keyring: Any = None
159 self.tsig: dns.rrset.RRset | None = None
160 self.want_tsig_sign = False
161 self.request_mac = b""
162 self.xfr = False
163 self.origin: dns.name.Name | None = None
164 self.tsig_ctx: Any | None = None
165 self.index: IndexType = {}
166 self.errors: List[MessageError] = []
167 self.time = 0.0
168 self.wire: bytes | None = None
169
170 @property
171 def question(self) -> List[dns.rrset.RRset]:
172 """The question section."""
173 return self.sections[0]
174
175 @question.setter
176 def question(self, v):
177 self.sections[0] = v
178
179 @property
180 def answer(self) -> List[dns.rrset.RRset]:
181 """The answer section."""
182 return self.sections[1]
183
184 @answer.setter
185 def answer(self, v):
186 self.sections[1] = v
187
188 @property
189 def authority(self) -> List[dns.rrset.RRset]:
190 """The authority section."""
191 return self.sections[2]
192
193 @authority.setter
194 def authority(self, v):
195 self.sections[2] = v
196
197 @property
198 def additional(self) -> List[dns.rrset.RRset]:
199 """The additional data section."""
200 return self.sections[3]
201
202 @additional.setter
203 def additional(self, v):
204 self.sections[3] = v
205
206 def __repr__(self):
207 return "<DNS message, ID " + repr(self.id) + ">"
208
209 def __str__(self):
210 return self.to_text()
211
212 def to_text(
213 self,
214 origin: dns.name.Name | None = None,
215 relativize: bool = True,
216 **kw: Dict[str, Any],
217 ) -> str:
218 """Convert the message to text.
219
220 The *origin*, *relativize*, and any other keyword
221 arguments are passed to the RRset ``to_wire()`` method.
222
223 Returns a ``str``.
224 """
225
226 s = io.StringIO()
227 s.write(f"id {self.id}\n")
228 s.write(f"opcode {dns.opcode.to_text(self.opcode())}\n")
229 s.write(f"rcode {dns.rcode.to_text(self.rcode())}\n")
230 s.write(f"flags {dns.flags.to_text(self.flags)}\n")
231 if self.edns >= 0:
232 s.write(f"edns {self.edns}\n")
233 if self.ednsflags != 0:
234 s.write(f"eflags {dns.flags.edns_to_text(self.ednsflags)}\n")
235 s.write(f"payload {self.payload}\n")
236 for opt in self.options:
237 s.write(f"option {opt.to_text()}\n")
238 for name, which in self._section_enum.__members__.items():
239 s.write(f";{name}\n")
240 for rrset in self.section_from_number(which):
241 s.write(rrset.to_text(origin, relativize, **kw))
242 s.write("\n")
243 if self.tsig is not None:
244 s.write(self.tsig.to_text(origin, relativize, **kw))
245 s.write("\n")
246 #
247 # We strip off the final \n so the caller can print the result without
248 # doing weird things to get around eccentricities in Python print
249 # formatting
250 #
251 return s.getvalue()[:-1]
252
253 def __eq__(self, other):
254 """Two messages are equal if they have the same content in the
255 header, question, answer, and authority sections.
256
257 Returns a ``bool``.
258 """
259
260 if not isinstance(other, Message):
261 return False
262 if self.id != other.id:
263 return False
264 if self.flags != other.flags:
265 return False
266 for i, section in enumerate(self.sections):
267 other_section = other.sections[i]
268 for n in section:
269 if n not in other_section:
270 return False
271 for n in other_section:
272 if n not in section:
273 return False
274 return True
275
276 def __ne__(self, other):
277 return not self.__eq__(other)
278
279 def is_response(self, other: "Message") -> bool:
280 """Is *other*, also a ``dns.message.Message``, a response to this
281 message?
282
283 Returns a ``bool``.
284 """
285
286 if (
287 other.flags & dns.flags.QR == 0
288 or self.id != other.id
289 or dns.opcode.from_flags(self.flags) != dns.opcode.from_flags(other.flags)
290 ):
291 return False
292 if other.rcode() in {
293 dns.rcode.FORMERR,
294 dns.rcode.SERVFAIL,
295 dns.rcode.NOTIMP,
296 dns.rcode.REFUSED,
297 }:
298 # We don't check the question section in these cases if
299 # the other question section is empty, even though they
300 # still really ought to have a question section.
301 if len(other.question) == 0:
302 return True
303 if dns.opcode.is_update(self.flags):
304 # This is assuming the "sender doesn't include anything
305 # from the update", but we don't care to check the other
306 # case, which is that all the sections are returned and
307 # identical.
308 return True
309 for n in self.question:
310 if n not in other.question:
311 return False
312 for n in other.question:
313 if n not in self.question:
314 return False
315 return True
316
317 def section_number(self, section: List[dns.rrset.RRset]) -> int:
318 """Return the "section number" of the specified section for use
319 in indexing.
320
321 *section* is one of the section attributes of this message.
322
323 Raises ``ValueError`` if the section isn't known.
324
325 Returns an ``int``.
326 """
327
328 for i, our_section in enumerate(self.sections):
329 if section is our_section:
330 return self._section_enum(i)
331 raise ValueError("unknown section")
332
333 def section_from_number(self, number: int) -> List[dns.rrset.RRset]:
334 """Return the section list associated with the specified section
335 number.
336
337 *number* is a section number `int` or the text form of a section
338 name.
339
340 Raises ``ValueError`` if the section isn't known.
341
342 Returns a ``list``.
343 """
344
345 section = self._section_enum.make(number)
346 return self.sections[section]
347
348 def find_rrset(
349 self,
350 section: SectionType,
351 name: dns.name.Name,
352 rdclass: dns.rdataclass.RdataClass,
353 rdtype: dns.rdatatype.RdataType,
354 covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
355 deleting: dns.rdataclass.RdataClass | None = None,
356 create: bool = False,
357 force_unique: bool = False,
358 idna_codec: dns.name.IDNACodec | None = None,
359 ) -> dns.rrset.RRset:
360 """Find the RRset with the given attributes in the specified section.
361
362 *section*, an ``int`` section number, a ``str`` section name, or one of
363 the section attributes of this message. This specifies the
364 the section of the message to search. For example::
365
366 my_message.find_rrset(my_message.answer, name, rdclass, rdtype)
367 my_message.find_rrset(dns.message.ANSWER, name, rdclass, rdtype)
368 my_message.find_rrset("ANSWER", name, rdclass, rdtype)
369
370 *name*, a ``dns.name.Name`` or ``str``, the name of the RRset.
371
372 *rdclass*, an ``int`` or ``str``, the class of the RRset.
373
374 *rdtype*, an ``int`` or ``str``, the type of the RRset.
375
376 *covers*, an ``int`` or ``str``, the covers value of the RRset.
377 The default is ``dns.rdatatype.NONE``.
378
379 *deleting*, an ``int``, ``str``, or ``None``, the deleting value of the
380 RRset. The default is ``None``.
381
382 *create*, a ``bool``. If ``True``, create the RRset if it is not found.
383 The created RRset is appended to *section*.
384
385 *force_unique*, a ``bool``. If ``True`` and *create* is also ``True``,
386 create a new RRset regardless of whether a matching RRset exists
387 already. The default is ``False``. This is useful when creating
388 DDNS Update messages, as order matters for them.
389
390 *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
391 encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
392 is used.
393
394 Raises ``KeyError`` if the RRset was not found and create was
395 ``False``.
396
397 Returns a ``dns.rrset.RRset object``.
398 """
399
400 if isinstance(section, int):
401 section_number = section
402 section = self.section_from_number(section_number)
403 elif isinstance(section, str):
404 section_number = self._section_enum.from_text(section)
405 section = self.section_from_number(section_number)
406 else:
407 section_number = self.section_number(section)
408 if isinstance(name, str):
409 name = dns.name.from_text(name, idna_codec=idna_codec)
410 rdtype = dns.rdatatype.RdataType.make(rdtype)
411 rdclass = dns.rdataclass.RdataClass.make(rdclass)
412 covers = dns.rdatatype.RdataType.make(covers)
413 if deleting is not None:
414 deleting = dns.rdataclass.RdataClass.make(deleting)
415 key = (section_number, name, rdclass, rdtype, covers, deleting)
416 if not force_unique:
417 if self.index is not None:
418 rrset = self.index.get(key)
419 if rrset is not None:
420 return rrset
421 else:
422 for rrset in section:
423 if rrset.full_match(name, rdclass, rdtype, covers, deleting):
424 return rrset
425 if not create:
426 raise KeyError
427 rrset = dns.rrset.RRset(name, rdclass, rdtype, covers, deleting)
428 section.append(rrset)
429 if self.index is not None:
430 self.index[key] = rrset
431 return rrset
432
433 def get_rrset(
434 self,
435 section: SectionType,
436 name: dns.name.Name,
437 rdclass: dns.rdataclass.RdataClass,
438 rdtype: dns.rdatatype.RdataType,
439 covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
440 deleting: dns.rdataclass.RdataClass | None = None,
441 create: bool = False,
442 force_unique: bool = False,
443 idna_codec: dns.name.IDNACodec | None = None,
444 ) -> dns.rrset.RRset | None:
445 """Get the RRset with the given attributes in the specified section.
446
447 If the RRset is not found, None is returned.
448
449 *section*, an ``int`` section number, a ``str`` section name, or one of
450 the section attributes of this message. This specifies the
451 the section of the message to search. For example::
452
453 my_message.get_rrset(my_message.answer, name, rdclass, rdtype)
454 my_message.get_rrset(dns.message.ANSWER, name, rdclass, rdtype)
455 my_message.get_rrset("ANSWER", name, rdclass, rdtype)
456
457 *name*, a ``dns.name.Name`` or ``str``, the name of the RRset.
458
459 *rdclass*, an ``int`` or ``str``, the class of the RRset.
460
461 *rdtype*, an ``int`` or ``str``, the type of the RRset.
462
463 *covers*, an ``int`` or ``str``, the covers value of the RRset.
464 The default is ``dns.rdatatype.NONE``.
465
466 *deleting*, an ``int``, ``str``, or ``None``, the deleting value of the
467 RRset. The default is ``None``.
468
469 *create*, a ``bool``. If ``True``, create the RRset if it is not found.
470 The created RRset is appended to *section*.
471
472 *force_unique*, a ``bool``. If ``True`` and *create* is also ``True``,
473 create a new RRset regardless of whether a matching RRset exists
474 already. The default is ``False``. This is useful when creating
475 DDNS Update messages, as order matters for them.
476
477 *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
478 encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
479 is used.
480
481 Returns a ``dns.rrset.RRset object`` or ``None``.
482 """
483
484 try:
485 rrset = self.find_rrset(
486 section,
487 name,
488 rdclass,
489 rdtype,
490 covers,
491 deleting,
492 create,
493 force_unique,
494 idna_codec,
495 )
496 except KeyError:
497 rrset = None
498 return rrset
499
500 def section_count(self, section: SectionType) -> int:
501 """Returns the number of records in the specified section.
502
503 *section*, an ``int`` section number, a ``str`` section name, or one of
504 the section attributes of this message. This specifies the
505 the section of the message to count. For example::
506
507 my_message.section_count(my_message.answer)
508 my_message.section_count(dns.message.ANSWER)
509 my_message.section_count("ANSWER")
510 """
511
512 if isinstance(section, int):
513 section_number = section
514 section = self.section_from_number(section_number)
515 elif isinstance(section, str):
516 section_number = self._section_enum.from_text(section)
517 section = self.section_from_number(section_number)
518 else:
519 section_number = self.section_number(section)
520 count = sum(max(1, len(rrs)) for rrs in section)
521 if section_number == MessageSection.ADDITIONAL:
522 if self.opt is not None:
523 count += 1
524 if self.tsig is not None:
525 count += 1
526 return count
527
528 def _compute_opt_reserve(self) -> int:
529 """Compute the size required for the OPT RR, padding excluded"""
530 if not self.opt:
531 return 0
532 # 1 byte for the root name, 10 for the standard RR fields
533 size = 11
534 # This would be more efficient if options had a size() method, but we won't
535 # worry about that for now. We also don't worry if there is an existing padding
536 # option, as it is unlikely and probably harmless, as the worst case is that we
537 # may add another, and this seems to be legal.
538 opt_rdata = cast(dns.rdtypes.ANY.OPT.OPT, self.opt[0])
539 for option in opt_rdata.options:
540 wire = option.to_wire()
541 # We add 4 here to account for the option type and length
542 size += len(wire) + 4
543 if self.pad:
544 # Padding will be added, so again add the option type and length.
545 size += 4
546 return size
547
548 def _compute_tsig_reserve(self) -> int:
549 """Compute the size required for the TSIG RR"""
550 # This would be more efficient if TSIGs had a size method, but we won't
551 # worry about for now. Also, we can't really cope with the potential
552 # compressibility of the TSIG owner name, so we estimate with the uncompressed
553 # size. We will disable compression when TSIG and padding are both is active
554 # so that the padding comes out right.
555 if not self.tsig:
556 return 0
557 f = io.BytesIO()
558 self.tsig.to_wire(f)
559 return len(f.getvalue())
560
561 def to_wire(
562 self,
563 origin: dns.name.Name | None = None,
564 max_size: int = 0,
565 multi: bool = False,
566 tsig_ctx: Any | None = None,
567 prepend_length: bool = False,
568 prefer_truncation: bool = False,
569 **kw: Dict[str, Any],
570 ) -> bytes:
571 """Return a string containing the message in DNS compressed wire
572 format.
573
574 Additional keyword arguments are passed to the RRset ``to_wire()``
575 method.
576
577 *origin*, a ``dns.name.Name`` or ``None``, the origin to be appended
578 to any relative names. If ``None``, and the message has an origin
579 attribute that is not ``None``, then it will be used.
580
581 *max_size*, an ``int``, the maximum size of the wire format
582 output; default is 0, which means "the message's request
583 payload, if nonzero, or 65535".
584
585 *multi*, a ``bool``, should be set to ``True`` if this message is
586 part of a multiple message sequence.
587
588 *tsig_ctx*, a ``dns.tsig.HMACTSig`` or ``dns.tsig.GSSTSig`` object, the
589 ongoing TSIG context, used when signing zone transfers.
590
591 *prepend_length*, a ``bool``, should be set to ``True`` if the caller
592 wants the message length prepended to the message itself. This is
593 useful for messages sent over TCP, TLS (DoT), or QUIC (DoQ).
594
595 *prefer_truncation*, a ``bool``, should be set to ``True`` if the caller
596 wants the message to be truncated if it would otherwise exceed the
597 maximum length. If the truncation occurs before the additional section,
598 the TC bit will be set.
599
600 Raises ``dns.exception.TooBig`` if *max_size* was exceeded.
601
602 Returns a ``bytes``.
603 """
604
605 if origin is None and self.origin is not None:
606 origin = self.origin
607 if max_size == 0:
608 if self.request_payload != 0:
609 max_size = self.request_payload
610 else:
611 max_size = 65535
612 if max_size < 512:
613 max_size = 512
614 elif max_size > 65535:
615 max_size = 65535
616 r = dns.renderer.Renderer(self.id, self.flags, max_size, origin)
617 opt_reserve = self._compute_opt_reserve()
618 r.reserve(opt_reserve)
619 tsig_reserve = self._compute_tsig_reserve()
620 r.reserve(tsig_reserve)
621 try:
622 for rrset in self.question:
623 r.add_question(rrset.name, rrset.rdtype, rrset.rdclass)
624 for rrset in self.answer:
625 r.add_rrset(dns.renderer.ANSWER, rrset, **kw)
626 for rrset in self.authority:
627 r.add_rrset(dns.renderer.AUTHORITY, rrset, **kw)
628 for rrset in self.additional:
629 r.add_rrset(dns.renderer.ADDITIONAL, rrset, **kw)
630 except dns.exception.TooBig:
631 if prefer_truncation:
632 if r.section < dns.renderer.ADDITIONAL:
633 r.flags |= dns.flags.TC
634 else:
635 raise
636 r.release_reserved()
637 if self.opt is not None:
638 r.add_opt(self.opt, self.pad, opt_reserve, tsig_reserve)
639 r.write_header()
640 if self.tsig is not None:
641 if self.want_tsig_sign:
642 (new_tsig, ctx) = dns.tsig.sign(
643 r.get_wire(),
644 self.keyring,
645 self.tsig[0],
646 int(time.time()),
647 self.request_mac,
648 tsig_ctx,
649 multi,
650 )
651 self.tsig.clear()
652 self.tsig.add(new_tsig)
653 if multi:
654 self.tsig_ctx = ctx
655 r.add_rrset(dns.renderer.ADDITIONAL, self.tsig)
656 r.write_header()
657 wire = r.get_wire()
658 self.wire = wire
659 if prepend_length:
660 wire = len(wire).to_bytes(2, "big") + wire
661 return wire
662
663 @staticmethod
664 def _make_tsig(
665 keyname, algorithm, time_signed, fudge, mac, original_id, error, other
666 ):
667 tsig = dns.rdtypes.ANY.TSIG.TSIG(
668 dns.rdataclass.ANY,
669 dns.rdatatype.TSIG,
670 algorithm,
671 time_signed,
672 fudge,
673 mac,
674 original_id,
675 error,
676 other,
677 )
678 return dns.rrset.from_rdata(keyname, 0, tsig)
679
680 def use_tsig(
681 self,
682 keyring: Any,
683 keyname: dns.name.Name | str | None = None,
684 fudge: int = 300,
685 original_id: int | None = None,
686 tsig_error: int = 0,
687 other_data: bytes = b"",
688 algorithm: dns.name.Name | str = dns.tsig.default_algorithm,
689 ) -> None:
690 """When sending, a TSIG signature using the specified key
691 should be added.
692
693 *keyring*, a ``dict``, ``callable`` or ``dns.tsig.Key``, is either
694 the TSIG keyring or key to use.
695
696 The format of a keyring dict is a mapping from TSIG key name, as
697 ``dns.name.Name`` to ``dns.tsig.Key`` or a TSIG secret, a ``bytes``.
698 If a ``dict`` *keyring* is specified but a *keyname* is not, the key
699 used will be the first key in the *keyring*. Note that the order of
700 keys in a dictionary is not defined, so applications should supply a
701 keyname when a ``dict`` keyring is used, unless they know the keyring
702 contains only one key. If a ``callable`` keyring is specified, the
703 callable will be called with the message and the keyname, and is
704 expected to return a key.
705
706 *keyname*, a ``dns.name.Name``, ``str`` or ``None``, the name of
707 this TSIG key to use; defaults to ``None``. If *keyring* is a
708 ``dict``, the key must be defined in it. If *keyring* is a
709 ``dns.tsig.Key``, this is ignored.
710
711 *fudge*, an ``int``, the TSIG time fudge.
712
713 *original_id*, an ``int``, the TSIG original id. If ``None``,
714 the message's id is used.
715
716 *tsig_error*, an ``int``, the TSIG error code.
717
718 *other_data*, a ``bytes``, the TSIG other data.
719
720 *algorithm*, a ``dns.name.Name`` or ``str``, the TSIG algorithm to use. This is
721 only used if *keyring* is a ``dict``, and the key entry is a ``bytes``.
722 """
723
724 if isinstance(keyring, dns.tsig.Key):
725 key = keyring
726 keyname = key.name
727 elif callable(keyring):
728 key = keyring(self, keyname)
729 else:
730 if isinstance(keyname, str):
731 keyname = dns.name.from_text(keyname)
732 if keyname is None:
733 keyname = next(iter(keyring))
734 key = keyring[keyname]
735 if isinstance(key, bytes):
736 key = dns.tsig.Key(keyname, key, algorithm)
737 self.keyring = key
738 if original_id is None:
739 original_id = self.id
740 self.tsig = self._make_tsig(
741 keyname,
742 self.keyring.algorithm,
743 0,
744 fudge,
745 b"\x00" * dns.tsig.mac_sizes[self.keyring.algorithm],
746 original_id,
747 tsig_error,
748 other_data,
749 )
750 self.want_tsig_sign = True
751
752 @property
753 def keyname(self) -> dns.name.Name | None:
754 if self.tsig:
755 return self.tsig.name
756 else:
757 return None
758
759 @property
760 def keyalgorithm(self) -> dns.name.Name | None:
761 if self.tsig:
762 rdata = cast(dns.rdtypes.ANY.TSIG.TSIG, self.tsig[0])
763 return rdata.algorithm
764 else:
765 return None
766
767 @property
768 def mac(self) -> bytes | None:
769 if self.tsig:
770 rdata = cast(dns.rdtypes.ANY.TSIG.TSIG, self.tsig[0])
771 return rdata.mac
772 else:
773 return None
774
775 @property
776 def tsig_error(self) -> int | None:
777 if self.tsig:
778 rdata = cast(dns.rdtypes.ANY.TSIG.TSIG, self.tsig[0])
779 return rdata.error
780 else:
781 return None
782
783 @property
784 def had_tsig(self) -> bool:
785 return bool(self.tsig)
786
787 @staticmethod
788 def _make_opt(flags=0, payload=DEFAULT_EDNS_PAYLOAD, options=None):
789 opt = dns.rdtypes.ANY.OPT.OPT(payload, dns.rdatatype.OPT, options or ())
790 return dns.rrset.from_rdata(dns.name.root, int(flags), opt)
791
792 def use_edns(
793 self,
794 edns: int | bool | None = 0,
795 ednsflags: int = 0,
796 payload: int = DEFAULT_EDNS_PAYLOAD,
797 request_payload: int | None = None,
798 options: List[dns.edns.Option] | None = None,
799 pad: int = 0,
800 ) -> None:
801 """Configure EDNS behavior.
802
803 *edns*, an ``int``, is the EDNS level to use. Specifying ``None``, ``False``,
804 or ``-1`` means "do not use EDNS", and in this case the other parameters are
805 ignored. Specifying ``True`` is equivalent to specifying 0, i.e. "use EDNS0".
806
807 *ednsflags*, an ``int``, the EDNS flag values.
808
809 *payload*, an ``int``, is the EDNS sender's payload field, which is the maximum
810 size of UDP datagram the sender can handle. I.e. how big a response to this
811 message can be.
812
813 *request_payload*, an ``int``, is the EDNS payload size to use when sending this
814 message. If not specified, defaults to the value of *payload*.
815
816 *options*, a list of ``dns.edns.Option`` objects or ``None``, the EDNS options.
817
818 *pad*, a non-negative ``int``. If 0, the default, do not pad; otherwise add
819 padding bytes to make the message size a multiple of *pad*. Note that if
820 padding is non-zero, an EDNS PADDING option will always be added to the
821 message.
822 """
823
824 if edns is None or edns is False:
825 edns = -1
826 elif edns is True:
827 edns = 0
828 if edns < 0:
829 self.opt = None
830 self.request_payload = 0
831 else:
832 # make sure the EDNS version in ednsflags agrees with edns
833 ednsflags &= 0xFF00FFFF
834 ednsflags |= edns << 16
835 if options is None:
836 options = []
837 self.opt = self._make_opt(ednsflags, payload, options)
838 if request_payload is None:
839 request_payload = payload
840 self.request_payload = request_payload
841 if pad < 0:
842 raise ValueError("pad must be non-negative")
843 self.pad = pad
844
845 @property
846 def edns(self) -> int:
847 if self.opt:
848 return (self.ednsflags & 0xFF0000) >> 16
849 else:
850 return -1
851
852 @property
853 def ednsflags(self) -> int:
854 if self.opt:
855 return self.opt.ttl
856 else:
857 return 0
858
859 @ednsflags.setter
860 def ednsflags(self, v):
861 if self.opt:
862 self.opt.ttl = v
863 elif v:
864 self.opt = self._make_opt(v)
865
866 @property
867 def payload(self) -> int:
868 if self.opt:
869 rdata = cast(dns.rdtypes.ANY.OPT.OPT, self.opt[0])
870 return rdata.payload
871 else:
872 return 0
873
874 @property
875 def options(self) -> Tuple:
876 if self.opt:
877 rdata = cast(dns.rdtypes.ANY.OPT.OPT, self.opt[0])
878 return rdata.options
879 else:
880 return ()
881
882 def want_dnssec(self, wanted: bool = True) -> None:
883 """Enable or disable 'DNSSEC desired' flag in requests.
884
885 *wanted*, a ``bool``. If ``True``, then DNSSEC data is
886 desired in the response, EDNS is enabled if required, and then
887 the DO bit is set. If ``False``, the DO bit is cleared if
888 EDNS is enabled.
889 """
890
891 if wanted:
892 self.ednsflags |= dns.flags.DO
893 elif self.opt:
894 self.ednsflags &= ~int(dns.flags.DO)
895
896 def rcode(self) -> dns.rcode.Rcode:
897 """Return the rcode.
898
899 Returns a ``dns.rcode.Rcode``.
900 """
901 return dns.rcode.from_flags(int(self.flags), int(self.ednsflags))
902
903 def set_rcode(self, rcode: dns.rcode.Rcode) -> None:
904 """Set the rcode.
905
906 *rcode*, a ``dns.rcode.Rcode``, is the rcode to set.
907 """
908 (value, evalue) = dns.rcode.to_flags(rcode)
909 self.flags &= 0xFFF0
910 self.flags |= value
911 self.ednsflags &= 0x00FFFFFF
912 self.ednsflags |= evalue
913
914 def opcode(self) -> dns.opcode.Opcode:
915 """Return the opcode.
916
917 Returns a ``dns.opcode.Opcode``.
918 """
919 return dns.opcode.from_flags(int(self.flags))
920
921 def set_opcode(self, opcode: dns.opcode.Opcode) -> None:
922 """Set the opcode.
923
924 *opcode*, a ``dns.opcode.Opcode``, is the opcode to set.
925 """
926 self.flags &= 0x87FF
927 self.flags |= dns.opcode.to_flags(opcode)
928
929 def get_options(self, otype: dns.edns.OptionType) -> List[dns.edns.Option]:
930 """Return the list of options of the specified type."""
931 return [option for option in self.options if option.otype == otype]
932
933 def extended_errors(self) -> List[dns.edns.EDEOption]:
934 """Return the list of Extended DNS Error (EDE) options in the message"""
935 return cast(List[dns.edns.EDEOption], self.get_options(dns.edns.OptionType.EDE))
936
937 def _get_one_rr_per_rrset(self, value):
938 # What the caller picked is fine.
939 return value
940
941 # pylint: disable=unused-argument
942
943 def _parse_rr_header(self, section, name, rdclass, rdtype):
944 return (rdclass, rdtype, None, False)
945
946 # pylint: enable=unused-argument
947
948 def _parse_special_rr_header(self, section, count, position, name, rdclass, rdtype):
949 if rdtype == dns.rdatatype.OPT:
950 if (
951 section != MessageSection.ADDITIONAL
952 or self.opt
953 or name != dns.name.root
954 ):
955 raise BadEDNS
956 elif rdtype == dns.rdatatype.TSIG:
957 if (
958 section != MessageSection.ADDITIONAL
959 or rdclass != dns.rdatatype.ANY
960 or position != count - 1
961 ):
962 raise BadTSIG
963 return (rdclass, rdtype, None, False)
964
965
966 class ChainingResult:
967 """The result of a call to dns.message.QueryMessage.resolve_chaining().
968
969 The ``answer`` attribute is the answer RRSet, or ``None`` if it doesn't
970 exist.
971
972 The ``canonical_name`` attribute is the canonical name after all
973 chaining has been applied (this is the same name as ``rrset.name`` in cases
974 where rrset is not ``None``).
975
976 The ``minimum_ttl`` attribute is the minimum TTL, i.e. the TTL to
977 use if caching the data. It is the smallest of all the CNAME TTLs
978 and either the answer TTL if it exists or the SOA TTL and SOA
979 minimum values for negative answers.
980
981 The ``cnames`` attribute is a list of all the CNAME RRSets followed to
982 get to the canonical name.
983 """
984
985 def __init__(
986 self,
987 canonical_name: dns.name.Name,
988 answer: dns.rrset.RRset | None,
989 minimum_ttl: int,
990 cnames: List[dns.rrset.RRset],
991 ):
992 self.canonical_name = canonical_name
993 self.answer = answer
994 self.minimum_ttl = minimum_ttl
995 self.cnames = cnames
996
997
998 class QueryMessage(Message):
999 def resolve_chaining(self) -> ChainingResult:
1000 """Follow the CNAME chain in the response to determine the answer
1001 RRset.
1002
1003 Raises ``dns.message.NotQueryResponse`` if the message is not
1004 a response.
1005
1006 Raises ``dns.message.ChainTooLong`` if the CNAME chain is too long.
1007
1008 Raises ``dns.message.AnswerForNXDOMAIN`` if the rcode is NXDOMAIN
1009 but an answer was found.
1010
1011 Raises ``dns.exception.FormError`` if the question count is not 1.
1012
1013 Returns a ChainingResult object.
1014 """
1015 if self.flags & dns.flags.QR == 0:
1016 raise NotQueryResponse
1017 if len(self.question) != 1:
1018 raise dns.exception.FormError
1019 question = self.question[0]
1020 qname = question.name
1021 min_ttl = dns.ttl.MAX_TTL
1022 answer = None
1023 count = 0
1024 cnames = []
1025 while count < MAX_CHAIN:
1026 try:
1027 answer = self.find_rrset(
1028 self.answer, qname, question.rdclass, question.rdtype
1029 )
1030 min_ttl = min(min_ttl, answer.ttl)
1031 break
1032 except KeyError:
1033 if question.rdtype != dns.rdatatype.CNAME:
1034 try:
1035 crrset = self.find_rrset(
1036 self.answer, qname, question.rdclass, dns.rdatatype.CNAME
1037 )
1038 cnames.append(crrset)
1039 min_ttl = min(min_ttl, crrset.ttl)
1040 for rd in crrset:
1041 qname = rd.target
1042 break
1043 count += 1
1044 continue
1045 except KeyError:
1046 # Exit the chaining loop
1047 break
1048 else:
1049 # Exit the chaining loop
1050 break
1051 if count >= MAX_CHAIN:
1052 raise ChainTooLong
1053 if self.rcode() == dns.rcode.NXDOMAIN and answer is not None:
1054 raise AnswerForNXDOMAIN
1055 if answer is None:
1056 # Further minimize the TTL with NCACHE.
1057 auname = qname
1058 while True:
1059 # Look for an SOA RR whose owner name is a superdomain
1060 # of qname.
1061 try:
1062 srrset = self.find_rrset(
1063 self.authority, auname, question.rdclass, dns.rdatatype.SOA
1064 )
1065 srdata = cast(dns.rdtypes.ANY.SOA.SOA, srrset[0])
1066 min_ttl = min(min_ttl, srrset.ttl, srdata.minimum)
1067 break
1068 except KeyError:
1069 try:
1070 auname = auname.parent()
1071 except dns.name.NoParent:
1072 break
1073 return ChainingResult(qname, answer, min_ttl, cnames)
1074
1075 def canonical_name(self) -> dns.name.Name:
1076 """Return the canonical name of the first name in the question
1077 section.
1078
1079 Raises ``dns.message.NotQueryResponse`` if the message is not
1080 a response.
1081
1082 Raises ``dns.message.ChainTooLong`` if the CNAME chain is too long.
1083
1084 Raises ``dns.message.AnswerForNXDOMAIN`` if the rcode is NXDOMAIN
1085 but an answer was found.
1086
1087 Raises ``dns.exception.FormError`` if the question count is not 1.
1088 """
1089 return self.resolve_chaining().canonical_name
1090
1091
1092 def _maybe_import_update():
1093 # We avoid circular imports by doing this here. We do it in another
1094 # function as doing it in _message_factory_from_opcode() makes "dns"
1095 # a local symbol, and the first line fails :)
1096
1097 # pylint: disable=redefined-outer-name,import-outside-toplevel,unused-import
1098 import dns.update # noqa: F401
1099
1100
1101 def _message_factory_from_opcode(opcode):
1102 if opcode == dns.opcode.QUERY:
1103 return QueryMessage
1104 elif opcode == dns.opcode.UPDATE:
1105 _maybe_import_update()
1106 return dns.update.UpdateMessage # pyright: ignore
1107 else:
1108 return Message
1109
1110
1111 class _WireReader:
1112 """Wire format reader.
1113
1114 parser: the binary parser
1115 message: The message object being built
1116 initialize_message: Callback to set message parsing options
1117 question_only: Are we only reading the question?
1118 one_rr_per_rrset: Put each RR into its own RRset?
1119 keyring: TSIG keyring
1120 ignore_trailing: Ignore trailing junk at end of request?
1121 multi: Is this message part of a multi-message sequence?
1122 DNS dynamic updates.
1123 continue_on_error: try to extract as much information as possible from
1124 the message, accumulating MessageErrors in the *errors* attribute instead of
1125 raising them.
1126 """
1127
1128 def __init__(
1129 self,
1130 wire,
1131 initialize_message,
1132 question_only=False,
1133 one_rr_per_rrset=False,
1134 ignore_trailing=False,
1135 keyring=None,
1136 multi=False,
1137 continue_on_error=False,
1138 ):
1139 self.parser = dns.wire.Parser(wire)
1140 self.message = None
1141 self.initialize_message = initialize_message
1142 self.question_only = question_only
1143 self.one_rr_per_rrset = one_rr_per_rrset
1144 self.ignore_trailing = ignore_trailing
1145 self.keyring = keyring
1146 self.multi = multi
1147 self.continue_on_error = continue_on_error
1148 self.errors = []
1149
1150 def _get_question(self, section_number, qcount):
1151 """Read the next *qcount* records from the wire data and add them to
1152 the question section.
1153 """
1154 assert self.message is not None
1155 section = self.message.sections[section_number]
1156 for _ in range(qcount):
1157 qname = self.parser.get_name(self.message.origin)
1158 (rdtype, rdclass) = self.parser.get_struct("!HH")
1159 (rdclass, rdtype, _, _) = self.message._parse_rr_header(
1160 section_number, qname, rdclass, rdtype
1161 )
1162 self.message.find_rrset(
1163 section, qname, rdclass, rdtype, create=True, force_unique=True
1164 )
1165
1166 def _add_error(self, e):
1167 self.errors.append(MessageError(e, self.parser.current))
1168
1169 def _get_section(self, section_number, count):
1170 """Read the next I{count} records from the wire data and add them to
1171 the specified section.
1172
1173 section_number: the section of the message to which to add records
1174 count: the number of records to read
1175 """
1176 assert self.message is not None
1177 section = self.message.sections[section_number]
1178 force_unique = self.one_rr_per_rrset
1179 for i in range(count):
1180 rr_start = self.parser.current
1181 absolute_name = self.parser.get_name()
1182 if self.message.origin is not None:
1183 name = absolute_name.relativize(self.message.origin)
1184 else:
1185 name = absolute_name
1186 (rdtype, rdclass, ttl, rdlen) = self.parser.get_struct("!HHIH")
1187 if rdtype in (dns.rdatatype.OPT, dns.rdatatype.TSIG):
1188 (
1189 rdclass,
1190 rdtype,
1191 deleting,
1192 empty,
1193 ) = self.message._parse_special_rr_header(
1194 section_number, count, i, name, rdclass, rdtype
1195 )
1196 else:
1197 (rdclass, rdtype, deleting, empty) = self.message._parse_rr_header(
1198 section_number, name, rdclass, rdtype
1199 )
1200 rdata_start = self.parser.current
1201 try:
1202 if empty:
1203 if rdlen > 0:
1204 raise dns.exception.FormError
1205 rd = None
1206 covers = dns.rdatatype.NONE
1207 else:
1208 with self.parser.restrict_to(rdlen):
1209 rd = dns.rdata.from_wire_parser(
1210 rdclass, # pyright: ignore
1211 rdtype,
1212 self.parser,
1213 self.message.origin,
1214 )
1215 covers = rd.covers()
1216 if self.message.xfr and rdtype == dns.rdatatype.SOA:
1217 force_unique = True
1218 if rdtype == dns.rdatatype.OPT:
1219 self.message.opt = dns.rrset.from_rdata(name, ttl, rd)
1220 elif rdtype == dns.rdatatype.TSIG:
1221 trd = cast(dns.rdtypes.ANY.TSIG.TSIG, rd)
1222 if self.keyring is None or self.keyring is True:
1223 raise UnknownTSIGKey("got signed message without keyring")
1224 elif isinstance(self.keyring, dict):
1225 key = self.keyring.get(absolute_name)
1226 if isinstance(key, bytes):
1227 key = dns.tsig.Key(absolute_name, key, trd.algorithm)
1228 elif callable(self.keyring):
1229 key = self.keyring(self.message, absolute_name)
1230 else:
1231 key = self.keyring
1232 if key is None:
1233 raise UnknownTSIGKey(f"key '{name}' unknown")
1234 if key:
1235 self.message.keyring = key
1236 self.message.tsig_ctx = dns.tsig.validate(
1237 self.parser.wire,
1238 key,
1239 absolute_name,
1240 rd,
1241 int(time.time()),
1242 self.message.request_mac,
1243 rr_start,
1244 self.message.tsig_ctx,
1245 self.multi,
1246 )
1247 self.message.tsig = dns.rrset.from_rdata(absolute_name, 0, rd)
1248 else:
1249 rrset = self.message.find_rrset(
1250 section,
1251 name,
1252 rdclass, # pyright: ignore
1253 rdtype,
1254 covers,
1255 deleting,
1256 True,
1257 force_unique,
1258 )
1259 if rd is not None:
1260 if ttl > 0x7FFFFFFF:
1261 ttl = 0
1262 rrset.add(rd, ttl)
1263 except Exception as e:
1264 if self.continue_on_error:
1265 self._add_error(e)
1266 self.parser.seek(rdata_start + rdlen)
1267 else:
1268 raise
1269
1270 def read(self):
1271 """Read a wire format DNS message and build a dns.message.Message
1272 object."""
1273
1274 if self.parser.remaining() < 12:
1275 raise ShortHeader
1276 (id, flags, qcount, ancount, aucount, adcount) = self.parser.get_struct(
1277 "!HHHHHH"
1278 )
1279 factory = _message_factory_from_opcode(dns.opcode.from_flags(flags))
1280 self.message = factory(id=id)
1281 self.message.flags = dns.flags.Flag(flags)
1282 self.message.wire = self.parser.wire
1283 self.initialize_message(self.message)
1284 self.one_rr_per_rrset = self.message._get_one_rr_per_rrset(
1285 self.one_rr_per_rrset
1286 )
1287 try:
1288 self._get_question(MessageSection.QUESTION, qcount)
1289 if self.question_only:
1290 return self.message
1291 self._get_section(MessageSection.ANSWER, ancount)
1292 self._get_section(MessageSection.AUTHORITY, aucount)
1293 self._get_section(MessageSection.ADDITIONAL, adcount)
1294 if not self.ignore_trailing and self.parser.remaining() != 0:
1295 raise TrailingJunk
1296 if self.multi and self.message.tsig_ctx and not self.message.had_tsig:
1297 self.message.tsig_ctx.update(self.parser.wire)
1298 except Exception as e:
1299 if self.continue_on_error:
1300 self._add_error(e)
1301 else:
1302 raise
1303 return self.message
1304
1305
1306 def from_wire(
1307 wire: bytes,
1308 keyring: Any | None = None,
1309 request_mac: bytes | None = b"",
1310 xfr: bool = False,
1311 origin: dns.name.Name | None = None,
1312 tsig_ctx: dns.tsig.HMACTSig | dns.tsig.GSSTSig | None = None,
1313 multi: bool = False,
1314 question_only: bool = False,
1315 one_rr_per_rrset: bool = False,
1316 ignore_trailing: bool = False,
1317 raise_on_truncation: bool = False,
1318 continue_on_error: bool = False,
1319 ) -> Message:
1320 """Convert a DNS wire format message into a message object.
1321
1322 *keyring*, a ``dns.tsig.Key``, ``dict``, ``bool``, or ``None``, the key or keyring
1323 to use if the message is signed. If ``None`` or ``True``, then trying to decode
1324 a message with a TSIG will fail as it cannot be validated. If ``False``, then
1325 TSIG validation is disabled.
1326
1327 *request_mac*, a ``bytes`` or ``None``. If the message is a response to a
1328 TSIG-signed request, *request_mac* should be set to the MAC of that request.
1329
1330 *xfr*, a ``bool``, should be set to ``True`` if this message is part of a zone
1331 transfer.
1332
1333 *origin*, a ``dns.name.Name`` or ``None``. If the message is part of a zone
1334 transfer, *origin* should be the origin name of the zone. If not ``None``, names
1335 will be relativized to the origin.
1336
1337 *tsig_ctx*, a ``dns.tsig.HMACTSig`` or ``dns.tsig.GSSTSig`` object, the ongoing TSIG
1338 context, used when validating zone transfers.
1339
1340 *multi*, a ``bool``, should be set to ``True`` if this message is part of a multiple
1341 message sequence.
1342
1343 *question_only*, a ``bool``. If ``True``, read only up to the end of the question
1344 section.
1345
1346 *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own RRset.
1347
1348 *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of the
1349 message.
1350
1351 *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if the TC bit is
1352 set.
1353
1354 *continue_on_error*, a ``bool``. If ``True``, try to continue parsing even if
1355 errors occur. Erroneous rdata will be ignored. Errors will be accumulated as a
1356 list of MessageError objects in the message's ``errors`` attribute. This option is
1357 recommended only for DNS analysis tools, or for use in a server as part of an error
1358 handling path. The default is ``False``.
1359
1360 Raises ``dns.message.ShortHeader`` if the message is less than 12 octets long.
1361
1362 Raises ``dns.message.TrailingJunk`` if there were octets in the message past the end
1363 of the proper DNS message, and *ignore_trailing* is ``False``.
1364
1365 Raises ``dns.message.BadEDNS`` if an OPT record was in the wrong section, or
1366 occurred more than once.
1367
1368 Raises ``dns.message.BadTSIG`` if a TSIG record was not the last record of the
1369 additional data section.
1370
1371 Raises ``dns.message.Truncated`` if the TC flag is set and *raise_on_truncation* is
1372 ``True``.
1373
1374 Returns a ``dns.message.Message``.
1375 """
1376
1377 # We permit None for request_mac solely for backwards compatibility
1378 if request_mac is None:
1379 request_mac = b""
1380
1381 def initialize_message(message):
1382 message.request_mac = request_mac
1383 message.xfr = xfr
1384 message.origin = origin
1385 message.tsig_ctx = tsig_ctx
1386
1387 reader = _WireReader(
1388 wire,
1389 initialize_message,
1390 question_only,
1391 one_rr_per_rrset,
1392 ignore_trailing,
1393 keyring,
1394 multi,
1395 continue_on_error,
1396 )
1397 try:
1398 m = reader.read()
1399 except dns.exception.FormError:
1400 if (
1401 reader.message
1402 and (reader.message.flags & dns.flags.TC)
1403 and raise_on_truncation
1404 ):
1405 raise Truncated(message=reader.message)
1406 else:
1407 raise
1408 # Reading a truncated message might not have any errors, so we
1409 # have to do this check here too.
1410 if m.flags & dns.flags.TC and raise_on_truncation:
1411 raise Truncated(message=m)
1412 if continue_on_error:
1413 m.errors = reader.errors
1414
1415 return m
1416
1417
1418 class _TextReader:
1419 """Text format reader.
1420
1421 tok: the tokenizer.
1422 message: The message object being built.
1423 DNS dynamic updates.
1424 last_name: The most recently read name when building a message object.
1425 one_rr_per_rrset: Put each RR into its own RRset?
1426 origin: The origin for relative names
1427 relativize: relativize names?
1428 relativize_to: the origin to relativize to.
1429 """
1430
1431 def __init__(
1432 self,
1433 text: str,
1434 idna_codec: dns.name.IDNACodec | None,
1435 one_rr_per_rrset: bool = False,
1436 origin: dns.name.Name | None = None,
1437 relativize: bool = True,
1438 relativize_to: dns.name.Name | None = None,
1439 ):
1440 self.message: Message | None = None # mypy: ignore
1441 self.tok = dns.tokenizer.Tokenizer(text, idna_codec=idna_codec)
1442 self.last_name = None
1443 self.one_rr_per_rrset = one_rr_per_rrset
1444 self.origin = origin
1445 self.relativize = relativize
1446 self.relativize_to = relativize_to
1447 self.id = None
1448 self.edns = -1
1449 self.ednsflags = 0
1450 self.payload = DEFAULT_EDNS_PAYLOAD
1451 self.rcode = None
1452 self.opcode = dns.opcode.QUERY
1453 self.flags = 0
1454
1455 def _header_line(self, _):
1456 """Process one line from the text format header section."""
1457
1458 token = self.tok.get()
1459 what = token.value
1460 if what == "id":
1461 self.id = self.tok.get_int()
1462 elif what == "flags":
1463 while True:
1464 token = self.tok.get()
1465 if not token.is_identifier():
1466 self.tok.unget(token)
1467 break
1468 self.flags = self.flags | dns.flags.from_text(token.value)
1469 elif what == "edns":
1470 self.edns = self.tok.get_int()
1471 self.ednsflags = self.ednsflags | (self.edns << 16)
1472 elif what == "eflags":
1473 if self.edns < 0:
1474 self.edns = 0
1475 while True:
1476 token = self.tok.get()
1477 if not token.is_identifier():
1478 self.tok.unget(token)
1479 break
1480 self.ednsflags = self.ednsflags | dns.flags.edns_from_text(token.value)
1481 elif what == "payload":
1482 self.payload = self.tok.get_int()
1483 if self.edns < 0:
1484 self.edns = 0
1485 elif what == "opcode":
1486 text = self.tok.get_string()
1487 self.opcode = dns.opcode.from_text(text)
1488 self.flags = self.flags | dns.opcode.to_flags(self.opcode)
1489 elif what == "rcode":
1490 text = self.tok.get_string()
1491 self.rcode = dns.rcode.from_text(text)
1492 else:
1493 raise UnknownHeaderField
1494 self.tok.get_eol()
1495
1496 def _question_line(self, section_number):
1497 """Process one line from the text format question section."""
1498
1499 assert self.message is not None
1500 section = self.message.sections[section_number]
1501 token = self.tok.get(want_leading=True)
1502 if not token.is_whitespace():
1503 self.last_name = self.tok.as_name(
1504 token, self.message.origin, self.relativize, self.relativize_to
1505 )
1506 name = self.last_name
1507 if name is None:
1508 raise NoPreviousName
1509 token = self.tok.get()
1510 if not token.is_identifier():
1511 raise dns.exception.SyntaxError
1512 # Class
1513 try:
1514 rdclass = dns.rdataclass.from_text(token.value)
1515 token = self.tok.get()
1516 if not token.is_identifier():
1517 raise dns.exception.SyntaxError
1518 except dns.exception.SyntaxError:
1519 raise dns.exception.SyntaxError
1520 except Exception:
1521 rdclass = dns.rdataclass.IN
1522 # Type
1523 rdtype = dns.rdatatype.from_text(token.value)
1524 (rdclass, rdtype, _, _) = self.message._parse_rr_header(
1525 section_number, name, rdclass, rdtype
1526 )
1527 self.message.find_rrset(
1528 section, name, rdclass, rdtype, create=True, force_unique=True
1529 )
1530 self.tok.get_eol()
1531
1532 def _rr_line(self, section_number):
1533 """Process one line from the text format answer, authority, or
1534 additional data sections.
1535 """
1536
1537 assert self.message is not None
1538 section = self.message.sections[section_number]
1539 # Name
1540 token = self.tok.get(want_leading=True)
1541 if not token.is_whitespace():
1542 self.last_name = self.tok.as_name(
1543 token, self.message.origin, self.relativize, self.relativize_to
1544 )
1545 name = self.last_name
1546 if name is None:
1547 raise NoPreviousName
1548 token = self.tok.get()
1549 if not token.is_identifier():
1550 raise dns.exception.SyntaxError
1551 # TTL
1552 try:
1553 ttl = int(token.value, 0)
1554 token = self.tok.get()
1555 if not token.is_identifier():
1556 raise dns.exception.SyntaxError
1557 except dns.exception.SyntaxError:
1558 raise dns.exception.SyntaxError
1559 except Exception:
1560 ttl = 0
1561 # Class
1562 try:
1563 rdclass = dns.rdataclass.from_text(token.value)
1564 token = self.tok.get()
1565 if not token.is_identifier():
1566 raise dns.exception.SyntaxError
1567 except dns.exception.SyntaxError:
1568 raise dns.exception.SyntaxError
1569 except Exception:
1570 rdclass = dns.rdataclass.IN
1571 # Type
1572 rdtype = dns.rdatatype.from_text(token.value)
1573 (rdclass, rdtype, deleting, empty) = self.message._parse_rr_header(
1574 section_number, name, rdclass, rdtype
1575 )
1576 token = self.tok.get()
1577 if empty and not token.is_eol_or_eof():
1578 raise dns.exception.SyntaxError
1579 if not empty and token.is_eol_or_eof():
1580 raise dns.exception.UnexpectedEnd
1581 if not token.is_eol_or_eof():
1582 self.tok.unget(token)
1583 rd = dns.rdata.from_text(
1584 rdclass,
1585 rdtype,
1586 self.tok,
1587 self.message.origin,
1588 self.relativize,
1589 self.relativize_to,
1590 )
1591 covers = rd.covers()
1592 else:
1593 rd = None
1594 covers = dns.rdatatype.NONE
1595 rrset = self.message.find_rrset(
1596 section,
1597 name,
1598 rdclass,
1599 rdtype,
1600 covers,
1601 deleting,
1602 True,
1603 self.one_rr_per_rrset,
1604 )
1605 if rd is not None:
1606 rrset.add(rd, ttl)
1607
1608 def _make_message(self):
1609 factory = _message_factory_from_opcode(self.opcode)
1610 message = factory(id=self.id)
1611 message.flags = self.flags
1612 if self.edns >= 0:
1613 message.use_edns(self.edns, self.ednsflags, self.payload)
1614 if self.rcode:
1615 message.set_rcode(self.rcode)
1616 if self.origin:
1617 message.origin = self.origin
1618 return message
1619
1620 def read(self):
1621 """Read a text format DNS message and build a dns.message.Message
1622 object."""
1623
1624 line_method = self._header_line
1625 section_number = None
1626 while 1:
1627 token = self.tok.get(True, True)
1628 if token.is_eol_or_eof():
1629 break
1630 if token.is_comment():
1631 u = token.value.upper()
1632 if u == "HEADER":
1633 line_method = self._header_line
1634
1635 if self.message:
1636 message = self.message
1637 else:
1638 # If we don't have a message, create one with the current
1639 # opcode, so that we know which section names to parse.
1640 message = self._make_message()
1641 try:
1642 section_number = message._section_enum.from_text(u)
1643 # We found a section name. If we don't have a message,
1644 # use the one we just created.
1645 if not self.message:
1646 self.message = message
1647 self.one_rr_per_rrset = message._get_one_rr_per_rrset(
1648 self.one_rr_per_rrset
1649 )
1650 if section_number == MessageSection.QUESTION:
1651 line_method = self._question_line
1652 else:
1653 line_method = self._rr_line
1654 except Exception:
1655 # It's just a comment.
1656 pass
1657 self.tok.get_eol()
1658 continue
1659 self.tok.unget(token)
1660 line_method(section_number)
1661 if not self.message:
1662 self.message = self._make_message()
1663 return self.message
1664
1665
1666 def from_text(
1667 text: str,
1668 idna_codec: dns.name.IDNACodec | None = None,
1669 one_rr_per_rrset: bool = False,
1670 origin: dns.name.Name | None = None,
1671 relativize: bool = True,
1672 relativize_to: dns.name.Name | None = None,
1673 ) -> Message:
1674 """Convert the text format message into a message object.
1675
1676 The reader stops after reading the first blank line in the input to
1677 facilitate reading multiple messages from a single file with
1678 ``dns.message.from_file()``.
1679
1680 *text*, a ``str``, the text format message.
1681
1682 *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
1683 encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
1684 is used.
1685
1686 *one_rr_per_rrset*, a ``bool``. If ``True``, then each RR is put
1687 into its own rrset. The default is ``False``.
1688
1689 *origin*, a ``dns.name.Name`` (or ``None``), the
1690 origin to use for relative names.
1691
1692 *relativize*, a ``bool``. If true, name will be relativized.
1693
1694 *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use
1695 when relativizing names. If not set, the *origin* value will be used.
1696
1697 Raises ``dns.message.UnknownHeaderField`` if a header is unknown.
1698
1699 Raises ``dns.exception.SyntaxError`` if the text is badly formed.
1700
1701 Returns a ``dns.message.Message object``
1702 """
1703
1704 # 'text' can also be a file, but we don't publish that fact
1705 # since it's an implementation detail. The official file
1706 # interface is from_file().
1707
1708 reader = _TextReader(
1709 text, idna_codec, one_rr_per_rrset, origin, relativize, relativize_to
1710 )
1711 return reader.read()
1712
1713
1714 def from_file(
1715 f: Any,
1716 idna_codec: dns.name.IDNACodec | None = None,
1717 one_rr_per_rrset: bool = False,
1718 ) -> Message:
1719 """Read the next text format message from the specified file.
1720
1721 Message blocks are separated by a single blank line.
1722
1723 *f*, a ``file`` or ``str``. If *f* is text, it is treated as the
1724 pathname of a file to open.
1725
1726 *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
1727 encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
1728 is used.
1729
1730 *one_rr_per_rrset*, a ``bool``. If ``True``, then each RR is put
1731 into its own rrset. The default is ``False``.
1732
1733 Raises ``dns.message.UnknownHeaderField`` if a header is unknown.
1734
1735 Raises ``dns.exception.SyntaxError`` if the text is badly formed.
1736
1737 Returns a ``dns.message.Message object``
1738 """
1739
1740 if isinstance(f, str):
1741 cm: contextlib.AbstractContextManager = open(f, encoding="utf-8")
1742 else:
1743 cm = contextlib.nullcontext(f)
1744 with cm as f:
1745 return from_text(f, idna_codec, one_rr_per_rrset)
1746 assert False # for mypy lgtm[py/unreachable-statement]
1747
1748
1749 def make_query(
1750 qname: dns.name.Name | str,
1751 rdtype: dns.rdatatype.RdataType | str,
1752 rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN,
1753 use_edns: int | bool | None = None,
1754 want_dnssec: bool = False,
1755 ednsflags: int | None = None,
1756 payload: int | None = None,
1757 request_payload: int | None = None,
1758 options: List[dns.edns.Option] | None = None,
1759 idna_codec: dns.name.IDNACodec | None = None,
1760 id: int | None = None,
1761 flags: int = dns.flags.RD,
1762 pad: int = 0,
1763 ) -> QueryMessage:
1764 """Make a query message.
1765
1766 The query name, type, and class may all be specified either
1767 as objects of the appropriate type, or as strings.
1768
1769 The query will have a randomly chosen query id, and its DNS flags
1770 will be set to dns.flags.RD.
1771
1772 qname, a ``dns.name.Name`` or ``str``, the query name.
1773
1774 *rdtype*, an ``int`` or ``str``, the desired rdata type.
1775
1776 *rdclass*, an ``int`` or ``str``, the desired rdata class; the default
1777 is class IN.
1778
1779 *use_edns*, an ``int``, ``bool`` or ``None``. The EDNS level to use; the
1780 default is ``None``. If ``None``, EDNS will be enabled only if other
1781 parameters (*ednsflags*, *payload*, *request_payload*, or *options*) are
1782 set.
1783 See the description of dns.message.Message.use_edns() for the possible
1784 values for use_edns and their meanings.
1785
1786 *want_dnssec*, a ``bool``. If ``True``, DNSSEC data is desired.
1787
1788 *ednsflags*, an ``int``, the EDNS flag values.
1789
1790 *payload*, an ``int``, is the EDNS sender's payload field, which is the
1791 maximum size of UDP datagram the sender can handle. I.e. how big
1792 a response to this message can be.
1793
1794 *request_payload*, an ``int``, is the EDNS payload size to use when
1795 sending this message. If not specified, defaults to the value of
1796 *payload*.
1797
1798 *options*, a list of ``dns.edns.Option`` objects or ``None``, the EDNS
1799 options.
1800
1801 *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
1802 encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
1803 is used.
1804
1805 *id*, an ``int`` or ``None``, the desired query id. The default is
1806 ``None``, which generates a random query id.
1807
1808 *flags*, an ``int``, the desired query flags. The default is
1809 ``dns.flags.RD``.
1810
1811 *pad*, a non-negative ``int``. If 0, the default, do not pad; otherwise add
1812 padding bytes to make the message size a multiple of *pad*. Note that if
1813 padding is non-zero, an EDNS PADDING option will always be added to the
1814 message.
1815
1816 Returns a ``dns.message.QueryMessage``
1817 """
1818
1819 if isinstance(qname, str):
1820 qname = dns.name.from_text(qname, idna_codec=idna_codec)
1821 rdtype = dns.rdatatype.RdataType.make(rdtype)
1822 rdclass = dns.rdataclass.RdataClass.make(rdclass)
1823 m = QueryMessage(id=id)
1824 m.flags = dns.flags.Flag(flags)
1825 m.find_rrset(m.question, qname, rdclass, rdtype, create=True, force_unique=True)
1826 # only pass keywords on to use_edns if they have been set to a
1827 # non-None value. Setting a field will turn EDNS on if it hasn't
1828 # been configured.
1829 kwargs: Dict[str, Any] = {}
1830 if ednsflags is not None:
1831 kwargs["ednsflags"] = ednsflags
1832 if payload is not None:
1833 kwargs["payload"] = payload
1834 if request_payload is not None:
1835 kwargs["request_payload"] = request_payload
1836 if options is not None:
1837 kwargs["options"] = options
1838 if kwargs and use_edns is None:
1839 use_edns = 0
1840 kwargs["edns"] = use_edns
1841 kwargs["pad"] = pad
1842 m.use_edns(**kwargs)
1843 if want_dnssec:
1844 m.want_dnssec(want_dnssec)
1845 return m
1846
1847
1848 class CopyMode(enum.Enum):
1849 """
1850 How should sections be copied when making an update response?
1851 """
1852
1853 NOTHING = 0
1854 QUESTION = 1
1855 EVERYTHING = 2
1856
1857
1858 def make_response(
1859 query: Message,
1860 recursion_available: bool = False,
1861 our_payload: int = 8192,
1862 fudge: int = 300,
1863 tsig_error: int = 0,
1864 pad: int | None = None,
1865 copy_mode: CopyMode | None = None,
1866 ) -> Message:
1867 """Make a message which is a response for the specified query.
1868 The message returned is really a response skeleton; it has all of the infrastructure
1869 required of a response, but none of the content.
1870
1871 Response section(s) which are copied are shallow copies of the matching section(s)
1872 in the query, so the query's RRsets should not be changed.
1873
1874 *query*, a ``dns.message.Message``, the query to respond to.
1875
1876 *recursion_available*, a ``bool``, should RA be set in the response?
1877
1878 *our_payload*, an ``int``, the payload size to advertise in EDNS responses.
1879
1880 *fudge*, an ``int``, the TSIG time fudge.
1881
1882 *tsig_error*, an ``int``, the TSIG error.
1883
1884 *pad*, a non-negative ``int`` or ``None``. If 0, the default, do not pad; otherwise
1885 if not ``None`` add padding bytes to make the message size a multiple of *pad*. Note
1886 that if padding is non-zero, an EDNS PADDING option will always be added to the
1887 message. If ``None``, add padding following RFC 8467, namely if the request is
1888 padded, pad the response to 468 otherwise do not pad.
1889
1890 *copy_mode*, a ``dns.message.CopyMode`` or ``None``, determines how sections are
1891 copied. The default, ``None`` copies sections according to the default for the
1892 message's opcode, which is currently ``dns.message.CopyMode.QUESTION`` for all
1893 opcodes. ``dns.message.CopyMode.QUESTION`` copies only the question section.
1894 ``dns.message.CopyMode.EVERYTHING`` copies all sections other than OPT or TSIG
1895 records, which are created appropriately if needed. ``dns.message.CopyMode.NOTHING``
1896 copies no sections; note that this mode is for server testing purposes and is
1897 otherwise not recommended for use. In particular, ``dns.message.is_response()``
1898 will be ``False`` if you create a response this way and the rcode is not
1899 ``FORMERR``, ``SERVFAIL``, ``NOTIMP``, or ``REFUSED``.
1900
1901 Returns a ``dns.message.Message`` object whose specific class is appropriate for the
1902 query. For example, if query is a ``dns.update.UpdateMessage``, the response will
1903 be one too.
1904 """
1905
1906 if query.flags & dns.flags.QR:
1907 raise dns.exception.FormError("specified query message is not a query")
1908 opcode = query.opcode()
1909 factory = _message_factory_from_opcode(opcode)
1910 response = factory(id=query.id)
1911 response.flags = dns.flags.QR | (query.flags & dns.flags.RD)
1912 if recursion_available:
1913 response.flags |= dns.flags.RA
1914 response.set_opcode(opcode)
1915 if copy_mode is None:
1916 copy_mode = CopyMode.QUESTION
1917 if copy_mode != CopyMode.NOTHING:
1918 response.question = list(query.question)
1919 if copy_mode == CopyMode.EVERYTHING:
1920 response.answer = list(query.answer)
1921 response.authority = list(query.authority)
1922 response.additional = list(query.additional)
1923 if query.edns >= 0:
1924 if pad is None:
1925 # Set response padding per RFC 8467
1926 pad = 0
1927 for option in query.options:
1928 if option.otype == dns.edns.OptionType.PADDING:
1929 pad = 468
1930 response.use_edns(0, 0, our_payload, query.payload, pad=pad)
1931 if query.had_tsig and query.keyring:
1932 assert query.mac is not None
1933 assert query.keyalgorithm is not None
1934 response.use_tsig(
1935 query.keyring,
1936 query.keyname,
1937 fudge,
1938 None,
1939 tsig_error,
1940 b"",
1941 query.keyalgorithm,
1942 )
1943 response.request_mac = query.mac
1944 return response
1945
1946
1947 ### BEGIN generated MessageSection constants
1948
1949 QUESTION = MessageSection.QUESTION
1950 ANSWER = MessageSection.ANSWER
1951 AUTHORITY = MessageSection.AUTHORITY
1952 ADDITIONAL = MessageSection.ADDITIONAL
1953
1954 ### END generated MessageSection constants