1 # vim: set encoding=utf-8 et sw=4 sts=4 :
5 from pymin.seqtools import Sequence
6 from pymin.dispatcher import Handler, handler, HandlerError
7 from pymin.services.util import Restorable, ConfigWriter, RestartHandler, \
8 ReloadHandler, TransactionalHandler, \
11 __ALL__ = ('NatHandler', 'Error')
13 class Error(HandlerError):
15 Error(command) -> Error instance :: Base NatHandler exception class.
17 All exceptions raised by the NatHandler inherits from this one, so you can
18 easily catch any NatHandler exception.
20 message - A descriptive error message.
24 class PortForward(Sequence):
25 r"""PortForward(dev, protocol, port, dst[, dst_port[, ...]]) -> PortForward.
27 dev - Netword device to use.
28 protocol - TCP or UDP.
29 port - Port to forward.
30 dst - Destination IP address.
31 dst_port - Destination port (at dst).
32 src_net - Source network to apply the forward (as IP/mask).
33 dst_net - Source network to apply the forward (as IP/mask).
36 def __init__(self, dev, protocol, port, dst, dst_port=None, src_net=None,
38 r"Initialize object, see class documentation for details."
41 self.protocol = protocol
44 self.dst_port = dst_port
45 self.src_net = src_net
46 self.dst_net = dst_net
48 def update(self, dev=None, protocol=None, port=None, dst=None,
49 dst_port=None, src_net=None, dst_net=None):
50 r"update([dev[, ...]]) -> Update the values of a port (see class doc)."
52 if dev is not None: self.dev = dev
53 if protocol is not None: self.protocol = protocol
54 if port is not None: self.port = port
55 if dst is not None: self.dst = dst
56 if dst_port is not None: self.dst_port = dst_port
57 if src_net is not None: self.src_net = src_net
58 if dst_net is not None: self.dst_net = dst_net
61 r"Return a tuple representing the port forward."
62 return (self.dev, self.protocol, self.port, self.dst, self.dst_port,
63 self.src_net, self.dst_net)
65 def as_call_list(self, index=None):
66 if self.dst_port is not None:
67 self.dst = self.dst + ':' + self.dst_port
68 cmd = ['-t', 'nat', '-I', 'PREROUTING']
70 cmd.append(str(index))
71 cmd.extend(('-i', self.dev, '-j', 'DNAT', '--to', self.dst,
72 '-p', self.protocol, '--dport', self.port))
73 if self.src_net is not None:
74 cmd.extend(('-s', self.src_net))
75 if self.dst_net is not None:
76 cmd.extend(('-d', self.dst_net))
79 class PortForwardHandler(ListSubHandler):
80 r"""PortForwardHandler(parent) -> PortForwardHandler instance.
82 This class is a helper for NatHandler to do all the work related to port
85 parent - The parent service handler.
88 handler_help = u"Manage NAT port forwarding."
90 _cont_subhandler_attr = 'ports'
91 _cont_subhandler_class = PortForward
94 r"""SNat(dev, src[, src_net]) -> SNat instance.
96 dev - Netword device to use.
97 src - Source IP address.
98 src_net - Source network to apply the NAT (as IP/mask).
101 def __init__(self, dev, src, src_net=None):
102 r"Initialize object, see class documentation for details."
106 self.src_net = src_net
108 def update(self, dev=None, src=None, src_net=None):
109 r"update([dev[, ...]]) -> Update the values of a snat (see class doc)."
111 if dev is not None: self.dev = dev
112 if src is not None: self.src = src
113 if src_net is not None: self.src_net = src_net
115 def __cmp__(self, other):
116 r"Compares two SNat objects."
117 return cmp(self.as_tuple(), other.as_tuple())
120 r"Return a tuple representing the snat."
121 return (self.dev, self.src, self.src_net)
123 def as_call_list(self, index=None):
124 cmd = ['-t', 'nat', '-I', 'POSTROUTING']
125 if index is not None:
126 cmd.append(str(index))
127 cmd.extend(('-o', self.dev, '-j', 'SNAT', '--to', self.src))
128 if self.src_net is not None:
129 cmd.extend(('-s', self.src_net))
132 class SNatHandler(ListSubHandler):
133 r"""SNatHandler(parent) -> SNatHandler instance.
135 This class is a helper for NatHandler to do all the work related to
138 parent - The parent service handler.
141 handler_help = u"Manage source NAT."
143 _cont_subhandler_attr = 'snats'
144 _cont_subhandler_class = SNat
146 class Masq(Sequence):
147 r"""Masq(dev, src_net) -> Masq instance.
149 dev - Netword device to use.
150 src_net - Source network to apply the masquerade (as IP/mask).
153 def __init__(self, dev, src_net):
154 r"Initialize object, see class documentation for details."
157 self.src_net = src_net
159 def update(self, dev=None, src_net=None):
160 r"update([dev[, ...]]) -> Update the values of a masq (see class doc)."
162 if dev is not None: self.dev = dev
163 if src_net is not None: self.src_net = src_net
165 def __cmp__(self, other):
166 r"Compares two Masq objects."
167 return cmp(self.as_tuple(), other.as_tuple())
170 r"Return a tuple representing the masquerade."
171 return (self.dev, self.src_net)
173 def as_call_list(self, index=None):
174 cmd = ['-t', 'nat', '-I', 'POSTROUTING']
175 if index is not None:
176 cmd.append(str(index))
177 cmd.extend(('-o', self.dev, '-j', 'MASQUERADE', '-s', self.src_net))
180 class MasqHandler(ListSubHandler):
181 r"""MasqHandler(parent) -> MasqHandler instance.
183 This class is a helper for NatHandler to do all the work related to
186 parent - The parent service handler.
189 handler_help = u"Manage NAT masquerading."
191 _cont_subhandler_attr = 'masqs'
192 _cont_subhandler_class = Masq
194 class NatHandler(Restorable, ConfigWriter, RestartHandler, ReloadHandler,
195 TransactionalHandler):
196 r"""NatHandler([pickle_dir[, config_dir]]) -> NatHandler instance.
198 Handles NAT commands using iptables.
200 pickle_dir - Directory where to write the persistent configuration data.
202 config_dir - Directory where to store de generated configuration files.
204 Both defaults to the current working directory.
207 handler_help = u"Manage NAT (Network Address Translation) service."
209 _persistent_attrs = ('ports', 'snats', 'masqs')
211 _restorable_defaults = dict(
217 @handler(u'Start the service.')
219 for (index, port) in enumerate(self.ports):
220 call(['iptables'] + port.as_call_list(index+1))
221 for (index, snat) in enumerate(self.snats):
222 call(['iptables'] + snat.as_call_list(index+1))
223 for (index, masq) in enumerate(self.masqs):
224 call(['iptables'] + masq.as_call_list(index+1))
226 @handler(u'Stop the service.')
228 call(('iptables', '-t', 'nat', '-F'))
230 def __init__(self, pickle_dir='.'):
231 r"Initialize the object, see class documentation for details."
232 self._persistent_dir = pickle_dir
234 self.forward = PortForwardHandler(self)
235 self.snat = SNatHandler(self)
236 self.masq = MasqHandler(self)
239 if __name__ == '__main__':
243 handler = NatHandler()
247 print 'Forwarded ports:'
248 print handler.forward.show()
251 print handler.snat.show()
254 print handler.masq.show()
258 handler.forward.add('eth0','tcp','80', '192.168.0.9', '8080')
259 handler.forward.update(0, dst_net='192.168.0.188/32')
260 handler.forward.add('eth0', 'udp', '53', '192.168.1.0')
264 handler.snat.add('eth0', '192.168.0.9')
265 handler.snat.update(0, src_net='192.168.0.188/32')
266 handler.snat.add('eth0', '192.168.1.0')
270 handler.masq.add('eth0', '192.168.0.9/24')
271 handler.masq.update(0, src_net='192.168.0.188/30')
272 handler.masq.add('eth1', '192.168.1.0/24')
276 os.system('rm -f *.pkl')