dnssec.py 41 KB

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