xfrin_test.py 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154
  1. # Copyright (C) 2009-2011 Internet Systems Consortium.
  2. #
  3. # Permission to use, copy, modify, and distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  8. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  9. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  10. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  12. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  14. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. import unittest
  16. import shutil
  17. import socket
  18. import io
  19. from isc.testutils.tsigctx_mock import MockTSIGContext
  20. from xfrin import *
  21. from isc.xfrin.diff import Diff
  22. import isc.log
  23. #
  24. # Commonly used (mostly constant) test parameters
  25. #
  26. TEST_ZONE_NAME_STR = "example.com."
  27. TEST_ZONE_NAME = Name(TEST_ZONE_NAME_STR)
  28. TEST_RRCLASS = RRClass.IN()
  29. TEST_RRCLASS_STR = 'IN'
  30. TEST_DB_FILE = 'db_file'
  31. TEST_MASTER_IPV4_ADDRESS = '127.0.0.1'
  32. TEST_MASTER_IPV4_ADDRINFO = (socket.AF_INET, socket.SOCK_STREAM,
  33. socket.IPPROTO_TCP, '',
  34. (TEST_MASTER_IPV4_ADDRESS, 53))
  35. TEST_MASTER_IPV6_ADDRESS = '::1'
  36. TEST_MASTER_IPV6_ADDRINFO = (socket.AF_INET6, socket.SOCK_STREAM,
  37. socket.IPPROTO_TCP, '',
  38. (TEST_MASTER_IPV6_ADDRESS, 53))
  39. TESTDATA_SRCDIR = os.getenv("TESTDATASRCDIR")
  40. TESTDATA_OBJDIR = os.getenv("TESTDATAOBJDIR")
  41. # XXX: This should be a non priviledge port that is unlikely to be used.
  42. # If some other process uses this port test will fail.
  43. TEST_MASTER_PORT = '53535'
  44. TSIG_KEY = TSIGKey("example.com:SFuWd/q99SzF8Yzd1QbB9g==")
  45. # SOA intended to be used for the new SOA as a result of transfer.
  46. soa_rdata = Rdata(RRType.SOA(), TEST_RRCLASS,
  47. 'master.example.com. admin.example.com ' +
  48. '1234 3600 1800 2419200 7200')
  49. soa_rrset = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.SOA(), RRTTL(3600))
  50. soa_rrset.add_rdata(soa_rdata)
  51. # SOA intended to be used for the current SOA at the secondary side.
  52. # Note that its serial is smaller than that of soa_rdata.
  53. begin_soa_rdata = Rdata(RRType.SOA(), TEST_RRCLASS,
  54. 'master.example.com. admin.example.com ' +
  55. '1230 3600 1800 2419200 7200')
  56. begin_soa_rrset = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.SOA(), RRTTL(3600))
  57. begin_soa_rrset.add_rdata(begin_soa_rdata)
  58. example_axfr_question = Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.AXFR())
  59. example_soa_question = Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.SOA())
  60. default_questions = [example_axfr_question]
  61. default_answers = [soa_rrset]
  62. def check_diffs(assert_fn, expected, actual):
  63. '''A helper function checking the differences made in the XFR session.
  64. This is expected called from some subclass of unittest.TestCase and
  65. assert_fn is generally expected to be 'self.assertEqual' of that class.
  66. '''
  67. assert_fn(len(expected), len(actual))
  68. for (diffs_exp, diffs_actual) in zip(expected, actual):
  69. assert_fn(len(diffs_exp), len(diffs_actual))
  70. for (diff_exp, diff_actual) in zip(diffs_exp, diffs_actual):
  71. # operation should match
  72. assert_fn(diff_exp[0], diff_actual[0])
  73. # The diff as RRset should be equal (for simplicity we assume
  74. # all RRsets contain exactly one RDATA)
  75. assert_fn(diff_exp[1].get_name(), diff_actual[1].get_name())
  76. assert_fn(diff_exp[1].get_type(), diff_actual[1].get_type())
  77. assert_fn(diff_exp[1].get_class(), diff_actual[1].get_class())
  78. assert_fn(diff_exp[1].get_rdata_count(),
  79. diff_actual[1].get_rdata_count())
  80. assert_fn(1, diff_exp[1].get_rdata_count())
  81. assert_fn(diff_exp[1].get_rdata()[0],
  82. diff_actual[1].get_rdata()[0])
  83. class XfrinTestException(Exception):
  84. pass
  85. class XfrinTestTimeoutException(Exception):
  86. pass
  87. class MockCC():
  88. def get_default_value(self, identifier):
  89. if identifier == "zones/master_port":
  90. return TEST_MASTER_PORT
  91. if identifier == "zones/class":
  92. return TEST_RRCLASS_STR
  93. class MockDataSourceClient():
  94. '''A simple mock data source client.
  95. This class provides a minimal set of wrappers related the data source
  96. API that would be used by Diff objects. For our testing purposes they
  97. only keep truck of the history of the changes.
  98. '''
  99. def __init__(self):
  100. self.force_fail = False # if True, raise an exception on commit
  101. self.committed_diffs = []
  102. self.diffs = []
  103. def get_class(self):
  104. '''Mock version of get_class().
  105. We simply return the commonly used constant RR class. If and when
  106. we use this mock for a different RR class we need to adjust it
  107. accordingly.
  108. '''
  109. return TEST_RRCLASS
  110. def find_zone(self, zone_name):
  111. '''Mock version of find_zone().
  112. It returns itself (subsequently acting as a mock ZoneFinder) for
  113. some test zone names. For some others it returns either NOTFOUND
  114. or PARTIALMATCH.
  115. '''
  116. if zone_name == TEST_ZONE_NAME or \
  117. zone_name == Name('no-soa.example') or \
  118. zone_name == Name('dup-soa.example'):
  119. return (isc.datasrc.DataSourceClient.SUCCESS, self)
  120. elif zone_name == Name('no-such-zone.example'):
  121. return (DataSourceClient.NOTFOUND, None)
  122. elif zone_name == Name('partial-match-zone.example'):
  123. return (DataSourceClient.PARTIALMATCH, self)
  124. raise ValueError('Unexpected input to mock client: bug in test case?')
  125. def find(self, name, rrtype, target, options):
  126. '''Mock ZoneFinder.find().
  127. It returns the predefined SOA RRset to queries for SOA of the common
  128. test zone name. It also emulates some unusual cases for special
  129. zone names.
  130. '''
  131. if name == TEST_ZONE_NAME and rrtype == RRType.SOA():
  132. return (ZoneFinder.SUCCESS, begin_soa_rrset)
  133. if name == Name('no-soa.example'):
  134. return (ZoneFinder.NXDOMAIN, None)
  135. if name == Name('dup-soa.example'):
  136. dup_soa_rrset = RRset(name, TEST_RRCLASS, RRType.SOA(), RRTTL(0))
  137. dup_soa_rrset.add_rdata(begin_soa_rdata)
  138. dup_soa_rrset.add_rdata(soa_rdata)
  139. return (ZoneFinder.SUCCESS, dup_soa_rrset)
  140. raise ValueError('Unexpected input to mock finder: bug in test case?')
  141. def get_updater(self, zone_name, replace):
  142. return self
  143. def add_rrset(self, rrset):
  144. self.diffs.append(('add', rrset))
  145. def delete_rrset(self, rrset):
  146. self.diffs.append(('delete', rrset))
  147. def commit(self):
  148. if self.force_fail:
  149. raise isc.datasrc.Error('Updater.commit() failed')
  150. self.committed_diffs.append(self.diffs)
  151. self.diffs = []
  152. class MockXfrin(Xfrin):
  153. # This is a class attribute of a callable object that specifies a non
  154. # default behavior triggered in _cc_check_command(). Specific test methods
  155. # are expected to explicitly set this attribute before creating a
  156. # MockXfrin object (when it needs a non default behavior).
  157. # See the TestMain class.
  158. check_command_hook = None
  159. def _cc_setup(self):
  160. self._tsig_key = None
  161. self._module_cc = MockCC()
  162. pass
  163. def _get_db_file(self):
  164. pass
  165. def _cc_check_command(self):
  166. self._shutdown_event.set()
  167. if MockXfrin.check_command_hook:
  168. MockXfrin.check_command_hook()
  169. def xfrin_start(self, zone_name, rrclass, db_file, master_addrinfo,
  170. tsig_key, request_type, check_soa=True):
  171. # store some of the arguments for verification, then call this
  172. # method in the superclass
  173. self.xfrin_started_master_addr = master_addrinfo[2][0]
  174. self.xfrin_started_master_port = master_addrinfo[2][1]
  175. self.xfrin_started_request_type = request_type
  176. return Xfrin.xfrin_start(self, zone_name, rrclass, None,
  177. master_addrinfo, tsig_key,
  178. request_type, check_soa)
  179. class MockXfrinConnection(XfrinConnection):
  180. def __init__(self, sock_map, zone_name, rrclass, shutdown_event,
  181. master_addr):
  182. super().__init__(sock_map, zone_name, rrclass, MockDataSourceClient(),
  183. shutdown_event, master_addr)
  184. self.query_data = b''
  185. self.reply_data = b''
  186. self.force_time_out = False
  187. self.force_close = False
  188. self.qlen = None
  189. self.qid = None
  190. self.response_generator = None
  191. def _asyncore_loop(self):
  192. if self.force_close:
  193. self.handle_close()
  194. elif not self.force_time_out:
  195. self.handle_read()
  196. def connect_to_master(self):
  197. return True
  198. def recv(self, size):
  199. data = self.reply_data[:size]
  200. self.reply_data = self.reply_data[size:]
  201. if len(data) == 0:
  202. raise XfrinTestTimeoutException('Emulated timeout')
  203. if len(data) < size:
  204. raise XfrinTestException('cannot get reply data (' + str(size) +
  205. ' bytes)')
  206. return data
  207. def send(self, data):
  208. if self.qlen != None and len(self.query_data) >= self.qlen:
  209. # This is a new query. reset the internal state.
  210. self.qlen = None
  211. self.qid = None
  212. self.query_data = b''
  213. self.query_data += data
  214. # when the outgoing data is sufficiently large to contain the length
  215. # and the QID fields (4 octets or more), extract these fields.
  216. # The length will be reset the internal query data to support multiple
  217. # queries in a single test.
  218. # The QID will be used to construct a matching response.
  219. if len(self.query_data) >= 4 and self.qid == None:
  220. self.qlen = socket.htons(struct.unpack('H',
  221. self.query_data[0:2])[0])
  222. self.qid = socket.htons(struct.unpack('H', self.query_data[2:4])[0])
  223. # if the response generator method is specified, invoke it now.
  224. if self.response_generator != None:
  225. self.response_generator()
  226. return len(data)
  227. def create_response_data(self, response=True, bad_qid=False,
  228. rcode=Rcode.NOERROR(),
  229. questions=default_questions,
  230. answers=default_answers,
  231. tsig_ctx=None):
  232. resp = Message(Message.RENDER)
  233. qid = self.qid
  234. if bad_qid:
  235. qid += 1
  236. resp.set_qid(qid)
  237. resp.set_opcode(Opcode.QUERY())
  238. resp.set_rcode(rcode)
  239. if response:
  240. resp.set_header_flag(Message.HEADERFLAG_QR)
  241. [resp.add_question(q) for q in questions]
  242. [resp.add_rrset(Message.SECTION_ANSWER, a) for a in answers]
  243. renderer = MessageRenderer()
  244. if tsig_ctx is not None:
  245. resp.to_wire(renderer, tsig_ctx)
  246. else:
  247. resp.to_wire(renderer)
  248. reply_data = struct.pack('H', socket.htons(renderer.get_length()))
  249. reply_data += renderer.get_data()
  250. return reply_data
  251. class TestXfrinState(unittest.TestCase):
  252. def setUp(self):
  253. self.sock_map = {}
  254. self.conn = MockXfrinConnection(self.sock_map, TEST_ZONE_NAME,
  255. TEST_RRCLASS, threading.Event(),
  256. TEST_MASTER_IPV4_ADDRINFO)
  257. self.begin_soa = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.SOA(),
  258. RRTTL(3600))
  259. self.begin_soa.add_rdata(Rdata(RRType.SOA(), TEST_RRCLASS,
  260. 'm. r. 1230 0 0 0 0'))
  261. self.ns_rrset = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.NS(),
  262. RRTTL(3600))
  263. self.ns_rrset.add_rdata(Rdata(RRType.NS(), TEST_RRCLASS,
  264. 'ns.example.com'))
  265. self.a_rrset = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.A(),
  266. RRTTL(3600))
  267. self.a_rrset.add_rdata(Rdata(RRType.A(), TEST_RRCLASS, '192.0.2.1'))
  268. self.conn._datasrc_client = MockDataSourceClient()
  269. self.conn._diff = Diff(self.conn._datasrc_client, TEST_ZONE_NAME)
  270. class TestXfrinStateBase(TestXfrinState):
  271. def setUp(self):
  272. super().setUp()
  273. def test_handle_rr_on_base(self):
  274. # The base version of handle_rr() isn't supposed to be called
  275. # directly (the argument doesn't matter in this test)
  276. self.assertRaises(XfrinException, XfrinState().handle_rr, None)
  277. class TestXfrinInitialSOA(TestXfrinState):
  278. def setUp(self):
  279. super().setUp()
  280. self.state = XfrinInitialSOA()
  281. def test_handle_rr(self):
  282. # normal case
  283. self.assertTrue(self.state.handle_rr(self.conn, soa_rrset))
  284. self.assertEqual(type(XfrinFirstData()),
  285. type(self.conn.get_xfrstate()))
  286. self.assertEqual(1234, self.conn._end_serial)
  287. def test_handle_not_soa(self):
  288. # The given RR is not of SOA
  289. self.assertRaises(XfrinProtocolError, self.state.handle_rr, self.conn,
  290. self.ns_rrset)
  291. def test_finish_message(self):
  292. self.assertTrue(self.state.finish_message(self.conn))
  293. class TestXfrinFirstData(TestXfrinState):
  294. def setUp(self):
  295. super().setUp()
  296. self.state = XfrinFirstData()
  297. self.conn._request_type = RRType.IXFR()
  298. self.conn._request_serial = 1230 # arbitrary chosen serial < 1234
  299. self.conn._diff = None # should be replaced in the AXFR case
  300. def test_handle_ixfr_begin_soa(self):
  301. self.conn._request_type = RRType.IXFR()
  302. self.assertFalse(self.state.handle_rr(self.conn, self.begin_soa))
  303. self.assertEqual(type(XfrinIXFRDeleteSOA()),
  304. type(self.conn.get_xfrstate()))
  305. def test_handle_axfr(self):
  306. # If the original type is AXFR, other conditions aren't considered,
  307. # and AXFR processing will continue
  308. self.conn._request_type = RRType.AXFR()
  309. self.assertFalse(self.state.handle_rr(self.conn, self.begin_soa))
  310. self.assertEqual(type(XfrinAXFR()), type(self.conn.get_xfrstate()))
  311. def test_handle_ixfr_to_axfr(self):
  312. # Detecting AXFR-compatible IXFR response by seeing a non SOA RR after
  313. # the initial SOA. Should switch to AXFR.
  314. self.assertFalse(self.state.handle_rr(self.conn, self.ns_rrset))
  315. self.assertEqual(type(XfrinAXFR()), type(self.conn.get_xfrstate()))
  316. # The Diff for AXFR should be created at this point
  317. self.assertNotEqual(None, self.conn._diff)
  318. def test_handle_ixfr_to_axfr_by_different_soa(self):
  319. # An unusual case: Response contains two consecutive SOA but the
  320. # serial of the second does not match the requested one. See
  321. # the documentation for XfrinFirstData.handle_rr().
  322. self.assertFalse(self.state.handle_rr(self.conn, soa_rrset))
  323. self.assertEqual(type(XfrinAXFR()), type(self.conn.get_xfrstate()))
  324. self.assertNotEqual(None, self.conn._diff)
  325. def test_finish_message(self):
  326. self.assertTrue(self.state.finish_message(self.conn))
  327. class TestXfrinIXFRDeleteSOA(TestXfrinState):
  328. def setUp(self):
  329. super().setUp()
  330. self.state = XfrinIXFRDeleteSOA()
  331. # In this state a new Diff object is expected to be created. To
  332. # confirm it, we nullify it beforehand.
  333. self.conn._diff = None
  334. def test_handle_rr(self):
  335. self.assertTrue(self.state.handle_rr(self.conn, self.begin_soa))
  336. self.assertEqual(type(XfrinIXFRDelete()),
  337. type(self.conn.get_xfrstate()))
  338. self.assertEqual([('delete', self.begin_soa)],
  339. self.conn._diff.get_buffer())
  340. def test_handle_non_soa(self):
  341. self.assertRaises(XfrinException, self.state.handle_rr, self.conn,
  342. self.ns_rrset)
  343. def test_finish_message(self):
  344. self.assertTrue(self.state.finish_message(self.conn))
  345. class TestXfrinIXFRDelete(TestXfrinState):
  346. def setUp(self):
  347. super().setUp()
  348. # We need record the state in 'conn' to check the case where the
  349. # state doesn't change.
  350. XfrinIXFRDelete().set_xfrstate(self.conn, XfrinIXFRDelete())
  351. self.state = self.conn.get_xfrstate()
  352. def test_handle_delete_rr(self):
  353. # Non SOA RRs are simply (goting to be) deleted in this state
  354. self.assertTrue(self.state.handle_rr(self.conn, self.ns_rrset))
  355. self.assertEqual([('delete', self.ns_rrset)],
  356. self.conn._diff.get_buffer())
  357. # The state shouldn't change
  358. self.assertEqual(type(XfrinIXFRDelete()),
  359. type(self.conn.get_xfrstate()))
  360. def test_handle_soa(self):
  361. # SOA in this state means the beginning of added RRs. This SOA
  362. # should also be added in the next state, so handle_rr() should return
  363. # false.
  364. self.assertFalse(self.state.handle_rr(self.conn, soa_rrset))
  365. self.assertEqual([], self.conn._diff.get_buffer())
  366. self.assertEqual(1234, self.conn._current_serial)
  367. self.assertEqual(type(XfrinIXFRAddSOA()),
  368. type(self.conn.get_xfrstate()))
  369. def test_finish_message(self):
  370. self.assertTrue(self.state.finish_message(self.conn))
  371. class TestXfrinIXFRAddSOA(TestXfrinState):
  372. def setUp(self):
  373. super().setUp()
  374. self.state = XfrinIXFRAddSOA()
  375. def test_handle_rr(self):
  376. self.assertTrue(self.state.handle_rr(self.conn, soa_rrset))
  377. self.assertEqual(type(XfrinIXFRAdd()), type(self.conn.get_xfrstate()))
  378. self.assertEqual([('add', soa_rrset)],
  379. self.conn._diff.get_buffer())
  380. def test_handle_non_soa(self):
  381. self.assertRaises(XfrinException, self.state.handle_rr, self.conn,
  382. self.ns_rrset)
  383. def test_finish_message(self):
  384. self.assertTrue(self.state.finish_message(self.conn))
  385. class TestXfrinIXFRAdd(TestXfrinState):
  386. def setUp(self):
  387. super().setUp()
  388. # We need record the state in 'conn' to check the case where the
  389. # state doesn't change.
  390. XfrinIXFRAdd().set_xfrstate(self.conn, XfrinIXFRAdd())
  391. self.conn._current_serial = 1230
  392. self.state = self.conn.get_xfrstate()
  393. def test_handle_add_rr(self):
  394. # Non SOA RRs are simply (goting to be) added in this state
  395. self.assertTrue(self.state.handle_rr(self.conn, self.ns_rrset))
  396. self.assertEqual([('add', self.ns_rrset)],
  397. self.conn._diff.get_buffer())
  398. # The state shouldn't change
  399. self.assertEqual(type(XfrinIXFRAdd()), type(self.conn.get_xfrstate()))
  400. def test_handle_end_soa(self):
  401. self.conn._end_serial = 1234
  402. self.conn._diff.add_data(self.ns_rrset) # put some dummy change
  403. self.assertTrue(self.state.handle_rr(self.conn, soa_rrset))
  404. self.assertEqual(type(XfrinIXFREnd()), type(self.conn.get_xfrstate()))
  405. # handle_rr should have caused commit, and the buffer should now be
  406. # empty.
  407. self.assertEqual([], self.conn._diff.get_buffer())
  408. def test_handle_new_delete(self):
  409. self.conn._end_serial = 1234
  410. # SOA RR whose serial is the current one means we are going to a new
  411. # difference, starting with removing that SOA.
  412. self.conn._diff.add_data(self.ns_rrset) # put some dummy change
  413. self.assertFalse(self.state.handle_rr(self.conn, self.begin_soa))
  414. self.assertEqual([], self.conn._diff.get_buffer())
  415. self.assertEqual(type(XfrinIXFRDeleteSOA()),
  416. type(self.conn.get_xfrstate()))
  417. def test_handle_out_of_sync(self):
  418. # getting SOA with an inconsistent serial. This is an error.
  419. self.conn._end_serial = 1235
  420. self.assertRaises(XfrinProtocolError, self.state.handle_rr,
  421. self.conn, soa_rrset)
  422. def test_finish_message(self):
  423. self.assertTrue(self.state.finish_message(self.conn))
  424. class TestXfrinIXFREnd(TestXfrinState):
  425. def setUp(self):
  426. super().setUp()
  427. self.state = XfrinIXFREnd()
  428. def test_handle_rr(self):
  429. self.assertRaises(XfrinProtocolError, self.state.handle_rr, self.conn,
  430. self.ns_rrset)
  431. def test_finish_message(self):
  432. self.assertFalse(self.state.finish_message(self.conn))
  433. class TestXfrinAXFR(TestXfrinState):
  434. def setUp(self):
  435. super().setUp()
  436. self.state = XfrinAXFR()
  437. self.conn._end_serial = 1234
  438. def test_handle_rr(self):
  439. """
  440. Test we can put data inside.
  441. """
  442. # Put some data inside
  443. self.assertTrue(self.state.handle_rr(self.conn, self.a_rrset))
  444. # This test uses internal Diff structure to check the behaviour of
  445. # XfrinAXFR. Maybe there could be a cleaner way, but it would be more
  446. # complicated.
  447. self.assertEqual([('add', self.a_rrset)], self.conn._diff.get_buffer())
  448. # This SOA terminates the transfer
  449. self.assertTrue(self.state.handle_rr(self.conn, soa_rrset))
  450. # It should have changed the state
  451. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  452. # At this point, the data haven't been committed yet
  453. self.assertEqual([('add', self.a_rrset), ('add', soa_rrset)],
  454. self.conn._diff.get_buffer())
  455. def test_handle_rr_mismatch_soa(self):
  456. """ SOA with inconsistent serial - unexpected, but we accept it.
  457. """
  458. self.assertTrue(self.state.handle_rr(self.conn, begin_soa_rrset))
  459. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  460. def test_finish_message(self):
  461. """
  462. Check normal end of message.
  463. """
  464. # When a message ends, nothing happens usually
  465. self.assertTrue(self.state.finish_message(self.conn))
  466. class TestXfrinAXFREnd(TestXfrinState):
  467. def setUp(self):
  468. super().setUp()
  469. self.state = XfrinAXFREnd()
  470. def test_handle_rr(self):
  471. self.assertRaises(XfrinProtocolError, self.state.handle_rr, self.conn,
  472. self.ns_rrset)
  473. def test_finish_message(self):
  474. self.conn._diff.add_data(self.a_rrset)
  475. self.conn._diff.add_data(soa_rrset)
  476. self.assertFalse(self.state.finish_message(self.conn))
  477. # The data should have been committed
  478. self.assertEqual([], self.conn._diff.get_buffer())
  479. check_diffs(self.assertEqual, [[('add', self.a_rrset),
  480. ('add', soa_rrset)]],
  481. self.conn._datasrc_client.committed_diffs)
  482. self.assertRaises(ValueError, self.conn._diff.commit)
  483. class TestXfrinConnection(unittest.TestCase):
  484. '''Convenient parent class for XFR-protocol tests.
  485. This class provides common setups and helper methods for protocol related
  486. tests on AXFR and IXFR.
  487. '''
  488. def setUp(self):
  489. if os.path.exists(TEST_DB_FILE):
  490. os.remove(TEST_DB_FILE)
  491. self.sock_map = {}
  492. self.conn = MockXfrinConnection(self.sock_map, TEST_ZONE_NAME,
  493. TEST_RRCLASS, threading.Event(),
  494. TEST_MASTER_IPV4_ADDRINFO)
  495. self.soa_response_params = {
  496. 'questions': [example_soa_question],
  497. 'bad_qid': False,
  498. 'response': True,
  499. 'rcode': Rcode.NOERROR(),
  500. 'tsig': False,
  501. 'axfr_after_soa': self._create_normal_response_data
  502. }
  503. self.axfr_response_params = {
  504. 'question_1st': default_questions,
  505. 'question_2nd': default_questions,
  506. 'answer_1st': [soa_rrset, self._create_ns()],
  507. 'answer_2nd': default_answers,
  508. 'tsig_1st': None,
  509. 'tsig_2nd': None
  510. }
  511. def tearDown(self):
  512. self.conn.close()
  513. if os.path.exists(TEST_DB_FILE):
  514. os.remove(TEST_DB_FILE)
  515. def _create_normal_response_data(self):
  516. # This helper method creates a simple sequence of DNS messages that
  517. # forms a valid AXFR transaction. It consists of two messages: the
  518. # first one containing SOA, NS, the second containing the trailing SOA.
  519. question_1st = self.axfr_response_params['question_1st']
  520. question_2nd = self.axfr_response_params['question_2nd']
  521. answer_1st = self.axfr_response_params['answer_1st']
  522. answer_2nd = self.axfr_response_params['answer_2nd']
  523. tsig_1st = self.axfr_response_params['tsig_1st']
  524. tsig_2nd = self.axfr_response_params['tsig_2nd']
  525. self.conn.reply_data = self.conn.create_response_data(
  526. questions=question_1st, answers=answer_1st,
  527. tsig_ctx=tsig_1st)
  528. self.conn.reply_data += \
  529. self.conn.create_response_data(questions=question_2nd,
  530. answers=answer_2nd,
  531. tsig_ctx=tsig_2nd)
  532. def _create_soa_response_data(self):
  533. # This helper method creates a DNS message that is supposed to be
  534. # used a valid response to SOA queries prior to XFR.
  535. # If tsig is True, it tries to verify the query with a locally
  536. # created TSIG context (which may or may not succeed) so that the
  537. # response will include a TSIG.
  538. # If axfr_after_soa is True, it resets the response_generator so that
  539. # a valid XFR messages will follow.
  540. verify_ctx = None
  541. if self.soa_response_params['tsig']:
  542. # xfrin (currently) always uses TCP. strip off the length field.
  543. query_data = self.conn.query_data[2:]
  544. query_message = Message(Message.PARSE)
  545. query_message.from_wire(query_data)
  546. verify_ctx = TSIGContext(TSIG_KEY)
  547. verify_ctx.verify(query_message.get_tsig_record(), query_data)
  548. self.conn.reply_data = self.conn.create_response_data(
  549. bad_qid=self.soa_response_params['bad_qid'],
  550. response=self.soa_response_params['response'],
  551. rcode=self.soa_response_params['rcode'],
  552. questions=self.soa_response_params['questions'],
  553. tsig_ctx=verify_ctx)
  554. if self.soa_response_params['axfr_after_soa'] != None:
  555. self.conn.response_generator = \
  556. self.soa_response_params['axfr_after_soa']
  557. def _create_broken_response_data(self):
  558. # This helper method creates a bogus "DNS message" that only contains
  559. # 4 octets of data. The DNS message parser will raise an exception.
  560. bogus_data = b'xxxx'
  561. self.conn.reply_data = struct.pack('H', socket.htons(len(bogus_data)))
  562. self.conn.reply_data += bogus_data
  563. def _create_a(self, address):
  564. rrset = RRset(Name('a.example.com'), TEST_RRCLASS, RRType.A(),
  565. RRTTL(3600))
  566. rrset.add_rdata(Rdata(RRType.A(), TEST_RRCLASS, address))
  567. return rrset
  568. def _create_soa(self, serial):
  569. rrset = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.SOA(),
  570. RRTTL(3600))
  571. rdata_str = 'm. r. ' + serial + ' 3600 1800 2419200 7200'
  572. rrset.add_rdata(Rdata(RRType.SOA(), TEST_RRCLASS, rdata_str))
  573. return rrset
  574. def _create_ns(self, nsname='ns.'+TEST_ZONE_NAME_STR):
  575. rrset = RRset(TEST_ZONE_NAME, TEST_RRCLASS, RRType.NS(), RRTTL(3600))
  576. rrset.add_rdata(Rdata(RRType.NS(), TEST_RRCLASS, nsname))
  577. return rrset
  578. class TestAXFR(TestXfrinConnection):
  579. def setUp(self):
  580. super().setUp()
  581. XfrinInitialSOA().set_xfrstate(self.conn, XfrinInitialSOA())
  582. def __create_mock_tsig(self, key, error):
  583. # This helper function creates a MockTSIGContext for a given key
  584. # and TSIG error to be used as a result of verify (normally faked
  585. # one)
  586. mock_ctx = MockTSIGContext(key)
  587. mock_ctx.error = error
  588. return mock_ctx
  589. def __match_exception(self, expected_exception, expected_msg, expression):
  590. # This helper method is a higher-granularity version of assertRaises().
  591. # If it's not sufficient to check the exception class (e.g., when
  592. # the same type of exceptions can be thrown from many places), this
  593. # method can be used to check it with the exception argument.
  594. try:
  595. expression()
  596. except expected_exception as ex:
  597. self.assertEqual(str(ex), expected_msg)
  598. else:
  599. self.assertFalse('exception is expected, but not raised')
  600. def test_close(self):
  601. # we shouldn't be using the global asyncore map.
  602. self.assertEqual(len(asyncore.socket_map), 0)
  603. # there should be exactly one entry in our local map
  604. self.assertEqual(len(self.sock_map), 1)
  605. # once closing the dispatch the map should become empty
  606. self.conn.close()
  607. self.assertEqual(len(self.sock_map), 0)
  608. def test_init_ip6(self):
  609. # This test simply creates a new XfrinConnection object with an
  610. # IPv6 address, tries to bind it to an IPv6 wildcard address/port
  611. # to confirm an AF_INET6 socket has been created. A naive application
  612. # tends to assume it's IPv4 only and hardcode AF_INET. This test
  613. # uncovers such a bug.
  614. c = MockXfrinConnection({}, TEST_ZONE_NAME, TEST_RRCLASS,
  615. threading.Event(), TEST_MASTER_IPV6_ADDRINFO)
  616. c.bind(('::', 0))
  617. c.close()
  618. def test_init_chclass(self):
  619. c = MockXfrinConnection({}, TEST_ZONE_NAME, RRClass.CH(),
  620. threading.Event(), TEST_MASTER_IPV4_ADDRINFO)
  621. axfrmsg = c._create_query(RRType.AXFR())
  622. self.assertEqual(axfrmsg.get_question()[0].get_class(),
  623. RRClass.CH())
  624. c.close()
  625. def test_create_query(self):
  626. def check_query(expected_qtype, expected_auth):
  627. '''Helper method to repeat the same pattern of tests'''
  628. self.assertEqual(Opcode.QUERY(), msg.get_opcode())
  629. self.assertEqual(Rcode.NOERROR(), msg.get_rcode())
  630. self.assertEqual(1, msg.get_rr_count(Message.SECTION_QUESTION))
  631. self.assertEqual(TEST_ZONE_NAME, msg.get_question()[0].get_name())
  632. self.assertEqual(expected_qtype, msg.get_question()[0].get_type())
  633. self.assertEqual(0, msg.get_rr_count(Message.SECTION_ANSWER))
  634. self.assertEqual(0, msg.get_rr_count(Message.SECTION_ADDITIONAL))
  635. if expected_auth is None:
  636. self.assertEqual(0,
  637. msg.get_rr_count(Message.SECTION_AUTHORITY))
  638. else:
  639. self.assertEqual(1,
  640. msg.get_rr_count(Message.SECTION_AUTHORITY))
  641. auth_rr = msg.get_section(Message.SECTION_AUTHORITY)[0]
  642. self.assertEqual(expected_auth.get_name(), auth_rr.get_name())
  643. self.assertEqual(expected_auth.get_type(), auth_rr.get_type())
  644. self.assertEqual(expected_auth.get_class(),
  645. auth_rr.get_class())
  646. # In our test scenario RDATA must be 1
  647. self.assertEqual(1, expected_auth.get_rdata_count())
  648. self.assertEqual(1, auth_rr.get_rdata_count())
  649. self.assertEqual(expected_auth.get_rdata()[0],
  650. auth_rr.get_rdata()[0])
  651. # Actual tests start here
  652. # SOA query
  653. msg = self.conn._create_query(RRType.SOA())
  654. check_query(RRType.SOA(), None)
  655. # AXFR query
  656. msg = self.conn._create_query(RRType.AXFR())
  657. check_query(RRType.AXFR(), None)
  658. # IXFR query
  659. msg = self.conn._create_query(RRType.IXFR())
  660. check_query(RRType.IXFR(), begin_soa_rrset)
  661. self.assertEqual(1230, self.conn._request_serial)
  662. def test_create_ixfr_query_fail(self):
  663. # In these cases _create_query() will fail to find a valid SOA RR to
  664. # insert in the IXFR query, and should raise an exception.
  665. self.conn._zone_name = Name('no-such-zone.example')
  666. self.assertRaises(XfrinException, self.conn._create_query,
  667. RRType.IXFR())
  668. self.conn._zone_name = Name('partial-match-zone.example')
  669. self.assertRaises(XfrinException, self.conn._create_query,
  670. RRType.IXFR())
  671. self.conn._zone_name = Name('no-soa.example')
  672. self.assertRaises(XfrinException, self.conn._create_query,
  673. RRType.IXFR())
  674. self.conn._zone_name = Name('dup-soa.example')
  675. self.assertRaises(XfrinException, self.conn._create_query,
  676. RRType.IXFR())
  677. def test_send_query(self):
  678. def message_has_tsig(data):
  679. # a simple check if the actual data contains a TSIG RR.
  680. # At our level this simple check should suffice; other detailed
  681. # tests regarding the TSIG protocol are done in pydnspp.
  682. msg = Message(Message.PARSE)
  683. msg.from_wire(data)
  684. return msg.get_tsig_record() is not None
  685. # soa request with tsig
  686. self.conn._tsig_key = TSIG_KEY
  687. self.conn._send_query(RRType.SOA())
  688. self.assertTrue(message_has_tsig(self.conn.query_data[2:]))
  689. # axfr request with tsig
  690. self.conn._send_query(RRType.AXFR())
  691. self.assertTrue(message_has_tsig(self.conn.query_data[2:]))
  692. def test_response_with_invalid_msg(self):
  693. self.conn.reply_data = b'aaaxxxx'
  694. self.assertRaises(XfrinTestException,
  695. self.conn._handle_xfrin_responses)
  696. def test_response_with_tsigfail(self):
  697. self.conn._tsig_key = TSIG_KEY
  698. # server tsig check fail, return with RCODE 9 (NOTAUTH)
  699. self.conn._send_query(RRType.SOA())
  700. self.conn.reply_data = self.conn.create_response_data(rcode=Rcode.NOTAUTH())
  701. self.assertRaises(XfrinException, self.conn._handle_xfrin_responses)
  702. def test_response_without_end_soa(self):
  703. self.conn._send_query(RRType.AXFR())
  704. self.conn.reply_data = self.conn.create_response_data()
  705. # This should result in timeout in the asyncore loop. We emulate
  706. # that situation in recv() by emptying the reply data buffer.
  707. self.assertRaises(XfrinTestTimeoutException,
  708. self.conn._handle_xfrin_responses)
  709. def test_response_bad_qid(self):
  710. self.conn._send_query(RRType.AXFR())
  711. self.conn.reply_data = self.conn.create_response_data(bad_qid=True)
  712. self.assertRaises(XfrinException, self.conn._handle_xfrin_responses)
  713. def test_response_error_code_bad_sig(self):
  714. self.conn._tsig_key = TSIG_KEY
  715. self.conn._tsig_ctx_creator = \
  716. lambda key: self.__create_mock_tsig(key, TSIGError.BAD_SIG)
  717. self.conn._send_query(RRType.AXFR())
  718. self.conn.reply_data = self.conn.create_response_data(
  719. rcode=Rcode.SERVFAIL())
  720. # xfrin should check TSIG before other part of incoming message
  721. # validate log message for XfrinException
  722. self.__match_exception(XfrinException,
  723. "TSIG verify fail: BADSIG",
  724. self.conn._handle_xfrin_responses)
  725. def test_response_bad_qid_bad_key(self):
  726. self.conn._tsig_key = TSIG_KEY
  727. self.conn._tsig_ctx_creator = \
  728. lambda key: self.__create_mock_tsig(key, TSIGError.BAD_KEY)
  729. self.conn._send_query(RRType.AXFR())
  730. self.conn.reply_data = self.conn.create_response_data(bad_qid=True)
  731. # xfrin should check TSIG before other part of incoming message
  732. # validate log message for XfrinException
  733. self.__match_exception(XfrinException,
  734. "TSIG verify fail: BADKEY",
  735. self.conn._handle_xfrin_responses)
  736. def test_response_non_response(self):
  737. self.conn._send_query(RRType.AXFR())
  738. self.conn.reply_data = self.conn.create_response_data(response=False)
  739. self.assertRaises(XfrinException, self.conn._handle_xfrin_responses)
  740. def test_response_error_code(self):
  741. self.conn._send_query(RRType.AXFR())
  742. self.conn.reply_data = self.conn.create_response_data(
  743. rcode=Rcode.SERVFAIL())
  744. self.assertRaises(XfrinException, self.conn._handle_xfrin_responses)
  745. def test_response_multi_question(self):
  746. self.conn._send_query(RRType.AXFR())
  747. self.conn.reply_data = self.conn.create_response_data(
  748. questions=[example_axfr_question, example_axfr_question])
  749. self.assertRaises(XfrinException, self.conn._handle_xfrin_responses)
  750. def test_response_non_response(self):
  751. self.conn._send_query(RRType.AXFR())
  752. self.conn.reply_data = self.conn.create_response_data(response = False)
  753. self.assertRaises(XfrinException, self.conn._handle_xfrin_responses)
  754. def test_soacheck(self):
  755. # we need to defer the creation until we know the QID, which is
  756. # determined in _check_soa_serial(), so we use response_generator.
  757. self.conn.response_generator = self._create_soa_response_data
  758. self.assertEqual(self.conn._check_soa_serial(), XFRIN_OK)
  759. def test_soacheck_with_bad_response(self):
  760. self.conn.response_generator = self._create_broken_response_data
  761. self.assertRaises(MessageTooShort, self.conn._check_soa_serial)
  762. def test_soacheck_badqid(self):
  763. self.soa_response_params['bad_qid'] = True
  764. self.conn.response_generator = self._create_soa_response_data
  765. self.assertRaises(XfrinException, self.conn._check_soa_serial)
  766. def test_soacheck_bad_qid_bad_sig(self):
  767. self.conn._tsig_key = TSIG_KEY
  768. self.conn._tsig_ctx_creator = \
  769. lambda key: self.__create_mock_tsig(key, TSIGError.BAD_SIG)
  770. self.soa_response_params['bad_qid'] = True
  771. self.conn.response_generator = self._create_soa_response_data
  772. # xfrin should check TSIG before other part of incoming message
  773. # validate log message for XfrinException
  774. self.__match_exception(XfrinException,
  775. "TSIG verify fail: BADSIG",
  776. self.conn._check_soa_serial)
  777. def test_soacheck_non_response(self):
  778. self.soa_response_params['response'] = False
  779. self.conn.response_generator = self._create_soa_response_data
  780. self.assertRaises(XfrinException, self.conn._check_soa_serial)
  781. def test_soacheck_error_code(self):
  782. self.soa_response_params['rcode'] = Rcode.SERVFAIL()
  783. self.conn.response_generator = self._create_soa_response_data
  784. self.assertRaises(XfrinException, self.conn._check_soa_serial)
  785. def test_soacheck_with_tsig(self):
  786. # Use a mock tsig context emulating a validly signed response
  787. self.conn._tsig_key = TSIG_KEY
  788. self.conn._tsig_ctx_creator = \
  789. lambda key: self.__create_mock_tsig(key, TSIGError.NOERROR)
  790. self.conn.response_generator = self._create_soa_response_data
  791. self.assertEqual(self.conn._check_soa_serial(), XFRIN_OK)
  792. self.assertEqual(self.conn._tsig_ctx.get_error(), TSIGError.NOERROR)
  793. def test_soacheck_with_tsig_notauth(self):
  794. # emulate a valid error response
  795. self.conn._tsig_key = TSIG_KEY
  796. self.conn._tsig_ctx_creator = \
  797. lambda key: self.__create_mock_tsig(key, TSIGError.BAD_SIG)
  798. self.soa_response_params['rcode'] = Rcode.NOTAUTH()
  799. self.conn.response_generator = self._create_soa_response_data
  800. self.assertRaises(XfrinException, self.conn._check_soa_serial)
  801. def test_soacheck_with_tsig_noerror_badsig(self):
  802. self.conn._tsig_key = TSIG_KEY
  803. self.conn._tsig_ctx_creator = \
  804. lambda key: self.__create_mock_tsig(key, TSIGError.BAD_SIG)
  805. # emulate a normal response bad verification failure due to BADSIG.
  806. # According RFC2845, in this case we should ignore it and keep
  807. # waiting for a valid response until a timeout. But we immediately
  808. # treat this as a final failure (just as BIND 9 does).
  809. self.conn.response_generator = self._create_soa_response_data
  810. self.assertRaises(XfrinException, self.conn._check_soa_serial)
  811. def test_soacheck_with_tsig_unsigned_response(self):
  812. # we can use a real TSIGContext for this. the response doesn't
  813. # contain a TSIG while we sent a signed query. RFC2845 states
  814. # we should wait for a valid response in this case, but we treat
  815. # it as a fatal transaction failure, too.
  816. self.conn._tsig_key = TSIG_KEY
  817. self.conn.response_generator = self._create_soa_response_data
  818. self.assertRaises(XfrinException, self.conn._check_soa_serial)
  819. def test_soacheck_with_unexpected_tsig_response(self):
  820. # we reject unexpected TSIG in responses (following BIND 9's
  821. # behavior)
  822. self.soa_response_params['tsig'] = True
  823. self.conn.response_generator = self._create_soa_response_data
  824. self.assertRaises(XfrinException, self.conn._check_soa_serial)
  825. def test_response_shutdown(self):
  826. self.conn.response_generator = self._create_normal_response_data
  827. self.conn._shutdown_event.set()
  828. self.conn._send_query(RRType.AXFR())
  829. self.assertRaises(XfrinException, self.conn._handle_xfrin_responses)
  830. def test_response_timeout(self):
  831. self.conn.response_generator = self._create_normal_response_data
  832. self.conn.force_time_out = True
  833. self.assertRaises(XfrinException, self.conn._handle_xfrin_responses)
  834. def test_response_remote_close(self):
  835. self.conn.response_generator = self._create_normal_response_data
  836. self.conn.force_close = True
  837. self.assertRaises(XfrinException, self.conn._handle_xfrin_responses)
  838. def test_response_bad_message(self):
  839. self.conn.response_generator = self._create_broken_response_data
  840. self.conn._send_query(RRType.AXFR())
  841. self.assertRaises(Exception, self.conn._handle_xfrin_responses)
  842. def test_axfr_response(self):
  843. # A simple normal case: AXFR consists of SOA, NS, then trailing SOA.
  844. self.conn.response_generator = self._create_normal_response_data
  845. self.conn._send_query(RRType.AXFR())
  846. self.conn._handle_xfrin_responses()
  847. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  848. check_diffs(self.assertEqual,
  849. [[('add', self._create_ns()), ('add', soa_rrset)]],
  850. self.conn._datasrc_client.committed_diffs)
  851. def test_response_empty_answer(self):
  852. '''Test with an empty AXFR answer section.
  853. This is an unusual response, but there is no reason to reject it.
  854. The second message is a complete AXFR response, and transfer should
  855. succeed just like the normal case.
  856. '''
  857. self.axfr_response_params['answer_1st'] = []
  858. self.axfr_response_params['answer_2nd'] = [soa_rrset,
  859. self._create_ns(),
  860. soa_rrset]
  861. self.conn.response_generator = self._create_normal_response_data
  862. self.conn._send_query(RRType.AXFR())
  863. self.conn._handle_xfrin_responses()
  864. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  865. check_diffs(self.assertEqual,
  866. [[('add', self._create_ns()), ('add', soa_rrset)]],
  867. self.conn._datasrc_client.committed_diffs)
  868. def test_axfr_response_soa_mismatch(self):
  869. '''AXFR response whose begin/end SOAs are not same.
  870. What should we do this is moot, for now we accept it, so does BIND 9.
  871. '''
  872. ns_rr = self._create_ns()
  873. a_rr = self._create_a('192.0.2.1')
  874. self.conn._send_query(RRType.AXFR())
  875. self.conn.reply_data = self.conn.create_response_data(
  876. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  877. RRType.AXFR())],
  878. # begin serial=1230, end serial=1234. end will be used.
  879. answers=[begin_soa_rrset, ns_rr, a_rr, soa_rrset])
  880. self.conn._handle_xfrin_responses()
  881. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  882. check_diffs(self.assertEqual,
  883. [[('add', ns_rr), ('add', a_rr), ('add', soa_rrset)]],
  884. self.conn._datasrc_client.committed_diffs)
  885. def test_axfr_response_extra(self):
  886. '''Test with an extra RR after the end of AXFR session.
  887. The session should be rejected, and nothing should be committed.
  888. '''
  889. ns_rr = self._create_ns()
  890. a_rr = self._create_a('192.0.2.1')
  891. self.conn._send_query(RRType.AXFR())
  892. self.conn.reply_data = self.conn.create_response_data(
  893. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  894. RRType.AXFR())],
  895. answers=[soa_rrset, ns_rr, a_rr, soa_rrset, a_rr])
  896. self.assertRaises(XfrinProtocolError,
  897. self.conn._handle_xfrin_responses)
  898. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  899. self.assertEqual([], self.conn._datasrc_client.committed_diffs)
  900. def test_axfr_response_qname_mismatch(self):
  901. '''AXFR response with a mismatch question name.
  902. Our implementation accepts that, so does BIND 9.
  903. '''
  904. self.axfr_response_params['question_1st'] = \
  905. [Question(Name('mismatch.example'), TEST_RRCLASS, RRType.AXFR())]
  906. self.conn.response_generator = self._create_normal_response_data
  907. self.conn._send_query(RRType.AXFR())
  908. self.conn._handle_xfrin_responses()
  909. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  910. check_diffs(self.assertEqual,
  911. [[('add', self._create_ns()), ('add', soa_rrset)]],
  912. self.conn._datasrc_client.committed_diffs)
  913. def test_axfr_response_qclass_mismatch(self):
  914. '''AXFR response with a mismatch RR class.
  915. Our implementation accepts that, so does BIND 9.
  916. '''
  917. self.axfr_response_params['question_1st'] = \
  918. [Question(TEST_ZONE_NAME, RRClass.CH(), RRType.AXFR())]
  919. self.conn.response_generator = self._create_normal_response_data
  920. self.conn._send_query(RRType.AXFR())
  921. self.conn._handle_xfrin_responses()
  922. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  923. check_diffs(self.assertEqual,
  924. [[('add', self._create_ns()), ('add', soa_rrset)]],
  925. self.conn._datasrc_client.committed_diffs)
  926. def test_axfr_response_qtype_mismatch(self):
  927. '''AXFR response with a mismatch RR type.
  928. Our implementation accepts that, so does BIND 9.
  929. '''
  930. # returning IXFR in question to AXFR query
  931. self.axfr_response_params['question_1st'] = \
  932. [Question(TEST_ZONE_NAME, RRClass.CH(), RRType.IXFR())]
  933. self.conn.response_generator = self._create_normal_response_data
  934. self.conn._send_query(RRType.AXFR())
  935. self.conn._handle_xfrin_responses()
  936. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  937. check_diffs(self.assertEqual,
  938. [[('add', self._create_ns()), ('add', soa_rrset)]],
  939. self.conn._datasrc_client.committed_diffs)
  940. def test_axfr_response_empty_question(self):
  941. '''AXFR response with an empty question.
  942. Our implementation accepts that, so does BIND 9.
  943. '''
  944. self.axfr_response_params['question_1st'] = []
  945. self.conn.response_generator = self._create_normal_response_data
  946. self.conn._send_query(RRType.AXFR())
  947. self.conn._handle_xfrin_responses()
  948. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  949. check_diffs(self.assertEqual,
  950. [[('add', self._create_ns()), ('add', soa_rrset)]],
  951. self.conn._datasrc_client.committed_diffs)
  952. def test_do_xfrin(self):
  953. self.conn.response_generator = self._create_normal_response_data
  954. self.assertEqual(self.conn.do_xfrin(False), XFRIN_OK)
  955. def test_do_xfrin_with_tsig(self):
  956. # use TSIG with a mock context. we fake all verify results to
  957. # emulate successful verification.
  958. self.conn._tsig_key = TSIG_KEY
  959. self.conn._tsig_ctx_creator = \
  960. lambda key: self.__create_mock_tsig(key, TSIGError.NOERROR)
  961. self.conn.response_generator = self._create_normal_response_data
  962. self.assertEqual(self.conn.do_xfrin(False), XFRIN_OK)
  963. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  964. check_diffs(self.assertEqual,
  965. [[('add', self._create_ns()), ('add', soa_rrset)]],
  966. self.conn._datasrc_client.committed_diffs)
  967. def test_do_xfrin_with_tsig_fail(self):
  968. # TSIG verify will fail for the first message. xfrin should fail
  969. # immediately.
  970. self.conn._tsig_key = TSIG_KEY
  971. self.conn._tsig_ctx_creator = \
  972. lambda key: self.__create_mock_tsig(key, TSIGError.BAD_SIG)
  973. self.conn.response_generator = self._create_normal_response_data
  974. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  975. self.assertEqual(1, self.conn._tsig_ctx.verify_called)
  976. def test_do_xfrin_with_tsig_fail_for_second_message(self):
  977. # Similar to the previous test, but first verify succeeds. There
  978. # should be a second verify attempt, which will fail, which should
  979. # make xfrin fail.
  980. def fake_tsig_error(ctx):
  981. if self.conn._tsig_ctx.verify_called == 1:
  982. return TSIGError.NOERROR
  983. return TSIGError.BAD_SIG
  984. self.conn._tsig_key = TSIG_KEY
  985. self.conn._tsig_ctx_creator = \
  986. lambda key: self.__create_mock_tsig(key, fake_tsig_error)
  987. self.conn.response_generator = self._create_normal_response_data
  988. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  989. self.assertEqual(2, self.conn._tsig_ctx.verify_called)
  990. def test_do_xfrin_with_missing_tsig(self):
  991. # XFR request sent with TSIG, but the response doesn't have TSIG.
  992. # xfr should fail.
  993. self.conn._tsig_key = TSIG_KEY
  994. self.conn._tsig_ctx_creator = \
  995. lambda key: self.__create_mock_tsig(key, None)
  996. self.conn._tsig_ctx = MockTSIGContext(TSIG_KEY)
  997. self.conn.response_generator = self._create_normal_response_data
  998. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  999. self.assertEqual(1, self.conn._tsig_ctx.verify_called)
  1000. def test_do_xfrin_with_missing_tsig_for_second_message(self):
  1001. # Similar to the previous test, but firt one contains TSIG and verify
  1002. # succeeds (due to fake). The second message lacks TSIG.
  1003. #
  1004. # Note: this test case is actually not that trivial: Skipping
  1005. # intermediate TSIG is allowed. In this case, however, the second
  1006. # message is the last one, which must contain TSIG anyway, so the
  1007. # expected result is correct. If/when we support skipping
  1008. # intermediate TSIGs, we'll need additional test cases.
  1009. def fake_tsig_error(ctx):
  1010. if self.conn._tsig_ctx.verify_called == 1:
  1011. return TSIGError.NOERROR
  1012. return TSIGError.FORMERR
  1013. self.conn._tsig_key = TSIG_KEY
  1014. self.conn._tsig_ctx_creator = \
  1015. lambda key: self.__create_mock_tsig(key, fake_tsig_error)
  1016. self.conn.response_generator = self._create_normal_response_data
  1017. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1018. self.assertEqual(2, self.conn._tsig_ctx.verify_called)
  1019. def test_do_xfrin_with_unexpected_tsig(self):
  1020. # XFR request wasn't signed, but response includes TSIG. Like BIND 9,
  1021. # we reject that.
  1022. self.axfr_response_params['tsig_1st'] = TSIGContext(TSIG_KEY)
  1023. self.conn.response_generator = self._create_normal_response_data
  1024. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1025. def test_do_xfrin_with_unexpected_tsig_for_second_message(self):
  1026. # similar to the previous test, but the first message is normal.
  1027. # the second one contains an unexpected TSIG. should be rejected.
  1028. self.axfr_response_params['tsig_2nd'] = TSIGContext(TSIG_KEY)
  1029. self.conn.response_generator = self._create_normal_response_data
  1030. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1031. def test_do_xfrin_empty_response(self):
  1032. # skipping the creation of response data, so the transfer will fail.
  1033. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1034. def test_do_xfrin_bad_response(self):
  1035. self.conn.response_generator = self._create_broken_response_data
  1036. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1037. def test_do_xfrin_datasrc_error(self):
  1038. # Emulate failure in the data source client on commit.
  1039. self.conn._datasrc_client.force_fail = True
  1040. self.conn.response_generator = self._create_normal_response_data
  1041. self.assertEqual(self.conn.do_xfrin(False), XFRIN_FAIL)
  1042. def test_do_soacheck_and_xfrin(self):
  1043. self.conn.response_generator = self._create_soa_response_data
  1044. self.assertEqual(self.conn.do_xfrin(True), XFRIN_OK)
  1045. def test_do_soacheck_and_xfrin_with_tsig(self):
  1046. # We are going to have a SOA query/response transaction, followed by
  1047. # AXFR, all TSIG signed. xfrin should use a new TSIG context for
  1048. # AXFR. We are not interested in whether verify works correctly in
  1049. # this test, so we simply fake the results (they need to succeed for
  1050. # this test)
  1051. self.conn._tsig_key = TSIG_KEY
  1052. self.conn._tsig_ctx_creator = \
  1053. lambda key: self.__create_mock_tsig(key, TSIGError.NOERROR)
  1054. self.soa_response_params['tsig'] = True
  1055. self.conn.response_generator = self._create_soa_response_data
  1056. self.assertEqual(self.conn.do_xfrin(True), XFRIN_OK)
  1057. # We should've got 3 response messages: 1 SOA and two AXFR, but
  1058. # the context should be replaced for AXFR, so verify() should be
  1059. # called only twice for the latest context.
  1060. self.assertEqual(2, self.conn._tsig_ctx.verify_called)
  1061. def test_do_soacheck_broken_response(self):
  1062. self.conn.response_generator = self._create_broken_response_data
  1063. self.assertEqual(self.conn.do_xfrin(True), XFRIN_FAIL)
  1064. def test_do_soacheck_badqid(self):
  1065. # the QID mismatch would internally trigger a XfrinException exception,
  1066. # and covers part of the code that other tests can't.
  1067. self.soa_response_params['bad_qid'] = True
  1068. self.conn.response_generator = self._create_soa_response_data
  1069. self.assertEqual(self.conn.do_xfrin(True), XFRIN_FAIL)
  1070. class TestIXFRResponse(TestXfrinConnection):
  1071. def setUp(self):
  1072. super().setUp()
  1073. self.conn._query_id = self.conn.qid = 1035
  1074. self.conn._request_serial = 1230
  1075. self.conn._request_type = RRType.IXFR()
  1076. self._zone_name = TEST_ZONE_NAME
  1077. self.conn._datasrc_client = MockDataSourceClient()
  1078. XfrinInitialSOA().set_xfrstate(self.conn, XfrinInitialSOA())
  1079. def test_ixfr_response(self):
  1080. '''A simplest form of IXFR response.
  1081. It simply updates the zone's SOA one time.
  1082. '''
  1083. self.conn.reply_data = self.conn.create_response_data(
  1084. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1085. answers=[soa_rrset, begin_soa_rrset, soa_rrset, soa_rrset])
  1086. self.conn._handle_xfrin_responses()
  1087. self.assertEqual(type(XfrinIXFREnd()), type(self.conn.get_xfrstate()))
  1088. self.assertEqual([], self.conn._datasrc_client.diffs)
  1089. check_diffs(self.assertEqual,
  1090. [[('delete', begin_soa_rrset), ('add', soa_rrset)]],
  1091. self.conn._datasrc_client.committed_diffs)
  1092. def test_ixfr_response_multi_sequences(self):
  1093. '''Similar to the previous case, but with multiple diff seqs.
  1094. '''
  1095. self.conn.reply_data = self.conn.create_response_data(
  1096. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1097. answers=[soa_rrset,
  1098. # removing one A in serial 1230
  1099. begin_soa_rrset, self._create_a('192.0.2.1'),
  1100. # adding one A in serial 1231
  1101. self._create_soa('1231'), self._create_a('192.0.2.2'),
  1102. # removing one A in serial 1231
  1103. self._create_soa('1231'), self._create_a('192.0.2.3'),
  1104. # adding one A in serial 1232
  1105. self._create_soa('1232'), self._create_a('192.0.2.4'),
  1106. # removing one A in serial 1232
  1107. self._create_soa('1232'), self._create_a('192.0.2.5'),
  1108. # adding one A in serial 1234
  1109. soa_rrset, self._create_a('192.0.2.6'),
  1110. soa_rrset])
  1111. self.conn._handle_xfrin_responses()
  1112. self.assertEqual(type(XfrinIXFREnd()), type(self.conn.get_xfrstate()))
  1113. self.assertEqual([], self.conn._datasrc_client.diffs)
  1114. check_diffs(self.assertEqual,
  1115. [[('delete', begin_soa_rrset),
  1116. ('delete', self._create_a('192.0.2.1')),
  1117. ('add', self._create_soa('1231')),
  1118. ('add', self._create_a('192.0.2.2'))],
  1119. [('delete', self._create_soa('1231')),
  1120. ('delete', self._create_a('192.0.2.3')),
  1121. ('add', self._create_soa('1232')),
  1122. ('add', self._create_a('192.0.2.4'))],
  1123. [('delete', self._create_soa('1232')),
  1124. ('delete', self._create_a('192.0.2.5')),
  1125. ('add', soa_rrset),
  1126. ('add', self._create_a('192.0.2.6'))]],
  1127. self.conn._datasrc_client.committed_diffs)
  1128. def test_ixfr_response_multi_messages(self):
  1129. '''Similar to the first case, but RRs span over multiple messages.
  1130. '''
  1131. self.conn.reply_data = self.conn.create_response_data(
  1132. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1133. answers=[soa_rrset, begin_soa_rrset, soa_rrset])
  1134. self.conn.reply_data += self.conn.create_response_data(
  1135. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1136. answers=[soa_rrset])
  1137. self.conn._handle_xfrin_responses()
  1138. self.assertEqual(type(XfrinIXFREnd()), type(self.conn.get_xfrstate()))
  1139. check_diffs(self.assertEqual,
  1140. [[('delete', begin_soa_rrset), ('add', soa_rrset)]],
  1141. self.conn._datasrc_client.committed_diffs)
  1142. def test_ixfr_response_broken(self):
  1143. '''Test with a broken response.
  1144. '''
  1145. # SOA sequence is out-of-sync
  1146. self.conn.reply_data = self.conn.create_response_data(
  1147. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1148. answers=[soa_rrset, begin_soa_rrset, soa_rrset,
  1149. self._create_soa('1235')])
  1150. self.assertRaises(XfrinProtocolError,
  1151. self.conn._handle_xfrin_responses)
  1152. # no diffs should have been committed
  1153. check_diffs(self.assertEqual,
  1154. [], self.conn._datasrc_client.committed_diffs)
  1155. def test_ixfr_response_extra(self):
  1156. '''Test with an extra RR after the end of IXFR diff sequences.
  1157. IXFR should be rejected, but complete diff sequences should be
  1158. committed; it's not clear whether it's compliant to the protocol
  1159. specification, but it is how BIND 9 works and we do the same.
  1160. '''
  1161. self.conn.reply_data = self.conn.create_response_data(
  1162. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1163. answers=[soa_rrset, begin_soa_rrset, soa_rrset, soa_rrset,
  1164. self._create_a('192.0.2.1')])
  1165. self.assertRaises(XfrinProtocolError,
  1166. self.conn._handle_xfrin_responses)
  1167. check_diffs(self.assertEqual,
  1168. [[('delete', begin_soa_rrset), ('add', soa_rrset)]],
  1169. self.conn._datasrc_client.committed_diffs)
  1170. def test_ixfr_to_axfr_response(self):
  1171. '''AXFR-style IXFR response.
  1172. It simply updates the zone's SOA one time.
  1173. '''
  1174. ns_rr = self._create_ns()
  1175. a_rr = self._create_a('192.0.2.1')
  1176. self.conn.reply_data = self.conn.create_response_data(
  1177. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1178. answers=[soa_rrset, ns_rr, a_rr, soa_rrset])
  1179. self.conn._handle_xfrin_responses()
  1180. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1181. self.assertEqual([], self.conn._datasrc_client.diffs)
  1182. # The SOA should be added exactly once, and in our implementation
  1183. # it should be added at the end of the sequence.
  1184. check_diffs(self.assertEqual,
  1185. [[('add', ns_rr), ('add', a_rr), ('add', soa_rrset)]],
  1186. self.conn._datasrc_client.committed_diffs)
  1187. def test_ixfr_to_axfr_response_mismatch_soa(self):
  1188. '''AXFR-style IXFR response, but the two SOA are not the same.
  1189. In the current implementation, we accept it and use the second SOA.
  1190. '''
  1191. ns_rr = self._create_ns()
  1192. a_rr = self._create_a('192.0.2.1')
  1193. self.conn.reply_data = self.conn.create_response_data(
  1194. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1195. answers=[soa_rrset, ns_rr, a_rr, begin_soa_rrset])
  1196. self.conn._handle_xfrin_responses()
  1197. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1198. self.assertEqual([], self.conn._datasrc_client.diffs)
  1199. check_diffs(self.assertEqual,
  1200. [[('add', ns_rr), ('add', a_rr),
  1201. ('add', begin_soa_rrset)]],
  1202. self.conn._datasrc_client.committed_diffs)
  1203. def test_ixfr_to_axfr_response_extra(self):
  1204. '''Test with an extra RR after the end of AXFR-style IXFR session.
  1205. The session should be rejected, and nothing should be committed.
  1206. '''
  1207. ns_rr = self._create_ns()
  1208. a_rr = self._create_a('192.0.2.1')
  1209. self.conn.reply_data = self.conn.create_response_data(
  1210. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, RRType.IXFR())],
  1211. answers=[soa_rrset, ns_rr, a_rr, soa_rrset, a_rr])
  1212. self.assertRaises(XfrinProtocolError,
  1213. self.conn._handle_xfrin_responses)
  1214. self.assertEqual(type(XfrinAXFREnd()), type(self.conn.get_xfrstate()))
  1215. self.assertEqual([], self.conn._datasrc_client.committed_diffs)
  1216. class TestIXFRSession(TestXfrinConnection):
  1217. '''Tests for a full IXFR session (query and response).
  1218. Detailed corner cases should have been covered in test_create_query()
  1219. and TestIXFRResponse, so we'll only check some typical cases to confirm
  1220. the general logic flow.
  1221. '''
  1222. def setUp(self):
  1223. super().setUp()
  1224. def test_do_xfrin(self):
  1225. def create_ixfr_response():
  1226. self.conn.reply_data = self.conn.create_response_data(
  1227. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  1228. RRType.IXFR())],
  1229. answers=[soa_rrset, begin_soa_rrset, soa_rrset, soa_rrset])
  1230. self.conn.response_generator = create_ixfr_response
  1231. self.assertEqual(XFRIN_OK, self.conn.do_xfrin(False, RRType.IXFR()))
  1232. # Check some details of the IXFR protocol processing
  1233. self.assertEqual(type(XfrinIXFREnd()), type(self.conn.get_xfrstate()))
  1234. check_diffs(self.assertEqual,
  1235. [[('delete', begin_soa_rrset), ('add', soa_rrset)]],
  1236. self.conn._datasrc_client.committed_diffs)
  1237. # Check if the query was IXFR.
  1238. qdata = self.conn.query_data[2:]
  1239. qmsg = Message(Message.PARSE)
  1240. qmsg.from_wire(qdata, len(qdata))
  1241. self.assertEqual(1, qmsg.get_rr_count(Message.SECTION_QUESTION))
  1242. self.assertEqual(TEST_ZONE_NAME, qmsg.get_question()[0].get_name())
  1243. self.assertEqual(RRType.IXFR(), qmsg.get_question()[0].get_type())
  1244. def test_do_xfrin_fail(self):
  1245. '''IXFR fails due to a protocol error.
  1246. '''
  1247. def create_ixfr_response():
  1248. self.conn.reply_data = self.conn.create_response_data(
  1249. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  1250. RRType.IXFR())],
  1251. answers=[soa_rrset, begin_soa_rrset, soa_rrset,
  1252. self._create_soa('1235')])
  1253. self.conn.response_generator = create_ixfr_response
  1254. self.assertEqual(XFRIN_FAIL, self.conn.do_xfrin(False, RRType.IXFR()))
  1255. def test_do_xfrin_fail(self):
  1256. '''IXFR fails due to a bogus DNS message.
  1257. '''
  1258. self._create_broken_response_data()
  1259. self.assertEqual(XFRIN_FAIL, self.conn.do_xfrin(False, RRType.IXFR()))
  1260. class TestXFRSessionWithSQLite3(TestXfrinConnection):
  1261. '''Tests for XFR sessions using an SQLite3 DB.
  1262. These are provided mainly to confirm the implementation actually works
  1263. in an environment closer to actual operational environments. So we
  1264. only check a few common cases; other details are tested using mock
  1265. data sources.
  1266. '''
  1267. def setUp(self):
  1268. self.sqlite3db_src = TESTDATA_SRCDIR + '/example.com.sqlite3'
  1269. self.sqlite3db_obj = TESTDATA_OBJDIR + '/example.com.sqlite3.copy'
  1270. self.empty_sqlite3db_obj = TESTDATA_OBJDIR + '/empty.sqlite3'
  1271. self.sqlite3db_cfg = "{ \"database_file\": \"" +\
  1272. self.sqlite3db_obj + "\"}"
  1273. super().setUp()
  1274. if os.path.exists(self.sqlite3db_obj):
  1275. os.unlink(self.sqlite3db_obj)
  1276. if os.path.exists(self.empty_sqlite3db_obj):
  1277. os.unlink(self.empty_sqlite3db_obj)
  1278. shutil.copyfile(self.sqlite3db_src, self.sqlite3db_obj)
  1279. self.conn._datasrc_client = DataSourceClient("sqlite3",
  1280. self.sqlite3db_cfg)
  1281. def tearDown(self):
  1282. if os.path.exists(self.sqlite3db_obj):
  1283. os.unlink(self.sqlite3db_obj)
  1284. if os.path.exists(self.empty_sqlite3db_obj):
  1285. os.unlink(self.empty_sqlite3db_obj)
  1286. def get_zone_serial(self):
  1287. result, finder = self.conn._datasrc_client.find_zone(TEST_ZONE_NAME)
  1288. self.assertEqual(DataSourceClient.SUCCESS, result)
  1289. result, soa = finder.find(TEST_ZONE_NAME, RRType.SOA(),
  1290. None, ZoneFinder.FIND_DEFAULT)
  1291. self.assertEqual(ZoneFinder.SUCCESS, result)
  1292. self.assertEqual(1, soa.get_rdata_count())
  1293. return get_soa_serial(soa.get_rdata()[0])
  1294. def record_exist(self, name, type):
  1295. result, finder = self.conn._datasrc_client.find_zone(TEST_ZONE_NAME)
  1296. self.assertEqual(DataSourceClient.SUCCESS, result)
  1297. result, soa = finder.find(name, type, None, ZoneFinder.FIND_DEFAULT)
  1298. return result == ZoneFinder.SUCCESS
  1299. def test_do_ixfrin_sqlite3(self):
  1300. def create_ixfr_response():
  1301. self.conn.reply_data = self.conn.create_response_data(
  1302. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  1303. RRType.IXFR())],
  1304. answers=[soa_rrset, begin_soa_rrset, soa_rrset, soa_rrset])
  1305. self.conn.response_generator = create_ixfr_response
  1306. # Confirm xfrin succeeds and SOA is updated
  1307. self.assertEqual(1230, self.get_zone_serial())
  1308. self.assertEqual(XFRIN_OK, self.conn.do_xfrin(False, RRType.IXFR()))
  1309. self.assertEqual(1234, self.get_zone_serial())
  1310. def test_do_ixfrin_sqlite3_fail(self):
  1311. '''Similar to the previous test, but xfrin fails due to error.
  1312. Check the DB is not changed.
  1313. '''
  1314. def create_ixfr_response():
  1315. self.conn.reply_data = self.conn.create_response_data(
  1316. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  1317. RRType.IXFR())],
  1318. answers=[soa_rrset, begin_soa_rrset, soa_rrset,
  1319. self._create_soa('1235')])
  1320. self.conn.response_generator = create_ixfr_response
  1321. self.assertEqual(1230, self.get_zone_serial())
  1322. self.assertEqual(XFRIN_FAIL, self.conn.do_xfrin(False, RRType.IXFR()))
  1323. self.assertEqual(1230, self.get_zone_serial())
  1324. def test_do_ixfrin_nozone_sqlite3(self):
  1325. self.conn._zone_name = Name('nosuchzone.example')
  1326. self.assertEqual(XFRIN_FAIL, self.conn.do_xfrin(False, RRType.IXFR()))
  1327. # This should fail even before starting state transition
  1328. self.assertEqual(None, self.conn.get_xfrstate())
  1329. def axfr_check(self, type):
  1330. '''Common checks for AXFR and AXFR-style IXFR
  1331. '''
  1332. def create_response():
  1333. self.conn.reply_data = self.conn.create_response_data(
  1334. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, type)],
  1335. answers=[soa_rrset, self._create_ns(), soa_rrset])
  1336. self.conn.response_generator = create_response
  1337. # Confirm xfrin succeeds and SOA is updated, A RR is deleted.
  1338. self.assertEqual(1230, self.get_zone_serial())
  1339. self.assertTrue(self.record_exist(Name('dns01.example.com'),
  1340. RRType.A()))
  1341. self.assertEqual(XFRIN_OK, self.conn.do_xfrin(False, type))
  1342. self.assertEqual(1234, self.get_zone_serial())
  1343. self.assertFalse(self.record_exist(Name('dns01.example.com'),
  1344. RRType.A()))
  1345. def test_do_ixfrin_axfr_sqlite3(self):
  1346. '''AXFR-style IXFR.
  1347. '''
  1348. self.axfr_check(RRType.IXFR())
  1349. def test_do_axfrin_sqlite3(self):
  1350. '''AXFR.
  1351. '''
  1352. self.axfr_check(RRType.AXFR())
  1353. def axfr_failure_check(self, type):
  1354. '''Similar to the previous two tests, but xfrin fails due to error.
  1355. Check the DB is not changed.
  1356. '''
  1357. def create_response():
  1358. self.conn.reply_data = self.conn.create_response_data(
  1359. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS, type)],
  1360. answers=[soa_rrset, self._create_ns(), soa_rrset, soa_rrset])
  1361. self.conn.response_generator = create_response
  1362. self.assertEqual(1230, self.get_zone_serial())
  1363. self.assertTrue(self.record_exist(Name('dns01.example.com'),
  1364. RRType.A()))
  1365. self.assertEqual(XFRIN_FAIL, self.conn.do_xfrin(False, type))
  1366. self.assertEqual(1230, self.get_zone_serial())
  1367. self.assertTrue(self.record_exist(Name('dns01.example.com'),
  1368. RRType.A()))
  1369. def test_do_xfrin_axfr_sqlite3_fail(self):
  1370. '''Failure case for AXFR-style IXFR.
  1371. '''
  1372. self.axfr_failure_check(RRType.IXFR())
  1373. def test_do_axfrin_sqlite3_fail(self):
  1374. '''Failure case for AXFR.
  1375. '''
  1376. self.axfr_failure_check(RRType.AXFR())
  1377. def test_do_axfrin_nozone_sqlite3(self):
  1378. '''AXFR test with an empty SQLite3 DB file, thus no target zone there.
  1379. For now, we provide backward compatible behavior: xfrin will create
  1380. the zone (after even setting up the entire schema) in the zone.
  1381. Note: a future version of this test will make it fail.
  1382. '''
  1383. self.conn._db_file = self.empty_sqlite3db_obj
  1384. self.conn._datasrc_client = DataSourceClient(
  1385. "sqlite3",
  1386. "{ \"database_file\": \"" + self.empty_sqlite3db_obj + "\"}")
  1387. def create_response():
  1388. self.conn.reply_data = self.conn.create_response_data(
  1389. questions=[Question(TEST_ZONE_NAME, TEST_RRCLASS,
  1390. RRType.AXFR())],
  1391. answers=[soa_rrset, self._create_ns(), soa_rrset])
  1392. self.conn.response_generator = create_response
  1393. self.conn._zone_name = Name('example.com')
  1394. self.assertEqual(XFRIN_OK, self.conn.do_xfrin(False, RRType.AXFR()))
  1395. self.assertEqual(type(XfrinAXFREnd()),
  1396. type(self.conn.get_xfrstate()))
  1397. self.assertEqual(1234, self.get_zone_serial())
  1398. self.assertFalse(self.record_exist(Name('dns01.example.com'),
  1399. RRType.A()))
  1400. class TestXfrinRecorder(unittest.TestCase):
  1401. def setUp(self):
  1402. self.recorder = XfrinRecorder()
  1403. def test_increment(self):
  1404. self.assertEqual(self.recorder.count(), 0)
  1405. self.recorder.increment(TEST_ZONE_NAME)
  1406. self.assertEqual(self.recorder.count(), 1)
  1407. # duplicate "increment" should probably be rejected. but it's not
  1408. # checked at this moment
  1409. self.recorder.increment(TEST_ZONE_NAME)
  1410. self.assertEqual(self.recorder.count(), 2)
  1411. def test_decrement(self):
  1412. self.assertEqual(self.recorder.count(), 0)
  1413. self.recorder.increment(TEST_ZONE_NAME)
  1414. self.assertEqual(self.recorder.count(), 1)
  1415. self.recorder.decrement(TEST_ZONE_NAME)
  1416. self.assertEqual(self.recorder.count(), 0)
  1417. def test_decrement_from_empty(self):
  1418. self.assertEqual(self.recorder.count(), 0)
  1419. self.recorder.decrement(TEST_ZONE_NAME)
  1420. self.assertEqual(self.recorder.count(), 0)
  1421. def test_inprogress(self):
  1422. self.assertEqual(self.recorder.count(), 0)
  1423. self.recorder.increment(TEST_ZONE_NAME)
  1424. self.assertEqual(self.recorder.xfrin_in_progress(TEST_ZONE_NAME), True)
  1425. self.recorder.decrement(TEST_ZONE_NAME)
  1426. self.assertEqual(self.recorder.xfrin_in_progress(TEST_ZONE_NAME), False)
  1427. class TestXfrin(unittest.TestCase):
  1428. def setUp(self):
  1429. # redirect output
  1430. self.stderr_backup = sys.stderr
  1431. sys.stderr = open(os.devnull, 'w')
  1432. self.xfr = MockXfrin()
  1433. self.args = {}
  1434. self.args['zone_name'] = TEST_ZONE_NAME_STR
  1435. self.args['class'] = TEST_RRCLASS_STR
  1436. self.args['port'] = TEST_MASTER_PORT
  1437. self.args['master'] = TEST_MASTER_IPV4_ADDRESS
  1438. self.args['db_file'] = TEST_DB_FILE
  1439. self.args['tsig_key'] = ''
  1440. def tearDown(self):
  1441. self.xfr.shutdown()
  1442. sys.stderr= self.stderr_backup
  1443. def _do_parse_zone_name_class(self):
  1444. return self.xfr._parse_zone_name_and_class(self.args)
  1445. def _do_parse_master_port(self):
  1446. name, rrclass = self._do_parse_zone_name_class()
  1447. return self.xfr._parse_master_and_port(self.args, name, rrclass)
  1448. def test_parse_cmd_params(self):
  1449. name, rrclass = self._do_parse_zone_name_class()
  1450. master_addrinfo = self._do_parse_master_port()
  1451. db_file = self.args.get('db_file')
  1452. self.assertEqual(master_addrinfo[2][1], int(TEST_MASTER_PORT))
  1453. self.assertEqual(name, TEST_ZONE_NAME)
  1454. self.assertEqual(rrclass, TEST_RRCLASS)
  1455. self.assertEqual(master_addrinfo[2][0], TEST_MASTER_IPV4_ADDRESS)
  1456. self.assertEqual(db_file, TEST_DB_FILE)
  1457. def test_parse_cmd_params_default_port(self):
  1458. del self.args['port']
  1459. master_addrinfo = self._do_parse_master_port()
  1460. self.assertEqual(master_addrinfo[2][1], 53)
  1461. def test_parse_cmd_params_ip6master(self):
  1462. self.args['master'] = TEST_MASTER_IPV6_ADDRESS
  1463. master_addrinfo = self._do_parse_master_port()
  1464. self.assertEqual(master_addrinfo[2][0], TEST_MASTER_IPV6_ADDRESS)
  1465. def test_parse_cmd_params_chclass(self):
  1466. self.args['zone_class'] = 'CH'
  1467. self.assertEqual(self._do_parse_zone_name_class()[1], RRClass.CH())
  1468. def test_parse_cmd_params_bogusclass(self):
  1469. self.args['zone_class'] = 'XXX'
  1470. self.assertRaises(XfrinZoneInfoException, self._do_parse_zone_name_class)
  1471. def test_parse_cmd_params_nozone(self):
  1472. # zone name is mandatory.
  1473. del self.args['zone_name']
  1474. self.assertRaises(XfrinException, self._do_parse_zone_name_class)
  1475. def test_parse_cmd_params_nomaster(self):
  1476. # master address is mandatory.
  1477. del self.args['master']
  1478. self.assertRaises(XfrinException, self._do_parse_master_port)
  1479. def test_parse_cmd_params_bad_ip4(self):
  1480. self.args['master'] = '3.3.3.3.3'
  1481. self.assertRaises(XfrinException, self._do_parse_master_port)
  1482. def test_parse_cmd_params_bad_ip6(self):
  1483. self.args['master'] = '1::1::1'
  1484. self.assertRaises(XfrinException, self._do_parse_master_port)
  1485. def test_parse_cmd_params_bad_port(self):
  1486. self.args['port'] = '-1'
  1487. self.assertRaises(XfrinException, self._do_parse_master_port)
  1488. self.args['port'] = '65536'
  1489. self.assertRaises(XfrinException, self._do_parse_master_port)
  1490. self.args['port'] = 'http'
  1491. self.assertRaises(XfrinException, self._do_parse_master_port)
  1492. def test_command_handler_shutdown(self):
  1493. self.assertEqual(self.xfr.command_handler("shutdown",
  1494. None)['result'][0], 0)
  1495. # shutdown command doesn't expect an argument, but accepts it if any.
  1496. self.assertEqual(self.xfr.command_handler("shutdown",
  1497. "unused")['result'][0], 0)
  1498. def test_command_handler_retransfer(self):
  1499. self.assertEqual(self.xfr.command_handler("retransfer",
  1500. self.args)['result'][0], 0)
  1501. self.assertEqual(self.args['master'], self.xfr.xfrin_started_master_addr)
  1502. self.assertEqual(int(self.args['port']), self.xfr.xfrin_started_master_port)
  1503. # By default we use AXFR (for now)
  1504. self.assertEqual(RRType.AXFR(), self.xfr.xfrin_started_request_type)
  1505. def test_command_handler_retransfer_short_command1(self):
  1506. # try it when only specifying the zone name (of unknown zone)
  1507. # this should fail because master address is not specified.
  1508. short_args = {}
  1509. short_args['zone_name'] = TEST_ZONE_NAME_STR
  1510. self.assertEqual(self.xfr.command_handler("retransfer",
  1511. short_args)['result'][0], 1)
  1512. def test_command_handler_retransfer_short_command2(self):
  1513. # try it when only specifying the zone name (of known zone)
  1514. short_args = {}
  1515. short_args['zone_name'] = TEST_ZONE_NAME_STR
  1516. zones = { 'zones': [
  1517. { 'name': TEST_ZONE_NAME_STR,
  1518. 'master_addr': TEST_MASTER_IPV4_ADDRESS,
  1519. 'master_port': TEST_MASTER_PORT
  1520. }
  1521. ]}
  1522. self.xfr.config_handler(zones)
  1523. self.assertEqual(self.xfr.command_handler("retransfer",
  1524. short_args)['result'][0], 0)
  1525. self.assertEqual(TEST_MASTER_IPV4_ADDRESS,
  1526. self.xfr.xfrin_started_master_addr)
  1527. self.assertEqual(int(TEST_MASTER_PORT),
  1528. self.xfr.xfrin_started_master_port)
  1529. def test_command_handler_retransfer_short_command3(self):
  1530. # try it when only specifying the zone name (of known zone)
  1531. short_args = {}
  1532. # test it without the trailing root dot
  1533. short_args['zone_name'] = TEST_ZONE_NAME_STR[:-1]
  1534. zones = { 'zones': [
  1535. { 'name': TEST_ZONE_NAME_STR,
  1536. 'master_addr': TEST_MASTER_IPV4_ADDRESS,
  1537. 'master_port': TEST_MASTER_PORT
  1538. }
  1539. ]}
  1540. self.xfr.config_handler(zones)
  1541. self.assertEqual(self.xfr.command_handler("retransfer",
  1542. short_args)['result'][0], 0)
  1543. self.assertEqual(TEST_MASTER_IPV4_ADDRESS,
  1544. self.xfr.xfrin_started_master_addr)
  1545. self.assertEqual(int(TEST_MASTER_PORT),
  1546. self.xfr.xfrin_started_master_port)
  1547. def test_command_handler_retransfer_short_command4(self):
  1548. # try it when only specifying the zone name (of known zone, with
  1549. # different case)
  1550. short_args = {}
  1551. # swap the case of the zone name in our command
  1552. short_args['zone_name'] = TEST_ZONE_NAME_STR.swapcase()
  1553. zones = { 'zones': [
  1554. { 'name': TEST_ZONE_NAME_STR,
  1555. 'master_addr': TEST_MASTER_IPV4_ADDRESS,
  1556. 'master_port': TEST_MASTER_PORT
  1557. }
  1558. ]}
  1559. self.xfr.config_handler(zones)
  1560. self.assertEqual(self.xfr.command_handler("retransfer",
  1561. short_args)['result'][0], 0)
  1562. self.assertEqual(TEST_MASTER_IPV4_ADDRESS,
  1563. self.xfr.xfrin_started_master_addr)
  1564. self.assertEqual(int(TEST_MASTER_PORT),
  1565. self.xfr.xfrin_started_master_port)
  1566. def test_command_handler_retransfer_badcommand(self):
  1567. self.args['master'] = 'invalid'
  1568. self.assertEqual(self.xfr.command_handler("retransfer",
  1569. self.args)['result'][0], 1)
  1570. def test_command_handler_retransfer_quota(self):
  1571. self.args['master'] = TEST_MASTER_IPV4_ADDRESS
  1572. for i in range(self.xfr._max_transfers_in - 1):
  1573. self.xfr.recorder.increment(Name(str(i) + TEST_ZONE_NAME_STR))
  1574. # there can be one more outstanding transfer.
  1575. self.assertEqual(self.xfr.command_handler("retransfer",
  1576. self.args)['result'][0], 0)
  1577. # make sure the # xfrs would excceed the quota
  1578. self.xfr.recorder.increment(Name(str(self.xfr._max_transfers_in) + TEST_ZONE_NAME_STR))
  1579. # this one should fail
  1580. self.assertEqual(self.xfr.command_handler("retransfer",
  1581. self.args)['result'][0], 1)
  1582. def test_command_handler_retransfer_inprogress(self):
  1583. self.xfr.recorder.increment(TEST_ZONE_NAME)
  1584. self.assertEqual(self.xfr.command_handler("retransfer",
  1585. self.args)['result'][0], 1)
  1586. def test_command_handler_retransfer_nomodule(self):
  1587. dns_module = sys.modules['pydnspp'] # this must exist
  1588. del sys.modules['pydnspp']
  1589. self.assertEqual(self.xfr.command_handler("retransfer",
  1590. self.args)['result'][0], 1)
  1591. # sys.modules is global, so we must recover it
  1592. sys.modules['pydnspp'] = dns_module
  1593. def test_command_handler_refresh(self):
  1594. # at this level, refresh is no different than retransfer.
  1595. # just confirm the successful case with a different family of address.
  1596. self.args['master'] = TEST_MASTER_IPV6_ADDRESS
  1597. self.assertEqual(self.xfr.command_handler("refresh",
  1598. self.args)['result'][0], 0)
  1599. self.assertEqual(TEST_MASTER_IPV6_ADDRESS,
  1600. self.xfr.xfrin_started_master_addr)
  1601. self.assertEqual(int(TEST_MASTER_PORT),
  1602. self.xfr.xfrin_started_master_port)
  1603. # By default we use AXFR (for now)
  1604. self.assertEqual(RRType.AXFR(), self.xfr.xfrin_started_request_type)
  1605. def test_command_handler_notify(self):
  1606. # at this level, refresh is no different than retransfer.
  1607. self.args['master'] = TEST_MASTER_IPV6_ADDRESS
  1608. # ...but the zone is unknown so this would return an error
  1609. self.assertEqual(self.xfr.command_handler("notify",
  1610. self.args)['result'][0], 1)
  1611. def test_command_handler_notify_known_zone_bad_addr(self):
  1612. # try it with a known zone
  1613. self.args['master'] = TEST_MASTER_IPV6_ADDRESS
  1614. # but use a different address in the actual command
  1615. zones = { 'zones': [
  1616. { 'name': TEST_ZONE_NAME_STR,
  1617. 'master_addr': TEST_MASTER_IPV4_ADDRESS,
  1618. 'master_port': TEST_MASTER_PORT
  1619. }
  1620. ]}
  1621. self.xfr.config_handler(zones)
  1622. # the command should now fail
  1623. self.assertEqual(self.xfr.command_handler("notify",
  1624. self.args)['result'][0], 1)
  1625. def test_command_handler_notify_known_zone(self):
  1626. # try it with a known zone
  1627. self.args['master'] = TEST_MASTER_IPV6_ADDRESS
  1628. # with a zone configuration that has a matching master address.
  1629. zones = { 'zones': [
  1630. { 'name': TEST_ZONE_NAME_STR,
  1631. 'master_addr': TEST_MASTER_IPV6_ADDRESS,
  1632. 'master_port': TEST_MASTER_PORT
  1633. }
  1634. ]}
  1635. self.xfr.config_handler(zones)
  1636. self.assertEqual(self.xfr.command_handler("notify",
  1637. self.args)['result'][0], 0)
  1638. def test_command_handler_unknown(self):
  1639. self.assertEqual(self.xfr.command_handler("xxx", None)['result'][0], 1)
  1640. def test_command_handler_transfers_in(self):
  1641. self.assertEqual(self.xfr.config_handler({})['result'][0], 0)
  1642. self.assertEqual(self.xfr.config_handler({'transfers_in': 3})['result'][0], 0)
  1643. self.assertEqual(self.xfr._max_transfers_in, 3)
  1644. def _check_zones_config(self, config_given):
  1645. if 'transfers_in' in config_given:
  1646. self.assertEqual(config_given['transfers_in'],
  1647. self.xfr._max_transfers_in)
  1648. for zone_config in config_given['zones']:
  1649. zone_name = zone_config['name']
  1650. zone_info = self.xfr._get_zone_info(Name(zone_name), RRClass.IN())
  1651. self.assertEqual(str(zone_info.master_addr), zone_config['master_addr'])
  1652. self.assertEqual(zone_info.master_port, zone_config['master_port'])
  1653. if 'tsig_key' in zone_config:
  1654. self.assertEqual(zone_info.tsig_key.to_text(), TSIGKey(zone_config['tsig_key']).to_text())
  1655. else:
  1656. self.assertIsNone(zone_info.tsig_key)
  1657. if 'use_ixfr' in zone_config and\
  1658. zone_config.get('use_ixfr'):
  1659. self.assertTrue(zone_info.use_ixfr)
  1660. else:
  1661. # if not set, should default to False
  1662. self.assertFalse(zone_info.use_ixfr)
  1663. def test_config_handler_zones(self):
  1664. # This test passes a number of good and bad configs, and checks whether
  1665. # the values are reflected in the structure that will dictate the
  1666. # actual behaviour. It also checks if bad values are correctly
  1667. # handled
  1668. config1 = { 'transfers_in': 3,
  1669. 'zones': [
  1670. { 'name': 'test.example.',
  1671. 'master_addr': '192.0.2.1',
  1672. 'master_port': 53,
  1673. 'use_ixfr': False
  1674. }
  1675. ]}
  1676. self.assertEqual(self.xfr.config_handler(config1)['result'][0], 0)
  1677. self._check_zones_config(config1)
  1678. config2 = { 'transfers_in': 4,
  1679. 'zones': [
  1680. { 'name': 'test.example.',
  1681. 'master_addr': '192.0.2.2',
  1682. 'master_port': 53,
  1683. 'tsig_key': "example.com:SFuWd/q99SzF8Yzd1QbB9g==",
  1684. 'use_ixfr': True
  1685. }
  1686. ]}
  1687. self.assertEqual(self.xfr.config_handler(config2)['result'][0], 0)
  1688. self._check_zones_config(config2)
  1689. # test that configuring the zone multiple times fails
  1690. zones = { 'transfers_in': 5,
  1691. 'zones': [
  1692. { 'name': 'test.example.',
  1693. 'master_addr': '192.0.2.1',
  1694. 'master_port': 53
  1695. },
  1696. { 'name': 'test.example.',
  1697. 'master_addr': '192.0.2.2',
  1698. 'master_port': 53
  1699. }
  1700. ]}
  1701. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  1702. # since this has failed, we should still have the previous config
  1703. self._check_zones_config(config2)
  1704. zones = { 'zones': [
  1705. { 'name': 'test.example.',
  1706. 'master_addr': '192.0.2.3',
  1707. 'master_port': 53,
  1708. 'class': 'BADCLASS'
  1709. }
  1710. ]}
  1711. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  1712. self._check_zones_config(config2)
  1713. zones = { 'zones': [
  1714. { 'master_addr': '192.0.2.4',
  1715. 'master_port': 53
  1716. }
  1717. ]}
  1718. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  1719. # since this has failed, we should still have the previous config
  1720. self._check_zones_config(config2)
  1721. zones = { 'zones': [
  1722. { 'name': 'bad..zone.',
  1723. 'master_addr': '192.0.2.5',
  1724. 'master_port': 53
  1725. }
  1726. ]}
  1727. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  1728. # since this has failed, we should still have the previous config
  1729. self._check_zones_config(config2)
  1730. zones = { 'zones': [
  1731. { 'name': '',
  1732. 'master_addr': '192.0.2.6',
  1733. 'master_port': 53
  1734. }
  1735. ]}
  1736. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  1737. # since this has failed, we should still have the previous config
  1738. self._check_zones_config(config2)
  1739. zones = { 'zones': [
  1740. { 'name': 'test.example',
  1741. 'master_addr': 'badaddress',
  1742. 'master_port': 53
  1743. }
  1744. ]}
  1745. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  1746. # since this has failed, we should still have the previous config
  1747. self._check_zones_config(config2)
  1748. zones = { 'zones': [
  1749. { 'name': 'test.example',
  1750. 'master_addr': '192.0.2.7',
  1751. 'master_port': 'bad_port'
  1752. }
  1753. ]}
  1754. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  1755. # since this has failed, we should still have the previous config
  1756. self._check_zones_config(config2)
  1757. zones = { 'zones': [
  1758. { 'name': 'test.example',
  1759. 'master_addr': '192.0.2.7',
  1760. 'master_port': 53,
  1761. # using a bad TSIG key spec
  1762. 'tsig_key': "bad..example.com:SFuWd/q99SzF8Yzd1QbB9g=="
  1763. }
  1764. ]}
  1765. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  1766. # since this has failed, we should still have the previous config
  1767. self._check_zones_config(config2)
  1768. # let's also add a zone that is correct too, and make sure
  1769. # that the new config is not partially taken
  1770. zones = { 'zones': [
  1771. { 'name': 'test.example.',
  1772. 'master_addr': '192.0.2.8',
  1773. 'master_port': 53
  1774. },
  1775. { 'name': 'test2.example.',
  1776. 'master_addr': '192.0.2.9',
  1777. 'master_port': 53,
  1778. 'tsig_key': 'badkey'
  1779. }
  1780. ]}
  1781. self.assertEqual(self.xfr.config_handler(zones)['result'][0], 1)
  1782. # since this has failed, we should still have the previous config
  1783. self._check_zones_config(config2)
  1784. def common_ixfr_setup(self, xfr_mode, use_ixfr):
  1785. # This helper method explicitly sets up a zone configuration with
  1786. # use_ixfr, and invokes either retransfer or refresh.
  1787. # Shared by some of the following test cases.
  1788. config = {'zones': [
  1789. {'name': 'example.com.',
  1790. 'master_addr': '192.0.2.1',
  1791. 'use_ixfr': use_ixfr}]}
  1792. self.assertEqual(self.xfr.config_handler(config)['result'][0], 0)
  1793. self.assertEqual(self.xfr.command_handler(xfr_mode,
  1794. self.args)['result'][0], 0)
  1795. def test_command_handler_retransfer_ixfr_enabled(self):
  1796. # If IXFR is explicitly enabled in config, IXFR will be used
  1797. self.common_ixfr_setup('retransfer', True)
  1798. self.assertEqual(RRType.IXFR(), self.xfr.xfrin_started_request_type)
  1799. def test_command_handler_refresh_ixfr_enabled(self):
  1800. # Same for refresh
  1801. self.common_ixfr_setup('refresh', True)
  1802. self.assertEqual(RRType.IXFR(), self.xfr.xfrin_started_request_type)
  1803. def test_command_handler_retransfer_ixfr_disabled(self):
  1804. # Similar to the previous case, but explicitly disabled. AXFR should
  1805. # be used.
  1806. self.common_ixfr_setup('retransfer', False)
  1807. self.assertEqual(RRType.AXFR(), self.xfr.xfrin_started_request_type)
  1808. def test_command_handler_refresh_ixfr_disabled(self):
  1809. # Same for refresh
  1810. self.common_ixfr_setup('refresh', False)
  1811. self.assertEqual(RRType.AXFR(), self.xfr.xfrin_started_request_type)
  1812. def raise_interrupt():
  1813. raise KeyboardInterrupt()
  1814. def raise_ccerror():
  1815. raise isc.cc.session.SessionError('test error')
  1816. def raise_exception():
  1817. raise Exception('test exception')
  1818. class TestMain(unittest.TestCase):
  1819. def setUp(self):
  1820. MockXfrin.check_command_hook = None
  1821. def tearDown(self):
  1822. MockXfrin.check_command_hook = None
  1823. def test_startup(self):
  1824. main(MockXfrin, False)
  1825. def test_startup_interrupt(self):
  1826. MockXfrin.check_command_hook = raise_interrupt
  1827. main(MockXfrin, False)
  1828. def test_startup_ccerror(self):
  1829. MockXfrin.check_command_hook = raise_ccerror
  1830. main(MockXfrin, False)
  1831. def test_startup_generalerror(self):
  1832. MockXfrin.check_command_hook = raise_exception
  1833. main(MockXfrin, False)
  1834. if __name__== "__main__":
  1835. try:
  1836. isc.log.resetUnitTestRootLogger()
  1837. unittest.main()
  1838. except KeyboardInterrupt as e:
  1839. print(e)