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.seqtools import Sequence
10 from pymin.dispatcher import Handler, handler, HandlerError
11 from pymin.services.util import Restorable, ConfigWriter, ServiceHandler, \
12 TransactionalHandler, ListSubHandler
14 __ALL__ = ('FirewallHandler',)
17 r"""Rule(chain, target[, src[, dst[, ...]]]) -> Rule instance.
19 chain - INPUT, OUTPUT or FORWARD.
20 target - ACCEPT, REJECT or DROP.
21 src - Source subnet as IP/mask.
22 dst - Destination subnet as IP/mask.
23 protocol - ICMP, UDP, TCP or ALL.
24 src_port - Source port (only for UDP or TCP protocols).
25 dst_port - Destination port (only for UDP or TCP protocols).
28 def __init__(self, chain, target, src=None, dst=None, protocol=None,
29 src_port=None, dst_port=None):
30 r"Initialize object, see class documentation for details."
35 self.protocol = protocol
36 # TODO Validate that src_port and dst_port could be not None only
37 # if the protocol is UDP or TCP
38 self.src_port = src_port
39 self.dst_port = dst_port
41 def update(self, chain=None, target=None, src=None, dst=None, protocol=None,
42 src_port=None, dst_port=None):
43 r"update([chain[, ...]]) -> Update the values of a rule (see Rule doc)."
44 if chain is not None: self.chain = chain
45 if target is not None: self.target = target
46 if src is not None: self.src = src
47 if dst is not None: self.dst = dst
48 if protocol is not None: self.protocol = protocol
49 # TODO Validate that src_port and dst_port could be not None only
50 # if the protocol is UDP or TCP
51 if src_port is not None: self.src_port = src_port
52 if dst_port is not None: self.dst_port = dst_port
55 r"Return a tuple representing the rule."
56 return (self.chain, self.target, self.src, self.dst, self.protocol,
57 self.src_port, self.dst_port)
59 class RuleHandler(ListSubHandler):
60 r"""RuleHandler(parent) -> RuleHandler instance :: Handle a list of rules.
62 This class is a helper for FirewallHandler to do all the work related to rules
65 parent - The parent service handler.
68 handler_help = u"Manage firewall rules"
70 _cont_subhandler_attr = 'rules'
71 _cont_subhandler_class = Rule
73 class FirewallHandler(Restorable, ConfigWriter, ServiceHandler,
74 TransactionalHandler):
75 r"""FirewallHandler([pickle_dir[, config_dir]]) -> FirewallHandler instance.
77 Handles firewall commands using iptables.
79 pickle_dir - Directory where to write the persistent configuration data.
81 config_dir - Directory where to store de generated configuration files.
83 Both defaults to the current working directory.
86 handler_help = u"Manage firewall service"
88 _persistent_attrs = ['rules']
90 _restorable_defaults = dict(rules=list())
92 _config_writer_files = 'iptables.sh'
93 _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
95 def __init__(self, pickle_dir='.', config_dir='.'):
96 r"Initialize the object, see class documentation for details."
97 log.debug(u'FirewallHandler(%r, %r)', pickle_dir, config_dir)
98 self._persistent_dir = pickle_dir
99 self._config_writer_cfg_dir = config_dir
100 self._service_start = ('sh', path.join(self._config_writer_cfg_dir,
101 self._config_writer_files))
102 self._service_stop = ('iptables', '-t', 'filter', '-F')
103 self._service_restart = self._service_start
104 self._service_reload = self._service_start
105 self._config_build_templates()
106 ServiceHandler.__init__(self)
107 self.rule = RuleHandler(self)
109 def _get_config_vars(self, config_file):
110 return dict(rules=self.rules)
113 if __name__ == '__main__':
116 level = logging.DEBUG,
117 format = '%(asctime)s %(levelname)-8s %(message)s',
118 datefmt = '%H:%M:%S',
123 fw_handler = FirewallHandler()
128 print fw_handler.rule.show()
133 fw_handler.rule.add('input','drop','icmp')
135 fw_handler.rule.update(0, dst='192.168.0.188/32')
137 fw_handler.rule.add('output','accept', '192.168.1.0/24')
145 os.system('rm -f *.pkl iptables.sh')