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 from formencode import Invalid
8 from formencode.validators import OneOf, CIDR, Int
9 import logging ; log = logging.getLogger('pymin.services.firewall')
11 from pymin.item import Item
12 from pymin.validatedclass import Field
13 from pymin.dispatcher import Handler, handler, HandlerError
14 from pymin.service.util import Restorable, ConfigWriter, ServiceHandler, \
15 TransactionalHandler, ListSubHandler
17 __all__ = ('FirewallHandler')
21 def validate_python(self, value, state):
23 return OneOf.validate_python(self, value, state)
26 r"""Rule(chain, target[, src[, dst[, ...]]]) -> Rule instance.
28 chain - INPUT, OUTPUT or FORWARD.
29 target - ACCEPT, REJECT or DROP.
30 src - Source subnet as IP/mask.
31 dst - Destination subnet as IP/mask.
32 protocol - ICMP, UDP, TCP or ALL.
33 src_port - Source port (only for UDP or TCP protocols).
34 dst_port - Destination port (only for UDP or TCP protocols).
36 chain = Field(UpOneOf(['INPUT', 'OUTPUT', 'FORWARD'], not_empty=True))
37 target = Field(UpOneOf(['ACCEPT', 'REJECT', 'DROP'], not_empty=True))
38 src = Field(CIDR(if_empty=None, if_missing=None))
39 dst = Field(CIDR(if_empty=None, if_missing=None))
40 protocol = Field(UpOneOf(['ICMP', 'UDP', 'TCP', 'ALL'], if_missing=None))
41 src_port = Field(Int(min=0, max=65535, if_empty=None, if_missing=None))
42 dst_port = Field(Int(min=0, max=65535, if_empty=None, if_missing=None))
43 def chained_validator(self, fields, state):
45 if fields['protocol'] not in ('TCP', 'UDP'):
46 for name in ('src_port', 'dst_port'):
47 if fields[name] is not None:
48 errors[name] = u"Should be None if protocol " \
49 "(%(protocol)s) is not TCP or UDP" % fields
51 raise Invalid(u"You can't specify any ports if the protocol "
52 u'is not TCP or UDP', fields, state, error_dict=errors)
54 class RuleHandler(ListSubHandler):
55 r"""RuleHandler(parent) -> RuleHandler instance :: Handle a list of rules.
57 This class is a helper for FirewallHandler to do all the work related to rules
60 parent - The parent service handler.
63 handler_help = u"Manage firewall rules"
65 _cont_subhandler_attr = 'rules'
66 _cont_subhandler_class = Rule
68 class FirewallHandler(Restorable, ConfigWriter, ServiceHandler,
69 TransactionalHandler):
70 r"""FirewallHandler([pickle_dir[, config_dir]]) -> FirewallHandler instance.
72 Handles firewall commands using iptables.
74 pickle_dir - Directory where to write the persistent configuration data.
76 config_dir - Directory where to store de generated configuration files.
78 Both defaults to the current working directory.
81 handler_help = u"Manage firewall service"
83 _persistent_attrs = ['rules']
85 _restorable_defaults = dict(rules=list())
87 _config_writer_files = 'iptables.sh'
88 _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
90 def __init__(self, pickle_dir='.', config_dir='.'):
91 r"Initialize the object, see class documentation for details."
92 log.debug(u'FirewallHandler(%r, %r)', pickle_dir, config_dir)
93 self._persistent_dir = pickle_dir
94 self._config_writer_cfg_dir = config_dir
95 self._service_start = ('sh', path.join(self._config_writer_cfg_dir,
96 self._config_writer_files))
97 self._service_stop = ('iptables', '-t', 'filter', '-F')
98 self._service_restart = self._service_start
99 self._service_reload = self._service_start
100 self._config_build_templates()
101 ServiceHandler.__init__(self)
102 self.rule = RuleHandler(self)
104 def _get_config_vars(self, config_file):
105 return dict(rules=self.rules)
108 if __name__ == '__main__':
111 level = logging.DEBUG,
112 format = '%(asctime)s %(levelname)-8s %(message)s',
113 datefmt = '%H:%M:%S',
118 fw_handler = FirewallHandler()
123 print fw_handler.rule.show()
128 fw_handler.rule.add('input', 'drop', protocol='icmp')
130 fw_handler.rule.update(0, dst='192.168.0.188/32')
132 fw_handler.rule.add('output', 'accept', '192.168.1.0/24')
140 os.system('rm -f *.pkl iptables.sh')