renderer.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. """Help for building DNS wire format messages"""
  17. import contextlib
  18. import io
  19. import random
  20. import struct
  21. import time
  22. import dns.edns
  23. import dns.exception
  24. import dns.rdataclass
  25. import dns.rdatatype
  26. import dns.tsig
  27. # Note we can't import dns.message for cicularity reasons
  28. QUESTION = 0
  29. ANSWER = 1
  30. AUTHORITY = 2
  31. ADDITIONAL = 3
  32. @contextlib.contextmanager
  33. def prefixed_length(output, length_length):
  34. output.write(b"\00" * length_length)
  35. start = output.tell()
  36. yield
  37. end = output.tell()
  38. length = end - start
  39. if length > 0:
  40. try:
  41. output.seek(start - length_length)
  42. try:
  43. output.write(length.to_bytes(length_length, "big"))
  44. except OverflowError:
  45. raise dns.exception.FormError
  46. finally:
  47. output.seek(end)
  48. class Renderer:
  49. """Helper class for building DNS wire-format messages.
  50. Most applications can use the higher-level L{dns.message.Message}
  51. class and its to_wire() method to generate wire-format messages.
  52. This class is for those applications which need finer control
  53. over the generation of messages.
  54. Typical use::
  55. r = dns.renderer.Renderer(id=1, flags=0x80, max_size=512)
  56. r.add_question(qname, qtype, qclass)
  57. r.add_rrset(dns.renderer.ANSWER, rrset_1)
  58. r.add_rrset(dns.renderer.ANSWER, rrset_2)
  59. r.add_rrset(dns.renderer.AUTHORITY, ns_rrset)
  60. r.add_rrset(dns.renderer.ADDITIONAL, ad_rrset_1)
  61. r.add_rrset(dns.renderer.ADDITIONAL, ad_rrset_2)
  62. r.add_edns(0, 0, 4096)
  63. r.write_header()
  64. r.add_tsig(keyname, secret, 300, 1, 0, '', request_mac)
  65. wire = r.get_wire()
  66. If padding is going to be used, then the OPT record MUST be
  67. written after everything else in the additional section except for
  68. the TSIG (if any).
  69. output, an io.BytesIO, where rendering is written
  70. id: the message id
  71. flags: the message flags
  72. max_size: the maximum size of the message
  73. origin: the origin to use when rendering relative names
  74. compress: the compression table
  75. section: an int, the section currently being rendered
  76. counts: list of the number of RRs in each section
  77. mac: the MAC of the rendered message (if TSIG was used)
  78. """
  79. def __init__(self, id=None, flags=0, max_size=65535, origin=None):
  80. """Initialize a new renderer."""
  81. self.output = io.BytesIO()
  82. if id is None:
  83. self.id = random.randint(0, 65535)
  84. else:
  85. self.id = id
  86. self.flags = flags
  87. self.max_size = max_size
  88. self.origin = origin
  89. self.compress = {}
  90. self.section = QUESTION
  91. self.counts = [0, 0, 0, 0]
  92. self.output.write(b"\x00" * 12)
  93. self.mac = ""
  94. self.reserved = 0
  95. self.was_padded = False
  96. def _rollback(self, where):
  97. """Truncate the output buffer at offset *where*, and remove any
  98. compression table entries that pointed beyond the truncation
  99. point.
  100. """
  101. self.output.seek(where)
  102. self.output.truncate()
  103. keys_to_delete = []
  104. for k, v in self.compress.items():
  105. if v >= where:
  106. keys_to_delete.append(k)
  107. for k in keys_to_delete:
  108. del self.compress[k]
  109. def _set_section(self, section):
  110. """Set the renderer's current section.
  111. Sections must be rendered order: QUESTION, ANSWER, AUTHORITY,
  112. ADDITIONAL. Sections may be empty.
  113. Raises dns.exception.FormError if an attempt was made to set
  114. a section value less than the current section.
  115. """
  116. if self.section != section:
  117. if self.section > section:
  118. raise dns.exception.FormError
  119. self.section = section
  120. @contextlib.contextmanager
  121. def _track_size(self):
  122. start = self.output.tell()
  123. yield start
  124. if self.output.tell() > self.max_size:
  125. self._rollback(start)
  126. raise dns.exception.TooBig
  127. @contextlib.contextmanager
  128. def _temporarily_seek_to(self, where):
  129. current = self.output.tell()
  130. try:
  131. self.output.seek(where)
  132. yield
  133. finally:
  134. self.output.seek(current)
  135. def add_question(self, qname, rdtype, rdclass=dns.rdataclass.IN):
  136. """Add a question to the message."""
  137. self._set_section(QUESTION)
  138. with self._track_size():
  139. qname.to_wire(self.output, self.compress, self.origin)
  140. self.output.write(struct.pack("!HH", rdtype, rdclass))
  141. self.counts[QUESTION] += 1
  142. def add_rrset(self, section, rrset, **kw):
  143. """Add the rrset to the specified section.
  144. Any keyword arguments are passed on to the rdataset's to_wire()
  145. routine.
  146. """
  147. self._set_section(section)
  148. with self._track_size():
  149. n = rrset.to_wire(self.output, self.compress, self.origin, **kw)
  150. self.counts[section] += n
  151. def add_rdataset(self, section, name, rdataset, **kw):
  152. """Add the rdataset to the specified section, using the specified
  153. name as the owner name.
  154. Any keyword arguments are passed on to the rdataset's to_wire()
  155. routine.
  156. """
  157. self._set_section(section)
  158. with self._track_size():
  159. n = rdataset.to_wire(name, self.output, self.compress, self.origin, **kw)
  160. self.counts[section] += n
  161. def add_opt(self, opt, pad=0, opt_size=0, tsig_size=0):
  162. """Add *opt* to the additional section, applying padding if desired. The
  163. padding will take the specified precomputed OPT size and TSIG size into
  164. account.
  165. Note that we don't have reliable way of knowing how big a GSS-TSIG digest
  166. might be, so we we might not get an even multiple of the pad in that case."""
  167. if pad:
  168. ttl = opt.ttl
  169. assert opt_size >= 11
  170. opt_rdata = opt[0]
  171. size_without_padding = self.output.tell() + opt_size + tsig_size
  172. remainder = size_without_padding % pad
  173. if remainder:
  174. pad = b"\x00" * (pad - remainder)
  175. else:
  176. pad = b""
  177. options = list(opt_rdata.options)
  178. options.append(dns.edns.GenericOption(dns.edns.OptionType.PADDING, pad))
  179. opt = dns.message.Message._make_opt( # pyright: ignore
  180. ttl, opt_rdata.rdclass, options
  181. )
  182. self.was_padded = True
  183. self.add_rrset(ADDITIONAL, opt)
  184. def add_edns(self, edns, ednsflags, payload, options=None):
  185. """Add an EDNS OPT record to the message."""
  186. # make sure the EDNS version in ednsflags agrees with edns
  187. ednsflags &= 0xFF00FFFF
  188. ednsflags |= edns << 16
  189. opt = dns.message.Message._make_opt( # pyright: ignore
  190. ednsflags, payload, options
  191. )
  192. self.add_opt(opt)
  193. def add_tsig(
  194. self,
  195. keyname,
  196. secret,
  197. fudge,
  198. id,
  199. tsig_error,
  200. other_data,
  201. request_mac,
  202. algorithm=dns.tsig.default_algorithm,
  203. ):
  204. """Add a TSIG signature to the message."""
  205. s = self.output.getvalue()
  206. if isinstance(secret, dns.tsig.Key):
  207. key = secret
  208. else:
  209. key = dns.tsig.Key(keyname, secret, algorithm)
  210. tsig = dns.message.Message._make_tsig( # pyright: ignore
  211. keyname, algorithm, 0, fudge, b"", id, tsig_error, other_data
  212. )
  213. (tsig, _) = dns.tsig.sign(s, key, tsig[0], int(time.time()), request_mac)
  214. self._write_tsig(tsig, keyname)
  215. def add_multi_tsig(
  216. self,
  217. ctx,
  218. keyname,
  219. secret,
  220. fudge,
  221. id,
  222. tsig_error,
  223. other_data,
  224. request_mac,
  225. algorithm=dns.tsig.default_algorithm,
  226. ):
  227. """Add a TSIG signature to the message. Unlike add_tsig(), this can be
  228. used for a series of consecutive DNS envelopes, e.g. for a zone
  229. transfer over TCP [RFC2845, 4.4].
  230. For the first message in the sequence, give ctx=None. For each
  231. subsequent message, give the ctx that was returned from the
  232. add_multi_tsig() call for the previous message."""
  233. s = self.output.getvalue()
  234. if isinstance(secret, dns.tsig.Key):
  235. key = secret
  236. else:
  237. key = dns.tsig.Key(keyname, secret, algorithm)
  238. tsig = dns.message.Message._make_tsig( # pyright: ignore
  239. keyname, algorithm, 0, fudge, b"", id, tsig_error, other_data
  240. )
  241. (tsig, ctx) = dns.tsig.sign(
  242. s, key, tsig[0], int(time.time()), request_mac, ctx, True
  243. )
  244. self._write_tsig(tsig, keyname)
  245. return ctx
  246. def _write_tsig(self, tsig, keyname):
  247. if self.was_padded:
  248. compress = None
  249. else:
  250. compress = self.compress
  251. self._set_section(ADDITIONAL)
  252. with self._track_size():
  253. keyname.to_wire(self.output, compress, self.origin)
  254. self.output.write(
  255. struct.pack("!HHI", dns.rdatatype.TSIG, dns.rdataclass.ANY, 0)
  256. )
  257. with prefixed_length(self.output, 2):
  258. tsig.to_wire(self.output)
  259. self.counts[ADDITIONAL] += 1
  260. with self._temporarily_seek_to(10):
  261. self.output.write(struct.pack("!H", self.counts[ADDITIONAL]))
  262. def write_header(self):
  263. """Write the DNS message header.
  264. Writing the DNS message header is done after all sections
  265. have been rendered, but before the optional TSIG signature
  266. is added.
  267. """
  268. with self._temporarily_seek_to(0):
  269. self.output.write(
  270. struct.pack(
  271. "!HHHHHH",
  272. self.id,
  273. self.flags,
  274. self.counts[0],
  275. self.counts[1],
  276. self.counts[2],
  277. self.counts[3],
  278. )
  279. )
  280. def get_wire(self):
  281. """Return the wire format message."""
  282. return self.output.getvalue()
  283. def reserve(self, size: int) -> None:
  284. """Reserve *size* bytes."""
  285. if size < 0:
  286. raise ValueError("reserved amount must be non-negative")
  287. if size > self.max_size:
  288. raise ValueError("cannot reserve more than the maximum size")
  289. self.reserved += size
  290. self.max_size -= size
  291. def release_reserved(self) -> None:
  292. """Release the reserved bytes."""
  293. self.max_size += self.reserved
  294. self.reserved = 0