xfrin_test.py 106 KB

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