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.
8 from pymin.seqtools import Sequence
9 from pymin.dispatcher import Handler, handler, HandlerError
10 from pymin.services.util import Restorable, ConfigWriter, ServiceHandler, \
11 TransactionalHandler, ListSubHandler
13 __ALL__ = ('FirewallHandler', 'Error')
15 class Error(HandlerError):
17 Error(command) -> Error instance :: Base FirewallHandler exception class.
19 All exceptions raised by the FirewallHandler inherits from this one, so you can
20 easily catch any FirewallHandler exception.
22 message - A descriptive error message.
27 r"""Rule(chain, target[, src[, dst[, ...]]]) -> Rule instance.
29 chain - INPUT, OUTPUT or FORWARD.
30 target - ACCEPT, REJECT or DROP.
31 src - Source subnet as IP/mask.
32 dst - Destination subnet as IP/mask.
33 protocol - ICMP, UDP, TCP or ALL.
34 src_port - Source port (only for UDP or TCP protocols).
35 dst_port - Destination port (only for UDP or TCP protocols).
38 def __init__(self, chain, target, src=None, dst=None, protocol=None,
39 src_port=None, dst_port=None):
40 r"Initialize object, see class documentation for details."
45 self.protocol = protocol
46 # TODO Validate that src_port and dst_port could be not None only
47 # if the protocol is UDP or TCP
48 self.src_port = src_port
49 self.dst_port = dst_port
51 def update(self, chain=None, target=None, src=None, dst=None, protocol=None,
52 src_port=None, dst_port=None):
53 r"update([chain[, ...]]) -> Update the values of a rule (see Rule doc)."
54 if chain is not None: self.chain = chain
55 if target is not None: self.target = target
56 if src is not None: self.src = src
57 if dst is not None: self.dst = dst
58 if protocol is not None: self.protocol = protocol
59 # TODO Validate that src_port and dst_port could be not None only
60 # if the protocol is UDP or TCP
61 if src_port is not None: self.src_port = src_port
62 if dst_port is not None: self.dst_port = dst_port
65 r"Return a tuple representing the rule."
66 return (self.chain, self.target, self.src, self.dst, self.protocol,
67 self.src_port, self.dst_port)
69 class RuleHandler(ListSubHandler):
70 r"""RuleHandler(parent) -> RuleHandler instance :: Handle a list of rules.
72 This class is a helper for FirewallHandler to do all the work related to rules
75 parent - The parent service handler.
78 handler_help = u"Manage firewall rules"
80 _cont_subhandler_attr = 'rules'
81 _cont_subhandler_class = Rule
83 class FirewallHandler(Restorable, ConfigWriter, ServiceHandler,
84 TransactionalHandler):
85 r"""FirewallHandler([pickle_dir[, config_dir]]) -> FirewallHandler instance.
87 Handles firewall commands using iptables.
89 pickle_dir - Directory where to write the persistent configuration data.
91 config_dir - Directory where to store de generated configuration files.
93 Both defaults to the current working directory.
96 handler_help = u"Manage firewall service"
98 _persistent_attrs = 'rules'
100 _restorable_defaults = dict(rules=list())
102 _config_writer_files = 'iptables.sh'
103 _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
105 def __init__(self, pickle_dir='.', config_dir='.'):
106 r"Initialize the object, see class documentation for details."
107 self._persistent_dir = pickle_dir
108 self._config_writer_cfg_dir = config_dir
109 self._service_start = ('sh', path.join(self._config_writer_cfg_dir,
110 self._config_writer_files))
111 self._service_stop = ('iptables', '-t', 'filter', '-F')
112 self._service_restart = self._service_start
113 self._service_reload = self._service_start
114 self._config_build_templates()
116 self.rule = RuleHandler(self)
118 def _get_config_vars(self, config_file):
119 return dict(rules=self.rules)
122 if __name__ == '__main__':
126 fw_handler = FirewallHandler()
131 print fw_handler.rule.show()
136 fw_handler.rule.add('input','drop','icmp')
138 fw_handler.rule.update(0, dst='192.168.0.188/32')
140 fw_handler.rule.add('output','accept', '192.168.1.0/24')
148 os.system('rm -f *.pkl iptables.sh')