test_firewall.py 26 KB

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