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