xfrout_test.py.in 76 KB

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