You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

456 lines
14 KiB

4 years ago
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2001-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. """DNS rdata."""
  17. from io import BytesIO
  18. import base64
  19. import binascii
  20. import dns.exception
  21. import dns.name
  22. import dns.rdataclass
  23. import dns.rdatatype
  24. import dns.tokenizer
  25. import dns.wiredata
  26. from ._compat import xrange, string_types, text_type
  27. try:
  28. import threading as _threading
  29. except ImportError:
  30. import dummy_threading as _threading
  31. _hex_chunksize = 32
  32. def _hexify(data, chunksize=_hex_chunksize):
  33. """Convert a binary string into its hex encoding, broken up into chunks
  34. of chunksize characters separated by a space.
  35. """
  36. line = binascii.hexlify(data)
  37. return b' '.join([line[i:i + chunksize]
  38. for i
  39. in range(0, len(line), chunksize)]).decode()
  40. _base64_chunksize = 32
  41. def _base64ify(data, chunksize=_base64_chunksize):
  42. """Convert a binary string into its base64 encoding, broken up into chunks
  43. of chunksize characters separated by a space.
  44. """
  45. line = base64.b64encode(data)
  46. return b' '.join([line[i:i + chunksize]
  47. for i
  48. in range(0, len(line), chunksize)]).decode()
  49. __escaped = bytearray(b'"\\')
  50. def _escapify(qstring):
  51. """Escape the characters in a quoted string which need it."""
  52. if isinstance(qstring, text_type):
  53. qstring = qstring.encode()
  54. if not isinstance(qstring, bytearray):
  55. qstring = bytearray(qstring)
  56. text = ''
  57. for c in qstring:
  58. if c in __escaped:
  59. text += '\\' + chr(c)
  60. elif c >= 0x20 and c < 0x7F:
  61. text += chr(c)
  62. else:
  63. text += '\\%03d' % c
  64. return text
  65. def _truncate_bitmap(what):
  66. """Determine the index of greatest byte that isn't all zeros, and
  67. return the bitmap that contains all the bytes less than that index.
  68. """
  69. for i in xrange(len(what) - 1, -1, -1):
  70. if what[i] != 0:
  71. return what[0: i + 1]
  72. return what[0:1]
  73. class Rdata(object):
  74. """Base class for all DNS rdata types."""
  75. __slots__ = ['rdclass', 'rdtype']
  76. def __init__(self, rdclass, rdtype):
  77. """Initialize an rdata.
  78. *rdclass*, an ``int`` is the rdataclass of the Rdata.
  79. *rdtype*, an ``int`` is the rdatatype of the Rdata.
  80. """
  81. self.rdclass = rdclass
  82. self.rdtype = rdtype
  83. def covers(self):
  84. """Return the type a Rdata covers.
  85. DNS SIG/RRSIG rdatas apply to a specific type; this type is
  86. returned by the covers() function. If the rdata type is not
  87. SIG or RRSIG, dns.rdatatype.NONE is returned. This is useful when
  88. creating rdatasets, allowing the rdataset to contain only RRSIGs
  89. of a particular type, e.g. RRSIG(NS).
  90. Returns an ``int``.
  91. """
  92. return dns.rdatatype.NONE
  93. def extended_rdatatype(self):
  94. """Return a 32-bit type value, the least significant 16 bits of
  95. which are the ordinary DNS type, and the upper 16 bits of which are
  96. the "covered" type, if any.
  97. Returns an ``int``.
  98. """
  99. return self.covers() << 16 | self.rdtype
  100. def to_text(self, origin=None, relativize=True, **kw):
  101. """Convert an rdata to text format.
  102. Returns a ``text``.
  103. """
  104. raise NotImplementedError
  105. def to_wire(self, file, compress=None, origin=None):
  106. """Convert an rdata to wire format.
  107. Returns a ``binary``.
  108. """
  109. raise NotImplementedError
  110. def to_digestable(self, origin=None):
  111. """Convert rdata to a format suitable for digesting in hashes. This
  112. is also the DNSSEC canonical form.
  113. Returns a ``binary``.
  114. """
  115. f = BytesIO()
  116. self.to_wire(f, None, origin)
  117. return f.getvalue()
  118. def validate(self):
  119. """Check that the current contents of the rdata's fields are
  120. valid.
  121. If you change an rdata by assigning to its fields,
  122. it is a good idea to call validate() when you are done making
  123. changes.
  124. Raises various exceptions if there are problems.
  125. Returns ``None``.
  126. """
  127. dns.rdata.from_text(self.rdclass, self.rdtype, self.to_text())
  128. def __repr__(self):
  129. covers = self.covers()
  130. if covers == dns.rdatatype.NONE:
  131. ctext = ''
  132. else:
  133. ctext = '(' + dns.rdatatype.to_text(covers) + ')'
  134. return '<DNS ' + dns.rdataclass.to_text(self.rdclass) + ' ' + \
  135. dns.rdatatype.to_text(self.rdtype) + ctext + ' rdata: ' + \
  136. str(self) + '>'
  137. def __str__(self):
  138. return self.to_text()
  139. def _cmp(self, other):
  140. """Compare an rdata with another rdata of the same rdtype and
  141. rdclass.
  142. Return < 0 if self < other in the DNSSEC ordering, 0 if self
  143. == other, and > 0 if self > other.
  144. """
  145. our = self.to_digestable(dns.name.root)
  146. their = other.to_digestable(dns.name.root)
  147. if our == their:
  148. return 0
  149. elif our > their:
  150. return 1
  151. else:
  152. return -1
  153. def __eq__(self, other):
  154. if not isinstance(other, Rdata):
  155. return False
  156. if self.rdclass != other.rdclass or self.rdtype != other.rdtype:
  157. return False
  158. return self._cmp(other) == 0
  159. def __ne__(self, other):
  160. if not isinstance(other, Rdata):
  161. return True
  162. if self.rdclass != other.rdclass or self.rdtype != other.rdtype:
  163. return True
  164. return self._cmp(other) != 0
  165. def __lt__(self, other):
  166. if not isinstance(other, Rdata) or \
  167. self.rdclass != other.rdclass or self.rdtype != other.rdtype:
  168. return NotImplemented
  169. return self._cmp(other) < 0
  170. def __le__(self, other):
  171. if not isinstance(other, Rdata) or \
  172. self.rdclass != other.rdclass or self.rdtype != other.rdtype:
  173. return NotImplemented
  174. return self._cmp(other) <= 0
  175. def __ge__(self, other):
  176. if not isinstance(other, Rdata) or \
  177. self.rdclass != other.rdclass or self.rdtype != other.rdtype:
  178. return NotImplemented
  179. return self._cmp(other) >= 0
  180. def __gt__(self, other):
  181. if not isinstance(other, Rdata) or \
  182. self.rdclass != other.rdclass or self.rdtype != other.rdtype:
  183. return NotImplemented
  184. return self._cmp(other) > 0
  185. def __hash__(self):
  186. return hash(self.to_digestable(dns.name.root))
  187. @classmethod
  188. def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True):
  189. raise NotImplementedError
  190. @classmethod
  191. def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin=None):
  192. raise NotImplementedError
  193. def choose_relativity(self, origin=None, relativize=True):
  194. """Convert any domain names in the rdata to the specified
  195. relativization.
  196. """
  197. class GenericRdata(Rdata):
  198. """Generic Rdata Class
  199. This class is used for rdata types for which we have no better
  200. implementation. It implements the DNS "unknown RRs" scheme.
  201. """
  202. __slots__ = ['data']
  203. def __init__(self, rdclass, rdtype, data):
  204. super(GenericRdata, self).__init__(rdclass, rdtype)
  205. self.data = data
  206. def to_text(self, origin=None, relativize=True, **kw):
  207. return r'\# %d ' % len(self.data) + _hexify(self.data)
  208. @classmethod
  209. def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True):
  210. token = tok.get()
  211. if not token.is_identifier() or token.value != r'\#':
  212. raise dns.exception.SyntaxError(
  213. r'generic rdata does not start with \#')
  214. length = tok.get_int()
  215. chunks = []
  216. while 1:
  217. token = tok.get()
  218. if token.is_eol_or_eof():
  219. break
  220. chunks.append(token.value.encode())
  221. hex = b''.join(chunks)
  222. data = binascii.unhexlify(hex)
  223. if len(data) != length:
  224. raise dns.exception.SyntaxError(
  225. 'generic rdata hex data has wrong length')
  226. return cls(rdclass, rdtype, data)
  227. def to_wire(self, file, compress=None, origin=None):
  228. file.write(self.data)
  229. @classmethod
  230. def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin=None):
  231. return cls(rdclass, rdtype, wire[current: current + rdlen])
  232. _rdata_modules = {}
  233. _module_prefix = 'dns.rdtypes'
  234. _import_lock = _threading.Lock()
  235. def get_rdata_class(rdclass, rdtype):
  236. def import_module(name):
  237. with _import_lock:
  238. mod = __import__(name)
  239. components = name.split('.')
  240. for comp in components[1:]:
  241. mod = getattr(mod, comp)
  242. return mod
  243. mod = _rdata_modules.get((rdclass, rdtype))
  244. rdclass_text = dns.rdataclass.to_text(rdclass)
  245. rdtype_text = dns.rdatatype.to_text(rdtype)
  246. rdtype_text = rdtype_text.replace('-', '_')
  247. if not mod:
  248. mod = _rdata_modules.get((dns.rdatatype.ANY, rdtype))
  249. if not mod:
  250. try:
  251. mod = import_module('.'.join([_module_prefix,
  252. rdclass_text, rdtype_text]))
  253. _rdata_modules[(rdclass, rdtype)] = mod
  254. except ImportError:
  255. try:
  256. mod = import_module('.'.join([_module_prefix,
  257. 'ANY', rdtype_text]))
  258. _rdata_modules[(dns.rdataclass.ANY, rdtype)] = mod
  259. except ImportError:
  260. mod = None
  261. if mod:
  262. cls = getattr(mod, rdtype_text)
  263. else:
  264. cls = GenericRdata
  265. return cls
  266. def from_text(rdclass, rdtype, tok, origin=None, relativize=True):
  267. """Build an rdata object from text format.
  268. This function attempts to dynamically load a class which
  269. implements the specified rdata class and type. If there is no
  270. class-and-type-specific implementation, the GenericRdata class
  271. is used.
  272. Once a class is chosen, its from_text() class method is called
  273. with the parameters to this function.
  274. If *tok* is a ``text``, then a tokenizer is created and the string
  275. is used as its input.
  276. *rdclass*, an ``int``, the rdataclass.
  277. *rdtype*, an ``int``, the rdatatype.
  278. *tok*, a ``dns.tokenizer.Tokenizer`` or a ``text``.
  279. *origin*, a ``dns.name.Name`` (or ``None``), the
  280. origin to use for relative names.
  281. *relativize*, a ``bool``. If true, name will be relativized to
  282. the specified origin.
  283. Returns an instance of the chosen Rdata subclass.
  284. """
  285. if isinstance(tok, string_types):
  286. tok = dns.tokenizer.Tokenizer(tok)
  287. cls = get_rdata_class(rdclass, rdtype)
  288. if cls != GenericRdata:
  289. # peek at first token
  290. token = tok.get()
  291. tok.unget(token)
  292. if token.is_identifier() and \
  293. token.value == r'\#':
  294. #
  295. # Known type using the generic syntax. Extract the
  296. # wire form from the generic syntax, and then run
  297. # from_wire on it.
  298. #
  299. rdata = GenericRdata.from_text(rdclass, rdtype, tok, origin,
  300. relativize)
  301. return from_wire(rdclass, rdtype, rdata.data, 0, len(rdata.data),
  302. origin)
  303. return cls.from_text(rdclass, rdtype, tok, origin, relativize)
  304. def from_wire(rdclass, rdtype, wire, current, rdlen, origin=None):
  305. """Build an rdata object from wire format
  306. This function attempts to dynamically load a class which
  307. implements the specified rdata class and type. If there is no
  308. class-and-type-specific implementation, the GenericRdata class
  309. is used.
  310. Once a class is chosen, its from_wire() class method is called
  311. with the parameters to this function.
  312. *rdclass*, an ``int``, the rdataclass.
  313. *rdtype*, an ``int``, the rdatatype.
  314. *wire*, a ``binary``, the wire-format message.
  315. *current*, an ``int``, the offset in wire of the beginning of
  316. the rdata.
  317. *rdlen*, an ``int``, the length of the wire-format rdata
  318. *origin*, a ``dns.name.Name`` (or ``None``). If not ``None``,
  319. then names will be relativized to this origin.
  320. Returns an instance of the chosen Rdata subclass.
  321. """
  322. wire = dns.wiredata.maybe_wrap(wire)
  323. cls = get_rdata_class(rdclass, rdtype)
  324. return cls.from_wire(rdclass, rdtype, wire, current, rdlen, origin)
  325. class RdatatypeExists(dns.exception.DNSException):
  326. """DNS rdatatype already exists."""
  327. supp_kwargs = {'rdclass', 'rdtype'}
  328. fmt = "The rdata type with class {rdclass} and rdtype {rdtype} " + \
  329. "already exists."
  330. def register_type(implementation, rdtype, rdtype_text, is_singleton=False,
  331. rdclass=dns.rdataclass.IN):
  332. """Dynamically register a module to handle an rdatatype.
  333. *implementation*, a module implementing the type in the usual dnspython
  334. way.
  335. *rdtype*, an ``int``, the rdatatype to register.
  336. *rdtype_text*, a ``text``, the textual form of the rdatatype.
  337. *is_singleton*, a ``bool``, indicating if the type is a singleton (i.e.
  338. RRsets of the type can have only one member.)
  339. *rdclass*, the rdataclass of the type, or ``dns.rdataclass.ANY`` if
  340. it applies to all classes.
  341. """
  342. existing_cls = get_rdata_class(rdclass, rdtype)
  343. if existing_cls != GenericRdata:
  344. raise RdatatypeExists(rdclass=rdclass, rdtype=rdtype)
  345. _rdata_modules[(rdclass, rdtype)] = implementation
  346. dns.rdatatype.register_type(rdtype, rdtype_text, is_singleton)