xfrout_test.py.in 77 KB

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