test_firewall.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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', 'raw', '-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', 'raw', '-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-POSTROUTING'],
  278. ['-t', 'raw', '-F', 'QBS-PREROUTING'],
  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-POSTROUTING'],
  289. ['-t', 'raw', '-F', 'QBS-PREROUTING'],
  290. ])
  291. def test_008_update_connected_ips(self):
  292. with patch.object(self.obj, 'get_connected_ips') as get_connected_ips:
  293. get_connected_ips.return_value = ['10.137.0.1', '10.137.0.2']
  294. self.obj.called_commands[4] = []
  295. self.obj.update_connected_ips(4)
  296. self.assertEqual(self.obj.called_commands[4], [
  297. ['-t', 'raw', '-F', 'QBS-PREROUTING'],
  298. ['-t', 'mangle', '-F', 'QBS-POSTROUTING'],
  299. ['-t', 'raw', '-A', 'QBS-PREROUTING',
  300. '!', '-i', 'vif+', '-s', '10.137.0.1', '-j', 'DROP'],
  301. ['-t', 'mangle', '-A', 'QBS-POSTROUTING',
  302. '!', '-o', 'vif+', '-d', '10.137.0.1', '-j', 'DROP'],
  303. ['-t', 'raw', '-A', 'QBS-PREROUTING',
  304. '!', '-i', 'vif+', '-s', '10.137.0.2', '-j', 'DROP'],
  305. ['-t', 'mangle', '-A', 'QBS-POSTROUTING',
  306. '!', '-o', 'vif+', '-d', '10.137.0.2', '-j', 'DROP']
  307. ])
  308. class TestNftablesWorker(TestCase):
  309. def setUp(self):
  310. super(TestNftablesWorker, self).setUp()
  311. self.obj = NftablesWorker()
  312. self.subprocess_patch = patch('subprocess.call')
  313. self.subprocess_mock = self.subprocess_patch.start()
  314. def tearDown(self):
  315. self.subprocess_patch.stop()
  316. def test_000_chain_for_addr(self):
  317. self.assertEqual(
  318. self.obj.chain_for_addr('10.137.0.1'), 'qbs-10-137-0-1')
  319. self.assertEqual(
  320. self.obj.chain_for_addr('fd09:24ef:4179:0000::3'),
  321. 'qbs-fd09-24ef-4179-0000--3')
  322. def expected_create_chain(self, family, addr, chain):
  323. return (
  324. 'table {family} qubes-firewall {{\n'
  325. ' chain {chain} {{\n'
  326. ' }}\n'
  327. ' chain forward {{\n'
  328. ' {family} saddr {addr} jump {chain}\n'
  329. ' }}\n'
  330. '}}\n'.format(family=family, addr=addr, chain=chain))
  331. def test_001_create_chain(self):
  332. testdata = [
  333. (4, '10.137.0.1', 'qbs-10-137-0-1'),
  334. (6, 'fd09:24ef:4179:0000::3', 'qbs-fd09-24ef-4179-0000--3')
  335. ]
  336. for family, addr, chain in testdata:
  337. self.obj.create_chain(addr, chain, family)
  338. self.assertEqual(self.obj.loaded_rules,
  339. [self.expected_create_chain('ip', '10.137.0.1', 'qbs-10-137-0-1'),
  340. self.expected_create_chain(
  341. 'ip6', 'fd09:24ef:4179:0000::3', 'qbs-fd09-24ef-4179-0000--3'),
  342. ])
  343. def test_002_prepare_rules4(self):
  344. rules = [
  345. {'action': 'accept', 'proto': 'tcp',
  346. 'dstports': '80-80', 'dst4': '1.2.3.0/24'},
  347. {'action': 'accept', 'proto': 'udp',
  348. 'dstports': '443-1024', 'dsthost': 'yum.qubes-os.org'},
  349. {'action': 'accept', 'specialtarget': 'dns'},
  350. {'action': 'drop', 'proto': 'udp', 'specialtarget': 'dns'},
  351. {'action': 'drop', 'proto': 'icmp'},
  352. {'action': 'drop'},
  353. ]
  354. expected_nft = (
  355. 'flush chain ip qubes-firewall chain\n'
  356. 'table ip qubes-firewall {\n'
  357. ' chain chain {\n'
  358. ' ip protocol tcp ip daddr 1.2.3.0/24 tcp dport 80 accept\n'
  359. ' ip protocol udp ip daddr { 147.75.32.69/32 } '
  360. 'udp dport 443-1024 accept\n'
  361. ' ip daddr { 1.1.1.1/32, 2.2.2.2/32 } tcp dport 53 accept\n'
  362. ' ip daddr { 1.1.1.1/32, 2.2.2.2/32 } udp dport 53 accept\n'
  363. ' ip protocol udp ip daddr { 1.1.1.1/32, 2.2.2.2/32 } udp dport '
  364. '53 reject with icmp type admin-prohibited\n'
  365. ' ip protocol icmp reject with icmp type admin-prohibited\n'
  366. ' reject with icmp type admin-prohibited\n'
  367. ' }\n'
  368. '}\n'
  369. )
  370. self.assertEqual(self.obj.prepare_rules('chain', rules, 4),
  371. expected_nft)
  372. with self.assertRaises(qubesagent.firewall.RuleParseError):
  373. self.obj.prepare_rules('chain', [{'unknown': 'xxx'}], 4)
  374. with self.assertRaises(qubesagent.firewall.RuleParseError):
  375. self.obj.prepare_rules('chain', [{'dst6': 'a::b'}], 4)
  376. with self.assertRaises(qubesagent.firewall.RuleParseError):
  377. self.obj.prepare_rules('chain', [{'dst4': '3.3.3.3'}], 6)
  378. def test_003_prepare_rules6(self):
  379. rules = [
  380. {'action': 'accept', 'proto': 'tcp',
  381. 'dstports': '80-80', 'dst6': 'a::b/128'},
  382. {'action': 'accept', 'proto': 'tcp',
  383. 'dsthost': 'ripe.net'},
  384. {'action': 'accept', 'specialtarget': 'dns'},
  385. {'action': 'drop', 'proto': 'udp', 'specialtarget': 'dns'},
  386. {'action': 'drop', 'proto': 'icmp', 'icmptype': '128'},
  387. {'action': 'drop'},
  388. ]
  389. expected_nft = (
  390. 'flush chain ip6 qubes-firewall chain\n'
  391. 'table ip6 qubes-firewall {\n'
  392. ' chain chain {\n'
  393. ' ip6 nexthdr tcp ip6 daddr a::b/128 tcp dport 80 accept\n'
  394. ' ip6 nexthdr tcp ip6 daddr { 2001:67c:2e8:22::c100:68b/128 } '
  395. 'accept\n'
  396. ' ip6 daddr { 2001::1/128, 2001::2/128 } tcp dport 53 accept\n'
  397. ' ip6 daddr { 2001::1/128, 2001::2/128 } udp dport 53 accept\n'
  398. ' ip6 nexthdr udp ip6 daddr { 2001::1/128, 2001::2/128 } '
  399. 'udp dport 53 reject with icmpv6 type admin-prohibited\n'
  400. ' ip6 nexthdr icmpv6 icmpv6 type 128 reject with icmpv6 type '
  401. 'admin-prohibited\n'
  402. ' reject with icmpv6 type admin-prohibited\n'
  403. ' }\n'
  404. '}\n'
  405. )
  406. self.assertEqual(self.obj.prepare_rules('chain', rules, 6),
  407. expected_nft)
  408. def test_004_apply_rules4(self):
  409. rules = [{'action': 'accept'}]
  410. chain = 'qbs-10-137-0-1'
  411. self.obj.apply_rules('10.137.0.1', rules)
  412. self.assertEqual(self.obj.loaded_rules,
  413. [self.expected_create_chain('ip', '10.137.0.1', chain),
  414. self.obj.prepare_rules(chain, rules, 4),
  415. ])
  416. def test_005_apply_rules6(self):
  417. rules = [{'action': 'accept'}]
  418. chain = 'qbs-2000--a'
  419. self.obj.apply_rules('2000::a', rules)
  420. self.assertEqual(self.obj.loaded_rules,
  421. [self.expected_create_chain('ip6', '2000::a', chain),
  422. self.obj.prepare_rules(chain, rules, 6),
  423. ])
  424. def test_006_init(self):
  425. self.obj.init()
  426. self.assertEqual(self.obj.loaded_rules,
  427. [
  428. 'table ip qubes-firewall {\n'
  429. ' chain forward {\n'
  430. ' type filter hook forward priority 0;\n'
  431. ' policy drop;\n'
  432. ' ct state established,related accept\n'
  433. ' meta iifname != "vif*" accept\n'
  434. ' }\n'
  435. ' chain prerouting {\n'
  436. ' type filter hook prerouting priority -300;\n'
  437. ' policy accept;\n'
  438. ' }\n'
  439. ' chain postrouting {\n'
  440. ' type filter hook postrouting priority -300;\n'
  441. ' policy accept;\n'
  442. ' }\n'
  443. '}\n'
  444. 'table ip6 qubes-firewall {\n'
  445. ' chain forward {\n'
  446. ' type filter hook forward priority 0;\n'
  447. ' policy drop;\n'
  448. ' ct state established,related accept\n'
  449. ' meta iifname != "vif*" accept\n'
  450. ' }\n'
  451. ' chain prerouting {\n'
  452. ' type filter hook prerouting priority -300;\n'
  453. ' policy accept;\n'
  454. ' }\n'
  455. ' chain postrouting {\n'
  456. ' type filter hook postrouting priority -300;\n'
  457. ' policy accept;\n'
  458. ' }\n'
  459. '}\n'
  460. ])
  461. def test_007_cleanup(self):
  462. self.obj.init()
  463. self.obj.create_chain('1.2.3.4', 'chain-ip4-1', 4)
  464. self.obj.create_chain('1.2.3.6', 'chain-ip4-2', 4)
  465. self.obj.create_chain('2000::1', 'chain-ip6-1', 6)
  466. self.obj.create_chain('2000::2', 'chain-ip6-2', 6)
  467. # forget about commands called earlier
  468. self.obj.loaded_rules = []
  469. self.obj.cleanup()
  470. self.assertEqual(self.obj.loaded_rules,
  471. ['delete table ip qubes-firewall\n'
  472. 'delete table ip6 qubes-firewall\n',
  473. ])
  474. def test_008_update_connected_ips(self):
  475. with patch.object(self.obj, 'get_connected_ips') as get_connected_ips:
  476. get_connected_ips.return_value = ['10.137.0.1', '10.137.0.2']
  477. self.obj.loaded_rules = []
  478. self.obj.update_connected_ips(4)
  479. self.assertEqual(self.obj.loaded_rules, [
  480. 'flush chain ip qubes-firewall prerouting\n'
  481. 'flush chain ip qubes-firewall postrouting\n'
  482. 'table ip qubes-firewall {\n'
  483. ' chain prerouting {\n'
  484. ' iifname != "vif*" ip saddr {10.137.0.1, 10.137.0.2} drop\n'
  485. ' }\n'
  486. ' chain postrouting {\n'
  487. ' oifname != "vif*" ip daddr {10.137.0.1, 10.137.0.2} drop\n'
  488. ' }\n'
  489. '}\n'
  490. ])
  491. class TestFirewallWorker(TestCase):
  492. def setUp(self):
  493. self.obj = FirewallWorker()
  494. rules = {
  495. '10.137.0.1': {
  496. 'policy': b'accept',
  497. '0000': b'proto=tcp dstports=80-80 action=drop',
  498. '0001': b'proto=udp specialtarget=dns action=accept',
  499. '0002': b'proto=udp action=drop',
  500. },
  501. '10.137.0.2': {'policy': b'accept'},
  502. # no policy
  503. '10.137.0.3': {'0000': b'proto=tcp action=accept'},
  504. # no action
  505. '10.137.0.4': {
  506. 'policy': b'drop',
  507. '0000': b'proto=tcp'
  508. },
  509. }
  510. for addr, entries in rules.items():
  511. for key, value in entries.items():
  512. self.obj.qdb.entries[
  513. '/qubes-firewall/{}/{}'.format(addr, key)] = value
  514. self.subprocess_patch = patch('subprocess.call')
  515. self.subprocess_mock = self.subprocess_patch.start()
  516. def tearDown(self):
  517. self.subprocess_patch.stop()
  518. def test_read_rules(self):
  519. expected_rules1 = [
  520. {'proto': 'tcp', 'dstports': '80-80', 'action': 'drop'},
  521. {'proto': 'udp', 'specialtarget': 'dns', 'action': 'accept'},
  522. {'proto': 'udp', 'action': 'drop'},
  523. {'action': 'accept'},
  524. ]
  525. expected_rules2 = [
  526. {'action': 'accept'},
  527. ]
  528. self.assertEqual(self.obj.read_rules('10.137.0.1'), expected_rules1)
  529. self.assertEqual(self.obj.read_rules('10.137.0.2'), expected_rules2)
  530. with self.assertRaises(qubesagent.firewall.RuleParseError):
  531. self.obj.read_rules('10.137.0.3')
  532. with self.assertRaises(qubesagent.firewall.RuleParseError):
  533. self.obj.read_rules('10.137.0.4')
  534. def test_list_targets(self):
  535. self.assertEqual(self.obj.list_targets(), set(['10.137.0.{}'.format(x)
  536. for x in range(1, 5)]))
  537. def test_is_ip6(self):
  538. self.assertTrue(self.obj.is_ip6('2000::abcd'))
  539. self.assertTrue(self.obj.is_ip6('2000:1:2:3:4:5:6:abcd'))
  540. self.assertFalse(self.obj.is_ip6('10.137.0.1'))
  541. def test_handle_addr(self):
  542. self.obj.handle_addr('10.137.0.2')
  543. self.assertEqual(self.obj.rules['10.137.0.2'], [{'action': 'accept'}])
  544. # fallback to block all
  545. self.obj.handle_addr('10.137.0.3')
  546. self.assertEqual(self.obj.rules['10.137.0.3'], [{'action': 'drop'}])
  547. self.obj.handle_addr('10.137.0.4')
  548. self.assertEqual(self.obj.rules['10.137.0.4'], [{'action': 'drop'}])
  549. @patch('os.path.isfile')
  550. @patch('os.access')
  551. @patch('subprocess.call')
  552. def test_run_user_script(self, mock_subprocess, mock_os_access,
  553. mock_os_path_isfile):
  554. mock_os_path_isfile.return_value = False
  555. mock_os_access.return_value = False
  556. super(FirewallWorker, self.obj).run_user_script()
  557. self.assertFalse(mock_subprocess.called)
  558. mock_os_path_isfile.return_value = True
  559. mock_os_access.return_value = False
  560. super(FirewallWorker, self.obj).run_user_script()
  561. self.assertFalse(mock_subprocess.called)
  562. mock_os_path_isfile.return_value = True
  563. mock_os_access.return_value = True
  564. super(FirewallWorker, self.obj).run_user_script()
  565. mock_subprocess.assert_called_once_with(
  566. ['/rw/config/qubes-firewall-user-script'])
  567. def test_main(self):
  568. self.obj.main()
  569. self.assertTrue(self.obj.init_called)
  570. self.assertTrue(self.obj.cleanup_called)
  571. self.assertTrue(self.obj.user_script_called)
  572. self.assertEqual(self.obj.update_connected_ips_called_with, [4, 6])
  573. self.assertEqual(set(self.obj.rules.keys()), self.obj.list_targets())
  574. # rules content were already tested