xfrin.py.in 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  1. #!@PYTHON@
  2. # Copyright (C) 2009-2011 Internet Systems Consortium.
  3. #
  4. # Permission to use, copy, modify, and distribute this software for any
  5. # purpose with or without fee is hereby granted, provided that the above
  6. # copyright notice and this permission notice appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  9. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  10. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  11. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  12. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  13. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  14. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  15. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. import sys; sys.path.append ('@@PYTHONPATH@@')
  17. import os
  18. import signal
  19. import isc
  20. import asyncore
  21. import struct
  22. import threading
  23. import socket
  24. import random
  25. from optparse import OptionParser, OptionValueError
  26. from isc.config.ccsession import *
  27. from isc.notify import notify_out
  28. import isc.util.process
  29. from isc.datasrc import DataSourceClient, ZoneFinder
  30. import isc.net.parse
  31. from isc.xfrin.diff import Diff
  32. from isc.log_messages.xfrin_messages import *
  33. isc.log.init("b10-xfrin")
  34. logger = isc.log.Logger("xfrin")
  35. try:
  36. from pydnspp import *
  37. except ImportError as e:
  38. # C++ loadable module may not be installed; even so the xfrin process
  39. # must keep running, so we warn about it and move forward.
  40. logger.error(XFRIN_IMPORT_DNS, str(e))
  41. isc.util.process.rename()
  42. # If B10_FROM_BUILD is set in the environment, we use data files
  43. # from a directory relative to that, otherwise we use the ones
  44. # installed on the system
  45. if "B10_FROM_BUILD" in os.environ:
  46. SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/xfrin"
  47. AUTH_SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/auth"
  48. else:
  49. PREFIX = "@prefix@"
  50. DATAROOTDIR = "@datarootdir@"
  51. SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  52. AUTH_SPECFILE_PATH = SPECFILE_PATH
  53. SPECFILE_LOCATION = SPECFILE_PATH + "/xfrin.spec"
  54. AUTH_SPECFILE_LOCATION = AUTH_SPECFILE_PATH + "/auth.spec"
  55. XFROUT_MODULE_NAME = 'Xfrout'
  56. ZONE_MANAGER_MODULE_NAME = 'Zonemgr'
  57. REFRESH_FROM_ZONEMGR = 'refresh_from_zonemgr'
  58. ZONE_XFRIN_FAILED = 'zone_xfrin_failed'
  59. # Constants for debug levels, to be removed when we have #1074.
  60. DBG_XFRIN_TRACE = 3
  61. # These two default are currently hard-coded. For config this isn't
  62. # necessary, but we need these defaults for optional command arguments
  63. # (TODO: have similar support to get default values for command
  64. # arguments as we do for config options)
  65. DEFAULT_MASTER_PORT = 53
  66. DEFAULT_ZONE_CLASS = RRClass.IN()
  67. __version__ = 'BIND10'
  68. # define xfrin rcode
  69. XFRIN_OK = 0
  70. XFRIN_FAIL = 1
  71. class XfrinException(Exception):
  72. pass
  73. class XfrinProtocolError(Exception):
  74. '''An exception raised for errors encountered in xfrin protocol handling.
  75. '''
  76. pass
  77. class XfrinZoneInfoException(Exception):
  78. """This exception is raised if there is an error in the given
  79. configuration (part), or when a command does not have a required
  80. argument or has bad arguments, for instance when the zone's master
  81. address is not a valid IP address, when the zone does not
  82. have a name, or when multiple settings are given for the same
  83. zone."""
  84. pass
  85. def _check_zone_name(zone_name_str):
  86. """Checks if the given zone name is a valid domain name, and returns
  87. it as a Name object. Raises an XfrinException if it is not."""
  88. try:
  89. # In the _zones dict, part of the key is the zone name,
  90. # but due to a limitation in the Name class, we
  91. # cannot directly use it as a dict key, and we use to_text()
  92. #
  93. # Downcase the name here for that reason.
  94. return Name(zone_name_str, True)
  95. except (EmptyLabel, TooLongLabel, BadLabelType, BadEscape,
  96. TooLongName, IncompleteName) as ne:
  97. raise XfrinZoneInfoException("bad zone name: " + zone_name_str + " (" + str(ne) + ")")
  98. def _check_zone_class(zone_class_str):
  99. """If the given argument is a string: checks if the given class is
  100. a valid one, and returns an RRClass object if so.
  101. Raises XfrinZoneInfoException if not.
  102. If it is None, this function returns the default RRClass.IN()"""
  103. if zone_class_str is None:
  104. return DEFAULT_ZONE_CLASS
  105. try:
  106. return RRClass(zone_class_str)
  107. except InvalidRRClass as irce:
  108. raise XfrinZoneInfoException("bad zone class: " + zone_class_str + " (" + str(irce) + ")")
  109. def get_soa_serial(soa_rdata):
  110. '''Extract the serial field of an SOA RDATA and returns it as an intger.
  111. We don't have to be very efficient here, so we first dump the entire RDATA
  112. as a string and convert the first corresponding field. This should be
  113. sufficient in practice, but may not always work when the MNAME or RNAME
  114. contains an (escaped) space character in their labels. Ideally there
  115. should be a more direct and convenient way to get access to the SOA
  116. fields.
  117. '''
  118. return int(soa_rdata.to_text().split()[2])
  119. class XfrinState:
  120. '''
  121. The states of the incomding *XFR state machine.
  122. '''
  123. def set_xfrstate(self, conn, new_state):
  124. '''Set the XfrConnection to a given new state
  125. As a "friend" class, this method intentionally gets access to the
  126. connection's "private" method.
  127. '''
  128. conn._XfrinConnection__set_xfrstate(new_state)
  129. class XfrinInitialSOA(XfrinState):
  130. def handle_rr(self, conn, rr):
  131. if rr.get_type() != RRType.SOA():
  132. raise XfrinProtocolError('First RR in zone transfer must be SOA ('
  133. + rr.get_type().to_text() + ' given)')
  134. conn._end_serial = get_soa_serial(rr.get_rdata()[0])
  135. # FIXME: we need to check the serial is actually greater than ours.
  136. # To do so, however, we need a way to find records from datasource.
  137. # Complete that part later as a separate task. (Always performing
  138. # xfr could be inefficient, but shouldn't do any harm otherwise)
  139. self.set_xfrstate(conn, XfrinFirstData())
  140. return True
  141. class XfrinFirstData(XfrinState):
  142. def handle_rr(self, conn, rr):
  143. # If the transfer begins with one SOA record, it is an AXFR,
  144. # if it begins with two SOAs (the serial of the second one being
  145. # equal to our serial), it is an IXFR.
  146. if conn._request_type == RRType.IXFR() and \
  147. rr.get_type() == RRType.SOA() and \
  148. conn._request_serial == get_soa_serial(rr.get_rdata()[0]):
  149. logger.debug(DBG_XFRIN_TRACE, XFRIN_GOT_INCREMENTAL_RESP,
  150. conn.zone_str())
  151. self.set_xfrstate(conn, XfrinIXFRDeleteSOA())
  152. else:
  153. logger.debug(DBG_XFRIN_TRACE, XFRIN_GOT_NONINCREMENTAL_RESP,
  154. conn.zone_str())
  155. self.set_xfrstate(conn, XfrinAXFR())
  156. return False # need to revisit this RR in an update context
  157. class XfrinIXFRDeleteSOA(XfrinState):
  158. def handle_rr(self, conn, rr):
  159. if rr.get_type() != RRType.SOA():
  160. # this shouldn't happen; should this occur it means an internal
  161. # bug.
  162. raise XfrinException(rr.get_type().to_text() + \
  163. ' RR is given in IXFRDeleteSOA state')
  164. conn._diff.remove_data(rr)
  165. self.set_xfrstate(conn, XfrinIXFRDelete())
  166. return True
  167. class XfrinIXFRDelete(XfrinState):
  168. def handle_rr(self, conn, rr):
  169. if rr.get_type() == RRType.SOA():
  170. # This is the only place where current_serial is set
  171. conn._current_serial = get_soa_serial(rr.get_rdata()[0])
  172. self.set_xfrstate(conn, XfrinIXFRAddSOA())
  173. return False
  174. conn._diff.remove_data(rr)
  175. return True
  176. class XfrinIXFRAddSOA(XfrinState):
  177. def handle_rr(self, conn, rr):
  178. if rr.get_type() != RRType.SOA():
  179. # this shouldn't happen; should this occur it means an internal
  180. # bug.
  181. raise XfrinException(rr.get_type().to_text() + \
  182. ' RR is given in IXFRAddSOA state')
  183. conn._diff.add_data(rr)
  184. self.set_xfrstate(conn, XfrinIXFRAdd())
  185. return True
  186. class XfrinIXFRAdd(XfrinState):
  187. def handle_rr(self, conn, rr):
  188. if rr.get_type() == RRType.SOA():
  189. soa_serial = get_soa_serial(rr.get_rdata()[0])
  190. if soa_serial == conn._end_serial:
  191. conn._diff.commit()
  192. self.set_xfrstate(conn, XfrinIXFREnd())
  193. return True
  194. elif soa_serial != conn._current_serial:
  195. raise XfrinProtocolError('IXFR out of sync: expected ' + \
  196. 'serial ' + \
  197. str(conn._current_serial) + \
  198. ', got ' + str(soa_serial))
  199. else:
  200. conn._diff.commit()
  201. self.set_xfrstate(conn, XfrinIXFRDeleteSOA())
  202. return False
  203. conn._diff.add_data(rr)
  204. return True
  205. class XfrinIXFREnd(XfrinState):
  206. def handle_rr(self, conn, rr):
  207. raise XfrinProtocolError('Extra data after the end of IXFR diffs: ' + \
  208. rr.to_text())
  209. class XfrinAXFR(XfrinState):
  210. def handle_rr(self, conn, rr):
  211. raise XfrinException('Falling back from IXFR to AXFR not ' + \
  212. 'supported yet')
  213. class XfrinConnection(asyncore.dispatcher):
  214. '''Do xfrin in this class. '''
  215. def __init__(self,
  216. sock_map, zone_name, rrclass, db_file, shutdown_event,
  217. master_addrinfo, tsig_key = None, verbose = False,
  218. idle_timeout = 60):
  219. ''' idle_timeout: max idle time for read data from socket.
  220. db_file: specify the data source file.
  221. check_soa: when it's true, check soa first before sending xfr query
  222. '''
  223. asyncore.dispatcher.__init__(self, map=sock_map)
  224. self.__state = None
  225. # Requested transfer type (RRType.AXFR or RRType.IXFR). The actual
  226. # transfer type may differ due to IXFR->AXFR fallback:
  227. self._request_type = None
  228. self._end_serial = None # essentially private
  229. # Zone parameters
  230. self._zone_name = zone_name
  231. self._rrclass = rrclass
  232. # Data source handlers
  233. self._db_file = db_file # temporary for sqlite3 specific code
  234. self._datasrc_client = self._get_datasrc_client(rrclass)
  235. self.create_socket(master_addrinfo[0], master_addrinfo[1])
  236. self._sock_map = sock_map
  237. self._soa_rr_count = 0
  238. self._idle_timeout = idle_timeout
  239. self.setblocking(1)
  240. self._shutdown_event = shutdown_event
  241. self._verbose = verbose
  242. self._master_address = master_addrinfo[2]
  243. self._tsig_key = tsig_key
  244. self._tsig_ctx = None
  245. # tsig_ctx_creator is introduced to allow tests to use a mock class for
  246. # easier tests (in normal case we always use the default)
  247. self._tsig_ctx_creator = self.__create_tsig_ctx
  248. def __create_tsig_ctx(self, key):
  249. return TSIGContext(key)
  250. def _get_datasrc_client(self, rrclass):
  251. # Create a client here once #1206 is done
  252. return None
  253. def __set_xfrstate(self, new_state):
  254. self.__state = new_state
  255. def get_xfrstate(self):
  256. return self.__state
  257. def zone_str(self):
  258. '''A convenient function for logging to include zone name and class'''
  259. return self._zone_name.to_text() + '/' + str(self._rrclass)
  260. def connect_to_master(self):
  261. '''Connect to master in TCP.'''
  262. try:
  263. self.connect(self._master_address)
  264. return True
  265. except socket.error as e:
  266. logger.error(XFRIN_CONNECT_MASTER, self._master_address, str(e))
  267. return False
  268. def _create_query(self, query_type):
  269. '''Create an XFR-related query message.
  270. query_type is either SOA, AXFR or IXFR. For type IXFR, it searches
  271. the associated data source for the current SOA record to include
  272. it in the query. If the corresponding zone or the SOA record
  273. cannot be found, it raises an XfrinException exception. Note that
  274. this may not necessarily a broken configuration; for the first attempt
  275. of transfer the secondary may not have any boot-strap zone
  276. information, in which case IXFR simply won't work. The xfrin
  277. should then fall back to AXFR. _request_serial is recorded for
  278. later use.
  279. '''
  280. msg = Message(Message.RENDER)
  281. query_id = random.randint(0, 0xFFFF)
  282. self._query_id = query_id
  283. msg.set_qid(query_id)
  284. msg.set_opcode(Opcode.QUERY())
  285. msg.set_rcode(Rcode.NOERROR())
  286. msg.add_question(Question(self._zone_name, self._rrclass, query_type))
  287. if query_type == RRType.IXFR():
  288. # get the zone finder. this must be SUCCESS (not even
  289. # PARTIALMATCH) because we are specifying the zone origin name.
  290. result, finder = self._datasrc_client.find_zone(self._zone_name)
  291. if result != DataSourceClient.SUCCESS:
  292. raise XfrinException('Zone not found in the given data ' +
  293. 'source: ' + self.zone_str())
  294. result, soa_rrset = finder.find(self._zone_name, RRType.SOA(),
  295. None, ZoneFinder.FIND_DEFAULT)
  296. if result != ZoneFinder.SUCCESS:
  297. raise XfrinException('SOA RR not found in zone: ' +
  298. self.zone_str())
  299. # Especially for database-based zones, working zones may be in
  300. # a broken state where it has more than one SOA RR. We proactively
  301. # check the condition and abort the xfr attempt if we identify it.
  302. if soa_rrset.get_rdata_count() != 1:
  303. raise XfrinException('Invalid number of SOA RRs for ' +
  304. self.zone_str() + ': ' +
  305. str(soa_rrset.get_rdata_count()))
  306. msg.add_rrset(Message.SECTION_AUTHORITY, soa_rrset)
  307. self._request_serial = get_soa_serial(soa_rrset.get_rdata()[0])
  308. return msg
  309. def _send_data(self, data):
  310. size = len(data)
  311. total_count = 0
  312. while total_count < size:
  313. count = self.send(data[total_count:])
  314. total_count += count
  315. def _send_query(self, query_type):
  316. '''Send query message over TCP. '''
  317. msg = self._create_query(query_type)
  318. render = MessageRenderer()
  319. # XXX Currently, python wrapper doesn't accept 'None' parameter in this case,
  320. # we should remove the if statement and use a universal interface later.
  321. if self._tsig_key is not None:
  322. self._tsig_ctx = self._tsig_ctx_creator(self._tsig_key)
  323. msg.to_wire(render, self._tsig_ctx)
  324. else:
  325. msg.to_wire(render)
  326. header_len = struct.pack('H', socket.htons(render.get_length()))
  327. self._send_data(header_len)
  328. self._send_data(render.get_data())
  329. def _asyncore_loop(self):
  330. '''
  331. This method is a trivial wrapper for asyncore.loop(). It's extracted from
  332. _get_request_response so that we can test the rest of the code without
  333. involving actual communication with a remote server.'''
  334. asyncore.loop(self._idle_timeout, map=self._sock_map, count=1)
  335. def _get_request_response(self, size):
  336. recv_size = 0
  337. data = b''
  338. while recv_size < size:
  339. self._recv_time_out = True
  340. self._need_recv_size = size - recv_size
  341. self._asyncore_loop()
  342. if self._recv_time_out:
  343. raise XfrinException('receive data from socket time out.')
  344. recv_size += self._recvd_size
  345. data += self._recvd_data
  346. return data
  347. def _check_response_tsig(self, msg, response_data):
  348. tsig_record = msg.get_tsig_record()
  349. if self._tsig_ctx is not None:
  350. tsig_error = self._tsig_ctx.verify(tsig_record, response_data)
  351. if tsig_error != TSIGError.NOERROR:
  352. raise XfrinException('TSIG verify fail: %s' % str(tsig_error))
  353. elif tsig_record is not None:
  354. # If the response includes a TSIG while we didn't sign the query,
  355. # we treat it as an error. RFC doesn't say anything about this
  356. # case, but it clearly states the server must not sign a response
  357. # to an unsigned request. Although we could be flexible, no sane
  358. # implementation would return such a response, and since this is
  359. # part of security mechanism, it's probably better to be more
  360. # strict.
  361. raise XfrinException('Unexpected TSIG in response')
  362. def _check_soa_serial(self):
  363. ''' Compare the soa serial, if soa serial in master is less than
  364. the soa serial in local, Finish xfrin.
  365. False: soa serial in master is less or equal to the local one.
  366. True: soa serial in master is bigger
  367. '''
  368. self._send_query(RRType.SOA())
  369. data_len = self._get_request_response(2)
  370. msg_len = socket.htons(struct.unpack('H', data_len)[0])
  371. soa_response = self._get_request_response(msg_len)
  372. msg = Message(Message.PARSE)
  373. msg.from_wire(soa_response)
  374. # TSIG related checks, including an unexpected signed response
  375. self._check_response_tsig(msg, soa_response)
  376. # perform some minimal level validation. It's an open issue how
  377. # strict we should be (see the comment in _check_response_header())
  378. self._check_response_header(msg)
  379. # TODO, need select soa record from data source then compare the two
  380. # serial, current just return OK, since this function hasn't been used
  381. # now.
  382. return XFRIN_OK
  383. def do_xfrin(self, check_soa, ixfr_first=False):
  384. '''Do an xfr session by sending xfr request and parsing responses.'''
  385. try:
  386. ret = XFRIN_OK
  387. if check_soa:
  388. logstr = 'SOA check for \'%s\' ' % self.zone_str()
  389. ret = self._check_soa_serial()
  390. if ret == XFRIN_OK:
  391. if not ixfr_first:
  392. logger.info(XFRIN_AXFR_TRANSFER_STARTED, self.zone_str())
  393. self._send_query(RRType.AXFR())
  394. isc.datasrc.sqlite3_ds.load(self._db_file,
  395. self._zone_name.to_text(),
  396. self._handle_axfrin_response)
  397. logger.info(XFRIN_AXFR_TRANSFER_SUCCESS, self.zone_str())
  398. except XfrinException as e:
  399. logger.error(XFRIN_AXFR_TRANSFER_FAILURE, self.zone_str(), str(e))
  400. ret = XFRIN_FAIL
  401. #TODO, recover data source.
  402. except isc.datasrc.sqlite3_ds.Sqlite3DSError as e:
  403. logger.error(XFRIN_AXFR_DATABASE_FAILURE, self.zone_str(), str(e))
  404. ret = XFRIN_FAIL
  405. except UserWarning as e:
  406. # XXX: this is an exception from our C++ library via the
  407. # Boost.Python binding. It would be better to have more more
  408. # specific exceptions, but at this moment this is the finest
  409. # granularity.
  410. logger.error(XFRIN_AXFR_INTERNAL_FAILURE, self.zone_str(), str(e))
  411. ret = XFRIN_FAIL
  412. finally:
  413. self.close()
  414. return ret
  415. def _check_response_header(self, msg):
  416. '''Perform minimal validation on responses'''
  417. # It's not clear how strict we should be about response validation.
  418. # BIND 9 ignores some cases where it would normally be considered a
  419. # bogus response. For example, it accepts a response even if its
  420. # opcode doesn't match that of the corresponding request.
  421. # According to an original developer of BIND 9 some of the missing
  422. # checks are deliberate to be kind to old implementations that would
  423. # cause interoperability trouble with stricter checks.
  424. msg_rcode = msg.get_rcode()
  425. if msg_rcode != Rcode.NOERROR():
  426. raise XfrinException('error response: %s' % msg_rcode.to_text())
  427. if not msg.get_header_flag(Message.HEADERFLAG_QR):
  428. raise XfrinException('response is not a response')
  429. if msg.get_qid() != self._query_id:
  430. raise XfrinException('bad query id')
  431. def _check_response_status(self, msg):
  432. '''Check validation of xfr response. '''
  433. self._check_response_header(msg)
  434. if msg.get_rr_count(Message.SECTION_ANSWER) == 0:
  435. raise XfrinException('answer section is empty')
  436. if msg.get_rr_count(Message.SECTION_QUESTION) > 1:
  437. raise XfrinException('query section count greater than 1')
  438. def _handle_answer_section(self, answer_section):
  439. '''Return a generator for the reponse in one tcp package to a zone transfer.'''
  440. for rrset in answer_section:
  441. rrset_name = rrset.get_name().to_text()
  442. rrset_ttl = int(rrset.get_ttl().to_text())
  443. rrset_class = rrset.get_class().to_text()
  444. rrset_type = rrset.get_type().to_text()
  445. for rdata in rrset.get_rdata():
  446. # Count the soa record count
  447. if rrset.get_type() == RRType.SOA():
  448. self._soa_rr_count += 1
  449. # XXX: the current DNS message parser can't preserve the
  450. # RR order or separete the beginning and ending SOA RRs.
  451. # As a short term workaround, we simply ignore the second
  452. # SOA, and ignore the erroneous case where the transfer
  453. # session doesn't end with an SOA.
  454. if (self._soa_rr_count == 2):
  455. # Avoid inserting soa record twice
  456. break
  457. rdata_text = rdata.to_text()
  458. yield (rrset_name, rrset_ttl, rrset_class, rrset_type,
  459. rdata_text)
  460. def _handle_axfrin_response(self):
  461. '''Return a generator for the response to a zone transfer. '''
  462. while True:
  463. data_len = self._get_request_response(2)
  464. msg_len = socket.htons(struct.unpack('H', data_len)[0])
  465. recvdata = self._get_request_response(msg_len)
  466. msg = Message(Message.PARSE)
  467. msg.from_wire(recvdata)
  468. # TSIG related checks, including an unexpected signed response
  469. self._check_response_tsig(msg, recvdata)
  470. # Perform response status validation
  471. self._check_response_status(msg)
  472. answer_section = msg.get_section(Message.SECTION_ANSWER)
  473. for rr in self._handle_answer_section(answer_section):
  474. yield rr
  475. if self._soa_rr_count == 2:
  476. break
  477. if self._shutdown_event.is_set():
  478. raise XfrinException('xfrin is forced to stop')
  479. def handle_read(self):
  480. '''Read query's response from socket. '''
  481. self._recvd_data = self.recv(self._need_recv_size)
  482. self._recvd_size = len(self._recvd_data)
  483. self._recv_time_out = False
  484. def writable(self):
  485. '''Ignore the writable socket. '''
  486. return False
  487. def log_info(self, msg, type='info'):
  488. # Overwrite the log function, log nothing
  489. pass
  490. def process_xfrin(server, xfrin_recorder, zone_name, rrclass, db_file,
  491. shutdown_event, master_addrinfo, check_soa, verbose,
  492. tsig_key):
  493. xfrin_recorder.increment(zone_name)
  494. sock_map = {}
  495. conn = XfrinConnection(sock_map, zone_name, rrclass, db_file,
  496. shutdown_event, master_addrinfo,
  497. tsig_key, verbose)
  498. ret = XFRIN_FAIL
  499. if conn.connect_to_master():
  500. ret = conn.do_xfrin(check_soa)
  501. # Publish the zone transfer result news, so zonemgr can reset the
  502. # zone timer, and xfrout can notify the zone's slaves if the result
  503. # is success.
  504. server.publish_xfrin_news(zone_name, rrclass, ret)
  505. xfrin_recorder.decrement(zone_name)
  506. class XfrinRecorder:
  507. def __init__(self):
  508. self._lock = threading.Lock()
  509. self._zones = []
  510. def increment(self, zone_name):
  511. self._lock.acquire()
  512. self._zones.append(zone_name)
  513. self._lock.release()
  514. def decrement(self, zone_name):
  515. self._lock.acquire()
  516. if zone_name in self._zones:
  517. self._zones.remove(zone_name)
  518. self._lock.release()
  519. def xfrin_in_progress(self, zone_name):
  520. self._lock.acquire()
  521. ret = zone_name in self._zones
  522. self._lock.release()
  523. return ret
  524. def count(self):
  525. self._lock.acquire()
  526. ret = len(self._zones)
  527. self._lock.release()
  528. return ret
  529. class ZoneInfo:
  530. def __init__(self, config_data, module_cc):
  531. """Creates a zone_info with the config data element as
  532. specified by the 'zones' list in xfrin.spec. Module_cc is
  533. needed to get the defaults from the specification"""
  534. self._module_cc = module_cc
  535. self.set_name(config_data.get('name'))
  536. self.set_master_addr(config_data.get('master_addr'))
  537. self.set_master_port(config_data.get('master_port'))
  538. self.set_zone_class(config_data.get('class'))
  539. self.set_tsig_key(config_data.get('tsig_key'))
  540. self.set_ixfr_disabled(config_data.get('ixfr_disabled'))
  541. def set_name(self, name_str):
  542. """Set the name for this zone given a name string.
  543. Raises XfrinZoneInfoException if name_str is None or if it
  544. cannot be parsed."""
  545. if name_str is None:
  546. raise XfrinZoneInfoException("Configuration zones list "
  547. "element does not contain "
  548. "'name' attribute")
  549. else:
  550. self.name = _check_zone_name(name_str)
  551. def set_master_addr(self, master_addr_str):
  552. """Set the master address for this zone given an IP address
  553. string. Raises XfrinZoneInfoException if master_addr_str is
  554. None or if it cannot be parsed."""
  555. if master_addr_str is None:
  556. raise XfrinZoneInfoException("master address missing from config data")
  557. else:
  558. try:
  559. self.master_addr = isc.net.parse.addr_parse(master_addr_str)
  560. except ValueError:
  561. logger.error(XFRIN_BAD_MASTER_ADDR_FORMAT, master_addr_str)
  562. errmsg = "bad format for zone's master: " + master_addr_str
  563. raise XfrinZoneInfoException(errmsg)
  564. def set_master_port(self, master_port_str):
  565. """Set the master port given a port number string. If
  566. master_port_str is None, the default from the specification
  567. for this module will be used. Raises XfrinZoneInfoException if
  568. the string contains an invalid port number"""
  569. if master_port_str is None:
  570. self.master_port = self._module_cc.get_default_value("zones/master_port")
  571. else:
  572. try:
  573. self.master_port = isc.net.parse.port_parse(master_port_str)
  574. except ValueError:
  575. logger.error(XFRIN_BAD_MASTER_PORT_FORMAT, master_port_str)
  576. errmsg = "bad format for zone's master port: " + master_port_str
  577. raise XfrinZoneInfoException(errmsg)
  578. def set_zone_class(self, zone_class_str):
  579. """Set the zone class given an RR class str (e.g. "IN"). If
  580. zone_class_str is None, it will default to what is specified
  581. in the specification file for this module. Raises
  582. XfrinZoneInfoException if the string cannot be parsed."""
  583. # TODO: remove _str
  584. self.class_str = zone_class_str or self._module_cc.get_default_value("zones/class")
  585. if zone_class_str == None:
  586. #TODO rrclass->zone_class
  587. self.rrclass = RRClass(self._module_cc.get_default_value("zones/class"))
  588. else:
  589. try:
  590. self.rrclass = RRClass(zone_class_str)
  591. except InvalidRRClass:
  592. logger.error(XFRIN_BAD_ZONE_CLASS, zone_class_str)
  593. errmsg = "invalid zone class: " + zone_class_str
  594. raise XfrinZoneInfoException(errmsg)
  595. def set_tsig_key(self, tsig_key_str):
  596. """Set the tsig_key for this zone, given a TSIG key string
  597. representation. If tsig_key_str is None, no TSIG key will
  598. be set. Raises XfrinZoneInfoException if tsig_key_str cannot
  599. be parsed."""
  600. if tsig_key_str is None:
  601. self.tsig_key = None
  602. else:
  603. try:
  604. self.tsig_key = TSIGKey(tsig_key_str)
  605. except InvalidParameter as ipe:
  606. logger.error(XFRIN_BAD_TSIG_KEY_STRING, tsig_key_str)
  607. errmsg = "bad TSIG key string: " + tsig_key_str
  608. raise XfrinZoneInfoException(errmsg)
  609. def set_ixfr_disabled(self, ixfr_disabled):
  610. """Set ixfr_disabled. If set to False (the default), it will use
  611. IXFR for incoming transfers. If set to True, it will use AXFR.
  612. At this moment there is no automatic fallback"""
  613. # don't care what type it is; if evaluates to true, set to True
  614. if ixfr_disabled:
  615. self.ixfr_disabled = True
  616. else:
  617. self.ixfr_disabled = False
  618. def get_master_addr_info(self):
  619. return (self.master_addr.family, socket.SOCK_STREAM,
  620. (str(self.master_addr), self.master_port))
  621. class Xfrin:
  622. def __init__(self, verbose = False):
  623. self._max_transfers_in = 10
  624. self._zones = {}
  625. self._cc_setup()
  626. self.recorder = XfrinRecorder()
  627. self._shutdown_event = threading.Event()
  628. self._verbose = verbose
  629. def _cc_setup(self):
  630. '''This method is used only as part of initialization, but is
  631. implemented separately for convenience of unit tests; by letting
  632. the test code override this method we can test most of this class
  633. without requiring a command channel.'''
  634. # Create one session for sending command to other modules, because the
  635. # listening session will block the send operation.
  636. self._send_cc_session = isc.cc.Session()
  637. self._module_cc = isc.config.ModuleCCSession(SPECFILE_LOCATION,
  638. self.config_handler,
  639. self.command_handler)
  640. self._module_cc.start()
  641. config_data = self._module_cc.get_full_config()
  642. self.config_handler(config_data)
  643. def _cc_check_command(self):
  644. '''This is a straightforward wrapper for cc.check_command,
  645. but provided as a separate method for the convenience
  646. of unit tests.'''
  647. self._module_cc.check_command(False)
  648. def _get_zone_info(self, name, rrclass):
  649. """Returns the ZoneInfo object containing the configured data
  650. for the given zone name. If the zone name did not have any
  651. data, returns None"""
  652. return self._zones.get((name.to_text(), rrclass.to_text()))
  653. def _add_zone_info(self, zone_info):
  654. """Add the zone info. Raises a XfrinZoneInfoException if a zone
  655. with the same name and class is already configured"""
  656. key = (zone_info.name.to_text(), zone_info.class_str)
  657. if key in self._zones:
  658. raise XfrinZoneInfoException("zone " + str(key) +
  659. " configured multiple times")
  660. self._zones[key] = zone_info
  661. def _clear_zone_info(self):
  662. self._zones = {}
  663. def config_handler(self, new_config):
  664. # backup all config data (should there be a problem in the new
  665. # data)
  666. old_max_transfers_in = self._max_transfers_in
  667. old_zones = self._zones
  668. self._max_transfers_in = new_config.get("transfers_in") or self._max_transfers_in
  669. if 'zones' in new_config:
  670. self._clear_zone_info()
  671. for zone_config in new_config.get('zones'):
  672. try:
  673. zone_info = ZoneInfo(zone_config, self._module_cc)
  674. self._add_zone_info(zone_info)
  675. except XfrinZoneInfoException as xce:
  676. self._zones = old_zones
  677. self._max_transfers_in = old_max_transfers_in
  678. return create_answer(1, str(xce))
  679. return create_answer(0)
  680. def shutdown(self):
  681. ''' shutdown the xfrin process. the thread which is doing xfrin should be
  682. terminated.
  683. '''
  684. self._shutdown_event.set()
  685. main_thread = threading.currentThread()
  686. for th in threading.enumerate():
  687. if th is main_thread:
  688. continue
  689. th.join()
  690. def command_handler(self, command, args):
  691. answer = create_answer(0)
  692. try:
  693. if command == 'shutdown':
  694. self._shutdown_event.set()
  695. elif command == 'notify' or command == REFRESH_FROM_ZONEMGR:
  696. # Xfrin receives the refresh/notify command from zone manager.
  697. # notify command maybe has the parameters which
  698. # specify the notifyfrom address and port, according the RFC1996, zone
  699. # transfer should starts first from the notifyfrom, but now, let 'TODO' it.
  700. # (using the value now, while we can only set one master address, would be
  701. # a security hole. Once we add the ability to have multiple master addresses,
  702. # we should check if it matches one of them, and then use it.)
  703. (zone_name, rrclass) = self._parse_zone_name_and_class(args)
  704. zone_info = self._get_zone_info(zone_name, rrclass)
  705. if zone_info is None:
  706. # TODO what to do? no info known about zone. defaults?
  707. errmsg = "Got notification to retransfer unknown zone " + zone_name.to_text()
  708. logger.error(XFRIN_RETRANSFER_UNKNOWN_ZONE, zone_name.to_text())
  709. answer = create_answer(1, errmsg)
  710. else:
  711. master_addr = zone_info.get_master_addr_info()
  712. ret = self.xfrin_start(zone_name,
  713. rrclass,
  714. self._get_db_file(),
  715. master_addr,
  716. zone_info.tsig_key,
  717. True)
  718. answer = create_answer(ret[0], ret[1])
  719. elif command == 'retransfer' or command == 'refresh':
  720. # Xfrin receives the retransfer/refresh from cmdctl(sent by bindctl).
  721. # If the command has specified master address, do transfer from the
  722. # master address, or else do transfer from the configured masters.
  723. (zone_name, rrclass) = self._parse_zone_name_and_class(args)
  724. master_addr = self._parse_master_and_port(args, zone_name,
  725. rrclass)
  726. zone_info = self._get_zone_info(zone_name, rrclass)
  727. tsig_key = None
  728. if zone_info:
  729. tsig_key = zone_info.tsig_key
  730. db_file = args.get('db_file') or self._get_db_file()
  731. ret = self.xfrin_start(zone_name,
  732. rrclass,
  733. db_file,
  734. master_addr,
  735. tsig_key,
  736. (False if command == 'retransfer' else True))
  737. answer = create_answer(ret[0], ret[1])
  738. else:
  739. answer = create_answer(1, 'unknown command: ' + command)
  740. except XfrinException as err:
  741. logger.error(XFRIN_COMMAND_ERROR, command, str(err))
  742. answer = create_answer(1, str(err))
  743. return answer
  744. def _parse_zone_name_and_class(self, args):
  745. zone_name_str = args.get('zone_name')
  746. if zone_name_str is None:
  747. raise XfrinException('zone name should be provided')
  748. return (_check_zone_name(zone_name_str), _check_zone_class(args.get('zone_class')))
  749. def _parse_master_and_port(self, args, zone_name, zone_class):
  750. """
  751. Return tuple (family, socktype, sockaddr) for address and port in given
  752. args dict.
  753. IPv4 and IPv6 are the only supported addresses now, so sockaddr will be
  754. (address, port). The socktype is socket.SOCK_STREAM for now.
  755. """
  756. # check if we have configured info about this zone, in case
  757. # port or master are not specified
  758. zone_info = self._get_zone_info(zone_name, zone_class)
  759. addr_str = args.get('master')
  760. if addr_str is None:
  761. if zone_info is not None:
  762. addr = zone_info.master_addr
  763. else:
  764. raise XfrinException("Master address not given or "
  765. "configured for " + zone_name.to_text())
  766. else:
  767. try:
  768. addr = isc.net.parse.addr_parse(addr_str)
  769. except ValueError as err:
  770. raise XfrinException("failed to resolve master address %s: %s" %
  771. (addr_str, str(err)))
  772. port_str = args.get('port')
  773. if port_str is None:
  774. if zone_info is not None:
  775. port = zone_info.master_port
  776. else:
  777. port = DEFAULT_MASTER_PORT
  778. else:
  779. try:
  780. port = isc.net.parse.port_parse(port_str)
  781. except ValueError as err:
  782. raise XfrinException("failed to parse port=%s: %s" %
  783. (port_str, str(err)))
  784. return (addr.family, socket.SOCK_STREAM, (str(addr), port))
  785. def _get_db_file(self):
  786. #TODO, the db file path should be got in auth server's configuration
  787. # if we need access to this configuration more often, we
  788. # should add it on start, and not remove it here
  789. # (or, if we have writable ds, we might not need this in
  790. # the first place)
  791. self._module_cc.add_remote_config(AUTH_SPECFILE_LOCATION)
  792. db_file, is_default = self._module_cc.get_remote_config_value("Auth", "database_file")
  793. if is_default and "B10_FROM_BUILD" in os.environ:
  794. # this too should be unnecessary, but currently the
  795. # 'from build' override isn't stored in the config
  796. # (and we don't have writable datasources yet)
  797. db_file = os.environ["B10_FROM_BUILD"] + os.sep + "bind10_zones.sqlite3"
  798. self._module_cc.remove_remote_config(AUTH_SPECFILE_LOCATION)
  799. return db_file
  800. def publish_xfrin_news(self, zone_name, zone_class, xfr_result):
  801. '''Send command to xfrout/zone manager module.
  802. If xfrin has finished successfully for one zone, tell the good
  803. news(command: zone_new_data_ready) to zone manager and xfrout.
  804. if xfrin failed, just tell the bad news to zone manager, so that
  805. it can reset the refresh timer for that zone. '''
  806. param = {'zone_name': zone_name, 'zone_class': zone_class.to_text()}
  807. if xfr_result == XFRIN_OK:
  808. msg = create_command(notify_out.ZONE_NEW_DATA_READY_CMD, param)
  809. # catch the exception, in case msgq has been killed.
  810. try:
  811. seq = self._send_cc_session.group_sendmsg(msg,
  812. XFROUT_MODULE_NAME)
  813. try:
  814. answer, env = self._send_cc_session.group_recvmsg(False,
  815. seq)
  816. except isc.cc.session.SessionTimeout:
  817. pass # for now we just ignore the failure
  818. seq = self._send_cc_session.group_sendmsg(msg, ZONE_MANAGER_MODULE_NAME)
  819. try:
  820. answer, env = self._send_cc_session.group_recvmsg(False,
  821. seq)
  822. except isc.cc.session.SessionTimeout:
  823. pass # for now we just ignore the failure
  824. except socket.error as err:
  825. logger.error(XFRIN_MSGQ_SEND_ERROR, XFROUT_MODULE_NAME, ZONE_MANAGER_MODULE_NAME)
  826. else:
  827. msg = create_command(ZONE_XFRIN_FAILED, param)
  828. # catch the exception, in case msgq has been killed.
  829. try:
  830. seq = self._send_cc_session.group_sendmsg(msg, ZONE_MANAGER_MODULE_NAME)
  831. try:
  832. answer, env = self._send_cc_session.group_recvmsg(False,
  833. seq)
  834. except isc.cc.session.SessionTimeout:
  835. pass # for now we just ignore the failure
  836. except socket.error as err:
  837. logger.error(XFRIN_MSGQ_SEND_ERROR_ZONE_MANAGER, ZONE_MANAGER_MODULE_NAME)
  838. def startup(self):
  839. while not self._shutdown_event.is_set():
  840. self._cc_check_command()
  841. def xfrin_start(self, zone_name, rrclass, db_file, master_addrinfo, tsig_key,
  842. check_soa = True):
  843. if "pydnspp" not in sys.modules:
  844. return (1, "xfrin failed, can't load dns message python library: 'pydnspp'")
  845. # check max_transfer_in, else return quota error
  846. if self.recorder.count() >= self._max_transfers_in:
  847. return (1, 'xfrin quota error')
  848. if self.recorder.xfrin_in_progress(zone_name):
  849. return (1, 'zone xfrin is in progress')
  850. xfrin_thread = threading.Thread(target = process_xfrin,
  851. args = (self,
  852. self.recorder,
  853. zone_name,
  854. rrclass,
  855. db_file,
  856. self._shutdown_event,
  857. master_addrinfo, check_soa,
  858. self._verbose,
  859. tsig_key))
  860. xfrin_thread.start()
  861. return (0, 'zone xfrin is started')
  862. xfrind = None
  863. def signal_handler(signal, frame):
  864. if xfrind:
  865. xfrind.shutdown()
  866. sys.exit(0)
  867. def set_signal_handler():
  868. signal.signal(signal.SIGTERM, signal_handler)
  869. signal.signal(signal.SIGINT, signal_handler)
  870. def set_cmd_options(parser):
  871. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  872. help="display more about what is going on")
  873. def main(xfrin_class, use_signal = True):
  874. """The main loop of the Xfrin daemon.
  875. @param xfrin_class: A class of the Xfrin object. This is normally Xfrin,
  876. but can be a subclass of it for customization.
  877. @param use_signal: True if this process should catch signals. This is
  878. normally True, but may be disabled when this function is called in a
  879. testing context."""
  880. global xfrind
  881. try:
  882. parser = OptionParser(version = __version__)
  883. set_cmd_options(parser)
  884. (options, args) = parser.parse_args()
  885. if use_signal:
  886. set_signal_handler()
  887. xfrind = xfrin_class(verbose = options.verbose)
  888. xfrind.startup()
  889. except KeyboardInterrupt:
  890. logger.info(XFRIN_STOPPED_BY_KEYBOARD)
  891. except isc.cc.session.SessionError as e:
  892. logger.error(XFRIN_CC_SESSION_ERROR, str(e))
  893. except Exception as e:
  894. logger.error(XFRIN_UNKNOWN_ERROR, str(e))
  895. if xfrind:
  896. xfrind.shutdown()
  897. if __name__ == '__main__':
  898. main(Xfrin)