test_firewall.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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 list(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 WorkerCommon(object):
  136. def assertPrepareRulesDnsRet(self, dns_ret, expected_domain, family):
  137. self.assertEqual(dns_ret.keys(), {expected_domain})
  138. self.assertIsInstance(dns_ret[expected_domain], set)
  139. if family == 4:
  140. self.assertIsNotNone(re.match('^\d+\.\d+\.\d+\.\d+/32$',
  141. dns_ret[expected_domain].pop()))
  142. elif family == 6:
  143. self.assertIsNotNone(re.match('^[0-9a-f:]+/\d+$',
  144. dns_ret[expected_domain].pop()))
  145. else:
  146. raise ValueError()
  147. def test_701_dns_info(self):
  148. rules = [
  149. {'action': 'accept', 'proto': 'tcp',
  150. 'dstports': '80-80', 'dsthost': 'ripe.net'},
  151. {'action': 'drop'},
  152. ]
  153. self.obj.apply_rules('10.137.0.1', rules)
  154. self.assertIsNotNone(self.obj.qdb.read('/dns/10.137.0.1/ripe.net'))
  155. self.obj.apply_rules('10.137.0.1', [{'action': 'drop'}])
  156. self.assertIsNone(self.obj.qdb.read('/dns/10.137.0.1/ripe.net'))
  157. class TestIptablesWorker(TestCase, WorkerCommon):
  158. def setUp(self):
  159. super(TestIptablesWorker, self).setUp()
  160. self.obj = IptablesWorker()
  161. self.subprocess_patch = patch('subprocess.call')
  162. self.subprocess_mock = self.subprocess_patch.start()
  163. def tearDown(self):
  164. self.subprocess_patch.stop()
  165. def test_000_chain_for_addr(self):
  166. self.assertEqual(
  167. self.obj.chain_for_addr('10.137.0.1'), 'qbs-10-137-0-1')
  168. self.assertEqual(
  169. self.obj.chain_for_addr('fd09:24ef:4179:0000::3'),
  170. 'qbs-09-24ef-4179-0000--3')
  171. def test_001_create_chain(self):
  172. testdata = [
  173. (4, '10.137.0.1', 'qbs-10-137-0-1'),
  174. (6, 'fd09:24ef:4179:0000::3', 'qbs-fd09-24ef-4179-0000--3')
  175. ]
  176. for family, addr, chain in testdata:
  177. self.obj.create_chain(addr, chain, family)
  178. self.assertEqual(self.obj.called_commands[family],
  179. [['-N', chain],
  180. ['-I', 'QBS-FORWARD', '-s', addr, '-j', chain]])
  181. def test_002_prepare_rules4(self):
  182. rules = [
  183. {'action': 'accept', 'proto': 'tcp',
  184. 'dstports': '80-80', 'dst4': '1.2.3.0/24'},
  185. {'action': 'accept', 'proto': 'udp',
  186. 'dstports': '443-1024', 'dsthost': 'yum.qubes-os.org'},
  187. {'action': 'accept', 'specialtarget': 'dns'},
  188. {'action': 'drop', 'proto': 'udp', 'specialtarget': 'dns'},
  189. {'action': 'drop', 'proto': 'icmp'},
  190. {'action': 'drop'},
  191. ]
  192. expected_iptables = (
  193. "*filter\n"
  194. "-A chain -d 1.2.3.0/24 -p tcp --dport 80:80 -j ACCEPT\n"
  195. "-A chain -d 147.75.32.1/32 -p udp --dport 443:1024 -j ACCEPT\n"
  196. "-A chain -d 1.1.1.1/32 -p tcp --dport 53:53 -j ACCEPT\n"
  197. "-A chain -d 2.2.2.2/32 -p tcp --dport 53:53 -j ACCEPT\n"
  198. "-A chain -d 1.1.1.1/32 -p udp --dport 53:53 -j ACCEPT\n"
  199. "-A chain -d 2.2.2.2/32 -p udp --dport 53:53 -j ACCEPT\n"
  200. "-A chain -d 1.1.1.1/32 -p udp --dport 53:53 -j REJECT "
  201. "--reject-with icmp-admin-prohibited\n"
  202. "-A chain -d 2.2.2.2/32 -p udp --dport 53:53 -j REJECT "
  203. "--reject-with icmp-admin-prohibited\n"
  204. "-A chain -p icmp -j REJECT "
  205. "--reject-with icmp-admin-prohibited\n"
  206. "-A chain -j REJECT "
  207. "--reject-with icmp-admin-prohibited\n"
  208. "COMMIT\n"
  209. )
  210. ret = self.obj.prepare_rules('chain', rules, 4)
  211. self.assertEqual(ret[0], expected_iptables)
  212. self.assertPrepareRulesDnsRet(ret[1], 'yum.qubes-os.org', 4)
  213. with self.assertRaises(qubesagent.firewall.RuleParseError):
  214. self.obj.prepare_rules('chain', [{'unknown': 'xxx'}], 4)
  215. with self.assertRaises(qubesagent.firewall.RuleParseError):
  216. self.obj.prepare_rules('chain', [{'dst6': 'a::b'}], 4)
  217. with self.assertRaises(qubesagent.firewall.RuleParseError):
  218. self.obj.prepare_rules('chain', [{'dst4': '3.3.3.3'}], 6)
  219. def test_003_prepare_rules6(self):
  220. rules = [
  221. {'action': 'accept', 'proto': 'tcp',
  222. 'dstports': '80-80', 'dst6': 'a::b/128'},
  223. {'action': 'accept', 'proto': 'tcp',
  224. 'dsthost': 'ripe.net'},
  225. {'action': 'accept', 'specialtarget': 'dns'},
  226. {'action': 'drop', 'proto': 'udp', 'specialtarget': 'dns'},
  227. {'action': 'drop', 'proto': 'icmp'},
  228. {'action': 'drop'},
  229. ]
  230. expected_iptables = (
  231. "*filter\n"
  232. "-A chain -d a::b/128 -p tcp --dport 80:80 -j ACCEPT\n"
  233. "-A chain -d 2001:67c:2e8:22::c100:68b/128 -p tcp -j ACCEPT\n"
  234. "-A chain -d 2001::1/128 -p tcp --dport 53:53 -j ACCEPT\n"
  235. "-A chain -d 2001::2/128 -p tcp --dport 53:53 -j ACCEPT\n"
  236. "-A chain -d 2001::1/128 -p udp --dport 53:53 -j ACCEPT\n"
  237. "-A chain -d 2001::2/128 -p udp --dport 53:53 -j ACCEPT\n"
  238. "-A chain -d 2001::1/128 -p udp --dport 53:53 -j REJECT "
  239. "--reject-with icmp6-adm-prohibited\n"
  240. "-A chain -d 2001::2/128 -p udp --dport 53:53 -j REJECT "
  241. "--reject-with icmp6-adm-prohibited\n"
  242. "-A chain -p icmpv6 -j REJECT "
  243. "--reject-with icmp6-adm-prohibited\n"
  244. "-A chain -j REJECT "
  245. "--reject-with icmp6-adm-prohibited\n"
  246. "COMMIT\n"
  247. )
  248. ret = self.obj.prepare_rules('chain', rules, 6)
  249. self.assertEqual(ret[0], expected_iptables)
  250. self.assertPrepareRulesDnsRet(ret[1], 'ripe.net', 6)
  251. def test_004_apply_rules4(self):
  252. rules = [{'action': 'accept'}]
  253. chain = 'qbs-10-137-0-1'
  254. self.obj.apply_rules('10.137.0.1', rules)
  255. self.assertEqual(self.obj.called_commands[4],
  256. [
  257. ['-N', chain],
  258. ['-I', 'QBS-FORWARD', '-s', '10.137.0.1', '-j', chain],
  259. ['-F', chain]])
  260. self.assertEqual(self.obj.loaded_iptables[4],
  261. self.obj.prepare_rules(chain, rules, 4)[0])
  262. self.assertEqual(self.obj.called_commands[6], [])
  263. self.assertIsNone(self.obj.loaded_iptables[6])
  264. def test_005_apply_rules6(self):
  265. rules = [{'action': 'accept'}]
  266. chain = 'qbs-2000--a'
  267. self.obj.apply_rules('2000::a', rules)
  268. self.assertEqual(self.obj.called_commands[6],
  269. [
  270. ['-N', chain],
  271. ['-I', 'QBS-FORWARD', '-s', '2000::a', '-j', chain],
  272. ['-F', chain]])
  273. self.assertEqual(self.obj.loaded_iptables[6],
  274. self.obj.prepare_rules(chain, rules, 6)[0])
  275. self.assertEqual(self.obj.called_commands[4], [])
  276. self.assertIsNone(self.obj.loaded_iptables[4])
  277. def test_006_init(self):
  278. self.obj.init()
  279. self.assertEqual(self.obj.called_commands[4], [
  280. ['-F', 'QBS-FORWARD'],
  281. ['-A', 'QBS-FORWARD', '!', '-i', 'vif+', '-j', 'RETURN'],
  282. ['-A', 'QBS-FORWARD', '-j', 'DROP'],
  283. ['-t', 'raw', '-F', 'QBS-PREROUTING'],
  284. ['-t', 'mangle', '-F', 'QBS-POSTROUTING'],
  285. ])
  286. self.assertEqual(self.obj.called_commands[6], [
  287. ['-F', 'QBS-FORWARD'],
  288. ['-A', 'QBS-FORWARD', '!', '-i', 'vif+', '-j', 'RETURN'],
  289. ['-A', 'QBS-FORWARD', '-j', 'DROP'],
  290. ['-t', 'raw', '-F', 'QBS-PREROUTING'],
  291. ['-t', 'mangle', '-F', 'QBS-POSTROUTING'],
  292. ])
  293. def test_007_cleanup(self):
  294. self.obj.init()
  295. self.obj.create_chain('1.2.3.4', 'chain-ip4-1', 4)
  296. self.obj.create_chain('1.2.3.6', 'chain-ip4-2', 4)
  297. self.obj.create_chain('2000::1', 'chain-ip6-1', 6)
  298. self.obj.create_chain('2000::2', 'chain-ip6-2', 6)
  299. # forget about commands called earlier
  300. self.obj.called_commands[4] = []
  301. self.obj.called_commands[6] = []
  302. self.obj.cleanup()
  303. self.assertEqual([self.obj.called_commands[4][0]] +
  304. sorted(self.obj.called_commands[4][1:], key=operator.itemgetter(1)),
  305. [
  306. ['-F', 'QBS-FORWARD'],
  307. ['-F', 'chain-ip4-1'],
  308. ['-X', 'chain-ip4-1'],
  309. ['-F', 'chain-ip4-2'],
  310. ['-X', 'chain-ip4-2'],
  311. ['-t', 'mangle', '-F', 'QBS-POSTROUTING'],
  312. ['-t', 'raw', '-F', 'QBS-PREROUTING'],
  313. ])
  314. self.assertEqual([self.obj.called_commands[6][0]] +
  315. sorted(self.obj.called_commands[6][1:], key=operator.itemgetter(1)),
  316. [
  317. ['-F', 'QBS-FORWARD'],
  318. ['-F', 'chain-ip6-1'],
  319. ['-X', 'chain-ip6-1'],
  320. ['-F', 'chain-ip6-2'],
  321. ['-X', 'chain-ip6-2'],
  322. ['-t', 'mangle', '-F', 'QBS-POSTROUTING'],
  323. ['-t', 'raw', '-F', 'QBS-PREROUTING'],
  324. ])
  325. def test_008_update_connected_ips(self):
  326. self.obj.qdb.entries['/connected-ips'] = b'10.137.0.1 10.137.0.2'
  327. self.obj.called_commands[4] = []
  328. self.obj.update_connected_ips(4)
  329. self.assertEqual(self.obj.called_commands[4], [
  330. ['-t', 'raw', '-P', 'PREROUTING', 'DROP'],
  331. ['-t', 'mangle', '-P', 'POSTROUTING', 'DROP'],
  332. ['-t', 'raw', '-F', 'QBS-PREROUTING'],
  333. ['-t', 'mangle', '-F', 'QBS-POSTROUTING'],
  334. ['-t', 'raw', '-A', 'QBS-PREROUTING',
  335. '!', '-i', 'vif+', '-s', '10.137.0.1', '-j', 'DROP'],
  336. ['-t', 'mangle', '-A', 'QBS-POSTROUTING',
  337. '!', '-o', 'vif+', '-d', '10.137.0.1', '-j', 'DROP'],
  338. ['-t', 'raw', '-A', 'QBS-PREROUTING',
  339. '!', '-i', 'vif+', '-s', '10.137.0.2', '-j', 'DROP'],
  340. ['-t', 'mangle', '-A', 'QBS-POSTROUTING',
  341. '!', '-o', 'vif+', '-d', '10.137.0.2', '-j', 'DROP'],
  342. ['-t', 'raw', '-P', 'PREROUTING', 'ACCEPT'],
  343. ['-t', 'mangle', '-P', 'POSTROUTING', 'ACCEPT'],
  344. ])
  345. def test_009_update_connected_ips_empty(self):
  346. self.obj.qdb.entries['/connected-ips'] = b''
  347. self.obj.called_commands[4] = []
  348. self.obj.update_connected_ips(4)
  349. self.assertEqual(self.obj.called_commands[4], [
  350. ['-t', 'raw', '-F', 'QBS-PREROUTING'],
  351. ['-t', 'mangle', '-F', 'QBS-POSTROUTING'],
  352. ])
  353. def test_010_update_connected_ips_missing(self):
  354. self.obj.called_commands[4] = []
  355. self.obj.update_connected_ips(4)
  356. self.assertEqual(self.obj.called_commands[4], [
  357. ['-t', 'raw', '-F', 'QBS-PREROUTING'],
  358. ['-t', 'mangle', '-F', 'QBS-POSTROUTING'],
  359. ])
  360. class TestNftablesWorker(TestCase, WorkerCommon):
  361. def setUp(self):
  362. super(TestNftablesWorker, self).setUp()
  363. self.obj = NftablesWorker()
  364. self.subprocess_patch = patch('subprocess.call')
  365. self.subprocess_mock = self.subprocess_patch.start()
  366. def tearDown(self):
  367. self.subprocess_patch.stop()
  368. def test_000_chain_for_addr(self):
  369. self.assertEqual(
  370. self.obj.chain_for_addr('10.137.0.1'), 'qbs-10-137-0-1')
  371. self.assertEqual(
  372. self.obj.chain_for_addr('fd09:24ef:4179:0000::3'),
  373. 'qbs-fd09-24ef-4179-0000--3')
  374. def expected_create_chain(self, family, addr, chain):
  375. return (
  376. 'table {family} qubes-firewall {{\n'
  377. ' chain {chain} {{\n'
  378. ' }}\n'
  379. ' chain forward {{\n'
  380. ' {family} saddr {addr} jump {chain}\n'
  381. ' }}\n'
  382. '}}\n'.format(family=family, addr=addr, chain=chain))
  383. def test_001_create_chain(self):
  384. testdata = [
  385. (4, '10.137.0.1', 'qbs-10-137-0-1'),
  386. (6, 'fd09:24ef:4179:0000::3', 'qbs-fd09-24ef-4179-0000--3')
  387. ]
  388. for family, addr, chain in testdata:
  389. self.obj.create_chain(addr, chain, family)
  390. self.assertEqual(self.obj.loaded_rules,
  391. [self.expected_create_chain('ip', '10.137.0.1', 'qbs-10-137-0-1'),
  392. self.expected_create_chain(
  393. 'ip6', 'fd09:24ef:4179:0000::3', 'qbs-fd09-24ef-4179-0000--3'),
  394. ])
  395. def test_002_prepare_rules4(self):
  396. rules = [
  397. {'action': 'accept', 'proto': 'tcp',
  398. 'dstports': '80-80', 'dst4': '1.2.3.0/24'},
  399. {'action': 'accept', 'proto': 'udp',
  400. 'dstports': '443-1024', 'dsthost': 'yum.qubes-os.org'},
  401. {'action': 'accept', 'specialtarget': 'dns'},
  402. {'action': 'drop', 'proto': 'udp', 'specialtarget': 'dns'},
  403. {'action': 'drop', 'proto': 'icmp'},
  404. {'action': 'drop'},
  405. ]
  406. expected_nft = (
  407. 'flush chain ip qubes-firewall chain\n'
  408. 'table ip qubes-firewall {\n'
  409. ' chain chain {\n'
  410. ' ip protocol tcp ip daddr 1.2.3.0/24 tcp dport 80 accept\n'
  411. ' ip protocol udp ip daddr { 147.75.32.1/32 } '
  412. 'udp dport 443-1024 accept\n'
  413. ' ip daddr { 1.1.1.1/32, 2.2.2.2/32 } tcp dport 53 accept\n'
  414. ' ip daddr { 1.1.1.1/32, 2.2.2.2/32 } udp dport 53 accept\n'
  415. ' ip protocol udp ip daddr { 1.1.1.1/32, 2.2.2.2/32 } udp dport '
  416. '53 reject with icmp type admin-prohibited\n'
  417. ' ip protocol icmp reject with icmp type admin-prohibited\n'
  418. ' reject with icmp type admin-prohibited\n'
  419. ' }\n'
  420. '}\n'
  421. )
  422. ret = self.obj.prepare_rules('chain', rules, 4)
  423. self.assertEqual(ret[0], expected_nft)
  424. self.assertPrepareRulesDnsRet(ret[1], 'yum.qubes-os.org', 4)
  425. with self.assertRaises(qubesagent.firewall.RuleParseError):
  426. self.obj.prepare_rules('chain', [{'unknown': 'xxx'}], 4)
  427. with self.assertRaises(qubesagent.firewall.RuleParseError):
  428. self.obj.prepare_rules('chain', [{'dst6': 'a::b'}], 4)
  429. with self.assertRaises(qubesagent.firewall.RuleParseError):
  430. self.obj.prepare_rules('chain', [{'dst4': '3.3.3.3'}], 6)
  431. def test_003_prepare_rules6(self):
  432. rules = [
  433. {'action': 'accept', 'proto': 'tcp',
  434. 'dstports': '80-80', 'dst6': 'a::b/128'},
  435. {'action': 'accept', 'proto': 'tcp',
  436. 'dsthost': 'ripe.net'},
  437. {'action': 'accept', 'specialtarget': 'dns'},
  438. {'action': 'drop', 'proto': 'udp', 'specialtarget': 'dns'},
  439. {'action': 'drop', 'proto': 'icmp', 'icmptype': '128'},
  440. {'action': 'drop'},
  441. ]
  442. expected_nft = (
  443. 'flush chain ip6 qubes-firewall chain\n'
  444. 'table ip6 qubes-firewall {\n'
  445. ' chain chain {\n'
  446. ' ip6 nexthdr tcp ip6 daddr a::b/128 tcp dport 80 accept\n'
  447. ' ip6 nexthdr tcp ip6 daddr { 2001:67c:2e8:22::c100:68b/128 } '
  448. 'accept\n'
  449. ' ip6 daddr { 2001::1/128, 2001::2/128 } tcp dport 53 accept\n'
  450. ' ip6 daddr { 2001::1/128, 2001::2/128 } udp dport 53 accept\n'
  451. ' ip6 nexthdr udp ip6 daddr { 2001::1/128, 2001::2/128 } '
  452. 'udp dport 53 reject with icmpv6 type admin-prohibited\n'
  453. ' ip6 nexthdr icmpv6 icmpv6 type 128 reject with icmpv6 type '
  454. 'admin-prohibited\n'
  455. ' reject with icmpv6 type admin-prohibited\n'
  456. ' }\n'
  457. '}\n'
  458. )
  459. ret = self.obj.prepare_rules('chain', rules, 6)
  460. self.assertEqual(ret[0], expected_nft)
  461. self.assertPrepareRulesDnsRet(ret[1], 'ripe.net', 6)
  462. def test_004_apply_rules4(self):
  463. rules = [{'action': 'accept'}]
  464. chain = 'qbs-10-137-0-1'
  465. self.obj.apply_rules('10.137.0.1', rules)
  466. self.assertEqual(self.obj.loaded_rules,
  467. [self.expected_create_chain('ip', '10.137.0.1', chain),
  468. self.obj.prepare_rules(chain, rules, 4)[0],
  469. ])
  470. def test_005_apply_rules6(self):
  471. rules = [{'action': 'accept'}]
  472. chain = 'qbs-2000--a'
  473. self.obj.apply_rules('2000::a', rules)
  474. self.assertEqual(self.obj.loaded_rules,
  475. [self.expected_create_chain('ip6', '2000::a', chain),
  476. self.obj.prepare_rules(chain, rules, 6)[0],
  477. ])
  478. def test_006_init(self):
  479. self.obj.init()
  480. self.assertEqual(self.obj.loaded_rules,
  481. [
  482. 'table ip qubes-firewall {\n'
  483. ' chain forward {\n'
  484. ' type filter hook forward priority 0;\n'
  485. ' policy drop;\n'
  486. ' ct state established,related accept\n'
  487. ' meta iifname != "vif*" accept\n'
  488. ' }\n'
  489. ' chain prerouting {\n'
  490. ' type filter hook prerouting priority -300;\n'
  491. ' policy accept;\n'
  492. ' }\n'
  493. ' chain postrouting {\n'
  494. ' type filter hook postrouting priority -300;\n'
  495. ' policy accept;\n'
  496. ' }\n'
  497. '}\n'
  498. 'table ip6 qubes-firewall {\n'
  499. ' chain forward {\n'
  500. ' type filter hook forward priority 0;\n'
  501. ' policy drop;\n'
  502. ' ct state established,related accept\n'
  503. ' meta iifname != "vif*" accept\n'
  504. ' }\n'
  505. ' chain prerouting {\n'
  506. ' type filter hook prerouting priority -300;\n'
  507. ' policy accept;\n'
  508. ' }\n'
  509. ' chain postrouting {\n'
  510. ' type filter hook postrouting priority -300;\n'
  511. ' policy accept;\n'
  512. ' }\n'
  513. '}\n'
  514. ])
  515. def test_007_cleanup(self):
  516. self.obj.init()
  517. self.obj.create_chain('1.2.3.4', 'chain-ip4-1', 4)
  518. self.obj.create_chain('1.2.3.6', 'chain-ip4-2', 4)
  519. self.obj.create_chain('2000::1', 'chain-ip6-1', 6)
  520. self.obj.create_chain('2000::2', 'chain-ip6-2', 6)
  521. # forget about commands called earlier
  522. self.obj.loaded_rules = []
  523. self.obj.cleanup()
  524. self.assertEqual(self.obj.loaded_rules,
  525. ['delete table ip qubes-firewall\n'
  526. 'delete table ip6 qubes-firewall\n',
  527. ])
  528. def test_008_update_connected_ips(self):
  529. self.obj.qdb.entries['/connected-ips'] = b'10.137.0.1 10.137.0.2'
  530. self.obj.loaded_rules = []
  531. self.obj.update_connected_ips(4)
  532. self.assertEqual(self.obj.loaded_rules, [
  533. 'flush chain ip qubes-firewall prerouting\n'
  534. 'flush chain ip qubes-firewall postrouting\n'
  535. 'table ip qubes-firewall {\n'
  536. ' chain prerouting {\n'
  537. ' iifname != "vif*" ip saddr {10.137.0.1, 10.137.0.2} drop\n'
  538. ' }\n'
  539. ' chain postrouting {\n'
  540. ' oifname != "vif*" ip daddr {10.137.0.1, 10.137.0.2} drop\n'
  541. ' }\n'
  542. '}\n'
  543. ])
  544. def test_009_update_connected_ips_empty(self):
  545. self.obj.qdb.entries['/connected-ips'] = b''
  546. self.obj.loaded_rules = []
  547. self.obj.update_connected_ips(4)
  548. self.assertEqual(self.obj.loaded_rules, [
  549. 'flush chain ip qubes-firewall prerouting\n'
  550. 'flush chain ip qubes-firewall postrouting\n'
  551. ])
  552. def test_010_update_connected_ips_missing(self):
  553. self.obj.loaded_rules = []
  554. self.obj.update_connected_ips(4)
  555. self.assertEqual(self.obj.loaded_rules, [
  556. 'flush chain ip qubes-firewall prerouting\n'
  557. 'flush chain ip qubes-firewall postrouting\n'
  558. ])
  559. class TestFirewallWorker(TestCase):
  560. def setUp(self):
  561. self.obj = FirewallWorker()
  562. rules = {
  563. '10.137.0.1': {
  564. 'policy': b'accept',
  565. '0000': b'proto=tcp dstports=80-80 action=drop',
  566. '0001': b'proto=udp specialtarget=dns action=accept',
  567. '0002': b'proto=udp action=drop',
  568. },
  569. '10.137.0.2': {'policy': b'accept'},
  570. # no policy
  571. '10.137.0.3': {'0000': b'proto=tcp action=accept'},
  572. # no action
  573. '10.137.0.4': {
  574. 'policy': b'drop',
  575. '0000': b'proto=tcp'
  576. },
  577. }
  578. for addr, entries in rules.items():
  579. for key, value in entries.items():
  580. self.obj.qdb.entries[
  581. '/qubes-firewall/{}/{}'.format(addr, key)] = value
  582. self.subprocess_patch = patch('subprocess.call')
  583. self.subprocess_mock = self.subprocess_patch.start()
  584. def tearDown(self):
  585. self.subprocess_patch.stop()
  586. def test_read_rules(self):
  587. expected_rules1 = [
  588. {'proto': 'tcp', 'dstports': '80-80', 'action': 'drop'},
  589. {'proto': 'udp', 'specialtarget': 'dns', 'action': 'accept'},
  590. {'proto': 'udp', 'action': 'drop'},
  591. {'action': 'accept'},
  592. ]
  593. expected_rules2 = [
  594. {'action': 'accept'},
  595. ]
  596. self.assertEqual(self.obj.read_rules('10.137.0.1'), expected_rules1)
  597. self.assertEqual(self.obj.read_rules('10.137.0.2'), expected_rules2)
  598. with self.assertRaises(qubesagent.firewall.RuleParseError):
  599. self.obj.read_rules('10.137.0.3')
  600. with self.assertRaises(qubesagent.firewall.RuleParseError):
  601. self.obj.read_rules('10.137.0.4')
  602. def test_list_targets(self):
  603. self.assertEqual(self.obj.list_targets(), set(['10.137.0.{}'.format(x)
  604. for x in range(1, 5)]))
  605. def test_is_ip6(self):
  606. self.assertTrue(self.obj.is_ip6('2000::abcd'))
  607. self.assertTrue(self.obj.is_ip6('2000:1:2:3:4:5:6:abcd'))
  608. self.assertFalse(self.obj.is_ip6('10.137.0.1'))
  609. def test_handle_addr(self):
  610. self.obj.handle_addr('10.137.0.2')
  611. self.assertEqual(self.obj.rules['10.137.0.2'], [{'action': 'accept'}])
  612. self.assertEqual(self.obj.qdb.entries['/qubes-firewall-handled/10.137.0.2'], '1')
  613. self.obj.handle_addr('10.137.0.2')
  614. self.assertEqual(self.obj.rules['10.137.0.2'], [{'action': 'accept'}])
  615. self.assertEqual(self.obj.qdb.entries['/qubes-firewall-handled/10.137.0.2'], '2')
  616. # fallback to block all
  617. self.obj.handle_addr('10.137.0.3')
  618. self.assertEqual(self.obj.rules['10.137.0.3'], [{'action': 'drop'}])
  619. self.assertEqual(self.obj.qdb.entries['/qubes-firewall-handled/10.137.0.3'], '1')
  620. self.obj.handle_addr('10.137.0.4')
  621. self.assertEqual(self.obj.rules['10.137.0.4'], [{'action': 'drop'}])
  622. self.assertEqual(self.obj.qdb.entries['/qubes-firewall-handled/10.137.0.4'], '1')
  623. @patch('os.path.isfile')
  624. @patch('os.access')
  625. @patch('subprocess.call')
  626. def test_run_user_script(self, mock_subprocess, mock_os_access,
  627. mock_os_path_isfile):
  628. mock_os_path_isfile.return_value = False
  629. mock_os_access.return_value = False
  630. super(FirewallWorker, self.obj).run_user_script()
  631. self.assertFalse(mock_subprocess.called)
  632. mock_os_path_isfile.return_value = True
  633. mock_os_access.return_value = False
  634. super(FirewallWorker, self.obj).run_user_script()
  635. self.assertFalse(mock_subprocess.called)
  636. mock_os_path_isfile.return_value = True
  637. mock_os_access.return_value = True
  638. super(FirewallWorker, self.obj).run_user_script()
  639. mock_subprocess.assert_called_once_with(
  640. ['/rw/config/qubes-firewall-user-script'])
  641. def test_main(self):
  642. self.obj.main()
  643. self.assertTrue(self.obj.init_called)
  644. self.assertTrue(self.obj.cleanup_called)
  645. self.assertTrue(self.obj.user_script_called)
  646. self.assertEqual(self.obj.update_connected_ips_called_with, [4, 6])
  647. self.assertEqual(set(self.obj.rules.keys()), self.obj.list_targets())
  648. # rules content were already tested