summaryrefslogtreecommitdiff
path: root/src/leap/eip/config.py
blob: f82049d34d9be89026529767a0002c05bb128554 (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
import logging
import os
import platform
import re
import tempfile

from leap import __branding as BRANDING
from leap import certs
from leap.util.misc import null_check
from leap.util.fileutil import (which, mkdir_p, check_and_fix_urw_only)

from leap.base import config as baseconfig
from leap.baseapp.permcheck import (is_pkexec_in_system,
                                    is_auth_agent_running)
from leap.eip import exceptions as eip_exceptions
from leap.eip import specs as eipspecs

logger = logging.getLogger(name=__name__)
provider_ca_file = BRANDING.get('provider_ca_file', None)


class EIPConfig(baseconfig.JSONLeapConfig):
    spec = eipspecs.eipconfig_spec

    def _get_slug(self):
        eipjsonpath = baseconfig.get_config_file(
            'eip.json')
        return eipjsonpath

    def _set_slug(self, *args, **kwargs):
        raise AttributeError("you cannot set slug")

    slug = property(_get_slug, _set_slug)


class EIPServiceConfig(baseconfig.JSONLeapConfig):
    spec = eipspecs.eipservice_config_spec

    def _get_slug(self):
        domain = getattr(self, 'domain', None)
        if domain:
            path = baseconfig.get_provider_path(domain)
        else:
            path = baseconfig.get_default_provider_path()
        return baseconfig.get_config_file(
            'eip-service.json', folder=path)

    def _set_slug(self):
        raise AttributeError("you cannot set slug")

    slug = property(_get_slug, _set_slug)


def get_socket_path():
    socket_path = os.path.join(
        tempfile.mkdtemp(prefix="leap-tmp"),
        'openvpn.socket')
    #logger.debug('socket path: %s', socket_path)
    return socket_path


def get_eip_gateway(eipconfig=None, eipserviceconfig=None):
    """
    return the first host in eip service config
    that matches the name defined in the eip.json config
    file.
    """
    # XXX eventually we should move to a more clever
    # gateway selection. maybe we could return
    # all gateways that match our cluster.

    null_check(eipconfig, "eipconfig")
    null_check(eipserviceconfig, "eipserviceconfig")
    PLACEHOLDER = "testprovider.example.org"

    conf = eipconfig.config
    eipsconf = eipserviceconfig.config

    primary_gateway = conf.get('primary_gateway', None)
    if not primary_gateway:
        return PLACEHOLDER

    gateways = eipsconf.get('gateways', None)
    if not gateways:
        logger.error('missing gateways in eip service config')
        return PLACEHOLDER

    if len(gateways) > 0:
        for gw in gateways:
            clustername = gw.get('cluster', None)
            if not clustername:
                logger.error('no cluster name')
                return

            if clustername == primary_gateway:
                # XXX at some moment, we must
                # make this a more generic function,
                # and return ports, protocols...
                ipaddress = gw.get('ip_address', None)
                if not ipaddress:
                    logger.error('no ip_address')
                    return
                return ipaddress
    logger.error('could not find primary gateway in provider'
                 'gateway list')


def get_cipher_options(eipserviceconfig=None):
    """
    gathers optional cipher options from eip-service config.
    :param eipserviceconfig: EIPServiceConfig instance
    """
    null_check(eipserviceconfig, 'eipserviceconfig')
    eipsconf = eipserviceconfig.get_config()

    ALLOWED_KEYS = ("auth", "cipher", "tls-cipher")
    CIPHERS_REGEX = re.compile("[A-Z0-9\-]+")
    opts = []
    if 'openvpn_configuration' in eipsconf:
        config = eipserviceconfig.config.get(
            "openvpn_configuration", {})
        for key, value in config.items():
            if key in ALLOWED_KEYS and value is not None:
                sanitized_val = CIPHERS_REGEX.findall(value)
                if len(sanitized_val) != 0:
                    _val = sanitized_val[0]
                    opts.append('--%s' % key)
                    opts.append('%s' % _val)
    return opts


def build_ovpn_options(daemon=False, socket_path=None, **kwargs):
    """
    build a list of options
    to be passed in the
    openvpn invocation
    @rtype: list
    @rparam: options
    """
    # XXX review which of the
    # options we don't need.

    # TODO pass also the config file,
    # since we will need to take some
    # things from there if present.

    provider = kwargs.pop('provider', None)
    eipconfig = EIPConfig(domain=provider)
    eipconfig.load()
    eipserviceconfig = EIPServiceConfig(domain=provider)
    eipserviceconfig.load()

    # get user/group name
    # also from config.
    user = baseconfig.get_username()
    group = baseconfig.get_groupname()

    opts = []

    opts.append('--client')

    opts.append('--dev')
    # XXX same in win?
    opts.append('tun')
    opts.append('--persist-tun')
    opts.append('--persist-key')

    verbosity = kwargs.get('ovpn_verbosity', None)
    if verbosity and 1 <= verbosity <= 6:
        opts.append('--verb')
        opts.append("%s" % verbosity)

    # remote ##############################
    # (server, port, protocol)

    opts.append('--remote')

    gw = get_eip_gateway(eipconfig=eipconfig,
                         eipserviceconfig=eipserviceconfig)
    logger.debug('setting eip gateway to %s', gw)
    opts.append(str(gw))

    # get port/protocol from eipservice too
    opts.append('1194')
    #opts.append('80')
    opts.append('udp')

    opts.append('--tls-client')
    opts.append('--remote-cert-tls')
    opts.append('server')

    # get ciphers #######################

    ciphers = get_cipher_options(
        eipserviceconfig=eipserviceconfig)
    for cipheropt in ciphers:
        opts.append(str(cipheropt))

    # set user and group
    opts.append('--user')
    opts.append('%s' % user)
    opts.append('--group')
    opts.append('%s' % group)

    opts.append('--management-client-user')
    opts.append('%s' % user)
    opts.append('--management-signal')

    # set default options for management
    # interface. unix sockets or telnet interface for win.
    # XXX take them from the config object.

    ourplatform = platform.system()
    if ourplatform in ("Linux", "Darwin"):
        opts.append('--management')

        if socket_path is None:
            socket_path = get_socket_path()
        opts.append(socket_path)
        opts.append('unix')

    if ourplatform == "Windows":
        opts.append('--management')
        opts.append('localhost')
        # XXX which is a good choice?
        opts.append('7777')

    # certs
    client_cert_path = eipspecs.client_cert_path(provider)
    ca_cert_path = eipspecs.provider_ca_path(provider)

    # XXX FIX paths for MAC
    opts.append('--cert')
    opts.append(client_cert_path)
    opts.append('--key')
    opts.append(client_cert_path)
    opts.append('--ca')
    opts.append(ca_cert_path)

    # we cannot run in daemon mode
    # with the current subp setting.
    # see: https://leap.se/code/issues/383
    #if daemon is True:
        #opts.append('--daemon')

    logger.debug('vpn options: %s', opts)
    return opts


def build_ovpn_command(debug=False, do_pkexec_check=True, vpnbin=None,
                       socket_path=None, **kwargs):
    """
    build a string with the
    complete openvpn invocation

    @rtype [string, [list of strings]]
    @rparam: a list containing the command string
        and a list of options.
    """
    command = []
    use_pkexec = True
    ovpn = None

    _plat = platform.system()

    # XXX get use_pkexec from config instead.

    if _plat == "Linux" and use_pkexec and do_pkexec_check:

        # check for both pkexec
        # AND a suitable authentication
        # agent running.
        logger.info('use_pkexec set to True')

        if not is_pkexec_in_system():
            logger.error('no pkexec in system')
            raise eip_exceptions.EIPNoPkexecAvailable

        if not is_auth_agent_running():
            logger.warning(
                "no polkit auth agent found. "
                "pkexec will use its own text "
                "based authentication agent. "
                "that's probably a bad idea")
            raise eip_exceptions.EIPNoPolkitAuthAgentAvailable

        command.append('pkexec')


    if vpnbin is None:
        if _plat == "Darwin":
            # XXX Should hardcode our installed path
            # /Applications/LEAPClient.app/Contents/Resources/openvpn.leap
            openvpn_bin = "openvpn.leap"
        else:
            openvpn_bin = "openvpn"
        #XXX hardcode for darwin
        ovpn = which(openvpn_bin)
    else:
        ovpn = vpnbin
    if ovpn:
        vpn_command = ovpn
    else:
        vpn_command = "openvpn"
    command.append(vpn_command)
    daemon_mode = not debug

    for opt in build_ovpn_options(daemon=daemon_mode, socket_path=socket_path,
                                  **kwargs):
        command.append(opt)

    # XXX check len and raise proper error

    if _plat == "Darwin":
        OSX_ASADMIN = 'do shell script "%s" with administrator privileges'
        # XXX fix workaround for Nones
        _command = [x if x else " " for x in command]
        # XXX debugging!
        #import ipdb;ipdb.set_trace() 
        #XXX get openvpn log path from debug flags 
        _command.append('--log')
        _command.append('/tmp/leap_openvpn.log')
        return ["osascript", ["-e", OSX_ASADMIN % ' '.join(_command)]]
    else:
        return [command[0], command[1:]]


def check_vpn_keys(provider=None):
    """
    performs an existance and permission check
    over the openvpn keys file.
    Currently we're expecting a single file
    per provider, containing the CA cert,
    the provider key, and our client certificate
    """
    assert provider is not None
    provider_ca = eipspecs.provider_ca_path(provider)
    client_cert = eipspecs.client_cert_path(provider)

    logger.debug('provider ca = %s', provider_ca)
    logger.debug('client cert = %s', client_cert)

    # if no keys, raise error.
    # it's catched by the ui and signal user.

    if not os.path.isfile(provider_ca):
        # not there. let's try to copy.
        folder, filename = os.path.split(provider_ca)
        if not os.path.isdir(folder):
            mkdir_p(folder)
        if provider_ca_file:
            cacert = certs.where(provider_ca_file)
        with open(provider_ca, 'w') as pca:
            with open(cacert, 'r') as cac:
                pca.write(cac.read())

    if not os.path.isfile(provider_ca):
        logger.error('key file %s not found. aborting.',
                     provider_ca)
        raise eip_exceptions.EIPInitNoKeyFileError

    if not os.path.isfile(client_cert):
        logger.error('key file %s not found. aborting.',
                     client_cert)
        raise eip_exceptions.EIPInitNoKeyFileError

    for keyfile in (provider_ca, client_cert):
        # bad perms? try to fix them
        try:
            check_and_fix_urw_only(keyfile)
        except OSError:
            raise eip_exceptions.EIPInitBadKeyFilePermError