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.services.util import Restorable, ConfigWriter, ServiceHandler, \
15 TransactionalHandler, ListSubHandler
17 __all__ = ('FirewallHandler',)
20 def validate_python(self, value, state):
22 return OneOf.validate_python(self, value, state)
25 r"""Rule(chain, target[, src[, dst[, ...]]]) -> Rule instance.
27 chain - INPUT, OUTPUT or FORWARD.
28 target - ACCEPT, REJECT or DROP.
29 src - Source subnet as IP/mask.
30 dst - Destination subnet as IP/mask.
31 protocol - ICMP, UDP, TCP or ALL.
32 src_port - Source port (only for UDP or TCP protocols).
33 dst_port - Destination port (only for UDP or TCP protocols).
35 chain = Field(UpOneOf(['INPUT', 'OUTPUT', 'FORWARD'], not_empty=True))
36 target = Field(UpOneOf(['ACCEPT', 'REJECT', 'DROP'], not_empty=True))
37 src = Field(CIDR(if_empty=None, if_missing=None))
38 dst = Field(CIDR(if_empty=None, if_missing=None))
39 protocol = Field(UpOneOf(['ICMP', 'UDP', 'TCP', 'ALL'], if_missing=None))
40 src_port = Field(Int(min=0, max=65535, if_empty=None, if_missing=None))
41 dst_port = Field(Int(min=0, max=65535, if_empty=None, if_missing=None))
42 def chained_validator(self, fields, state):
44 if fields['protocol'] not in ('TCP', 'UDP'):
45 for name in ('src_port', 'dst_port'):
46 if fields[name] is not None:
47 errors[name] = u"Should be None if protocol " \
48 "(%(protocol)s) is not TCP or UDP" % fields
50 raise Invalid(u"You can't specify any ports if the protocol "
51 u'is not TCP or UDP', fields, state, error_dict=errors)
53 class RuleHandler(ListSubHandler):
54 r"""RuleHandler(parent) -> RuleHandler instance :: Handle a list of rules.
56 This class is a helper for FirewallHandler to do all the work related to rules
59 parent - The parent service handler.
62 handler_help = u"Manage firewall rules"
64 _cont_subhandler_attr = 'rules'
65 _cont_subhandler_class = Rule
67 class FirewallHandler(Restorable, ConfigWriter, ServiceHandler,
68 TransactionalHandler):
69 r"""FirewallHandler([pickle_dir[, config_dir]]) -> FirewallHandler instance.
71 Handles firewall commands using iptables.
73 pickle_dir - Directory where to write the persistent configuration data.
75 config_dir - Directory where to store de generated configuration files.
77 Both defaults to the current working directory.
80 handler_help = u"Manage firewall service"
82 _persistent_attrs = ['rules']
84 _restorable_defaults = dict(rules=list())
86 _config_writer_files = 'iptables.sh'
87 _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
89 def __init__(self, pickle_dir='.', config_dir='.'):
90 r"Initialize the object, see class documentation for details."
91 log.debug(u'FirewallHandler(%r, %r)', pickle_dir, config_dir)
92 self._persistent_dir = pickle_dir
93 self._config_writer_cfg_dir = config_dir
94 self._service_start = ('sh', path.join(self._config_writer_cfg_dir,
95 self._config_writer_files))
96 self._service_stop = ('iptables', '-t', 'filter', '-F')
97 self._service_restart = self._service_start
98 self._service_reload = self._service_start
99 self._config_build_templates()
100 ServiceHandler.__init__(self)
101 self.rule = RuleHandler(self)
103 def _get_config_vars(self, config_file):
104 return dict(rules=self.rules)
107 if __name__ == '__main__':
110 level = logging.DEBUG,
111 format = '%(asctime)s %(levelname)-8s %(message)s',
112 datefmt = '%H:%M:%S',
117 fw_handler = FirewallHandler()
122 print fw_handler.rule.show()
127 fw_handler.rule.add('input', 'drop', protocol='icmp')
129 fw_handler.rule.update(0, dst='192.168.0.188/32')
131 fw_handler.rule.add('output', 'accept', '192.168.1.0/24')
139 os.system('rm -f *.pkl iptables.sh')