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, \
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,
117 class RuleHandler(Handler):
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 rules - A list of Rule objects.
126 handler_help = u"Manage firewall rules"
128 def __init__(self, rules):
129 r"Initialize the object, see class documentation for details."
132 @handler(u'Add a new rule')
133 def add(self, *args, **kwargs):
134 r"add(rule) -> None :: Add a rule to the rules list (see Rule doc)."
135 rule = Rule(*args, **kwargs)
136 if rule in self.rules:
137 raise RuleAlreadyExistsError(rule)
138 self.rules.append(rule)
140 @handler(u'Update a rule')
141 def update(self, index, *args, **kwargs):
142 r"update(index, rule) -> None :: Update a rule (see Rule doc)."
143 # TODO check if the modified rule is the same of an existing one
144 index = int(index) # TODO validation
146 self.rules[index].update(*args, **kwargs)
148 raise RuleNotFoundError(index)
150 @handler(u'Delete a rule')
151 def delete(self, index):
152 r"delete(index) -> Rule :: Delete a rule from the list returning it."
153 index = int(index) # TODO validation
155 return self.rules.pop(index)
157 raise RuleNotFoundError(index)
159 @handler(u'Get information about a rule')
160 def get(self, index):
161 r"get(rule) -> Rule :: Get all the information about a rule."
162 index = int(index) # TODO validation
164 return self.rules[index]
166 raise RuleNotFoundError(index)
168 @handler(u'Get information about all rules')
170 r"show() -> list of Rules :: List all the complete rules information."
174 class FirewallHandler(Restorable, ConfigWriter, ServiceHandler,
175 TransactionalHandler):
176 r"""FirewallHandler([pickle_dir[, config_dir]]) -> FirewallHandler instance.
178 Handles firewall commands using iptables.
180 pickle_dir - Directory where to write the persistent configuration data.
182 config_dir - Directory where to store de generated configuration files.
184 Both defaults to the current working directory.
187 handler_help = u"Manage firewall service"
189 _persistent_attrs = 'rules'
191 _restorable_defaults = dict(rules=list())
193 _config_writer_files = 'iptables.sh'
194 _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
196 def __init__(self, pickle_dir='.', config_dir='.'):
197 r"Initialize the object, see class documentation for details."
198 self._persistent_dir = pickle_dir
199 self._config_writer_cfg_dir = config_dir
200 self._service_start = path.join(self._config_writer_cfg_dir,
201 self._config_writer_files)
202 self._service_stop = ('iptables', '-t', 'filter', '-F')
203 self._service_restart = self._service_start
204 self._service_reload = self._service_start
205 self._config_build_templates()
207 self.rule = RuleHandler(self.rules)
209 def _get_config_vars(self, config_file):
210 return dict(rules=self.rules)
213 if __name__ == '__main__':
217 fw_handler = FirewallHandler()
222 print fw_handler.rule.show()
227 fw_handler.rule.add('input','drop','icmp')
229 fw_handler.rule.update(0, dst='192.168.0.188/32')
231 fw_handler.rule.add('output','accept', '192.168.1.0/24')
239 os.system('rm -f *.pkl iptables.sh')