message.py 67 KB

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