renderer.py 11 KB

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