1 # vim: set encoding=utf-8 et sw=4 sts=4 :
3 # TODO See if it's better (more secure) to execute commands via python instead
4 # of using script templates.
7 import logging ; log = logging.getLogger('pymin.services.firewall')
9 from pymin.service.util import Restorable, ConfigWriter, ServiceHandler, \
12 from rule import RuleHandler
14 __all__ = ('FirewallHandler',)
17 class FirewallHandler(Restorable, ConfigWriter, ServiceHandler,
18 TransactionalHandler):
19 r"""FirewallHandler([pickle_dir[, config_dir]]) -> FirewallHandler instance.
21 Handles firewall commands using iptables.
23 pickle_dir - Directory where to write the persistent configuration data.
25 config_dir - Directory where to store de generated configuration files.
27 Both defaults to the current working directory.
30 handler_help = u"Manage firewall service"
32 _persistent_attrs = ['rules']
34 _restorable_defaults = dict(rules=list())
36 _config_writer_files = 'iptables.sh'
37 _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
39 def __init__(self, pickle_dir='.', config_dir='.'):
40 r"Initialize the object, see class documentation for details."
41 log.debug(u'FirewallHandler(%r, %r)', pickle_dir, config_dir)
42 self._persistent_dir = pickle_dir
43 self._config_writer_cfg_dir = config_dir
44 self._service_start = ('sh', path.join(self._config_writer_cfg_dir,
45 self._config_writer_files))
46 self._service_stop = ('iptables', '-t', 'filter', '-F')
47 self._service_restart = self._service_start
48 self._service_reload = self._service_start
49 self._config_build_templates()
50 ServiceHandler.__init__(self)
51 self.rule = RuleHandler(self)
53 def _get_config_vars(self, config_file):
54 return dict(rules=self.rules)
57 if __name__ == '__main__':
60 level = logging.DEBUG,
61 format = '%(asctime)s %(levelname)-8s %(message)s',
67 fw_handler = FirewallHandler()
72 print fw_handler.rule.show()
77 fw_handler.rule.add('input', 'drop', protocol='icmp')
79 fw_handler.rule.update(0, dst='192.168.0.188/32')
81 fw_handler.rule.add('output', 'accept', '192.168.1.0/24')
89 os.system('rm -f *.pkl iptables.sh')