You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

291 lines
11 KiB

4 years ago
  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. from io import BytesIO
  18. import struct
  19. import random
  20. import time
  21. import dns.exception
  22. import dns.tsig
  23. from ._compat import long
  24. QUESTION = 0
  25. ANSWER = 1
  26. AUTHORITY = 2
  27. ADDITIONAL = 3
  28. class Renderer(object):
  29. """Helper class for building DNS wire-format messages.
  30. Most applications can use the higher-level L{dns.message.Message}
  31. class and its to_wire() method to generate wire-format messages.
  32. This class is for those applications which need finer control
  33. over the generation of messages.
  34. Typical use::
  35. r = dns.renderer.Renderer(id=1, flags=0x80, max_size=512)
  36. r.add_question(qname, qtype, qclass)
  37. r.add_rrset(dns.renderer.ANSWER, rrset_1)
  38. r.add_rrset(dns.renderer.ANSWER, rrset_2)
  39. r.add_rrset(dns.renderer.AUTHORITY, ns_rrset)
  40. r.add_edns(0, 0, 4096)
  41. r.add_rrset(dns.renderer.ADDTIONAL, ad_rrset_1)
  42. r.add_rrset(dns.renderer.ADDTIONAL, ad_rrset_2)
  43. r.write_header()
  44. r.add_tsig(keyname, secret, 300, 1, 0, '', request_mac)
  45. wire = r.get_wire()
  46. output, a BytesIO, where rendering is written
  47. id: the message id
  48. flags: the message flags
  49. max_size: the maximum size of the message
  50. origin: the origin to use when rendering relative names
  51. compress: the compression table
  52. section: an int, the section currently being rendered
  53. counts: list of the number of RRs in each section
  54. mac: the MAC of the rendered message (if TSIG was used)
  55. """
  56. def __init__(self, id=None, flags=0, max_size=65535, origin=None):
  57. """Initialize a new renderer."""
  58. self.output = BytesIO()
  59. if id is None:
  60. self.id = random.randint(0, 65535)
  61. else:
  62. self.id = id
  63. self.flags = flags
  64. self.max_size = max_size
  65. self.origin = origin
  66. self.compress = {}
  67. self.section = QUESTION
  68. self.counts = [0, 0, 0, 0]
  69. self.output.write(b'\x00' * 12)
  70. self.mac = ''
  71. def _rollback(self, where):
  72. """Truncate the output buffer at offset *where*, and remove any
  73. compression table entries that pointed beyond the truncation
  74. point.
  75. """
  76. self.output.seek(where)
  77. self.output.truncate()
  78. keys_to_delete = []
  79. for k, v in self.compress.items():
  80. if v >= where:
  81. keys_to_delete.append(k)
  82. for k in keys_to_delete:
  83. del self.compress[k]
  84. def _set_section(self, section):
  85. """Set the renderer's current section.
  86. Sections must be rendered order: QUESTION, ANSWER, AUTHORITY,
  87. ADDITIONAL. Sections may be empty.
  88. Raises dns.exception.FormError if an attempt was made to set
  89. a section value less than the current section.
  90. """
  91. if self.section != section:
  92. if self.section > section:
  93. raise dns.exception.FormError
  94. self.section = section
  95. def add_question(self, qname, rdtype, rdclass=dns.rdataclass.IN):
  96. """Add a question to the message."""
  97. self._set_section(QUESTION)
  98. before = self.output.tell()
  99. qname.to_wire(self.output, self.compress, self.origin)
  100. self.output.write(struct.pack("!HH", rdtype, rdclass))
  101. after = self.output.tell()
  102. if after >= self.max_size:
  103. self._rollback(before)
  104. raise dns.exception.TooBig
  105. self.counts[QUESTION] += 1
  106. def add_rrset(self, section, rrset, **kw):
  107. """Add the rrset to the specified section.
  108. Any keyword arguments are passed on to the rdataset's to_wire()
  109. routine.
  110. """
  111. self._set_section(section)
  112. before = self.output.tell()
  113. n = rrset.to_wire(self.output, self.compress, self.origin, **kw)
  114. after = self.output.tell()
  115. if after >= self.max_size:
  116. self._rollback(before)
  117. raise dns.exception.TooBig
  118. self.counts[section] += n
  119. def add_rdataset(self, section, name, rdataset, **kw):
  120. """Add the rdataset to the specified section, using the specified
  121. name as the owner name.
  122. Any keyword arguments are passed on to the rdataset's to_wire()
  123. routine.
  124. """
  125. self._set_section(section)
  126. before = self.output.tell()
  127. n = rdataset.to_wire(name, self.output, self.compress, self.origin,
  128. **kw)
  129. after = self.output.tell()
  130. if after >= self.max_size:
  131. self._rollback(before)
  132. raise dns.exception.TooBig
  133. self.counts[section] += n
  134. def add_edns(self, edns, ednsflags, payload, options=None):
  135. """Add an EDNS OPT record to the message."""
  136. # make sure the EDNS version in ednsflags agrees with edns
  137. ednsflags &= long(0xFF00FFFF)
  138. ednsflags |= (edns << 16)
  139. self._set_section(ADDITIONAL)
  140. before = self.output.tell()
  141. self.output.write(struct.pack('!BHHIH', 0, dns.rdatatype.OPT, payload,
  142. ednsflags, 0))
  143. if options is not None:
  144. lstart = self.output.tell()
  145. for opt in options:
  146. stuff = struct.pack("!HH", opt.otype, 0)
  147. self.output.write(stuff)
  148. start = self.output.tell()
  149. opt.to_wire(self.output)
  150. end = self.output.tell()
  151. assert end - start < 65536
  152. self.output.seek(start - 2)
  153. stuff = struct.pack("!H", end - start)
  154. self.output.write(stuff)
  155. self.output.seek(0, 2)
  156. lend = self.output.tell()
  157. assert lend - lstart < 65536
  158. self.output.seek(lstart - 2)
  159. stuff = struct.pack("!H", lend - lstart)
  160. self.output.write(stuff)
  161. self.output.seek(0, 2)
  162. after = self.output.tell()
  163. if after >= self.max_size:
  164. self._rollback(before)
  165. raise dns.exception.TooBig
  166. self.counts[ADDITIONAL] += 1
  167. def add_tsig(self, keyname, secret, fudge, id, tsig_error, other_data,
  168. request_mac, algorithm=dns.tsig.default_algorithm):
  169. """Add a TSIG signature to the message."""
  170. s = self.output.getvalue()
  171. (tsig_rdata, self.mac, ctx) = dns.tsig.sign(s,
  172. keyname,
  173. secret,
  174. int(time.time()),
  175. fudge,
  176. id,
  177. tsig_error,
  178. other_data,
  179. request_mac,
  180. algorithm=algorithm)
  181. self._write_tsig(tsig_rdata, keyname)
  182. def add_multi_tsig(self, ctx, keyname, secret, fudge, id, tsig_error,
  183. other_data, request_mac,
  184. algorithm=dns.tsig.default_algorithm):
  185. """Add a TSIG signature to the message. Unlike add_tsig(), this can be
  186. used for a series of consecutive DNS envelopes, e.g. for a zone
  187. transfer over TCP [RFC2845, 4.4].
  188. For the first message in the sequence, give ctx=None. For each
  189. subsequent message, give the ctx that was returned from the
  190. add_multi_tsig() call for the previous message."""
  191. s = self.output.getvalue()
  192. (tsig_rdata, self.mac, ctx) = dns.tsig.sign(s,
  193. keyname,
  194. secret,
  195. int(time.time()),
  196. fudge,
  197. id,
  198. tsig_error,
  199. other_data,
  200. request_mac,
  201. ctx=ctx,
  202. first=ctx is None,
  203. multi=True,
  204. algorithm=algorithm)
  205. self._write_tsig(tsig_rdata, keyname)
  206. return ctx
  207. def _write_tsig(self, tsig_rdata, keyname):
  208. self._set_section(ADDITIONAL)
  209. before = self.output.tell()
  210. keyname.to_wire(self.output, self.compress, self.origin)
  211. self.output.write(struct.pack('!HHIH', dns.rdatatype.TSIG,
  212. dns.rdataclass.ANY, 0, 0))
  213. rdata_start = self.output.tell()
  214. self.output.write(tsig_rdata)
  215. after = self.output.tell()
  216. assert after - rdata_start < 65536
  217. if after >= self.max_size:
  218. self._rollback(before)
  219. raise dns.exception.TooBig
  220. self.output.seek(rdata_start - 2)
  221. self.output.write(struct.pack('!H', after - rdata_start))
  222. self.counts[ADDITIONAL] += 1
  223. self.output.seek(10)
  224. self.output.write(struct.pack('!H', self.counts[ADDITIONAL]))
  225. self.output.seek(0, 2)
  226. def write_header(self):
  227. """Write the DNS message header.
  228. Writing the DNS message header is done after all sections
  229. have been rendered, but before the optional TSIG signature
  230. is added.
  231. """
  232. self.output.seek(0)
  233. self.output.write(struct.pack('!HHHHHH', self.id, self.flags,
  234. self.counts[0], self.counts[1],
  235. self.counts[2], self.counts[3]))
  236. self.output.seek(0, 2)
  237. def get_wire(self):
  238. """Return the wire format message."""
  239. return self.output.getvalue()