]> git.llucax.com Git - software/pymin.git/blob - services/vpn/handler.py
4f0e04ba31d01a597ad6a004b726093e67367105
[software/pymin.git] / services / vpn / handler.py
1 # vim: set encoding=utf-8 et sw=4 sts=4 :
2
3 import os
4 import errno
5 import signal
6 from os import path
7 import logging ; log = logging.getLogger('pymin.services.vpn')
8
9 from pymin.seqtools import Sequence
10 from pymin.dispatcher import Handler, handler, HandlerError
11 from pymin.service.util import Restorable, ConfigWriter, InitdHandler, \
12                                TransactionalHandler, DictSubHandler, DictComposedSubHandler, call, ExecutionError
13
14 __all__ = ('VpnHandler', 'get_service')
15
16
17 def get_service(config):
18     return VpnHandler(config.vpn.pickle_dir, config.vpn.config_dir)
19
20
21 class Host(Sequence):
22     def __init__(self, vpn_src, ip, vpn_src_net, key):
23         self.name = vpn_src
24         self.ip = ip
25         self.src_net = vpn_src_net
26         self.pub_key = key
27         self._delete = False
28
29     def as_tuple(self):
30         return(self.name, self.ip, self.src_net, self.pub_key)
31
32 class HostHandler(DictComposedSubHandler):
33
34     handler_help = u"Manage hosts for a vpn"
35     _comp_subhandler_cont = 'vpns'
36     _comp_subhandler_attr = 'hosts'
37     _comp_subhandler_class = Host
38
39
40 class Vpn(Sequence):
41     def __init__(self, vpn_src, vpn_dst, vpn_src_ip, vpn_src_mask,
42                     pub_key=None, priv_key=None):
43         self.vpn_src = vpn_src
44         self.vpn_dst = vpn_dst
45         self.vpn_src_ip = vpn_src_ip
46         self.vpn_src_mask = vpn_src_mask
47         self.pub_key = pub_key
48         self.priv_key = priv_key
49         self.hosts = dict()
50         self._delete = False
51
52     def as_tuple(self):
53         return(self.vpn_src, self.vpn_dst, self.vpn_src_ip, self.vpn_src_mask, self.pub_key, self.priv_key)
54
55     def update(self, vpn_dst=None, vpn_src_ip=None, vpn_src_mask=None):
56         if vpn_dst is not None:
57             self.vpn_dst = vpn_dst
58         if vpn_src_ip is not None:
59             self.vpn_src_ip = vpn_src_ip
60         if vpn_src_mask is not None:
61             self.vpn_src_mask = vpn_src_mask
62
63
64 class VpnHandler(Restorable, ConfigWriter,
65                    TransactionalHandler, DictSubHandler):
66
67     handler_help = u"Manage vpn service"
68
69     _cont_subhandler_attr = 'vpns'
70     _cont_subhandler_class = Vpn
71
72     _persistent_attrs = ('vpns','hosts')
73
74     _restorable_defaults = dict(
75             vpns = dict(),
76             hosts = dict(),
77     )
78
79     _config_writer_files = ('tinc.conf','tinc-up','host')
80     _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
81
82     def __init__(self,  pickle_dir='.', config_dir='/etc/tinc'):
83         log.debug(u'VpnHandler(%r, %r)', pickle_dir, config_dir)
84         DictSubHandler.__init__(self, self)
85         self._config_writer_cfg_dir = config_dir
86         self._persistent_dir = pickle_dir
87         self._config_build_templates()
88         self._restore()
89         self.host = HostHandler(self)
90
91     @handler('usage: start <vpn_name>')
92     def start(self, vpn_src):
93         log.debug(u'VpnHandler.start(%r)', vpn_src)
94         if vpn_src in self.vpns:
95             call(('tincd','--net='+ vpn_src))
96
97     @handler('usage: stop <vpn_name>')
98     def stop(self, vpn_src):
99         log.debug(u'VpnHandler.stop(%r)', vpn_src)
100         if vpn_src in self.vpns:
101             pid_file = '/var/run/tinc.' + vpn_src + '.pid'
102             log.debug(u'VpnHandler.stop: getting pid from %r', pid_file)
103             if path.exists(pid_file):
104                 pid = file(pid_file).readline()
105                 pid = int(pid.strip())
106                 try:
107                     log.debug(u'VpnHandler.stop: killing pid %r', pid)
108                     os.kill(pid, signal.SIGTERM)
109                 except OSError:
110                     log.debug(u'VpnHandler.stop: error killing: %r', e)
111             else:
112                 log.debug(u'VpnHandler.stop: pid file not found')
113
114     def _write_config(self):
115         log.debug(u'VpnHandler._write_config()')
116         for v in self.vpns.values():
117             log.debug(u'VpnHandler._write_config: processing %r', v)
118             #chek whether it's been created or not.
119             if not v._delete:
120                 if v.pub_key is None:
121                     log.debug(u'VpnHandler._write_config: new VPN, generating '
122                                 'key...')
123                     try:
124                         log.debug(u'VpnHandler._write_config: creating dir %r',
125                                     path.join(self._config_writer_cfg_dir,
126                                                 v.vpn_src ,'hosts'))
127                         #first create the directory for the vpn
128                         try:
129                             os.makedirs(path.join(self._config_writer_cfg_dir,
130                                                   v.vpn_src, 'hosts'))
131                         except (IOError, OSError), e:
132                             if e.errno != errno.EEXIST:
133                                 raise HandlerError(u"Can't create VPN config "
134                                                    "directory '%s' (%s)'"
135                                                     % (e.filename, e.strerror))
136                         #this command should generate 2 files inside the vpn
137                         #dir, one rsa_key.priv and one rsa_key.pub
138                         #for some reason debian does not work like this
139                         # FIXME if the < /dev/null works, is magic!
140                         log.debug(u'VpnHandler._write_config: creating key...')
141                         call(('tincd', '-n', v.vpn_src, '-K', '<', '/dev/null'))
142                         #open the created files and load the keys
143                         try:
144                             f = file(path.join(self._config_writer_cfg_dir,
145                                                v.vpn_src, 'rsa_key.pub'),
146                                      'r')
147                             pub = f.read()
148                             f.close()
149                         except (IOError, OSError), e:
150                             raise HandlerError(u"Can't read VPN key '%s' (%s)'"
151                                                 % (e.filename, e.strerror))
152
153                         v.pub_key = pub
154                         v.priv_key = priv
155                     except ExecutionError, e:
156                         log.debug(u'VpnHandler._write_config: error executing '
157                                     'the command: %r', e)
158
159                 vars = dict(
160                     vpn = v,
161                 )
162                 self._write_single_config('tinc.conf',
163                                 path.join(v.vpn_src, 'tinc.conf'), vars)
164                 self._write_single_config('tinc-up',
165                                 path.join(v.vpn_src, 'tinc-up'), vars)
166                 for h in v.hosts.values():
167                     if not h._delete:
168                         vars = dict(
169                             host = h,
170                         )
171                         self._write_single_config('host',
172                                 path.join(v.vpn_src, 'hosts', h.name), vars)
173                     else:
174                         log.debug(u'VpnHandler._write_config: removing...')
175                         try:
176                             # FIXME use os.unlink()
177                             call(('rm','-f',
178                                     path.join(v.vpn_src, 'hosts', h.name)))
179                             del v.hosts[h.name]
180                         except ExecutionError, e:
181                             log.debug(u'VpnHandler._write_config: error '
182                                     'removing files: %r', e)
183             else:
184                 #delete the vpn root at tinc dir
185                 if path.exists('/etc/tinc/' + v.vpn_src):
186                     self.stop(v.vpn_src)
187                     call(('rm','-rf','/etc/tinc/' + v.vpn_src))
188                     del self.vpns[v.vpn_src]
189
190
191 if __name__ == '__main__':
192
193     logging.basicConfig(
194         level   = logging.DEBUG,
195         format  = '%(asctime)s %(levelname)-8s %(message)s',
196         datefmt = '%H:%M:%S',
197     )
198
199     v = VpnHandler()
200     v.add('prueba','sarasa','192.168.0.188','255.255.255.0')
201     v.host.add('prueba', 'azazel' ,'192.168.0.77', '192.168.0.0',
202                 'kjdhfkbdskljvkjblkbjeslkjbvkljbselvslberjhbvslbevlhb')
203     v.commit()
204