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 seqtools import Sequence
9 from dispatcher import Handler, handler, HandlerError
10 from services.util import Restorable, ConfigWriter
11 from services.util import ServiceHandler, TransactionalHandler
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.
26 def __init__(self, message):
27 r"Initialize the Error object. See class documentation for more info."
28 self.message = message
33 class RuleError(Error, KeyError):
35 RuleError(rule) -> RuleError instance.
37 This is the base exception for all rule related errors.
40 def __init__(self, rule):
41 r"Initialize the object. See class documentation for more info."
42 self.message = 'Rule error: "%s"' % rule
44 class RuleAlreadyExistsError(RuleError):
46 RuleAlreadyExistsError(rule) -> RuleAlreadyExistsError instance.
48 This exception is raised when trying to add a rule that already exists.
51 def __init__(self, rule):
52 r"Initialize the object. See class documentation for more info."
53 self.message = 'Rule already exists: "%s"' % rule
55 class RuleNotFoundError(RuleError):
57 RuleNotFoundError(rule) -> RuleNotFoundError instance.
59 This exception is raised when trying to operate on a rule that doesn't
63 def __init__(self, rule):
64 r"Initialize the object. See class documentation for more info."
65 self.message = 'Rule not found: "%s"' % rule
68 r"""Rule(chain, target[, src[, dst[, ...]]]) -> Rule instance.
70 chain - INPUT, OUTPUT or FORWARD.
71 target - ACCEPT, REJECT or DROP.
72 src - Source subnet as IP/mask.
73 dst - Destination subnet as IP/mask.
74 protocol - ICMP, UDP, TCP or ALL.
75 src_port - Source port (only for UDP or TCP protocols).
76 dst_port - Destination port (only for UDP or TCP protocols).
79 def __init__(self, chain, target, src=None, dst=None, protocol=None,
80 src_port=None, dst_port=None):
81 r"Initialize object, see class documentation for details."
86 self.protocol = protocol
87 # TODO Validate that src_port and dst_port could be not None only
88 # if the protocol is UDP or TCP
89 self.src_port = src_port
90 self.dst_port = dst_port
92 def update(self, chain=None, target=None, src=None, dst=None, protocol=None,
93 src_port=None, dst_port=None):
94 r"update([chain[, ...]]) -> Update the values of a rule (see Rule doc)."
95 if chain is not None: self.chain = chain
96 if target is not None: self.target = target
97 if src is not None: self.src = src
98 if dst is not None: self.dst = dst
99 if protocol is not None: self.protocol = protocol
100 # TODO Validate that src_port and dst_port could be not None only
101 # if the protocol is UDP or TCP
102 if src_port is not None: self.src_port = src_port
103 if dst_port is not None: self.dst_port = dst_port
105 def __cmp__(self, other):
106 r"Compares two Rule objects."
107 if self.chain == other.chain \
108 and self.target == other.target \
109 and self.src == other.src \
110 and self.dst == other.dst \
111 and self.protocol == other.protocol \
112 and self.src_port == other.src_port \
113 and self.dst_port == other.dst_port:
115 return cmp(id(self), id(other))
118 r"Return a tuple representing the rule."
119 return (self.chain, self.target, self.src, self.dst, self.protocol,
122 class RuleHandler(Handler):
123 r"""RuleHandler(rules) -> RuleHandler instance :: Handle a list of rules.
125 This class is a helper for FirewallHandler to do all the work related to rules
128 rules - A list of Rule objects.
131 def __init__(self, rules):
132 r"Initialize the object, see class documentation for details."
135 @handler(u'Add a new rule.')
136 def add(self, *args, **kwargs):
137 r"add(rule) -> None :: Add a rule to the rules list (see Rule doc)."
138 rule = Rule(*args, **kwargs)
139 if rule in self.rules:
140 raise RuleAlreadyExistsError(rule)
141 self.rules.append(rule)
143 @handler(u'Update a rule.')
144 def update(self, index, *args, **kwargs):
145 r"update(index, rule) -> None :: Update a rule (see Rule doc)."
146 # TODO check if the modified rule is the same of an existing one
147 index = int(index) # TODO validation
149 self.rules[index].update(*args, **kwargs)
151 raise RuleNotFoundError(index)
153 @handler(u'Delete a rule.')
154 def delete(self, index):
155 r"delete(index) -> Rule :: Delete a rule from the list returning it."
156 index = int(index) # TODO validation
158 return self.rules.pop(index)
160 raise RuleNotFoundError(index)
162 @handler(u'Get information about a rule.')
163 def get(self, index):
164 r"get(rule) -> Rule :: Get all the information about a rule."
165 index = int(index) # TODO validation
167 return self.rules[index]
169 raise RuleNotFoundError(index)
171 @handler(u'Get information about all rules.')
173 r"show() -> list of Rules :: List all the complete rules information."
176 class FirewallHandler(Restorable, ConfigWriter, ServiceHandler,
177 TransactionalHandler):
178 r"""FirewallHandler([pickle_dir[, config_dir]]) -> FirewallHandler instance.
180 Handles firewall commands using iptables.
182 pickle_dir - Directory where to write the persistent configuration data.
184 config_dir - Directory where to store de generated configuration files.
186 Both defaults to the current working directory.
189 _persistent_vars = '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)
212 if __name__ == '__main__':
216 fw_handler = FirewallHandler()
221 print fw_handler.rule.show()
226 fw_handler.rule.add('input','drop','icmp')
228 fw_handler.rule.update(0, dst='192.168.0.188/32')
230 fw_handler.rule.add('output','accept', '192.168.1.0/24')
238 os.system('rm -f *.pkl iptables.sh')