Esempio n. 1
0
    def get_average(self):
        """
        Gets the moving average.
        """
        data = filter(None, self.get())
        traff = [traffic for (ts, traffic) in data]
        times = [ts for (ts, traffic) in data]

        try:
            deltatraffic = traff[-1] - first(traff)
            deltat = (times[-1] - first(times)).seconds
        except IndexError:
            deltatraffic = 0
            deltat = 0

        try:
            rate = float(deltatraffic) / float(deltat) / 1024
        except ZeroDivisionError:
            rate = 0

        # In some cases we get negative rates
        if rate < 0:
            rate = 0

        return rate
Esempio n. 2
0
    def get_average(self):
        """
        Gets the moving average.
        """
        data = filter(None, self.get())
        traff = [traffic for (ts, traffic) in data]
        times = [ts for (ts, traffic) in data]

        try:
            deltatraffic = traff[-1] - first(traff)
            deltat = (times[-1] - first(times)).seconds
        except IndexError:
            deltatraffic = 0
            deltat = 0

        try:
            rate = float(deltatraffic) / float(deltat) / 1024
        except ZeroDivisionError:
            rate = 0

        # In some cases we get negative rates
        if rate < 0:
            rate = 0

        return rate
    def get_vpn_command(kls, eipconfig, providerconfig, socket_host,
                        socket_port="unix", openvpn_verb=1):
        """
        Returns the Linux implementation for the vpn launching command.

        Might raise:
            EIPNoPkexecAvailable,
            EIPNoPolkitAuthAgentAvailable,
            OpenVPNNotFoundException,
            VPNLauncherException.

        :param eipconfig: eip configuration object
        :type eipconfig: EIPConfig
        :param providerconfig: provider specific configuration
        :type providerconfig: ProviderConfig
        :param socket_host: either socket path (unix) or socket IP
        :type socket_host: str
        :param socket_port: either string "unix" if it's a unix socket,
                            or port otherwise
        :type socket_port: str
        :param openvpn_verb: the openvpn verbosity wanted
        :type openvpn_verb: int

        :return: A VPN command ready to be launched.
        :rtype: list
        """
        # we use `super` in order to send the class to use
        command = super(LinuxVPNLauncher, kls).get_vpn_command(
            eipconfig, providerconfig, socket_host, socket_port, openvpn_verb)

        pkexec = kls.maybe_pkexec()
        if pkexec:
            command.insert(0, first(pkexec))

        return command
    def _pick_server(self, uuid):
        """
        Choose a soledad server to sync against.

        :param uuid: the uuid for the user.
        :type uuid: unicode
        :returns: the server url
        :rtype: unicode
        """
        if not self._soledad_config:
            self._soledad_config = SoledadConfig()

        # TODO: Select server based on timezone (issue #3308)
        server_dict = self._soledad_config.get_hosts()

        if not server_dict.keys():
            # XXX raise more specific exception, and catch it properly!
            raise Exception("No soledad server found")

        selected_server = server_dict[first(server_dict.keys())]
        server_url = "https://%s:%s/user-%s" % (
            selected_server["hostname"],
            selected_server["port"],
            uuid)
        logger.debug("Using soledad server url: %s" % (server_url,))
        return server_url
Esempio n. 5
0
    def _run(self, cmd):
        """
        Run an email firewall command with bitmask-root

        Might raise:
            NoPkexecAvailable,
            NoPolkitAuthAgentAvailable,

        :param cmd: command to send to bitmask-root fw-email
        :type cmd: [str]
        :returns: exit code of bitmask-root
        :rtype: int
        """
        command = []

        policyChecker = LinuxPolicyChecker()
        pkexec = policyChecker.maybe_pkexec()
        if pkexec:
            command.append(first(pkexec))

        command.append(force_eval(self.BITMASK_ROOT))
        command.append("fw-email")
        command += cmd

        # XXX: will be nice to use twisted ProcessProtocol instead of
        #      subprocess to avoid blocking until it finish
        return subprocess.call(command)
Esempio n. 6
0
    def _run(self, cmd):
        """
        Run an email firewall command with bitmask-root

        Might raise:
            NoPkexecAvailable,
            NoPolkitAuthAgentAvailable,

        :param cmd: command to send to bitmask-root fw-email
        :type cmd: [str]
        :returns: exit code of bitmask-root
        :rtype: int
        """
        command = []

        policyChecker = LinuxPolicyChecker()
        pkexec = policyChecker.maybe_pkexec()
        if pkexec:
            command.append(first(pkexec))

        command.append(force_eval(self.BITMASK_ROOT))
        command.append("fw-email")
        command += cmd

        # XXX: will be nice to use twisted ProcessProtocol instead of
        #      subprocess to avoid blocking until it finish
        return subprocess.call(command)
def _linux_install_missing_scripts(badexec, notfound):
    """
    Tries to install the missing up/down scripts.

    :param badexec: error for notifying execution error during command.
    :type badexec: str
    :param notfound: error for notifying missing path.
    :type notfound: str
    :returns: True if the files could be copied successfully.
    :rtype: bool
    """
    success = False
    installer_path = os.path.join(os.getcwd(), "apps", "eip", "files")
    launcher = LinuxVPNLauncher

    # XXX refactor with darwin, same block.

    if os.path.isdir(installer_path):
        fd, tempscript = tempfile.mkstemp(prefix="leap_installer-")
        polfd, pol_tempfile = tempfile.mkstemp(prefix="leap_installer-")
        try:
            path = launcher.OPENVPN_BIN_PATH
            policy_contents = privilege_policies.get_policy_contents(path)

            with os.fdopen(polfd, 'w') as f:
                f.write(policy_contents)

            pkexec = first(launcher.maybe_pkexec())
            scriptlines = launcher.cmd_for_missing_scripts(installer_path,
                                                           pol_tempfile)
            with os.fdopen(fd, 'w') as f:
                f.write(scriptlines)

            st = os.stat(tempscript)
            os.chmod(tempscript, st.st_mode | stat.S_IEXEC | stat.S_IXUSR |
                     stat.S_IXGRP | stat.S_IXOTH)
            cmdline = ["%s %s" % (pkexec, tempscript)]
            ret = subprocess.call(
                cmdline, stdout=subprocess.PIPE,
                shell=True)
            success = ret == 0
            if not success:
                logger.error("Install missing scripts failed.")
        except Exception as exc:
            logger.error(badexec)
            logger.error("Error was: %r" % (exc,))
        finally:
            try:
                os.remove(tempscript)
            except OSError as exc:
                logger.error("%r" % (exc,))
    else:
        logger.error(notfound)
        logger.debug('path searched: %s' % (installer_path,))

    return success
Esempio n. 8
0
    def get_vpn_command(kls,
                        eipconfig,
                        providerconfig,
                        socket_host,
                        socket_port="unix",
                        openvpn_verb=1):
        """
        Returns the Linux implementation for the vpn launching command.

        Might raise:
            EIPNoPkexecAvailable,
            EIPNoPolkitAuthAgentAvailable,
            OpenVPNNotFoundException,
            VPNLauncherException.

        :param eipconfig: eip configuration object
        :type eipconfig: EIPConfig
        :param providerconfig: provider specific configuration
        :type providerconfig: ProviderConfig
        :param socket_host: either socket path (unix) or socket IP
        :type socket_host: str
        :param socket_port: either string "unix" if it's a unix socket,
                            or port otherwise
        :type socket_port: str
        :param openvpn_verb: the openvpn verbosity wanted
        :type openvpn_verb: int

        :return: A VPN command ready to be launched.
        :rtype: list
        """
        # we use `super` in order to send the class to use
        command = super(LinuxVPNLauncher,
                        kls).get_vpn_command(eipconfig, providerconfig,
                                             socket_host, socket_port,
                                             openvpn_verb)

        command.insert(0, force_eval(kls.BITMASK_ROOT))
        command.insert(1, "openvpn")
        command.insert(2, "start")

        policyChecker = LinuxPolicyChecker()
        try:
            pkexec = policyChecker.maybe_pkexec()
        except NoPolkitAuthAgentAvailable:
            raise EIPNoPolkitAuthAgentAvailable()
        except NoPkexecAvailable:
            raise EIPNoPkexecAvailable()
        if pkexec:
            command.insert(0, first(pkexec))

        return command
Esempio n. 9
0
    def _cleanup_tempfiles(self):
        """
        Remove all temporal files we might have left behind.

        Iif self.port is 'unix', we have created a temporal socket path that,
        under normal circumstances, we should be able to delete.
        """
        if self._socket_port == "unix":
            logger.debug('cleaning socket file temp folder')
            tempfolder = first(os.path.split(self._socket_host))
            if tempfolder and os.path.isdir(tempfolder):
                try:
                    shutil.rmtree(tempfolder)
                except OSError:
                    logger.error('could not delete tmpfolder %s' % tempfolder)
Esempio n. 10
0
    def _cleanup_tempfiles(self):
        """
        Remove all temporal files we might have left behind.

        Iif self.port is 'unix', we have created a temporal socket path that,
        under normal circumstances, we should be able to delete.
        """
        if self._socket_port == "unix":
            logger.debug('cleaning socket file temp folder')
            tempfolder = first(os.path.split(self._socket_host))
            if tempfolder and os.path.isdir(tempfolder):
                try:
                    shutil.rmtree(tempfolder)
                except OSError:
                    logger.error('could not delete tmpfolder %s' % tempfolder)
Esempio n. 11
0
def _linux_install_missing_scripts(badexec, notfound):
    """
    Try to install the missing helper files.

    :param badexec: error for notifying execution error during command.
    :type badexec: str
    :param notfound: error for notifying missing path.
    :type notfound: str
    :returns: True if the files could be copied successfully.
    :rtype: bool
    """
    success = False
    installer_path = os.path.abspath(
        os.path.join(os.getcwd(), "..", "apps", "eip", "files"))

    install_helper = "leap-install-helper.sh"
    install_helper_path = os.path.join(installer_path, install_helper)

    install_opts = ("--from-path %s --install-bitmask-root YES "
                    "--install-polkit-file YES --install-openvpn YES "
                    "--remove-old-files YES" % (installer_path,))

    if os.path.isdir(installer_path):
        try:
            policyChecker = LinuxPolicyChecker()
            pkexec = first(policyChecker.maybe_pkexec())
            cmdline = ["%s %s %s" % (
                pkexec, install_helper_path, install_opts)]

            ret = subprocess.call(
                cmdline, stdout=subprocess.PIPE,
                shell=True)
            success = ret == 0
            if not success:
                logger.error("Install of helpers failed.")
        except Exception as exc:
            logger.error(badexec)
            logger.error("Error was: %r" % (exc,))
    else:
        logger.error(notfound)
        logger.debug('path searched: %s' % (installer_path,))

    return success
Esempio n. 12
0
def _linux_install_missing_scripts(badexec, notfound):
    """
    Try to install the missing helper files.

    :param badexec: error for notifying execution error during command.
    :type badexec: str
    :param notfound: error for notifying missing path.
    :type notfound: str
    :returns: True if the files could be copied successfully.
    :rtype: bool
    """
    success = False
    installer_path = os.path.abspath(
        os.path.join(os.getcwd(), "..", "apps", "eip", "files"))

    install_helper = "leap-install-helper.sh"
    install_helper_path = os.path.join(installer_path, install_helper)

    install_opts = ("--from-path %s --install-bitmask-root YES "
                    "--install-polkit-file YES --install-openvpn YES "
                    "--remove-old-files YES" % (installer_path, ))

    if os.path.isdir(installer_path):
        try:
            policyChecker = LinuxPolicyChecker()
            pkexec = first(policyChecker.maybe_pkexec())
            cmdline = [
                "%s %s %s" % (pkexec, install_helper_path, install_opts)
            ]

            ret = subprocess.call(cmdline, stdout=subprocess.PIPE, shell=True)
            success = ret == 0
            if not success:
                logger.error("Install of helpers failed.")
        except Exception as exc:
            logger.error(badexec)
            logger.error("Error was: %r" % (exc, ))
    else:
        logger.error(notfound)
        logger.debug('path searched: %s' % (installer_path, ))

    return success
Esempio n. 13
0
    def _pick_server(self, uuid):
        """
        Choose a soledad server to sync against.

        :param uuid: the uuid for the user.
        :type uuid: unicode
        :returns: the server url
        :rtype: unicode
        """
        # TODO: Select server based on timezone (issue #3308)
        server_dict = self._soledad_config.get_hosts()

        if not server_dict.keys():
            # XXX raise more specific exception, and catch it properly!
            raise Exception("No soledad server found")

        selected_server = server_dict[first(server_dict.keys())]
        server_url = "https://%s:%s/user-%s" % (selected_server["hostname"],
                                                selected_server["port"], uuid)
        logger.debug("Using soledad server url: %s" % (server_url, ))
        return server_url
Esempio n. 14
0
    def get_vpn_command(
        self, eipconfig=None, providerconfig=None, socket_host=None, socket_port="unix", openvpn_verb=1
    ):
        """
        Returns the platform dependant vpn launching command

        Might raise VPNException.

        :param eipconfig: eip configuration object
        :type eipconfig: EIPConfig

        :param providerconfig: provider specific configuration
        :type providerconfig: ProviderConfig

        :param socket_host: either socket path (unix) or socket IP
        :type socket_host: str

        :param socket_port: either string "unix" if it's a unix
                            socket, or port otherwise
        :type socket_port: str

        :param openvpn_verb: openvpn verbosity wanted
        :type openvpn_verb: int

        :return: A VPN command ready to be launched
        :rtype: list
        """
        leap_assert(eipconfig, "We need an eip config")
        leap_assert_type(eipconfig, EIPConfig)
        leap_assert(providerconfig, "We need a provider config")
        leap_assert_type(providerconfig, ProviderConfig)
        leap_assert(socket_host, "We need a socket host!")
        leap_assert(socket_port, "We need a socket port!")

        if not self.maybe_kextloaded():
            raise EIPNoTunKextLoaded

        kwargs = {}
        if ProviderConfig.standalone:
            kwargs["path_extension"] = os.path.join(providerconfig.get_path_prefix(), "..", "apps", "eip")

        openvpn_possibilities = which(self.OPENVPN_BIN, **kwargs)
        if len(openvpn_possibilities) == 0:
            raise OpenVPNNotFoundException()

        openvpn = first(openvpn_possibilities)
        args = [openvpn]

        args += ["--setenv", "LEAPOPENVPN", "1"]

        if openvpn_verb is not None:
            args += ["--verb", "%d" % (openvpn_verb,)]

        gateways = []
        leap_settings = LeapSettings(ProviderConfig.standalone)
        domain = providerconfig.get_domain()
        gateway_conf = leap_settings.get_selected_gateway(domain)

        if gateway_conf == leap_settings.GATEWAY_AUTOMATIC:
            gateway_selector = VPNGatewaySelector(eipconfig)
            gateways = gateway_selector.get_gateways()
        else:
            gateways = [gateway_conf]

        if not gateways:
            logger.error("No gateway was found!")
            raise VPNLauncherException(self.tr("No gateway was found!"))

        logger.debug("Using gateways ips: {0}".format(", ".join(gateways)))

        for gw in gateways:
            args += ["--remote", gw, "1194", "udp"]

        args += [
            "--client",
            "--dev",
            "tun",
            ##############################################################
            # persist-tun makes ping-restart fail because it leaves a
            # broken routing table
            ##############################################################
            # '--persist-tun',
            "--persist-key",
            "--tls-client",
            "--remote-cert-tls",
            "server",
        ]

        openvpn_configuration = eipconfig.get_openvpn_configuration()
        for key, value in openvpn_configuration.items():
            args += ["--%s" % (key,), value]

        user = getpass.getuser()

        ##############################################################
        # The down-root plugin fails in some situations, so we don't
        # drop privs for the time being
        ##############################################################
        # args += [
        #     '--user', user,
        #     '--group', grp.getgrgid(os.getgroups()[-1]).gr_name
        # ]

        if socket_port == "unix":
            args += ["--management-client-user", user]

        args += ["--management-signal", "--management", socket_host, socket_port, "--script-security", "2"]

        if _has_updown_scripts(self.UP_SCRIPT):
            args += ["--up", '"%s"' % (self.UP_SCRIPT,)]

        if _has_updown_scripts(self.DOWN_SCRIPT):
            args += ["--down", '"%s"' % (self.DOWN_SCRIPT,)]

            # should have the down script too
            if _has_updown_scripts(self.OPENVPN_DOWN_PLUGIN):
                args += [
                    ###########################################################
                    # For the time being we are disabling the usage of the
                    # down-root plugin, because it doesn't quite work as
                    # expected (i.e. it doesn't run route -del as root
                    # when finishing, so it fails to properly
                    # restart/quit)
                    ###########################################################
                    # '--plugin', self.OPENVPN_DOWN_PLUGIN,
                    # '\'%s\'' % self.DOWN_SCRIPT
                ]

        # we set user to be passed to the up/down scripts
        args += ["--setenv", "LEAPUSER", "%s" % (user,)]

        args += [
            "--cert",
            eipconfig.get_client_cert_path(providerconfig),
            "--key",
            eipconfig.get_client_cert_path(providerconfig),
            "--ca",
            providerconfig.get_ca_cert_path(),
        ]

        command, cargs = self.get_cocoasudo_ovpn_cmd()
        cmd_args = cargs + args

        logger.debug("Running VPN with command:")
        logger.debug("%s %s" % (command, " ".join(cmd_args)))

        return [command] + cmd_args
Esempio n. 15
0
    def get_vpn_command(kls, eipconfig, providerconfig,
                        socket_host, socket_port, openvpn_verb=1):
        """
        Returns the platform dependant vpn launching command

        Might raise:
            OpenVPNNotFoundException,
            VPNLauncherException.

        :param eipconfig: eip configuration object
        :type eipconfig: EIPConfig
        :param providerconfig: provider specific configuration
        :type providerconfig: ProviderConfig
        :param socket_host: either socket path (unix) or socket IP
        :type socket_host: str
        :param socket_port: either string "unix" if it's a unix socket,
                            or port otherwise
        :type socket_port: str
        :param openvpn_verb: the openvpn verbosity wanted
        :type openvpn_verb: int

        :return: A VPN command ready to be launched.
        :rtype: list
        """
        leap_assert_type(eipconfig, EIPConfig)
        leap_assert_type(providerconfig, ProviderConfig)

        kwargs = {}
        if flags.STANDALONE:
            kwargs['path_extension'] = os.path.join(
                get_path_prefix(), "..", "apps", "eip")

        openvpn_possibilities = which(kls.OPENVPN_BIN, **kwargs)
        if len(openvpn_possibilities) == 0:
            raise OpenVPNNotFoundException()

        openvpn = first(openvpn_possibilities)
        args = []

        args += [
            '--setenv', "LEAPOPENVPN", "1",
            '--nobind'
        ]

        if openvpn_verb is not None:
            args += ['--verb', '%d' % (openvpn_verb,)]

        gateways = []
        leap_settings = LeapSettings()
        domain = providerconfig.get_domain()
        gateway_conf = leap_settings.get_selected_gateway(domain)

        if gateway_conf == leap_settings.GATEWAY_AUTOMATIC:
            gateway_selector = VPNGatewaySelector(eipconfig)
            gateways = gateway_selector.get_gateways()
        else:
            gateways = [gateway_conf]

        if not gateways:
            logger.error('No gateway was found!')
            raise VPNLauncherException('No gateway was found!')

        logger.debug("Using gateways ips: {0}".format(', '.join(gateways)))

        for gw in gateways:
            args += ['--remote', gw, '1194', 'udp']

        args += [
            '--client',
            '--dev', 'tun',
            ##############################################################
            # persist-tun makes ping-restart fail because it leaves a
            # broken routing table
            ##############################################################
            # '--persist-tun',
            '--persist-key',
            '--tls-client',
            '--remote-cert-tls',
            'server'
        ]

        openvpn_configuration = eipconfig.get_openvpn_configuration()
        for key, value in openvpn_configuration.items():
            args += ['--%s' % (key,), value]

        user = getpass.getuser()

        ##############################################################
        # The down-root plugin fails in some situations, so we don't
        # drop privs for the time being
        ##############################################################
        # args += [
        #     '--user', user,
        #     '--group', grp.getgrgid(os.getgroups()[-1]).gr_name
        # ]

        if socket_port == "unix":  # that's always the case for linux
            args += [
                '--management-client-user', user
            ]

        args += [
            '--management-signal',
            '--management', socket_host, socket_port,
            '--script-security', '2'
        ]

        if kls.UP_SCRIPT is not None:
            if _has_updown_scripts(kls.UP_SCRIPT):
                args += [
                    '--up', '\"%s\"' % (kls.UP_SCRIPT,),
                ]

        if kls.DOWN_SCRIPT is not None:
            if _has_updown_scripts(kls.DOWN_SCRIPT):
                args += [
                    '--down', '\"%s\"' % (kls.DOWN_SCRIPT,)
                ]

        ###########################################################
        # For the time being we are disabling the usage of the
        # down-root plugin, because it doesn't quite work as
        # expected (i.e. it doesn't run route -del as root
        # when finishing, so it fails to properly
        # restart/quit)
        ###########################################################
        # if _has_updown_scripts(kls.OPENVPN_DOWN_PLUGIN):
        #     args += [
        #         '--plugin', kls.OPENVPN_DOWN_ROOT,
        #         '\'%s\'' % kls.DOWN_SCRIPT  # for OSX
        #         '\'script_type=down %s\'' % kls.DOWN_SCRIPT  # for Linux
        #     ]

        args += [
            '--cert', eipconfig.get_client_cert_path(providerconfig),
            '--key', eipconfig.get_client_cert_path(providerconfig),
            '--ca', providerconfig.get_ca_cert_path()
        ]

        args += [
            '--ping', '10',
            '--ping-restart', '30']

        command_and_args = [openvpn] + args
        return command_and_args
Esempio n. 16
0
    def get_vpn_command(
        self, eipconfig=None, providerconfig=None, socket_host=None, socket_port="unix", openvpn_verb=1
    ):
        """
        Returns the platform dependant vpn launching command. It will
        look for openvpn in the regular paths and algo in
        path_prefix/apps/eip/ (in case standalone is set)

        Might raise:
            VPNLauncherException,
            OpenVPNNotFoundException.

        :param eipconfig: eip configuration object
        :type eipconfig: EIPConfig

        :param providerconfig: provider specific configuration
        :type providerconfig: ProviderConfig

        :param socket_host: either socket path (unix) or socket IP
        :type socket_host: str

        :param socket_port: either string "unix" if it's a unix
                            socket, or port otherwise
        :type socket_port: str

        :param openvpn_verb: openvpn verbosity wanted
        :type openvpn_verb: int

        :return: A VPN command ready to be launched
        :rtype: list
        """
        leap_assert(eipconfig, "We need an eip config")
        leap_assert_type(eipconfig, EIPConfig)
        leap_assert(providerconfig, "We need a provider config")
        leap_assert_type(providerconfig, ProviderConfig)
        leap_assert(socket_host, "We need a socket host!")
        leap_assert(socket_port, "We need a socket port!")

        kwargs = {}
        if ProviderConfig.standalone:
            kwargs["path_extension"] = os.path.join(providerconfig.get_path_prefix(), "..", "apps", "eip")

        openvpn_possibilities = which(self.OPENVPN_BIN, **kwargs)

        if len(openvpn_possibilities) == 0:
            raise OpenVPNNotFoundException()

        openvpn = first(openvpn_possibilities)
        args = []

        pkexec = self.maybe_pkexec()
        if pkexec:
            args.append(openvpn)
            openvpn = first(pkexec)

        args += ["--setenv", "LEAPOPENVPN", "1"]

        if openvpn_verb is not None:
            args += ["--verb", "%d" % (openvpn_verb,)]

        gateways = []
        leap_settings = LeapSettings(ProviderConfig.standalone)
        domain = providerconfig.get_domain()
        gateway_conf = leap_settings.get_selected_gateway(domain)

        if gateway_conf == leap_settings.GATEWAY_AUTOMATIC:
            gateway_selector = VPNGatewaySelector(eipconfig)
            gateways = gateway_selector.get_gateways()
        else:
            gateways = [gateway_conf]

        if not gateways:
            logger.error("No gateway was found!")
            raise VPNLauncherException(self.tr("No gateway was found!"))

        logger.debug("Using gateways ips: {0}".format(", ".join(gateways)))

        for gw in gateways:
            args += ["--remote", gw, "1194", "udp"]

        args += [
            "--client",
            "--dev",
            "tun",
            ##############################################################
            # persist-tun makes ping-restart fail because it leaves a
            # broken routing table
            ##############################################################
            # '--persist-tun',
            "--persist-key",
            "--tls-client",
            "--remote-cert-tls",
            "server",
        ]

        openvpn_configuration = eipconfig.get_openvpn_configuration()

        for key, value in openvpn_configuration.items():
            args += ["--%s" % (key,), value]

        ##############################################################
        # The down-root plugin fails in some situations, so we don't
        # drop privs for the time being
        ##############################################################
        # args += [
        #     '--user', getpass.getuser(),
        #     '--group', grp.getgrgid(os.getgroups()[-1]).gr_name
        # ]

        if socket_port == "unix":  # that's always the case for linux
            args += ["--management-client-user", getpass.getuser()]

        args += ["--management-signal", "--management", socket_host, socket_port, "--script-security", "2"]

        plugin_path = self.maybe_down_plugin()
        # If we do not have the down plugin neither in the bundle
        # nor in the system, we do not do updown scripts. The alternative
        # is leaving the user without the ability to restore dns and routes
        # to its original state.

        if plugin_path and _has_updown_scripts(self.UP_DOWN_PATH):
            args += [
                "--up",
                self.UP_DOWN_PATH,
                "--down",
                self.UP_DOWN_PATH,
                ##############################################################
                # For the time being we are disabling the usage of the
                # down-root plugin, because it doesn't quite work as
                # expected (i.e. it doesn't run route -del as root
                # when finishing, so it fails to properly
                # restart/quit)
                ##############################################################
                # '--plugin', plugin_path,
                # '\'script_type=down %s\'' % self.UP_DOWN_PATH
            ]

        args += [
            "--cert",
            eipconfig.get_client_cert_path(providerconfig),
            "--key",
            eipconfig.get_client_cert_path(providerconfig),
            "--ca",
            providerconfig.get_ca_cert_path(),
        ]

        logger.debug("Running VPN with command:")
        logger.debug("%s %s" % (openvpn, " ".join(args)))

        return [openvpn] + args
Esempio n. 17
0
    def get_vpn_command(
        self, eipconfig=None, providerconfig=None, socket_host=None, socket_port="9876", openvpn_verb=1
    ):
        """
        Returns the platform dependant vpn launching command. It will
        look for openvpn in the regular paths and algo in
        path_prefix/apps/eip/ (in case standalone is set)

        Might raise VPNException.

        :param eipconfig: eip configuration object
        :type eipconfig: EIPConfig

        :param providerconfig: provider specific configuration
        :type providerconfig: ProviderConfig

        :param socket_host: either socket path (unix) or socket IP
        :type socket_host: str

        :param socket_port: either string "unix" if it's a unix
        socket, or port otherwise
        :type socket_port: str

        :param openvpn_verb: the openvpn verbosity wanted
        :type openvpn_verb: int

        :return: A VPN command ready to be launched
        :rtype: list
        """
        leap_assert(eipconfig, "We need an eip config")
        leap_assert_type(eipconfig, EIPConfig)
        leap_assert(providerconfig, "We need a provider config")
        leap_assert_type(providerconfig, ProviderConfig)
        leap_assert(socket_host, "We need a socket host!")
        leap_assert(socket_port, "We need a socket port!")
        leap_assert(socket_port != "unix", "We cannot use unix sockets in windows!")

        openvpn_possibilities = which(
            self.OPENVPN_BIN, path_extension=os.path.join(providerconfig.get_path_prefix(), "..", "apps", "eip")
        )

        if len(openvpn_possibilities) == 0:
            raise OpenVPNNotFoundException()

        openvpn = first(openvpn_possibilities)
        args = []

        args += ["--setenv", "LEAPOPENVPN", "1"]

        if openvpn_verb is not None:
            args += ["--verb", "%d" % (openvpn_verb,)]

        gateways = []
        leap_settings = LeapSettings(ProviderConfig.standalone)
        domain = providerconfig.get_domain()
        gateway_conf = leap_settings.get_selected_gateway(domain)

        if gateway_conf == leap_settings.GATEWAY_AUTOMATIC:
            gateway_selector = VPNGatewaySelector(eipconfig)
            gateways = gateway_selector.get_gateways()
        else:
            gateways = [gateway_conf]

        if not gateways:
            logger.error("No gateway was found!")
            raise VPNLauncherException(self.tr("No gateway was found!"))

        logger.debug("Using gateways ips: {0}".format(", ".join(gateways)))

        for gw in gateways:
            args += ["--remote", gw, "1194", "udp"]

        args += [
            "--client",
            "--dev",
            "tun",
            ##############################################################
            # persist-tun makes ping-restart fail because it leaves a
            # broken routing table
            ##############################################################
            # '--persist-tun',
            "--persist-key",
            "--tls-client",
            # We make it log to a file because we cannot attach to the
            # openvpn process' stdout since it's a process with more
            # privileges than we are
            "--log-append",
            "eip.log",
            "--remote-cert-tls",
            "server",
        ]

        openvpn_configuration = eipconfig.get_openvpn_configuration()
        for key, value in openvpn_configuration.items():
            args += ["--%s" % (key,), value]

        ##############################################################
        # The down-root plugin fails in some situations, so we don't
        # drop privs for the time being
        ##############################################################
        # args += [
        #     '--user', getpass.getuser(),
        #     #'--group', grp.getgrgid(os.getgroups()[-1]).gr_name
        # ]

        args += ["--management-signal", "--management", socket_host, socket_port, "--script-security", "2"]

        args += [
            "--cert",
            eipconfig.get_client_cert_path(providerconfig),
            "--key",
            eipconfig.get_client_cert_path(providerconfig),
            "--ca",
            providerconfig.get_ca_cert_path(),
        ]

        logger.debug("Running VPN with command:")
        logger.debug("%s %s" % (openvpn, " ".join(args)))

        return [openvpn] + args
Esempio n. 18
0
    return not_number == 1


__version__ = "unknown"
IS_RELEASE_VERSION = False

__short_version__ = "unknown"

try:
    from leap.bitmask._version import get_versions
    __version__ = get_versions()['version']
    __version_hash__ = get_versions()['full']
    IS_RELEASE_VERSION = _is_release_version(__version__)
    del get_versions
except ImportError:
    #running on a tree that has not run
    #the setup.py setver
    pass

__appname__ = "unknown"
try:
    from leap._appname import __appname__
except ImportError:
    #running on a tree that has not run
    #the setup.py setver
    pass

__short_version__ = first(re.findall('\d+\.\d+\.\d+', __version__))
__full_version__ = __appname__ + '/' + str(__version__)