Debian Codegraph @

dns/xfr.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 # Copyright (C) 2003-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 from typing import Any, List, Tuple, cast
19
20 import dns.edns
21 import dns.exception
22 import dns.message
23 import dns.name
24 import dns.rcode
25 import dns.rdata
26 import dns.rdataset
27 import dns.rdatatype
28 import dns.rdtypes
29 import dns.rdtypes.ANY
30 import dns.rdtypes.ANY.SMIMEA
31 import dns.rdtypes.ANY.SOA
32 import dns.rdtypes.svcbbase
33 import dns.serial
34 import dns.transaction
35 import dns.tsig
36 import dns.zone
37
38
39 class TransferError(dns.exception.DNSException):
40 """A zone transfer response got a non-zero rcode."""
41
42 def __init__(self, rcode):
43 message = f"Zone transfer error: {dns.rcode.to_text(rcode)}"
44 super().__init__(message)
45 self.rcode = rcode
46
47
48 class SerialWentBackwards(dns.exception.FormError):
49 """The current serial number is less than the serial we know."""
50
51
52 class UseTCP(dns.exception.DNSException):
53 """This IXFR cannot be completed with UDP."""
54
55
56 class Inbound:
57 """
58 State machine for zone transfers.
59 """
60
61 def __init__(
62 self,
63 txn_manager: dns.transaction.TransactionManager,
64 rdtype: dns.rdatatype.RdataType = dns.rdatatype.AXFR,
65 serial: int | None = None,
66 is_udp: bool = False,
67 ):
68 """Initialize an inbound zone transfer.
69
70 *txn_manager* is a :py:class:`dns.transaction.TransactionManager`.
71
72 *rdtype* can be `dns.rdatatype.AXFR` or `dns.rdatatype.IXFR`
73
74 *serial* is the base serial number for IXFRs, and is required in
75 that case.
76
77 *is_udp*, a ``bool`` indidicates if UDP is being used for this
78 XFR.
79 """
80 self.txn_manager = txn_manager
81 self.txn: dns.transaction.Transaction | None = None
82 self.rdtype = rdtype
83 if rdtype == dns.rdatatype.IXFR:
84 if serial is None:
85 raise ValueError("a starting serial must be supplied for IXFRs")
86 self.incremental = True
87 elif rdtype == dns.rdatatype.AXFR:
88 if is_udp:
89 raise ValueError("is_udp specified for AXFR")
90 self.incremental = False
91 else:
92 raise ValueError("rdtype is not IXFR or AXFR")
93 self.serial = serial
94 self.is_udp = is_udp
95 (_, _, self.origin) = txn_manager.origin_information()
96 self.soa_rdataset: dns.rdataset.Rdataset | None = None
97 self.done = False
98 self.expecting_SOA = False
99 self.delete_mode = False
100
101 def process_message(self, message: dns.message.Message) -> bool:
102 """Process one message in the transfer.
103
104 The message should have the same relativization as was specified when
105 the `dns.xfr.Inbound` was created. The message should also have been
106 created with `one_rr_per_rrset=True` because order matters.
107
108 Returns `True` if the transfer is complete, and `False` otherwise.
109 """
110 if self.txn is None:
111 self.txn = self.txn_manager.writer(not self.incremental)
112 rcode = message.rcode()
113 if rcode != dns.rcode.NOERROR:
114 raise TransferError(rcode)
115 #
116 # We don't require a question section, but if it is present is
117 # should be correct.
118 #
119 if len(message.question) > 0:
120 if message.question[0].name != self.origin:
121 raise dns.exception.FormError("wrong question name")
122 if message.question[0].rdtype != self.rdtype:
123 raise dns.exception.FormError("wrong question rdatatype")
124 answer_index = 0
125 if self.soa_rdataset is None:
126 #
127 # This is the first message. We're expecting an SOA at
128 # the origin.
129 #
130 if not message.answer or message.answer[0].name != self.origin:
131 raise dns.exception.FormError("No answer or RRset not for zone origin")
132 rrset = message.answer[0]
133 rdataset = rrset
134 if rdataset.rdtype != dns.rdatatype.SOA:
135 raise dns.exception.FormError("first RRset is not an SOA")
136 answer_index = 1
137 self.soa_rdataset = rdataset.copy() # pyright: ignore
138 if self.incremental:
139 assert self.soa_rdataset is not None
140 soa = cast(dns.rdtypes.ANY.SOA.SOA, self.soa_rdataset[0])
141 if soa.serial == self.serial:
142 #
143 # We're already up-to-date.
144 #
145 self.done = True
146 elif dns.serial.Serial(soa.serial) < self.serial:
147 # It went backwards!
148 raise SerialWentBackwards
149 else:
150 if self.is_udp and len(message.answer[answer_index:]) == 0:
151 #
152 # There are no more records, so this is the
153 # "truncated" response. Say to use TCP
154 #
155 raise UseTCP
156 #
157 # Note we're expecting another SOA so we can detect
158 # if this IXFR response is an AXFR-style response.
159 #
160 self.expecting_SOA = True
161 #
162 # Process the answer section (other than the initial SOA in
163 # the first message).
164 #
165 for rrset in message.answer[answer_index:]:
166 name = rrset.name
167 rdataset = rrset
168 if self.done:
169 raise dns.exception.FormError("answers after final SOA")
170 assert self.txn is not None # for mypy
171 if rdataset.rdtype == dns.rdatatype.SOA and name == self.origin:
172 #
173 # Every time we see an origin SOA delete_mode inverts
174 #
175 if self.incremental:
176 self.delete_mode = not self.delete_mode
177 #
178 # If this SOA Rdataset is equal to the first we saw
179 # then we're finished. If this is an IXFR we also
180 # check that we're seeing the record in the expected
181 # part of the response.
182 #
183 if rdataset == self.soa_rdataset and (
184 (not self.incremental) or self.delete_mode
185 ):
186 #
187 # This is the final SOA
188 #
189 soa = cast(dns.rdtypes.ANY.SOA.SOA, rdataset[0])
190 if self.expecting_SOA:
191 # We got an empty IXFR sequence!
192 raise dns.exception.FormError("empty IXFR sequence")
193 if self.incremental and self.serial != soa.serial:
194 raise dns.exception.FormError("unexpected end of IXFR sequence")
195 self.txn.replace(name, rdataset)
196 self.txn.commit()
197 self.txn = None
198 self.done = True
199 else:
200 #
201 # This is not the final SOA
202 #
203 self.expecting_SOA = False
204 soa = cast(dns.rdtypes.ANY.SOA.SOA, rdataset[0])
205 if self.incremental:
206 if self.delete_mode:
207 # This is the start of an IXFR deletion set
208 if soa.serial != self.serial:
209 raise dns.exception.FormError(
210 "IXFR base serial mismatch"
211 )
212 else:
213 # This is the start of an IXFR addition set
214 self.serial = soa.serial
215 self.txn.replace(name, rdataset)
216 else:
217 # We saw a non-final SOA for the origin in an AXFR.
218 raise dns.exception.FormError("unexpected origin SOA in AXFR")
219 continue
220 if self.expecting_SOA:
221 #
222 # We made an IXFR request and are expecting another
223 # SOA RR, but saw something else, so this must be an
224 # AXFR response.
225 #
226 self.incremental = False
227 self.expecting_SOA = False
228 self.delete_mode = False
229 self.txn.rollback()
230 self.txn = self.txn_manager.writer(True)
231 #
232 # Note we are falling through into the code below
233 # so whatever rdataset this was gets written.
234 #
235 # Add or remove the data
236 if self.delete_mode:
237 self.txn.delete_exact(name, rdataset)
238 else:
239 self.txn.add(name, rdataset)
240 if self.is_udp and not self.done:
241 #
242 # This is a UDP IXFR and we didn't get to done, and we didn't
243 # get the proper "truncated" response
244 #
245 raise dns.exception.FormError("unexpected end of UDP IXFR")
246 return self.done
247
248 #
249 # Inbounds are context managers.
250 #
251
252 def __enter__(self):
253 return self
254
255 def __exit__(self, exc_type, exc_val, exc_tb):
256 if self.txn:
257 self.txn.rollback()
258 return False
259
260
261 def make_query(
262 txn_manager: dns.transaction.TransactionManager,
263 serial: int | None = 0,
264 use_edns: int | bool | None = None,
265 ednsflags: int | None = None,
266 payload: int | None = None,
267 request_payload: int | None = None,
268 options: List[dns.edns.Option] | None = None,
269 keyring: Any = None,
270 keyname: dns.name.Name | None = None,
271 keyalgorithm: dns.name.Name | str = dns.tsig.default_algorithm,
272 ) -> Tuple[dns.message.QueryMessage, int | None]:
273 """Make an AXFR or IXFR query.
274
275 *txn_manager* is a ``dns.transaction.TransactionManager``, typically a
276 ``dns.zone.Zone``.
277
278 *serial* is an ``int`` or ``None``. If 0, then IXFR will be
279 attempted using the most recent serial number from the
280 *txn_manager*; it is the caller's responsibility to ensure there
281 are no write transactions active that could invalidate the
282 retrieved serial. If a serial cannot be determined, AXFR will be
283 forced. Other integer values are the starting serial to use.
284 ``None`` forces an AXFR.
285
286 Please see the documentation for :py:func:`dns.message.make_query` and
287 :py:func:`dns.message.Message.use_tsig` for details on the other parameters
288 to this function.
289
290 Returns a `(query, serial)` tuple.
291 """
292 (zone_origin, _, origin) = txn_manager.origin_information()
293 if zone_origin is None:
294 raise ValueError("no zone origin")
295 if serial is None:
296 rdtype = dns.rdatatype.AXFR
297 elif not isinstance(serial, int):
298 raise ValueError("serial is not an integer")
299 elif serial == 0:
300 with txn_manager.reader() as txn:
301 rdataset = txn.get(origin, "SOA")
302 if rdataset:
303 soa = cast(dns.rdtypes.ANY.SOA.SOA, rdataset[0])
304 serial = soa.serial
305 rdtype = dns.rdatatype.IXFR
306 else:
307 serial = None
308 rdtype = dns.rdatatype.AXFR
309 elif serial > 0 and serial < 4294967296:
310 rdtype = dns.rdatatype.IXFR
311 else:
312 raise ValueError("serial out-of-range")
313 rdclass = txn_manager.get_class()
314 q = dns.message.make_query(
315 zone_origin,
316 rdtype,
317 rdclass,
318 use_edns,
319 False,
320 ednsflags,
321 payload,
322 request_payload,
323 options,
324 )
325 if serial is not None:
326 rdata = dns.rdata.from_text(rdclass, "SOA", f". . {serial} 0 0 0 0")
327 rrset = q.find_rrset(
328 q.authority, zone_origin, rdclass, dns.rdatatype.SOA, create=True
329 )
330 rrset.add(rdata, 0)
331 if keyring is not None:
332 q.use_tsig(keyring, keyname, algorithm=keyalgorithm)
333 return (q, serial)
334
335
336 def extract_serial_from_query(query: dns.message.Message) -> int | None:
337 """Extract the SOA serial number from query if it is an IXFR and return
338 it, otherwise return None.
339
340 *query* is a dns.message.QueryMessage that is an IXFR or AXFR request.
341
342 Raises if the query is not an IXFR or AXFR, or if an IXFR doesn't have
343 an appropriate SOA RRset in the authority section.
344 """
345 if not isinstance(query, dns.message.QueryMessage):
346 raise ValueError("query not a QueryMessage")
347 question = query.question[0]
348 if question.rdtype == dns.rdatatype.AXFR:
349 return None
350 elif question.rdtype != dns.rdatatype.IXFR:
351 raise ValueError("query is not an AXFR or IXFR")
352 soa_rrset = query.find_rrset(
353 query.authority, question.name, question.rdclass, dns.rdatatype.SOA
354 )
355 soa = cast(dns.rdtypes.ANY.SOA.SOA, soa_rrset[0])
356 return soa.serial