xfrout.py.in 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. #!@PYTHON@
  2. # Copyright (C) 2010 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 isc
  18. import isc.cc
  19. import threading
  20. import struct
  21. import signal
  22. from isc.datasrc import DataSourceClient, ZoneFinder, ZoneJournalReader
  23. from socketserver import *
  24. import os
  25. from isc.config.ccsession import *
  26. from isc.cc import SessionError, SessionTimeout
  27. from isc.notify import notify_out
  28. import isc.util.process
  29. import socket
  30. import select
  31. import errno
  32. from optparse import OptionParser, OptionValueError
  33. from isc.util import socketserver_mixin
  34. from isc.log_messages.xfrout_messages import *
  35. isc.log.init("b10-xfrout")
  36. logger = isc.log.Logger("xfrout")
  37. DBG_XFROUT_TRACE = logger.DBGLVL_TRACE_BASIC
  38. try:
  39. from libutil_io_python import *
  40. from pydnspp import *
  41. except ImportError as e:
  42. # C++ loadable module may not be installed; even so the xfrout process
  43. # must keep running, so we warn about it and move forward.
  44. logger.error(XFROUT_IMPORT, str(e))
  45. from isc.acl.acl import ACCEPT, REJECT, DROP, LoaderError
  46. from isc.acl.dns import REQUEST_LOADER
  47. isc.util.process.rename()
  48. class XfroutConfigError(Exception):
  49. """An exception indicating an error in updating xfrout configuration.
  50. This exception is raised when the xfrout process encouters an error in
  51. handling configuration updates. Not all syntax error can be caught
  52. at the module-CC layer, so xfrout needs to (explicitly or implicitly)
  53. validate the given configuration data itself. When it finds an error
  54. it raises this exception (either directly or by converting an exception
  55. from other modules) as a unified error in configuration.
  56. """
  57. pass
  58. class XfroutSessionError(Exception):
  59. '''An exception raised for some unexpected events during an xfrout session.
  60. '''
  61. pass
  62. def init_paths():
  63. global SPECFILE_PATH
  64. global AUTH_SPECFILE_PATH
  65. global UNIX_SOCKET_FILE
  66. if "B10_FROM_BUILD" in os.environ:
  67. SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/xfrout"
  68. AUTH_SPECFILE_PATH = os.environ["B10_FROM_BUILD"] + "/src/bin/auth"
  69. if "B10_FROM_SOURCE_LOCALSTATEDIR" in os.environ:
  70. UNIX_SOCKET_FILE = os.environ["B10_FROM_SOURCE_LOCALSTATEDIR"] + \
  71. "/auth_xfrout_conn"
  72. else:
  73. UNIX_SOCKET_FILE = os.environ["B10_FROM_BUILD"] + "/auth_xfrout_conn"
  74. else:
  75. PREFIX = "@prefix@"
  76. DATAROOTDIR = "@datarootdir@"
  77. SPECFILE_PATH = "@datadir@/@PACKAGE@".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  78. AUTH_SPECFILE_PATH = SPECFILE_PATH
  79. if "BIND10_XFROUT_SOCKET_FILE" in os.environ:
  80. UNIX_SOCKET_FILE = os.environ["BIND10_XFROUT_SOCKET_FILE"]
  81. else:
  82. UNIX_SOCKET_FILE = "@@LOCALSTATEDIR@@/@PACKAGE_NAME@/auth_xfrout_conn"
  83. init_paths()
  84. SPECFILE_LOCATION = SPECFILE_PATH + "/xfrout.spec"
  85. AUTH_SPECFILE_LOCATION = AUTH_SPECFILE_PATH + os.sep + "auth.spec"
  86. VERBOSE_MODE = False
  87. XFROUT_DNS_HEADER_SIZE = 12 # protocol constant
  88. XFROUT_MAX_MESSAGE_SIZE = 65535 # ditto
  89. # borrowed from xfrin.py @ #1298. We should eventually unify it.
  90. def format_zone_str(zone_name, zone_class):
  91. """Helper function to format a zone name and class as a string of
  92. the form '<name>/<class>'.
  93. Parameters:
  94. zone_name (isc.dns.Name) name to format
  95. zone_class (isc.dns.RRClass) class to format
  96. """
  97. return zone_name.to_text(True) + '/' + str(zone_class)
  98. # borrowed from xfrin.py @ #1298.
  99. def format_addrinfo(addrinfo):
  100. """Helper function to format the addrinfo as a string of the form
  101. <addr>:<port> (for IPv4) or [<addr>]:port (for IPv6). For unix domain
  102. sockets, and unknown address families, it returns a basic string
  103. conversion of the third element of the passed tuple.
  104. Parameters:
  105. addrinfo: a 3-tuple consisting of address family, socket type, and,
  106. depending on the family, either a 2-tuple with the address
  107. and port, or a filename
  108. """
  109. try:
  110. if addrinfo[0] == socket.AF_INET:
  111. return str(addrinfo[2][0]) + ":" + str(addrinfo[2][1])
  112. elif addrinfo[0] == socket.AF_INET6:
  113. return "[" + str(addrinfo[2][0]) + "]:" + str(addrinfo[2][1])
  114. else:
  115. return str(addrinfo[2])
  116. except IndexError:
  117. raise TypeError("addrinfo argument to format_addrinfo() does not "
  118. "appear to be consisting of (family, socktype, (addr, port))")
  119. def get_rrset_len(rrset):
  120. """Returns the wire length of the given RRset"""
  121. bytes = bytearray()
  122. rrset.to_wire(bytes)
  123. return len(bytes)
  124. def get_soa_serial(soa_rdata):
  125. '''Extract the serial field of an SOA RDATA and returns it as an Serial object.
  126. '''
  127. return Serial(int(soa_rdata.to_text().split()[2]))
  128. class XfroutSession():
  129. def __init__(self, sock_fd, request_data, server, tsig_key_ring, remote,
  130. default_acl, zone_config, client_class=DataSourceClient):
  131. self._sock_fd = sock_fd
  132. self._request_data = request_data
  133. self._server = server
  134. self._tsig_key_ring = tsig_key_ring
  135. self._tsig_ctx = None
  136. self._tsig_len = 0
  137. self._remote = remote
  138. self._request_type = None
  139. self._request_typestr = None
  140. self._acl = default_acl
  141. self._zone_config = zone_config
  142. self.ClientClass = client_class # parameterize this for testing
  143. self._soa = None # will be set in _xfrout_setup or in tests
  144. self._jnl_reader = None # will be set to a reader for IXFR
  145. self._handle()
  146. def create_tsig_ctx(self, tsig_record, tsig_key_ring):
  147. return TSIGContext(tsig_record.get_name(), tsig_record.get_rdata().get_algorithm(),
  148. tsig_key_ring)
  149. def _handle(self):
  150. ''' Handle a xfrout query, send xfrout response(s).
  151. This is separated from the constructor so that we can override
  152. it from tests.
  153. '''
  154. # Check the xfrout quota. We do both increase/decrease in this
  155. # method so it's clear we always release it once acuired.
  156. quota_ok = self._server.increase_transfers_counter()
  157. ex = None
  158. try:
  159. self.dns_xfrout_start(self._sock_fd, self._request_data, quota_ok)
  160. except Exception as e:
  161. # To avoid resource leak we need catch all possible exceptions
  162. # We log it later to exclude the case where even logger raises
  163. # an exception.
  164. ex = e
  165. # Release any critical resources
  166. if quota_ok:
  167. self._server.decrease_transfers_counter()
  168. self._close_socket()
  169. if ex is not None:
  170. logger.error(XFROUT_HANDLE_QUERY_ERROR, ex)
  171. def _close_socket(self):
  172. '''Simply close the socket via the given FD.
  173. This is a dedicated subroutine of handle() and is sepsarated from it
  174. for the convenience of tests.
  175. '''
  176. os.close(self._sock_fd)
  177. def _check_request_tsig(self, msg, request_data):
  178. ''' If request has a tsig record, perform tsig related checks '''
  179. tsig_record = msg.get_tsig_record()
  180. if tsig_record is not None:
  181. self._tsig_len = tsig_record.get_length()
  182. self._tsig_ctx = self.create_tsig_ctx(tsig_record,
  183. self._tsig_key_ring)
  184. tsig_error = self._tsig_ctx.verify(tsig_record, request_data)
  185. if tsig_error != TSIGError.NOERROR:
  186. return Rcode.NOTAUTH()
  187. return Rcode.NOERROR()
  188. def _parse_query_message(self, mdata):
  189. ''' parse query message to [socket,message]'''
  190. #TODO, need to add parseHeader() in case the message header is invalid
  191. try:
  192. msg = Message(Message.PARSE)
  193. Message.from_wire(msg, mdata)
  194. except Exception as err: # Exception is too broad
  195. logger.error(XFROUT_PARSE_QUERY_ERROR, err)
  196. return Rcode.FORMERR(), None
  197. # TSIG related checks
  198. rcode = self._check_request_tsig(msg, mdata)
  199. if rcode != Rcode.NOERROR():
  200. return rcode, msg
  201. # Make sure the question is valid. This should be ensured by
  202. # the auth server, but since it's far from xfrout itself, we check
  203. # it by ourselves. A viloation would be an internal bug, so we
  204. # raise and stop here rather than returning a FORMERR or SERVFAIL.
  205. if msg.get_rr_count(Message.SECTION_QUESTION) != 1:
  206. raise RuntimeError('Invalid number of question for XFR: ' +
  207. str(msg.get_rr_count(Message.SECTION_QUESTION)))
  208. question = msg.get_question()[0]
  209. # Identify the request type
  210. self._request_type = question.get_type()
  211. if self._request_type == RRType.AXFR():
  212. self._request_typestr = 'AXFR'
  213. elif self._request_type == RRType.IXFR():
  214. self._request_typestr = 'IXFR'
  215. else:
  216. # Likewise, this should be impossible.
  217. raise RuntimeError('Unexpected XFR type: ' +
  218. str(self._request_type))
  219. # ACL checks
  220. zone_name = question.get_name()
  221. zone_class = question.get_class()
  222. acl = self._get_transfer_acl(zone_name, zone_class)
  223. acl_result = acl.execute(
  224. isc.acl.dns.RequestContext(self._remote[2], msg.get_tsig_record()))
  225. if acl_result == DROP:
  226. logger.debug(DBG_XFROUT_TRACE, XFROUT_QUERY_DROPPED,
  227. self._request_type, format_addrinfo(self._remote),
  228. format_zone_str(zone_name, zone_class))
  229. return None, None
  230. elif acl_result == REJECT:
  231. logger.debug(DBG_XFROUT_TRACE, XFROUT_QUERY_REJECTED,
  232. self._request_type, format_addrinfo(self._remote),
  233. format_zone_str(zone_name, zone_class))
  234. return Rcode.REFUSED(), msg
  235. return rcode, msg
  236. def _get_transfer_acl(self, zone_name, zone_class):
  237. '''Return the ACL that should be applied for a given zone.
  238. The zone is identified by a tuple of name and RR class.
  239. If a per zone configuration for the zone exists and contains
  240. transfer_acl, that ACL will be used; otherwise, the default
  241. ACL will be used.
  242. '''
  243. # Internally zone names are managed in lower cased label characters,
  244. # so we first need to convert the name.
  245. zone_name_lower = Name(zone_name.to_text(), True)
  246. config_key = (zone_class.to_text(), zone_name_lower.to_text())
  247. if config_key in self._zone_config and \
  248. 'transfer_acl' in self._zone_config[config_key]:
  249. return self._zone_config[config_key]['transfer_acl']
  250. return self._acl
  251. def _send_data(self, sock_fd, data):
  252. size = len(data)
  253. total_count = 0
  254. while total_count < size:
  255. count = os.write(sock_fd, data[total_count:])
  256. total_count += count
  257. def _send_message(self, sock_fd, msg, tsig_ctx=None):
  258. render = MessageRenderer()
  259. # As defined in RFC5936 section3.4, perform case-preserving name
  260. # compression for AXFR message.
  261. render.set_compress_mode(MessageRenderer.CASE_SENSITIVE)
  262. render.set_length_limit(XFROUT_MAX_MESSAGE_SIZE)
  263. # XXX Currently, python wrapper doesn't accept 'None' parameter in this case,
  264. # we should remove the if statement and use a universal interface later.
  265. if tsig_ctx is not None:
  266. msg.to_wire(render, tsig_ctx)
  267. else:
  268. msg.to_wire(render)
  269. header_len = struct.pack('H', socket.htons(render.get_length()))
  270. self._send_data(sock_fd, header_len)
  271. self._send_data(sock_fd, render.get_data())
  272. def _reply_query_with_error_rcode(self, msg, sock_fd, rcode_):
  273. if not msg:
  274. return # query message is invalid. send nothing back.
  275. msg.make_response()
  276. msg.set_rcode(rcode_)
  277. self._send_message(sock_fd, msg, self._tsig_ctx)
  278. def _get_zone_soa(self, zone_name):
  279. '''Retrieve the SOA RR of the given zone.
  280. It returns a pair of RCODE and the SOA (in the form of RRset).
  281. On success RCODE is NOERROR and returned SOA is not None;
  282. on failure RCODE indicates the appropriate code in the context of
  283. xfr processing, and the returned SOA is None.
  284. '''
  285. result, finder = self._datasrc_client.find_zone(zone_name)
  286. if result != DataSourceClient.SUCCESS:
  287. return (Rcode.NOTAUTH(), None)
  288. result, soa_rrset, _ = finder.find(zone_name, RRType.SOA())
  289. if result != ZoneFinder.SUCCESS:
  290. return (Rcode.SERVFAIL(), None)
  291. # Especially for database-based zones, a working zone may be in
  292. # a broken state where it has more than one SOA RR. We proactively
  293. # check the condition and abort the xfr attempt if we identify it.
  294. if soa_rrset.get_rdata_count() != 1:
  295. return (Rcode.SERVFAIL(), None)
  296. return (Rcode.NOERROR(), soa_rrset)
  297. def __axfr_setup(self, zone_name):
  298. '''Setup a zone iterator for AXFR or AXFR-style IXFR.
  299. '''
  300. try:
  301. # Note that we enable 'separate_rrs'. In xfr-out we need to
  302. # preserve as many things as possible (even if it's half broken)
  303. # stored in the zone.
  304. self._iterator = self._datasrc_client.get_iterator(zone_name,
  305. True)
  306. except isc.datasrc.Error:
  307. # If the current name server does not have authority for the
  308. # zone, xfrout can't serve for it, return rcode NOTAUTH.
  309. # Note: this exception can happen for other reasons. We should
  310. # update get_iterator() API so that we can distinguish "no such
  311. # zone" and other cases (#1373). For now we consider all these
  312. # cases as NOTAUTH.
  313. return Rcode.NOTAUTH()
  314. # If we are an authoritative name server for the zone, but fail
  315. # to find the zone's SOA record in datasource, xfrout can't
  316. # provide zone transfer for it.
  317. self._soa = self._iterator.get_soa()
  318. if self._soa is None or self._soa.get_rdata_count() != 1:
  319. return Rcode.SERVFAIL()
  320. return Rcode.NOERROR()
  321. def __ixfr_setup(self, request_msg, zone_name, zone_class):
  322. '''Setup a zone journal reader for IXFR.
  323. If the underlying data source does not know the requested range
  324. of zone differences it automatically falls back to AXFR-style
  325. IXFR by setting up a zone iterator instead of a journal reader.
  326. '''
  327. # Check the authority section. Look for a SOA record with
  328. # the same name and class as the question.
  329. remote_soa = None
  330. for auth_rrset in request_msg.get_section(Message.SECTION_AUTHORITY):
  331. # Ignore data whose owner name is not the zone apex, and
  332. # ignore non-SOA or different class of records.
  333. if auth_rrset.get_name() != zone_name or \
  334. auth_rrset.get_type() != RRType.SOA() or \
  335. auth_rrset.get_class() != zone_class:
  336. continue
  337. if auth_rrset.get_rdata_count() != 1:
  338. logger.info(XFROUT_IXFR_MULTIPLE_SOA,
  339. format_addrinfo(self._remote))
  340. return Rcode.FORMERR()
  341. remote_soa = auth_rrset
  342. if remote_soa is None:
  343. logger.info(XFROUT_IXFR_NO_SOA, format_addrinfo(self._remote))
  344. return Rcode.FORMERR()
  345. # Retrieve the local SOA
  346. rcode, self._soa = self._get_zone_soa(zone_name)
  347. if rcode != Rcode.NOERROR():
  348. return rcode
  349. # RFC1995 says "If an IXFR query with the same or newer version
  350. # number than that of the server is received, it is replied to with
  351. # a single SOA record of the server's current version, just as
  352. # in AXFR". The claim about AXFR is incorrect, but other than that,
  353. # we do as the RFC says.
  354. begin_serial = get_soa_serial(remote_soa.get_rdata()[0])
  355. end_serial = get_soa_serial(self._soa.get_rdata()[0])
  356. if begin_serial >= end_serial:
  357. # clear both iterator and jnl_reader to signal we won't do
  358. # iteration in response generation
  359. self._iterator = None
  360. self._jnl_reader = None
  361. logger.info(XFROUT_IXFR_UPTODATE, format_addrinfo(self._remote),
  362. format_zone_str(zone_name, zone_class),
  363. begin_serial, end_serial)
  364. return Rcode.NOERROR()
  365. # Set up the journal reader or fall back to AXFR-style IXFR
  366. try:
  367. code, self._jnl_reader = self._datasrc_client.get_journal_reader(
  368. zone_name, begin_serial.get_value(), end_serial.get_value())
  369. except isc.datasrc.NotImplemented as ex:
  370. # The underlying data source doesn't support journaling.
  371. # Fall back to AXFR-style IXFR.
  372. logger.info(XFROUT_IXFR_NO_JOURNAL_SUPPORT,
  373. format_addrinfo(self._remote),
  374. format_zone_str(zone_name, zone_class))
  375. return self.__axfr_setup(zone_name)
  376. if code == ZoneJournalReader.NO_SUCH_VERSION:
  377. logger.info(XFROUT_IXFR_NO_VERSION, format_addrinfo(self._remote),
  378. format_zone_str(zone_name, zone_class),
  379. begin_serial, end_serial)
  380. return self.__axfr_setup(zone_name)
  381. if code == ZoneJournalReader.NO_SUCH_ZONE:
  382. # this is quite unexpected as we know zone's SOA exists.
  383. # It might be a bug or the data source is somehow broken,
  384. # but it can still happen if someone has removed the zone
  385. # between these two operations. We treat it as NOTAUTH.
  386. logger.warn(XFROUT_IXFR_NO_ZONE, format_addrinfo(self._remote),
  387. format_zone_str(zone_name, zone_class))
  388. return Rcode.NOTAUTH()
  389. # Use the reader as the iterator to generate the response.
  390. self._iterator = self._jnl_reader
  391. return Rcode.NOERROR()
  392. def _xfrout_setup(self, request_msg, zone_name, zone_class):
  393. '''Setup a context for xfr responses according to the request type.
  394. This method identifies the most appropriate data source for the
  395. request and set up a zone iterator or journal reader depending on
  396. whether the request is AXFR or IXFR. If it identifies any protocol
  397. level error it returns an RCODE other than NOERROR.
  398. '''
  399. # Identify the data source for the requested zone and see if it has
  400. # SOA while initializing objects used for request processing later.
  401. # We should eventually generalize this so that we can choose the
  402. # appropriate data source from (possible) multiple candidates.
  403. # We should eventually take into account the RR class here.
  404. # For now, we hardcode a particular type (SQLite3-based), and only
  405. # consider that one.
  406. datasrc_config = '{ "database_file": "' + \
  407. self._server.get_db_file() + '"}'
  408. self._datasrc_client = self.ClientClass('sqlite3', datasrc_config)
  409. if self._request_type == RRType.AXFR():
  410. return self.__axfr_setup(zone_name)
  411. else:
  412. return self.__ixfr_setup(request_msg, zone_name, zone_class)
  413. def dns_xfrout_start(self, sock_fd, msg_query, quota_ok=True):
  414. rcode_, msg = self._parse_query_message(msg_query)
  415. #TODO. create query message and parse header
  416. if rcode_ is None: # Dropped by ACL
  417. return
  418. elif rcode_ == Rcode.NOTAUTH() or rcode_ == Rcode.REFUSED():
  419. return self._reply_query_with_error_rcode(msg, sock_fd, rcode_)
  420. elif rcode_ != Rcode.NOERROR():
  421. return self._reply_query_with_error_rcode(msg, sock_fd,
  422. Rcode.FORMERR())
  423. elif not quota_ok:
  424. logger.warn(XFROUT_QUERY_QUOTA_EXCCEEDED, self._request_typestr,
  425. format_addrinfo(self._remote),
  426. self._server._max_transfers_out)
  427. return self._reply_query_with_error_rcode(msg, sock_fd,
  428. Rcode.REFUSED())
  429. question = msg.get_question()[0]
  430. zone_name = question.get_name()
  431. zone_class = question.get_class()
  432. zone_str = format_zone_str(zone_name, zone_class) # for logging
  433. try:
  434. rcode_ = self._xfrout_setup(msg, zone_name, zone_class)
  435. except Exception as ex:
  436. logger.error(XFROUT_XFR_TRANSFER_CHECK_ERROR, self._request_typestr,
  437. format_addrinfo(self._remote), zone_str, ex)
  438. rcode_ = Rcode.SERVFAIL()
  439. if rcode_ != Rcode.NOERROR():
  440. logger.info(XFROUT_XFR_TRANSFER_FAILED, self._request_typestr,
  441. format_addrinfo(self._remote), zone_str, rcode_)
  442. return self._reply_query_with_error_rcode(msg, sock_fd, rcode_)
  443. try:
  444. logger.info(XFROUT_XFR_TRANSFER_STARTED, self._request_typestr,
  445. format_addrinfo(self._remote), zone_str)
  446. self._reply_xfrout_query(msg, sock_fd)
  447. except Exception as err:
  448. logger.error(XFROUT_XFR_TRANSFER_ERROR, self._request_typestr,
  449. format_addrinfo(self._remote), zone_str, err)
  450. logger.info(XFROUT_XFR_TRANSFER_DONE, self._request_typestr,
  451. format_addrinfo(self._remote), zone_str)
  452. def _clear_message(self, msg):
  453. qid = msg.get_qid()
  454. opcode = msg.get_opcode()
  455. rcode = msg.get_rcode()
  456. msg.clear(Message.RENDER)
  457. msg.set_qid(qid)
  458. msg.set_opcode(opcode)
  459. msg.set_rcode(rcode)
  460. msg.set_header_flag(Message.HEADERFLAG_AA)
  461. msg.set_header_flag(Message.HEADERFLAG_QR)
  462. return msg
  463. def _send_message_with_last_soa(self, msg, sock_fd, rrset_soa,
  464. message_upper_len):
  465. '''Add the SOA record to the end of message.
  466. If it would exceed the maximum allowable size of a message, a new
  467. message will be created to send out the last SOA.
  468. We assume a message with a single SOA can always fit the buffer
  469. with or without TSIG. In theory this could be wrong if TSIG is
  470. stupidly large, but in practice this assumption should be reasonable.
  471. '''
  472. if message_upper_len + get_rrset_len(rrset_soa) > \
  473. XFROUT_MAX_MESSAGE_SIZE:
  474. self._send_message(sock_fd, msg, self._tsig_ctx)
  475. msg = self._clear_message(msg)
  476. msg.add_rrset(Message.SECTION_ANSWER, rrset_soa)
  477. self._send_message(sock_fd, msg, self._tsig_ctx)
  478. def _reply_xfrout_query(self, msg, sock_fd):
  479. msg.make_response()
  480. msg.set_header_flag(Message.HEADERFLAG_AA)
  481. # Reserved space for the fixed header size, the size of the question
  482. # section, and TSIG size (when included). The size of the question
  483. # section is the sum of the qname length and the size of the
  484. # fixed-length fields (type and class, 2 bytes each).
  485. message_upper_len = XFROUT_DNS_HEADER_SIZE + \
  486. msg.get_question()[0].get_name().get_length() + 4 + \
  487. self._tsig_len
  488. # If the iterator is None, we are responding to IXFR with a single
  489. # SOA RR.
  490. if self._iterator is None:
  491. self._send_message_with_last_soa(msg, sock_fd, self._soa,
  492. message_upper_len)
  493. return
  494. # Add the beginning SOA
  495. msg.add_rrset(Message.SECTION_ANSWER, self._soa)
  496. message_upper_len += get_rrset_len(self._soa)
  497. # Add the rest of the zone/diff contets
  498. for rrset in self._iterator:
  499. # Check if xfrout is shutdown
  500. if self._server._shutdown_event.is_set():
  501. logger.info(XFROUT_STOPPING)
  502. return
  503. # For AXFR (or AXFR-style IXFR), in which case _jnl_reader is None,
  504. # we should skip SOAs from the iterator.
  505. if self._jnl_reader is None and rrset.get_type() == RRType.SOA():
  506. continue
  507. # We calculate the maximum size of the RRset (i.e. the
  508. # size without compression) and use that to see if we
  509. # may have reached the limit
  510. rrset_len = get_rrset_len(rrset)
  511. if message_upper_len + rrset_len <= XFROUT_MAX_MESSAGE_SIZE:
  512. msg.add_rrset(Message.SECTION_ANSWER, rrset)
  513. message_upper_len += rrset_len
  514. continue
  515. # RR would not fit. If there are other RRs in the buffer, send
  516. # them now and leave this RR to the next message.
  517. self._send_message(sock_fd, msg, self._tsig_ctx)
  518. # Create a new message and reserve space for the carried-over
  519. # RR (and TSIG space in case it's to be TSIG signed)
  520. msg = self._clear_message(msg)
  521. message_upper_len = XFROUT_DNS_HEADER_SIZE + rrset_len + \
  522. self._tsig_len
  523. # If this RR overflows the buffer all by itself, fail. In theory
  524. # some RRs might fit in a TCP message when compressed even if they
  525. # do not fit when uncompressed, but surely we don't want to send
  526. # such monstrosities to an unsuspecting slave.
  527. if message_upper_len > XFROUT_MAX_MESSAGE_SIZE:
  528. raise XfroutSessionError('RR too large for zone transfer (' +
  529. str(rrset_len) + ' bytes)')
  530. # Add the RRset to the new message
  531. msg.add_rrset(Message.SECTION_ANSWER, rrset)
  532. # Add and send the trailing SOA
  533. self._send_message_with_last_soa(msg, sock_fd, self._soa,
  534. message_upper_len)
  535. class UnixSockServer(socketserver_mixin.NoPollMixIn,
  536. ThreadingUnixStreamServer):
  537. '''The unix domain socket server which accept xfr query sent from auth server.'''
  538. def __init__(self, sock_file, handle_class, shutdown_event, config_data,
  539. cc):
  540. self._remove_unused_sock_file(sock_file)
  541. self._sock_file = sock_file
  542. socketserver_mixin.NoPollMixIn.__init__(self)
  543. ThreadingUnixStreamServer.__init__(self, sock_file, handle_class)
  544. self._shutdown_event = shutdown_event
  545. self._write_sock, self._read_sock = socket.socketpair()
  546. self._common_init()
  547. self._cc = cc
  548. self.update_config_data(config_data)
  549. def _common_init(self):
  550. '''Initialization shared with the mock server class used for tests'''
  551. self._lock = threading.Lock()
  552. self._transfers_counter = 0
  553. self._zone_config = {}
  554. self._acl = None # this will be initialized in update_config_data()
  555. def _receive_query_message(self, sock):
  556. ''' receive request message from sock'''
  557. # receive data length
  558. data_len = sock.recv(2)
  559. if not data_len:
  560. return None
  561. msg_len = struct.unpack('!H', data_len)[0]
  562. # receive data
  563. recv_size = 0
  564. msgdata = b''
  565. while recv_size < msg_len:
  566. data = sock.recv(msg_len - recv_size)
  567. if not data:
  568. return None
  569. recv_size += len(data)
  570. msgdata += data
  571. return msgdata
  572. def handle_request(self):
  573. ''' Enable server handle a request until shutdown or auth is closed.'''
  574. try:
  575. request, client_address = self.get_request()
  576. except socket.error:
  577. logger.error(XFROUT_FETCH_REQUEST_ERROR)
  578. return
  579. # Check self._shutdown_event to ensure the real shutdown comes.
  580. # Linux could trigger a spurious readable event on the _read_sock
  581. # due to a bug, so we need perform a double check.
  582. while not self._shutdown_event.is_set(): # Check if xfrout is shutdown
  583. try:
  584. (rlist, wlist, xlist) = select.select([self._read_sock, request], [], [])
  585. except select.error as e:
  586. if e.args[0] == errno.EINTR:
  587. (rlist, wlist, xlist) = ([], [], [])
  588. continue
  589. else:
  590. logger.error(XFROUT_SOCKET_SELECT_ERROR, str(e))
  591. break
  592. # self.server._shutdown_event will be set by now, if it is not a false
  593. # alarm
  594. if self._read_sock in rlist:
  595. continue
  596. try:
  597. self.process_request(request)
  598. except Exception as pre:
  599. logger.error(XFROUT_PROCESS_REQUEST_ERROR, str(pre))
  600. break
  601. def _handle_request_noblock(self):
  602. """Override the function _handle_request_noblock(), it creates a new
  603. thread to handle requests for each auth"""
  604. td = threading.Thread(target=self.handle_request)
  605. td.setDaemon(True)
  606. td.start()
  607. def process_request(self, request):
  608. """Receive socket fd and query message from auth, then
  609. start a new thread to process the request."""
  610. sock_fd = recv_fd(request.fileno())
  611. if sock_fd < 0:
  612. # This may happen when one xfrout process try to connect to
  613. # xfrout unix socket server, to check whether there is another
  614. # xfrout running.
  615. if sock_fd == FD_SYSTEM_ERROR:
  616. logger.error(XFROUT_RECEIVE_FILE_DESCRIPTOR_ERROR)
  617. return
  618. # receive request msg
  619. request_data = self._receive_query_message(request)
  620. if not request_data:
  621. return
  622. t = threading.Thread(target=self.finish_request,
  623. args = (sock_fd, request_data))
  624. if self.daemon_threads:
  625. t.daemon = True
  626. t.start()
  627. def _guess_remote(self, sock_fd):
  628. """Guess remote address and port of the socket.
  629. The sock_fd must be a file descriptor of a socket.
  630. This method retuns a 3-tuple consisting of address family,
  631. socket type, and a 2-tuple with the address (string) and port (int).
  632. """
  633. # This uses a trick. If the socket is IPv4 in reality and we pretend
  634. # it to be IPv6, it returns IPv4 address anyway. This doesn't seem
  635. # to care about the SOCK_STREAM parameter at all (which it really is,
  636. # except for testing)
  637. if socket.has_ipv6:
  638. sock = socket.fromfd(sock_fd, socket.AF_INET6, socket.SOCK_STREAM)
  639. else:
  640. # To make it work even on hosts without IPv6 support
  641. # (Any idea how to simulate this in test?)
  642. sock = socket.fromfd(sock_fd, socket.AF_INET, socket.SOCK_STREAM)
  643. peer = sock.getpeername()
  644. # Identify the correct socket family. Due to the above "trick",
  645. # we cannot simply use sock.family.
  646. family = socket.AF_INET6
  647. try:
  648. socket.inet_pton(socket.AF_INET6, peer[0])
  649. except socket.error:
  650. family = socket.AF_INET
  651. return (family, socket.SOCK_STREAM, peer)
  652. def finish_request(self, sock_fd, request_data):
  653. '''Finish one request by instantiating RequestHandlerClass.
  654. This is an entry point of a separate thread spawned in
  655. UnixSockServer.process_request().
  656. This method creates a XfroutSession object.
  657. '''
  658. self._lock.acquire()
  659. acl = self._acl
  660. zone_config = self._zone_config
  661. self._lock.release()
  662. self.RequestHandlerClass(sock_fd, request_data, self,
  663. self.tsig_key_ring,
  664. self._guess_remote(sock_fd), acl, zone_config)
  665. def _remove_unused_sock_file(self, sock_file):
  666. '''Try to remove the socket file. If the file is being used
  667. by one running xfrout process, exit from python.
  668. If it's not a socket file or nobody is listening
  669. , it will be removed. If it can't be removed, exit from python. '''
  670. if self._sock_file_in_use(sock_file):
  671. logger.error(XFROUT_UNIX_SOCKET_FILE_IN_USE, sock_file)
  672. sys.exit(0)
  673. else:
  674. if not os.path.exists(sock_file):
  675. return
  676. try:
  677. os.unlink(sock_file)
  678. except OSError as err:
  679. logger.error(XFROUT_REMOVE_OLD_UNIX_SOCKET_FILE_ERROR, sock_file, str(err))
  680. sys.exit(0)
  681. def _sock_file_in_use(self, sock_file):
  682. '''Check whether the socket file 'sock_file' exists and
  683. is being used by one running xfrout process. If it is,
  684. return True, or else return False. '''
  685. try:
  686. sock = socket.socket(socket.AF_UNIX)
  687. sock.connect(sock_file)
  688. except socket.error as err:
  689. return False
  690. else:
  691. return True
  692. def shutdown(self):
  693. self._write_sock.send(b"shutdown") #terminate the xfrout session thread
  694. super().shutdown() # call the shutdown() of class socketserver_mixin.NoPollMixIn
  695. try:
  696. os.unlink(self._sock_file)
  697. except Exception as e:
  698. logger.error(XFROUT_REMOVE_UNIX_SOCKET_FILE_ERROR, self._sock_file, str(e))
  699. def update_config_data(self, new_config):
  700. '''Apply the new config setting of xfrout module.
  701. '''
  702. self._lock.acquire()
  703. try:
  704. logger.info(XFROUT_NEW_CONFIG)
  705. new_acl = self._acl
  706. if 'transfer_acl' in new_config:
  707. try:
  708. new_acl = REQUEST_LOADER.load(new_config['transfer_acl'])
  709. except LoaderError as e:
  710. raise XfroutConfigError('Failed to parse transfer_acl: ' +
  711. str(e))
  712. new_zone_config = self._zone_config
  713. zconfig_data = new_config.get('zone_config')
  714. if zconfig_data is not None:
  715. new_zone_config = self.__create_zone_config(zconfig_data)
  716. self._acl = new_acl
  717. self._zone_config = new_zone_config
  718. self._max_transfers_out = new_config.get('transfers_out')
  719. self.set_tsig_key_ring(new_config.get('tsig_key_ring'))
  720. except Exception as e:
  721. self._lock.release()
  722. raise e
  723. self._lock.release()
  724. logger.info(XFROUT_NEW_CONFIG_DONE)
  725. def __create_zone_config(self, zone_config_list):
  726. new_config = {}
  727. for zconf in zone_config_list:
  728. # convert the class, origin (name) pair. First build pydnspp
  729. # object to reject invalid input.
  730. zclass_str = zconf.get('class')
  731. if zclass_str is None:
  732. #zclass_str = 'IN' # temporary
  733. zclass_str = self._cc.get_default_value('zone_config/class')
  734. zclass = RRClass(zclass_str)
  735. zorigin = Name(zconf['origin'], True)
  736. config_key = (zclass.to_text(), zorigin.to_text())
  737. # reject duplicate config
  738. if config_key in new_config:
  739. raise XfroutConfigError('Duplicate zone_config for ' +
  740. str(zorigin) + '/' + str(zclass))
  741. # create a new config entry, build any given (and known) config
  742. new_config[config_key] = {}
  743. if 'transfer_acl' in zconf:
  744. try:
  745. new_config[config_key]['transfer_acl'] = \
  746. REQUEST_LOADER.load(zconf['transfer_acl'])
  747. except LoaderError as e:
  748. raise XfroutConfigError('Failed to parse transfer_acl ' +
  749. 'for ' + zorigin.to_text() + '/' +
  750. zclass_str + ': ' + str(e))
  751. return new_config
  752. def set_tsig_key_ring(self, key_list):
  753. """Set the tsig_key_ring , given a TSIG key string list representation. """
  754. # XXX add values to configure zones/tsig options
  755. self.tsig_key_ring = TSIGKeyRing()
  756. # If key string list is empty, create a empty tsig_key_ring
  757. if not key_list:
  758. return
  759. for key_item in key_list:
  760. try:
  761. self.tsig_key_ring.add(TSIGKey(key_item))
  762. except InvalidParameter as ipe:
  763. logger.error(XFROUT_BAD_TSIG_KEY_STRING, str(key_item))
  764. def get_db_file(self):
  765. file, is_default = self._cc.get_remote_config_value("Auth", "database_file")
  766. # this too should be unnecessary, but currently the
  767. # 'from build' override isn't stored in the config
  768. # (and we don't have indirect python access to datasources yet)
  769. if is_default and "B10_FROM_BUILD" in os.environ:
  770. file = os.environ["B10_FROM_BUILD"] + os.sep + "bind10_zones.sqlite3"
  771. return file
  772. def increase_transfers_counter(self):
  773. '''Return False, if counter + 1 > max_transfers_out, or else
  774. return True
  775. '''
  776. ret = False
  777. self._lock.acquire()
  778. if self._transfers_counter < self._max_transfers_out:
  779. self._transfers_counter += 1
  780. ret = True
  781. self._lock.release()
  782. return ret
  783. def decrease_transfers_counter(self):
  784. self._lock.acquire()
  785. self._transfers_counter -= 1
  786. self._lock.release()
  787. class XfroutServer:
  788. def __init__(self):
  789. self._unix_socket_server = None
  790. self._listen_sock_file = UNIX_SOCKET_FILE
  791. self._shutdown_event = threading.Event()
  792. self._cc = isc.config.ModuleCCSession(SPECFILE_LOCATION, self.config_handler, self.command_handler)
  793. self._config_data = self._cc.get_full_config()
  794. self._cc.start()
  795. self._cc.add_remote_config(AUTH_SPECFILE_LOCATION);
  796. self._start_xfr_query_listener()
  797. self._start_notifier()
  798. def _start_xfr_query_listener(self):
  799. '''Start a new thread to accept xfr query. '''
  800. self._unix_socket_server = UnixSockServer(self._listen_sock_file,
  801. XfroutSession,
  802. self._shutdown_event,
  803. self._config_data,
  804. self._cc)
  805. listener = threading.Thread(target=self._unix_socket_server.serve_forever)
  806. listener.start()
  807. def _start_notifier(self):
  808. datasrc = self._unix_socket_server.get_db_file()
  809. self._notifier = notify_out.NotifyOut(datasrc)
  810. self._notifier.dispatcher()
  811. def send_notify(self, zone_name, zone_class):
  812. self._notifier.send_notify(zone_name, zone_class)
  813. def config_handler(self, new_config):
  814. '''Update config data. TODO. Do error check'''
  815. answer = create_answer(0)
  816. for key in new_config:
  817. if key not in self._config_data:
  818. answer = create_answer(1, "Unknown config data: " + str(key))
  819. continue
  820. self._config_data[key] = new_config[key]
  821. if self._unix_socket_server:
  822. try:
  823. self._unix_socket_server.update_config_data(self._config_data)
  824. except Exception as e:
  825. answer = create_answer(1,
  826. "Failed to handle new configuration: " +
  827. str(e))
  828. return answer
  829. def shutdown(self):
  830. ''' shutdown the xfrout process. The thread which is doing zone transfer-out should be
  831. terminated.
  832. '''
  833. global xfrout_server
  834. xfrout_server = None #Avoid shutdown is called twice
  835. self._shutdown_event.set()
  836. self._notifier.shutdown()
  837. if self._unix_socket_server:
  838. self._unix_socket_server.shutdown()
  839. # Wait for all threads to terminate
  840. main_thread = threading.currentThread()
  841. for th in threading.enumerate():
  842. if th is main_thread:
  843. continue
  844. th.join()
  845. def command_handler(self, cmd, args):
  846. if cmd == "shutdown":
  847. logger.info(XFROUT_RECEIVED_SHUTDOWN_COMMAND)
  848. self.shutdown()
  849. answer = create_answer(0)
  850. elif cmd == notify_out.ZONE_NEW_DATA_READY_CMD:
  851. zone_name = args.get('zone_name')
  852. zone_class = args.get('zone_class')
  853. if zone_name and zone_class:
  854. logger.info(XFROUT_NOTIFY_COMMAND, zone_name, zone_class)
  855. self.send_notify(zone_name, zone_class)
  856. answer = create_answer(0)
  857. else:
  858. answer = create_answer(1, "Bad command parameter:" + str(args))
  859. else:
  860. answer = create_answer(1, "Unknown command:" + str(cmd))
  861. return answer
  862. def run(self):
  863. '''Get and process all commands sent from cfgmgr or other modules. '''
  864. while not self._shutdown_event.is_set():
  865. self._cc.check_command(False)
  866. xfrout_server = None
  867. def signal_handler(signal, frame):
  868. if xfrout_server:
  869. xfrout_server.shutdown()
  870. sys.exit(0)
  871. def set_signal_handler():
  872. signal.signal(signal.SIGTERM, signal_handler)
  873. signal.signal(signal.SIGINT, signal_handler)
  874. def set_cmd_options(parser):
  875. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  876. help="display more about what is going on")
  877. if '__main__' == __name__:
  878. try:
  879. parser = OptionParser()
  880. set_cmd_options(parser)
  881. (options, args) = parser.parse_args()
  882. VERBOSE_MODE = options.verbose
  883. set_signal_handler()
  884. xfrout_server = XfroutServer()
  885. xfrout_server.run()
  886. except KeyboardInterrupt:
  887. logger.INFO(XFROUT_STOPPED_BY_KEYBOARD)
  888. except SessionError as e:
  889. logger.error(XFROUT_CC_SESSION_ERROR, str(e))
  890. except ModuleCCSessionError as e:
  891. logger.error(XFROUT_MODULECC_SESSION_ERROR, str(e))
  892. except XfroutConfigError as e:
  893. logger.error(XFROUT_CONFIG_ERROR, str(e))
  894. except SessionTimeout as e:
  895. logger.error(XFROUT_CC_SESSION_TIMEOUT_ERROR)
  896. if xfrout_server:
  897. xfrout_server.shutdown()