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
|
@@ -0,0 +1,1029 @@
|
|
|
1
|
+
"""DNSSEC canonicalization, DS records, and signature operations."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import hashlib
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Iterable, Mapping
|
|
7
|
+
from contextlib import nullcontext
|
|
8
|
+
from dataclasses import dataclass, replace
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
from enum import IntEnum, IntFlag
|
|
11
|
+
from functools import partial
|
|
12
|
+
from struct import Struct
|
|
13
|
+
|
|
14
|
+
from cryptography.exceptions import InvalidSignature
|
|
15
|
+
from cryptography.exceptions import UnsupportedAlgorithm as UnsupportedCryptoAlgorithm
|
|
16
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
17
|
+
from cryptography.hazmat.primitives.asymmetric import (
|
|
18
|
+
dsa,
|
|
19
|
+
ec,
|
|
20
|
+
ed448,
|
|
21
|
+
ed25519,
|
|
22
|
+
padding,
|
|
23
|
+
rsa,
|
|
24
|
+
utils,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
try:
|
|
28
|
+
from cryptography.hazmat.primitives.asymmetric.mldsa import MLDSA44PublicKey
|
|
29
|
+
except ImportError:
|
|
30
|
+
MLDSA44PublicKey = None
|
|
31
|
+
|
|
32
|
+
from tba_codec_dns.message import RRset as EditableRRset
|
|
33
|
+
from tba_codec_dns.rdata import Rdata, decoded, from_record, type_bitmap
|
|
34
|
+
from tba_codec_dns.rdataset import Rdataset
|
|
35
|
+
from tba_codec_dns.rdataset import from_records as dataset_from_records
|
|
36
|
+
from tba_codec_dns.rrset import RRset, from_rdataset
|
|
37
|
+
from tba_codec_dns.wire import RecordClass, RecordType, ResourceRecord, _name_wire
|
|
38
|
+
from tba_concrete_dns_zone.zone import Zone
|
|
39
|
+
from tba_primitives_dns_name.name import Name as DomainName
|
|
40
|
+
from tba_primitives_dns_name.name import from_text as parse_domain
|
|
41
|
+
from tba_primitives_dns_name.name import root
|
|
42
|
+
from tba_primitives_dns_name.names import (
|
|
43
|
+
Name,
|
|
44
|
+
is_subdomain,
|
|
45
|
+
parse_name,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
from .dnssecalgs import (
|
|
49
|
+
GenericPrivateKey as GenericPrivateKey,
|
|
50
|
+
GenericPublicKey as GenericPublicKey,
|
|
51
|
+
get_algorithm_cls as get_algorithm_cls,
|
|
52
|
+
get_algorithm_cls_from_dnskey as get_algorithm_cls_from_dnskey,
|
|
53
|
+
register_algorithm_cls as register_algorithm_cls,
|
|
54
|
+
)
|
|
55
|
+
from .dnssecalgs._native import NativePublicKey
|
|
56
|
+
|
|
57
|
+
_SIG = Struct("!HBBIIIH")
|
|
58
|
+
_DS = Struct("!HBB")
|
|
59
|
+
_RSA = {
|
|
60
|
+
1: hashes.MD5,
|
|
61
|
+
5: hashes.SHA1,
|
|
62
|
+
7: hashes.SHA1,
|
|
63
|
+
8: hashes.SHA256,
|
|
64
|
+
10: hashes.SHA512,
|
|
65
|
+
}
|
|
66
|
+
_DSA = frozenset({3, 6})
|
|
67
|
+
_EC = {13: (ec.SECP256R1, hashes.SHA256, 32), 14: (ec.SECP384R1, hashes.SHA384, 48)}
|
|
68
|
+
_ED = {
|
|
69
|
+
15: (ed25519.Ed25519PrivateKey, ed25519.Ed25519PublicKey),
|
|
70
|
+
16: (ed448.Ed448PrivateKey, ed448.Ed448PublicKey),
|
|
71
|
+
}
|
|
72
|
+
_DIGESTS = {1: "sha1", 2: "sha256", 4: "sha384"}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Algorithm(IntEnum):
|
|
76
|
+
RSAMD5 = 1
|
|
77
|
+
DH = 2
|
|
78
|
+
DSA = 3
|
|
79
|
+
RSASHA1 = 5
|
|
80
|
+
DSANSEC3SHA1 = 6
|
|
81
|
+
RSASHA1NSEC3SHA1 = 7
|
|
82
|
+
RSASHA256 = 8
|
|
83
|
+
RSASHA512 = 10
|
|
84
|
+
ECCGOST = 12
|
|
85
|
+
ECDSAP256SHA256 = 13
|
|
86
|
+
ECDSAP384SHA384 = 14
|
|
87
|
+
ED25519 = 15
|
|
88
|
+
ED448 = 16
|
|
89
|
+
SM2SM3 = 17
|
|
90
|
+
MLDSA44 = 18
|
|
91
|
+
ECCGOST12 = 23
|
|
92
|
+
INDIRECT = 252
|
|
93
|
+
PRIVATEDNS = 253
|
|
94
|
+
PRIVATEOID = 254
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class DSDigest(IntEnum):
|
|
98
|
+
NULL = 0
|
|
99
|
+
SHA1 = 1
|
|
100
|
+
SHA256 = 2
|
|
101
|
+
GOST = 3
|
|
102
|
+
SHA384 = 4
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class Flag(IntFlag):
|
|
106
|
+
SEP = 1
|
|
107
|
+
REVOKE = 128
|
|
108
|
+
ZONE = 256
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def algorithm_from_text(text: str | int) -> int:
|
|
112
|
+
if isinstance(text, str):
|
|
113
|
+
if text.startswith("-") and text[1:].isdecimal():
|
|
114
|
+
raise ValueError("DNSSEC algorithm outside 0..255")
|
|
115
|
+
name = text.upper().replace("-", "")
|
|
116
|
+
if not name.isdecimal():
|
|
117
|
+
try:
|
|
118
|
+
return Algorithm[name]
|
|
119
|
+
except KeyError as exc:
|
|
120
|
+
raise ValueError(f"unknown DNSSEC algorithm {text!r}") from exc
|
|
121
|
+
text = int(name)
|
|
122
|
+
if not 0 <= text <= 255:
|
|
123
|
+
raise ValueError("DNSSEC algorithm outside 0..255")
|
|
124
|
+
return text
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def algorithm_to_text(value: int) -> str:
|
|
128
|
+
value = algorithm_from_text(value)
|
|
129
|
+
try:
|
|
130
|
+
return Algorithm(value).name
|
|
131
|
+
except ValueError:
|
|
132
|
+
return str(value)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class ValidationError(ValueError):
|
|
136
|
+
"""DNSSEC data did not pass validation."""
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@dataclass(frozen=True)
|
|
140
|
+
class Policy:
|
|
141
|
+
sign_algorithms: frozenset[int] = frozenset({8, 10, 13, 14, 15, 16, 18})
|
|
142
|
+
validate_algorithms: frozenset[int] = frozenset({5, 7, 8, 10, 13, 14, 15, 16, 18})
|
|
143
|
+
create_ds_digests: frozenset[int] = frozenset({2, 4})
|
|
144
|
+
validate_ds_digests: frozenset[int] = frozenset({1, 2, 4})
|
|
145
|
+
|
|
146
|
+
def ok_to_sign(self, key: Rdata) -> bool:
|
|
147
|
+
return key.algorithm in self.sign_algorithms
|
|
148
|
+
|
|
149
|
+
def ok_to_validate(self, key: Rdata) -> bool:
|
|
150
|
+
return key.algorithm in self.validate_algorithms
|
|
151
|
+
|
|
152
|
+
def ok_to_create_ds(self, algorithm: int) -> bool:
|
|
153
|
+
return algorithm in self.create_ds_digests
|
|
154
|
+
|
|
155
|
+
def ok_to_validate_ds(self, algorithm: int) -> bool:
|
|
156
|
+
return algorithm in self.validate_ds_digests
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@dataclass(frozen=True, init=False)
|
|
160
|
+
class SimpleDeny(Policy):
|
|
161
|
+
_denied_sign: frozenset
|
|
162
|
+
_denied_validate: frozenset
|
|
163
|
+
_denied_create_ds: frozenset
|
|
164
|
+
_denied_validate_ds: frozenset
|
|
165
|
+
|
|
166
|
+
def __init__(self, deny_sign, deny_validate, deny_create_ds, deny_validate_ds):
|
|
167
|
+
object.__setattr__(self, "_denied_sign", frozenset(deny_sign))
|
|
168
|
+
object.__setattr__(self, "_denied_validate", frozenset(deny_validate))
|
|
169
|
+
object.__setattr__(self, "_denied_create_ds", frozenset(deny_create_ds))
|
|
170
|
+
object.__setattr__(self, "_denied_validate_ds", frozenset(deny_validate_ds))
|
|
171
|
+
|
|
172
|
+
def ok_to_sign(self, key: Rdata) -> bool:
|
|
173
|
+
return key.algorithm not in self._denied_sign
|
|
174
|
+
|
|
175
|
+
def ok_to_validate(self, key: Rdata) -> bool:
|
|
176
|
+
return key.algorithm not in self._denied_validate
|
|
177
|
+
|
|
178
|
+
def ok_to_create_ds(self, algorithm: int) -> bool:
|
|
179
|
+
return algorithm not in self._denied_create_ds
|
|
180
|
+
|
|
181
|
+
def ok_to_validate_ds(self, algorithm: int) -> bool:
|
|
182
|
+
return algorithm not in self._denied_validate_ds
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
rfc_8624_policy = SimpleDeny(
|
|
186
|
+
{Algorithm.RSAMD5, Algorithm.DSA, Algorithm.DSANSEC3SHA1, Algorithm.ECCGOST},
|
|
187
|
+
{Algorithm.RSAMD5, Algorithm.DSA, Algorithm.DSANSEC3SHA1},
|
|
188
|
+
{DSDigest.NULL, DSDigest.SHA1, DSDigest.GOST},
|
|
189
|
+
{DSDigest.NULL},
|
|
190
|
+
)
|
|
191
|
+
rfc_9904_policy = rfc_8624_policy
|
|
192
|
+
allow_all_policy = SimpleDeny((), (), (), ())
|
|
193
|
+
default_policy = rfc_9904_policy
|
|
194
|
+
DEFAULT_POLICY = Policy()
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _canonical(name: Name) -> Name:
|
|
198
|
+
return tuple(label.lower() for label in name)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _absolute_owner(name, origin=None) -> Name:
|
|
202
|
+
if isinstance(origin, str):
|
|
203
|
+
origin = parse_domain(origin)
|
|
204
|
+
if isinstance(name, str):
|
|
205
|
+
name = parse_domain(name, origin=origin or root)
|
|
206
|
+
if isinstance(name, DomainName):
|
|
207
|
+
if not name.is_absolute() and origin is None:
|
|
208
|
+
raise ValueError("relative DNSSEC name requires an origin")
|
|
209
|
+
return name.derelativize(origin).labels[:-1]
|
|
210
|
+
return name
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def key_tag(key: ResourceRecord | Rdata) -> int:
|
|
214
|
+
if isinstance(key, Rdata):
|
|
215
|
+
key = key.record((), 0)
|
|
216
|
+
if (
|
|
217
|
+
key.type not in (RecordType.DNSKEY, RecordType.CDNSKEY, RecordType.KEY)
|
|
218
|
+
or len(key.data) < 4
|
|
219
|
+
):
|
|
220
|
+
raise ValidationError("invalid DNSKEY data")
|
|
221
|
+
if key.data[3] == 1:
|
|
222
|
+
if len(key.data) < 7:
|
|
223
|
+
raise ValidationError("truncated RSAMD5 DNSKEY")
|
|
224
|
+
return int.from_bytes(key.data[-3:-1], "big")
|
|
225
|
+
total = sum(
|
|
226
|
+
byte << 8 if index % 2 == 0 else byte for index, byte in enumerate(key.data)
|
|
227
|
+
)
|
|
228
|
+
return (total + (total >> 16)) & 65535
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
key_id = key_tag
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
class DeniedByPolicy(ValidationError):
|
|
235
|
+
"""The DNSSEC policy rejected the requested operation."""
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _digest_number(algorithm):
|
|
239
|
+
if isinstance(algorithm, str):
|
|
240
|
+
try:
|
|
241
|
+
return DSDigest[algorithm.upper().replace("-", "")]
|
|
242
|
+
except KeyError as exc:
|
|
243
|
+
raise UnsupportedAlgorithm(f"unsupported DS digest {algorithm!r}") from exc
|
|
244
|
+
return algorithm
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _ds_data(owner, key: Rdata, digest, policy, validating):
|
|
248
|
+
digest = _digest_number(digest)
|
|
249
|
+
if key.rdtype not in (RecordType.DNSKEY, RecordType.CDNSKEY):
|
|
250
|
+
raise ValidationError("DS requires a DNSKEY or CDNSKEY")
|
|
251
|
+
allowed = policy.ok_to_validate_ds if validating else policy.ok_to_create_ds
|
|
252
|
+
if not allowed(digest):
|
|
253
|
+
raise DeniedByPolicy(f"DS digest {digest} denied by policy")
|
|
254
|
+
if digest not in _DIGESTS:
|
|
255
|
+
raise UnsupportedAlgorithm(f"unsupported DS digest {digest}")
|
|
256
|
+
value = hashlib.new(
|
|
257
|
+
_DIGESTS[digest], _name_wire(_canonical(owner)) + key.to_wire()
|
|
258
|
+
).digest()
|
|
259
|
+
return _DS.pack(key_tag(key), key.algorithm, digest) + value
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _make_ds_record(
|
|
263
|
+
key: ResourceRecord,
|
|
264
|
+
digest: int | str = 2,
|
|
265
|
+
*,
|
|
266
|
+
policy: Policy = DEFAULT_POLICY,
|
|
267
|
+
validating: bool = False,
|
|
268
|
+
cds: bool = False,
|
|
269
|
+
) -> ResourceRecord:
|
|
270
|
+
value = from_record(key)
|
|
271
|
+
if value.rdtype in (RecordType.DNSKEY, RecordType.CDNSKEY) and value.protocol != 3:
|
|
272
|
+
raise ValidationError("DNSKEY protocol must be 3")
|
|
273
|
+
data = _ds_data(key.name, value, digest, policy, validating)
|
|
274
|
+
return ResourceRecord(
|
|
275
|
+
key.name, RecordType.CDS if cds else RecordType.DS, key.rdclass, key.ttl, data
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _make_ds_rdata(name, key, algorithm, origin=None, policy=None, validating=False):
|
|
280
|
+
if not isinstance(key, Rdata):
|
|
281
|
+
raise ValueError("DS requires detached DNSKEY or CDNSKEY RDATA")
|
|
282
|
+
owner = _absolute_owner(name, origin)
|
|
283
|
+
data = _ds_data(
|
|
284
|
+
owner, key, algorithm, default_policy if policy is None else policy, validating
|
|
285
|
+
)
|
|
286
|
+
return from_record(ResourceRecord(owner, RecordType.DS, RecordClass.IN, 0, data))
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def make_ds(*args, **kwargs) -> Rdata | ResourceRecord:
|
|
290
|
+
"""Construct DS RDATA from a DNS name, DNSKEY RDATA, and digest algorithm.
|
|
291
|
+
|
|
292
|
+
The legacy form accepts a DNSKEY wire record and preserves its owner and TTL.
|
|
293
|
+
"""
|
|
294
|
+
if (
|
|
295
|
+
isinstance(args[0] if args else kwargs.get("key"), ResourceRecord)
|
|
296
|
+
and "name" not in kwargs
|
|
297
|
+
):
|
|
298
|
+
return _make_ds_record(*args, **kwargs)
|
|
299
|
+
return _make_ds_rdata(*args, **kwargs)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _integer(value: int) -> bytes:
|
|
303
|
+
return value.to_bytes(max(1, (value.bit_length() + 7) // 8), "big")
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
class UnsupportedAlgorithm(ValidationError):
|
|
307
|
+
"""The DNSSEC key algorithm is unavailable."""
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
class AlgorithmKeyMismatch(UnsupportedAlgorithm):
|
|
311
|
+
"""The public key is incompatible with the requested DNSSEC algorithm."""
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _check_native_public_key(public_key):
|
|
315
|
+
if not isinstance(
|
|
316
|
+
public_key,
|
|
317
|
+
(
|
|
318
|
+
rsa.RSAPublicKey,
|
|
319
|
+
dsa.DSAPublicKey,
|
|
320
|
+
ec.EllipticCurvePublicKey,
|
|
321
|
+
ed25519.Ed25519PublicKey,
|
|
322
|
+
ed448.Ed448PublicKey,
|
|
323
|
+
),
|
|
324
|
+
) and not (
|
|
325
|
+
MLDSA44PublicKey is not None and isinstance(public_key, MLDSA44PublicKey)
|
|
326
|
+
):
|
|
327
|
+
raise TypeError("expected a DNSSEC public key")
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _native_dnskey_data(public_key, algorithm: int) -> bytes:
|
|
331
|
+
if algorithm in _RSA and isinstance(public_key, rsa.RSAPublicKey):
|
|
332
|
+
numbers = public_key.public_numbers()
|
|
333
|
+
exponent = _integer(numbers.e)
|
|
334
|
+
size = len(exponent)
|
|
335
|
+
data = bytes((size,)) if size < 256 else b"\x00" + size.to_bytes(2, "big")
|
|
336
|
+
data += exponent + _integer(numbers.n)
|
|
337
|
+
elif algorithm in _DSA and isinstance(public_key, dsa.DSAPublicKey):
|
|
338
|
+
numbers = public_key.public_numbers()
|
|
339
|
+
params = numbers.parameter_numbers
|
|
340
|
+
width = len(_integer(params.p))
|
|
341
|
+
if not 64 <= width <= 128 or (width - 64) % 8 or params.q.bit_length() != 160:
|
|
342
|
+
raise ValidationError("DSA parameters cannot be encoded as DNSKEY")
|
|
343
|
+
t = (width - 64) // 8
|
|
344
|
+
data = (
|
|
345
|
+
bytes((t,))
|
|
346
|
+
+ params.q.to_bytes(20, "big")
|
|
347
|
+
+ b"".join(
|
|
348
|
+
number.to_bytes(width, "big")
|
|
349
|
+
for number in (params.p, params.g, numbers.y)
|
|
350
|
+
)
|
|
351
|
+
)
|
|
352
|
+
elif algorithm in _EC and isinstance(public_key, ec.EllipticCurvePublicKey):
|
|
353
|
+
curve, _, size = _EC[algorithm]
|
|
354
|
+
if not isinstance(public_key.curve, curve):
|
|
355
|
+
raise AlgorithmKeyMismatch("DNSKEY curve does not match its algorithm")
|
|
356
|
+
numbers = public_key.public_numbers()
|
|
357
|
+
data = numbers.x.to_bytes(size, "big") + numbers.y.to_bytes(size, "big")
|
|
358
|
+
elif algorithm in _ED and isinstance(public_key, _ED[algorithm][1]):
|
|
359
|
+
data = public_key.public_bytes(
|
|
360
|
+
serialization.Encoding.Raw, serialization.PublicFormat.Raw
|
|
361
|
+
)
|
|
362
|
+
elif (
|
|
363
|
+
algorithm == Algorithm.MLDSA44
|
|
364
|
+
and MLDSA44PublicKey is not None
|
|
365
|
+
and isinstance(public_key, MLDSA44PublicKey)
|
|
366
|
+
):
|
|
367
|
+
data = public_key.public_bytes_raw()
|
|
368
|
+
else:
|
|
369
|
+
raise AlgorithmKeyMismatch("public key does not match its DNSSEC algorithm")
|
|
370
|
+
return data
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _make_key_rdata(
|
|
374
|
+
public_key, algorithm: int | str, flags=Flag.ZONE, protocol=3
|
|
375
|
+
) -> Rdata:
|
|
376
|
+
algorithm = algorithm_from_text(algorithm)
|
|
377
|
+
if not isinstance(public_key, GenericPublicKey):
|
|
378
|
+
cls = get_algorithm_cls(algorithm).public_cls
|
|
379
|
+
if issubclass(cls, NativePublicKey):
|
|
380
|
+
_check_native_public_key(public_key)
|
|
381
|
+
public_key = cls(key=public_key)
|
|
382
|
+
return public_key.to_dnskey(flags=flags, protocol=protocol)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _make_key_record(
|
|
386
|
+
owner: str | Name | DomainName,
|
|
387
|
+
public_key,
|
|
388
|
+
algorithm: int | str,
|
|
389
|
+
*,
|
|
390
|
+
flags=Flag.ZONE,
|
|
391
|
+
ttl=3600,
|
|
392
|
+
rdclass=RecordClass.IN,
|
|
393
|
+
cdnskey=False,
|
|
394
|
+
) -> ResourceRecord:
|
|
395
|
+
return ResourceRecord(
|
|
396
|
+
_canonical(_absolute_owner(owner)),
|
|
397
|
+
RecordType.CDNSKEY if cdnskey else RecordType.DNSKEY,
|
|
398
|
+
rdclass,
|
|
399
|
+
ttl,
|
|
400
|
+
_make_key_rdata(public_key, algorithm, flags).to_wire(),
|
|
401
|
+
)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def make_dnskey(*args, **kwargs) -> Rdata | ResourceRecord:
|
|
405
|
+
"""Convert (public_key, algorithm, flags=ZONE, protocol=3) to DNSKEY RDATA.
|
|
406
|
+
|
|
407
|
+
The legacy (owner, public_key, algorithm) form returns a wire record.
|
|
408
|
+
"""
|
|
409
|
+
if "owner" in kwargs or (args and isinstance(args[0], (str, tuple, DomainName))):
|
|
410
|
+
return _make_key_record(*args, **kwargs)
|
|
411
|
+
return _make_key_rdata(*args, **kwargs)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def make_cdnskey(*args, **kwargs) -> Rdata | ResourceRecord:
|
|
415
|
+
"""Convert public key material to CDNSKEY using the DNSKEY call forms."""
|
|
416
|
+
key = make_dnskey(*args, **kwargs)
|
|
417
|
+
if isinstance(key, ResourceRecord):
|
|
418
|
+
return replace(key, type=RecordType.CDNSKEY)
|
|
419
|
+
return from_record(replace(key.record(()), type=RecordType.CDNSKEY))
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def make_cds(*args, **kwargs) -> Rdata | ResourceRecord:
|
|
423
|
+
"""Construct CDS using the same owner and digest conversion as DS."""
|
|
424
|
+
value = make_ds(*args, **kwargs)
|
|
425
|
+
if isinstance(value, ResourceRecord):
|
|
426
|
+
return replace(value, type=RecordType.CDS)
|
|
427
|
+
return from_record(replace(value.record(()), type=RecordType.CDS))
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _make_ds_rdataset_from_keys(
|
|
431
|
+
owner: str | Name,
|
|
432
|
+
keys: Rdataset,
|
|
433
|
+
digests: Iterable[int | str] = (DSDigest.SHA256,),
|
|
434
|
+
*,
|
|
435
|
+
policy: Policy = DEFAULT_POLICY,
|
|
436
|
+
cds: bool = False,
|
|
437
|
+
) -> Rdataset:
|
|
438
|
+
name = (
|
|
439
|
+
parse_name(owner, canonical=True)
|
|
440
|
+
if isinstance(owner, str)
|
|
441
|
+
else _canonical(owner)
|
|
442
|
+
)
|
|
443
|
+
algorithms = tuple(digests)
|
|
444
|
+
if not algorithms:
|
|
445
|
+
raise ValueError("a DS dataset requires at least one digest algorithm")
|
|
446
|
+
return dataset_from_records(
|
|
447
|
+
make_ds(key, digest, policy=policy, cds=cds)
|
|
448
|
+
for key in keys.records(name)
|
|
449
|
+
for digest in algorithms
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _make_ds_rdataset_from_rrset(rrset, algorithms, origin=None) -> Rdataset:
|
|
454
|
+
if isinstance(rrset, RRset):
|
|
455
|
+
owner, dataset = rrset.name, rrset.to_rdataset()
|
|
456
|
+
if origin is None and rrset.origin is not None:
|
|
457
|
+
origin = rrset.origin
|
|
458
|
+
elif isinstance(rrset, EditableRRset):
|
|
459
|
+
owner, dataset = rrset.name, rrset
|
|
460
|
+
else:
|
|
461
|
+
owner, dataset = rrset
|
|
462
|
+
if dataset.rdtype not in (RecordType.DNSKEY, RecordType.CDNSKEY, RecordType.CDS):
|
|
463
|
+
raise ValueError("expected a DNSKEY, CDNSKEY, or CDS dataset")
|
|
464
|
+
digests = dict.fromkeys(_digest_number(digest) for digest in algorithms)
|
|
465
|
+
if dataset.rdtype == RecordType.CDS:
|
|
466
|
+
result = Rdataset(dataset.rdclass, RecordType.DS, ttl=dataset.ttl)
|
|
467
|
+
for value in cds_rdataset_to_ds_rdataset(dataset):
|
|
468
|
+
if value.digest_type in digests:
|
|
469
|
+
result.add(value)
|
|
470
|
+
if not result:
|
|
471
|
+
raise ValueError("no CDS records matched the requested digest algorithms")
|
|
472
|
+
return result
|
|
473
|
+
|
|
474
|
+
# The 2.9.2 RRset form yields CDS for DNSKEY and CDNSKEY inputs.
|
|
475
|
+
result = Rdataset(RecordClass.IN, RecordType.CDS, ttl=dataset.ttl)
|
|
476
|
+
for digest in digests:
|
|
477
|
+
for key in dataset:
|
|
478
|
+
result.add(make_cds(owner, key, digest, origin))
|
|
479
|
+
if not result:
|
|
480
|
+
raise ValueError("no DNSKEY records or digest algorithms")
|
|
481
|
+
return result
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def make_ds_rdataset(*args, **kwargs) -> Rdataset:
|
|
485
|
+
"""Build a delegation dataset from an RRset or the legacy owner/key form."""
|
|
486
|
+
if "rrset" in kwargs or (
|
|
487
|
+
args
|
|
488
|
+
and (
|
|
489
|
+
isinstance(args[0], (RRset, EditableRRset))
|
|
490
|
+
or (
|
|
491
|
+
isinstance(args[0], tuple)
|
|
492
|
+
and len(args[0]) == 2
|
|
493
|
+
and isinstance(args[0][1], Rdataset)
|
|
494
|
+
)
|
|
495
|
+
)
|
|
496
|
+
):
|
|
497
|
+
return _make_ds_rdataset_from_rrset(*args, **kwargs)
|
|
498
|
+
return _make_ds_rdataset_from_keys(*args, **kwargs)
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def dnskey_rdataset_to_cds_rdataset(
|
|
502
|
+
name: str | DomainName,
|
|
503
|
+
rdataset: Rdataset,
|
|
504
|
+
algorithm: DSDigest | str,
|
|
505
|
+
origin: DomainName | None = None,
|
|
506
|
+
) -> Rdataset:
|
|
507
|
+
"""Derive a CDS dataset from a DNSKEY or CDNSKEY dataset."""
|
|
508
|
+
if rdataset.rdtype not in (RecordType.DNSKEY, RecordType.CDNSKEY):
|
|
509
|
+
raise ValueError("expected a DNSKEY or CDNSKEY dataset")
|
|
510
|
+
return make_ds_rdataset(
|
|
511
|
+
_absolute_owner(name, origin), rdataset, (algorithm,), cds=True
|
|
512
|
+
)
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def cds_rdataset_to_ds_rdataset(rdataset: Rdataset) -> Rdataset:
|
|
516
|
+
if rdataset.rdtype != RecordType.CDS:
|
|
517
|
+
raise ValueError("expected a CDS dataset")
|
|
518
|
+
return _convert_dataset(rdataset, RecordType.DS)
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def dnskey_rdataset_to_cdnskey_rdataset(rdataset: Rdataset) -> Rdataset:
|
|
522
|
+
if rdataset.rdtype != RecordType.DNSKEY:
|
|
523
|
+
raise ValueError("expected a DNSKEY dataset")
|
|
524
|
+
return _convert_dataset(rdataset, RecordType.CDNSKEY)
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _convert_dataset(rdataset, rdtype):
|
|
528
|
+
return Rdataset(
|
|
529
|
+
rdataset.rdclass,
|
|
530
|
+
rdtype,
|
|
531
|
+
ttl=rdataset.ttl,
|
|
532
|
+
values=(
|
|
533
|
+
from_record(replace(value.record((), rdataset.ttl), type=rdtype))
|
|
534
|
+
for value in rdataset
|
|
535
|
+
),
|
|
536
|
+
)
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _public_key(algorithm: int, data: bytes):
|
|
540
|
+
try:
|
|
541
|
+
if algorithm in _RSA:
|
|
542
|
+
if not data:
|
|
543
|
+
raise ValueError("missing RSA exponent")
|
|
544
|
+
offset, size = (
|
|
545
|
+
(1, data[0]) if data[0] else (3, int.from_bytes(data[1:3], "big"))
|
|
546
|
+
)
|
|
547
|
+
if not size or offset + size >= len(data):
|
|
548
|
+
raise ValueError("bad RSA exponent length")
|
|
549
|
+
exponent = int.from_bytes(data[offset : offset + size], "big")
|
|
550
|
+
modulus = int.from_bytes(data[offset + size :], "big")
|
|
551
|
+
return rsa.RSAPublicNumbers(exponent, modulus).public_key()
|
|
552
|
+
if algorithm in _DSA:
|
|
553
|
+
if not data or data[0] > 8:
|
|
554
|
+
raise ValueError("bad DSA parameter size")
|
|
555
|
+
width = 64 + 8 * data[0]
|
|
556
|
+
if len(data) != 21 + 3 * width:
|
|
557
|
+
raise ValueError("bad DSA public key length")
|
|
558
|
+
q = int.from_bytes(data[1:21], "big")
|
|
559
|
+
p, g, y = (
|
|
560
|
+
int.from_bytes(data[start : start + width], "big")
|
|
561
|
+
for start in range(21, len(data), width)
|
|
562
|
+
)
|
|
563
|
+
return dsa.DSAPublicNumbers(
|
|
564
|
+
y, dsa.DSAParameterNumbers(p, q, g)
|
|
565
|
+
).public_key()
|
|
566
|
+
if algorithm in _EC:
|
|
567
|
+
curve, _, size = _EC[algorithm]
|
|
568
|
+
if len(data) != 2 * size:
|
|
569
|
+
raise ValueError("bad ECDSA point length")
|
|
570
|
+
return ec.EllipticCurvePublicKey.from_encoded_point(curve(), b"\x04" + data)
|
|
571
|
+
if algorithm in _ED:
|
|
572
|
+
return _ED[algorithm][1].from_public_bytes(data)
|
|
573
|
+
if algorithm == Algorithm.MLDSA44 and MLDSA44PublicKey is not None:
|
|
574
|
+
return MLDSA44PublicKey.from_public_bytes(data)
|
|
575
|
+
except (ValueError, UnsupportedCryptoAlgorithm) as exc:
|
|
576
|
+
raise ValidationError(
|
|
577
|
+
"invalid or unsupported DNSKEY public-key encoding"
|
|
578
|
+
) from exc
|
|
579
|
+
raise ValidationError("unsupported DNSSEC algorithm")
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def _rrset(records: Iterable[ResourceRecord]) -> tuple[ResourceRecord, ...]:
|
|
583
|
+
items = tuple(records)
|
|
584
|
+
if not items:
|
|
585
|
+
raise ValidationError("DNSSEC requires a nonempty RRset")
|
|
586
|
+
first = items[0]
|
|
587
|
+
if any(
|
|
588
|
+
(_canonical(rr.name), rr.type, rr.rdclass)
|
|
589
|
+
!= (_canonical(first.name), first.type, first.rdclass)
|
|
590
|
+
for rr in items
|
|
591
|
+
):
|
|
592
|
+
raise ValidationError("inconsistent DNSSEC RRset")
|
|
593
|
+
return items
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def _signature_data(
|
|
597
|
+
records: tuple[ResourceRecord, ...], signature: ResourceRecord
|
|
598
|
+
) -> bytes:
|
|
599
|
+
covered, _, labels, ttl, _, _, _, signer, _ = decoded(signature)
|
|
600
|
+
first = records[0]
|
|
601
|
+
owner = _canonical(first.name)
|
|
602
|
+
if (
|
|
603
|
+
signature.type != RecordType.RRSIG
|
|
604
|
+
or _canonical(signature.name) != owner
|
|
605
|
+
or signature.rdclass != first.rdclass
|
|
606
|
+
or covered != first.type
|
|
607
|
+
or labels > len(owner)
|
|
608
|
+
or not is_subdomain(owner, signer)
|
|
609
|
+
):
|
|
610
|
+
raise ValidationError("signature does not cover this DNS RRset")
|
|
611
|
+
if owner[:1] == (b"*",) and labels != len(owner) - 1:
|
|
612
|
+
raise ValidationError("wrong labels count for wildcard RRset")
|
|
613
|
+
if labels < len(owner):
|
|
614
|
+
owner = (b"*",) + owner[len(owner) - labels :]
|
|
615
|
+
ordered = sorted({rr.uncompressed_data(canonical=True) for rr in records})
|
|
616
|
+
return (
|
|
617
|
+
signature.data[: _SIG.size]
|
|
618
|
+
+ _name_wire(_canonical(signer))
|
|
619
|
+
+ b"".join(
|
|
620
|
+
ResourceRecord(owner, first.type, first.rdclass, ttl, item).to_wire()
|
|
621
|
+
for item in ordered
|
|
622
|
+
)
|
|
623
|
+
)
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def _seconds(start: int, end: int) -> int:
|
|
627
|
+
return (end - start) % 2**32
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def sign_rrset(
|
|
631
|
+
records: Iterable[ResourceRecord],
|
|
632
|
+
key: ResourceRecord,
|
|
633
|
+
private_key,
|
|
634
|
+
*,
|
|
635
|
+
inception: int,
|
|
636
|
+
expiration: int,
|
|
637
|
+
policy: Policy = DEFAULT_POLICY,
|
|
638
|
+
deterministic: bool = False,
|
|
639
|
+
verify: bool = False,
|
|
640
|
+
) -> ResourceRecord:
|
|
641
|
+
items = _rrset(records)
|
|
642
|
+
first = items[0]
|
|
643
|
+
if key.type != RecordType.DNSKEY or key.rdclass != first.rdclass:
|
|
644
|
+
raise ValidationError("signing requires a matching DNSKEY")
|
|
645
|
+
dnskey = from_record(key)
|
|
646
|
+
flags, protocol, algorithm, _ = decoded(key)
|
|
647
|
+
if protocol != 3 or not flags & Flag.ZONE or not policy.ok_to_sign(dnskey):
|
|
648
|
+
raise DeniedByPolicy("DNSKEY is not permitted for signing")
|
|
649
|
+
if not 0 < expiration - inception < 2**31:
|
|
650
|
+
raise ValidationError("invalid DNSSEC signature validity period")
|
|
651
|
+
if not isinstance(private_key, GenericPrivateKey):
|
|
652
|
+
private_key = get_algorithm_cls_from_dnskey(dnskey)(key=private_key)
|
|
653
|
+
if private_key.public_key().to_dnskey(flags, protocol).to_wire() != key.data:
|
|
654
|
+
raise ValidationError("private key does not match the DNSKEY")
|
|
655
|
+
labels = len(first.name) - int(first.name[:1] == (b"*",))
|
|
656
|
+
ttl = min(rr.ttl for rr in items)
|
|
657
|
+
unsigned = _SIG.pack(
|
|
658
|
+
first.type,
|
|
659
|
+
algorithm,
|
|
660
|
+
labels,
|
|
661
|
+
ttl,
|
|
662
|
+
expiration % 2**32,
|
|
663
|
+
inception % 2**32,
|
|
664
|
+
key_tag(key),
|
|
665
|
+
) + _name_wire(_canonical(key.name))
|
|
666
|
+
signature = ResourceRecord(
|
|
667
|
+
first.name, RecordType.RRSIG, first.rdclass, ttl, unsigned
|
|
668
|
+
)
|
|
669
|
+
payload = _signature_data(items, signature)
|
|
670
|
+
return replace(
|
|
671
|
+
signature, data=unsigned + private_key.sign(payload, verify, deterministic)
|
|
672
|
+
)
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
def _native_sign(private_key, payload, algorithm, data, deterministic):
|
|
676
|
+
if algorithm in _RSA:
|
|
677
|
+
raw = private_key.sign(payload, padding.PKCS1v15(), _RSA[algorithm]())
|
|
678
|
+
elif algorithm in _DSA:
|
|
679
|
+
r, s = utils.decode_dss_signature(private_key.sign(payload, hashes.SHA1()))
|
|
680
|
+
raw = data[:1] + r.to_bytes(20, "big") + s.to_bytes(20, "big")
|
|
681
|
+
elif algorithm in _EC:
|
|
682
|
+
_, digest, size = _EC[algorithm]
|
|
683
|
+
r, s = utils.decode_dss_signature(
|
|
684
|
+
private_key.sign(
|
|
685
|
+
payload, ec.ECDSA(digest(), deterministic_signing=deterministic)
|
|
686
|
+
)
|
|
687
|
+
)
|
|
688
|
+
raw = r.to_bytes(size, "big") + s.to_bytes(size, "big")
|
|
689
|
+
else:
|
|
690
|
+
raw = private_key.sign(payload)
|
|
691
|
+
return raw
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
def _native_verify(public_key, raw, payload, algorithm, data):
|
|
695
|
+
if algorithm in _RSA:
|
|
696
|
+
public_key.verify(raw, payload, padding.PKCS1v15(), _RSA[algorithm]())
|
|
697
|
+
elif algorithm in _DSA:
|
|
698
|
+
if len(raw) != 41 or raw[0] != data[0]:
|
|
699
|
+
raise ValidationError("invalid DNSSEC DSA signature length")
|
|
700
|
+
signature_der = utils.encode_dss_signature(
|
|
701
|
+
int.from_bytes(raw[1:21], "big"), int.from_bytes(raw[21:41], "big")
|
|
702
|
+
)
|
|
703
|
+
public_key.verify(signature_der, payload, hashes.SHA1())
|
|
704
|
+
elif algorithm in _EC:
|
|
705
|
+
_, digest, size = _EC[algorithm]
|
|
706
|
+
if len(raw) != 2 * size:
|
|
707
|
+
raise ValidationError("invalid DNSSEC ECDSA signature length")
|
|
708
|
+
signature_der = utils.encode_dss_signature(
|
|
709
|
+
int.from_bytes(raw[:size], "big"), int.from_bytes(raw[size:], "big")
|
|
710
|
+
)
|
|
711
|
+
public_key.verify(signature_der, payload, ec.ECDSA(digest()))
|
|
712
|
+
else:
|
|
713
|
+
public_key.verify(raw, payload)
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
def _resource_records(rrset, origin):
|
|
717
|
+
if isinstance(rrset, RRset):
|
|
718
|
+
return rrset.records
|
|
719
|
+
if isinstance(rrset, EditableRRset):
|
|
720
|
+
return rrset.to_records(
|
|
721
|
+
parse_domain(origin) if isinstance(origin, str) else origin
|
|
722
|
+
)
|
|
723
|
+
if isinstance(rrset, tuple) and len(rrset) == 2 and isinstance(rrset[1], Rdataset):
|
|
724
|
+
return rrset[1].records(_absolute_owner(rrset[0], origin))
|
|
725
|
+
return tuple(rrset)
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def _signature_time(value):
|
|
729
|
+
if isinstance(value, datetime):
|
|
730
|
+
if value.tzinfo is None:
|
|
731
|
+
value = value.replace(tzinfo=timezone.utc)
|
|
732
|
+
return int(value.timestamp())
|
|
733
|
+
if isinstance(value, str) and len(value) == 14:
|
|
734
|
+
parsed = datetime.strptime(value, "%Y%m%d%H%M%S")
|
|
735
|
+
return int(parsed.replace(tzinfo=timezone.utc).timestamp())
|
|
736
|
+
return int(value)
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
def sign(
|
|
740
|
+
rrset,
|
|
741
|
+
private_key,
|
|
742
|
+
signer,
|
|
743
|
+
dnskey,
|
|
744
|
+
inception=None,
|
|
745
|
+
expiration=None,
|
|
746
|
+
lifetime=None,
|
|
747
|
+
verify=False,
|
|
748
|
+
policy=None,
|
|
749
|
+
origin=None,
|
|
750
|
+
deterministic=True,
|
|
751
|
+
):
|
|
752
|
+
"""Sign an owner-qualified RRset and return its typed RRSIG."""
|
|
753
|
+
owner = _absolute_owner(signer, origin)
|
|
754
|
+
key = dnskey.record(owner, 0) if isinstance(dnskey, Rdata) else dnskey
|
|
755
|
+
if _canonical(key.name) != _canonical(owner):
|
|
756
|
+
raise ValidationError("DNSKEY owner does not match the signer")
|
|
757
|
+
start = int(time.time()) if inception is None else _signature_time(inception)
|
|
758
|
+
if expiration is not None:
|
|
759
|
+
end = _signature_time(expiration)
|
|
760
|
+
elif lifetime is not None:
|
|
761
|
+
end = start + lifetime
|
|
762
|
+
else:
|
|
763
|
+
raise ValueError("DNSSEC signing requires an expiration or lifetime")
|
|
764
|
+
records = _resource_records(rrset, origin)
|
|
765
|
+
policy = default_policy if policy is None else policy
|
|
766
|
+
signature = sign_rrset(
|
|
767
|
+
records,
|
|
768
|
+
key,
|
|
769
|
+
private_key,
|
|
770
|
+
inception=start,
|
|
771
|
+
expiration=end,
|
|
772
|
+
policy=policy,
|
|
773
|
+
deterministic=deterministic,
|
|
774
|
+
verify=verify,
|
|
775
|
+
)
|
|
776
|
+
if verify:
|
|
777
|
+
validate_rrsig(records, signature, (key,), now=start, policy=policy)
|
|
778
|
+
return from_record(signature)
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def _validation_keys(keys, signer, rdclass, origin):
|
|
782
|
+
if not isinstance(keys, Mapping):
|
|
783
|
+
return keys
|
|
784
|
+
signer = _canonical(signer)
|
|
785
|
+
for owner, node in keys.items():
|
|
786
|
+
labels = _absolute_owner(owner, origin)
|
|
787
|
+
if _canonical(labels) != signer:
|
|
788
|
+
continue
|
|
789
|
+
dataset = (
|
|
790
|
+
node
|
|
791
|
+
if isinstance(node, Rdataset)
|
|
792
|
+
else node.get_rdataset(rdclass, RecordType.DNSKEY)
|
|
793
|
+
)
|
|
794
|
+
if dataset is not None:
|
|
795
|
+
return dataset.records(labels)
|
|
796
|
+
return ()
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
def validate_rrsig(
|
|
800
|
+
rrset,
|
|
801
|
+
rrsig,
|
|
802
|
+
keys,
|
|
803
|
+
origin=None,
|
|
804
|
+
now: int | float | None = None,
|
|
805
|
+
policy: Policy | None = None,
|
|
806
|
+
) -> None:
|
|
807
|
+
items = _rrset(_resource_records(rrset, origin))
|
|
808
|
+
signature = (
|
|
809
|
+
rrsig.record(items[0].name, items[0].ttl) if isinstance(rrsig, Rdata) else rrsig
|
|
810
|
+
)
|
|
811
|
+
policy = default_policy if policy is None else policy
|
|
812
|
+
if signature.type != RecordType.RRSIG:
|
|
813
|
+
raise ValidationError("expected a DNS RRSIG record")
|
|
814
|
+
_, algorithm, _, _, expiration, inception, tag, signer, raw = decoded(signature)
|
|
815
|
+
current = int(time.time() if now is None else now)
|
|
816
|
+
if not 0 < _seconds(inception, expiration) < 2**31 or _seconds(
|
|
817
|
+
inception, current
|
|
818
|
+
) > _seconds(inception, expiration):
|
|
819
|
+
raise ValidationError("DNSSEC signature outside its validity period")
|
|
820
|
+
payload = _signature_data(items, signature)
|
|
821
|
+
for key in _validation_keys(keys, signer, signature.rdclass, origin):
|
|
822
|
+
if (
|
|
823
|
+
key.type != RecordType.DNSKEY
|
|
824
|
+
or key.rdclass != signature.rdclass
|
|
825
|
+
or _canonical(key.name) != _canonical(signer)
|
|
826
|
+
):
|
|
827
|
+
continue
|
|
828
|
+
dnskey = from_record(key)
|
|
829
|
+
flags, protocol, key_algorithm, _ = decoded(key)
|
|
830
|
+
if (
|
|
831
|
+
protocol != 3
|
|
832
|
+
or not flags & Flag.ZONE
|
|
833
|
+
or (flags & Flag.REVOKE and items[0].type != RecordType.DNSKEY)
|
|
834
|
+
or key_algorithm != algorithm
|
|
835
|
+
or key_tag(key) != tag
|
|
836
|
+
or not policy.ok_to_validate(dnskey)
|
|
837
|
+
):
|
|
838
|
+
continue
|
|
839
|
+
try:
|
|
840
|
+
public_cls = get_algorithm_cls_from_dnskey(dnskey).public_cls
|
|
841
|
+
public_cls.from_dnskey(dnskey).verify(raw, payload)
|
|
842
|
+
return
|
|
843
|
+
except (InvalidSignature, ValueError):
|
|
844
|
+
continue
|
|
845
|
+
raise ValidationError("no DNSKEY validated the RRSIG")
|
|
846
|
+
|
|
847
|
+
|
|
848
|
+
def validate(
|
|
849
|
+
rrset,
|
|
850
|
+
rrsigset,
|
|
851
|
+
keys,
|
|
852
|
+
origin=None,
|
|
853
|
+
now: int | float | None = None,
|
|
854
|
+
policy: Policy | None = None,
|
|
855
|
+
) -> None:
|
|
856
|
+
items = _resource_records(rrset, origin)
|
|
857
|
+
candidates = keys if isinstance(keys, Mapping) else tuple(keys)
|
|
858
|
+
for signature in _resource_records(rrsigset, origin):
|
|
859
|
+
try:
|
|
860
|
+
validate_rrsig(items, signature, candidates, origin, now, policy)
|
|
861
|
+
return
|
|
862
|
+
except ValueError:
|
|
863
|
+
continue
|
|
864
|
+
raise ValidationError("no valid DNSSEC RRSIG for RRset")
|
|
865
|
+
|
|
866
|
+
|
|
867
|
+
def nsec3_hash(
|
|
868
|
+
name: str | Name | DomainName,
|
|
869
|
+
salt: str | bytes | None,
|
|
870
|
+
iterations: int,
|
|
871
|
+
algorithm: int | str = 1,
|
|
872
|
+
) -> str:
|
|
873
|
+
if isinstance(algorithm, str) and algorithm.upper() == "SHA1":
|
|
874
|
+
algorithm = 1
|
|
875
|
+
if algorithm != 1 or not 0 <= iterations <= 65535:
|
|
876
|
+
raise ValueError("unsupported NSEC3 hash algorithm or iteration count")
|
|
877
|
+
owner = _canonical(_absolute_owner(name))
|
|
878
|
+
if salt is None:
|
|
879
|
+
salt = b""
|
|
880
|
+
elif isinstance(salt, str):
|
|
881
|
+
salt = b"" if salt == "-" else bytes.fromhex(salt)
|
|
882
|
+
if len(salt) > 255:
|
|
883
|
+
raise ValueError("NSEC3 salt is longer than 255 octets")
|
|
884
|
+
digest = hashlib.sha1(_name_wire(owner) + salt).digest()
|
|
885
|
+
for _ in range(iterations):
|
|
886
|
+
digest = hashlib.sha1(digest + salt).digest()
|
|
887
|
+
return base64.b32hexencode(digest).decode().rstrip("=")
|
|
888
|
+
|
|
889
|
+
|
|
890
|
+
def default_rrset_signer(
|
|
891
|
+
txn,
|
|
892
|
+
rrset,
|
|
893
|
+
signer,
|
|
894
|
+
ksks,
|
|
895
|
+
zsks,
|
|
896
|
+
inception=None,
|
|
897
|
+
expiration=None,
|
|
898
|
+
lifetime=None,
|
|
899
|
+
policy=None,
|
|
900
|
+
origin=None,
|
|
901
|
+
deterministic=True,
|
|
902
|
+
):
|
|
903
|
+
"""Add signatures for an RRset using the keys assigned to its record type."""
|
|
904
|
+
keys = (
|
|
905
|
+
ksks
|
|
906
|
+
if rrset.rdtype in (RecordType.DNSKEY, RecordType.CDS, RecordType.CDNSKEY)
|
|
907
|
+
else zsks
|
|
908
|
+
)
|
|
909
|
+
for private_key, dnskey in keys:
|
|
910
|
+
signature = sign(
|
|
911
|
+
rrset,
|
|
912
|
+
private_key,
|
|
913
|
+
signer,
|
|
914
|
+
dnskey,
|
|
915
|
+
inception=inception,
|
|
916
|
+
expiration=expiration,
|
|
917
|
+
lifetime=lifetime,
|
|
918
|
+
policy=policy,
|
|
919
|
+
origin=origin,
|
|
920
|
+
deterministic=deterministic,
|
|
921
|
+
)
|
|
922
|
+
txn.add(rrset.name, rrset.ttl, signature)
|
|
923
|
+
|
|
924
|
+
|
|
925
|
+
def sign_zone(
|
|
926
|
+
zone: Zone,
|
|
927
|
+
txn=None,
|
|
928
|
+
keys=None,
|
|
929
|
+
add_dnskey=True,
|
|
930
|
+
dnskey_ttl=None,
|
|
931
|
+
inception=None,
|
|
932
|
+
expiration=None,
|
|
933
|
+
lifetime=None,
|
|
934
|
+
nsec3=None,
|
|
935
|
+
rrset_signer=None,
|
|
936
|
+
policy=None,
|
|
937
|
+
deterministic=True,
|
|
938
|
+
) -> None:
|
|
939
|
+
"""Sign the zone in place or stage signatures in a caller-owned writer."""
|
|
940
|
+
if nsec3 is not None:
|
|
941
|
+
raise NotImplementedError("zone signing with NSEC3 is unsupported")
|
|
942
|
+
origin, relativize, apex = zone.origin_information()
|
|
943
|
+
if origin is None:
|
|
944
|
+
raise ValueError("zone signing requires an origin")
|
|
945
|
+
keypairs = []
|
|
946
|
+
for private_key, dnskey in keys or ():
|
|
947
|
+
if isinstance(dnskey, ResourceRecord):
|
|
948
|
+
if _canonical(dnskey.name) != _canonical(origin.labels[:-1]):
|
|
949
|
+
raise ValidationError("zone signing requires apex DNSKEYs")
|
|
950
|
+
dnskey = from_record(dnskey)
|
|
951
|
+
if (dnskey.rdclass, dnskey.rdtype) != (zone.get_class(), RecordType.DNSKEY):
|
|
952
|
+
raise ValidationError("zone signing requires DNSKEYs of the zone class")
|
|
953
|
+
keypairs.append((private_key, dnskey))
|
|
954
|
+
|
|
955
|
+
if rrset_signer is None:
|
|
956
|
+
ksks = [pair for pair in keypairs if pair[1].flags & Flag.SEP]
|
|
957
|
+
zsks = [pair for pair in keypairs if not pair[1].flags & Flag.SEP]
|
|
958
|
+
rrset_signer = partial(
|
|
959
|
+
default_rrset_signer,
|
|
960
|
+
signer=origin,
|
|
961
|
+
ksks=ksks or keypairs,
|
|
962
|
+
zsks=zsks or keypairs,
|
|
963
|
+
inception=inception,
|
|
964
|
+
expiration=expiration,
|
|
965
|
+
lifetime=lifetime,
|
|
966
|
+
policy=policy,
|
|
967
|
+
origin=origin,
|
|
968
|
+
deterministic=deterministic,
|
|
969
|
+
)
|
|
970
|
+
|
|
971
|
+
with zone.writer() if txn is None else nullcontext(txn) as change:
|
|
972
|
+
soa = change.get(apex, RecordType.SOA)
|
|
973
|
+
if soa is None or len(soa) != 1:
|
|
974
|
+
raise ValueError("zone signing requires one apex SOA")
|
|
975
|
+
if add_dnskey and keypairs:
|
|
976
|
+
if dnskey_ttl is None:
|
|
977
|
+
existing_keys = change.get(apex, RecordType.DNSKEY)
|
|
978
|
+
dnskey_ttl = existing_keys.ttl if existing_keys else soa.ttl
|
|
979
|
+
change.add(apex, dnskey_ttl, *(key for _, key in keypairs))
|
|
980
|
+
_sign_nsec_chain(
|
|
981
|
+
change,
|
|
982
|
+
origin,
|
|
983
|
+
origin if relativize else None,
|
|
984
|
+
soa[0].minimum,
|
|
985
|
+
zone.get_class(),
|
|
986
|
+
rrset_signer,
|
|
987
|
+
)
|
|
988
|
+
|
|
989
|
+
|
|
990
|
+
def _sign_nsec_chain(txn, origin, display_origin, ttl, rdclass, signer):
|
|
991
|
+
"""Sign authoritative data and emit an NSEC chain in canonical name order."""
|
|
992
|
+
|
|
993
|
+
def add_nsec(owner, successor):
|
|
994
|
+
node = txn.get_node(owner)
|
|
995
|
+
types = {dataset.rdtype for dataset in node}
|
|
996
|
+
types.update((RecordType.NSEC, RecordType.RRSIG))
|
|
997
|
+
record = ResourceRecord(
|
|
998
|
+
owner.labels[:-1],
|
|
999
|
+
RecordType.NSEC,
|
|
1000
|
+
rdclass,
|
|
1001
|
+
ttl,
|
|
1002
|
+
_name_wire(successor.labels[:-1]) + type_bitmap(tuple(types)),
|
|
1003
|
+
)
|
|
1004
|
+
value = from_record(record)
|
|
1005
|
+
txn.replace(owner, ttl, value)
|
|
1006
|
+
signer(
|
|
1007
|
+
txn,
|
|
1008
|
+
RRset(record.name, rdclass, record.type, ttl, (record,), display_origin),
|
|
1009
|
+
)
|
|
1010
|
+
|
|
1011
|
+
previous = delegation = None
|
|
1012
|
+
for owner in tuple(txn.iterate_names()):
|
|
1013
|
+
owner = owner.derelativize(origin)
|
|
1014
|
+
if delegation is not None and owner.is_subdomain(delegation):
|
|
1015
|
+
continue
|
|
1016
|
+
delegation = (
|
|
1017
|
+
owner if owner != origin and txn.get(owner, RecordType.NS) else None
|
|
1018
|
+
)
|
|
1019
|
+
for dataset in txn.get_node(owner):
|
|
1020
|
+
if dataset.rdtype in (RecordType.RRSIG, RecordType.NSEC, RecordType.NSEC3):
|
|
1021
|
+
continue
|
|
1022
|
+
if delegation is None or dataset.rdtype == RecordType.DS:
|
|
1023
|
+
rrset = from_rdataset(owner, dataset)
|
|
1024
|
+
signer(txn, replace(rrset, origin=display_origin))
|
|
1025
|
+
if previous is not None:
|
|
1026
|
+
add_nsec(previous, owner)
|
|
1027
|
+
previous = owner
|
|
1028
|
+
if previous is not None:
|
|
1029
|
+
add_nsec(previous, origin)
|