xfrin_test.py 118 KB

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