xfrin_test.py 148 KB

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