test_firewall.py 28 KB

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