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, SubHandler
13 __ALL__ = ('FirewallHandler', 'Error', 'RuleError', 'RuleAlreadyExistsError',
16 class Error(HandlerError):
18 Error(command) -> Error instance :: Base FirewallHandler exception class.
20 All exceptions raised by the FirewallHandler inherits from this one, so you can
21 easily catch any FirewallHandler exception.
23 message - A descriptive error message.
27 class RuleError(Error, KeyError):
29 RuleError(rule) -> RuleError instance.
31 This is the base exception for all rule related errors.
34 def __init__(self, rule):
35 r"Initialize the object. See class documentation for more info."
36 self.message = u'Rule error: "%s"' % rule
38 class RuleAlreadyExistsError(RuleError):
40 RuleAlreadyExistsError(rule) -> RuleAlreadyExistsError instance.
42 This exception is raised when trying to add a rule that already exists.
45 def __init__(self, rule):
46 r"Initialize the object. See class documentation for more info."
47 self.message = u'Rule already exists: "%s"' % rule
49 class RuleNotFoundError(RuleError):
51 RuleNotFoundError(rule) -> RuleNotFoundError instance.
53 This exception is raised when trying to operate on a rule that doesn't
57 def __init__(self, rule):
58 r"Initialize the object. See class documentation for more info."
59 self.message = u'Rule not found: "%s"' % rule
63 r"""Rule(chain, target[, src[, dst[, ...]]]) -> Rule instance.
65 chain - INPUT, OUTPUT or FORWARD.
66 target - ACCEPT, REJECT or DROP.
67 src - Source subnet as IP/mask.
68 dst - Destination subnet as IP/mask.
69 protocol - ICMP, UDP, TCP or ALL.
70 src_port - Source port (only for UDP or TCP protocols).
71 dst_port - Destination port (only for UDP or TCP protocols).
74 def __init__(self, chain, target, src=None, dst=None, protocol=None,
75 src_port=None, dst_port=None):
76 r"Initialize object, see class documentation for details."
81 self.protocol = protocol
82 # TODO Validate that src_port and dst_port could be not None only
83 # if the protocol is UDP or TCP
84 self.src_port = src_port
85 self.dst_port = dst_port
87 def update(self, chain=None, target=None, src=None, dst=None, protocol=None,
88 src_port=None, dst_port=None):
89 r"update([chain[, ...]]) -> Update the values of a rule (see Rule doc)."
90 if chain is not None: self.chain = chain
91 if target is not None: self.target = target
92 if src is not None: self.src = src
93 if dst is not None: self.dst = dst
94 if protocol is not None: self.protocol = protocol
95 # TODO Validate that src_port and dst_port could be not None only
96 # if the protocol is UDP or TCP
97 if src_port is not None: self.src_port = src_port
98 if dst_port is not None: self.dst_port = dst_port
100 def __cmp__(self, other):
101 r"Compares two Rule objects."
102 if self.chain == other.chain \
103 and self.target == other.target \
104 and self.src == other.src \
105 and self.dst == other.dst \
106 and self.protocol == other.protocol \
107 and self.src_port == other.src_port \
108 and self.dst_port == other.dst_port:
110 return cmp(id(self), id(other))
113 r"Return a tuple representing the rule."
114 return (self.chain, self.target, self.src, self.dst, self.protocol,
115 self.src_port, self.dst_port)
117 class RuleHandler(SubHandler):
118 r"""RuleHandler(rules) -> RuleHandler instance :: Handle a list of rules.
120 This class is a helper for FirewallHandler to do all the work related to rules
123 parent - The parent service handler.
126 handler_help = u"Manage firewall rules"
128 @handler(u'Add a new rule')
129 def add(self, *args, **kwargs):
130 r"add(rule) -> None :: Add a rule to the rules list (see Rule doc)."
131 rule = Rule(*args, **kwargs)
132 if rule in self.parent.rules:
133 raise RuleAlreadyExistsError(rule)
134 self.parent.rules.append(rule)
136 @handler(u'Update a rule')
137 def update(self, index, *args, **kwargs):
138 r"update(index, rule) -> None :: Update a rule (see Rule doc)."
139 # TODO check if the modified rule is the same of an existing one
140 index = int(index) # TODO validation
142 self.parent.rules[index].update(*args, **kwargs)
144 raise RuleNotFoundError(index)
146 @handler(u'Delete a rule')
147 def delete(self, index):
148 r"delete(index) -> Rule :: Delete a rule from the list returning it."
149 index = int(index) # TODO validation
151 return self.parent.rules.pop(index)
153 raise RuleNotFoundError(index)
155 @handler(u'Get information about a rule')
156 def get(self, index):
157 r"get(rule) -> Rule :: Get all the information about a rule."
158 index = int(index) # TODO validation
160 return self.parent.rules[index]
162 raise RuleNotFoundError(index)
164 @handler(u'Get information about all rules')
166 r"show() -> list of Rules :: List all the complete rules information."
167 return self.parent.rules
170 class FirewallHandler(Restorable, ConfigWriter, ServiceHandler,
171 TransactionalHandler):
172 r"""FirewallHandler([pickle_dir[, config_dir]]) -> FirewallHandler instance.
174 Handles firewall commands using iptables.
176 pickle_dir - Directory where to write the persistent configuration data.
178 config_dir - Directory where to store de generated configuration files.
180 Both defaults to the current working directory.
183 handler_help = u"Manage firewall service"
185 _persistent_attrs = 'rules'
187 _restorable_defaults = dict(rules=list())
189 _config_writer_files = 'iptables.sh'
190 _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
192 def __init__(self, pickle_dir='.', config_dir='.'):
193 r"Initialize the object, see class documentation for details."
194 self._persistent_dir = pickle_dir
195 self._config_writer_cfg_dir = config_dir
196 self._service_start = ('sh', path.join(self._config_writer_cfg_dir,
197 self._config_writer_files))
198 self._service_stop = ('iptables', '-t', 'filter', '-F')
199 self._service_restart = self._service_start
200 self._service_reload = self._service_start
201 self._config_build_templates()
203 self.rule = RuleHandler(self)
205 def _get_config_vars(self, config_file):
206 return dict(rules=self.rules)
209 if __name__ == '__main__':
213 fw_handler = FirewallHandler()
218 print fw_handler.rule.show()
223 fw_handler.rule.add('input','drop','icmp')
225 fw_handler.rule.update(0, dst='192.168.0.188/32')
227 fw_handler.rule.add('output','accept', '192.168.1.0/24')
235 os.system('rm -f *.pkl iptables.sh')