tba-protocol-dns 0.4.0.dev5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tba_protocol_dns/__init__.py +1 -0
- tba_protocol_dns/ddr.py +7 -0
- tba_protocol_dns/dnssec.py +1029 -0
- tba_protocol_dns/dnssecalgs/__init__.py +65 -0
- tba_protocol_dns/dnssecalgs/_native.py +82 -0
- tba_protocol_dns/dnssecalgs/base.py +80 -0
- tba_protocol_dns/dnssecalgs/cryptography.py +56 -0
- tba_protocol_dns/dnssecalgs/dsa.py +15 -0
- tba_protocol_dns/dnssecalgs/ecdsa.py +17 -0
- tba_protocol_dns/dnssecalgs/eddsa.py +15 -0
- tba_protocol_dns/dnssecalgs/mldsa.py +14 -0
- tba_protocol_dns/dnssecalgs/rsa.py +19 -0
- tba_protocol_dns/gss_tsig.py +103 -0
- tba_protocol_dns/py.typed +0 -0
- tba_protocol_dns/update.py +198 -0
- tba_protocol_dns/xfr.py +794 -0
- tba_protocol_dns/zonemd.py +7 -0
- tba_protocol_dns-0.4.0.dev5.dist-info/METADATA +348 -0
- tba_protocol_dns-0.4.0.dev5.dist-info/RECORD +23 -0
- tba_protocol_dns-0.4.0.dev5.dist-info/WHEEL +4 -0
- tba_protocol_dns-0.4.0.dev5.dist-info/entry_points.txt +5 -0
- tba_protocol_dns-0.4.0.dev5.dist-info/licenses/LICENSE +201 -0
- tba_protocol_dns-0.4.0.dev5.dist-info/licenses/NOTICE +10 -0
tba_protocol_dns/xfr.py
ADDED
|
@@ -0,0 +1,794 @@
|
|
|
1
|
+
"""AXFR and IXFR zone transfers (RFC 5936 and RFC 1995)."""
|
|
2
|
+
|
|
3
|
+
import secrets
|
|
4
|
+
import socket
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
from contextlib import contextmanager
|
|
7
|
+
from dataclasses import dataclass, replace
|
|
8
|
+
from time import monotonic, time
|
|
9
|
+
|
|
10
|
+
from tba_codec_dns import message as editable_message
|
|
11
|
+
from tba_codec_dns.rdata import decoded, from_record, from_text as parse_rdata
|
|
12
|
+
from tba_codec_dns.tsig import AuthKey, StreamVerifier, sign
|
|
13
|
+
from tba_codec_dns.wire import (
|
|
14
|
+
Message,
|
|
15
|
+
Question,
|
|
16
|
+
RecordClass,
|
|
17
|
+
RecordType,
|
|
18
|
+
ResourceRecord,
|
|
19
|
+
Truncated,
|
|
20
|
+
WireError,
|
|
21
|
+
record_class,
|
|
22
|
+
record_type,
|
|
23
|
+
)
|
|
24
|
+
from tba_concrete_dns_zone.zone import Zone
|
|
25
|
+
from tba_primitives_dns_name.name import Name as DomainName
|
|
26
|
+
from tba_primitives_dns_name.name import from_text as domain_from_text
|
|
27
|
+
from tba_primitives_dns_name.names import Name, is_subdomain, parse_name
|
|
28
|
+
from tba_provider_dns_resolver import asyncquery, query as syncquery
|
|
29
|
+
from tba_provider_dns_resolver.async_transport import run_blocking
|
|
30
|
+
from tba_provider_dns_resolver.asyncbackend import get_default_backend
|
|
31
|
+
from tba_provider_dns_resolver.transport import (
|
|
32
|
+
check_response,
|
|
33
|
+
deadline_after,
|
|
34
|
+
exchange_udp_packet,
|
|
35
|
+
remaining,
|
|
36
|
+
stream,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _serial(record: ResourceRecord) -> int:
|
|
41
|
+
return decoded(record)[2]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _same_soa(left: ResourceRecord, right: ResourceRecord) -> bool:
|
|
45
|
+
return (
|
|
46
|
+
right.type == RecordType.SOA
|
|
47
|
+
and left.name == right.name
|
|
48
|
+
and left.rdclass == right.rdclass
|
|
49
|
+
and left.uncompressed_data(canonical=True)
|
|
50
|
+
== right.uncompressed_data(canonical=True)
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _newer(candidate: int, baseline: int) -> bool:
|
|
55
|
+
return 0 < (candidate - baseline) % 2**32 < 2**31
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class Delta:
|
|
60
|
+
previous: ResourceRecord
|
|
61
|
+
deleted: tuple[ResourceRecord, ...]
|
|
62
|
+
current: ResourceRecord
|
|
63
|
+
added: tuple[ResourceRecord, ...]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class Transfer:
|
|
68
|
+
origin: Name
|
|
69
|
+
rdclass: int
|
|
70
|
+
soa: ResourceRecord
|
|
71
|
+
snapshot: tuple[ResourceRecord, ...] | None = None
|
|
72
|
+
deltas: tuple[Delta, ...] = ()
|
|
73
|
+
|
|
74
|
+
def apply(self, base: Zone | None = None) -> Zone:
|
|
75
|
+
if self.snapshot is not None:
|
|
76
|
+
zone = Zone(self.origin, rdclass=self.rdclass)
|
|
77
|
+
else:
|
|
78
|
+
if base is None:
|
|
79
|
+
raise ValueError("IXFR requires the matching local zone")
|
|
80
|
+
zone = Zone(base.origin, base.records(), rdclass=base.rdclass)
|
|
81
|
+
self.apply_to(zone)
|
|
82
|
+
return zone
|
|
83
|
+
|
|
84
|
+
def apply_to(self, zone: Zone, *, transaction_setup=None) -> None:
|
|
85
|
+
"""Commit a complete transfer atomically to an existing zone."""
|
|
86
|
+
origin, _, _ = zone.origin_information()
|
|
87
|
+
if (origin.labels[:-1], zone.get_class()) != (self.origin, self.rdclass):
|
|
88
|
+
raise ValueError("DNS transfer requires the matching local zone")
|
|
89
|
+
with zone.writer(replacement=self.snapshot is not None) as txn:
|
|
90
|
+
if transaction_setup is not None:
|
|
91
|
+
transaction_setup(txn)
|
|
92
|
+
if self.snapshot is not None:
|
|
93
|
+
for rr in self.snapshot:
|
|
94
|
+
txn.add(rr.name, rr.ttl, from_record(rr))
|
|
95
|
+
txn.check_origin()
|
|
96
|
+
return
|
|
97
|
+
apex = txn.get(self.origin, RecordType.SOA)
|
|
98
|
+
expected = self.deltas[0].previous if self.deltas else self.soa
|
|
99
|
+
if (
|
|
100
|
+
apex is None
|
|
101
|
+
or len(apex) != 1
|
|
102
|
+
or not _same_soa(apex[0].record(self.origin, apex.ttl), expected)
|
|
103
|
+
):
|
|
104
|
+
raise ValueError("local zone SOA does not match the IXFR baseline")
|
|
105
|
+
for delta in self.deltas:
|
|
106
|
+
txn.delete(self.origin, RecordType.SOA)
|
|
107
|
+
for rr in delta.deleted:
|
|
108
|
+
txn.delete_exact(rr.name, from_record(rr))
|
|
109
|
+
txn.add(
|
|
110
|
+
delta.current.name, delta.current.ttl, from_record(delta.current)
|
|
111
|
+
)
|
|
112
|
+
for rr in delta.added:
|
|
113
|
+
txn.add(rr.name, rr.ttl, from_record(rr))
|
|
114
|
+
txn.check_origin()
|
|
115
|
+
if not txn.changed():
|
|
116
|
+
txn.rollback()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _deltas(records: list[ResourceRecord], serial: int) -> tuple[Delta, ...]:
|
|
120
|
+
opening, closing = records[0], records[-1]
|
|
121
|
+
milestones = [
|
|
122
|
+
i for i in range(1, len(records) - 1) if records[i].type == RecordType.SOA
|
|
123
|
+
]
|
|
124
|
+
if not milestones or len(milestones) % 2 or not _same_soa(opening, closing):
|
|
125
|
+
raise WireError("invalid IXFR delta structure")
|
|
126
|
+
milestones.append(len(records) - 1)
|
|
127
|
+
output = []
|
|
128
|
+
for old_index, new_index, next_index in zip(
|
|
129
|
+
milestones[::2], milestones[1::2], milestones[2::2]
|
|
130
|
+
):
|
|
131
|
+
previous, current = records[old_index], records[new_index]
|
|
132
|
+
if _serial(previous) != serial or not _newer(_serial(current), serial):
|
|
133
|
+
raise WireError("IXFR serial sequence is invalid")
|
|
134
|
+
if output and not _same_soa(output[-1].current, previous):
|
|
135
|
+
raise WireError("IXFR delta SOAs disagree")
|
|
136
|
+
output.append(
|
|
137
|
+
Delta(
|
|
138
|
+
previous,
|
|
139
|
+
tuple(records[old_index + 1 : new_index]),
|
|
140
|
+
current,
|
|
141
|
+
tuple(records[new_index + 1 : next_index]),
|
|
142
|
+
)
|
|
143
|
+
)
|
|
144
|
+
serial = _serial(current)
|
|
145
|
+
if not _same_soa(output[-1].current, opening):
|
|
146
|
+
raise WireError("IXFR did not reach the advertised serial")
|
|
147
|
+
return tuple(output)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@contextmanager
|
|
151
|
+
def _frames(
|
|
152
|
+
query: Message,
|
|
153
|
+
packet: bytes,
|
|
154
|
+
server: str,
|
|
155
|
+
port: int,
|
|
156
|
+
deadline: float,
|
|
157
|
+
udp_serial: int | None,
|
|
158
|
+
) -> Iterator[Iterator[bytes]]:
|
|
159
|
+
if udp_serial is not None:
|
|
160
|
+
try:
|
|
161
|
+
udp_deadline = monotonic() + min(2, remaining(deadline) / 2)
|
|
162
|
+
answer = exchange_udp_packet(
|
|
163
|
+
query, packet, server, port, udp_deadline, None
|
|
164
|
+
)
|
|
165
|
+
except OSError:
|
|
166
|
+
answer = None
|
|
167
|
+
if answer is not None and not answer[2] & 2:
|
|
168
|
+
response = Message.from_wire(answer)
|
|
169
|
+
if (
|
|
170
|
+
len(response.answers) != 1
|
|
171
|
+
or response.answers[0].type != RecordType.SOA
|
|
172
|
+
or _serial(response.answers[0]) == udp_serial
|
|
173
|
+
):
|
|
174
|
+
yield iter((answer,))
|
|
175
|
+
return
|
|
176
|
+
with stream(server, port, deadline) as connection:
|
|
177
|
+
connection.send(packet)
|
|
178
|
+
|
|
179
|
+
def frames():
|
|
180
|
+
while True:
|
|
181
|
+
yield connection.receive()
|
|
182
|
+
|
|
183
|
+
yield frames()
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def transfer(
|
|
187
|
+
origin: str,
|
|
188
|
+
server: str,
|
|
189
|
+
*,
|
|
190
|
+
port: int = 53,
|
|
191
|
+
timeout: float = 10,
|
|
192
|
+
rdclass: int | str = RecordClass.IN,
|
|
193
|
+
base_soa: ResourceRecord | None = None,
|
|
194
|
+
key: AuthKey | None = None,
|
|
195
|
+
max_records: int = 1000000,
|
|
196
|
+
try_udp: bool = False,
|
|
197
|
+
) -> Transfer:
|
|
198
|
+
if max_records <= 0:
|
|
199
|
+
raise ValueError("DNS transfer requires a positive record limit")
|
|
200
|
+
if try_udp and base_soa is None:
|
|
201
|
+
raise ValueError("UDP transfer requires an IXFR baseline")
|
|
202
|
+
owner = parse_name(origin, canonical=True)
|
|
203
|
+
class_number = record_class(rdclass)
|
|
204
|
+
serial = None
|
|
205
|
+
if base_soa is not None:
|
|
206
|
+
if (base_soa.name, base_soa.rdclass, base_soa.type) != (
|
|
207
|
+
owner,
|
|
208
|
+
class_number,
|
|
209
|
+
RecordType.SOA,
|
|
210
|
+
):
|
|
211
|
+
raise ValueError("IXFR baseline must be the matching apex SOA")
|
|
212
|
+
serial = _serial(base_soa)
|
|
213
|
+
query = Message(
|
|
214
|
+
secrets.randbits(16),
|
|
215
|
+
0,
|
|
216
|
+
(
|
|
217
|
+
Question(
|
|
218
|
+
owner,
|
|
219
|
+
RecordType.AXFR if serial is None else RecordType.IXFR,
|
|
220
|
+
class_number,
|
|
221
|
+
),
|
|
222
|
+
),
|
|
223
|
+
authority=() if base_soa is None else (base_soa,),
|
|
224
|
+
)
|
|
225
|
+
packet = query.to_wire()
|
|
226
|
+
verifier = None
|
|
227
|
+
if key is not None:
|
|
228
|
+
packet, mac = sign(packet, key)
|
|
229
|
+
verifier = StreamVerifier(key, mac)
|
|
230
|
+
decoder = _transfer_decoder(query, serial, verifier, max_records)
|
|
231
|
+
next(decoder)
|
|
232
|
+
with _frames(
|
|
233
|
+
query,
|
|
234
|
+
packet,
|
|
235
|
+
server,
|
|
236
|
+
port,
|
|
237
|
+
deadline_after(timeout),
|
|
238
|
+
serial if try_udp else None,
|
|
239
|
+
) as packets:
|
|
240
|
+
for response_packet in packets:
|
|
241
|
+
try:
|
|
242
|
+
decoder.send(response_packet)
|
|
243
|
+
except StopIteration as finished:
|
|
244
|
+
return finished.value
|
|
245
|
+
raise WireError("DNS transfer ended before its closing SOA")
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
class TransferError(WireError):
|
|
249
|
+
"""The primary returned an unsuccessful DNS response code."""
|
|
250
|
+
|
|
251
|
+
def __init__(self, rcode):
|
|
252
|
+
super().__init__(f"DNS transfer failed with rcode {rcode}")
|
|
253
|
+
self.rcode = rcode
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
class SerialWentBackwards(WireError):
|
|
257
|
+
"""A primary advertised a serial older than the local zone."""
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class UseTCP(WireError):
|
|
261
|
+
"""A UDP response cannot complete this IXFR."""
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _transfer_decoder(
|
|
265
|
+
query,
|
|
266
|
+
serial,
|
|
267
|
+
verifier,
|
|
268
|
+
max_records,
|
|
269
|
+
raise_on_serial_went_backwards=True,
|
|
270
|
+
*,
|
|
271
|
+
parsed=False,
|
|
272
|
+
):
|
|
273
|
+
owner, class_number = query.questions[0].name, query.questions[0].rdclass
|
|
274
|
+
records = []
|
|
275
|
+
opening = None
|
|
276
|
+
incremental = signed = False
|
|
277
|
+
soa_count = 0
|
|
278
|
+
while True:
|
|
279
|
+
response_packet = yield
|
|
280
|
+
response = response_packet if parsed else Message.from_wire(response_packet)
|
|
281
|
+
if parsed:
|
|
282
|
+
if response.questions and response.questions != query.questions:
|
|
283
|
+
raise WireError("unexpected DNS transfer question")
|
|
284
|
+
else:
|
|
285
|
+
check_response(query, response, allow_empty_question=bool(records))
|
|
286
|
+
if response.rcode:
|
|
287
|
+
raise TransferError(response.rcode)
|
|
288
|
+
if not response.answers or (not parsed and not response.flags & 0x0400):
|
|
289
|
+
raise WireError("invalid DNS transfer response")
|
|
290
|
+
if parsed and not records:
|
|
291
|
+
signed = bool(response.request_mac)
|
|
292
|
+
if signed and not response.had_tsig:
|
|
293
|
+
raise WireError("missing TSIG on first transfer response")
|
|
294
|
+
completed = False
|
|
295
|
+
for rr in response.answers:
|
|
296
|
+
if completed or len(records) >= max_records:
|
|
297
|
+
raise WireError("excess records in DNS transfer")
|
|
298
|
+
if not is_subdomain(rr.name, owner) and parsed and records:
|
|
299
|
+
continue
|
|
300
|
+
if rr.rdclass != class_number or not is_subdomain(rr.name, owner):
|
|
301
|
+
raise WireError("record is outside the transferred zone")
|
|
302
|
+
if rr.type == RecordType.SOA:
|
|
303
|
+
if rr.name != owner:
|
|
304
|
+
raise WireError("transfer SOA is outside the apex")
|
|
305
|
+
soa_count += 1
|
|
306
|
+
if not records:
|
|
307
|
+
if rr.type != RecordType.SOA:
|
|
308
|
+
raise WireError("DNS transfer requires an opening SOA")
|
|
309
|
+
opening = rr
|
|
310
|
+
elif len(records) == 1 and serial is not None:
|
|
311
|
+
incremental = rr.type == RecordType.SOA and not _same_soa(opening, rr)
|
|
312
|
+
if len(records) and _same_soa(opening, rr):
|
|
313
|
+
completed = not incremental or (soa_count >= 4 and soa_count % 2 == 0)
|
|
314
|
+
records.append(rr)
|
|
315
|
+
same_serial = serial is not None and _serial(opening) == serial
|
|
316
|
+
older_serial = serial is not None and _newer(serial, _serial(opening))
|
|
317
|
+
if parsed and (completed or same_serial or older_serial):
|
|
318
|
+
if (signed or response.request_mac) and not response.had_tsig:
|
|
319
|
+
raise WireError("missing TSIG on last transfer response")
|
|
320
|
+
if (same_serial or older_serial) and len(records) != 1:
|
|
321
|
+
raise WireError("unexpected records after the current SOA")
|
|
322
|
+
if older_serial:
|
|
323
|
+
if verifier is not None:
|
|
324
|
+
verifier.verify(response_packet, last=True)
|
|
325
|
+
if raise_on_serial_went_backwards:
|
|
326
|
+
raise SerialWentBackwards(
|
|
327
|
+
"primary zone serial is older than the local serial"
|
|
328
|
+
)
|
|
329
|
+
return Transfer(owner, class_number, opening)
|
|
330
|
+
unchanged = len(records) == 1 and same_serial
|
|
331
|
+
if verifier is not None:
|
|
332
|
+
verifier.verify(response_packet, last=completed or unchanged)
|
|
333
|
+
if unchanged:
|
|
334
|
+
return Transfer(owner, class_number, opening)
|
|
335
|
+
if completed:
|
|
336
|
+
if incremental:
|
|
337
|
+
return Transfer(
|
|
338
|
+
owner, class_number, opening, deltas=_deltas(records, serial)
|
|
339
|
+
)
|
|
340
|
+
if soa_count != 2:
|
|
341
|
+
raise WireError("full DNS transfer contains interior SOA records")
|
|
342
|
+
return Transfer(owner, class_number, opening, snapshot=tuple(records[:-1]))
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
class Inbound:
|
|
346
|
+
"""Apply one complete AXFR or IXFR to a transaction manager."""
|
|
347
|
+
|
|
348
|
+
def __init__(
|
|
349
|
+
self,
|
|
350
|
+
txn_manager,
|
|
351
|
+
rdtype=RecordType.AXFR,
|
|
352
|
+
serial=None,
|
|
353
|
+
is_udp=False,
|
|
354
|
+
raise_on_serial_went_backwards=True,
|
|
355
|
+
transaction_setup=None,
|
|
356
|
+
):
|
|
357
|
+
if rdtype not in (RecordType.AXFR, RecordType.IXFR):
|
|
358
|
+
raise ValueError("expected AXFR or IXFR")
|
|
359
|
+
if rdtype == RecordType.IXFR and serial is None:
|
|
360
|
+
raise ValueError("IXFR requires an initial serial")
|
|
361
|
+
if rdtype == RecordType.AXFR and (serial is not None or is_udp):
|
|
362
|
+
raise ValueError("AXFR requires TCP and no initial serial")
|
|
363
|
+
origin, _, _ = txn_manager.origin_information()
|
|
364
|
+
if origin is None:
|
|
365
|
+
raise ValueError("transfer requires a zone origin")
|
|
366
|
+
self.txn_manager = txn_manager
|
|
367
|
+
self.transaction_setup = transaction_setup
|
|
368
|
+
self.is_udp = is_udp
|
|
369
|
+
self.done = False
|
|
370
|
+
self._serial = serial
|
|
371
|
+
self._closed = False
|
|
372
|
+
query = Message(
|
|
373
|
+
0, 0, (Question(origin.labels[:-1], rdtype, txn_manager.get_class()),)
|
|
374
|
+
)
|
|
375
|
+
self._decoder = _transfer_decoder(
|
|
376
|
+
query,
|
|
377
|
+
serial,
|
|
378
|
+
None,
|
|
379
|
+
1000000,
|
|
380
|
+
raise_on_serial_went_backwards,
|
|
381
|
+
parsed=True,
|
|
382
|
+
)
|
|
383
|
+
next(self._decoder)
|
|
384
|
+
|
|
385
|
+
def process_message(self, message):
|
|
386
|
+
"""Consume a parsed frame and commit once its closing SOA arrives."""
|
|
387
|
+
if self._closed:
|
|
388
|
+
raise WireError("DNS transfer is already closed")
|
|
389
|
+
if isinstance(message, editable_message.Message):
|
|
390
|
+
message = message._wire_message()
|
|
391
|
+
try:
|
|
392
|
+
self._decoder.send(message)
|
|
393
|
+
except StopIteration as finished:
|
|
394
|
+
self._closed = True
|
|
395
|
+
result = finished.value
|
|
396
|
+
if self._serial is None or _newer(_serial(result.soa), self._serial):
|
|
397
|
+
result.apply_to(
|
|
398
|
+
self.txn_manager, transaction_setup=self.transaction_setup
|
|
399
|
+
)
|
|
400
|
+
self.done = True
|
|
401
|
+
except BaseException:
|
|
402
|
+
self._closed = True
|
|
403
|
+
raise
|
|
404
|
+
if self.is_udp and not self.done:
|
|
405
|
+
self.__exit__(None, None, None)
|
|
406
|
+
if len(message.answers) == 1:
|
|
407
|
+
raise UseTCP("IXFR requires TCP")
|
|
408
|
+
raise WireError("incomplete UDP IXFR")
|
|
409
|
+
return self.done
|
|
410
|
+
|
|
411
|
+
def __enter__(self):
|
|
412
|
+
return self
|
|
413
|
+
|
|
414
|
+
def __exit__(self, exc_type, exc_value, traceback):
|
|
415
|
+
self._closed = True
|
|
416
|
+
self._decoder.close()
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def make_query(
|
|
420
|
+
txn_manager,
|
|
421
|
+
serial=0,
|
|
422
|
+
use_edns=None,
|
|
423
|
+
ednsflags=None,
|
|
424
|
+
payload=None,
|
|
425
|
+
request_payload=None,
|
|
426
|
+
options=None,
|
|
427
|
+
keyring=None,
|
|
428
|
+
keyname=None,
|
|
429
|
+
keyalgorithm="hmac-sha256.",
|
|
430
|
+
):
|
|
431
|
+
"""Build a zone transfer request and return its requested serial."""
|
|
432
|
+
origin, _, effective_origin = txn_manager.origin_information()
|
|
433
|
+
if origin is None:
|
|
434
|
+
raise ValueError("transfer requires a zone origin")
|
|
435
|
+
if serial is not None and (not isinstance(serial, int) or not 0 <= serial < 2**32):
|
|
436
|
+
raise ValueError("invalid IXFR serial")
|
|
437
|
+
if serial == 0:
|
|
438
|
+
with txn_manager.reader() as reader:
|
|
439
|
+
soa = reader.get(effective_origin, RecordType.SOA)
|
|
440
|
+
serial = soa[0].serial if soa else None
|
|
441
|
+
rdclass = txn_manager.get_class()
|
|
442
|
+
query = editable_message.make_query(
|
|
443
|
+
origin,
|
|
444
|
+
RecordType.AXFR if serial is None else RecordType.IXFR,
|
|
445
|
+
rdclass,
|
|
446
|
+
use_edns=use_edns,
|
|
447
|
+
ednsflags=ednsflags or 0,
|
|
448
|
+
payload=payload,
|
|
449
|
+
request_payload=request_payload or 0,
|
|
450
|
+
options=options,
|
|
451
|
+
)
|
|
452
|
+
if serial is not None:
|
|
453
|
+
soa = query.find_rrset(
|
|
454
|
+
query.authority, origin, rdclass, RecordType.SOA, create=True
|
|
455
|
+
)
|
|
456
|
+
soa.add(parse_rdata(rdclass, RecordType.SOA, f". . {serial} 0 0 0 0"), 0)
|
|
457
|
+
if keyring is not None:
|
|
458
|
+
query.use_tsig(keyring, keyname, algorithm=keyalgorithm)
|
|
459
|
+
return query, serial
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def extract_serial_from_query(query):
|
|
463
|
+
"""Return the IXFR baseline or None for AXFR."""
|
|
464
|
+
if isinstance(query, editable_message.QueryMessage):
|
|
465
|
+
query = query._wire_message()
|
|
466
|
+
if not isinstance(query, Message) or query.opcode != 0 or len(query.questions) != 1:
|
|
467
|
+
raise ValueError("expected an AXFR or IXFR query")
|
|
468
|
+
question = query.questions[0]
|
|
469
|
+
if question.type == RecordType.AXFR:
|
|
470
|
+
return None
|
|
471
|
+
if question.type != RecordType.IXFR:
|
|
472
|
+
raise ValueError("expected an AXFR or IXFR query")
|
|
473
|
+
for record in query.authority:
|
|
474
|
+
if (record.name, record.rdclass, record.type) == (
|
|
475
|
+
question.name,
|
|
476
|
+
question.rdclass,
|
|
477
|
+
RecordType.SOA,
|
|
478
|
+
):
|
|
479
|
+
return _serial(record)
|
|
480
|
+
raise ValueError("IXFR requires an apex SOA")
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
async def transfer_async(origin: str, server: str, **kwargs) -> Transfer:
|
|
484
|
+
return await run_blocking(transfer, origin, server, **kwargs)
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _request(query):
|
|
488
|
+
key = (
|
|
489
|
+
query.keyring if isinstance(query, editable_message.Message) else query.tsig_key
|
|
490
|
+
)
|
|
491
|
+
packet = query.to_wire()
|
|
492
|
+
query = Message.from_wire(packet)
|
|
493
|
+
if query.had_tsig and key is None:
|
|
494
|
+
raise ValueError("a signed DNS transfer query requires its TSIG key")
|
|
495
|
+
serial = extract_serial_from_query(query)
|
|
496
|
+
return query, packet, key, serial
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _manager_request(txn_manager, query):
|
|
500
|
+
origin, relativize, _ = txn_manager.origin_information()
|
|
501
|
+
if origin is None:
|
|
502
|
+
raise ValueError("transfer requires a zone origin")
|
|
503
|
+
if query is None:
|
|
504
|
+
query, _ = make_query(txn_manager)
|
|
505
|
+
request = _request(query)
|
|
506
|
+
question = request[0].questions[0]
|
|
507
|
+
if (question.name, question.rdclass) != (
|
|
508
|
+
origin.labels[:-1],
|
|
509
|
+
txn_manager.get_class(),
|
|
510
|
+
):
|
|
511
|
+
raise ValueError("DNS transfer query does not match the transaction manager")
|
|
512
|
+
return request, origin if relativize else None
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def _sync_frames(
|
|
516
|
+
where,
|
|
517
|
+
port,
|
|
518
|
+
source,
|
|
519
|
+
source_port,
|
|
520
|
+
timeout,
|
|
521
|
+
expiration,
|
|
522
|
+
request,
|
|
523
|
+
origin,
|
|
524
|
+
udp,
|
|
525
|
+
raise_on_serial_went_backwards,
|
|
526
|
+
):
|
|
527
|
+
query, packet, key, serial = request
|
|
528
|
+
verifier = None if key is None else StreamVerifier(key, query.mac or None)
|
|
529
|
+
keyring = None if verifier is None else False
|
|
530
|
+
state = _transfer_decoder(
|
|
531
|
+
query, serial, verifier, 1000000, raise_on_serial_went_backwards
|
|
532
|
+
)
|
|
533
|
+
kind = socket.SOCK_DGRAM if udp else socket.SOCK_STREAM
|
|
534
|
+
family, _, _, _, peer = socket.getaddrinfo(
|
|
535
|
+
where, port, type=kind, flags=socket.AI_NUMERICHOST
|
|
536
|
+
)[0]
|
|
537
|
+
|
|
538
|
+
def frame_expiration():
|
|
539
|
+
if timeout is None:
|
|
540
|
+
return expiration
|
|
541
|
+
per_frame = time() + timeout
|
|
542
|
+
return per_frame if expiration is None else min(per_frame, expiration)
|
|
543
|
+
|
|
544
|
+
try:
|
|
545
|
+
next(state)
|
|
546
|
+
with syncquery.make_socket(
|
|
547
|
+
family, kind, syncquery._source(family, source, source_port)
|
|
548
|
+
) as sock:
|
|
549
|
+
sock.settimeout(None if expiration is None else max(expiration - time(), 0))
|
|
550
|
+
sock.connect(peer)
|
|
551
|
+
if udp:
|
|
552
|
+
syncquery.send_udp(sock, packet, None, expiration)
|
|
553
|
+
else:
|
|
554
|
+
syncquery.send_tcp(sock, packet, expiration)
|
|
555
|
+
while True:
|
|
556
|
+
if udp:
|
|
557
|
+
try:
|
|
558
|
+
reply, _ = syncquery.receive_udp(
|
|
559
|
+
sock,
|
|
560
|
+
peer,
|
|
561
|
+
frame_expiration(),
|
|
562
|
+
keyring=keyring,
|
|
563
|
+
raise_on_truncation=True,
|
|
564
|
+
)
|
|
565
|
+
except Truncated as exc:
|
|
566
|
+
raise UseTCP("IXFR requires TCP") from exc
|
|
567
|
+
else:
|
|
568
|
+
reply, _ = syncquery.receive_tcp(
|
|
569
|
+
sock, frame_expiration(), keyring=keyring
|
|
570
|
+
)
|
|
571
|
+
try:
|
|
572
|
+
state.send(reply.wire)
|
|
573
|
+
except StopIteration as finished:
|
|
574
|
+
result = finished.value
|
|
575
|
+
else:
|
|
576
|
+
result = None
|
|
577
|
+
if udp and result is None:
|
|
578
|
+
raise UseTCP("IXFR requires more than one UDP response")
|
|
579
|
+
response = Message.from_wire(
|
|
580
|
+
reply.wire,
|
|
581
|
+
origin=origin,
|
|
582
|
+
xfr=True,
|
|
583
|
+
one_rr_per_rrset=serial is not None,
|
|
584
|
+
)
|
|
585
|
+
yield editable_message.Message._from_wire_message(
|
|
586
|
+
replace(response, tsig_key=key, request_mac=query.mac or b"")
|
|
587
|
+
)
|
|
588
|
+
if result is not None:
|
|
589
|
+
return result
|
|
590
|
+
finally:
|
|
591
|
+
state.close()
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def xfr(
|
|
595
|
+
where,
|
|
596
|
+
zone,
|
|
597
|
+
rdtype,
|
|
598
|
+
rdclass,
|
|
599
|
+
timeout,
|
|
600
|
+
port,
|
|
601
|
+
keyring,
|
|
602
|
+
keyname,
|
|
603
|
+
relativize,
|
|
604
|
+
lifetime,
|
|
605
|
+
source,
|
|
606
|
+
source_port,
|
|
607
|
+
serial,
|
|
608
|
+
use_udp,
|
|
609
|
+
keyalgorithm,
|
|
610
|
+
raise_on_serial_went_backwards,
|
|
611
|
+
):
|
|
612
|
+
origin = zone if isinstance(zone, DomainName) else domain_from_text(zone)
|
|
613
|
+
rdtype, rdclass = record_type(rdtype), record_class(rdclass)
|
|
614
|
+
if use_udp and rdtype != RecordType.IXFR:
|
|
615
|
+
raise ValueError("cannot do a UDP AXFR")
|
|
616
|
+
question = editable_message.make_query(origin, rdtype, rdclass)
|
|
617
|
+
if rdtype == RecordType.IXFR:
|
|
618
|
+
if not isinstance(serial, int) or not 0 <= serial < 2**32:
|
|
619
|
+
raise ValueError("invalid IXFR serial")
|
|
620
|
+
soa = question.find_rrset(
|
|
621
|
+
question.authority, origin, rdclass, RecordType.SOA, create=True
|
|
622
|
+
)
|
|
623
|
+
soa.add(parse_rdata(rdclass, RecordType.SOA, f". . {serial} 0 0 0 0"), 0)
|
|
624
|
+
if keyring is not None:
|
|
625
|
+
question.use_tsig(keyring, keyname, algorithm=keyalgorithm)
|
|
626
|
+
yield from _sync_frames(
|
|
627
|
+
where,
|
|
628
|
+
port,
|
|
629
|
+
source,
|
|
630
|
+
source_port,
|
|
631
|
+
timeout,
|
|
632
|
+
None if lifetime is None else time() + lifetime,
|
|
633
|
+
_request(question),
|
|
634
|
+
origin if relativize else None,
|
|
635
|
+
use_udp,
|
|
636
|
+
raise_on_serial_went_backwards,
|
|
637
|
+
)
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
def inbound_xfr_sync(
|
|
641
|
+
where,
|
|
642
|
+
txn_manager,
|
|
643
|
+
query,
|
|
644
|
+
port,
|
|
645
|
+
timeout,
|
|
646
|
+
lifetime,
|
|
647
|
+
source,
|
|
648
|
+
source_port,
|
|
649
|
+
udp_mode,
|
|
650
|
+
raise_on_serial_went_backwards,
|
|
651
|
+
):
|
|
652
|
+
request, origin = _manager_request(txn_manager, query)
|
|
653
|
+
serial = request[3]
|
|
654
|
+
expiration = None if lifetime is None else time() + lifetime
|
|
655
|
+
|
|
656
|
+
def consume(udp):
|
|
657
|
+
frames = _sync_frames(
|
|
658
|
+
where,
|
|
659
|
+
port,
|
|
660
|
+
source,
|
|
661
|
+
source_port,
|
|
662
|
+
timeout,
|
|
663
|
+
expiration,
|
|
664
|
+
request,
|
|
665
|
+
origin,
|
|
666
|
+
udp,
|
|
667
|
+
raise_on_serial_went_backwards,
|
|
668
|
+
)
|
|
669
|
+
try:
|
|
670
|
+
while True:
|
|
671
|
+
next(frames)
|
|
672
|
+
except StopIteration as finished:
|
|
673
|
+
result = finished.value
|
|
674
|
+
if serial is None or _newer(_serial(result.soa), serial):
|
|
675
|
+
result.apply_to(txn_manager)
|
|
676
|
+
|
|
677
|
+
udp_mode = syncquery.UDPMode(udp_mode)
|
|
678
|
+
if serial is not None and udp_mode != syncquery.UDPMode.NEVER:
|
|
679
|
+
try:
|
|
680
|
+
consume(True)
|
|
681
|
+
return
|
|
682
|
+
except UseTCP:
|
|
683
|
+
if udp_mode == syncquery.UDPMode.ONLY:
|
|
684
|
+
raise
|
|
685
|
+
consume(False)
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
async def inbound_xfr(
|
|
689
|
+
where,
|
|
690
|
+
txn_manager,
|
|
691
|
+
query=None,
|
|
692
|
+
port=53,
|
|
693
|
+
timeout=None,
|
|
694
|
+
lifetime=None,
|
|
695
|
+
source=None,
|
|
696
|
+
source_port=0,
|
|
697
|
+
udp_mode=asyncquery.UDPMode.NEVER,
|
|
698
|
+
backend=None,
|
|
699
|
+
raise_on_serial_went_backwards=True,
|
|
700
|
+
):
|
|
701
|
+
"""Receive an AXFR or IXFR and commit it only after validating the last frame."""
|
|
702
|
+
(query, packet, key, serial), _ = _manager_request(txn_manager, query)
|
|
703
|
+
backend = get_default_backend() if backend is None else backend
|
|
704
|
+
expiration = None if lifetime is None else time() + lifetime
|
|
705
|
+
|
|
706
|
+
def remaining_lifetime():
|
|
707
|
+
if expiration is None:
|
|
708
|
+
return None
|
|
709
|
+
delay = expiration - time()
|
|
710
|
+
if delay <= 0:
|
|
711
|
+
raise TimeoutError("DNS transfer lifetime elapsed")
|
|
712
|
+
return delay
|
|
713
|
+
|
|
714
|
+
def frame_expiration():
|
|
715
|
+
remaining_lifetime()
|
|
716
|
+
return (
|
|
717
|
+
expiration
|
|
718
|
+
if timeout is None
|
|
719
|
+
else min(time() + timeout, expiration or float("inf"))
|
|
720
|
+
)
|
|
721
|
+
|
|
722
|
+
def decoder():
|
|
723
|
+
verifier = None if key is None else StreamVerifier(key, query.mac or None)
|
|
724
|
+
result = _transfer_decoder(
|
|
725
|
+
query, serial, verifier, 1000000, raise_on_serial_went_backwards
|
|
726
|
+
)
|
|
727
|
+
next(result)
|
|
728
|
+
return result
|
|
729
|
+
|
|
730
|
+
def apply(result):
|
|
731
|
+
if serial is not None and _newer(serial, _serial(result.soa)):
|
|
732
|
+
return
|
|
733
|
+
result.apply_to(txn_manager)
|
|
734
|
+
|
|
735
|
+
async def open_socket(kind):
|
|
736
|
+
family, _, protocol, _, peer = socket.getaddrinfo(
|
|
737
|
+
where,
|
|
738
|
+
port,
|
|
739
|
+
type=kind,
|
|
740
|
+
flags=socket.AI_NUMERICHOST,
|
|
741
|
+
)[0]
|
|
742
|
+
local = None
|
|
743
|
+
if source is not None or source_port:
|
|
744
|
+
host = source or ("::" if family == socket.AF_INET6 else "0.0.0.0")
|
|
745
|
+
local = socket.getaddrinfo(
|
|
746
|
+
host, source_port, family, kind, 0, socket.AI_NUMERICHOST
|
|
747
|
+
)[0][4]
|
|
748
|
+
sock = await backend.make_socket(
|
|
749
|
+
family, kind, protocol, local, peer, remaining_lifetime()
|
|
750
|
+
)
|
|
751
|
+
return sock, peer
|
|
752
|
+
|
|
753
|
+
udp_mode = asyncquery.UDPMode(udp_mode)
|
|
754
|
+
if serial is not None and udp_mode != asyncquery.UDPMode.NEVER:
|
|
755
|
+
sock, peer = await open_socket(socket.SOCK_DGRAM)
|
|
756
|
+
try:
|
|
757
|
+
async with sock:
|
|
758
|
+
await asyncquery.send_udp(sock, packet, None, frame_expiration())
|
|
759
|
+
reply, _, _ = await asyncquery.receive_udp(
|
|
760
|
+
sock,
|
|
761
|
+
peer,
|
|
762
|
+
frame_expiration(),
|
|
763
|
+
keyring=None if key is None else False,
|
|
764
|
+
raise_on_truncation=True,
|
|
765
|
+
)
|
|
766
|
+
state = decoder()
|
|
767
|
+
try:
|
|
768
|
+
state.send(reply.wire)
|
|
769
|
+
except StopIteration as finished:
|
|
770
|
+
apply(finished.value)
|
|
771
|
+
return
|
|
772
|
+
finally:
|
|
773
|
+
state.close()
|
|
774
|
+
raise UseTCP("IXFR requires more than one UDP response")
|
|
775
|
+
except (UseTCP, Truncated) as exc:
|
|
776
|
+
if udp_mode == asyncquery.UDPMode.ONLY:
|
|
777
|
+
raise UseTCP("IXFR requires TCP") from exc
|
|
778
|
+
|
|
779
|
+
sock, _ = await open_socket(socket.SOCK_STREAM)
|
|
780
|
+
state = decoder()
|
|
781
|
+
try:
|
|
782
|
+
async with sock:
|
|
783
|
+
await asyncquery.send_tcp(sock, packet, frame_expiration())
|
|
784
|
+
while True:
|
|
785
|
+
reply, _ = await asyncquery.receive_tcp(
|
|
786
|
+
sock, frame_expiration(), keyring=None if key is None else False
|
|
787
|
+
)
|
|
788
|
+
try:
|
|
789
|
+
state.send(reply.wire)
|
|
790
|
+
except StopIteration as finished:
|
|
791
|
+
apply(finished.value)
|
|
792
|
+
return
|
|
793
|
+
finally:
|
|
794
|
+
state.close()
|