zone.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2003-2007, 2009-2011 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. """DNS Zones."""
  17. import contextlib
  18. import hashlib
  19. import io
  20. import os
  21. import struct
  22. import dns.exception
  23. import dns.immutable
  24. import dns.name
  25. import dns.node
  26. import dns.rdataclass
  27. import dns.rdatatype
  28. import dns.rdata
  29. import dns.rdtypes.ANY.SOA
  30. import dns.rdtypes.ANY.ZONEMD
  31. import dns.rrset
  32. import dns.tokenizer
  33. import dns.transaction
  34. import dns.ttl
  35. import dns.grange
  36. import dns.zonefile
  37. class BadZone(dns.exception.DNSException):
  38. """The DNS zone is malformed."""
  39. class NoSOA(BadZone):
  40. """The DNS zone has no SOA RR at its origin."""
  41. class NoNS(BadZone):
  42. """The DNS zone has no NS RRset at its origin."""
  43. class UnknownOrigin(BadZone):
  44. """The DNS zone's origin is unknown."""
  45. class UnsupportedDigestScheme(dns.exception.DNSException):
  46. """The zone digest's scheme is unsupported."""
  47. class UnsupportedDigestHashAlgorithm(dns.exception.DNSException):
  48. """The zone digest's origin is unsupported."""
  49. class NoDigest(dns.exception.DNSException):
  50. """The DNS zone has no ZONEMD RRset at its origin."""
  51. class DigestVerificationFailure(dns.exception.DNSException):
  52. """The ZONEMD digest failed to verify."""
  53. class DigestScheme(dns.enum.IntEnum):
  54. """ZONEMD Scheme"""
  55. SIMPLE = 1
  56. @classmethod
  57. def _maximum(cls):
  58. return 255
  59. class DigestHashAlgorithm(dns.enum.IntEnum):
  60. """ZONEMD Hash Algorithm"""
  61. SHA384 = 1
  62. SHA512 = 2
  63. @classmethod
  64. def _maximum(cls):
  65. return 255
  66. _digest_hashers = {
  67. DigestHashAlgorithm.SHA384: hashlib.sha384,
  68. DigestHashAlgorithm.SHA512: hashlib.sha512,
  69. }
  70. class Zone(dns.transaction.TransactionManager):
  71. """A DNS zone.
  72. A ``Zone`` is a mapping from names to nodes. The zone object may be
  73. treated like a Python dictionary, e.g. ``zone[name]`` will retrieve
  74. the node associated with that name. The *name* may be a
  75. ``dns.name.Name object``, or it may be a string. In either case,
  76. if the name is relative it is treated as relative to the origin of
  77. the zone.
  78. """
  79. node_factory = dns.node.Node
  80. __slots__ = ['rdclass', 'origin', 'nodes', 'relativize']
  81. def __init__(self, origin, rdclass=dns.rdataclass.IN, relativize=True):
  82. """Initialize a zone object.
  83. *origin* is the origin of the zone. It may be a ``dns.name.Name``,
  84. a ``str``, or ``None``. If ``None``, then the zone's origin will
  85. be set by the first ``$ORIGIN`` line in a zone file.
  86. *rdclass*, an ``int``, the zone's rdata class; the default is class IN.
  87. *relativize*, a ``bool``, determine's whether domain names are
  88. relativized to the zone's origin. The default is ``True``.
  89. """
  90. if origin is not None:
  91. if isinstance(origin, str):
  92. origin = dns.name.from_text(origin)
  93. elif not isinstance(origin, dns.name.Name):
  94. raise ValueError("origin parameter must be convertible to a "
  95. "DNS name")
  96. if not origin.is_absolute():
  97. raise ValueError("origin parameter must be an absolute name")
  98. self.origin = origin
  99. self.rdclass = rdclass
  100. self.nodes = {}
  101. self.relativize = relativize
  102. def __eq__(self, other):
  103. """Two zones are equal if they have the same origin, class, and
  104. nodes.
  105. Returns a ``bool``.
  106. """
  107. if not isinstance(other, Zone):
  108. return False
  109. if self.rdclass != other.rdclass or \
  110. self.origin != other.origin or \
  111. self.nodes != other.nodes:
  112. return False
  113. return True
  114. def __ne__(self, other):
  115. """Are two zones not equal?
  116. Returns a ``bool``.
  117. """
  118. return not self.__eq__(other)
  119. def _validate_name(self, name):
  120. if isinstance(name, str):
  121. name = dns.name.from_text(name, None)
  122. elif not isinstance(name, dns.name.Name):
  123. raise KeyError("name parameter must be convertible to a DNS name")
  124. if name.is_absolute():
  125. if not name.is_subdomain(self.origin):
  126. raise KeyError(
  127. "name parameter must be a subdomain of the zone origin")
  128. if self.relativize:
  129. name = name.relativize(self.origin)
  130. elif not self.relativize:
  131. # We have a relative name in a non-relative zone, so derelativize.
  132. if self.origin is None:
  133. raise KeyError('no zone origin is defined')
  134. name = name.derelativize(self.origin)
  135. return name
  136. def __getitem__(self, key):
  137. key = self._validate_name(key)
  138. return self.nodes[key]
  139. def __setitem__(self, key, value):
  140. key = self._validate_name(key)
  141. self.nodes[key] = value
  142. def __delitem__(self, key):
  143. key = self._validate_name(key)
  144. del self.nodes[key]
  145. def __iter__(self):
  146. return self.nodes.__iter__()
  147. def keys(self):
  148. return self.nodes.keys()
  149. def values(self):
  150. return self.nodes.values()
  151. def items(self):
  152. return self.nodes.items()
  153. def get(self, key):
  154. key = self._validate_name(key)
  155. return self.nodes.get(key)
  156. def __contains__(self, key):
  157. key = self._validate_name(key)
  158. return key in self.nodes
  159. def find_node(self, name, create=False):
  160. """Find a node in the zone, possibly creating it.
  161. *name*: the name of the node to find.
  162. The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
  163. name must be a subdomain of the zone's origin. If ``zone.relativize``
  164. is ``True``, then the name will be relativized.
  165. *create*, a ``bool``. If true, the node will be created if it does
  166. not exist.
  167. Raises ``KeyError`` if the name is not known and create was
  168. not specified, or if the name was not a subdomain of the origin.
  169. Returns a ``dns.node.Node``.
  170. """
  171. name = self._validate_name(name)
  172. node = self.nodes.get(name)
  173. if node is None:
  174. if not create:
  175. raise KeyError
  176. node = self.node_factory()
  177. self.nodes[name] = node
  178. return node
  179. def get_node(self, name, create=False):
  180. """Get a node in the zone, possibly creating it.
  181. This method is like ``find_node()``, except it returns None instead
  182. of raising an exception if the node does not exist and creation
  183. has not been requested.
  184. *name*: the name of the node to find.
  185. The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
  186. name must be a subdomain of the zone's origin. If ``zone.relativize``
  187. is ``True``, then the name will be relativized.
  188. *create*, a ``bool``. If true, the node will be created if it does
  189. not exist.
  190. Raises ``KeyError`` if the name is not known and create was
  191. not specified, or if the name was not a subdomain of the origin.
  192. Returns a ``dns.node.Node`` or ``None``.
  193. """
  194. try:
  195. node = self.find_node(name, create)
  196. except KeyError:
  197. node = None
  198. return node
  199. def delete_node(self, name):
  200. """Delete the specified node if it exists.
  201. *name*: the name of the node to find.
  202. The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
  203. name must be a subdomain of the zone's origin. If ``zone.relativize``
  204. is ``True``, then the name will be relativized.
  205. It is not an error if the node does not exist.
  206. """
  207. name = self._validate_name(name)
  208. if name in self.nodes:
  209. del self.nodes[name]
  210. def find_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE,
  211. create=False):
  212. """Look for an rdataset with the specified name and type in the zone,
  213. and return an rdataset encapsulating it.
  214. The rdataset returned is not a copy; changes to it will change
  215. the zone.
  216. KeyError is raised if the name or type are not found.
  217. *name*: the name of the node to find.
  218. The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
  219. name must be a subdomain of the zone's origin. If ``zone.relativize``
  220. is ``True``, then the name will be relativized.
  221. *rdtype*, an ``int`` or ``str``, the rdata type desired.
  222. *covers*, an ``int`` or ``str`` or ``None``, the covered type.
  223. Usually this value is ``dns.rdatatype.NONE``, but if the
  224. rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
  225. then the covers value will be the rdata type the SIG/RRSIG
  226. covers. The library treats the SIG and RRSIG types as if they
  227. were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
  228. This makes RRSIGs much easier to work with than if RRSIGs
  229. covering different rdata types were aggregated into a single
  230. RRSIG rdataset.
  231. *create*, a ``bool``. If true, the node will be created if it does
  232. not exist.
  233. Raises ``KeyError`` if the name is not known and create was
  234. not specified, or if the name was not a subdomain of the origin.
  235. Returns a ``dns.rdataset.Rdataset``.
  236. """
  237. name = self._validate_name(name)
  238. rdtype = dns.rdatatype.RdataType.make(rdtype)
  239. if covers is not None:
  240. covers = dns.rdatatype.RdataType.make(covers)
  241. node = self.find_node(name, create)
  242. return node.find_rdataset(self.rdclass, rdtype, covers, create)
  243. def get_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE,
  244. create=False):
  245. """Look for an rdataset with the specified name and type in the zone.
  246. This method is like ``find_rdataset()``, except it returns None instead
  247. of raising an exception if the rdataset does not exist and creation
  248. has not been requested.
  249. The rdataset returned is not a copy; changes to it will change
  250. the zone.
  251. *name*: the name of the node to find.
  252. The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
  253. name must be a subdomain of the zone's origin. If ``zone.relativize``
  254. is ``True``, then the name will be relativized.
  255. *rdtype*, an ``int`` or ``str``, the rdata type desired.
  256. *covers*, an ``int`` or ``str`` or ``None``, the covered type.
  257. Usually this value is ``dns.rdatatype.NONE``, but if the
  258. rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
  259. then the covers value will be the rdata type the SIG/RRSIG
  260. covers. The library treats the SIG and RRSIG types as if they
  261. were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
  262. This makes RRSIGs much easier to work with than if RRSIGs
  263. covering different rdata types were aggregated into a single
  264. RRSIG rdataset.
  265. *create*, a ``bool``. If true, the node will be created if it does
  266. not exist.
  267. Raises ``KeyError`` if the name is not known and create was
  268. not specified, or if the name was not a subdomain of the origin.
  269. Returns a ``dns.rdataset.Rdataset`` or ``None``.
  270. """
  271. try:
  272. rdataset = self.find_rdataset(name, rdtype, covers, create)
  273. except KeyError:
  274. rdataset = None
  275. return rdataset
  276. def delete_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE):
  277. """Delete the rdataset matching *rdtype* and *covers*, if it
  278. exists at the node specified by *name*.
  279. It is not an error if the node does not exist, or if there is no
  280. matching rdataset at the node.
  281. If the node has no rdatasets after the deletion, it will itself
  282. be deleted.
  283. *name*: the name of the node to find.
  284. The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
  285. name must be a subdomain of the zone's origin. If ``zone.relativize``
  286. is ``True``, then the name will be relativized.
  287. *rdtype*, an ``int`` or ``str``, the rdata type desired.
  288. *covers*, an ``int`` or ``str`` or ``None``, the covered type.
  289. Usually this value is ``dns.rdatatype.NONE``, but if the
  290. rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
  291. then the covers value will be the rdata type the SIG/RRSIG
  292. covers. The library treats the SIG and RRSIG types as if they
  293. were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
  294. This makes RRSIGs much easier to work with than if RRSIGs
  295. covering different rdata types were aggregated into a single
  296. RRSIG rdataset.
  297. """
  298. name = self._validate_name(name)
  299. rdtype = dns.rdatatype.RdataType.make(rdtype)
  300. if covers is not None:
  301. covers = dns.rdatatype.RdataType.make(covers)
  302. node = self.get_node(name)
  303. if node is not None:
  304. node.delete_rdataset(self.rdclass, rdtype, covers)
  305. if len(node) == 0:
  306. self.delete_node(name)
  307. def replace_rdataset(self, name, replacement):
  308. """Replace an rdataset at name.
  309. It is not an error if there is no rdataset matching I{replacement}.
  310. Ownership of the *replacement* object is transferred to the zone;
  311. in other words, this method does not store a copy of *replacement*
  312. at the node, it stores *replacement* itself.
  313. If the node does not exist, it is created.
  314. *name*: the name of the node to find.
  315. The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
  316. name must be a subdomain of the zone's origin. If ``zone.relativize``
  317. is ``True``, then the name will be relativized.
  318. *replacement*, a ``dns.rdataset.Rdataset``, the replacement rdataset.
  319. """
  320. if replacement.rdclass != self.rdclass:
  321. raise ValueError('replacement.rdclass != zone.rdclass')
  322. node = self.find_node(name, True)
  323. node.replace_rdataset(replacement)
  324. def find_rrset(self, name, rdtype, covers=dns.rdatatype.NONE):
  325. """Look for an rdataset with the specified name and type in the zone,
  326. and return an RRset encapsulating it.
  327. This method is less efficient than the similar
  328. ``find_rdataset()`` because it creates an RRset instead of
  329. returning the matching rdataset. It may be more convenient
  330. for some uses since it returns an object which binds the owner
  331. name to the rdataset.
  332. This method may not be used to create new nodes or rdatasets;
  333. use ``find_rdataset`` instead.
  334. *name*: the name of the node to find.
  335. The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
  336. name must be a subdomain of the zone's origin. If ``zone.relativize``
  337. is ``True``, then the name will be relativized.
  338. *rdtype*, an ``int`` or ``str``, the rdata type desired.
  339. *covers*, an ``int`` or ``str`` or ``None``, the covered type.
  340. Usually this value is ``dns.rdatatype.NONE``, but if the
  341. rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
  342. then the covers value will be the rdata type the SIG/RRSIG
  343. covers. The library treats the SIG and RRSIG types as if they
  344. were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
  345. This makes RRSIGs much easier to work with than if RRSIGs
  346. covering different rdata types were aggregated into a single
  347. RRSIG rdataset.
  348. *create*, a ``bool``. If true, the node will be created if it does
  349. not exist.
  350. Raises ``KeyError`` if the name is not known and create was
  351. not specified, or if the name was not a subdomain of the origin.
  352. Returns a ``dns.rrset.RRset`` or ``None``.
  353. """
  354. name = self._validate_name(name)
  355. rdtype = dns.rdatatype.RdataType.make(rdtype)
  356. if covers is not None:
  357. covers = dns.rdatatype.RdataType.make(covers)
  358. rdataset = self.nodes[name].find_rdataset(self.rdclass, rdtype, covers)
  359. rrset = dns.rrset.RRset(name, self.rdclass, rdtype, covers)
  360. rrset.update(rdataset)
  361. return rrset
  362. def get_rrset(self, name, rdtype, covers=dns.rdatatype.NONE):
  363. """Look for an rdataset with the specified name and type in the zone,
  364. and return an RRset encapsulating it.
  365. This method is less efficient than the similar ``get_rdataset()``
  366. because it creates an RRset instead of returning the matching
  367. rdataset. It may be more convenient for some uses since it
  368. returns an object which binds the owner name to the rdataset.
  369. This method may not be used to create new nodes or rdatasets;
  370. use ``get_rdataset()`` instead.
  371. *name*: the name of the node to find.
  372. The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
  373. name must be a subdomain of the zone's origin. If ``zone.relativize``
  374. is ``True``, then the name will be relativized.
  375. *rdtype*, an ``int`` or ``str``, the rdata type desired.
  376. *covers*, an ``int`` or ``str`` or ``None``, the covered type.
  377. Usually this value is ``dns.rdatatype.NONE``, but if the
  378. rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
  379. then the covers value will be the rdata type the SIG/RRSIG
  380. covers. The library treats the SIG and RRSIG types as if they
  381. were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
  382. This makes RRSIGs much easier to work with than if RRSIGs
  383. covering different rdata types were aggregated into a single
  384. RRSIG rdataset.
  385. *create*, a ``bool``. If true, the node will be created if it does
  386. not exist.
  387. Raises ``KeyError`` if the name is not known and create was
  388. not specified, or if the name was not a subdomain of the origin.
  389. Returns a ``dns.rrset.RRset`` or ``None``.
  390. """
  391. try:
  392. rrset = self.find_rrset(name, rdtype, covers)
  393. except KeyError:
  394. rrset = None
  395. return rrset
  396. def iterate_rdatasets(self, rdtype=dns.rdatatype.ANY,
  397. covers=dns.rdatatype.NONE):
  398. """Return a generator which yields (name, rdataset) tuples for
  399. all rdatasets in the zone which have the specified *rdtype*
  400. and *covers*. If *rdtype* is ``dns.rdatatype.ANY``, the default,
  401. then all rdatasets will be matched.
  402. *rdtype*, an ``int`` or ``str``, the rdata type desired.
  403. *covers*, an ``int`` or ``str`` or ``None``, the covered type.
  404. Usually this value is ``dns.rdatatype.NONE``, but if the
  405. rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
  406. then the covers value will be the rdata type the SIG/RRSIG
  407. covers. The library treats the SIG and RRSIG types as if they
  408. were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
  409. This makes RRSIGs much easier to work with than if RRSIGs
  410. covering different rdata types were aggregated into a single
  411. RRSIG rdataset.
  412. """
  413. rdtype = dns.rdatatype.RdataType.make(rdtype)
  414. if covers is not None:
  415. covers = dns.rdatatype.RdataType.make(covers)
  416. for (name, node) in self.items():
  417. for rds in node:
  418. if rdtype == dns.rdatatype.ANY or \
  419. (rds.rdtype == rdtype and rds.covers == covers):
  420. yield (name, rds)
  421. def iterate_rdatas(self, rdtype=dns.rdatatype.ANY,
  422. covers=dns.rdatatype.NONE):
  423. """Return a generator which yields (name, ttl, rdata) tuples for
  424. all rdatas in the zone which have the specified *rdtype*
  425. and *covers*. If *rdtype* is ``dns.rdatatype.ANY``, the default,
  426. then all rdatas will be matched.
  427. *rdtype*, an ``int`` or ``str``, the rdata type desired.
  428. *covers*, an ``int`` or ``str`` or ``None``, the covered type.
  429. Usually this value is ``dns.rdatatype.NONE``, but if the
  430. rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
  431. then the covers value will be the rdata type the SIG/RRSIG
  432. covers. The library treats the SIG and RRSIG types as if they
  433. were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
  434. This makes RRSIGs much easier to work with than if RRSIGs
  435. covering different rdata types were aggregated into a single
  436. RRSIG rdataset.
  437. """
  438. rdtype = dns.rdatatype.RdataType.make(rdtype)
  439. if covers is not None:
  440. covers = dns.rdatatype.RdataType.make(covers)
  441. for (name, node) in self.items():
  442. for rds in node:
  443. if rdtype == dns.rdatatype.ANY or \
  444. (rds.rdtype == rdtype and rds.covers == covers):
  445. for rdata in rds:
  446. yield (name, rds.ttl, rdata)
  447. def to_file(self, f, sorted=True, relativize=True, nl=None,
  448. want_comments=False, want_origin=False):
  449. """Write a zone to a file.
  450. *f*, a file or `str`. If *f* is a string, it is treated
  451. as the name of a file to open.
  452. *sorted*, a ``bool``. If True, the default, then the file
  453. will be written with the names sorted in DNSSEC order from
  454. least to greatest. Otherwise the names will be written in
  455. whatever order they happen to have in the zone's dictionary.
  456. *relativize*, a ``bool``. If True, the default, then domain
  457. names in the output will be relativized to the zone's origin
  458. if possible.
  459. *nl*, a ``str`` or None. The end of line string. If not
  460. ``None``, the output will use the platform's native
  461. end-of-line marker (i.e. LF on POSIX, CRLF on Windows).
  462. *want_comments*, a ``bool``. If ``True``, emit end-of-line comments
  463. as part of writing the file. If ``False``, the default, do not
  464. emit them.
  465. *want_origin*, a ``bool``. If ``True``, emit a $ORIGIN line at
  466. the start of the file. If ``False``, the default, do not emit
  467. one.
  468. """
  469. with contextlib.ExitStack() as stack:
  470. if isinstance(f, str):
  471. f = stack.enter_context(open(f, 'wb'))
  472. # must be in this way, f.encoding may contain None, or even
  473. # attribute may not be there
  474. file_enc = getattr(f, 'encoding', None)
  475. if file_enc is None:
  476. file_enc = 'utf-8'
  477. if nl is None:
  478. # binary mode, '\n' is not enough
  479. nl_b = os.linesep.encode(file_enc)
  480. nl = '\n'
  481. elif isinstance(nl, str):
  482. nl_b = nl.encode(file_enc)
  483. else:
  484. nl_b = nl
  485. nl = nl.decode()
  486. if want_origin:
  487. l = '$ORIGIN ' + self.origin.to_text()
  488. l_b = l.encode(file_enc)
  489. try:
  490. f.write(l_b)
  491. f.write(nl_b)
  492. except TypeError: # textual mode
  493. f.write(l)
  494. f.write(nl)
  495. if sorted:
  496. names = list(self.keys())
  497. names.sort()
  498. else:
  499. names = self.keys()
  500. for n in names:
  501. l = self[n].to_text(n, origin=self.origin,
  502. relativize=relativize,
  503. want_comments=want_comments)
  504. l_b = l.encode(file_enc)
  505. try:
  506. f.write(l_b)
  507. f.write(nl_b)
  508. except TypeError: # textual mode
  509. f.write(l)
  510. f.write(nl)
  511. def to_text(self, sorted=True, relativize=True, nl=None,
  512. want_comments=False, want_origin=False):
  513. """Return a zone's text as though it were written to a file.
  514. *sorted*, a ``bool``. If True, the default, then the file
  515. will be written with the names sorted in DNSSEC order from
  516. least to greatest. Otherwise the names will be written in
  517. whatever order they happen to have in the zone's dictionary.
  518. *relativize*, a ``bool``. If True, the default, then domain
  519. names in the output will be relativized to the zone's origin
  520. if possible.
  521. *nl*, a ``str`` or None. The end of line string. If not
  522. ``None``, the output will use the platform's native
  523. end-of-line marker (i.e. LF on POSIX, CRLF on Windows).
  524. *want_comments*, a ``bool``. If ``True``, emit end-of-line comments
  525. as part of writing the file. If ``False``, the default, do not
  526. emit them.
  527. *want_origin*, a ``bool``. If ``True``, emit a $ORIGIN line at
  528. the start of the output. If ``False``, the default, do not emit
  529. one.
  530. Returns a ``str``.
  531. """
  532. temp_buffer = io.StringIO()
  533. self.to_file(temp_buffer, sorted, relativize, nl, want_comments,
  534. want_origin)
  535. return_value = temp_buffer.getvalue()
  536. temp_buffer.close()
  537. return return_value
  538. def check_origin(self):
  539. """Do some simple checking of the zone's origin.
  540. Raises ``dns.zone.NoSOA`` if there is no SOA RRset.
  541. Raises ``dns.zone.NoNS`` if there is no NS RRset.
  542. Raises ``KeyError`` if there is no origin node.
  543. """
  544. if self.relativize:
  545. name = dns.name.empty
  546. else:
  547. name = self.origin
  548. if self.get_rdataset(name, dns.rdatatype.SOA) is None:
  549. raise NoSOA
  550. if self.get_rdataset(name, dns.rdatatype.NS) is None:
  551. raise NoNS
  552. def _compute_digest(self, hash_algorithm, scheme=DigestScheme.SIMPLE):
  553. hashinfo = _digest_hashers.get(hash_algorithm)
  554. if not hashinfo:
  555. raise UnsupportedDigestHashAlgorithm
  556. if scheme != DigestScheme.SIMPLE:
  557. raise UnsupportedDigestScheme
  558. if self.relativize:
  559. origin_name = dns.name.empty
  560. else:
  561. origin_name = self.origin
  562. hasher = hashinfo()
  563. for (name, node) in sorted(self.items()):
  564. rrnamebuf = name.to_digestable(self.origin)
  565. for rdataset in sorted(node,
  566. key=lambda rds: (rds.rdtype, rds.covers)):
  567. if name == origin_name and \
  568. dns.rdatatype.ZONEMD in (rdataset.rdtype, rdataset.covers):
  569. continue
  570. rrfixed = struct.pack('!HHI', rdataset.rdtype,
  571. rdataset.rdclass, rdataset.ttl)
  572. rdatas = [rdata.to_digestable(self.origin)
  573. for rdata in rdataset]
  574. for rdata in sorted(rdatas):
  575. rrlen = struct.pack('!H', len(rdata))
  576. hasher.update(rrnamebuf + rrfixed + rrlen + rdata)
  577. return hasher.digest()
  578. def compute_digest(self, hash_algorithm, scheme=DigestScheme.SIMPLE):
  579. if self.relativize:
  580. origin_name = dns.name.empty
  581. else:
  582. origin_name = self.origin
  583. serial = self.get_rdataset(origin_name, dns.rdatatype.SOA)[0].serial
  584. digest = self._compute_digest(hash_algorithm, scheme)
  585. return dns.rdtypes.ANY.ZONEMD.ZONEMD(self.rdclass,
  586. dns.rdatatype.ZONEMD,
  587. serial, scheme, hash_algorithm,
  588. digest)
  589. def verify_digest(self, zonemd=None):
  590. if zonemd:
  591. digests = [zonemd]
  592. else:
  593. digests = self.get_rdataset(self.origin, dns.rdatatype.ZONEMD)
  594. if digests is None:
  595. raise NoDigest
  596. for digest in digests:
  597. try:
  598. computed = self._compute_digest(digest.hash_algorithm,
  599. digest.scheme)
  600. if computed == digest.digest:
  601. return
  602. except Exception:
  603. pass
  604. raise DigestVerificationFailure
  605. # TransactionManager methods
  606. def reader(self):
  607. return Transaction(self, False,
  608. Version(self, 1, self.nodes, self.origin))
  609. def writer(self, replacement=False):
  610. txn = Transaction(self, replacement)
  611. txn._setup_version()
  612. return txn
  613. def origin_information(self):
  614. if self.relativize:
  615. effective = dns.name.empty
  616. else:
  617. effective = self.origin
  618. return (self.origin, self.relativize, effective)
  619. def get_class(self):
  620. return self.rdclass
  621. # Transaction methods
  622. def _end_read(self, txn):
  623. pass
  624. def _end_write(self, txn):
  625. pass
  626. def _commit_version(self, _, version, origin):
  627. self.nodes = version.nodes
  628. if self.origin is None:
  629. self.origin = origin
  630. def _get_next_version_id(self):
  631. # Versions are ephemeral and all have id 1
  632. return 1
  633. # These classes used to be in dns.versioned, but have moved here so we can use
  634. # the copy-on-write transaction mechanism for both kinds of zones. In a
  635. # regular zone, the version only exists during the transaction, and the nodes
  636. # are regular dns.node.Nodes.
  637. # A node with a version id.
  638. class VersionedNode(dns.node.Node):
  639. __slots__ = ['id']
  640. def __init__(self):
  641. super().__init__()
  642. # A proper id will get set by the Version
  643. self.id = 0
  644. @dns.immutable.immutable
  645. class ImmutableVersionedNode(VersionedNode):
  646. __slots__ = ['id']
  647. def __init__(self, node):
  648. super().__init__()
  649. self.id = node.id
  650. self.rdatasets = tuple(
  651. [dns.rdataset.ImmutableRdataset(rds) for rds in node.rdatasets]
  652. )
  653. def find_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE,
  654. create=False):
  655. if create:
  656. raise TypeError("immutable")
  657. return super().find_rdataset(rdclass, rdtype, covers, False)
  658. def get_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE,
  659. create=False):
  660. if create:
  661. raise TypeError("immutable")
  662. return super().get_rdataset(rdclass, rdtype, covers, False)
  663. def delete_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE):
  664. raise TypeError("immutable")
  665. def replace_rdataset(self, replacement):
  666. raise TypeError("immutable")
  667. def is_immutable(self):
  668. return True
  669. class Version:
  670. def __init__(self, zone, id, nodes=None, origin=None):
  671. self.zone = zone
  672. self.id = id
  673. if nodes is not None:
  674. self.nodes = nodes
  675. else:
  676. self.nodes = {}
  677. self.origin = origin
  678. def _validate_name(self, name):
  679. if name.is_absolute():
  680. if self.origin is None:
  681. # This should probably never happen as other code (e.g.
  682. # _rr_line) will notice the lack of an origin before us, but
  683. # we check just in case!
  684. raise KeyError('no zone origin is defined')
  685. if not name.is_subdomain(self.origin):
  686. raise KeyError("name is not a subdomain of the zone origin")
  687. if self.zone.relativize:
  688. name = name.relativize(self.origin)
  689. elif not self.zone.relativize:
  690. # We have a relative name in a non-relative zone, so derelativize.
  691. if self.origin is None:
  692. raise KeyError('no zone origin is defined')
  693. name = name.derelativize(self.origin)
  694. return name
  695. def get_node(self, name):
  696. name = self._validate_name(name)
  697. return self.nodes.get(name)
  698. def get_rdataset(self, name, rdtype, covers):
  699. node = self.get_node(name)
  700. if node is None:
  701. return None
  702. return node.get_rdataset(self.zone.rdclass, rdtype, covers)
  703. def items(self):
  704. return self.nodes.items()
  705. class WritableVersion(Version):
  706. def __init__(self, zone, replacement=False):
  707. # The zone._versions_lock must be held by our caller in a versioned
  708. # zone.
  709. id = zone._get_next_version_id()
  710. super().__init__(zone, id)
  711. if not replacement:
  712. # We copy the map, because that gives us a simple and thread-safe
  713. # way of doing versions, and we have a garbage collector to help
  714. # us. We only make new node objects if we actually change the
  715. # node.
  716. self.nodes.update(zone.nodes)
  717. # We have to copy the zone origin as it may be None in the first
  718. # version, and we don't want to mutate the zone until we commit.
  719. self.origin = zone.origin
  720. self.changed = set()
  721. def _maybe_cow(self, name):
  722. name = self._validate_name(name)
  723. node = self.nodes.get(name)
  724. if node is None or name not in self.changed:
  725. new_node = self.zone.node_factory()
  726. if hasattr(new_node, 'id'):
  727. # We keep doing this for backwards compatibility, as earlier
  728. # code used new_node.id != self.id for the "do we need to CoW?"
  729. # test. Now we use the changed set as this works with both
  730. # regular zones and versioned zones.
  731. new_node.id = self.id
  732. if node is not None:
  733. # moo! copy on write!
  734. new_node.rdatasets.extend(node.rdatasets)
  735. self.nodes[name] = new_node
  736. self.changed.add(name)
  737. return new_node
  738. else:
  739. return node
  740. def delete_node(self, name):
  741. name = self._validate_name(name)
  742. if name in self.nodes:
  743. del self.nodes[name]
  744. self.changed.add(name)
  745. def put_rdataset(self, name, rdataset):
  746. node = self._maybe_cow(name)
  747. node.replace_rdataset(rdataset)
  748. def delete_rdataset(self, name, rdtype, covers):
  749. node = self._maybe_cow(name)
  750. node.delete_rdataset(self.zone.rdclass, rdtype, covers)
  751. if len(node) == 0:
  752. del self.nodes[name]
  753. @dns.immutable.immutable
  754. class ImmutableVersion(Version):
  755. def __init__(self, version):
  756. # We tell super() that it's a replacement as we don't want it
  757. # to copy the nodes, as we're about to do that with an
  758. # immutable Dict.
  759. super().__init__(version.zone, True)
  760. # set the right id!
  761. self.id = version.id
  762. # keep the origin
  763. self.origin = version.origin
  764. # Make changed nodes immutable
  765. for name in version.changed:
  766. node = version.nodes.get(name)
  767. # it might not exist if we deleted it in the version
  768. if node:
  769. version.nodes[name] = ImmutableVersionedNode(node)
  770. self.nodes = dns.immutable.Dict(version.nodes, True)
  771. class Transaction(dns.transaction.Transaction):
  772. def __init__(self, zone, replacement, version=None, make_immutable=False):
  773. read_only = version is not None
  774. super().__init__(zone, replacement, read_only)
  775. self.version = version
  776. self.make_immutable = make_immutable
  777. @property
  778. def zone(self):
  779. return self.manager
  780. def _setup_version(self):
  781. assert self.version is None
  782. self.version = WritableVersion(self.zone, self.replacement)
  783. def _get_rdataset(self, name, rdtype, covers):
  784. return self.version.get_rdataset(name, rdtype, covers)
  785. def _put_rdataset(self, name, rdataset):
  786. assert not self.read_only
  787. self.version.put_rdataset(name, rdataset)
  788. def _delete_name(self, name):
  789. assert not self.read_only
  790. self.version.delete_node(name)
  791. def _delete_rdataset(self, name, rdtype, covers):
  792. assert not self.read_only
  793. self.version.delete_rdataset(name, rdtype, covers)
  794. def _name_exists(self, name):
  795. return self.version.get_node(name) is not None
  796. def _changed(self):
  797. if self.read_only:
  798. return False
  799. else:
  800. return len(self.version.changed) > 0
  801. def _end_transaction(self, commit):
  802. if self.read_only:
  803. self.zone._end_read(self)
  804. elif commit and len(self.version.changed) > 0:
  805. if self.make_immutable:
  806. version = ImmutableVersion(self.version)
  807. else:
  808. version = self.version
  809. self.zone._commit_version(self, version, self.version.origin)
  810. else:
  811. # rollback
  812. self.zone._end_write(self)
  813. def _set_origin(self, origin):
  814. if self.version.origin is None:
  815. self.version.origin = origin
  816. def _iterate_rdatasets(self):
  817. for (name, node) in self.version.items():
  818. for rdataset in node:
  819. yield (name, rdataset)
  820. def _get_node(self, name):
  821. return self.version.get_node(name)
  822. def _origin_information(self):
  823. (absolute, relativize, effective) = self.manager.origin_information()
  824. if absolute is None and self.version.origin is not None:
  825. # No origin has been committed yet, but we've learned one as part of
  826. # this txn. Use it.
  827. absolute = self.version.origin
  828. if relativize:
  829. effective = dns.name.empty
  830. else:
  831. effective = absolute
  832. return (absolute, relativize, effective)
  833. def from_text(text, origin=None, rdclass=dns.rdataclass.IN,
  834. relativize=True, zone_factory=Zone, filename=None,
  835. allow_include=False, check_origin=True, idna_codec=None):
  836. """Build a zone object from a zone file format string.
  837. *text*, a ``str``, the zone file format input.
  838. *origin*, a ``dns.name.Name``, a ``str``, or ``None``. The origin
  839. of the zone; if not specified, the first ``$ORIGIN`` statement in the
  840. zone file will determine the origin of the zone.
  841. *rdclass*, an ``int``, the zone's rdata class; the default is class IN.
  842. *relativize*, a ``bool``, determine's whether domain names are
  843. relativized to the zone's origin. The default is ``True``.
  844. *zone_factory*, the zone factory to use or ``None``. If ``None``, then
  845. ``dns.zone.Zone`` will be used. The value may be any class or callable
  846. that returns a subclass of ``dns.zone.Zone``.
  847. *filename*, a ``str`` or ``None``, the filename to emit when
  848. describing where an error occurred; the default is ``'<string>'``.
  849. *allow_include*, a ``bool``. If ``True``, the default, then ``$INCLUDE``
  850. directives are permitted. If ``False``, then encoutering a ``$INCLUDE``
  851. will raise a ``SyntaxError`` exception.
  852. *check_origin*, a ``bool``. If ``True``, the default, then sanity
  853. checks of the origin node will be made by calling the zone's
  854. ``check_origin()`` method.
  855. *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
  856. encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
  857. is used.
  858. Raises ``dns.zone.NoSOA`` if there is no SOA RRset.
  859. Raises ``dns.zone.NoNS`` if there is no NS RRset.
  860. Raises ``KeyError`` if there is no origin node.
  861. Returns a subclass of ``dns.zone.Zone``.
  862. """
  863. # 'text' can also be a file, but we don't publish that fact
  864. # since it's an implementation detail. The official file
  865. # interface is from_file().
  866. if filename is None:
  867. filename = '<string>'
  868. zone = zone_factory(origin, rdclass, relativize=relativize)
  869. with zone.writer(True) as txn:
  870. tok = dns.tokenizer.Tokenizer(text, filename, idna_codec=idna_codec)
  871. reader = dns.zonefile.Reader(tok, rdclass, txn,
  872. allow_include=allow_include)
  873. try:
  874. reader.read()
  875. except dns.zonefile.UnknownOrigin:
  876. # for backwards compatibility
  877. raise dns.zone.UnknownOrigin
  878. # Now that we're done reading, do some basic checking of the zone.
  879. if check_origin:
  880. zone.check_origin()
  881. return zone
  882. def from_file(f, origin=None, rdclass=dns.rdataclass.IN,
  883. relativize=True, zone_factory=Zone, filename=None,
  884. allow_include=True, check_origin=True):
  885. """Read a zone file and build a zone object.
  886. *f*, a file or ``str``. If *f* is a string, it is treated
  887. as the name of a file to open.
  888. *origin*, a ``dns.name.Name``, a ``str``, or ``None``. The origin
  889. of the zone; if not specified, the first ``$ORIGIN`` statement in the
  890. zone file will determine the origin of the zone.
  891. *rdclass*, an ``int``, the zone's rdata class; the default is class IN.
  892. *relativize*, a ``bool``, determine's whether domain names are
  893. relativized to the zone's origin. The default is ``True``.
  894. *zone_factory*, the zone factory to use or ``None``. If ``None``, then
  895. ``dns.zone.Zone`` will be used. The value may be any class or callable
  896. that returns a subclass of ``dns.zone.Zone``.
  897. *filename*, a ``str`` or ``None``, the filename to emit when
  898. describing where an error occurred; the default is ``'<string>'``.
  899. *allow_include*, a ``bool``. If ``True``, the default, then ``$INCLUDE``
  900. directives are permitted. If ``False``, then encoutering a ``$INCLUDE``
  901. will raise a ``SyntaxError`` exception.
  902. *check_origin*, a ``bool``. If ``True``, the default, then sanity
  903. checks of the origin node will be made by calling the zone's
  904. ``check_origin()`` method.
  905. *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
  906. encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
  907. is used.
  908. Raises ``dns.zone.NoSOA`` if there is no SOA RRset.
  909. Raises ``dns.zone.NoNS`` if there is no NS RRset.
  910. Raises ``KeyError`` if there is no origin node.
  911. Returns a subclass of ``dns.zone.Zone``.
  912. """
  913. with contextlib.ExitStack() as stack:
  914. if isinstance(f, str):
  915. if filename is None:
  916. filename = f
  917. f = stack.enter_context(open(f))
  918. return from_text(f, origin, rdclass, relativize, zone_factory,
  919. filename, allow_include, check_origin)
  920. def from_xfr(xfr, zone_factory=Zone, relativize=True, check_origin=True):
  921. """Convert the output of a zone transfer generator into a zone object.
  922. *xfr*, a generator of ``dns.message.Message`` objects, typically
  923. ``dns.query.xfr()``.
  924. *relativize*, a ``bool``, determine's whether domain names are
  925. relativized to the zone's origin. The default is ``True``.
  926. It is essential that the relativize setting matches the one specified
  927. to the generator.
  928. *check_origin*, a ``bool``. If ``True``, the default, then sanity
  929. checks of the origin node will be made by calling the zone's
  930. ``check_origin()`` method.
  931. Raises ``dns.zone.NoSOA`` if there is no SOA RRset.
  932. Raises ``dns.zone.NoNS`` if there is no NS RRset.
  933. Raises ``KeyError`` if there is no origin node.
  934. Returns a subclass of ``dns.zone.Zone``.
  935. """
  936. z = None
  937. for r in xfr:
  938. if z is None:
  939. if relativize:
  940. origin = r.origin
  941. else:
  942. origin = r.answer[0].name
  943. rdclass = r.answer[0].rdclass
  944. z = zone_factory(origin, rdclass, relativize=relativize)
  945. for rrset in r.answer:
  946. znode = z.nodes.get(rrset.name)
  947. if not znode:
  948. znode = z.node_factory()
  949. z.nodes[rrset.name] = znode
  950. zrds = znode.find_rdataset(rrset.rdclass, rrset.rdtype,
  951. rrset.covers, True)
  952. zrds.update_ttl(rrset.ttl)
  953. for rd in rrset:
  954. zrds.add(rd)
  955. if check_origin:
  956. z.check_origin()
  957. return z