test_firewall.py 26 KB

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