summaryrefslogtreecommitdiff
path: root/src/leap/eip/openvpnconnection.py
blob: e51694651770b6982ce10539014b4754849eda22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
"""
OpenVPN Connection
"""
from __future__ import (print_function)
import logging
import os
import psutil
import shutil
import select
import socket
from functools import partial

logger = logging.getLogger(name=__name__)

from leap.base.connection import Connection
from leap.util.coroutines import spawn_and_watch_process

from leap.eip.udstelnet import UDSTelnet
from leap.eip import config as eip_config
from leap.eip import exceptions as eip_exceptions


class OpenVPNManagement(object):

    # TODO explain a little bit how management interface works
    # and our telnet interface with support for unix sockets.

    """
    for more information, read openvpn management notes.
    zcat `dpkg -L openvpn | grep management`
    """

    def _connect_to_management(self):
        """
        Connect to openvpn management interface
        """
        if hasattr(self, 'tn'):
            self._close_management_socket()
        self.tn = UDSTelnet(self.host, self.port)

        # XXX make password optional
        # specially for win. we should generate
        # the pass on the fly when invoking manager
        # from conductor

        #self.tn.read_until('ENTER PASSWORD:', 2)
        #self.tn.write(self.password + '\n')
        #self.tn.read_until('SUCCESS:', 2)
        if self.tn:
            self._seek_to_eof()
        return True

    def _close_management_socket(self, announce=True):
        """
        Close connection to openvpn management interface
        """
        logger.debug('closing socket')
        if announce:
            self.tn.write("quit\n")
            self.tn.read_all()
        self.tn.get_socket().close()
        del self.tn

    def _seek_to_eof(self):
        """
        Read as much as available. Position seek pointer to end of stream
        """
        try:
            b = self.tn.read_eager()
        except EOFError:
            logger.debug("Could not read from socket. Assuming it died.")
            return
        while b:
            try:
                b = self.tn.read_eager()
            except EOFError:
                logger.debug("Could not read from socket. Assuming it died.")

    def _send_command(self, cmd):
        """
        Send a command to openvpn and return response as list
        """
        if not self.connected():
            try:
                self._connect_to_management()
            except eip_exceptions.MissingSocketError:
                #logger.warning('missing management socket')
                return []
        try:
            if hasattr(self, 'tn'):
                self.tn.write(cmd + "\n")
        except socket.error:
            logger.error('socket error')
            self._close_management_socket(announce=False)
            return []
        try:
            buf = self.tn.read_until(b"END", 2)
            self._seek_to_eof()
            blist = buf.split('\r\n')
            if blist[-1].startswith('END'):
                del blist[-1]
                return blist
            else:
                return []
        except socket.error as exc:
            logger.debug('socket error: %s' % exc.message)
        except select.error as exc:    
            logger.debug('select error: %s' % exc.message)

    def _send_short_command(self, cmd):
        """
        parse output from commands that are
        delimited by "success" instead
        """
        if not self.connected():
            self.connect()
        self.tn.write(cmd + "\n")
        # XXX not working?
        buf = self.tn.read_until(b"SUCCESS", 2)
        self._seek_to_eof()
        blist = buf.split('\r\n')
        return blist

    #
    # random maybe useful vpn commands
    #

    def pid(self):
        #XXX broken
        return self._send_short_command("pid")


class OpenVPNConnection(Connection, OpenVPNManagement):
    """
    All related to invocation
    of the openvpn binary.
    It's extended by EIPConnection.
    """

    # XXX Inheriting from Connection was an early design idea
    # but currently that's an empty class.
    # We can get rid of that if we don't use it for sharing
    # state with other leap modules.

    def __init__(self,
                 watcher_cb=None,
                 debug=False,
                 host=None,
                 port="unix",
                 password=None,
                 *args, **kwargs):
        """
        :param watcher_cb: callback to be \
called for each line in watched stdout
        :param signal_map: dictionary of signal names and callables \
to be triggered for each one of them.
        :type watcher_cb: function
        :type signal_map: dict
        """
        #XXX FIXME
        #change watcher_cb to line_observer
        # XXX if not host: raise ImproperlyConfigured

        logger.debug('init openvpn connection')
        self.debug = debug
        self.ovpn_verbosity = kwargs.get('ovpn_verbosity', None)

        self.watcher_cb = watcher_cb
        #self.signal_maps = signal_maps

        self.subp = None
        self.watcher = None

        self.server = None
        self.port = None
        self.proto = None

        self.command = None
        self.args = None

        # XXX get autostart from config
        self.autostart = True

        # management interface init
        self.host = host
        if isinstance(port, str) and port.isdigit():
            port = int(port)
        elif port == "unix":
            port = "unix"
        else:
            port = None
        self.port = port
        self.password = password

    def run_openvpn_checks(self):
        """
        runs check needed before launching
        openvpn subprocess. will raise if errors found.
        """
        logger.debug('running openvpn checks')
        # XXX I think that "check_if_running" should be called
        # from try openvpn connection instead. -- kali.
        # let's prepare tests for that before changing it...
        self._check_if_running_instance()
        self._set_ovpn_command()
        self._check_vpn_keys()

    def try_openvpn_connection(self):
        """
        attempts to connect
        """
        # XXX should make public method
        if self.command is None:
            raise eip_exceptions.EIPNoCommandError
        if self.subp is not None:
            logger.debug('cowardly refusing to launch subprocess again')
            # XXX this is not returning ???!!
            # FIXME -- so it's calling it all the same!!

        self._launch_openvpn()

    def connected(self):
        """
        Returns True if connected
        rtype: bool
        """
        # XXX make a property
        return hasattr(self, 'tn')

    def terminate_openvpn_connection(self, shutdown=False):
        """
        terminates openvpn child subprocess
        """
        if self.subp:
            try:
                self._stop_openvpn()
            except eip_exceptions.ConnectionRefusedError:
                logger.warning(
                    'unable to send sigterm signal to openvpn: '
                    'connection refused.')

            # XXX kali --
            # XXX review-me
            # I think this will block if child process
            # does not return.
            # Maybe we can .poll() for a given
            # interval and exit in any case.

            RETCODE = self.subp.wait()
            if RETCODE:
                logger.error(
                    'cannot terminate subprocess! Retcode %s'
                    '(We might have left openvpn running)' % RETCODE)

        if shutdown:
            self._cleanup_tempfiles()

    def _cleanup_tempfiles(self):
        """
        remove all temporal files
        we might have left behind
        """
        # if self.port is 'unix', we have
        # created a temporal socket path that, under
        # normal circumstances, we should be able to
        # delete

        if self.port == "unix":
            logger.debug('cleaning socket file temp folder')

            tempfolder = os.path.split(self.host)[0]
            if os.path.isdir(tempfolder):
                try:
                    shutil.rmtree(tempfolder)
                except OSError:
                    logger.error('could not delete tmpfolder %s' % tempfolder)

    # checks

    def _check_if_running_instance(self):
        """
        check if openvpn is already running
        """
        try:
            #FIXME this gives DeprecationWarning
            for process in psutil.get_process_list():
                if process.name == "openvpn":
                    logger.debug('an openvpn instance is already running.')
                    logger.debug('attempting to stop openvpn instance.')
                    if not self._stop_openvpn():
                        raise eip_exceptions.OpenVPNAlreadyRunning

        except psutil.error.NoSuchProcess:
            logger.debug('detected a process which died. passing.')

        logger.debug('no openvpn instance found.')

    def _set_ovpn_command(self):
        try:
            command, args = eip_config.build_ovpn_command(
                provider=self.provider,
                debug=self.debug,
                socket_path=self.host,
                ovpn_verbosity=self.ovpn_verbosity)
        except eip_exceptions.EIPNoPolkitAuthAgentAvailable:
            command = args = None
            raise
        except eip_exceptions.EIPNoPkexecAvailable:
            command = args = None
            raise

        # XXX if not command, signal error.
        self.command = command
        self.args = args

    def _check_vpn_keys(self):
        """
        checks for correct permissions on vpn keys
        """
        try:
            eip_config.check_vpn_keys(provider=self.provider)
        except eip_exceptions.EIPInitBadKeyFilePermError:
            logger.error('Bad VPN Keys permission!')
            # do nothing now
        # and raise the rest ...

    # starting and stopping openvpn subprocess

    def _launch_openvpn(self):
        """
        invocation of openvpn binaries in a subprocess.
        """
        #XXX TODO:
        #deprecate watcher_cb,
        #use _only_ signal_maps instead

        logger.debug('_launch_openvpn called')
        if self.watcher_cb is not None:
            linewrite_callback = self.watcher_cb
        else:
            #XXX get logger instead
            linewrite_callback = lambda line: logger.debug(
                    'watcher: %s' % line)

        # the partial is not
        # being applied now because we're not observing the process
        # stdout like we did in the early stages. but I leave it
        # here since it will be handy for observing patterns in the
        # thru-the-manager updates (with regex)
        observers = (linewrite_callback,
                     partial(lambda con_status,
                             line: linewrite_callback, self.status))
        subp, watcher = spawn_and_watch_process(
            self.command,
            self.args,
            observers=observers)
        self.subp = subp
        self.watcher = watcher

    def _stop_openvpn(self):
        """
        stop openvpn process
        by sending SIGTERM to the management
        interface
        """
        # XXX method a bit too long, split
        logger.debug("terminating openvpn process...")
        if self.connected():
            try:
                self._send_command("signal SIGTERM\n")
            except socket.error:
                logger.warning('management socket died')
                return

        if self.subp:
            # ???
            return True

        #shutting openvpn failured
        #try patching in old openvpn host and trying again
        process = self._get_openvpn_process()
        if process:
            logger.debug('process :%s' % process)
            cmdline = process.cmdline

            manag_flag = "--management"
            if isinstance(cmdline, list) and manag_flag in cmdline:
                _index = cmdline.index(manag_flag)
                self.host = cmdline[_index + 1]
                self._send_command("signal SIGTERM\n")

            #make sure the process was terminated
            process = self._get_openvpn_process()
            if not process:
                logger.debug("Existing OpenVPN Process Terminated")
                return True
            else:
                logger.error("Unable to terminate existing OpenVPN Process.")
                return False

        return True

    def _get_openvpn_process(self):
        # plist = [p for p in psutil.get_process_list() if p.name == "openvpn"]
        # return plist[0] if plist else None
        for process in psutil.get_process_list():
            if process.name == "openvpn":
                return process
        return None

    def get_log(self, lines=1):
        log = self._send_command("log %s" % lines)
        return log