renderer.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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 struct
  20. import random
  21. import time
  22. import dns.exception
  23. import dns.tsig
  24. QUESTION = 0
  25. ANSWER = 1
  26. AUTHORITY = 2
  27. ADDITIONAL = 3
  28. class Renderer:
  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.ADDITIONAL, ad_rrset_1)
  42. r.add_rrset(dns.renderer.ADDITIONAL, 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, an io.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 = io.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. @contextlib.contextmanager
  96. def _track_size(self):
  97. start = self.output.tell()
  98. yield start
  99. if self.output.tell() > self.max_size:
  100. self._rollback(start)
  101. raise dns.exception.TooBig
  102. def add_question(self, qname, rdtype, rdclass=dns.rdataclass.IN):
  103. """Add a question to the message."""
  104. self._set_section(QUESTION)
  105. with self._track_size():
  106. qname.to_wire(self.output, self.compress, self.origin)
  107. self.output.write(struct.pack("!HH", rdtype, rdclass))
  108. self.counts[QUESTION] += 1
  109. def add_rrset(self, section, rrset, **kw):
  110. """Add the rrset to the specified section.
  111. Any keyword arguments are passed on to the rdataset's to_wire()
  112. routine.
  113. """
  114. self._set_section(section)
  115. with self._track_size():
  116. n = rrset.to_wire(self.output, self.compress, self.origin, **kw)
  117. self.counts[section] += n
  118. def add_rdataset(self, section, name, rdataset, **kw):
  119. """Add the rdataset to the specified section, using the specified
  120. name as the owner name.
  121. Any keyword arguments are passed on to the rdataset's to_wire()
  122. routine.
  123. """
  124. self._set_section(section)
  125. with self._track_size():
  126. n = rdataset.to_wire(name, self.output, self.compress, self.origin,
  127. **kw)
  128. self.counts[section] += n
  129. def add_edns(self, edns, ednsflags, payload, options=None):
  130. """Add an EDNS OPT record to the message."""
  131. # make sure the EDNS version in ednsflags agrees with edns
  132. ednsflags &= 0xFF00FFFF
  133. ednsflags |= (edns << 16)
  134. opt = dns.message.Message._make_opt(ednsflags, payload, options)
  135. self.add_rrset(ADDITIONAL, opt)
  136. def add_tsig(self, keyname, secret, fudge, id, tsig_error, other_data,
  137. request_mac, algorithm=dns.tsig.default_algorithm):
  138. """Add a TSIG signature to the message."""
  139. s = self.output.getvalue()
  140. if isinstance(secret, dns.tsig.Key):
  141. key = secret
  142. else:
  143. key = dns.tsig.Key(keyname, secret, algorithm)
  144. tsig = dns.message.Message._make_tsig(keyname, algorithm, 0, fudge,
  145. b'', id, tsig_error, other_data)
  146. (tsig, _) = dns.tsig.sign(s, key, tsig[0], int(time.time()),
  147. request_mac)
  148. self._write_tsig(tsig, keyname)
  149. def add_multi_tsig(self, ctx, keyname, secret, fudge, id, tsig_error,
  150. other_data, request_mac,
  151. algorithm=dns.tsig.default_algorithm):
  152. """Add a TSIG signature to the message. Unlike add_tsig(), this can be
  153. used for a series of consecutive DNS envelopes, e.g. for a zone
  154. transfer over TCP [RFC2845, 4.4].
  155. For the first message in the sequence, give ctx=None. For each
  156. subsequent message, give the ctx that was returned from the
  157. add_multi_tsig() call for the previous message."""
  158. s = self.output.getvalue()
  159. if isinstance(secret, dns.tsig.Key):
  160. key = secret
  161. else:
  162. key = dns.tsig.Key(keyname, secret, algorithm)
  163. tsig = dns.message.Message._make_tsig(keyname, algorithm, 0, fudge,
  164. b'', id, tsig_error, other_data)
  165. (tsig, ctx) = dns.tsig.sign(s, key, tsig[0], int(time.time()),
  166. request_mac, ctx, True)
  167. self._write_tsig(tsig, keyname)
  168. return ctx
  169. def _write_tsig(self, tsig, keyname):
  170. self._set_section(ADDITIONAL)
  171. with self._track_size():
  172. keyname.to_wire(self.output, self.compress, self.origin)
  173. self.output.write(struct.pack('!HHIH', dns.rdatatype.TSIG,
  174. dns.rdataclass.ANY, 0, 0))
  175. rdata_start = self.output.tell()
  176. tsig.to_wire(self.output)
  177. after = self.output.tell()
  178. self.output.seek(rdata_start - 2)
  179. self.output.write(struct.pack('!H', after - rdata_start))
  180. self.counts[ADDITIONAL] += 1
  181. self.output.seek(10)
  182. self.output.write(struct.pack('!H', self.counts[ADDITIONAL]))
  183. self.output.seek(0, io.SEEK_END)
  184. def write_header(self):
  185. """Write the DNS message header.
  186. Writing the DNS message header is done after all sections
  187. have been rendered, but before the optional TSIG signature
  188. is added.
  189. """
  190. self.output.seek(0)
  191. self.output.write(struct.pack('!HHHHHH', self.id, self.flags,
  192. self.counts[0], self.counts[1],
  193. self.counts[2], self.counts[3]))
  194. self.output.seek(0, io.SEEK_END)
  195. def get_wire(self):
  196. """Return the wire format message."""
  197. return self.output.getvalue()