xfr.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. import dns.exception
  17. import dns.message
  18. import dns.name
  19. import dns.rcode
  20. import dns.serial
  21. import dns.rdatatype
  22. import dns.zone
  23. class TransferError(dns.exception.DNSException):
  24. """A zone transfer response got a non-zero rcode."""
  25. def __init__(self, rcode):
  26. message = 'Zone transfer error: %s' % dns.rcode.to_text(rcode)
  27. super().__init__(message)
  28. self.rcode = rcode
  29. class SerialWentBackwards(dns.exception.FormError):
  30. """The current serial number is less than the serial we know."""
  31. class UseTCP(dns.exception.DNSException):
  32. """This IXFR cannot be completed with UDP."""
  33. class Inbound:
  34. """
  35. State machine for zone transfers.
  36. """
  37. def __init__(self, txn_manager, rdtype=dns.rdatatype.AXFR,
  38. serial=None, is_udp=False):
  39. """Initialize an inbound zone transfer.
  40. *txn_manager* is a :py:class:`dns.transaction.TransactionManager`.
  41. *rdtype* can be `dns.rdatatype.AXFR` or `dns.rdatatype.IXFR`
  42. *serial* is the base serial number for IXFRs, and is required in
  43. that case.
  44. *is_udp*, a ``bool`` indidicates if UDP is being used for this
  45. XFR.
  46. """
  47. self.txn_manager = txn_manager
  48. self.txn = None
  49. self.rdtype = rdtype
  50. if rdtype == dns.rdatatype.IXFR:
  51. if serial is None:
  52. raise ValueError('a starting serial must be supplied for IXFRs')
  53. elif is_udp:
  54. raise ValueError('is_udp specified for AXFR')
  55. self.serial = serial
  56. self.is_udp = is_udp
  57. (_, _, self.origin) = txn_manager.origin_information()
  58. self.soa_rdataset = None
  59. self.done = False
  60. self.expecting_SOA = False
  61. self.delete_mode = False
  62. def process_message(self, message):
  63. """Process one message in the transfer.
  64. The message should have the same relativization as was specified when
  65. the `dns.xfr.Inbound` was created. The message should also have been
  66. created with `one_rr_per_rrset=True` because order matters.
  67. Returns `True` if the transfer is complete, and `False` otherwise.
  68. """
  69. if self.txn is None:
  70. replacement = self.rdtype == dns.rdatatype.AXFR
  71. self.txn = self.txn_manager.writer(replacement)
  72. rcode = message.rcode()
  73. if rcode != dns.rcode.NOERROR:
  74. raise TransferError(rcode)
  75. #
  76. # We don't require a question section, but if it is present is
  77. # should be correct.
  78. #
  79. if len(message.question) > 0:
  80. if message.question[0].name != self.origin:
  81. raise dns.exception.FormError("wrong question name")
  82. if message.question[0].rdtype != self.rdtype:
  83. raise dns.exception.FormError("wrong question rdatatype")
  84. answer_index = 0
  85. if self.soa_rdataset is None:
  86. #
  87. # This is the first message. We're expecting an SOA at
  88. # the origin.
  89. #
  90. if not message.answer or message.answer[0].name != self.origin:
  91. raise dns.exception.FormError("No answer or RRset not "
  92. "for zone origin")
  93. rrset = message.answer[0]
  94. name = rrset.name
  95. rdataset = rrset
  96. if rdataset.rdtype != dns.rdatatype.SOA:
  97. raise dns.exception.FormError("first RRset is not an SOA")
  98. answer_index = 1
  99. self.soa_rdataset = rdataset.copy()
  100. if self.rdtype == dns.rdatatype.IXFR:
  101. if self.soa_rdataset[0].serial == self.serial:
  102. #
  103. # We're already up-to-date.
  104. #
  105. self.done = True
  106. elif dns.serial.Serial(self.soa_rdataset[0].serial) < \
  107. self.serial:
  108. # It went backwards!
  109. raise SerialWentBackwards
  110. else:
  111. if self.is_udp and len(message.answer[answer_index:]) == 0:
  112. #
  113. # There are no more records, so this is the
  114. # "truncated" response. Say to use TCP
  115. #
  116. raise UseTCP
  117. #
  118. # Note we're expecting another SOA so we can detect
  119. # if this IXFR response is an AXFR-style response.
  120. #
  121. self.expecting_SOA = True
  122. #
  123. # Process the answer section (other than the initial SOA in
  124. # the first message).
  125. #
  126. for rrset in message.answer[answer_index:]:
  127. name = rrset.name
  128. rdataset = rrset
  129. if self.done:
  130. raise dns.exception.FormError("answers after final SOA")
  131. if rdataset.rdtype == dns.rdatatype.SOA and \
  132. name == self.origin:
  133. #
  134. # Every time we see an origin SOA delete_mode inverts
  135. #
  136. if self.rdtype == dns.rdatatype.IXFR:
  137. self.delete_mode = not self.delete_mode
  138. #
  139. # If this SOA Rdataset is equal to the first we saw
  140. # then we're finished. If this is an IXFR we also
  141. # check that we're seeing the record in the expected
  142. # part of the response.
  143. #
  144. if rdataset == self.soa_rdataset and \
  145. (self.rdtype == dns.rdatatype.AXFR or
  146. (self.rdtype == dns.rdatatype.IXFR and
  147. self.delete_mode)):
  148. #
  149. # This is the final SOA
  150. #
  151. if self.expecting_SOA:
  152. # We got an empty IXFR sequence!
  153. raise dns.exception.FormError('empty IXFR sequence')
  154. if self.rdtype == dns.rdatatype.IXFR \
  155. and self.serial != rdataset[0].serial:
  156. raise dns.exception.FormError('unexpected end of IXFR '
  157. 'sequence')
  158. self.txn.replace(name, rdataset)
  159. self.txn.commit()
  160. self.txn = None
  161. self.done = True
  162. else:
  163. #
  164. # This is not the final SOA
  165. #
  166. self.expecting_SOA = False
  167. if self.rdtype == dns.rdatatype.IXFR:
  168. if self.delete_mode:
  169. # This is the start of an IXFR deletion set
  170. if rdataset[0].serial != self.serial:
  171. raise dns.exception.FormError(
  172. "IXFR base serial mismatch")
  173. else:
  174. # This is the start of an IXFR addition set
  175. self.serial = rdataset[0].serial
  176. self.txn.replace(name, rdataset)
  177. else:
  178. # We saw a non-final SOA for the origin in an AXFR.
  179. raise dns.exception.FormError('unexpected origin SOA '
  180. 'in AXFR')
  181. continue
  182. if self.expecting_SOA:
  183. #
  184. # We made an IXFR request and are expecting another
  185. # SOA RR, but saw something else, so this must be an
  186. # AXFR response.
  187. #
  188. self.rdtype = dns.rdatatype.AXFR
  189. self.expecting_SOA = False
  190. self.delete_mode = False
  191. self.txn.rollback()
  192. self.txn = self.txn_manager.writer(True)
  193. #
  194. # Note we are falling through into the code below
  195. # so whatever rdataset this was gets written.
  196. #
  197. # Add or remove the data
  198. if self.delete_mode:
  199. self.txn.delete_exact(name, rdataset)
  200. else:
  201. self.txn.add(name, rdataset)
  202. if self.is_udp and not self.done:
  203. #
  204. # This is a UDP IXFR and we didn't get to done, and we didn't
  205. # get the proper "truncated" response
  206. #
  207. raise dns.exception.FormError('unexpected end of UDP IXFR')
  208. return self.done
  209. #
  210. # Inbounds are context managers.
  211. #
  212. def __enter__(self):
  213. return self
  214. def __exit__(self, exc_type, exc_val, exc_tb):
  215. if self.txn:
  216. self.txn.rollback()
  217. return False
  218. def make_query(txn_manager, serial=0,
  219. use_edns=None, ednsflags=None, payload=None,
  220. request_payload=None, options=None,
  221. keyring=None, keyname=None,
  222. keyalgorithm=dns.tsig.default_algorithm):
  223. """Make an AXFR or IXFR query.
  224. *txn_manager* is a ``dns.transaction.TransactionManager``, typically a
  225. ``dns.zone.Zone``.
  226. *serial* is an ``int`` or ``None``. If 0, then IXFR will be
  227. attempted using the most recent serial number from the
  228. *txn_manager*; it is the caller's responsibility to ensure there
  229. are no write transactions active that could invalidate the
  230. retrieved serial. If a serial cannot be determined, AXFR will be
  231. forced. Other integer values are the starting serial to use.
  232. ``None`` forces an AXFR.
  233. Please see the documentation for :py:func:`dns.message.make_query` and
  234. :py:func:`dns.message.Message.use_tsig` for details on the other parameters
  235. to this function.
  236. Returns a `(query, serial)` tuple.
  237. """
  238. (zone_origin, _, origin) = txn_manager.origin_information()
  239. if serial is None:
  240. rdtype = dns.rdatatype.AXFR
  241. elif not isinstance(serial, int):
  242. raise ValueError('serial is not an integer')
  243. elif serial == 0:
  244. with txn_manager.reader() as txn:
  245. rdataset = txn.get(origin, 'SOA')
  246. if rdataset:
  247. serial = rdataset[0].serial
  248. rdtype = dns.rdatatype.IXFR
  249. else:
  250. serial = None
  251. rdtype = dns.rdatatype.AXFR
  252. elif serial > 0 and serial < 4294967296:
  253. rdtype = dns.rdatatype.IXFR
  254. else:
  255. raise ValueError('serial out-of-range')
  256. rdclass = txn_manager.get_class()
  257. q = dns.message.make_query(zone_origin, rdtype, rdclass,
  258. use_edns, False, ednsflags, payload,
  259. request_payload, options)
  260. if serial is not None:
  261. rdata = dns.rdata.from_text(rdclass, 'SOA', f'. . {serial} 0 0 0 0')
  262. rrset = q.find_rrset(q.authority, zone_origin, rdclass,
  263. dns.rdatatype.SOA, create=True)
  264. rrset.add(rdata, 0)
  265. if keyring is not None:
  266. q.use_tsig(keyring, keyname, algorithm=keyalgorithm)
  267. return (q, serial)
  268. def extract_serial_from_query(query):
  269. """Extract the SOA serial number from query if it is an IXFR and return
  270. it, otherwise return None.
  271. *query* is a dns.message.QueryMessage that is an IXFR or AXFR request.
  272. Raises if the query is not an IXFR or AXFR, or if an IXFR doesn't have
  273. an appropriate SOA RRset in the authority section."""
  274. question = query.question[0]
  275. if question.rdtype == dns.rdatatype.AXFR:
  276. return None
  277. elif question.rdtype != dns.rdatatype.IXFR:
  278. raise ValueError("query is not an AXFR or IXFR")
  279. soa = query.find_rrset(query.authority, question.name, question.rdclass,
  280. dns.rdatatype.SOA)
  281. return soa[0].serial