xfrout_test.py.in 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745
  1. # Copyright (C) 2010-2012 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. '''Tests for the XfroutSession and UnixSockServer classes '''
  16. import unittest
  17. import os
  18. from isc.testutils.tsigctx_mock import MockTSIGContext
  19. from isc.testutils.ccsession_mock import MockModuleCCSession
  20. from isc.cc.session import *
  21. import isc.config
  22. from isc.dns import *
  23. from isc.testutils.rrset_utils import *
  24. from xfrout import *
  25. import xfrout
  26. import isc.log
  27. import isc.acl.dns
  28. import isc.server_common.tsig_keyring
  29. TESTDATA_SRCDIR = os.getenv("TESTDATASRCDIR")
  30. TSIG_KEY = TSIGKey("example.com:SFuWd/q99SzF8Yzd1QbB9g==")
  31. #
  32. # Commonly used (mostly constant) test parameters
  33. #
  34. TEST_ZONE_NAME_STR = "example.com."
  35. TEST_ZONE_NAME = Name(TEST_ZONE_NAME_STR)
  36. TEST_RRCLASS = RRClass.IN()
  37. IXFR_OK_VERSION = 2011111802
  38. IXFR_NG_VERSION = 2011111803
  39. SOA_CURRENT_VERSION = 2011112001
  40. # our fake socket, where we can read and insert messages
  41. class MySocket():
  42. def __init__(self, family, type):
  43. self.family = family
  44. self.type = type
  45. self.sendqueue = bytearray()
  46. def connect(self, to):
  47. pass
  48. def close(self):
  49. pass
  50. def send(self, data):
  51. self.sendqueue.extend(data);
  52. return len(data)
  53. def fileno(self):
  54. return 42 # simply return a constant dummy value
  55. def readsent(self):
  56. if len(self.sendqueue) >= 2:
  57. size = 2 + struct.unpack("!H", self.sendqueue[:2])[0]
  58. else:
  59. size = 0
  60. result = self.sendqueue[:size]
  61. self.sendqueue = self.sendqueue[size:]
  62. return result
  63. def read_msg(self, parse_options=Message.PARSE_DEFAULT, need_len=False):
  64. sent_data = self.readsent()
  65. get_msg = Message(Message.PARSE)
  66. get_msg.from_wire(bytes(sent_data[2:]), parse_options)
  67. if need_len:
  68. return (get_msg, len(sent_data) - 2)
  69. return get_msg
  70. def clear_send(self):
  71. del self.sendqueue[:]
  72. class MockDataSrcClient:
  73. def __init__(self, type, config):
  74. pass
  75. def find_zone(self, zone_name):
  76. '''Mock version of find_zone().
  77. It returns itself (subsequently acting as a mock ZoneFinder) for
  78. some test zone names. For a special name it returns NOTFOUND to
  79. emulate the condition where the specified zone doen't exist.
  80. '''
  81. self._zone_name = zone_name
  82. if zone_name == Name('notauth.example.com'):
  83. return (isc.datasrc.DataSourceClient.NOTFOUND, None)
  84. return (isc.datasrc.DataSourceClient.SUCCESS, self)
  85. def find(self, name, rrtype, options=ZoneFinder.FIND_DEFAULT):
  86. '''Mock ZoneFinder.find().
  87. (At the moment) this method only handles query for type SOA.
  88. By default it returns a normal SOA RR(set) whose owner name is
  89. the query name It also emulates some unusual cases for special
  90. zone names.
  91. '''
  92. if name == Name('nosoa.example.com') and rrtype == RRType.SOA():
  93. return (ZoneFinder.NXDOMAIN, None, 0)
  94. elif name == Name('multisoa.example.com') and rrtype == RRType.SOA():
  95. soa_rrset = create_soa(SOA_CURRENT_VERSION)
  96. soa_rrset.add_rdata(soa_rrset.get_rdata()[0])
  97. return (ZoneFinder.SUCCESS, soa_rrset, 0)
  98. elif name == Name('maxserial.example.com'):
  99. soa_rrset = create_soa(0xffffffff)
  100. return (ZoneFinder.SUCCESS, soa_rrset, 0)
  101. elif rrtype == RRType.SOA():
  102. return (ZoneFinder.SUCCESS, create_soa(SOA_CURRENT_VERSION), 0)
  103. raise ValueError('Unexpected input to mock finder: bug in test case?')
  104. def get_iterator(self, zone_name, adjust_ttl=False):
  105. if zone_name == Name('notauth.example.com'):
  106. raise isc.datasrc.Error('no such zone')
  107. self._zone_name = zone_name
  108. return self
  109. def get_soa(self): # emulate ZoneIterator.get_soa()
  110. if self._zone_name == Name('nosoa.example.com'):
  111. return None
  112. soa_rrset = create_soa(SOA_CURRENT_VERSION)
  113. if self._zone_name == Name('multisoa.example.com'):
  114. soa_rrset.add_rdata(soa_rrset.get_rdata()[0])
  115. return soa_rrset
  116. def get_journal_reader(self, zone_name, begin_serial, end_serial):
  117. if zone_name == Name('notauth2.example.com'):
  118. return isc.datasrc.ZoneJournalReader.NO_SUCH_ZONE, None
  119. if zone_name == Name('nojournal.example.com'):
  120. raise isc.datasrc.NotImplemented('journaling not supported')
  121. if begin_serial == IXFR_NG_VERSION:
  122. return isc.datasrc.ZoneJournalReader.NO_SUCH_VERSION, None
  123. return isc.datasrc.ZoneJournalReader.SUCCESS, self
  124. class MyCCSession(isc.config.ConfigData):
  125. def __init__(self):
  126. module_spec = isc.config.module_spec_from_file(
  127. xfrout.SPECFILE_LOCATION)
  128. ConfigData.__init__(self, module_spec)
  129. def get_remote_config_value(self, module_name, identifier):
  130. if module_name == "Auth" and identifier == "database_file":
  131. return "initdb.file", False
  132. else:
  133. return "unknown", False
  134. # This constant dictionary stores all default configuration parameters
  135. # defined in the xfrout spec file.
  136. DEFAULT_CONFIG = MyCCSession().get_full_config()
  137. # We subclass the Session class we're testing here, only overriding a few
  138. # methods
  139. class MyXfroutSession(XfroutSession):
  140. def _handle(self):
  141. pass
  142. def _close_socket(self):
  143. pass
  144. def _send_data(self, sock, data):
  145. size = len(data)
  146. total_count = 0
  147. while total_count < size:
  148. count = sock.send(data[total_count:])
  149. total_count += count
  150. class Dbserver:
  151. def __init__(self):
  152. self._shutdown_event = threading.Event()
  153. self.transfer_counter = 0
  154. self._max_transfers_out = DEFAULT_CONFIG['transfers_out']
  155. def get_db_file(self):
  156. return 'test.sqlite3'
  157. def increase_transfers_counter(self):
  158. self.transfer_counter += 1
  159. return True
  160. def decrease_transfers_counter(self):
  161. self.transfer_counter -= 1
  162. class TestXfroutSessionBase(unittest.TestCase):
  163. '''Base classs for tests related to xfrout sessions
  164. This class defines common setup/teadown and utility methods. Actual
  165. tests are delegated to subclasses.
  166. '''
  167. def getmsg(self):
  168. msg = Message(Message.PARSE)
  169. msg.from_wire(self.mdata)
  170. return msg
  171. def create_mock_tsig_ctx(self, error):
  172. # This helper function creates a MockTSIGContext for a given key
  173. # and TSIG error to be used as a result of verify (normally faked
  174. # one)
  175. mock_ctx = MockTSIGContext(TSIG_KEY)
  176. mock_ctx.error = error
  177. return mock_ctx
  178. def message_has_tsig(self, msg):
  179. return msg.get_tsig_record() is not None
  180. def create_request_data(self, with_question=True, with_tsig=False,
  181. ixfr=None, qtype=None, zone_name=TEST_ZONE_NAME,
  182. soa_class=TEST_RRCLASS, num_soa=1):
  183. '''Create a commonly used XFR request data.
  184. By default the request type is AXFR; if 'ixfr' is an integer,
  185. the request type will be IXFR and an SOA with the serial being
  186. the value of the parameter will be included in the authority
  187. section.
  188. This method has various minor parameters only for creating bad
  189. format requests for testing purposes:
  190. qtype: the RR type of the question section. By default automatically
  191. determined by the value of ixfr, but could be an invalid type
  192. for testing.
  193. zone_name: the query (zone) name. for IXFR, it's also used as
  194. the owner name of the SOA in the authority section.
  195. soa_class: IXFR only. The RR class of the SOA RR in the authority
  196. section.
  197. num_soa: IXFR only. The number of SOA RDATAs in the authority
  198. section.
  199. '''
  200. msg = Message(Message.RENDER)
  201. query_id = 0x1035
  202. msg.set_qid(query_id)
  203. msg.set_opcode(Opcode.QUERY())
  204. msg.set_rcode(Rcode.NOERROR())
  205. req_type = RRType.AXFR() if ixfr is None else RRType.IXFR()
  206. if with_question:
  207. msg.add_question(Question(zone_name, RRClass.IN(),
  208. req_type if qtype is None else qtype))
  209. if req_type == RRType.IXFR():
  210. soa = RRset(zone_name, soa_class, RRType.SOA(), RRTTL(0))
  211. # In the RDATA only the serial matters.
  212. for i in range(0, num_soa):
  213. soa.add_rdata(Rdata(RRType.SOA(), soa_class,
  214. 'm r ' + str(ixfr) + ' 1 1 1 1'))
  215. msg.add_rrset(Message.SECTION_AUTHORITY, soa)
  216. renderer = MessageRenderer()
  217. if with_tsig:
  218. tsig_ctx = MockTSIGContext(TSIG_KEY)
  219. msg.to_wire(renderer, tsig_ctx)
  220. else:
  221. msg.to_wire(renderer)
  222. request_data = renderer.get_data()
  223. return request_data
  224. def set_request_type(self, type):
  225. self.xfrsess._request_type = type
  226. if type == RRType.AXFR():
  227. self.xfrsess._request_typestr = 'AXFR'
  228. else:
  229. self.xfrsess._request_typestr = 'IXFR'
  230. def setUp(self):
  231. self.sock = MySocket(socket.AF_INET,socket.SOCK_STREAM)
  232. self.setup_counters()
  233. self.xfrsess = MyXfroutSession(self.sock, None, Dbserver(),
  234. TSIGKeyRing(),
  235. (socket.AF_INET, socket.SOCK_STREAM,
  236. ('127.0.0.1', 12345)),
  237. # When not testing ACLs, simply accept
  238. isc.acl.dns.REQUEST_LOADER.load(
  239. [{"action": "ACCEPT"}]),
  240. {},
  241. **self._counters)
  242. self.set_request_type(RRType.AXFR()) # test AXFR by default
  243. self.mdata = self.create_request_data()
  244. self.soa_rrset = create_soa(SOA_CURRENT_VERSION)
  245. # some test replaces a module-wide function. We should ensure the
  246. # original is used elsewhere.
  247. self.orig_get_rrset_len = xfrout.get_rrset_len
  248. def setup_counters(self):
  249. self._statistics_data = {
  250. 'zones' : {
  251. TEST_ZONE_NAME_STR : {
  252. 'xfrrej': 0,
  253. 'xfrreqdone': 0
  254. }
  255. },
  256. 'axfr_started': 0,
  257. 'ixfr_started': 0,
  258. 'axfr_ended': 0,
  259. 'ixfr_ended': 0
  260. }
  261. def _counter_xfrrej(zone_name):
  262. self._statistics_data['zones'][zone_name]['xfrrej'] += 1
  263. def _counter_xfrreqdone(zone_name):
  264. self._statistics_data['zones'][zone_name]['xfrreqdone'] += 1
  265. def _inc_ixfr_running():
  266. self._statistics_data['ixfr_started'] += 1
  267. def _dec_ixfr_running():
  268. self._statistics_data['ixfr_ended'] += 1
  269. def _inc_axfr_running():
  270. self._statistics_data['axfr_started'] += 1
  271. def _dec_axfr_running():
  272. self._statistics_data['axfr_ended'] += 1
  273. self._counters = {
  274. 'counter_xfrrej': _counter_xfrrej,
  275. 'counter_xfrreqdone': _counter_xfrreqdone,
  276. 'inc_ixfr_running': _inc_ixfr_running,
  277. 'dec_ixfr_running': _dec_ixfr_running,
  278. 'inc_axfr_running': _inc_axfr_running,
  279. 'dec_axfr_running': _dec_axfr_running
  280. }
  281. self.get_counter = lambda n: \
  282. self._statistics_data[n] if 'ixfr_' in n or 'axfr_' in n \
  283. else self._statistics_data['zones'][TEST_ZONE_NAME_STR][n]
  284. def tearDown(self):
  285. xfrout.get_rrset_len = self.orig_get_rrset_len
  286. # transfer_counter must be always be reset no matter happens within
  287. # the XfroutSession object. We check the condition here.
  288. self.assertEqual(0, self.xfrsess._server.transfer_counter)
  289. class TestXfroutSession(TestXfroutSessionBase):
  290. def test_quota_error(self):
  291. '''Emulating the server being too busy.
  292. '''
  293. self.xfrsess._request_data = self.mdata
  294. self.xfrsess._server.increase_transfers_counter = lambda : False
  295. XfroutSession._handle(self.xfrsess)
  296. self.assertEqual(self.sock.read_msg().get_rcode(), Rcode.REFUSED())
  297. def test_quota_ok(self):
  298. '''The default case in terms of the xfrout quota.
  299. '''
  300. # set up a bogus request, which should result in FORMERR. (it only
  301. # has to be something that is different from the previous case)
  302. self.xfrsess._request_data = \
  303. self.create_request_data(ixfr=IXFR_OK_VERSION, num_soa=2)
  304. # Replace the data source client to avoid datasrc related exceptions
  305. self.xfrsess.ClientClass = MockDataSrcClient
  306. XfroutSession._handle(self.xfrsess)
  307. self.assertEqual(self.sock.read_msg().get_rcode(), Rcode.FORMERR())
  308. def test_exception_from_session(self):
  309. '''Test the case where the main processing raises an exception.
  310. We just check it doesn't any unexpected disruption and (in tearDown)
  311. transfer_counter is correctly reset to 0.
  312. '''
  313. def dns_xfrout_start(fd, msg, quota):
  314. raise ValueError('fake exception')
  315. self.xfrsess.dns_xfrout_start = dns_xfrout_start
  316. XfroutSession._handle(self.xfrsess)
  317. def test_parse_query_message(self):
  318. # Valid AXFR
  319. [get_rcode, get_msg] = self.xfrsess._parse_query_message(self.mdata)
  320. self.assertEqual(RRType.AXFR(), self.xfrsess._request_type)
  321. self.assertEqual(get_rcode.to_text(), "NOERROR")
  322. # Valid IXFR
  323. request_data = self.create_request_data(ixfr=2011111801)
  324. rcode, msg = self.xfrsess._parse_query_message(request_data)
  325. self.assertEqual(RRType.IXFR(), self.xfrsess._request_type)
  326. self.assertEqual(Rcode.NOERROR(), rcode)
  327. # Broken request: no question
  328. self.assertRaises(RuntimeError, self.xfrsess._parse_query_message,
  329. self.create_request_data(with_question=False))
  330. # Broken request: invalid RR type (neither AXFR nor IXFR)
  331. self.assertRaises(RuntimeError, self.xfrsess._parse_query_message,
  332. self.create_request_data(qtype=RRType.A()))
  333. # NOERROR
  334. request_data = self.create_request_data(ixfr=IXFR_OK_VERSION)
  335. rcode, msg = self.xfrsess._parse_query_message(request_data)
  336. self.assertEqual(rcode.to_text(), "NOERROR")
  337. # tsig signed query message
  338. request_data = self.create_request_data(with_tsig=True)
  339. # BADKEY
  340. [rcode, msg] = self.xfrsess._parse_query_message(request_data)
  341. self.assertEqual(rcode.to_text(), "NOTAUTH")
  342. self.assertTrue(self.xfrsess._tsig_ctx is not None)
  343. # NOERROR
  344. self.assertEqual(TSIGKeyRing.SUCCESS,
  345. self.xfrsess._tsig_key_ring.add(TSIG_KEY))
  346. [rcode, msg] = self.xfrsess._parse_query_message(request_data)
  347. self.assertEqual(rcode.to_text(), "NOERROR")
  348. self.assertTrue(self.xfrsess._tsig_ctx is not None)
  349. def check_transfer_acl(self, acl_setter):
  350. # ACL checks, put some ACL inside
  351. acl_setter(isc.acl.dns.REQUEST_LOADER.load([
  352. {
  353. "from": "127.0.0.1",
  354. "action": "ACCEPT"
  355. },
  356. {
  357. "from": "192.0.2.1",
  358. "action": "DROP"
  359. }
  360. ]))
  361. # Localhost (the default in this test) is accepted
  362. rcode, msg = self.xfrsess._parse_query_message(self.mdata)
  363. self.assertEqual(rcode.to_text(), "NOERROR")
  364. # This should be dropped completely, therefore returning None
  365. self.xfrsess._remote = (socket.AF_INET, socket.SOCK_STREAM,
  366. ('192.0.2.1', 12345))
  367. rcode, msg = self.xfrsess._parse_query_message(self.mdata)
  368. self.assertEqual(None, rcode)
  369. # This should be refused, therefore REFUSED
  370. self.xfrsess._remote = (socket.AF_INET, socket.SOCK_STREAM,
  371. ('192.0.2.2', 12345))
  372. rcode, msg = self.xfrsess._parse_query_message(self.mdata)
  373. self.assertEqual(rcode.to_text(), "REFUSED")
  374. # TSIG signed request
  375. request_data = self.create_request_data(with_tsig=True)
  376. # If the TSIG check fails, it should not check ACL
  377. # (If it checked ACL as well, it would just drop the request)
  378. self.xfrsess._remote = (socket.AF_INET, socket.SOCK_STREAM,
  379. ('192.0.2.1', 12345))
  380. self.xfrsess._tsig_key_ring = TSIGKeyRing()
  381. rcode, msg = self.xfrsess._parse_query_message(request_data)
  382. self.assertEqual(rcode.to_text(), "NOTAUTH")
  383. self.assertTrue(self.xfrsess._tsig_ctx is not None)
  384. # ACL using TSIG: successful case
  385. acl_setter(isc.acl.dns.REQUEST_LOADER.load([
  386. {"key": "example.com", "action": "ACCEPT"}, {"action": "REJECT"}
  387. ]))
  388. self.assertEqual(TSIGKeyRing.SUCCESS,
  389. self.xfrsess._tsig_key_ring.add(TSIG_KEY))
  390. [rcode, msg] = self.xfrsess._parse_query_message(request_data)
  391. self.assertEqual(rcode.to_text(), "NOERROR")
  392. # ACL using TSIG: key name doesn't match; should be rejected
  393. acl_setter(isc.acl.dns.REQUEST_LOADER.load([
  394. {"key": "example.org", "action": "ACCEPT"}, {"action": "REJECT"}
  395. ]))
  396. [rcode, msg] = self.xfrsess._parse_query_message(request_data)
  397. self.assertEqual(rcode.to_text(), "REFUSED")
  398. # ACL using TSIG: no TSIG; should be rejected
  399. acl_setter(isc.acl.dns.REQUEST_LOADER.load([
  400. {"key": "example.org", "action": "ACCEPT"}, {"action": "REJECT"}
  401. ]))
  402. [rcode, msg] = self.xfrsess._parse_query_message(self.mdata)
  403. self.assertEqual(rcode.to_text(), "REFUSED")
  404. #
  405. # ACL using IP + TSIG: both should match
  406. #
  407. acl_setter(isc.acl.dns.REQUEST_LOADER.load([
  408. {"ALL": [{"key": "example.com"}, {"from": "192.0.2.1"}],
  409. "action": "ACCEPT"},
  410. {"action": "REJECT"}
  411. ]))
  412. # both matches
  413. self.xfrsess._remote = (socket.AF_INET, socket.SOCK_STREAM,
  414. ('192.0.2.1', 12345))
  415. [rcode, msg] = self.xfrsess._parse_query_message(request_data)
  416. self.assertEqual(rcode.to_text(), "NOERROR")
  417. # TSIG matches, but address doesn't
  418. self.xfrsess._remote = (socket.AF_INET, socket.SOCK_STREAM,
  419. ('192.0.2.2', 12345))
  420. [rcode, msg] = self.xfrsess._parse_query_message(request_data)
  421. self.assertEqual(rcode.to_text(), "REFUSED")
  422. # Address matches, but TSIG doesn't (not included)
  423. self.xfrsess._remote = (socket.AF_INET, socket.SOCK_STREAM,
  424. ('192.0.2.1', 12345))
  425. [rcode, msg] = self.xfrsess._parse_query_message(self.mdata)
  426. self.assertEqual(rcode.to_text(), "REFUSED")
  427. # Neither address nor TSIG matches
  428. self.xfrsess._remote = (socket.AF_INET, socket.SOCK_STREAM,
  429. ('192.0.2.2', 12345))
  430. [rcode, msg] = self.xfrsess._parse_query_message(self.mdata)
  431. self.assertEqual(rcode.to_text(), "REFUSED")
  432. def test_transfer_acl(self):
  433. # ACL checks only with the default ACL
  434. def acl_setter(acl):
  435. self.xfrsess._acl = acl
  436. self.assertEqual(self.get_counter('xfrrej'), 0)
  437. self.check_transfer_acl(acl_setter)
  438. self.assertGreater(self.get_counter('xfrrej'), 0)
  439. def test_transfer_acl_with_nonetype_xfrrej(self):
  440. # ACL checks only with the default ACL and NoneType xfrrej
  441. # counter
  442. def acl_setter(acl):
  443. self.xfrsess._acl = acl
  444. self.xfrsess._counter_xfrrej = None
  445. self.assertIsNone(self._zone_name_xfrrej)
  446. self.check_transfer_acl(acl_setter)
  447. self.assertIsNone(self._zone_name_xfrrej)
  448. def test_transfer_acl_with_notcallable_xfrrej(self):
  449. # ACL checks only with the default ACL and not callable xfrrej
  450. # counter
  451. def acl_setter(acl):
  452. self.xfrsess._acl = acl
  453. self.xfrsess._counter_xfrrej = 'NOT CALLABLE'
  454. self.assertRaises(TypeError,
  455. self.check_transfer_acl, acl_setter)
  456. def test_transfer_zoneacl(self):
  457. # ACL check with a per zone ACL + default ACL. The per zone ACL
  458. # should match the queryied zone, so it should be used.
  459. def acl_setter(acl):
  460. zone_key = ('IN', 'example.com.')
  461. self.xfrsess._zone_config[zone_key] = {}
  462. self.xfrsess._zone_config[zone_key]['transfer_acl'] = acl
  463. self.xfrsess._acl = isc.acl.dns.REQUEST_LOADER.load([
  464. {"from": "127.0.0.1", "action": "DROP"}])
  465. self.assertEqual(self.get_counter('xfrrej'), 0)
  466. self.check_transfer_acl(acl_setter)
  467. self.assertGreater(self.get_counter('xfrrej'), 0)
  468. def test_transfer_zoneacl_nomatch(self):
  469. # similar to the previous one, but the per zone doesn't match the
  470. # query. The default should be used.
  471. def acl_setter(acl):
  472. zone_key = ('IN', 'example.org.')
  473. self.xfrsess._zone_config[zone_key] = {}
  474. self.xfrsess._zone_config[zone_key]['transfer_acl'] = \
  475. isc.acl.dns.REQUEST_LOADER.load([
  476. {"from": "127.0.0.1", "action": "DROP"}])
  477. self.xfrsess._acl = acl
  478. self.assertEqual(self.get_counter('xfrrej'), 0)
  479. self.check_transfer_acl(acl_setter)
  480. self.assertGreater(self.get_counter('xfrrej'), 0)
  481. def test_get_transfer_acl(self):
  482. # set the default ACL. If there's no specific zone ACL, this one
  483. # should be used.
  484. self.xfrsess._acl = isc.acl.dns.REQUEST_LOADER.load([
  485. {"from": "127.0.0.1", "action": "ACCEPT"}])
  486. acl = self.xfrsess._get_transfer_acl(Name('example.com'), RRClass.IN())
  487. self.assertEqual(acl, self.xfrsess._acl)
  488. # install a per zone config with transfer ACL for example.com. Then
  489. # that ACL will be used for example.com; for others the default ACL
  490. # will still be used.
  491. com_acl = isc.acl.dns.REQUEST_LOADER.load([
  492. {"from": "127.0.0.1", "action": "REJECT"}])
  493. self.xfrsess._zone_config[('IN', 'example.com.')] = {}
  494. self.xfrsess._zone_config[('IN', 'example.com.')]['transfer_acl'] = \
  495. com_acl
  496. self.assertEqual(com_acl,
  497. self.xfrsess._get_transfer_acl(Name('example.com'),
  498. RRClass.IN()))
  499. self.assertEqual(self.xfrsess._acl,
  500. self.xfrsess._get_transfer_acl(Name('example.org'),
  501. RRClass.IN()))
  502. # Name matching should be case insensitive.
  503. self.assertEqual(com_acl,
  504. self.xfrsess._get_transfer_acl(Name('EXAMPLE.COM'),
  505. RRClass.IN()))
  506. def test_send_data(self):
  507. self.xfrsess._send_data(self.sock, self.mdata)
  508. senddata = self.sock.readsent()
  509. self.assertEqual(senddata, self.mdata)
  510. def test_reply_xfrout_query_with_error_rcode(self):
  511. msg = self.getmsg()
  512. self.xfrsess._reply_query_with_error_rcode(msg, self.sock, Rcode(3))
  513. get_msg = self.sock.read_msg()
  514. self.assertEqual(get_msg.get_rcode().to_text(), "NXDOMAIN")
  515. # tsig signed message
  516. msg = self.getmsg()
  517. self.xfrsess._tsig_ctx = self.create_mock_tsig_ctx(TSIGError.NOERROR)
  518. self.xfrsess._reply_query_with_error_rcode(msg, self.sock, Rcode(3))
  519. get_msg = self.sock.read_msg()
  520. self.assertEqual(get_msg.get_rcode().to_text(), "NXDOMAIN")
  521. self.assertTrue(self.message_has_tsig(get_msg))
  522. def test_send_message(self):
  523. msg = self.getmsg()
  524. msg.make_response()
  525. # SOA record data with different cases
  526. soa_rrset = RRset(Name('Example.com.'), RRClass.IN(), RRType.SOA(),
  527. RRTTL(3600))
  528. soa_rrset.add_rdata(Rdata(RRType.SOA(), RRClass.IN(),
  529. 'master.Example.com. admin.exAmple.com. ' +
  530. '2011112001 3600 1800 2419200 7200'))
  531. msg.add_rrset(Message.SECTION_ANSWER, soa_rrset)
  532. self.xfrsess._send_message(self.sock, msg)
  533. send_out_data = self.sock.readsent()[2:]
  534. # CASE_INSENSITIVE compression mode
  535. render = MessageRenderer();
  536. render.set_length_limit(XFROUT_MAX_MESSAGE_SIZE)
  537. msg.to_wire(render)
  538. self.assertNotEqual(render.get_data(), send_out_data)
  539. # CASE_SENSITIVE compression mode
  540. render.clear()
  541. render.set_compress_mode(MessageRenderer.CASE_SENSITIVE)
  542. render.set_length_limit(XFROUT_MAX_MESSAGE_SIZE)
  543. msg.to_wire(render)
  544. self.assertEqual(render.get_data(), send_out_data)
  545. def test_clear_message(self):
  546. msg = self.getmsg()
  547. qid = msg.get_qid()
  548. opcode = msg.get_opcode()
  549. rcode = msg.get_rcode()
  550. self.xfrsess._clear_message(msg)
  551. self.assertEqual(msg.get_qid(), qid)
  552. self.assertEqual(msg.get_opcode(), opcode)
  553. self.assertEqual(msg.get_rcode(), rcode)
  554. self.assertTrue(msg.get_header_flag(Message.HEADERFLAG_AA))
  555. def test_send_message_with_last_soa(self):
  556. msg = self.getmsg()
  557. msg.make_response()
  558. self.xfrsess._send_message_with_last_soa(msg, self.sock,
  559. self.soa_rrset, 0)
  560. get_msg = self.sock.read_msg()
  561. # tsig context does not exist
  562. self.assertFalse(self.message_has_tsig(get_msg))
  563. self.assertEqual(get_msg.get_rr_count(Message.SECTION_QUESTION), 1)
  564. self.assertEqual(get_msg.get_rr_count(Message.SECTION_ANSWER), 1)
  565. self.assertEqual(get_msg.get_rr_count(Message.SECTION_AUTHORITY), 0)
  566. answer = get_msg.get_section(Message.SECTION_ANSWER)[0]
  567. self.assertEqual(answer.get_name().to_text(), "example.com.")
  568. self.assertEqual(answer.get_class(), RRClass("IN"))
  569. self.assertEqual(answer.get_type().to_text(), "SOA")
  570. rdata = answer.get_rdata()
  571. self.assertEqual(rdata[0], self.soa_rrset.get_rdata()[0])
  572. # Sending the message with last soa together
  573. self.xfrsess._send_message_with_last_soa(msg, self.sock,
  574. self.soa_rrset, 0)
  575. get_msg = self.sock.read_msg()
  576. # tsig context does not exist
  577. self.assertFalse(self.message_has_tsig(get_msg))
  578. def test_send_message_with_last_soa_with_tsig(self):
  579. # create tsig context
  580. self.xfrsess._tsig_ctx = self.create_mock_tsig_ctx(TSIGError.NOERROR)
  581. msg = self.getmsg()
  582. msg.make_response()
  583. # Sending the message with last soa together
  584. self.xfrsess._send_message_with_last_soa(msg, self.sock,
  585. self.soa_rrset, 0)
  586. get_msg = self.sock.read_msg()
  587. self.assertTrue(self.message_has_tsig(get_msg))
  588. self.assertEqual(get_msg.get_rr_count(Message.SECTION_QUESTION), 1)
  589. self.assertEqual(get_msg.get_rr_count(Message.SECTION_ANSWER), 1)
  590. self.assertEqual(get_msg.get_rr_count(Message.SECTION_AUTHORITY), 0)
  591. def test_trigger_send_message_with_last_soa(self):
  592. rrset_a = RRset(Name("example.com"), RRClass.IN(), RRType.A(), RRTTL(3600))
  593. rrset_a.add_rdata(Rdata(RRType.A(), RRClass.IN(), "192.0.2.1"))
  594. msg = self.getmsg()
  595. msg.make_response()
  596. msg.add_rrset(Message.SECTION_ANSWER, rrset_a)
  597. # length larger than MAX-len(rrset)
  598. length_need_split = xfrout.XFROUT_MAX_MESSAGE_SIZE - \
  599. get_rrset_len(self.soa_rrset) + 1
  600. # give the function a value that is larger than MAX-len(rrset)
  601. # this should have triggered the sending of two messages
  602. # (1 with the rrset we added manually, and 1 that triggered
  603. # the sending in _with_last_soa)
  604. self.xfrsess._send_message_with_last_soa(msg, self.sock,
  605. self.soa_rrset,
  606. length_need_split)
  607. get_msg = self.sock.read_msg()
  608. self.assertFalse(self.message_has_tsig(get_msg))
  609. self.assertEqual(get_msg.get_rr_count(Message.SECTION_QUESTION), 1)
  610. self.assertEqual(get_msg.get_rr_count(Message.SECTION_ANSWER), 1)
  611. self.assertEqual(get_msg.get_rr_count(Message.SECTION_AUTHORITY), 0)
  612. answer = get_msg.get_section(Message.SECTION_ANSWER)[0]
  613. self.assertEqual(answer.get_name().to_text(), "example.com.")
  614. self.assertEqual(answer.get_class(), RRClass("IN"))
  615. self.assertEqual(answer.get_type().to_text(), "A")
  616. rdata = answer.get_rdata()
  617. self.assertEqual(rdata[0].to_text(), "192.0.2.1")
  618. get_msg = self.sock.read_msg()
  619. self.assertFalse(self.message_has_tsig(get_msg))
  620. self.assertEqual(get_msg.get_rr_count(Message.SECTION_QUESTION), 0)
  621. self.assertEqual(get_msg.get_rr_count(Message.SECTION_ANSWER), 1)
  622. self.assertEqual(get_msg.get_rr_count(Message.SECTION_AUTHORITY), 0)
  623. answer = get_msg.get_section(Message.SECTION_ANSWER)[0]
  624. self.assertEqual(answer.get_name().to_text(), "example.com.")
  625. self.assertEqual(answer.get_class(), RRClass("IN"))
  626. self.assertEqual(answer.get_type().to_text(), "SOA")
  627. rdata = answer.get_rdata()
  628. self.assertEqual(rdata[0], self.soa_rrset.get_rdata()[0])
  629. # and it should not have sent anything else
  630. self.assertEqual(0, len(self.sock.sendqueue))
  631. def test_trigger_send_message_with_last_soa_with_tsig(self):
  632. self.xfrsess._tsig_ctx = self.create_mock_tsig_ctx(TSIGError.NOERROR)
  633. msg = self.getmsg()
  634. msg.make_response()
  635. msg.add_rrset(Message.SECTION_ANSWER, self.soa_rrset)
  636. # length larger than MAX-len(rrset)
  637. length_need_split = xfrout.XFROUT_MAX_MESSAGE_SIZE - \
  638. get_rrset_len(self.soa_rrset) + 1
  639. # give the function a value that is larger than MAX-len(rrset)
  640. # this should have triggered the sending of two messages
  641. # (1 with the rrset we added manually, and 1 that triggered
  642. # the sending in _with_last_soa)
  643. self.xfrsess._send_message_with_last_soa(msg, self.sock,
  644. self.soa_rrset,
  645. length_need_split)
  646. # Both messages should have TSIG RRs
  647. get_msg = self.sock.read_msg()
  648. self.assertTrue(self.message_has_tsig(get_msg))
  649. get_msg = self.sock.read_msg()
  650. self.assertTrue(self.message_has_tsig(get_msg))
  651. # and it should not have sent anything else
  652. self.assertEqual(0, len(self.sock.sendqueue))
  653. def test_get_rrset_len(self):
  654. self.assertEqual(82, get_rrset_len(self.soa_rrset))
  655. def test_xfrout_axfr_setup(self):
  656. self.xfrsess.ClientClass = MockDataSrcClient
  657. # Successful case. A zone iterator should be set up.
  658. self.assertEqual(self.xfrsess._xfrout_setup(
  659. self.getmsg(), TEST_ZONE_NAME, TEST_RRCLASS), Rcode.NOERROR())
  660. self.assertNotEqual(None, self.xfrsess._iterator)
  661. # Failure cases
  662. self.assertEqual(self.xfrsess._xfrout_setup(
  663. self.getmsg(), Name('notauth.example.com'), TEST_RRCLASS),
  664. Rcode.NOTAUTH())
  665. self.assertEqual(self.xfrsess._xfrout_setup(
  666. self.getmsg(), Name('nosoa.example.com'), TEST_RRCLASS),
  667. Rcode.SERVFAIL())
  668. self.assertEqual(self.xfrsess._xfrout_setup(
  669. self.getmsg(), Name('multisoa.example.com'), TEST_RRCLASS),
  670. Rcode.SERVFAIL())
  671. def test_xfrout_ixfr_setup(self):
  672. self.xfrsess.ClientClass = MockDataSrcClient
  673. self.set_request_type(RRType.IXFR())
  674. # Successful case of pure IXFR. A zone journal reader should be set
  675. # up.
  676. self.mdata = self.create_request_data(ixfr=IXFR_OK_VERSION)
  677. self.assertEqual(self.xfrsess._xfrout_setup(
  678. self.getmsg(), TEST_ZONE_NAME, TEST_RRCLASS), Rcode.NOERROR())
  679. self.assertNotEqual(None, self.xfrsess._jnl_reader)
  680. # Successful case, but as a result of falling back to AXFR-style
  681. # IXFR. A zone iterator should be set up instead of a journal reader.
  682. self.mdata = self.create_request_data(ixfr=IXFR_NG_VERSION)
  683. self.assertEqual(self.xfrsess._xfrout_setup(
  684. self.getmsg(), TEST_ZONE_NAME, TEST_RRCLASS), Rcode.NOERROR())
  685. self.assertNotEqual(None, self.xfrsess._iterator)
  686. self.assertEqual(None, self.xfrsess._jnl_reader)
  687. # Successful case, but the requested SOA serial is greater than that of
  688. # the local SOA. Both iterator and jnl_reader should be None,
  689. # indicating that the response will contain just one SOA.
  690. self.mdata = self.create_request_data(ixfr=SOA_CURRENT_VERSION+1)
  691. self.assertEqual(self.xfrsess._xfrout_setup(
  692. self.getmsg(), TEST_ZONE_NAME, TEST_RRCLASS), Rcode.NOERROR())
  693. self.assertEqual(None, self.xfrsess._iterator)
  694. self.assertEqual(None, self.xfrsess._jnl_reader)
  695. # Similar to the previous case, but the requested serial is equal to
  696. # the local SOA.
  697. self.mdata = self.create_request_data(ixfr=SOA_CURRENT_VERSION)
  698. self.assertEqual(self.xfrsess._xfrout_setup(
  699. self.getmsg(), TEST_ZONE_NAME, TEST_RRCLASS), Rcode.NOERROR())
  700. self.assertEqual(None, self.xfrsess._iterator)
  701. self.assertEqual(None, self.xfrsess._jnl_reader)
  702. # Similar to the previous case, but the comparison should be done
  703. # based on serial number arithmetic, not as integers.
  704. zone_name = Name('maxserial.example.com') # whose SOA is 0xffffffff
  705. self.mdata = self.create_request_data(ixfr=1, zone_name=zone_name)
  706. self.assertEqual(self.xfrsess._xfrout_setup(
  707. self.getmsg(), zone_name, TEST_RRCLASS), Rcode.NOERROR())
  708. self.assertEqual(None, self.xfrsess._iterator)
  709. self.assertEqual(None, self.xfrsess._jnl_reader)
  710. # The data source doesn't support journaling. Should fallback to AXFR.
  711. zone_name = Name('nojournal.example.com')
  712. self.mdata = self.create_request_data(ixfr=IXFR_OK_VERSION,
  713. zone_name=zone_name)
  714. self.assertEqual(self.xfrsess._xfrout_setup(
  715. self.getmsg(), zone_name, TEST_RRCLASS), Rcode.NOERROR())
  716. self.assertNotEqual(None, self.xfrsess._iterator)
  717. # Failure cases
  718. zone_name = Name('notauth.example.com')
  719. self.mdata = self.create_request_data(ixfr=IXFR_OK_VERSION,
  720. zone_name=zone_name)
  721. self.assertEqual(self.xfrsess._xfrout_setup(
  722. self.getmsg(), zone_name, TEST_RRCLASS), Rcode.NOTAUTH())
  723. # this is a strange case: zone's SOA will be found but the journal
  724. # reader won't be created due to 'no such zone'.
  725. zone_name = Name('notauth2.example.com')
  726. self.mdata = self.create_request_data(ixfr=IXFR_OK_VERSION,
  727. zone_name=zone_name)
  728. self.assertEqual(self.xfrsess._xfrout_setup(
  729. self.getmsg(), zone_name, TEST_RRCLASS), Rcode.NOTAUTH())
  730. zone_name = Name('nosoa.example.com')
  731. self.mdata = self.create_request_data(ixfr=IXFR_OK_VERSION,
  732. zone_name=zone_name)
  733. self.assertEqual(self.xfrsess._xfrout_setup(
  734. self.getmsg(), zone_name, TEST_RRCLASS), Rcode.SERVFAIL())
  735. zone_name = Name('multisoa.example.com')
  736. self.mdata = self.create_request_data(ixfr=IXFR_OK_VERSION,
  737. zone_name=zone_name)
  738. self.assertEqual(self.xfrsess._xfrout_setup(
  739. self.getmsg(), zone_name, TEST_RRCLASS), Rcode.SERVFAIL())
  740. # query name doesn't match the SOA's owner
  741. self.mdata = self.create_request_data(ixfr=IXFR_OK_VERSION)
  742. self.assertEqual(self.xfrsess._xfrout_setup(
  743. self.getmsg(), zone_name, TEST_RRCLASS), Rcode.FORMERR())
  744. # query's RR class doesn't match the SOA's class
  745. zone_name = TEST_ZONE_NAME # make sure the name matches this time
  746. self.mdata = self.create_request_data(ixfr=IXFR_OK_VERSION,
  747. soa_class=RRClass.CH())
  748. self.assertEqual(self.xfrsess._xfrout_setup(
  749. self.getmsg(), zone_name, TEST_RRCLASS), Rcode.FORMERR())
  750. # multiple SOA RRs
  751. self.mdata = self.create_request_data(ixfr=IXFR_OK_VERSION,
  752. num_soa=2)
  753. self.assertEqual(self.xfrsess._xfrout_setup(
  754. self.getmsg(), zone_name, TEST_RRCLASS), Rcode.FORMERR())
  755. def test_dns_xfrout_start_formerror(self):
  756. # formerror
  757. self.xfrsess.dns_xfrout_start(self.sock, b"\xd6=\x00\x00\x00\x01\x00")
  758. sent_data = self.sock.readsent()
  759. self.assertEqual(len(sent_data), 0)
  760. def test_dns_xfrout_start_notauth(self):
  761. def notauth(msg, name, rrclass):
  762. return Rcode.NOTAUTH()
  763. self.xfrsess._xfrout_setup = notauth
  764. self.xfrsess.dns_xfrout_start(self.sock, self.mdata)
  765. get_msg = self.sock.read_msg()
  766. self.assertEqual(get_msg.get_rcode().to_text(), "NOTAUTH")
  767. def test_dns_xfrout_start_datasrc_servfail(self):
  768. def internal_raise(x, y):
  769. raise isc.datasrc.Error('exception for the sake of test')
  770. self.xfrsess.ClientClass = internal_raise
  771. self.xfrsess.dns_xfrout_start(self.sock, self.mdata)
  772. self.assertEqual(self.sock.read_msg().get_rcode(), Rcode.SERVFAIL())
  773. def test_dns_xfrout_start_noerror(self):
  774. def noerror(msg, name, rrclass):
  775. return Rcode.NOERROR()
  776. self.xfrsess._xfrout_setup = noerror
  777. def myreply(msg, sock):
  778. self.sock.send(b"success")
  779. self.assertEqual(self.get_counter('xfrreqdone'), 0)
  780. self.xfrsess._reply_xfrout_query = myreply
  781. self.xfrsess.dns_xfrout_start(self.sock, self.mdata)
  782. self.assertEqual(self.sock.readsent(), b"success")
  783. self.assertGreater(self.get_counter('xfrreqdone'), 0)
  784. def test_dns_xfrout_start_with_nonetype_xfrreqdone(self):
  785. def noerror(msg, name, rrclass):
  786. return Rcode.NOERROR()
  787. self.xfrsess._xfrout_setup = noerror
  788. def myreply(msg, sock):
  789. self.sock.send(b"success")
  790. self.assertIsNone(self._zone_name_xfrreqdone)
  791. self.xfrsess._reply_xfrout_query = myreply
  792. self.xfrsess._counter_xfrreqdone = None
  793. self.xfrsess.dns_xfrout_start(self.sock, self.mdata)
  794. self.assertIsNone(self._zone_name_xfrreqdone)
  795. def test_dns_xfrout_start_with_notcallable_xfrreqdone(self):
  796. def noerror(msg, name, rrclass):
  797. return Rcode.NOERROR()
  798. self.xfrsess._xfrout_setup = noerror
  799. def myreply(msg, sock):
  800. self.sock.send(b"success")
  801. self.xfrsess._reply_xfrout_query = myreply
  802. self.xfrsess._counter_xfrreqdone = 'NOT CALLABLE'
  803. self.assertRaises(TypeError,
  804. self.xfrsess.dns_xfrout_start, self.sock,
  805. self.mdata)
  806. def test_reply_xfrout_query_axfr(self):
  807. self.xfrsess._soa = self.soa_rrset
  808. self.xfrsess._iterator = [self.soa_rrset]
  809. self.xfrsess._reply_xfrout_query(self.getmsg(), self.sock)
  810. reply_msg = self.sock.read_msg()
  811. self.assertEqual(reply_msg.get_rr_count(Message.SECTION_ANSWER), 2)
  812. def test_reply_xfrout_query_axfr_with_tsig(self):
  813. rrset = RRset(Name('a.example.com'), RRClass.IN(), RRType.A(),
  814. RRTTL(3600))
  815. rrset.add_rdata(Rdata(RRType.A(), RRClass.IN(), '192.0.2.1'))
  816. global xfrout
  817. def get_rrset_len(rrset):
  818. return 65520
  819. self.xfrsess._soa = self.soa_rrset
  820. self.xfrsess._iterator = [rrset for i in range(0, 100)]
  821. xfrout.get_rrset_len = get_rrset_len
  822. self.xfrsess._tsig_ctx = self.create_mock_tsig_ctx(TSIGError.NOERROR)
  823. self.xfrsess._reply_xfrout_query(self.getmsg(), self.sock)
  824. # All messages must have TSIG as we don't support the feature of
  825. # skipping intermediate TSIG records (with bulk signing).
  826. for i in range(0, 102): # 102 = all 100 RRs from iterator and 2 SOAs
  827. reply_msg = self.sock.read_msg()
  828. # With the hack of get_rrset_len() above, every message must have
  829. # exactly one RR in the answer section.
  830. self.assertEqual(reply_msg.get_rr_count(Message.SECTION_ANSWER), 1)
  831. self.assertTrue(self.message_has_tsig(reply_msg))
  832. # and it should not have sent anything else
  833. self.assertEqual(0, len(self.sock.sendqueue))
  834. def test_reply_xfrout_query_ixfr(self):
  835. # Creating a pure (incremental) IXFR response. Intermediate SOA
  836. # RRs won't be skipped.
  837. self.xfrsess._soa = create_soa(SOA_CURRENT_VERSION)
  838. self.xfrsess._iterator = [create_soa(IXFR_OK_VERSION),
  839. create_a(Name('a.example.com'), '192.0.2.2'),
  840. create_soa(SOA_CURRENT_VERSION),
  841. create_aaaa(Name('a.example.com'),
  842. '2001:db8::1')]
  843. self.xfrsess._jnl_reader = self.xfrsess._iterator
  844. self.xfrsess._reply_xfrout_query(self.getmsg(), self.sock)
  845. reply_msg = self.sock.read_msg(Message.PRESERVE_ORDER)
  846. actual_records = reply_msg.get_section(Message.SECTION_ANSWER)
  847. expected_records = self.xfrsess._iterator[:]
  848. expected_records.insert(0, create_soa(SOA_CURRENT_VERSION))
  849. expected_records.append(create_soa(SOA_CURRENT_VERSION))
  850. self.assertEqual(len(expected_records), len(actual_records))
  851. for (expected_rr, actual_rr) in zip(expected_records, actual_records):
  852. self.assertTrue(rrsets_equal(expected_rr, actual_rr))
  853. def test_reply_xfrout_query_axfr_maxlen(self):
  854. # The test RR(set) has the length of 65535 - 12 (size of hdr) bytes:
  855. # owner name = 1 (root), fixed fields (type,class,TTL,RDLEN) = 10
  856. # RDATA = 65512 (= 65535 - 12 - 1 - 10)
  857. self.xfrsess._soa = self.soa_rrset
  858. test_rr = create_generic(Name('.'), 65512)
  859. self.xfrsess._iterator = [self.soa_rrset, test_rr]
  860. self.xfrsess._reply_xfrout_query(self.getmsg(), self.sock)
  861. # The first message should contain the beginning SOA, and only that RR
  862. r = self.sock.read_msg()
  863. self.assertEqual(1, r.get_rr_count(Message.SECTION_ANSWER))
  864. self.assertTrue(rrsets_equal(self.soa_rrset,
  865. r.get_section(Message.SECTION_ANSWER)[0]))
  866. # The second message should contain the beginning SOA, and only that RR
  867. # The wire format data should have the possible maximum size.
  868. r, rlen = self.sock.read_msg(need_len=True)
  869. self.assertEqual(65535, rlen)
  870. self.assertEqual(1, r.get_rr_count(Message.SECTION_ANSWER))
  871. self.assertTrue(rrsets_equal(test_rr,
  872. r.get_section(Message.SECTION_ANSWER)[0]))
  873. # The third message should contain the ending SOA, and only that RR
  874. r = self.sock.read_msg()
  875. self.assertEqual(1, r.get_rr_count(Message.SECTION_ANSWER))
  876. self.assertTrue(rrsets_equal(self.soa_rrset,
  877. r.get_section(Message.SECTION_ANSWER)[0]))
  878. # there should be no more message
  879. self.assertEqual(0, len(self.sock.sendqueue))
  880. def maxlen_test_common_setup(self, tsig=False):
  881. '''Common initialization for some of the tests below
  882. For those tests we use '.' for all owner names and names in RDATA
  883. to avoid having unexpected results due to compression. It returns
  884. the created SOA for convenience.
  885. If tsig is True, also setup TSIG (mock) context. In our test cases
  886. the size of the TSIG RR is 81 bytes (key name = example.com,
  887. algorithm = hmac-md5)
  888. '''
  889. soa = RRset(Name('.'), RRClass.IN(), RRType.SOA(), RRTTL(3600))
  890. soa.add_rdata(Rdata(RRType.SOA(), RRClass.IN(), '. . 0 0 0 0 0'))
  891. self.mdata = self.create_request_data(zone_name=Name('.'))
  892. self.xfrsess._soa = soa
  893. if tsig:
  894. self.xfrsess._tsig_ctx = \
  895. self.create_mock_tsig_ctx(TSIGError.NOERROR)
  896. self.xfrsess._tsig_len = 81
  897. return soa
  898. def maxlen_test_common_checks(self, soa_rr, test_rr, expected_n_rr):
  899. '''A set of common assertion checks for some tests below.
  900. In all cases two AXFR response messages should have been created.
  901. expected_n_rr is a list of two elements, each specifies the expected
  902. number of answer RRs for each message: expected_n_rr[0] is the expected
  903. number of the first answer RRs; expected_n_rr[1] is the expected number
  904. of the second answer RRs. The message that contains two RRs should
  905. have the maximum possible wire length (65535 bytes). And, in all
  906. cases, the resulting RRs should be in the order of SOA, another RR,
  907. SOA.
  908. '''
  909. # Check the first message
  910. r, rlen = self.sock.read_msg(need_len=True)
  911. if expected_n_rr[0] == 2:
  912. self.assertEqual(65535, rlen)
  913. self.assertEqual(expected_n_rr[0],
  914. r.get_rr_count(Message.SECTION_ANSWER))
  915. actual_rrs = r.get_section(Message.SECTION_ANSWER)[:]
  916. # Check the second message
  917. r, rlen = self.sock.read_msg(need_len=True)
  918. if expected_n_rr[1] == 2:
  919. self.assertEqual(65535, rlen)
  920. self.assertEqual(expected_n_rr[1],
  921. r.get_rr_count(Message.SECTION_ANSWER))
  922. actual_rrs.extend(r.get_section(Message.SECTION_ANSWER))
  923. for (expected_rr, actual_rr) in zip([soa_rr, test_rr, soa_rr],
  924. actual_rrs):
  925. self.assertTrue(rrsets_equal(expected_rr, actual_rr))
  926. # there should be no more message
  927. self.assertEqual(0, len(self.sock.sendqueue))
  928. def test_reply_xfrout_query_axfr_maxlen_with_soa(self):
  929. # Similar to the 'maxlen' test, but the first message should be
  930. # able to contain both SOA and the large RR.
  931. soa = self.maxlen_test_common_setup()
  932. # The first message will contain the question (5 bytes), so the
  933. # test RDATA should allow a room for that.
  934. test_rr = create_generic(Name('.'), 65512 - 5 - get_rrset_len(soa))
  935. self.xfrsess._iterator = [soa, test_rr]
  936. self.xfrsess._reply_xfrout_query(self.getmsg(), self.sock)
  937. self.maxlen_test_common_checks(soa, test_rr, [2, 1])
  938. def test_reply_xfrout_query_axfr_maxlen_with_soa_with_tsig(self):
  939. # Similar to the previous case, but with TSIG (whose size is 81 bytes).
  940. soa = self.maxlen_test_common_setup(True)
  941. test_rr = create_generic(Name('.'), 65512 - 5 - 81 -
  942. get_rrset_len(soa))
  943. self.xfrsess._iterator = [soa, test_rr]
  944. self.xfrsess._reply_xfrout_query(self.getmsg(), self.sock)
  945. self.maxlen_test_common_checks(soa, test_rr, [2, 1])
  946. def test_reply_xfrout_query_axfr_maxlen_with_endsoa(self):
  947. # Similar to the max w/ soa test, but the first message cannot contain
  948. # both SOA and the long RR due to the question section. The second
  949. # message should be able to contain both.
  950. soa = self.maxlen_test_common_setup()
  951. test_rr = create_generic(Name('.'), 65512 - get_rrset_len(soa))
  952. self.xfrsess._iterator = [soa, test_rr]
  953. self.xfrsess._reply_xfrout_query(self.getmsg(), self.sock)
  954. self.maxlen_test_common_checks(soa, test_rr, [1, 2])
  955. def test_reply_xfrout_query_axfr_maxlen_with_endsoa_with_tsig(self):
  956. # Similar to the previous case, but with TSIG.
  957. soa = self.maxlen_test_common_setup(True)
  958. test_rr = create_generic(Name('.'), 65512 - 81 - get_rrset_len(soa))
  959. self.xfrsess._iterator = [soa, test_rr]
  960. self.xfrsess._reply_xfrout_query(self.getmsg(), self.sock)
  961. self.maxlen_test_common_checks(soa, test_rr, [1, 2])
  962. def test_reply_xfrout_query_axfr_toobigdata(self):
  963. # Similar to the 'maxlen' test, but the RR doesn't even fit in a
  964. # single message.
  965. self.xfrsess._soa = self.soa_rrset
  966. test_rr = create_generic(Name('.'), 65513) # 1 byte larger than 'max'
  967. self.xfrsess._iterator = [self.soa_rrset, test_rr]
  968. # the reply method should fail with exception
  969. self.assertRaises(XfroutSessionError, self.xfrsess._reply_xfrout_query,
  970. self.getmsg(), self.sock)
  971. # The first message should still have been sent and contain the
  972. # beginning SOA, and only that RR
  973. r = self.sock.read_msg()
  974. self.assertEqual(1, r.get_rr_count(Message.SECTION_ANSWER))
  975. self.assertTrue(rrsets_equal(self.soa_rrset,
  976. r.get_section(Message.SECTION_ANSWER)[0]))
  977. # And there should have been no other messages sent
  978. self.assertEqual(0, len(self.sock.sendqueue))
  979. def test_reply_xfrout_query_ixfr_soa_only(self):
  980. # Creating an IXFR response that contains only one RR, which is the
  981. # SOA of the current version.
  982. self.xfrsess._soa = create_soa(SOA_CURRENT_VERSION)
  983. self.xfrsess._iterator = None
  984. self.xfrsess._jnl_reader = None
  985. self.xfrsess._reply_xfrout_query(self.getmsg(), self.sock)
  986. reply_msg = self.sock.read_msg(Message.PRESERVE_ORDER)
  987. answer = reply_msg.get_section(Message.SECTION_ANSWER)
  988. self.assertEqual(1, len(answer))
  989. self.assertTrue(rrsets_equal(create_soa(SOA_CURRENT_VERSION),
  990. answer[0]))
  991. class TestXfroutSessionWithSQLite3(TestXfroutSessionBase):
  992. '''Tests for XFR-out sessions using an SQLite3 DB.
  993. These are provided mainly to confirm the implementation actually works
  994. in an environment closer to actual operational environments. So we
  995. only check a few common cases; other details are tested using mock
  996. data sources.
  997. '''
  998. def setUp(self):
  999. super().setUp()
  1000. self.xfrsess._request_data = self.mdata
  1001. self.xfrsess._server.get_db_file = lambda : TESTDATA_SRCDIR + \
  1002. 'test.sqlite3'
  1003. self.ns_name = 'a.dns.example.com'
  1004. def check_axfr_stream(self, response):
  1005. '''Common checks for AXFR(-style) response for the test zone.
  1006. '''
  1007. # This zone contains two A RRs for the same name with different TTLs.
  1008. # These TTLs should be preseved in the AXFR stream.
  1009. actual_records = response.get_section(Message.SECTION_ANSWER)
  1010. self.assertEqual(5, len(actual_records))
  1011. # The first and last RR should be the expected SOA
  1012. expected_soa = create_soa(2011112001)
  1013. self.assertTrue(rrsets_equal(expected_soa, actual_records[0]))
  1014. self.assertTrue(rrsets_equal(expected_soa, actual_records[-1]))
  1015. # The ordering of the intermediate RRs can differ depending on the
  1016. # internal details of the SQLite3 library, so we sort them by a simple
  1017. # rule sufficient for the purpose here, and then compare them.
  1018. expected_others = [create_ns(self.ns_name),
  1019. create_a(Name(self.ns_name), '192.0.2.1', 3600),
  1020. create_a(Name(self.ns_name), '192.0.2.2', 7200)]
  1021. keyfn = lambda x: (x.get_type(), x.get_ttl())
  1022. for (expected_rr, actual_rr) in zip(sorted(expected_others, key=keyfn),
  1023. sorted(actual_records[1:4],
  1024. key=keyfn)):
  1025. self.assertTrue(rrsets_equal(expected_rr, actual_rr))
  1026. def test_axfr_normal_session(self):
  1027. self.assertEqual(self.get_counter('axfr_started'), 0)
  1028. self.assertEqual(self.get_counter('axfr_ended'), 0)
  1029. self.assertEqual(self.get_counter('ixfr_started'), 0)
  1030. self.assertEqual(self.get_counter('ixfr_ended'), 0)
  1031. XfroutSession._handle(self.xfrsess)
  1032. response = self.sock.read_msg(Message.PRESERVE_ORDER);
  1033. self.assertEqual(Rcode.NOERROR(), response.get_rcode())
  1034. self.check_axfr_stream(response)
  1035. self.assertEqual(self.xfrsess._request_type, RRType.AXFR())
  1036. self.assertNotEqual(self.xfrsess._request_type, RRType.IXFR())
  1037. self.assertEqual(self.get_counter('axfr_started'), 1)
  1038. self.assertEqual(self.get_counter('axfr_ended'), 1)
  1039. self.assertEqual(self.get_counter('ixfr_started'), 0)
  1040. self.assertEqual(self.get_counter('ixfr_ended'), 0)
  1041. def test_ixfr_to_axfr(self):
  1042. self.xfrsess._request_data = \
  1043. self.create_request_data(ixfr=IXFR_NG_VERSION)
  1044. XfroutSession._handle(self.xfrsess)
  1045. response = self.sock.read_msg(Message.PRESERVE_ORDER);
  1046. self.assertEqual(Rcode.NOERROR(), response.get_rcode())
  1047. # This is an AXFR-style IXFR. So the question section should indicate
  1048. # that it's an IXFR resposne.
  1049. self.assertEqual(RRType.IXFR(), response.get_question()[0].get_type())
  1050. self.check_axfr_stream(response)
  1051. def test_ixfr_normal_session(self):
  1052. # See testdata/creatediff.py. There are 8 changes between two
  1053. # versions. So the answer section should contain all of these and
  1054. # two beginning and trailing SOAs.
  1055. self.xfrsess._request_data = \
  1056. self.create_request_data(ixfr=IXFR_OK_VERSION)
  1057. self.assertEqual(self.get_counter('axfr_started'), 0)
  1058. self.assertEqual(self.get_counter('axfr_ended'), 0)
  1059. self.assertEqual(self.get_counter('ixfr_started'), 0)
  1060. self.assertEqual(self.get_counter('ixfr_ended'), 0)
  1061. XfroutSession._handle(self.xfrsess)
  1062. response = self.sock.read_msg(Message.PRESERVE_ORDER)
  1063. actual_records = response.get_section(Message.SECTION_ANSWER)
  1064. expected_records = [create_soa(2011112001), create_soa(2011111802),
  1065. create_soa(2011111900),
  1066. create_a(Name(self.ns_name), '192.0.2.2', 7200),
  1067. create_soa(2011111900),
  1068. create_a(Name(self.ns_name), '192.0.2.53'),
  1069. create_aaaa(Name(self.ns_name), '2001:db8::1'),
  1070. create_soa(2011112001),
  1071. create_a(Name(self.ns_name), '192.0.2.1'),
  1072. create_soa(2011112001)]
  1073. self.assertEqual(len(expected_records), len(actual_records))
  1074. for (expected_rr, actual_rr) in zip(expected_records, actual_records):
  1075. self.assertTrue(rrsets_equal(expected_rr, actual_rr))
  1076. self.assertNotEqual(self.xfrsess._request_type, RRType.AXFR())
  1077. self.assertEqual(self.xfrsess._request_type, RRType.IXFR())
  1078. self.assertEqual(self.get_counter('axfr_started'), 0)
  1079. self.assertEqual(self.get_counter('axfr_ended'), 0)
  1080. self.assertEqual(self.get_counter('ixfr_started'), 1)
  1081. self.assertEqual(self.get_counter('ixfr_ended'), 1)
  1082. def ixfr_soa_only_common_checks(self, request_serial):
  1083. self.xfrsess._request_data = \
  1084. self.create_request_data(ixfr=request_serial)
  1085. XfroutSession._handle(self.xfrsess)
  1086. response = self.sock.read_msg(Message.PRESERVE_ORDER);
  1087. answers = response.get_section(Message.SECTION_ANSWER)
  1088. self.assertEqual(1, len(answers))
  1089. self.assertTrue(rrsets_equal(create_soa(SOA_CURRENT_VERSION),
  1090. answers[0]))
  1091. def test_ixfr_soa_only(self):
  1092. # The requested SOA serial is the latest one. The response should
  1093. # contain exactly one SOA of that serial.
  1094. self.ixfr_soa_only_common_checks(SOA_CURRENT_VERSION)
  1095. def test_ixfr_soa_only2(self):
  1096. # Similar to the previous test, but the requested SOA is larger than
  1097. # the current.
  1098. self.ixfr_soa_only_common_checks(SOA_CURRENT_VERSION + 1)
  1099. class MyUnixSockServer(UnixSockServer):
  1100. def __init__(self):
  1101. self._shutdown_event = threading.Event()
  1102. self._common_init()
  1103. self._cc = MyCCSession()
  1104. self.update_config_data(self._cc.get_full_config())
  1105. self._counters = {}
  1106. class TestUnixSockServer(unittest.TestCase):
  1107. def setUp(self):
  1108. self.write_sock, self.read_sock = socket.socketpair()
  1109. self.unix = MyUnixSockServer()
  1110. # Some test below modify these module-wide attributes. We'll need
  1111. # to restore them at the end of each test, so we remember them here.
  1112. self.__select_bak = xfrout.select.select
  1113. self.__recv_fd_back = xfrout.recv_fd
  1114. def tearDown(self):
  1115. # Restore possibly faked module-wide attributes.
  1116. xfrout.select.select = self.__select_bak
  1117. xfrout.recv_fd = self.__recv_fd_back
  1118. def test_tsig_keyring(self):
  1119. """
  1120. Check we use the global keyring when starting a request.
  1121. """
  1122. try:
  1123. # These are just so the keyring can be started
  1124. self.unix._cc.add_remote_config_by_name = \
  1125. lambda name, callback: None
  1126. self.unix._cc.get_remote_config_value = \
  1127. lambda module, name: ([], True)
  1128. self.unix._cc.remove_remote_config = lambda name: None
  1129. isc.server_common.tsig_keyring.init_keyring(self.unix._cc)
  1130. # These are not really interesting for the test. These are just
  1131. # handled over, so strings are OK.
  1132. self.unix._guess_remote = lambda sock: "Address"
  1133. self.unix._zone_config = "Zone config"
  1134. self.unix._acl = "acl"
  1135. # This would be the handler class, but we just check it is passed
  1136. # the right parametes, so function is enough for that.
  1137. keys = isc.server_common.tsig_keyring.get_keyring()
  1138. def handler(sock, data, server, keyring, address, acl, config):
  1139. self.assertEqual("sock", sock)
  1140. self.assertEqual("data", data)
  1141. self.assertEqual(self.unix, server)
  1142. self.assertEqual(keys, keyring)
  1143. self.assertEqual("Address", address)
  1144. self.assertEqual("acl", acl)
  1145. self.assertEqual("Zone config", config)
  1146. self.unix.RequestHandlerClass = handler
  1147. self.unix.finish_request("sock", "data")
  1148. finally:
  1149. isc.server_common.tsig_keyring.deinit_keyring()
  1150. def test_guess_remote(self):
  1151. """Test we can guess the remote endpoint when we have only the
  1152. file descriptor. This is needed, because we get only that one
  1153. from auth."""
  1154. # We test with UDP, as it can be "connected" without other
  1155. # endpoint. Note that in the current implementation _guess_remote()
  1156. # unconditionally returns SOCK_STREAM.
  1157. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  1158. sock.connect(('127.0.0.1', 12345))
  1159. self.assertEqual((socket.AF_INET, socket.SOCK_STREAM,
  1160. ('127.0.0.1', 12345)),
  1161. self.unix._guess_remote(sock.fileno()))
  1162. sock.close()
  1163. if socket.has_ipv6:
  1164. # Don't check IPv6 address on hosts not supporting them
  1165. sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
  1166. sock.connect(('::1', 12345))
  1167. self.assertEqual((socket.AF_INET6, socket.SOCK_STREAM,
  1168. ('::1', 12345, 0, 0)),
  1169. self.unix._guess_remote(sock.fileno()))
  1170. sock.close()
  1171. # Try when pretending there's no IPv6 support
  1172. # (No need to pretend when there's really no IPv6)
  1173. xfrout.socket.has_ipv6 = False
  1174. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  1175. sock.connect(('127.0.0.1', 12345))
  1176. self.assertEqual((socket.AF_INET, socket.SOCK_STREAM,
  1177. ('127.0.0.1', 12345)),
  1178. self.unix._guess_remote(sock.fileno()))
  1179. sock.close()
  1180. # Return it back
  1181. xfrout.socket.has_ipv6 = True
  1182. def test_receive_query_message(self):
  1183. send_msg = b"\xd6=\x00\x00\x00\x01\x00"
  1184. msg_len = struct.pack('H', socket.htons(len(send_msg)))
  1185. self.write_sock.send(msg_len)
  1186. self.write_sock.send(send_msg)
  1187. recv_msg = self.unix._receive_query_message(self.read_sock)
  1188. self.assertEqual(recv_msg, send_msg)
  1189. def check_default_ACL(self):
  1190. context = isc.acl.dns.RequestContext(socket.getaddrinfo("127.0.0.1",
  1191. 1234, 0, socket.SOCK_DGRAM,
  1192. socket.IPPROTO_UDP,
  1193. socket.AI_NUMERICHOST)[0][4])
  1194. self.assertEqual(isc.acl.acl.ACCEPT, self.unix._acl.execute(context))
  1195. def check_loaded_ACL(self, acl):
  1196. context = isc.acl.dns.RequestContext(socket.getaddrinfo("127.0.0.1",
  1197. 1234, 0, socket.SOCK_DGRAM,
  1198. socket.IPPROTO_UDP,
  1199. socket.AI_NUMERICHOST)[0][4])
  1200. self.assertEqual(isc.acl.acl.ACCEPT, acl.execute(context))
  1201. context = isc.acl.dns.RequestContext(socket.getaddrinfo("192.0.2.1",
  1202. 1234, 0, socket.SOCK_DGRAM,
  1203. socket.IPPROTO_UDP,
  1204. socket.AI_NUMERICHOST)[0][4])
  1205. self.assertEqual(isc.acl.acl.REJECT, acl.execute(context))
  1206. def test_update_config_data(self):
  1207. self.check_default_ACL()
  1208. self.unix.update_config_data({'transfers_out':10 })
  1209. self.assertEqual(self.unix._max_transfers_out, 10)
  1210. self.check_default_ACL()
  1211. self.unix.update_config_data({'transfers_out':9})
  1212. self.assertEqual(self.unix._max_transfers_out, 9)
  1213. # Load the ACL
  1214. self.unix.update_config_data({'transfer_acl': [{'from': '127.0.0.1',
  1215. 'action': 'ACCEPT'}]})
  1216. self.check_loaded_ACL(self.unix._acl)
  1217. # Pass a wrong data there and check it does not replace the old one
  1218. self.assertRaises(XfroutConfigError,
  1219. self.unix.update_config_data,
  1220. {'transfer_acl': ['Something bad']})
  1221. self.check_loaded_ACL(self.unix._acl)
  1222. def test_zone_config_data(self):
  1223. # By default, there's no specific zone config
  1224. self.assertEqual({}, self.unix._zone_config)
  1225. # Adding config for a specific zone. The config is empty unless
  1226. # explicitly specified.
  1227. self.unix.update_config_data({'zone_config':
  1228. [{'origin': 'example.com',
  1229. 'class': 'IN'}]})
  1230. self.assertEqual({}, self.unix._zone_config[('IN', 'example.com.')])
  1231. # zone class can be omitted
  1232. self.unix.update_config_data({'zone_config':
  1233. [{'origin': 'example.com'}]})
  1234. self.assertEqual({}, self.unix._zone_config[('IN', 'example.com.')])
  1235. # zone class, name are stored in the "normalized" form. class
  1236. # strings are upper cased, names are down cased.
  1237. self.unix.update_config_data({'zone_config':
  1238. [{'origin': 'EXAMPLE.com'}]})
  1239. self.assertEqual({}, self.unix._zone_config[('IN', 'example.com.')])
  1240. # invalid zone class, name will result in exceptions
  1241. self.assertRaises(EmptyLabel,
  1242. self.unix.update_config_data,
  1243. {'zone_config': [{'origin': 'bad..example'}]})
  1244. self.assertRaises(InvalidRRClass,
  1245. self.unix.update_config_data,
  1246. {'zone_config': [{'origin': 'example.com',
  1247. 'class': 'badclass'}]})
  1248. # Configuring a couple of more zones
  1249. self.unix.update_config_data({'zone_config':
  1250. [{'origin': 'example.com'},
  1251. {'origin': 'example.com',
  1252. 'class': 'CH'},
  1253. {'origin': 'example.org'}]})
  1254. self.assertEqual({}, self.unix._zone_config[('IN', 'example.com.')])
  1255. self.assertEqual({}, self.unix._zone_config[('CH', 'example.com.')])
  1256. self.assertEqual({}, self.unix._zone_config[('IN', 'example.org.')])
  1257. # Duplicate data: should be rejected with an exception
  1258. self.assertRaises(XfroutConfigError,
  1259. self.unix.update_config_data,
  1260. {'zone_config': [{'origin': 'example.com'},
  1261. {'origin': 'example.org'},
  1262. {'origin': 'example.com'}]})
  1263. def test_zone_config_data_with_acl(self):
  1264. # Similar to the previous test, but with transfer_acl config
  1265. self.unix.update_config_data({'zone_config':
  1266. [{'origin': 'example.com',
  1267. 'transfer_acl':
  1268. [{'from': '127.0.0.1',
  1269. 'action': 'ACCEPT'}]}]})
  1270. acl = self.unix._zone_config[('IN', 'example.com.')]['transfer_acl']
  1271. self.check_loaded_ACL(acl)
  1272. # invalid ACL syntax will be rejected with exception
  1273. self.assertRaises(XfroutConfigError,
  1274. self.unix.update_config_data,
  1275. {'zone_config': [{'origin': 'example.com',
  1276. 'transfer_acl':
  1277. [{'action': 'BADACTION'}]}]})
  1278. def test_get_db_file(self):
  1279. self.assertEqual(self.unix.get_db_file(), "initdb.file")
  1280. def test_increase_transfers_counter(self):
  1281. self.unix._max_transfers_out = 10
  1282. count = self.unix._transfers_counter
  1283. self.assertEqual(self.unix.increase_transfers_counter(), True)
  1284. self.assertEqual(count + 1, self.unix._transfers_counter)
  1285. self.unix._max_transfers_out = 0
  1286. count = self.unix._transfers_counter
  1287. self.assertEqual(self.unix.increase_transfers_counter(), False)
  1288. self.assertEqual(count, self.unix._transfers_counter)
  1289. def test_decrease_transfers_counter(self):
  1290. count = self.unix._transfers_counter
  1291. self.unix.decrease_transfers_counter()
  1292. self.assertEqual(count - 1, self.unix._transfers_counter)
  1293. def _remove_file(self, sock_file):
  1294. try:
  1295. os.remove(sock_file)
  1296. except OSError:
  1297. pass
  1298. def test_sock_file_in_use_file_exist(self):
  1299. sock_file = 'temp.sock.file'
  1300. self._remove_file(sock_file)
  1301. self.assertFalse(self.unix._sock_file_in_use(sock_file))
  1302. self.assertFalse(os.path.exists(sock_file))
  1303. def test_sock_file_in_use_file_not_exist(self):
  1304. self.assertFalse(self.unix._sock_file_in_use('temp.sock.file'))
  1305. def _start_unix_sock_server(self, sock_file):
  1306. serv = ThreadingUnixStreamServer(sock_file, BaseRequestHandler)
  1307. serv_thread = threading.Thread(target=serv.serve_forever)
  1308. serv_thread.setDaemon(True)
  1309. serv_thread.start()
  1310. def test_sock_file_in_use(self):
  1311. sock_file = 'temp.sock.file'
  1312. self._remove_file(sock_file)
  1313. self.assertFalse(self.unix._sock_file_in_use(sock_file))
  1314. self._start_unix_sock_server(sock_file)
  1315. self.assertTrue(self.unix._sock_file_in_use(sock_file))
  1316. def test_remove_unused_sock_file_in_use(self):
  1317. sock_file = 'temp.sock.file'
  1318. self._remove_file(sock_file)
  1319. self.assertFalse(self.unix._sock_file_in_use(sock_file))
  1320. self._start_unix_sock_server(sock_file)
  1321. try:
  1322. self.unix._remove_unused_sock_file(sock_file)
  1323. except SystemExit:
  1324. pass
  1325. else:
  1326. # This should never happen
  1327. self.assertTrue(False)
  1328. def test_remove_unused_sock_file_dir(self):
  1329. import tempfile
  1330. dir_name = tempfile.mkdtemp()
  1331. old_stdout = sys.stdout
  1332. sys.stdout = open(os.devnull, 'w')
  1333. try:
  1334. self.unix._remove_unused_sock_file(dir_name)
  1335. except SystemExit:
  1336. pass
  1337. else:
  1338. # This should never happen
  1339. self.assertTrue(False)
  1340. sys.stdout.close()
  1341. sys.stdout = old_stdout
  1342. os.rmdir(dir_name)
  1343. def __fake_select(self, r, w, e):
  1344. '''select emulator used in select_loop_fail test.'''
  1345. # This simplified faked function assumes to be called at most once,
  1346. # and in that case just return a pre-configured "readable" sockets.
  1347. if self.__select_count > 0:
  1348. raise RuntimeError('select called unexpected number of times')
  1349. self.__select_count += 1
  1350. return (self.__select_return_redable, [], [])
  1351. def test_select_loop_fail(self):
  1352. '''Check failure events in the main loop.'''
  1353. # setup faked select() environments
  1354. self.unix._read_sock = MySocket(socket.AF_INET6, socket.SOCK_STREAM)
  1355. xfrout.select.select = self.__fake_select
  1356. self.__select_return_redable = [MySocket(socket.AF_INET6,
  1357. socket.SOCK_STREAM)]
  1358. # Check that loop terminates if recv_fd() fails.
  1359. for ret_code in [-1, FD_SYSTEM_ERROR]:
  1360. # fake recv_fd so it returns the faked failure code.
  1361. xfrout.recv_fd = lambda fileno: ret_code
  1362. # reset the counter, go to the loop.
  1363. self.__select_count = 0
  1364. self.unix._select_loop(self.__select_return_redable[0])
  1365. # select should have been called exactly once.
  1366. self.assertEqual(1, self.__select_count)
  1367. # Next, we test the case where recf_fd succeeds but receiving the
  1368. # request fails.
  1369. self.__select_count = 0
  1370. xfrout.recv_fd = lambda fileno: 1
  1371. self.unix._receive_query_message = lambda fd: None
  1372. self.unix._select_loop(self.__select_return_redable[0])
  1373. self.assertEqual(1, self.__select_count)
  1374. class TestInitialization(unittest.TestCase):
  1375. def setEnv(self, name, value):
  1376. if value is None:
  1377. if name in os.environ:
  1378. del os.environ[name]
  1379. else:
  1380. os.environ[name] = value
  1381. def setUp(self):
  1382. self._oldSocket = os.getenv("BIND10_XFROUT_SOCKET_FILE")
  1383. self._oldFromBuild = os.getenv("B10_FROM_BUILD")
  1384. def tearDown(self):
  1385. self.setEnv("B10_FROM_BUILD", self._oldFromBuild)
  1386. self.setEnv("BIND10_XFROUT_SOCKET_FILE", self._oldSocket)
  1387. # Make sure even the computed values are back
  1388. xfrout.init_paths()
  1389. def testNoEnv(self):
  1390. self.setEnv("B10_FROM_BUILD", None)
  1391. self.setEnv("BIND10_XFROUT_SOCKET_FILE", None)
  1392. xfrout.init_paths()
  1393. self.assertEqual(xfrout.UNIX_SOCKET_FILE,
  1394. "@@LOCALSTATEDIR@@/@PACKAGE_NAME@/auth_xfrout_conn")
  1395. def testProvidedSocket(self):
  1396. self.setEnv("B10_FROM_BUILD", None)
  1397. self.setEnv("BIND10_XFROUT_SOCKET_FILE", "The/Socket/File")
  1398. xfrout.init_paths()
  1399. self.assertEqual(xfrout.UNIX_SOCKET_FILE, "The/Socket/File")
  1400. class MyNotifier():
  1401. def __init__(self):
  1402. self.shutdown_called = False
  1403. def shutdown(self):
  1404. self.shutdown_called = True
  1405. class MyXfroutServer(XfroutServer):
  1406. def __init__(self):
  1407. self._cc = MockModuleCCSession()
  1408. self._shutdown_event = threading.Event()
  1409. self._notifier = MyNotifier()
  1410. self._unix_socket_server = None
  1411. # Disable the wait for threads
  1412. self._wait_for_threads = lambda : None
  1413. self._cc.get_module_spec = lambda:\
  1414. isc.config.module_spec_from_file(xfrout.SPECFILE_LOCATION)
  1415. # setup an XfroutCount object
  1416. self._counter = XfroutCounter(
  1417. self._cc.get_module_spec().get_statistics_spec())
  1418. class TestXfroutCounter(unittest.TestCase):
  1419. def setUp(self):
  1420. self._module_spec = isc.config.module_spec_from_file(\
  1421. xfrout.SPECFILE_LOCATION)
  1422. statistics_spec = self._module_spec.get_statistics_spec()
  1423. self.xfrout_counter = XfroutCounter(statistics_spec)
  1424. self._counters = isc.config.spec_name_list(\
  1425. isc.config.find_spec_part(\
  1426. statistics_spec, XfroutCounter.perzone_prefix)\
  1427. ['named_set_item_spec']['map_item_spec'])
  1428. self._started = threading.Event()
  1429. self._number = 3 # number of the threads
  1430. self._cycle = 10000 # number of counting per thread
  1431. def test_get_default_statistics_data(self):
  1432. self.assertTrue(\
  1433. self._module_spec.validate_statistics(\
  1434. True,
  1435. self.xfrout_counter._get_default_statistics_data(),
  1436. )
  1437. )
  1438. def setup_incrementer(self, incrementer, *args):
  1439. self._started.wait()
  1440. for i in range(self._cycle): incrementer(*args)
  1441. def start_incrementer(self, incrementer, *args):
  1442. threads = []
  1443. for i in range(self._number):
  1444. threads.append(threading.Thread(\
  1445. target=self.setup_incrementer, \
  1446. args=(incrementer,) + args \
  1447. ))
  1448. for th in threads: th.start()
  1449. self._started.set()
  1450. for th in threads: th.join()
  1451. def get_count(self, zone_name, counter_name):
  1452. return isc.cc.data.find(\
  1453. self.xfrout_counter.get_statistics(),\
  1454. '%s/%s/%s' % (XfroutCounter.perzone_prefix,\
  1455. zone_name, counter_name))
  1456. def test_xxcrementers(self):
  1457. # for per-zone counters
  1458. result = { XfroutCounter.entire_server: {},
  1459. TEST_ZONE_NAME_STR: {} }
  1460. for counter_name in self._counters:
  1461. incrementer = \
  1462. dict(self.xfrout_counter.get_counters_for_xfroutsession(), \
  1463. **self.xfrout_counter.get_counters_for_notifyout())\
  1464. ['counter_%s' % counter_name]
  1465. self.start_incrementer(incrementer, TEST_ZONE_NAME_STR)
  1466. self.assertEqual(self.get_count(\
  1467. TEST_ZONE_NAME_STR, counter_name), \
  1468. self._number * self._cycle)
  1469. self.assertEqual(self.get_count(\
  1470. XfroutCounter.entire_server, counter_name), \
  1471. self._number * self._cycle)
  1472. result[XfroutCounter.entire_server][counter_name] = \
  1473. result[TEST_ZONE_NAME_STR][counter_name] = \
  1474. self._number * self._cycle
  1475. statistics_data = {XfroutCounter.perzone_prefix: result}
  1476. # for {a|i}xfrrunning counters
  1477. for counter_name in self.xfrout_counter._xfrrunning_names:
  1478. incrementer = \
  1479. dict(self.xfrout_counter.get_counters_for_xfroutsession(), \
  1480. **self.xfrout_counter.get_counters_for_notifyout())\
  1481. ['inc_%s' % counter_name]
  1482. self.start_incrementer(incrementer)
  1483. self.assertEqual(
  1484. self.xfrout_counter.get_statistics()[counter_name],
  1485. self._number * self._cycle
  1486. )
  1487. decrementer = \
  1488. dict(self.xfrout_counter.get_counters_for_xfroutsession(), \
  1489. **self.xfrout_counter.get_counters_for_notifyout())\
  1490. ['dec_%s' % counter_name]
  1491. self.start_incrementer(decrementer)
  1492. self.assertEqual(
  1493. self.xfrout_counter.get_statistics()[counter_name],
  1494. 0)
  1495. statistics_data[counter_name] = 0
  1496. self.assertEqual(
  1497. self.xfrout_counter.get_statistics(),
  1498. statistics_data)
  1499. self.assertTrue(\
  1500. self._module_spec.validate_statistics(\
  1501. True, statistics_data
  1502. )
  1503. )
  1504. def test_add_perzone_counter(self):
  1505. for counter_name in self._counters:
  1506. self.assertRaises(isc.cc.data.DataNotFoundError,\
  1507. self.get_count, TEST_ZONE_NAME_STR, counter_name)
  1508. self.xfrout_counter._add_perzone_counter(TEST_ZONE_NAME_STR)
  1509. for counter_name in self._counters:
  1510. self.assertEqual(self.get_count(TEST_ZONE_NAME_STR, counter_name), 0)
  1511. class TestXfroutServer(unittest.TestCase):
  1512. def setUp(self):
  1513. self.xfrout_server = MyXfroutServer()
  1514. def test_shutdown(self):
  1515. self.xfrout_server.shutdown()
  1516. self.assertTrue(self.xfrout_server._notifier.shutdown_called)
  1517. self.assertTrue(self.xfrout_server._cc.stopped)
  1518. def test_getstats(self):
  1519. self.assertEqual(
  1520. self.xfrout_server.command_handler('getstats', None), \
  1521. create_answer(0, {}))
  1522. if __name__== "__main__":
  1523. isc.log.resetUnitTestRootLogger()
  1524. unittest.main()