Debian Codegraph @

dns/renderer.py

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