dnssec.py 40 KB

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