test_iptables.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. # -*- coding: utf-8 -*-
  2. '''
  3. :codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
  4. '''
  5. # Import Python Libs
  6. from __future__ import absolute_import, unicode_literals, print_function
  7. import uuid
  8. # Import Salt Testing Libs
  9. from tests.support.mixins import LoaderModuleMockMixin
  10. from tests.support.unit import TestCase
  11. from tests.support.mock import (
  12. MagicMock,
  13. patch,
  14. )
  15. # Import Salt Libs
  16. import salt.modules.iptables as iptables
  17. class IptablesTestCase(TestCase, LoaderModuleMockMixin):
  18. '''
  19. Test cases for salt.modules.iptables
  20. '''
  21. def setup_loader_modules(self):
  22. return {iptables: {}}
  23. # 'version' function tests: 1
  24. def test_version(self):
  25. '''
  26. Test if it return version from iptables --version
  27. '''
  28. mock = MagicMock(return_value='iptables v1.4.21')
  29. with patch.dict(iptables.__salt__, {'cmd.run': mock}):
  30. self.assertEqual(iptables.version(), 'v1.4.21')
  31. # 'build_rule' function tests: 1
  32. def test_build_rule(self):
  33. '''
  34. Test if it build a well-formatted iptables rule based on kwargs.
  35. '''
  36. with patch.object(iptables, '_has_option', MagicMock(return_value=True)):
  37. self.assertEqual(iptables.build_rule(), '')
  38. self.assertEqual(iptables.build_rule(name='ignored', state='ignored'),
  39. '',
  40. 'build_rule should ignore name and state')
  41. # Should properly negate bang-prefixed values
  42. self.assertEqual(iptables.build_rule(**{'if': '!eth0'}),
  43. '! -i eth0')
  44. # Should properly negate "not"-prefixed values
  45. self.assertEqual(iptables.build_rule(**{'if': 'not eth0'}),
  46. '! -i eth0')
  47. self.assertEqual(iptables.build_rule(**{'protocol': 'tcp', 'syn': '!'}),
  48. '-p tcp ! --syn')
  49. self.assertEqual(iptables.build_rule(dports=[80, 443], protocol='tcp'),
  50. '-p tcp -m multiport --dports 80,443')
  51. self.assertEqual(iptables.build_rule(dports='80,443', protocol='tcp'),
  52. '-p tcp -m multiport --dports 80,443')
  53. # Should it really behave this way?
  54. self.assertEqual(iptables.build_rule(dports=['!80', 443],
  55. protocol='tcp'),
  56. '-p tcp -m multiport ! --dports 80,443')
  57. self.assertEqual(iptables.build_rule(dports='!80,443', protocol='tcp'),
  58. '-p tcp -m multiport ! --dports 80,443')
  59. self.assertEqual(iptables.build_rule(sports=[80, 443], protocol='tcp'),
  60. '-p tcp -m multiport --sports 80,443')
  61. self.assertEqual(iptables.build_rule(sports='80,443', protocol='tcp'),
  62. '-p tcp -m multiport --sports 80,443')
  63. self.assertEqual(iptables.build_rule('filter', 'INPUT', command='I',
  64. position='3', full=True,
  65. dports='protocol', jump='ACCEPT'),
  66. 'Error: protocol must be specified')
  67. self.assertEqual(iptables.build_rule('filter', 'INPUT', command='I',
  68. position='3', full=True,
  69. sports='protocol', jump='ACCEPT'),
  70. 'Error: protocol must be specified')
  71. self.assertEqual(iptables.build_rule('', 'INPUT', command='I',
  72. position='3', full='True',
  73. match='state', jump='ACCEPT'),
  74. 'Error: Table needs to be specified')
  75. self.assertEqual(iptables.build_rule('filter', '', command='I',
  76. position='3', full='True',
  77. match='state', jump='ACCEPT'),
  78. 'Error: Chain needs to be specified')
  79. self.assertEqual(iptables.build_rule('filter', 'INPUT', command='',
  80. position='3', full='True',
  81. match='state', jump='ACCEPT'),
  82. 'Error: Command needs to be specified')
  83. # Test arguments that should appear after the --jump
  84. self.assertEqual(iptables.build_rule(jump='REDIRECT',
  85. **{'to-port': 8080}),
  86. '--jump REDIRECT --to-port 8080')
  87. # Should quote arguments with spaces, like log-prefix often has
  88. self.assertEqual(iptables.build_rule(jump='LOG',
  89. **{'log-prefix': 'long prefix'}),
  90. '--jump LOG --log-prefix "long prefix"')
  91. # Should quote arguments with leading or trailing spaces
  92. self.assertEqual(iptables.build_rule(jump='LOG',
  93. **{'log-prefix': 'spam: '}),
  94. '--jump LOG --log-prefix "spam: "')
  95. # Should allow no-arg jump options
  96. self.assertEqual(iptables.build_rule(jump='CLUSTERIP',
  97. **{'new': ''}),
  98. '--jump CLUSTERIP --new')
  99. # Should allow no-arg jump options as None
  100. self.assertEqual(iptables.build_rule(jump='CT',
  101. **{'notrack': None}),
  102. '--jump CT --notrack')
  103. # should build match-sets with single string
  104. self.assertEqual(iptables.build_rule(**{'match-set': 'src flag1,flag2'}),
  105. '-m set --match-set src flag1,flag2')
  106. # should build match-sets as list
  107. match_sets = ['src1 flag1',
  108. 'src2 flag2,flag3',
  109. ]
  110. self.assertEqual(iptables.build_rule(**{'match-set': match_sets}),
  111. '-m set --match-set src1 flag1 -m set --match-set src2 flag2,flag3')
  112. # should handle negations for string match-sets
  113. self.assertEqual(iptables.build_rule(**{'match-set': '!src flag'}),
  114. '-m set ! --match-set src flag')
  115. # should handle negations for list match-sets
  116. match_sets = ['src1 flag',
  117. 'not src2 flag2']
  118. self.assertEqual(iptables.build_rule(**{'match-set': match_sets}),
  119. '-m set --match-set src1 flag -m set ! --match-set src2 flag2')
  120. # should allow escaped name
  121. self.assertEqual(iptables.build_rule(**{'match': 'recent', 'name_': 'SSH'}),
  122. '-m recent --name SSH')
  123. # should allow empty arguments
  124. self.assertEqual(iptables.build_rule(**{'match': 'recent', 'update': None}),
  125. '-m recent --update')
  126. # Should allow the --save jump option to CONNSECMARK
  127. #self.assertEqual(iptables.build_rule(jump='CONNSECMARK',
  128. # **{'save': ''}),
  129. # '--jump CONNSECMARK --save ')
  130. ret = '/sbin/iptables --wait -t salt -I INPUT 3 -m state --jump ACCEPT'
  131. with patch.object(iptables, '_iptables_cmd',
  132. MagicMock(return_value='/sbin/iptables')):
  133. self.assertEqual(iptables.build_rule('salt', 'INPUT', command='I',
  134. position='3', full='True',
  135. match='state', jump='ACCEPT'),
  136. ret)
  137. # 'get_saved_rules' function tests: 1
  138. def test_get_saved_rules(self):
  139. '''
  140. Test if it return a data structure of the rules in the conf file
  141. '''
  142. mock = MagicMock(return_value=False)
  143. with patch.object(iptables, '_parse_conf', mock):
  144. self.assertFalse(iptables.get_saved_rules())
  145. mock.assert_called_with(conf_file=None, family='ipv4')
  146. # 'get_rules' function tests: 1
  147. def test_get_rules(self):
  148. '''
  149. Test if it return a data structure of the current, in-memory rules
  150. '''
  151. mock = MagicMock(return_value=False)
  152. with patch.object(iptables, '_parse_conf', mock):
  153. self.assertFalse(iptables.get_rules())
  154. mock.assert_called_with(in_mem=True, family='ipv4')
  155. # 'get_saved_policy' function tests: 1
  156. def test_get_saved_policy(self):
  157. '''
  158. Test if it return the current policy for the specified table/chain
  159. '''
  160. self.assertEqual(iptables.get_saved_policy(table='filter', chain=None,
  161. conf_file=None,
  162. family='ipv4'),
  163. 'Error: Chain needs to be specified')
  164. with patch.object(iptables, '_parse_conf',
  165. MagicMock(return_value={'filter':
  166. {'INPUT':
  167. {'policy': True}}})):
  168. self.assertTrue(iptables.get_saved_policy(table='filter',
  169. chain='INPUT',
  170. conf_file=None,
  171. family='ipv4'))
  172. with patch.object(iptables, '_parse_conf',
  173. MagicMock(return_value={'filter':
  174. {'INPUT':
  175. {'policy1': True}}})):
  176. self.assertIsNone(iptables.get_saved_policy(table='filter',
  177. chain='INPUT',
  178. conf_file=None,
  179. family='ipv4'))
  180. # 'get_policy' function tests: 1
  181. def test_get_policy(self):
  182. '''
  183. Test if it return the current policy for the specified table/chain
  184. '''
  185. self.assertEqual(iptables.get_policy(table='filter', chain=None,
  186. family='ipv4'),
  187. 'Error: Chain needs to be specified')
  188. with patch.object(iptables, '_parse_conf',
  189. MagicMock(return_value={'filter':
  190. {'INPUT':
  191. {'policy': True}}})):
  192. self.assertTrue(iptables.get_policy(table='filter',
  193. chain='INPUT',
  194. family='ipv4'))
  195. with patch.object(iptables, '_parse_conf',
  196. MagicMock(return_value={'filter':
  197. {'INPUT':
  198. {'policy1': True}}})):
  199. self.assertIsNone(iptables.get_policy(table='filter',
  200. chain='INPUT',
  201. family='ipv4'))
  202. # 'set_policy' function tests: 1
  203. def test_set_policy(self):
  204. '''
  205. Test if it set the current policy for the specified table/chain
  206. '''
  207. with patch.object(iptables, '_has_option', MagicMock(return_value=True)):
  208. self.assertEqual(iptables.set_policy(table='filter', chain=None,
  209. policy=None,
  210. family='ipv4'),
  211. 'Error: Chain needs to be specified')
  212. self.assertEqual(iptables.set_policy(table='filter', chain='INPUT',
  213. policy=None,
  214. family='ipv4'),
  215. 'Error: Policy needs to be specified')
  216. mock = MagicMock(return_value=True)
  217. with patch.dict(iptables.__salt__, {'cmd.run': mock}):
  218. self.assertTrue(iptables.set_policy(table='filter',
  219. chain='INPUT',
  220. policy='ACCEPT',
  221. family='ipv4'))
  222. # 'save' function tests: 1
  223. def test_save(self):
  224. '''
  225. Test if it save the current in-memory rules to disk
  226. '''
  227. with patch('salt.modules.iptables._conf', MagicMock(return_value=False)), \
  228. patch('os.path.isdir', MagicMock(return_value=True)):
  229. mock = MagicMock(return_value=True)
  230. with patch.dict(iptables.__salt__, {'cmd.run': mock,
  231. 'file.write': mock,
  232. 'config.option': MagicMock(return_value=[])}):
  233. self.assertTrue(iptables.save(filename='/xyz', family='ipv4'))
  234. # 'check' function tests: 1
  235. def test_check(self):
  236. '''
  237. Test if it check for the existence of a rule in the table and chain
  238. '''
  239. self.assertEqual(iptables.check(table='filter', chain=None,
  240. rule=None,
  241. family='ipv4'),
  242. 'Error: Chain needs to be specified')
  243. self.assertEqual(iptables.check(table='filter', chain='INPUT',
  244. rule=None,
  245. family='ipv4'),
  246. 'Error: Rule needs to be specified')
  247. mock_rule = 'm state --state RELATED,ESTABLISHED -j ACCEPT'
  248. mock_chain = 'INPUT'
  249. mock_uuid = 31337
  250. mock_cmd = MagicMock(return_value='-A {0}\n-A {1}'.format(mock_chain,
  251. hex(mock_uuid)))
  252. mock_has = MagicMock(return_value=True)
  253. mock_not = MagicMock(return_value=False)
  254. with patch.object(iptables, '_has_option', mock_not):
  255. with patch.object(uuid, 'getnode', MagicMock(return_value=mock_uuid)):
  256. with patch.dict(iptables.__salt__, {'cmd.run': mock_cmd}):
  257. self.assertTrue(iptables.check(table='filter', chain=mock_chain,
  258. rule=mock_rule, family='ipv4'))
  259. mock_cmd = MagicMock(return_value='')
  260. with patch.object(iptables, '_has_option', mock_not):
  261. with patch.object(uuid, 'getnode', MagicMock(return_value=mock_uuid)):
  262. with patch.dict(iptables.__salt__, {'cmd.run': MagicMock(return_value='')}):
  263. self.assertFalse(iptables.check(table='filter', chain=mock_chain,
  264. rule=mock_rule, family='ipv4'))
  265. with patch.object(iptables, '_has_option', mock_has):
  266. with patch.dict(iptables.__salt__, {'cmd.run': mock_cmd}):
  267. self.assertTrue(iptables.check(table='filter', chain='INPUT',
  268. rule=mock_rule, family='ipv4'))
  269. mock_cmd = MagicMock(return_value='-A 0x4d2')
  270. mock_uuid = MagicMock(return_value=1234)
  271. with patch.object(iptables, '_has_option', mock_has):
  272. with patch.object(uuid, 'getnode', mock_uuid):
  273. with patch.dict(iptables.__salt__, {'cmd.run': mock_cmd}):
  274. self.assertTrue(iptables.check(table='filter',
  275. chain='0x4d2',
  276. rule=mock_rule, family='ipv4'))
  277. # 'check_chain' function tests: 1
  278. def test_check_chain(self):
  279. '''
  280. Test if it check for the existence of a chain in the table
  281. '''
  282. self.assertEqual(iptables.check_chain(table='filter', chain=None,
  283. family='ipv4'),
  284. 'Error: Chain needs to be specified')
  285. mock_cmd = MagicMock(return_value='')
  286. with patch.dict(iptables.__salt__, {'cmd.run': mock_cmd}):
  287. self.assertFalse(iptables.check_chain(table='filter',
  288. chain='INPUT',
  289. family='ipv4'))
  290. # 'new_chain' function tests: 1
  291. def test_new_chain(self):
  292. '''
  293. Test if it create new custom chain to the specified table.
  294. '''
  295. self.assertEqual(iptables.new_chain(table='filter', chain=None,
  296. family='ipv4'),
  297. 'Error: Chain needs to be specified')
  298. mock_cmd = MagicMock(return_value='')
  299. with patch.dict(iptables.__salt__, {'cmd.run': mock_cmd}):
  300. self.assertTrue(iptables.new_chain(table='filter',
  301. chain='INPUT',
  302. family='ipv4'))
  303. # 'delete_chain' function tests: 1
  304. def test_delete_chain(self):
  305. '''
  306. Test if it delete custom chain to the specified table.
  307. '''
  308. self.assertEqual(iptables.delete_chain(table='filter', chain=None,
  309. family='ipv4'),
  310. 'Error: Chain needs to be specified')
  311. mock_cmd = MagicMock(return_value='')
  312. with patch.dict(iptables.__salt__, {'cmd.run': mock_cmd}):
  313. self.assertTrue(iptables.delete_chain(table='filter',
  314. chain='INPUT',
  315. family='ipv4'))
  316. # 'append' function tests: 1
  317. def test_append(self):
  318. '''
  319. Test if it append a rule to the specified table/chain.
  320. '''
  321. with patch.object(iptables, '_has_option', MagicMock(return_value=True)), \
  322. patch.object(iptables, 'check', MagicMock(return_value=False)):
  323. self.assertEqual(iptables.append(table='filter', chain=None,
  324. rule=None,
  325. family='ipv4'),
  326. 'Error: Chain needs to be specified')
  327. self.assertEqual(iptables.append(table='filter', chain='INPUT',
  328. rule=None,
  329. family='ipv4'),
  330. 'Error: Rule needs to be specified')
  331. _rule = 'm state --state RELATED,ESTABLISHED -j ACCEPT'
  332. mock = MagicMock(side_effect=['', 'SALT'])
  333. with patch.dict(iptables.__salt__, {'cmd.run': mock}):
  334. self.assertTrue(iptables.append(table='filter', chain='INPUT',
  335. rule=_rule, family='ipv4'))
  336. self.assertFalse(iptables.append(table='filter', chain='INPUT',
  337. rule=_rule, family='ipv4'))
  338. # 'insert' function tests: 1
  339. def test_insert(self):
  340. '''
  341. Test if it insert a rule into the specified table/chain,
  342. at the specified position.
  343. '''
  344. with patch.object(iptables, '_has_option', MagicMock(return_value=True)), \
  345. patch.object(iptables, 'check', MagicMock(return_value=False)):
  346. self.assertEqual(iptables.insert(table='filter', chain=None,
  347. position=None, rule=None,
  348. family='ipv4'),
  349. 'Error: Chain needs to be specified')
  350. pos_err = 'Error: Position needs to be specified or use append (-A)'
  351. self.assertEqual(iptables.insert(table='filter', chain='INPUT',
  352. position=None, rule=None,
  353. family='ipv4'), pos_err)
  354. self.assertEqual(iptables.insert(table='filter', chain='INPUT',
  355. position=3, rule=None,
  356. family='ipv4'),
  357. 'Error: Rule needs to be specified')
  358. _rule = 'm state --state RELATED,ESTABLISHED -j ACCEPT'
  359. mock = MagicMock(return_value=True)
  360. with patch.dict(iptables.__salt__, {'cmd.run': mock}):
  361. self.assertTrue(iptables.insert(table='filter', chain='INPUT',
  362. position=3, rule=_rule,
  363. family='ipv4'))
  364. # 'delete' function tests: 1
  365. def test_delete(self):
  366. '''
  367. Test if it delete a rule from the specified table/chain
  368. '''
  369. with patch.object(iptables, '_has_option', MagicMock(return_value=True)):
  370. _rule = 'm state --state RELATED,ESTABLISHED -j ACCEPT'
  371. self.assertEqual(iptables.delete(table='filter', chain=None,
  372. position=3, rule=_rule,
  373. family='ipv4'),
  374. 'Error: Only specify a position or a rule, not both')
  375. mock = MagicMock(return_value=True)
  376. with patch.dict(iptables.__salt__, {'cmd.run': mock}):
  377. self.assertTrue(iptables.delete(table='filter', chain='INPUT',
  378. position=3, rule='',
  379. family='ipv4'))
  380. # 'flush' function tests: 1
  381. def test_flush(self):
  382. '''
  383. Test if it flush the chain in the specified table,
  384. flush all chains in the specified table if not specified chain.
  385. '''
  386. with patch.object(iptables, '_has_option', MagicMock(return_value=True)):
  387. mock_cmd = MagicMock(return_value=True)
  388. with patch.dict(iptables.__salt__, {'cmd.run': mock_cmd}):
  389. self.assertTrue(iptables.flush(table='filter',
  390. chain='INPUT',
  391. family='ipv4'))