xfrout.py.in 44 KB

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