test_firewall.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. import logging
  2. import operator
  3. from unittest import TestCase
  4. from unittest.mock import patch
  5. import qubesagent.firewall
  6. class DummyIptablesRestore(object):
  7. # pylint: disable=too-few-public-methods
  8. def __init__(self, worker_mock, family):
  9. self._worker_mock = worker_mock
  10. self._family = family
  11. self.returncode = 0
  12. def communicate(self, stdin=None):
  13. self._worker_mock.loaded_iptables[self._family] = stdin.decode()
  14. return ("", None)
  15. class DummyQubesDB(object):
  16. def __init__(self, worker_mock):
  17. self._worker_mock = worker_mock
  18. self.entries = {}
  19. self.pending_watches = []
  20. def read(self, key):
  21. try:
  22. return self.entries[key]
  23. except KeyError:
  24. return None
  25. def multiread(self, prefix):
  26. result = {}
  27. for key, value in self.entries.items():
  28. if key.startswith(prefix):
  29. result[key] = value
  30. return result
  31. def list(self, prefix):
  32. result = []
  33. for key in self.entries.keys():
  34. if key.startswith(prefix):
  35. result.append(key)
  36. return result
  37. def watch(self, path):
  38. pass
  39. def read_watch(self):
  40. try:
  41. return self.pending_watches.pop(0)
  42. except IndexError:
  43. return None
  44. class FirewallWorker(qubesagent.firewall.FirewallWorker):
  45. def __init__(self):
  46. # pylint: disable=super-init-not-called
  47. # don't call super on purpose - avoid connecting to QubesDB
  48. # super(FirewallWorker, self).__init__()
  49. self.qdb = DummyQubesDB(self)
  50. self.log = logging.getLogger('qubes.tests')
  51. self.init_called = False
  52. self.cleanup_called = False
  53. self.user_script_called = False
  54. self.update_connected_ips_called_with = []
  55. self.rules = {}
  56. def apply_rules(self, source_addr, rules):
  57. self.rules[source_addr] = rules
  58. def cleanup(self):
  59. self.init_called = True
  60. def init(self):
  61. self.cleanup_called = True
  62. def run_user_script(self):
  63. self.user_script_called = True
  64. def update_connected_ips(self, family):
  65. self.update_connected_ips_called_with.append(family)
  66. class IptablesWorker(qubesagent.firewall.IptablesWorker):
  67. '''Override methods actually modifying system state to only log what
  68. would be done'''
  69. def __init__(self):
  70. # pylint: disable=super-init-not-called
  71. # don't call super on purpose - avoid connecting to QubesDB
  72. # super(IptablesWorker, self).__init__()
  73. # copied __init__:
  74. self.qdb = DummyQubesDB(self)
  75. self.log = logging.getLogger('qubes.tests')
  76. self.chains = {
  77. 4: set(),
  78. 6: set(),
  79. }
  80. #: instead of really running `iptables`, log what would be called
  81. self.called_commands = {
  82. 4: [],
  83. 6: [],
  84. }
  85. #: rules that would be loaded with `iptables-restore`
  86. self.loaded_iptables = {
  87. 4: None,
  88. 6: None,
  89. }
  90. def run_ipt(self, family, args, **kwargs):
  91. self.called_commands[family].append(args)
  92. def run_ipt_restore(self, family, args):
  93. return DummyIptablesRestore(self, family)
  94. @staticmethod
  95. def dns_addresses(family=None):
  96. if family == 4:
  97. return ['1.1.1.1', '2.2.2.2']
  98. else:
  99. return ['2001::1', '2001::2']
  100. class NftablesWorker(qubesagent.firewall.NftablesWorker):
  101. '''Override methods actually modifying system state to only log what
  102. would be done'''
  103. def __init__(self):
  104. # pylint: disable=super-init-not-called
  105. # don't call super on purpose - avoid connecting to QubesDB
  106. # super(IptablesWorker, self).__init__()
  107. # copied __init__:
  108. self.qdb = DummyQubesDB(self)
  109. self.log = logging.getLogger('qubes.tests')
  110. self.chains = {
  111. 4: set(),
  112. 6: set(),
  113. }
  114. #: instead of really running `nft`, log what would be loaded
  115. #: rules that would be loaded with `nft`
  116. self.loaded_rules = []
  117. def run_nft(self, nft_input):
  118. self.loaded_rules.append(nft_input)
  119. @staticmethod
  120. def dns_addresses(family=None):
  121. if family == 4:
  122. return ['1.1.1.1', '2.2.2.2']
  123. else:
  124. return ['2001::1', '2001::2']
  125. class TestIptablesWorker(TestCase):
  126. def setUp(self):
  127. super(TestIptablesWorker, self).setUp()
  128. self.obj = IptablesWorker()
  129. self.subprocess_patch = patch('subprocess.call')
  130. self.subprocess_mock = self.subprocess_patch.start()
  131. def tearDown(self):
  132. self.subprocess_patch.stop()
  133. def test_000_chain_for_addr(self):
  134. self.assertEqual(
  135. self.obj.chain_for_addr('10.137.0.1'), 'qbs-10-137-0-1')
  136. self.assertEqual(
  137. self.obj.chain_for_addr('fd09:24ef:4179:0000::3'),
  138. 'qbs-09-24ef-4179-0000--3')
  139. def test_001_create_chain(self):
  140. testdata = [
  141. (4, '10.137.0.1', 'qbs-10-137-0-1'),
  142. (6, 'fd09:24ef:4179:0000::3', 'qbs-fd09-24ef-4179-0000--3')
  143. ]
  144. for family, addr, chain in testdata:
  145. self.obj.create_chain(addr, chain, family)
  146. self.assertEqual(self.obj.called_commands[family],
  147. [['-N', chain],
  148. ['-I', 'QBS-FORWARD', '-s', addr, '-j', chain]])
  149. def test_002_prepare_rules4(self):
  150. rules = [
  151. {'action': 'accept', 'proto': 'tcp',
  152. 'dstports': '80-80', 'dst4': '1.2.3.0/24'},
  153. {'action': 'accept', 'proto': 'udp',
  154. 'dstports': '443-1024', 'dsthost': 'yum.qubes-os.org'},
  155. {'action': 'accept', 'specialtarget': 'dns'},
  156. {'action': 'drop', 'proto': 'udp', 'specialtarget': 'dns'},
  157. {'action': 'drop', 'proto': 'icmp'},
  158. {'action': 'drop'},
  159. ]
  160. expected_iptables = (
  161. "*filter\n"
  162. "-A chain -d 1.2.3.0/24 -p tcp --dport 80:80 -j ACCEPT\n"
  163. "-A chain -d 147.75.32.69/32 -p udp --dport 443:1024 -j ACCEPT\n"
  164. "-A chain -d 1.1.1.1/32 -p tcp --dport 53:53 -j ACCEPT\n"
  165. "-A chain -d 2.2.2.2/32 -p tcp --dport 53:53 -j ACCEPT\n"
  166. "-A chain -d 1.1.1.1/32 -p udp --dport 53:53 -j ACCEPT\n"
  167. "-A chain -d 2.2.2.2/32 -p udp --dport 53:53 -j ACCEPT\n"
  168. "-A chain -d 1.1.1.1/32 -p udp --dport 53:53 -j REJECT "
  169. "--reject-with icmp-admin-prohibited\n"
  170. "-A chain -d 2.2.2.2/32 -p udp --dport 53:53 -j REJECT "
  171. "--reject-with icmp-admin-prohibited\n"
  172. "-A chain -p icmp -j REJECT "
  173. "--reject-with icmp-admin-prohibited\n"
  174. "-A chain -j REJECT "
  175. "--reject-with icmp-admin-prohibited\n"
  176. "COMMIT\n"
  177. )
  178. self.assertEqual(self.obj.prepare_rules('chain', rules, 4),
  179. expected_iptables)
  180. with self.assertRaises(qubesagent.firewall.RuleParseError):
  181. self.obj.prepare_rules('chain', [{'unknown': 'xxx'}], 4)
  182. with self.assertRaises(qubesagent.firewall.RuleParseError):
  183. self.obj.prepare_rules('chain', [{'dst6': 'a::b'}], 4)
  184. with self.assertRaises(qubesagent.firewall.RuleParseError):
  185. self.obj.prepare_rules('chain', [{'dst4': '3.3.3.3'}], 6)
  186. def test_003_prepare_rules6(self):
  187. rules = [
  188. {'action': 'accept', 'proto': 'tcp',
  189. 'dstports': '80-80', 'dst6': 'a::b/128'},
  190. {'action': 'accept', 'proto': 'tcp',
  191. 'dsthost': 'ripe.net'},
  192. {'action': 'accept', 'specialtarget': 'dns'},
  193. {'action': 'drop', 'proto': 'udp', 'specialtarget': 'dns'},
  194. {'action': 'drop', 'proto': 'icmp'},
  195. {'action': 'drop'},
  196. ]
  197. expected_iptables = (
  198. "*filter\n"
  199. "-A chain -d a::b/128 -p tcp --dport 80:80 -j ACCEPT\n"
  200. "-A chain -d 2001:67c:2e8:22::c100:68b/128 -p tcp -j ACCEPT\n"
  201. "-A chain -d 2001::1/128 -p tcp --dport 53:53 -j ACCEPT\n"
  202. "-A chain -d 2001::2/128 -p tcp --dport 53:53 -j ACCEPT\n"
  203. "-A chain -d 2001::1/128 -p udp --dport 53:53 -j ACCEPT\n"
  204. "-A chain -d 2001::2/128 -p udp --dport 53:53 -j ACCEPT\n"
  205. "-A chain -d 2001::1/128 -p udp --dport 53:53 -j REJECT "
  206. "--reject-with icmp6-adm-prohibited\n"
  207. "-A chain -d 2001::2/128 -p udp --dport 53:53 -j REJECT "
  208. "--reject-with icmp6-adm-prohibited\n"
  209. "-A chain -p icmpv6 -j REJECT "
  210. "--reject-with icmp6-adm-prohibited\n"
  211. "-A chain -j REJECT "
  212. "--reject-with icmp6-adm-prohibited\n"
  213. "COMMIT\n"
  214. )
  215. self.assertEqual(self.obj.prepare_rules('chain', rules, 6),
  216. expected_iptables)
  217. def test_004_apply_rules4(self):
  218. rules = [{'action': 'accept'}]
  219. chain = 'qbs-10-137-0-1'
  220. self.obj.apply_rules('10.137.0.1', rules)
  221. self.assertEqual(self.obj.called_commands[4],
  222. [
  223. ['-N', chain],
  224. ['-I', 'QBS-FORWARD', '-s', '10.137.0.1', '-j', chain],
  225. ['-F', chain]])
  226. self.assertEqual(self.obj.loaded_iptables[4],
  227. self.obj.prepare_rules(chain, rules, 4))
  228. self.assertEqual(self.obj.called_commands[6], [])
  229. self.assertIsNone(self.obj.loaded_iptables[6])
  230. def test_005_apply_rules6(self):
  231. rules = [{'action': 'accept'}]
  232. chain = 'qbs-2000--a'
  233. self.obj.apply_rules('2000::a', rules)
  234. self.assertEqual(self.obj.called_commands[6],
  235. [
  236. ['-N', chain],
  237. ['-I', 'QBS-FORWARD', '-s', '2000::a', '-j', chain],
  238. ['-F', chain]])
  239. self.assertEqual(self.obj.loaded_iptables[6],
  240. self.obj.prepare_rules(chain, rules, 6))
  241. self.assertEqual(self.obj.called_commands[4], [])
  242. self.assertIsNone(self.obj.loaded_iptables[4])
  243. def test_006_init(self):
  244. self.obj.init()
  245. self.assertEqual(self.obj.called_commands[4], [
  246. ['-F', 'QBS-FORWARD'],
  247. ['-A', 'QBS-FORWARD', '!', '-i', 'vif+', '-j', 'RETURN'],
  248. ['-A', 'QBS-FORWARD', '-j', 'DROP'],
  249. ['-t', 'mangle', '-F', 'QBS-PREROUTING'],
  250. ['-t', 'mangle', '-F', 'QBS-POSTROUTING'],
  251. ])
  252. self.assertEqual(self.obj.called_commands[6], [
  253. ['-F', 'QBS-FORWARD'],
  254. ['-A', 'QBS-FORWARD', '!', '-i', 'vif+', '-j', 'RETURN'],
  255. ['-A', 'QBS-FORWARD', '-j', 'DROP'],
  256. ['-t', 'mangle', '-F', 'QBS-PREROUTING'],
  257. ['-t', 'mangle', '-F', 'QBS-POSTROUTING'],
  258. ])
  259. def test_007_cleanup(self):
  260. self.obj.init()
  261. self.obj.create_chain('1.2.3.4', 'chain-ip4-1', 4)
  262. self.obj.create_chain('1.2.3.6', 'chain-ip4-2', 4)
  263. self.obj.create_chain('2000::1', 'chain-ip6-1', 6)
  264. self.obj.create_chain('2000::2', 'chain-ip6-2', 6)
  265. # forget about commands called earlier
  266. self.obj.called_commands[4] = []
  267. self.obj.called_commands[6] = []
  268. self.obj.cleanup()
  269. self.assertEqual([self.obj.called_commands[4][0]] +
  270. sorted(self.obj.called_commands[4][1:], key=operator.itemgetter(1)),
  271. [
  272. ['-F', 'QBS-FORWARD'],
  273. ['-F', 'chain-ip4-1'],
  274. ['-X', 'chain-ip4-1'],
  275. ['-F', 'chain-ip4-2'],
  276. ['-X', 'chain-ip4-2'],
  277. ['-t', 'mangle', '-F', 'QBS-PREROUTING'],
  278. ['-t', 'mangle', '-F', 'QBS-POSTROUTING'],
  279. ])
  280. self.assertEqual([self.obj.called_commands[6][0]] +
  281. sorted(self.obj.called_commands[6][1:], key=operator.itemgetter(1)),
  282. [
  283. ['-F', 'QBS-FORWARD'],
  284. ['-F', 'chain-ip6-1'],
  285. ['-X', 'chain-ip6-1'],
  286. ['-F', 'chain-ip6-2'],
  287. ['-X', 'chain-ip6-2'],
  288. ['-t', 'mangle', '-F', 'QBS-PREROUTING'],
  289. ['-t', 'mangle', '-F', 'QBS-POSTROUTING'],
  290. ])
  291. class TestNftablesWorker(TestCase):
  292. def setUp(self):
  293. super(TestNftablesWorker, self).setUp()
  294. self.obj = NftablesWorker()
  295. self.subprocess_patch = patch('subprocess.call')
  296. self.subprocess_mock = self.subprocess_patch.start()
  297. def tearDown(self):
  298. self.subprocess_patch.stop()
  299. def test_000_chain_for_addr(self):
  300. self.assertEqual(
  301. self.obj.chain_for_addr('10.137.0.1'), 'qbs-10-137-0-1')
  302. self.assertEqual(
  303. self.obj.chain_for_addr('fd09:24ef:4179:0000::3'),
  304. 'qbs-fd09-24ef-4179-0000--3')
  305. def expected_create_chain(self, family, addr, chain):
  306. return (
  307. 'table {family} qubes-firewall {{\n'
  308. ' chain {chain} {{\n'
  309. ' }}\n'
  310. ' chain forward {{\n'
  311. ' {family} saddr {addr} jump {chain}\n'
  312. ' }}\n'
  313. '}}\n'.format(family=family, addr=addr, chain=chain))
  314. def test_001_create_chain(self):
  315. testdata = [
  316. (4, '10.137.0.1', 'qbs-10-137-0-1'),
  317. (6, 'fd09:24ef:4179:0000::3', 'qbs-fd09-24ef-4179-0000--3')
  318. ]
  319. for family, addr, chain in testdata:
  320. self.obj.create_chain(addr, chain, family)
  321. self.assertEqual(self.obj.loaded_rules,
  322. [self.expected_create_chain('ip', '10.137.0.1', 'qbs-10-137-0-1'),
  323. self.expected_create_chain(
  324. 'ip6', 'fd09:24ef:4179:0000::3', 'qbs-fd09-24ef-4179-0000--3'),
  325. ])
  326. def test_002_prepare_rules4(self):
  327. rules = [
  328. {'action': 'accept', 'proto': 'tcp',
  329. 'dstports': '80-80', 'dst4': '1.2.3.0/24'},
  330. {'action': 'accept', 'proto': 'udp',
  331. 'dstports': '443-1024', 'dsthost': 'yum.qubes-os.org'},
  332. {'action': 'accept', 'specialtarget': 'dns'},
  333. {'action': 'drop', 'proto': 'udp', 'specialtarget': 'dns'},
  334. {'action': 'drop', 'proto': 'icmp'},
  335. {'action': 'drop'},
  336. ]
  337. expected_nft = (
  338. 'flush chain ip qubes-firewall chain\n'
  339. 'table ip qubes-firewall {\n'
  340. ' chain chain {\n'
  341. ' ip protocol tcp ip daddr 1.2.3.0/24 tcp dport 80 accept\n'
  342. ' ip protocol udp ip daddr { 147.75.32.69/32 } '
  343. 'udp dport 443-1024 accept\n'
  344. ' ip daddr { 1.1.1.1/32, 2.2.2.2/32 } tcp dport 53 accept\n'
  345. ' ip daddr { 1.1.1.1/32, 2.2.2.2/32 } udp dport 53 accept\n'
  346. ' ip protocol udp ip daddr { 1.1.1.1/32, 2.2.2.2/32 } udp dport '
  347. '53 reject with icmp type admin-prohibited\n'
  348. ' ip protocol icmp reject with icmp type admin-prohibited\n'
  349. ' reject with icmp type admin-prohibited\n'
  350. ' }\n'
  351. '}\n'
  352. )
  353. self.assertEqual(self.obj.prepare_rules('chain', rules, 4),
  354. expected_nft)
  355. with self.assertRaises(qubesagent.firewall.RuleParseError):
  356. self.obj.prepare_rules('chain', [{'unknown': 'xxx'}], 4)
  357. with self.assertRaises(qubesagent.firewall.RuleParseError):
  358. self.obj.prepare_rules('chain', [{'dst6': 'a::b'}], 4)
  359. with self.assertRaises(qubesagent.firewall.RuleParseError):
  360. self.obj.prepare_rules('chain', [{'dst4': '3.3.3.3'}], 6)
  361. def test_003_prepare_rules6(self):
  362. rules = [
  363. {'action': 'accept', 'proto': 'tcp',
  364. 'dstports': '80-80', 'dst6': 'a::b/128'},
  365. {'action': 'accept', 'proto': 'tcp',
  366. 'dsthost': 'ripe.net'},
  367. {'action': 'accept', 'specialtarget': 'dns'},
  368. {'action': 'drop', 'proto': 'udp', 'specialtarget': 'dns'},
  369. {'action': 'drop', 'proto': 'icmp', 'icmptype': '128'},
  370. {'action': 'drop'},
  371. ]
  372. expected_nft = (
  373. 'flush chain ip6 qubes-firewall chain\n'
  374. 'table ip6 qubes-firewall {\n'
  375. ' chain chain {\n'
  376. ' ip6 nexthdr tcp ip6 daddr a::b/128 tcp dport 80 accept\n'
  377. ' ip6 nexthdr tcp ip6 daddr { 2001:67c:2e8:22::c100:68b/128 } '
  378. 'accept\n'
  379. ' ip6 daddr { 2001::1/128, 2001::2/128 } tcp dport 53 accept\n'
  380. ' ip6 daddr { 2001::1/128, 2001::2/128 } udp dport 53 accept\n'
  381. ' ip6 nexthdr udp ip6 daddr { 2001::1/128, 2001::2/128 } '
  382. 'udp dport 53 reject with icmpv6 type admin-prohibited\n'
  383. ' ip6 nexthdr icmpv6 icmpv6 type 128 reject with icmpv6 type '
  384. 'admin-prohibited\n'
  385. ' reject with icmpv6 type admin-prohibited\n'
  386. ' }\n'
  387. '}\n'
  388. )
  389. self.assertEqual(self.obj.prepare_rules('chain', rules, 6),
  390. expected_nft)
  391. def test_004_apply_rules4(self):
  392. rules = [{'action': 'accept'}]
  393. chain = 'qbs-10-137-0-1'
  394. self.obj.apply_rules('10.137.0.1', rules)
  395. self.assertEqual(self.obj.loaded_rules,
  396. [self.expected_create_chain('ip', '10.137.0.1', chain),
  397. self.obj.prepare_rules(chain, rules, 4),
  398. ])
  399. def test_005_apply_rules6(self):
  400. rules = [{'action': 'accept'}]
  401. chain = 'qbs-2000--a'
  402. self.obj.apply_rules('2000::a', rules)
  403. self.assertEqual(self.obj.loaded_rules,
  404. [self.expected_create_chain('ip6', '2000::a', chain),
  405. self.obj.prepare_rules(chain, rules, 6),
  406. ])
  407. def test_006_init(self):
  408. self.obj.init()
  409. self.assertEqual(self.obj.loaded_rules,
  410. [
  411. 'table ip qubes-firewall {\n'
  412. ' chain forward {\n'
  413. ' type filter hook forward priority 0;\n'
  414. ' policy drop;\n'
  415. ' ct state established,related accept\n'
  416. ' meta iifname != "vif*" accept\n'
  417. ' }\n'
  418. ' chain prerouting {\n'
  419. ' type filter hook prerouting priority 0;\n'
  420. ' policy accept;\n'
  421. ' }\n'
  422. ' chain postrouting {\n'
  423. ' type filter hook postrouting priority 0;\n'
  424. ' policy accept;\n'
  425. ' }\n'
  426. '}\n'
  427. 'table ip6 qubes-firewall {\n'
  428. ' chain forward {\n'
  429. ' type filter hook forward priority 0;\n'
  430. ' policy drop;\n'
  431. ' ct state established,related accept\n'
  432. ' meta iifname != "vif*" accept\n'
  433. ' }\n'
  434. ' chain prerouting {\n'
  435. ' type filter hook prerouting priority 0;\n'
  436. ' policy accept;\n'
  437. ' }\n'
  438. ' chain postrouting {\n'
  439. ' type filter hook postrouting priority 0;\n'
  440. ' policy accept;\n'
  441. ' }\n'
  442. '}\n'
  443. ])
  444. def test_007_cleanup(self):
  445. self.obj.init()
  446. self.obj.create_chain('1.2.3.4', 'chain-ip4-1', 4)
  447. self.obj.create_chain('1.2.3.6', 'chain-ip4-2', 4)
  448. self.obj.create_chain('2000::1', 'chain-ip6-1', 6)
  449. self.obj.create_chain('2000::2', 'chain-ip6-2', 6)
  450. # forget about commands called earlier
  451. self.obj.loaded_rules = []
  452. self.obj.cleanup()
  453. self.assertEqual(self.obj.loaded_rules,
  454. ['delete table ip qubes-firewall\n'
  455. 'delete table ip6 qubes-firewall\n',
  456. ])
  457. class TestFirewallWorker(TestCase):
  458. def setUp(self):
  459. self.obj = FirewallWorker()
  460. rules = {
  461. '10.137.0.1': {
  462. 'policy': b'accept',
  463. '0000': b'proto=tcp dstports=80-80 action=drop',
  464. '0001': b'proto=udp specialtarget=dns action=accept',
  465. '0002': b'proto=udp action=drop',
  466. },
  467. '10.137.0.2': {'policy': b'accept'},
  468. # no policy
  469. '10.137.0.3': {'0000': b'proto=tcp action=accept'},
  470. # no action
  471. '10.137.0.4': {
  472. 'policy': b'drop',
  473. '0000': b'proto=tcp'
  474. },
  475. }
  476. for addr, entries in rules.items():
  477. for key, value in entries.items():
  478. self.obj.qdb.entries[
  479. '/qubes-firewall/{}/{}'.format(addr, key)] = value
  480. self.subprocess_patch = patch('subprocess.call')
  481. self.subprocess_mock = self.subprocess_patch.start()
  482. def tearDown(self):
  483. self.subprocess_patch.stop()
  484. def test_read_rules(self):
  485. expected_rules1 = [
  486. {'proto': 'tcp', 'dstports': '80-80', 'action': 'drop'},
  487. {'proto': 'udp', 'specialtarget': 'dns', 'action': 'accept'},
  488. {'proto': 'udp', 'action': 'drop'},
  489. {'action': 'accept'},
  490. ]
  491. expected_rules2 = [
  492. {'action': 'accept'},
  493. ]
  494. self.assertEqual(self.obj.read_rules('10.137.0.1'), expected_rules1)
  495. self.assertEqual(self.obj.read_rules('10.137.0.2'), expected_rules2)
  496. with self.assertRaises(qubesagent.firewall.RuleParseError):
  497. self.obj.read_rules('10.137.0.3')
  498. with self.assertRaises(qubesagent.firewall.RuleParseError):
  499. self.obj.read_rules('10.137.0.4')
  500. def test_list_targets(self):
  501. self.assertEqual(self.obj.list_targets(), set(['10.137.0.{}'.format(x)
  502. for x in range(1, 5)]))
  503. def test_is_ip6(self):
  504. self.assertTrue(self.obj.is_ip6('2000::abcd'))
  505. self.assertTrue(self.obj.is_ip6('2000:1:2:3:4:5:6:abcd'))
  506. self.assertFalse(self.obj.is_ip6('10.137.0.1'))
  507. def test_handle_addr(self):
  508. self.obj.handle_addr('10.137.0.2')
  509. self.assertEqual(self.obj.rules['10.137.0.2'], [{'action': 'accept'}])
  510. # fallback to block all
  511. self.obj.handle_addr('10.137.0.3')
  512. self.assertEqual(self.obj.rules['10.137.0.3'], [{'action': 'drop'}])
  513. self.obj.handle_addr('10.137.0.4')
  514. self.assertEqual(self.obj.rules['10.137.0.4'], [{'action': 'drop'}])
  515. @patch('os.path.isfile')
  516. @patch('os.access')
  517. @patch('subprocess.call')
  518. def test_run_user_script(self, mock_subprocess, mock_os_access,
  519. mock_os_path_isfile):
  520. mock_os_path_isfile.return_value = False
  521. mock_os_access.return_value = False
  522. super(FirewallWorker, self.obj).run_user_script()
  523. self.assertFalse(mock_subprocess.called)
  524. mock_os_path_isfile.return_value = True
  525. mock_os_access.return_value = False
  526. super(FirewallWorker, self.obj).run_user_script()
  527. self.assertFalse(mock_subprocess.called)
  528. mock_os_path_isfile.return_value = True
  529. mock_os_access.return_value = True
  530. super(FirewallWorker, self.obj).run_user_script()
  531. mock_subprocess.assert_called_once_with(
  532. ['/rw/config/qubes-firewall-user-script'])
  533. def test_main(self):
  534. self.obj.main()
  535. self.assertTrue(self.obj.init_called)
  536. self.assertTrue(self.obj.cleanup_called)
  537. self.assertTrue(self.obj.user_script_called)
  538. self.assertEqual(self.obj.update_connected_ips_called_with, [4, 6])
  539. self.assertEqual(set(self.obj.rules.keys()), self.obj.list_targets())
  540. # rules content were already tested