Debian Codegraph @

dns/dnssec.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 """Common DNSSEC-related functions and constants."""
19
20 # pylint: disable=unused-import
21
22 import base64
23 import contextlib
24 import functools
25 import hashlib
26 import struct
27 import time
28 from datetime import datetime
29 from typing import Callable, Dict, List, Set, Tuple, Union, cast
30
31 import dns._features
32 import dns.name
33 import dns.node
34 import dns.rdata
35 import dns.rdataclass
36 import dns.rdataset
37 import dns.rdatatype
38 import dns.rrset
39 import dns.transaction
40 import dns.zone
41 from dns.dnssectypes import Algorithm, DSDigest, NSEC3Hash
42 from dns.exception import AlgorithmKeyMismatch as AlgorithmKeyMismatch
43 from dns.exception import DeniedByPolicy, UnsupportedAlgorithm, ValidationFailure
44 from dns.rdtypes.ANY.CDNSKEY import CDNSKEY
45 from dns.rdtypes.ANY.CDS import CDS
46 from dns.rdtypes.ANY.DNSKEY import DNSKEY
47 from dns.rdtypes.ANY.DS import DS
48 from dns.rdtypes.ANY.NSEC import NSEC, Bitmap
49 from dns.rdtypes.ANY.NSEC3PARAM import NSEC3PARAM
50 from dns.rdtypes.ANY.RRSIG import RRSIG, sigtime_to_posixtime
51 from dns.rdtypes.dnskeybase import Flag
52
53 PublicKey = Union[
54 "GenericPublicKey",
55 "rsa.RSAPublicKey",
56 "ec.EllipticCurvePublicKey",
57 "ed25519.Ed25519PublicKey",
58 "ed448.Ed448PublicKey",
59 ]
60
61 PrivateKey = Union[
62 "GenericPrivateKey",
63 "rsa.RSAPrivateKey",
64 "ec.EllipticCurvePrivateKey",
65 "ed25519.Ed25519PrivateKey",
66 "ed448.Ed448PrivateKey",
67 ]
68
69 RRsetSigner = Callable[[dns.transaction.Transaction, dns.rrset.RRset], None]
70
71
72 def algorithm_from_text(text: str) -> Algorithm:
73 """Convert text into a DNSSEC algorithm value.
74
75 *text*, a ``str``, the text to convert to into an algorithm value.
76
77 Returns an ``int``.
78 """
79
80 return Algorithm.from_text(text)
81
82
83 def algorithm_to_text(value: Algorithm | int) -> str:
84 """Convert a DNSSEC algorithm value to text
85
86 *value*, a ``dns.dnssec.Algorithm``.
87
88 Returns a ``str``, the name of a DNSSEC algorithm.
89 """
90
91 return Algorithm.to_text(value)
92
93
94 def to_timestamp(value: datetime | str | float | int) -> int:
95 """Convert various format to a timestamp"""
96 if isinstance(value, datetime):
97 return int(value.timestamp())
98 elif isinstance(value, str):
99 return sigtime_to_posixtime(value)
100 elif isinstance(value, float):
101 return int(value)
102 elif isinstance(value, int):
103 return value
104 else:
105 raise TypeError("Unsupported timestamp type")
106
107
108 def key_id(key: DNSKEY | CDNSKEY) -> int:
109 """Return the key id (a 16-bit number) for the specified key.
110
111 *key*, a ``dns.rdtypes.ANY.DNSKEY.DNSKEY``
112
113 Returns an ``int`` between 0 and 65535
114 """
115
116 rdata = key.to_wire()
117 assert rdata is not None # for mypy
118 if key.algorithm == Algorithm.RSAMD5:
119 return (rdata[-3] << 8) + rdata[-2]
120 else:
121 total = 0
122 for i in range(len(rdata) // 2):
123 total += (rdata[2 * i] << 8) + rdata[2 * i + 1]
124 if len(rdata) % 2 != 0:
125 total += rdata[len(rdata) - 1] << 8
126 total += (total >> 16) & 0xFFFF
127 return total & 0xFFFF
128
129
130 class Policy:
131 def __init__(self):
132 pass
133
134 def ok_to_sign(self, key: DNSKEY) -> bool: # pragma: no cover
135 return False
136
137 def ok_to_validate(self, key: DNSKEY) -> bool: # pragma: no cover
138 return False
139
140 def ok_to_create_ds(self, algorithm: DSDigest) -> bool: # pragma: no cover
141 return False
142
143 def ok_to_validate_ds(self, algorithm: DSDigest) -> bool: # pragma: no cover
144 return False
145
146
147 class SimpleDeny(Policy):
148 def __init__(self, deny_sign, deny_validate, deny_create_ds, deny_validate_ds):
149 super().__init__()
150 self._deny_sign = deny_sign
151 self._deny_validate = deny_validate
152 self._deny_create_ds = deny_create_ds
153 self._deny_validate_ds = deny_validate_ds
154
155 def ok_to_sign(self, key: DNSKEY) -> bool:
156 return key.algorithm not in self._deny_sign
157
158 def ok_to_validate(self, key: DNSKEY) -> bool:
159 return key.algorithm not in self._deny_validate
160
161 def ok_to_create_ds(self, algorithm: DSDigest) -> bool:
162 return algorithm not in self._deny_create_ds
163
164 def ok_to_validate_ds(self, algorithm: DSDigest) -> bool:
165 return algorithm not in self._deny_validate_ds
166
167
168 rfc_8624_policy = SimpleDeny(
169 {Algorithm.RSAMD5, Algorithm.DSA, Algorithm.DSANSEC3SHA1, Algorithm.ECCGOST},
170 {Algorithm.RSAMD5, Algorithm.DSA, Algorithm.DSANSEC3SHA1},
171 {DSDigest.NULL, DSDigest.SHA1, DSDigest.GOST},
172 {DSDigest.NULL},
173 )
174
175 allow_all_policy = SimpleDeny(set(), set(), set(), set())
176
177
178 default_policy = rfc_8624_policy
179
180
181 def make_ds(
182 name: dns.name.Name | str,
183 key: dns.rdata.Rdata,
184 algorithm: DSDigest | str,
185 origin: dns.name.Name | None = None,
186 policy: Policy | None = None,
187 validating: bool = False,
188 ) -> DS:
189 """Create a DS record for a DNSSEC key.
190
191 *name*, a ``dns.name.Name`` or ``str``, the owner name of the DS record.
192
193 *key*, a ``dns.rdtypes.ANY.DNSKEY.DNSKEY`` or ``dns.rdtypes.ANY.DNSKEY.CDNSKEY``,
194 the key the DS is about.
195
196 *algorithm*, a ``str`` or ``int`` specifying the hash algorithm.
197 The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case
198 does not matter for these strings.
199
200 *origin*, a ``dns.name.Name`` or ``None``. If *key* is a relative name,
201 then it will be made absolute using the specified origin.
202
203 *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy,
204 ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624.
205
206 *validating*, a ``bool``. If ``True``, then policy is checked in
207 validating mode, i.e. "Is it ok to validate using this digest algorithm?".
208 Otherwise the policy is checked in creating mode, i.e. "Is it ok to create a DS with
209 this digest algorithm?".
210
211 Raises ``UnsupportedAlgorithm`` if the algorithm is unknown.
212
213 Raises ``DeniedByPolicy`` if the algorithm is denied by policy.
214
215 Returns a ``dns.rdtypes.ANY.DS.DS``
216 """
217
218 if policy is None:
219 policy = default_policy
220 try:
221 if isinstance(algorithm, str):
222 algorithm = DSDigest[algorithm.upper()]
223 except Exception:
224 raise UnsupportedAlgorithm(f'unsupported algorithm "{algorithm}"')
225 if validating:
226 check = policy.ok_to_validate_ds
227 else:
228 check = policy.ok_to_create_ds
229 if not check(algorithm):
230 raise DeniedByPolicy
231 if not isinstance(key, DNSKEY | CDNSKEY):
232 raise ValueError("key is not a DNSKEY | CDNSKEY")
233 if algorithm == DSDigest.SHA1:
234 dshash = hashlib.sha1()
235 elif algorithm == DSDigest.SHA256:
236 dshash = hashlib.sha256()
237 elif algorithm == DSDigest.SHA384:
238 dshash = hashlib.sha384()
239 else:
240 raise UnsupportedAlgorithm(f'unsupported algorithm "{algorithm}"')
241
242 if isinstance(name, str):
243 name = dns.name.from_text(name, origin)
244 wire = name.canonicalize().to_wire()
245 kwire = key.to_wire(origin=origin)
246 assert wire is not None and kwire is not None # for mypy
247 dshash.update(wire)
248 dshash.update(kwire)
249 digest = dshash.digest()
250
251 dsrdata = struct.pack("!HBB", key_id(key), key.algorithm, algorithm) + digest
252 ds = dns.rdata.from_wire(
253 dns.rdataclass.IN, dns.rdatatype.DS, dsrdata, 0, len(dsrdata)
254 )
255 return cast(DS, ds)
256
257
258 def make_cds(
259 name: dns.name.Name | str,
260 key: dns.rdata.Rdata,
261 algorithm: DSDigest | str,
262 origin: dns.name.Name | None = None,
263 ) -> CDS:
264 """Create a CDS record for a DNSSEC key.
265
266 *name*, a ``dns.name.Name`` or ``str``, the owner name of the DS record.
267
268 *key*, a ``dns.rdtypes.ANY.DNSKEY.DNSKEY`` or ``dns.rdtypes.ANY.DNSKEY.CDNSKEY``,
269 the key the DS is about.
270
271 *algorithm*, a ``str`` or ``int`` specifying the hash algorithm.
272 The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case
273 does not matter for these strings.
274
275 *origin*, a ``dns.name.Name`` or ``None``. If *key* is a relative name,
276 then it will be made absolute using the specified origin.
277
278 Raises ``UnsupportedAlgorithm`` if the algorithm is unknown.
279
280 Returns a ``dns.rdtypes.ANY.DS.CDS``
281 """
282
283 ds = make_ds(name, key, algorithm, origin)
284 return CDS(
285 rdclass=ds.rdclass,
286 rdtype=dns.rdatatype.CDS,
287 key_tag=ds.key_tag,
288 algorithm=ds.algorithm,
289 digest_type=ds.digest_type,
290 digest=ds.digest,
291 )
292
293
294 def _find_candidate_keys(
295 keys: Dict[dns.name.Name, dns.rdataset.Rdataset | dns.node.Node], rrsig: RRSIG
296 ) -> List[DNSKEY] | None:
297 value = keys.get(rrsig.signer)
298 if isinstance(value, dns.node.Node):
299 rdataset = value.get_rdataset(dns.rdataclass.IN, dns.rdatatype.DNSKEY)
300 else:
301 rdataset = value
302 if rdataset is None:
303 return None
304 return [
305 cast(DNSKEY, rd)
306 for rd in rdataset
307 if rd.algorithm == rrsig.algorithm
308 and key_id(rd) == rrsig.key_tag
309 and (rd.flags & Flag.ZONE) == Flag.ZONE # RFC 4034 2.1.1
310 and rd.protocol == 3 # RFC 4034 2.1.2
311 ]
312
313
314 def _get_rrname_rdataset(
315 rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset],
316 ) -> Tuple[dns.name.Name, dns.rdataset.Rdataset]:
317 if isinstance(rrset, tuple):
318 return rrset[0], rrset[1]
319 else:
320 return rrset.name, rrset
321
322
323 def _validate_signature(sig: bytes, data: bytes, key: DNSKEY) -> None:
324 # pylint: disable=possibly-used-before-assignment
325 public_cls = get_algorithm_cls_from_dnskey(key).public_cls
326 try:
327 public_key = public_cls.from_dnskey(key)
328 except ValueError:
329 raise ValidationFailure("invalid public key")
330 public_key.verify(sig, data)
331
332
333 def _validate_rrsig(
334 rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset],
335 rrsig: RRSIG,
336 keys: Dict[dns.name.Name, dns.node.Node | dns.rdataset.Rdataset],
337 origin: dns.name.Name | None = None,
338 now: float | None = None,
339 policy: Policy | None = None,
340 ) -> None:
341 """Validate an RRset against a single signature rdata, throwing an
342 exception if validation is not successful.
343
344 *rrset*, the RRset to validate. This can be a
345 ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``)
346 tuple.
347
348 *rrsig*, a ``dns.rdata.Rdata``, the signature to validate.
349
350 *keys*, the key dictionary, used to find the DNSKEY associated
351 with a given name. The dictionary is keyed by a
352 ``dns.name.Name``, and has ``dns.node.Node`` or
353 ``dns.rdataset.Rdataset`` values.
354
355 *origin*, a ``dns.name.Name`` or ``None``, the origin to use for relative
356 names.
357
358 *now*, a ``float`` or ``None``, the time, in seconds since the epoch, to
359 use as the current time when validating. If ``None``, the actual current
360 time is used.
361
362 *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy,
363 ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624.
364
365 Raises ``ValidationFailure`` if the signature is expired, not yet valid,
366 the public key is invalid, the algorithm is unknown, the verification
367 fails, etc.
368
369 Raises ``UnsupportedAlgorithm`` if the algorithm is recognized by
370 dnspython but not implemented.
371 """
372
373 if policy is None:
374 policy = default_policy
375
376 candidate_keys = _find_candidate_keys(keys, rrsig)
377 if candidate_keys is None:
378 raise ValidationFailure("unknown key")
379
380 if now is None:
381 now = time.time()
382 if rrsig.expiration < now:
383 raise ValidationFailure("expired")
384 if rrsig.inception > now:
385 raise ValidationFailure("not yet valid")
386
387 data = _make_rrsig_signature_data(rrset, rrsig, origin)
388
389 # pylint: disable=possibly-used-before-assignment
390 for candidate_key in candidate_keys:
391 if not policy.ok_to_validate(candidate_key):
392 continue
393 try:
394 _validate_signature(rrsig.signature, data, candidate_key)
395 return
396 except (InvalidSignature, ValidationFailure):
397 # this happens on an individual validation failure
398 continue
399 # nothing verified -- raise failure:
400 raise ValidationFailure("verify failure")
401
402
403 def _validate(
404 rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset],
405 rrsigset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset],
406 keys: Dict[dns.name.Name, dns.node.Node | dns.rdataset.Rdataset],
407 origin: dns.name.Name | None = None,
408 now: float | None = None,
409 policy: Policy | None = None,
410 ) -> None:
411 """Validate an RRset against a signature RRset, throwing an exception
412 if none of the signatures validate.
413
414 *rrset*, the RRset to validate. This can be a
415 ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``)
416 tuple.
417
418 *rrsigset*, the signature RRset. This can be a
419 ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``)
420 tuple.
421
422 *keys*, the key dictionary, used to find the DNSKEY associated
423 with a given name. The dictionary is keyed by a
424 ``dns.name.Name``, and has ``dns.node.Node`` or
425 ``dns.rdataset.Rdataset`` values.
426
427 *origin*, a ``dns.name.Name``, the origin to use for relative names;
428 defaults to None.
429
430 *now*, an ``int`` or ``None``, the time, in seconds since the epoch, to
431 use as the current time when validating. If ``None``, the actual current
432 time is used.
433
434 *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy,
435 ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624.
436
437 Raises ``ValidationFailure`` if the signature is expired, not yet valid,
438 the public key is invalid, the algorithm is unknown, the verification
439 fails, etc.
440 """
441
442 if policy is None:
443 policy = default_policy
444
445 if isinstance(origin, str):
446 origin = dns.name.from_text(origin, dns.name.root)
447
448 if isinstance(rrset, tuple):
449 rrname = rrset[0]
450 else:
451 rrname = rrset.name
452
453 if isinstance(rrsigset, tuple):
454 rrsigname = rrsigset[0]
455 rrsigrdataset = rrsigset[1]
456 else:
457 rrsigname = rrsigset.name
458 rrsigrdataset = rrsigset
459
460 rrname = rrname.choose_relativity(origin)
461 rrsigname = rrsigname.choose_relativity(origin)
462 if rrname != rrsigname:
463 raise ValidationFailure("owner names do not match")
464
465 for rrsig in rrsigrdataset:
466 if not isinstance(rrsig, RRSIG):
467 raise ValidationFailure("expected an RRSIG")
468 try:
469 _validate_rrsig(rrset, rrsig, keys, origin, now, policy)
470 return
471 except (ValidationFailure, UnsupportedAlgorithm):
472 pass
473 raise ValidationFailure("no RRSIGs validated")
474
475
476 def _sign(
477 rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset],
478 private_key: PrivateKey,
479 signer: dns.name.Name,
480 dnskey: DNSKEY,
481 inception: datetime | str | int | float | None = None,
482 expiration: datetime | str | int | float | None = None,
483 lifetime: int | None = None,
484 verify: bool = False,
485 policy: Policy | None = None,
486 origin: dns.name.Name | None = None,
487 deterministic: bool = True,
488 ) -> RRSIG:
489 """Sign RRset using private key.
490
491 *rrset*, the RRset to validate. This can be a
492 ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``)
493 tuple.
494
495 *private_key*, the private key to use for signing, a
496 ``cryptography.hazmat.primitives.asymmetric`` private key class applicable
497 for DNSSEC.
498
499 *signer*, a ``dns.name.Name``, the Signer's name.
500
501 *dnskey*, a ``DNSKEY`` matching ``private_key``.
502
503 *inception*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the
504 signature inception time. If ``None``, the current time is used. If a ``str``, the
505 format is "YYYYMMDDHHMMSS" or alternatively the number of seconds since the UNIX
506 epoch in text form; this is the same the RRSIG rdata's text form.
507 Values of type `int` or `float` are interpreted as seconds since the UNIX epoch.
508
509 *expiration*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the signature
510 expiration time. If ``None``, the expiration time will be the inception time plus
511 the value of the *lifetime* parameter. See the description of *inception* above
512 for how the various parameter types are interpreted.
513
514 *lifetime*, an ``int`` or ``None``, the signature lifetime in seconds. This
515 parameter is only meaningful if *expiration* is ``None``.
516
517 *verify*, a ``bool``. If set to ``True``, the signer will verify signatures
518 after they are created; the default is ``False``.
519
520 *policy*, a ``dns.dnssec.Policy`` or ``None``. If ``None``, the default policy,
521 ``dns.dnssec.default_policy`` is used; this policy defaults to that of RFC 8624.
522
523 *origin*, a ``dns.name.Name`` or ``None``. If ``None``, the default, then all
524 names in the rrset (including its owner name) must be absolute; otherwise the
525 specified origin will be used to make names absolute when signing.
526
527 *deterministic*, a ``bool``. If ``True``, the default, use deterministic
528 (reproducible) signatures when supported by the algorithm used for signing.
529 Currently, this only affects ECDSA.
530
531 Raises ``DeniedByPolicy`` if the signature is denied by policy.
532 """
533
534 if policy is None:
535 policy = default_policy
536 if not policy.ok_to_sign(dnskey):
537 raise DeniedByPolicy
538
539 if isinstance(rrset, tuple):
540 rdclass = rrset[1].rdclass
541 rdtype = rrset[1].rdtype
542 rrname = rrset[0]
543 original_ttl = rrset[1].ttl
544 else:
545 rdclass = rrset.rdclass
546 rdtype = rrset.rdtype
547 rrname = rrset.name
548 original_ttl = rrset.ttl
549
550 if inception is not None:
551 rrsig_inception = to_timestamp(inception)
552 else:
553 rrsig_inception = int(time.time())
554
555 if expiration is not None:
556 rrsig_expiration = to_timestamp(expiration)
557 elif lifetime is not None:
558 rrsig_expiration = rrsig_inception + lifetime
559 else:
560 raise ValueError("expiration or lifetime must be specified")
561
562 # Derelativize now because we need a correct labels length for the
563 # rrsig_template.
564 if origin is not None:
565 rrname = rrname.derelativize(origin)
566 labels = len(rrname) - 1
567
568 # Adjust labels appropriately for wildcards.
569 if rrname.is_wild():
570 labels -= 1
571
572 rrsig_template = RRSIG(
573 rdclass=rdclass,
574 rdtype=dns.rdatatype.RRSIG,
575 type_covered=rdtype,
576 algorithm=dnskey.algorithm,
577 labels=labels,
578 original_ttl=original_ttl,
579 expiration=rrsig_expiration,
580 inception=rrsig_inception,
581 key_tag=key_id(dnskey),
582 signer=signer,
583 signature=b"",
584 )
585
586 data = _make_rrsig_signature_data(rrset, rrsig_template, origin)
587
588 # pylint: disable=possibly-used-before-assignment
589 if isinstance(private_key, GenericPrivateKey):
590 signing_key = private_key
591 else:
592 try:
593 private_cls = get_algorithm_cls_from_dnskey(dnskey)
594 signing_key = private_cls(key=private_key)
595 except UnsupportedAlgorithm:
596 raise TypeError("Unsupported key algorithm")
597
598 signature = signing_key.sign(data, verify, deterministic)
599
600 return cast(RRSIG, rrsig_template.replace(signature=signature))
601
602
603 def _make_rrsig_signature_data(
604 rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset],
605 rrsig: RRSIG,
606 origin: dns.name.Name | None = None,
607 ) -> bytes:
608 """Create signature rdata.
609
610 *rrset*, the RRset to sign/validate. This can be a
611 ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``)
612 tuple.
613
614 *rrsig*, a ``dns.rdata.Rdata``, the signature to validate, or the
615 signature template used when signing.
616
617 *origin*, a ``dns.name.Name`` or ``None``, the origin to use for relative
618 names.
619
620 Raises ``UnsupportedAlgorithm`` if the algorithm is recognized by
621 dnspython but not implemented.
622 """
623
624 if isinstance(origin, str):
625 origin = dns.name.from_text(origin, dns.name.root)
626
627 signer = rrsig.signer
628 if not signer.is_absolute():
629 if origin is None:
630 raise ValidationFailure("relative RR name without an origin specified")
631 signer = signer.derelativize(origin)
632
633 # For convenience, allow the rrset to be specified as a (name,
634 # rdataset) tuple as well as a proper rrset
635 rrname, rdataset = _get_rrname_rdataset(rrset)
636
637 data = b""
638 wire = rrsig.to_wire(origin=signer)
639 assert wire is not None # for mypy
640 data += wire[:18]
641 data += rrsig.signer.to_digestable(signer)
642
643 # Derelativize the name before considering labels.
644 if not rrname.is_absolute():
645 if origin is None:
646 raise ValidationFailure("relative RR name without an origin specified")
647 rrname = rrname.derelativize(origin)
648
649 name_len = len(rrname)
650 if rrname.is_wild() and rrsig.labels != name_len - 2:
651 raise ValidationFailure("wild owner name has wrong label length")
652 if name_len - 1 < rrsig.labels:
653 raise ValidationFailure("owner name longer than RRSIG labels")
654 elif rrsig.labels < name_len - 1:
655 suffix = rrname.split(rrsig.labels + 1)[1]
656 rrname = dns.name.from_text("*", suffix)
657 rrnamebuf = rrname.to_digestable()
658 rrfixed = struct.pack("!HHI", rdataset.rdtype, rdataset.rdclass, rrsig.original_ttl)
659 rdatas = [rdata.to_digestable(origin) for rdata in rdataset]
660 for rdata in sorted(rdatas):
661 data += rrnamebuf
662 data += rrfixed
663 rrlen = struct.pack("!H", len(rdata))
664 data += rrlen
665 data += rdata
666
667 return data
668
669
670 def _make_dnskey(
671 public_key: PublicKey,
672 algorithm: int | str,
673 flags: int = Flag.ZONE,
674 protocol: int = 3,
675 ) -> DNSKEY:
676 """Convert a public key to DNSKEY Rdata
677
678 *public_key*, a ``PublicKey`` (``GenericPublicKey`` or
679 ``cryptography.hazmat.primitives.asymmetric``) to convert.
680
681 *algorithm*, a ``str`` or ``int`` specifying the DNSKEY algorithm.
682
683 *flags*: DNSKEY flags field as an integer.
684
685 *protocol*: DNSKEY protocol field as an integer.
686
687 Raises ``ValueError`` if the specified key algorithm parameters are not
688 unsupported, ``TypeError`` if the key type is unsupported,
689 `UnsupportedAlgorithm` if the algorithm is unknown and
690 `AlgorithmKeyMismatch` if the algorithm does not match the key type.
691
692 Return DNSKEY ``Rdata``.
693 """
694
695 algorithm = Algorithm.make(algorithm)
696
697 # pylint: disable=possibly-used-before-assignment
698 if isinstance(public_key, GenericPublicKey):
699 return public_key.to_dnskey(flags=flags, protocol=protocol)
700 else:
701 public_cls = get_algorithm_cls(algorithm).public_cls
702 return public_cls(key=public_key).to_dnskey(flags=flags, protocol=protocol)
703
704
705 def _make_cdnskey(
706 public_key: PublicKey,
707 algorithm: int | str,
708 flags: int = Flag.ZONE,
709 protocol: int = 3,
710 ) -> CDNSKEY:
711 """Convert a public key to CDNSKEY Rdata
712
713 *public_key*, the public key to convert, a
714 ``cryptography.hazmat.primitives.asymmetric`` public key class applicable
715 for DNSSEC.
716
717 *algorithm*, a ``str`` or ``int`` specifying the DNSKEY algorithm.
718
719 *flags*: DNSKEY flags field as an integer.
720
721 *protocol*: DNSKEY protocol field as an integer.
722
723 Raises ``ValueError`` if the specified key algorithm parameters are not
724 unsupported, ``TypeError`` if the key type is unsupported,
725 `UnsupportedAlgorithm` if the algorithm is unknown and
726 `AlgorithmKeyMismatch` if the algorithm does not match the key type.
727
728 Return CDNSKEY ``Rdata``.
729 """
730
731 dnskey = _make_dnskey(public_key, algorithm, flags, protocol)
732
733 return CDNSKEY(
734 rdclass=dnskey.rdclass,
735 rdtype=dns.rdatatype.CDNSKEY,
736 flags=dnskey.flags,
737 protocol=dnskey.protocol,
738 algorithm=dnskey.algorithm,
739 key=dnskey.key,
740 )
741
742
743 def nsec3_hash(
744 domain: dns.name.Name | str,
745 salt: str | bytes | None,
746 iterations: int,
747 algorithm: int | str,
748 ) -> str:
749 """
750 Calculate the NSEC3 hash, according to
751 https://tools.ietf.org/html/rfc5155#section-5
752
753 *domain*, a ``dns.name.Name`` or ``str``, the name to hash.
754
755 *salt*, a ``str``, ``bytes``, or ``None``, the hash salt. If a
756 string, it is decoded as a hex string.
757
758 *iterations*, an ``int``, the number of iterations.
759
760 *algorithm*, a ``str`` or ``int``, the hash algorithm.
761 The only defined algorithm is SHA1.
762
763 Returns a ``str``, the encoded NSEC3 hash.
764 """
765
766 b32_conversion = str.maketrans(
767 "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", "0123456789ABCDEFGHIJKLMNOPQRSTUV"
768 )
769
770 try:
771 if isinstance(algorithm, str):
772 algorithm = NSEC3Hash[algorithm.upper()]
773 except Exception:
774 raise ValueError("Wrong hash algorithm (only SHA1 is supported)")
775
776 if algorithm != NSEC3Hash.SHA1:
777 raise ValueError("Wrong hash algorithm (only SHA1 is supported)")
778
779 if salt is None:
780 salt_encoded = b""
781 elif isinstance(salt, str):
782 if len(salt) % 2 == 0:
783 salt_encoded = bytes.fromhex(salt)
784 else:
785 raise ValueError("Invalid salt length")
786 else:
787 salt_encoded = salt
788
789 if not isinstance(domain, dns.name.Name):
790 domain = dns.name.from_text(domain)
791 domain_encoded = domain.canonicalize().to_wire()
792 assert domain_encoded is not None
793
794 digest = hashlib.sha1(domain_encoded + salt_encoded).digest()
795 for _ in range(iterations):
796 digest = hashlib.sha1(digest + salt_encoded).digest()
797
798 output = base64.b32encode(digest).decode("utf-8")
799 output = output.translate(b32_conversion)
800
801 return output
802
803
804 def make_ds_rdataset(
805 rrset: dns.rrset.RRset | Tuple[dns.name.Name, dns.rdataset.Rdataset],
806 algorithms: Set[DSDigest | str],
807 origin: dns.name.Name | None = None,
808 ) -> dns.rdataset.Rdataset:
809 """Create a DS record from DNSKEY/CDNSKEY/CDS.
810
811 *rrset*, the RRset to create DS Rdataset for. This can be a
812 ``dns.rrset.RRset`` or a (``dns.name.Name``, ``dns.rdataset.Rdataset``)
813 tuple.
814
815 *algorithms*, a set of ``str`` or ``int`` specifying the hash algorithms.
816 The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case
817 does not matter for these strings. If the RRset is a CDS, only digest
818 algorithms matching algorithms are accepted.
819
820 *origin*, a ``dns.name.Name`` or ``None``. If `key` is a relative name,
821 then it will be made absolute using the specified origin.
822
823 Raises ``UnsupportedAlgorithm`` if any of the algorithms are unknown and
824 ``ValueError`` if the given RRset is not usable.
825
826 Returns a ``dns.rdataset.Rdataset``
827 """
828
829 rrname, rdataset = _get_rrname_rdataset(rrset)
830
831 if rdataset.rdtype not in (
832 dns.rdatatype.DNSKEY,
833 dns.rdatatype.CDNSKEY,
834 dns.rdatatype.CDS,
835 ):
836 raise ValueError("rrset not a DNSKEY/CDNSKEY/CDS")
837
838 _algorithms = set()
839 for algorithm in algorithms:
840 try:
841 if isinstance(algorithm, str):
842 algorithm = DSDigest[algorithm.upper()]
843 except Exception:
844 raise UnsupportedAlgorithm(f'unsupported algorithm "{algorithm}"')
845 _algorithms.add(algorithm)
846
847 if rdataset.rdtype == dns.rdatatype.CDS:
848 res = []
849 for rdata in cds_rdataset_to_ds_rdataset(rdataset):
850 if rdata.digest_type in _algorithms:
851 res.append(rdata)
852 if len(res) == 0:
853 raise ValueError("no acceptable CDS rdata found")
854 return dns.rdataset.from_rdata_list(rdataset.ttl, res)
855
856 res = []
857 for algorithm in _algorithms:
858 res.extend(dnskey_rdataset_to_cds_rdataset(rrname, rdataset, algorithm, origin))
859 return dns.rdataset.from_rdata_list(rdataset.ttl, res)
860
861
862 def cds_rdataset_to_ds_rdataset(
863 rdataset: dns.rdataset.Rdataset,
864 ) -> dns.rdataset.Rdataset:
865 """Create a CDS record from DS.
866
867 *rdataset*, a ``dns.rdataset.Rdataset``, to create DS Rdataset for.
868
869 Raises ``ValueError`` if the rdataset is not CDS.
870
871 Returns a ``dns.rdataset.Rdataset``
872 """
873
874 if rdataset.rdtype != dns.rdatatype.CDS:
875 raise ValueError("rdataset not a CDS")
876 res = []
877 for rdata in rdataset:
878 res.append(
879 CDS(
880 rdclass=rdata.rdclass,
881 rdtype=dns.rdatatype.DS,
882 key_tag=rdata.key_tag,
883 algorithm=rdata.algorithm,
884 digest_type=rdata.digest_type,
885 digest=rdata.digest,
886 )
887 )
888 return dns.rdataset.from_rdata_list(rdataset.ttl, res)
889
890
891 def dnskey_rdataset_to_cds_rdataset(
892 name: dns.name.Name | str,
893 rdataset: dns.rdataset.Rdataset,
894 algorithm: DSDigest | str,
895 origin: dns.name.Name | None = None,
896 ) -> dns.rdataset.Rdataset:
897 """Create a CDS record from DNSKEY/CDNSKEY.
898
899 *name*, a ``dns.name.Name`` or ``str``, the owner name of the CDS record.
900
901 *rdataset*, a ``dns.rdataset.Rdataset``, to create DS Rdataset for.
902
903 *algorithm*, a ``str`` or ``int`` specifying the hash algorithm.
904 The currently supported hashes are "SHA1", "SHA256", and "SHA384". Case
905 does not matter for these strings.
906
907 *origin*, a ``dns.name.Name`` or ``None``. If `key` is a relative name,
908 then it will be made absolute using the specified origin.
909
910 Raises ``UnsupportedAlgorithm`` if the algorithm is unknown or
911 ``ValueError`` if the rdataset is not DNSKEY/CDNSKEY.
912
913 Returns a ``dns.rdataset.Rdataset``
914 """
915
916 if rdataset.rdtype not in (dns.rdatatype.DNSKEY, dns.rdatatype.CDNSKEY):
917 raise ValueError("rdataset not a DNSKEY/CDNSKEY")
918 res = []
919 for rdata in rdataset:
920 res.append(make_cds(name, rdata, algorithm, origin))
921 return dns.rdataset.from_rdata_list(rdataset.ttl, res)
922
923
924 def dnskey_rdataset_to_cdnskey_rdataset(
925 rdataset: dns.rdataset.Rdataset,
926 ) -> dns.rdataset.Rdataset:
927 """Create a CDNSKEY record from DNSKEY.
928
929 *rdataset*, a ``dns.rdataset.Rdataset``, to create CDNSKEY Rdataset for.
930
931 Returns a ``dns.rdataset.Rdataset``
932 """
933
934 if rdataset.rdtype != dns.rdatatype.DNSKEY:
935 raise ValueError("rdataset not a DNSKEY")
936 res = []
937 for rdata in rdataset:
938 res.append(
939 CDNSKEY(
940 rdclass=rdataset.rdclass,
941 rdtype=rdataset.rdtype,
942 flags=rdata.flags,
943 protocol=rdata.protocol,
944 algorithm=rdata.algorithm,
945 key=rdata.key,
946 )
947 )
948 return dns.rdataset.from_rdata_list(rdataset.ttl, res)
949
950
951 def default_rrset_signer(
952 txn: dns.transaction.Transaction,
953 rrset: dns.rrset.RRset,
954 signer: dns.name.Name,
955 ksks: List[Tuple[PrivateKey, DNSKEY]],
956 zsks: List[Tuple[PrivateKey, DNSKEY]],
957 inception: datetime | str | int | float | None = None,
958 expiration: datetime | str | int | float | None = None,
959 lifetime: int | None = None,
960 policy: Policy | None = None,
961 origin: dns.name.Name | None = None,
962 deterministic: bool = True,
963 ) -> None:
964 """Default RRset signer"""
965
966 if rrset.rdtype in set(
967 [
968 dns.rdatatype.RdataType.DNSKEY,
969 dns.rdatatype.RdataType.CDS,
970 dns.rdatatype.RdataType.CDNSKEY,
971 ]
972 ):
973 keys = ksks
974 else:
975 keys = zsks
976
977 for private_key, dnskey in keys:
978 rrsig = sign(
979 rrset=rrset,
980 private_key=private_key,
981 dnskey=dnskey,
982 inception=inception,
983 expiration=expiration,
984 lifetime=lifetime,
985 signer=signer,
986 policy=policy,
987 origin=origin,
988 deterministic=deterministic,
989 )
990 txn.add(rrset.name, rrset.ttl, rrsig)
991
992
993 def sign_zone(
994 zone: dns.zone.Zone,
995 txn: dns.transaction.Transaction | None = None,
996 keys: List[Tuple[PrivateKey, DNSKEY]] | None = None,
997 add_dnskey: bool = True,
998 dnskey_ttl: int | None = None,
999 inception: datetime | str | int | float | None = None,
1000 expiration: datetime | str | int | float | None = None,
1001 lifetime: int | None = None,
1002 nsec3: NSEC3PARAM | None = None,
1003 rrset_signer: RRsetSigner | None = None,
1004 policy: Policy | None = None,
1005 deterministic: bool = True,
1006 ) -> None:
1007 """Sign zone.
1008
1009 *zone*, a ``dns.zone.Zone``, the zone to sign.
1010
1011 *txn*, a ``dns.transaction.Transaction``, an optional transaction to use for
1012 signing.
1013
1014 *keys*, a list of (``PrivateKey``, ``DNSKEY``) tuples, to use for signing. KSK/ZSK
1015 roles are assigned automatically if the SEP flag is used, otherwise all RRsets are
1016 signed by all keys.
1017
1018 *add_dnskey*, a ``bool``. If ``True``, the default, all specified DNSKEYs are
1019 automatically added to the zone on signing.
1020
1021 *dnskey_ttl*, a``int``, specifies the TTL for DNSKEY RRs. If not specified the TTL
1022 of the existing DNSKEY RRset used or the TTL of the SOA RRset.
1023
1024 *inception*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the signature
1025 inception time. If ``None``, the current time is used. If a ``str``, the format is
1026 "YYYYMMDDHHMMSS" or alternatively the number of seconds since the UNIX epoch in text
1027 form; this is the same the RRSIG rdata's text form. Values of type `int` or `float`
1028 are interpreted as seconds since the UNIX epoch.
1029
1030 *expiration*, a ``datetime``, ``str``, ``int``, ``float`` or ``None``, the signature
1031 expiration time. If ``None``, the expiration time will be the inception time plus
1032 the value of the *lifetime* parameter. See the description of *inception* above for
1033 how the various parameter types are interpreted.
1034
1035 *lifetime*, an ``int`` or ``None``, the signature lifetime in seconds. This
1036 parameter is only meaningful if *expiration* is ``None``.
1037
1038 *nsec3*, a ``NSEC3PARAM`` Rdata, configures signing using NSEC3. Not yet
1039 implemented.
1040
1041 *rrset_signer*, a ``Callable``, an optional function for signing RRsets. The
1042 function requires two arguments: transaction and RRset. If the not specified,
1043 ``dns.dnssec.default_rrset_signer`` will be used.
1044
1045 *deterministic*, a ``bool``. If ``True``, the default, use deterministic
1046 (reproducible) signatures when supported by the algorithm used for signing.
1047 Currently, this only affects ECDSA.
1048
1049 Returns ``None``.
1050 """
1051
1052 ksks = []
1053 zsks = []
1054
1055 # if we have both KSKs and ZSKs, split by SEP flag. if not, sign all
1056 # records with all keys
1057 if keys:
1058 for key in keys:
1059 if key[1].flags & Flag.SEP:
1060 ksks.append(key)
1061 else:
1062 zsks.append(key)
1063 if not ksks:
1064 ksks = keys
1065 if not zsks:
1066 zsks = keys
1067 else:
1068 keys = []
1069
1070 if txn:
1071 cm: contextlib.AbstractContextManager = contextlib.nullcontext(txn)
1072 else:
1073 cm = zone.writer()
1074
1075 if zone.origin is None:
1076 raise ValueError("no zone origin")
1077
1078 with cm as _txn:
1079 if add_dnskey:
1080 if dnskey_ttl is None:
1081 dnskey = _txn.get(zone.origin, dns.rdatatype.DNSKEY)
1082 if dnskey:
1083 dnskey_ttl = dnskey.ttl
1084 else:
1085 soa = _txn.get(zone.origin, dns.rdatatype.SOA)
1086 dnskey_ttl = soa.ttl
1087 for _, dnskey in keys:
1088 _txn.add(zone.origin, dnskey_ttl, dnskey)
1089
1090 if nsec3:
1091 raise NotImplementedError("Signing with NSEC3 not yet implemented")
1092 else:
1093 _rrset_signer = rrset_signer or functools.partial(
1094 default_rrset_signer,
1095 signer=zone.origin,
1096 ksks=ksks,
1097 zsks=zsks,
1098 inception=inception,
1099 expiration=expiration,
1100 lifetime=lifetime,
1101 policy=policy,
1102 origin=zone.origin,
1103 deterministic=deterministic,
1104 )
1105 return _sign_zone_nsec(zone, _txn, _rrset_signer)
1106
1107
1108 def _sign_zone_nsec(
1109 zone: dns.zone.Zone,
1110 txn: dns.transaction.Transaction,
1111 rrset_signer: RRsetSigner | None = None,
1112 ) -> None:
1113 """NSEC zone signer"""
1114
1115 def _txn_add_nsec(
1116 txn: dns.transaction.Transaction,
1117 name: dns.name.Name,
1118 next_secure: dns.name.Name | None,
1119 rdclass: dns.rdataclass.RdataClass,
1120 ttl: int,
1121 rrset_signer: RRsetSigner | None = None,
1122 ) -> None:
1123 """NSEC zone signer helper"""
1124 mandatory_types = set(
1125 [dns.rdatatype.RdataType.RRSIG, dns.rdatatype.RdataType.NSEC]
1126 )
1127 node = txn.get_node(name)
1128 if node and next_secure:
1129 types = (
1130 set([rdataset.rdtype for rdataset in node.rdatasets]) | mandatory_types
1131 )
1132 windows = Bitmap.from_rdtypes(list(types))
1133 rrset = dns.rrset.from_rdata(
1134 name,
1135 ttl,
1136 NSEC(
1137 rdclass=rdclass,
1138 rdtype=dns.rdatatype.RdataType.NSEC,
1139 next=next_secure,
1140 windows=windows,
1141 ),
1142 )
1143 txn.add(rrset)
1144 if rrset_signer:
1145 rrset_signer(txn, rrset)
1146
1147 rrsig_ttl = zone.get_soa(txn).minimum
1148 delegation = None
1149 last_secure = None
1150
1151 for name in sorted(txn.iterate_names()):
1152 if delegation and name.is_subdomain(delegation):
1153 # names below delegations are not secure
1154 continue
1155 elif txn.get(name, dns.rdatatype.NS) and name != zone.origin:
1156 # inside delegation
1157 delegation = name
1158 else:
1159 # outside delegation
1160 delegation = None
1161
1162 if rrset_signer:
1163 node = txn.get_node(name)
1164 if node:
1165 for rdataset in node.rdatasets:
1166 if rdataset.rdtype == dns.rdatatype.RRSIG:
1167 # do not sign RRSIGs
1168 continue
1169 elif delegation and rdataset.rdtype != dns.rdatatype.DS:
1170 # do not sign delegations except DS records
1171 continue
1172 else:
1173 rrset = dns.rrset.from_rdata(name, rdataset.ttl, *rdataset)
1174 rrset_signer(txn, rrset)
1175
1176 # We need "is not None" as the empty name is False because its length is 0.
1177 if last_secure is not None:
1178 _txn_add_nsec(txn, last_secure, name, zone.rdclass, rrsig_ttl, rrset_signer)
1179 last_secure = name
1180
1181 if last_secure:
1182 _txn_add_nsec(
1183 txn, last_secure, zone.origin, zone.rdclass, rrsig_ttl, rrset_signer
1184 )
1185
1186
1187 def _need_pyca(*args, **kwargs):
1188 raise ImportError(
1189 "DNSSEC validation requires python cryptography"
1190 ) # pragma: no cover
1191
1192
1193 if dns._features.have("dnssec"):
1194 from cryptography.exceptions import InvalidSignature
1195 from cryptography.hazmat.primitives.asymmetric import ec # pylint: disable=W0611
1196 from cryptography.hazmat.primitives.asymmetric import ed448 # pylint: disable=W0611
1197 from cryptography.hazmat.primitives.asymmetric import rsa # pylint: disable=W0611
1198 from cryptography.hazmat.primitives.asymmetric import ( # pylint: disable=W0611
1199 ed25519,
1200 )
1201
1202 from dns.dnssecalgs import ( # pylint: disable=C0412
1203 get_algorithm_cls,
1204 get_algorithm_cls_from_dnskey,
1205 )
1206 from dns.dnssecalgs.base import GenericPrivateKey, GenericPublicKey
1207
1208 validate = _validate # type: ignore
1209 validate_rrsig = _validate_rrsig # type: ignore
1210 sign = _sign
1211 make_dnskey = _make_dnskey
1212 make_cdnskey = _make_cdnskey
1213 _have_pyca = True
1214 else: # pragma: no cover
1215 validate = _need_pyca
1216 validate_rrsig = _need_pyca
1217 sign = _need_pyca
1218 make_dnskey = _need_pyca
1219 make_cdnskey = _need_pyca
1220 _have_pyca = False
1221
1222 ### BEGIN generated Algorithm constants
1223
1224 RSAMD5 = Algorithm.RSAMD5
1225 DH = Algorithm.DH
1226 DSA = Algorithm.DSA
1227 ECC = Algorithm.ECC
1228 RSASHA1 = Algorithm.RSASHA1
1229 DSANSEC3SHA1 = Algorithm.DSANSEC3SHA1
1230 RSASHA1NSEC3SHA1 = Algorithm.RSASHA1NSEC3SHA1
1231 RSASHA256 = Algorithm.RSASHA256
1232 RSASHA512 = Algorithm.RSASHA512
1233 ECCGOST = Algorithm.ECCGOST
1234 ECDSAP256SHA256 = Algorithm.ECDSAP256SHA256
1235 ECDSAP384SHA384 = Algorithm.ECDSAP384SHA384
1236 ED25519 = Algorithm.ED25519
1237 ED448 = Algorithm.ED448
1238 INDIRECT = Algorithm.INDIRECT
1239 PRIVATEDNS = Algorithm.PRIVATEDNS
1240 PRIVATEOID = Algorithm.PRIVATEOID
1241
1242 ### END generated Algorithm constants