xfrout.py.in 42 KB

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