xfrin_test.py 99 KB

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