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