test_firewall.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. import logging
  2. import operator
  3. from unittest import TestCase
  4. import qubesagent.firewall
  5. class DummyIptablesRestore(object):
  6. # pylint: disable=too-few-public-methods
  7. def __init__(self, worker_mock, family):
  8. self._worker_mock = worker_mock
  9. self._family = family
  10. self.returncode = 0
  11. def communicate(self, stdin=None):
  12. self._worker_mock.loaded_iptables[self._family] = stdin
  13. return ("", None)
  14. class DummyQubesDB(object):
  15. def __init__(self, worker_mock):
  16. self._worker_mock = worker_mock
  17. self.entries = {}
  18. self.pending_watches = []
  19. def read(self, key):
  20. try:
  21. return self.entries[key]
  22. except KeyError:
  23. return None
  24. def multiread(self, prefix):
  25. result = {}
  26. for key, value in self.entries.items():
  27. if key.startswith(prefix):
  28. result[key] = value
  29. return result
  30. def list(self, prefix):
  31. result = []
  32. for key in self.entries.keys():
  33. if key.startswith(prefix):
  34. result.append(key)
  35. return result
  36. def watch(self, path):
  37. pass
  38. def read_watch(self):
  39. try:
  40. return self.pending_watches.pop(0)
  41. except IndexError:
  42. return None
  43. class FirewallWorker(qubesagent.firewall.FirewallWorker):
  44. def __init__(self):
  45. # pylint: disable=super-init-not-called
  46. # don't call super on purpose - avoid connecting to QubesDB
  47. # super(FirewallWorker, self).__init__()
  48. self.qdb = DummyQubesDB(self)
  49. self.log = logging.getLogger('qubes.tests')
  50. self.init_called = False
  51. self.cleanup_called = False
  52. self.rules = {}
  53. def apply_rules(self, source_addr, rules):
  54. self.rules[source_addr] = rules
  55. def cleanup(self):
  56. self.init_called = True
  57. def init(self):
  58. self.cleanup_called = True
  59. class IptablesWorker(qubesagent.firewall.IptablesWorker):
  60. '''Override methods actually modifying system state to only log what
  61. would be done'''
  62. def __init__(self):
  63. # pylint: disable=super-init-not-called
  64. # don't call super on purpose - avoid connecting to QubesDB
  65. # super(IptablesWorker, self).__init__()
  66. # copied __init__:
  67. self.qdb = DummyQubesDB(self)
  68. self.log = logging.getLogger('qubes.tests')
  69. self.chains = {
  70. 4: set(),
  71. 6: set(),
  72. }
  73. #: instead of really running `iptables`, log what would be called
  74. self.called_commands = {
  75. 4: [],
  76. 6: [],
  77. }
  78. #: rules that would be loaded with `iptables-restore`
  79. self.loaded_iptables = {
  80. 4: None,
  81. 6: None,
  82. }
  83. def run_ipt(self, family, args, **kwargs):
  84. self.called_commands[family].append(args)
  85. def run_ipt_restore(self, family, args):
  86. return DummyIptablesRestore(self, family)
  87. @staticmethod
  88. def dns_addresses(family=None):
  89. if family == 4:
  90. return ['1.1.1.1', '2.2.2.2']
  91. else:
  92. return ['2001::1', '2001::2']
  93. class NftablesWorker(qubesagent.firewall.NftablesWorker):
  94. '''Override methods actually modifying system state to only log what
  95. would be done'''
  96. def __init__(self):
  97. # pylint: disable=super-init-not-called
  98. # don't call super on purpose - avoid connecting to QubesDB
  99. # super(IptablesWorker, self).__init__()
  100. # copied __init__:
  101. self.qdb = DummyQubesDB(self)
  102. self.log = logging.getLogger('qubes.tests')
  103. self.chains = {
  104. 4: set(),
  105. 6: set(),
  106. }
  107. #: instead of really running `nft`, log what would be loaded
  108. #: rules that would be loaded with `nft`
  109. self.loaded_rules = []
  110. def run_nft(self, nft_input):
  111. self.loaded_rules.append(nft_input)
  112. @staticmethod
  113. def dns_addresses(family=None):
  114. if family == 4:
  115. return ['1.1.1.1', '2.2.2.2']
  116. else:
  117. return ['2001::1', '2001::2']
  118. class TestIptablesWorker(TestCase):
  119. def setUp(self):
  120. super(TestIptablesWorker, self).setUp()
  121. self.obj = IptablesWorker()
  122. def test_000_chain_for_addr(self):
  123. self.assertEqual(
  124. self.obj.chain_for_addr('10.137.0.1'), 'qbs-10-137-0-1')
  125. self.assertEqual(
  126. self.obj.chain_for_addr('fd09:24ef:4179:0000::3'),
  127. 'qbs-fd09-24ef-4179-0000--3')
  128. def test_001_create_chain(self):
  129. testdata = [
  130. (4, '10.137.0.1', 'qbs-10-137-0-1'),
  131. (6, 'fd09:24ef:4179:0000::3', 'qbs-fd09-24ef-4179-0000--3')
  132. ]
  133. for family, addr, chain in testdata:
  134. self.obj.create_chain(addr, chain, family)
  135. self.assertEqual(self.obj.called_commands[family],
  136. [['-N', chain],
  137. ['-A', 'QBS-FORWARD', '-s', addr, '-j', chain]])
  138. def test_002_prepare_rules4(self):
  139. rules = [
  140. {'action': 'accept', 'proto': 'tcp',
  141. 'dstports': '80-80', 'dst4': '1.2.3.0/24'},
  142. {'action': 'accept', 'proto': 'udp',
  143. 'dstports': '443-1024', 'dsthost': 'yum.qubes-os.org'},
  144. {'action': 'accept', 'specialtarget': 'dns'},
  145. {'action': 'drop', 'proto': 'udp', 'specialtarget': 'dns'},
  146. {'action': 'drop', 'proto': 'icmp'},
  147. {'action': 'drop'},
  148. ]
  149. expected_iptables = (
  150. "*filter\n"
  151. "-A chain -d 1.2.3.0/24 -p tcp --dport 80:80 -j ACCEPT\n"
  152. "-A chain -d 82.94.215.165/32 -p udp --dport 443:1024 -j ACCEPT\n"
  153. "-A chain -d 1.1.1.1/32 -p tcp --dport 53:53 -j ACCEPT\n"
  154. "-A chain -d 2.2.2.2/32 -p tcp --dport 53:53 -j ACCEPT\n"
  155. "-A chain -d 1.1.1.1/32 -p udp --dport 53:53 -j ACCEPT\n"
  156. "-A chain -d 2.2.2.2/32 -p udp --dport 53:53 -j ACCEPT\n"
  157. "-A chain -d 1.1.1.1/32 -p udp --dport 53:53 -j DROP\n"
  158. "-A chain -d 2.2.2.2/32 -p udp --dport 53:53 -j DROP\n"
  159. "-A chain -p icmp -j DROP\n"
  160. "-A chain -j DROP\n"
  161. "COMMIT\n"
  162. )
  163. self.assertEqual(self.obj.prepare_rules('chain', rules, 4),
  164. expected_iptables)
  165. with self.assertRaises(qubesagent.firewall.RuleParseError):
  166. self.obj.prepare_rules('chain', [{'unknown': 'xxx'}], 4)
  167. with self.assertRaises(qubesagent.firewall.RuleParseError):
  168. self.obj.prepare_rules('chain', [{'dst6': 'a::b'}], 4)
  169. with self.assertRaises(qubesagent.firewall.RuleParseError):
  170. self.obj.prepare_rules('chain', [{'dst4': '3.3.3.3'}], 6)
  171. def test_003_prepare_rules6(self):
  172. rules = [
  173. {'action': 'accept', 'proto': 'tcp',
  174. 'dstports': '80-80', 'dst6': 'a::b/128'},
  175. {'action': 'accept', 'proto': 'tcp',
  176. 'dsthost': 'ripe.net'},
  177. {'action': 'accept', 'specialtarget': 'dns'},
  178. {'action': 'drop', 'proto': 'udp', 'specialtarget': 'dns'},
  179. {'action': 'drop', 'proto': 'icmp'},
  180. {'action': 'drop'},
  181. ]
  182. expected_iptables = (
  183. "*filter\n"
  184. "-A chain -d a::b/128 -p tcp --dport 80:80 -j ACCEPT\n"
  185. "-A chain -d 2001:67c:2e8:22::c100:68b/128 -p tcp -j ACCEPT\n"
  186. "-A chain -d 2001::1/128 -p tcp --dport 53:53 -j ACCEPT\n"
  187. "-A chain -d 2001::2/128 -p tcp --dport 53:53 -j ACCEPT\n"
  188. "-A chain -d 2001::1/128 -p udp --dport 53:53 -j ACCEPT\n"
  189. "-A chain -d 2001::2/128 -p udp --dport 53:53 -j ACCEPT\n"
  190. "-A chain -d 2001::1/128 -p udp --dport 53:53 -j DROP\n"
  191. "-A chain -d 2001::2/128 -p udp --dport 53:53 -j DROP\n"
  192. "-A chain -p icmp -j DROP\n"
  193. "-A chain -j DROP\n"
  194. "COMMIT\n"
  195. )
  196. self.assertEqual(self.obj.prepare_rules('chain', rules, 6),
  197. expected_iptables)
  198. def test_004_apply_rules4(self):
  199. rules = [{'action': 'accept'}]
  200. chain = 'qbs-10-137-0-1'
  201. self.obj.apply_rules('10.137.0.1', rules)
  202. self.assertEqual(self.obj.called_commands[4],
  203. [
  204. ['-N', chain],
  205. ['-A', 'QBS-FORWARD', '-s', '10.137.0.1', '-j', chain],
  206. ['-F', chain]])
  207. self.assertEqual(self.obj.loaded_iptables[4],
  208. self.obj.prepare_rules(chain, rules, 4))
  209. self.assertEqual(self.obj.called_commands[6], [])
  210. self.assertIsNone(self.obj.loaded_iptables[6])
  211. def test_005_apply_rules6(self):
  212. rules = [{'action': 'accept'}]
  213. chain = 'qbs-2000--a'
  214. self.obj.apply_rules('2000::a', rules)
  215. self.assertEqual(self.obj.called_commands[6],
  216. [
  217. ['-N', chain],
  218. ['-A', 'QBS-FORWARD', '-s', '2000::a', '-j', chain],
  219. ['-F', chain]])
  220. self.assertEqual(self.obj.loaded_iptables[6],
  221. self.obj.prepare_rules(chain, rules, 6))
  222. self.assertEqual(self.obj.called_commands[4], [])
  223. self.assertIsNone(self.obj.loaded_iptables[4])
  224. def test_006_init(self):
  225. self.obj.init()
  226. self.assertEqual(self.obj.called_commands[4],
  227. [['-nL', 'QBS-FORWARD']])
  228. self.assertEqual(self.obj.called_commands[6],
  229. [['-nL', 'QBS-FORWARD']])
  230. def test_007_cleanup(self):
  231. self.obj.init()
  232. self.obj.create_chain('1.2.3.4', 'chain-ip4-1', 4)
  233. self.obj.create_chain('1.2.3.6', 'chain-ip4-2', 4)
  234. self.obj.create_chain('2000::1', 'chain-ip6-1', 6)
  235. self.obj.create_chain('2000::2', 'chain-ip6-2', 6)
  236. # forget about commands called earlier
  237. self.obj.called_commands[4] = []
  238. self.obj.called_commands[6] = []
  239. self.obj.cleanup()
  240. self.assertEqual([self.obj.called_commands[4][0]] +
  241. sorted(self.obj.called_commands[4][1:], key=operator.itemgetter(1)),
  242. [['-F', 'QBS-FORWARD'],
  243. ['-F', 'chain-ip4-1'],
  244. ['-X', 'chain-ip4-1'],
  245. ['-F', 'chain-ip4-2'],
  246. ['-X', 'chain-ip4-2']])
  247. self.assertEqual([self.obj.called_commands[6][0]] +
  248. sorted(self.obj.called_commands[6][1:], key=operator.itemgetter(1)),
  249. [['-F', 'QBS-FORWARD'],
  250. ['-F', 'chain-ip6-1'],
  251. ['-X', 'chain-ip6-1'],
  252. ['-F', 'chain-ip6-2'],
  253. ['-X', 'chain-ip6-2']])
  254. class TestNftablesWorker(TestCase):
  255. def setUp(self):
  256. super(TestNftablesWorker, self).setUp()
  257. self.obj = NftablesWorker()
  258. def test_000_chain_for_addr(self):
  259. self.assertEqual(
  260. self.obj.chain_for_addr('10.137.0.1'), 'qbs-10-137-0-1')
  261. self.assertEqual(
  262. self.obj.chain_for_addr('fd09:24ef:4179:0000::3'),
  263. 'qbs-fd09-24ef-4179-0000--3')
  264. def expected_create_chain(self, family, addr, chain):
  265. return (
  266. 'table {family} qubes-firewall {{\n'
  267. ' chain {chain} {{\n'
  268. ' }}\n'
  269. ' chain forward {{\n'
  270. ' {family} saddr {addr} jump {chain}\n'
  271. ' }}\n'
  272. '}}\n'.format(family=family, addr=addr, chain=chain))
  273. def test_001_create_chain(self):
  274. testdata = [
  275. (4, '10.137.0.1', 'qbs-10-137-0-1'),
  276. (6, 'fd09:24ef:4179:0000::3', 'qbs-fd09-24ef-4179-0000--3')
  277. ]
  278. for family, addr, chain in testdata:
  279. self.obj.create_chain(addr, chain, family)
  280. self.assertEqual(self.obj.loaded_rules,
  281. [self.expected_create_chain('ip', '10.137.0.1', 'qbs-10-137-0-1'),
  282. self.expected_create_chain(
  283. 'ip6', 'fd09:24ef:4179:0000::3', 'qbs-fd09-24ef-4179-0000--3'),
  284. ])
  285. def test_002_prepare_rules4(self):
  286. rules = [
  287. {'action': 'accept', 'proto': 'tcp',
  288. 'dstports': '80-80', 'dst4': '1.2.3.0/24'},
  289. {'action': 'accept', 'proto': 'udp',
  290. 'dstports': '443-1024', 'dsthost': 'yum.qubes-os.org'},
  291. {'action': 'accept', 'specialtarget': 'dns'},
  292. {'action': 'drop', 'proto': 'udp', 'specialtarget': 'dns'},
  293. {'action': 'drop', 'proto': 'icmp'},
  294. {'action': 'drop'},
  295. ]
  296. expected_nft = (
  297. 'flush chain ip qubes-firewall chain\n'
  298. 'table ip qubes-firewall {\n'
  299. ' chain chain {\n'
  300. ' ip protocol tcp ip daddr 1.2.3.0/24 tcp dport 80 accept\n'
  301. ' ip protocol udp ip daddr { 82.94.215.165/32 } '
  302. 'udp dport 443-1024 accept\n'
  303. ' ip daddr { 1.1.1.1/32, 2.2.2.2/32 } tcp dport 53 accept\n'
  304. ' ip daddr { 1.1.1.1/32, 2.2.2.2/32 } udp dport 53 accept\n'
  305. ' ip protocol udp ip daddr { 1.1.1.1/32, 2.2.2.2/32 } udp dport '
  306. '53 drop\n'
  307. ' ip protocol icmp drop\n'
  308. ' drop\n'
  309. ' }\n'
  310. '}\n'
  311. )
  312. self.assertEqual(self.obj.prepare_rules('chain', rules, 4),
  313. expected_nft)
  314. with self.assertRaises(qubesagent.firewall.RuleParseError):
  315. self.obj.prepare_rules('chain', [{'unknown': 'xxx'}], 4)
  316. with self.assertRaises(qubesagent.firewall.RuleParseError):
  317. self.obj.prepare_rules('chain', [{'dst6': 'a::b'}], 4)
  318. with self.assertRaises(qubesagent.firewall.RuleParseError):
  319. self.obj.prepare_rules('chain', [{'dst4': '3.3.3.3'}], 6)
  320. def test_003_prepare_rules6(self):
  321. rules = [
  322. {'action': 'accept', 'proto': 'tcp',
  323. 'dstports': '80-80', 'dst6': 'a::b/128'},
  324. {'action': 'accept', 'proto': 'tcp',
  325. 'dsthost': 'ripe.net'},
  326. {'action': 'accept', 'specialtarget': 'dns'},
  327. {'action': 'drop', 'proto': 'udp', 'specialtarget': 'dns'},
  328. {'action': 'drop', 'proto': 'icmp', 'icmptype': '128'},
  329. {'action': 'drop'},
  330. ]
  331. expected_nft = (
  332. 'flush chain ip6 qubes-firewall chain\n'
  333. 'table ip6 qubes-firewall {\n'
  334. ' chain chain {\n'
  335. ' ip6 nexthdr tcp ip6 daddr a::b/128 tcp dport 80 accept\n'
  336. ' ip6 nexthdr tcp ip6 daddr { 2001:67c:2e8:22::c100:68b/128 } '
  337. 'accept\n'
  338. ' ip6 daddr { 2001::1/128, 2001::2/128 } tcp dport 53 accept\n'
  339. ' ip6 daddr { 2001::1/128, 2001::2/128 } udp dport 53 accept\n'
  340. ' ip6 nexthdr udp ip6 daddr { 2001::1/128, 2001::2/128 } '
  341. 'udp dport 53 drop\n'
  342. ' ip6 nexthdr icmpv6 icmpv6 type 128 drop\n'
  343. ' drop\n'
  344. ' }\n'
  345. '}\n'
  346. )
  347. self.assertEqual(self.obj.prepare_rules('chain', rules, 6),
  348. expected_nft)
  349. def test_004_apply_rules4(self):
  350. rules = [{'action': 'accept'}]
  351. chain = 'qbs-10-137-0-1'
  352. self.obj.apply_rules('10.137.0.1', rules)
  353. self.assertEqual(self.obj.loaded_rules,
  354. [self.expected_create_chain('ip', '10.137.0.1', chain),
  355. self.obj.prepare_rules(chain, rules, 4),
  356. ])
  357. def test_005_apply_rules6(self):
  358. rules = [{'action': 'accept'}]
  359. chain = 'qbs-2000--a'
  360. self.obj.apply_rules('2000::a', rules)
  361. self.assertEqual(self.obj.loaded_rules,
  362. [self.expected_create_chain('ip6', '2000::a', chain),
  363. self.obj.prepare_rules(chain, rules, 6),
  364. ])
  365. def test_006_init(self):
  366. self.obj.init()
  367. self.assertEqual(self.obj.loaded_rules,
  368. [
  369. 'table ip qubes-firewall {\n'
  370. ' chain forward {\n'
  371. ' type filter hook forward priority 0;\n'
  372. ' }\n'
  373. '}\n'
  374. 'table ip6 qubes-firewall {\n'
  375. ' chain forward {\n'
  376. ' type filter hook forward priority 0;\n'
  377. ' }\n'
  378. '}\n'
  379. ])
  380. def test_007_cleanup(self):
  381. self.obj.init()
  382. self.obj.create_chain('1.2.3.4', 'chain-ip4-1', 4)
  383. self.obj.create_chain('1.2.3.6', 'chain-ip4-2', 4)
  384. self.obj.create_chain('2000::1', 'chain-ip6-1', 6)
  385. self.obj.create_chain('2000::2', 'chain-ip6-2', 6)
  386. # forget about commands called earlier
  387. self.obj.loaded_rules = []
  388. self.obj.cleanup()
  389. self.assertEqual(self.obj.loaded_rules,
  390. ['delete table ip qubes-firewall\n'
  391. 'delete table ip6 qubes-firewall\n',
  392. ])
  393. class TestFirewallWorker(TestCase):
  394. def setUp(self):
  395. self.obj = FirewallWorker()
  396. rules = {
  397. '10.137.0.1': {
  398. 'policy': 'accept',
  399. '0000': 'proto=tcp dstports=80-80 action=drop',
  400. '0001': 'proto=udp specialtarget=dns action=accept',
  401. '0002': 'proto=udp action=drop',
  402. },
  403. '10.137.0.2': {'policy': 'accept'},
  404. # no policy
  405. '10.137.0.3': {'0000': 'proto=tcp action=accept'},
  406. # no action
  407. '10.137.0.4': {
  408. 'policy': 'drop',
  409. '0000': 'proto=tcp'
  410. },
  411. }
  412. for addr, entries in rules.items():
  413. for key, value in entries.items():
  414. self.obj.qdb.entries[
  415. '/qubes-firewall/{}/{}'.format(addr, key)] = value
  416. def test_read_rules(self):
  417. expected_rules1 = [
  418. {'proto': 'tcp', 'dstports': '80-80', 'action': 'drop'},
  419. {'proto': 'udp', 'specialtarget': 'dns', 'action': 'accept'},
  420. {'proto': 'udp', 'action': 'drop'},
  421. {'action': 'accept'},
  422. ]
  423. expected_rules2 = [
  424. {'action': 'accept'},
  425. ]
  426. self.assertEqual(self.obj.read_rules('10.137.0.1'), expected_rules1)
  427. self.assertEqual(self.obj.read_rules('10.137.0.2'), expected_rules2)
  428. with self.assertRaises(qubesagent.firewall.RuleParseError):
  429. self.obj.read_rules('10.137.0.3')
  430. with self.assertRaises(qubesagent.firewall.RuleParseError):
  431. self.obj.read_rules('10.137.0.4')
  432. def test_list_targets(self):
  433. self.assertEqual(self.obj.list_targets(), set(['10.137.0.{}'.format(x)
  434. for x in range(1, 5)]))
  435. def test_is_ip6(self):
  436. self.assertTrue(self.obj.is_ip6('2000::abcd'))
  437. self.assertTrue(self.obj.is_ip6('2000:1:2:3:4:5:6:abcd'))
  438. self.assertFalse(self.obj.is_ip6('10.137.0.1'))
  439. def test_handle_addr(self):
  440. self.obj.handle_addr('10.137.0.2')
  441. self.assertEqual(self.obj.rules['10.137.0.2'], [{'action': 'accept'}])
  442. # fallback to block all
  443. self.obj.handle_addr('10.137.0.3')
  444. self.assertEqual(self.obj.rules['10.137.0.3'], [{'action': 'drop'}])
  445. self.obj.handle_addr('10.137.0.4')
  446. self.assertEqual(self.obj.rules['10.137.0.4'], [{'action': 'drop'}])
  447. def test_main(self):
  448. self.obj.main()
  449. self.assertTrue(self.obj.init_called)
  450. self.assertTrue(self.obj.cleanup_called)
  451. self.assertEqual(set(self.obj.rules.keys()), self.obj.list_targets())
  452. # rules content were already tested