def _download_client_certificates(self, *args):
        """
        Downloads the SMTP client certificate for the given provider

        We actually are downloading the certificate for the same uri as
        for the EIP config, but we duplicate these bits to allow mail
        service to be working in a provider that does not offer EIP.
        """
        # TODO factor out with eipboostrapper.download_client_certificates
        # TODO this shouldn't be a private method, it's called from
        # mainwindow.
        leap_assert(self._provider_config, "We need a provider configuration!")
        leap_assert(self._smtp_config, "We need an smtp configuration!")

        logger.debug("Downloading SMTP client certificate for %s" %
                     (self._provider_config.get_domain(),))

        client_cert_path = self._smtp_config.\
            get_client_cert_path(self._provider_config,
                                 about_to_download=True)

        # For re-download if something is wrong with the cert
        self._download_if_needed = self._download_if_needed and \
            not leap_certs.should_redownload(client_cert_path)

        if self._download_if_needed and \
                os.path.isfile(client_cert_path):
            check_and_fix_urw_only(client_cert_path)
            return

        download_client_cert(self._provider_config,
                             client_cert_path,
                             self._session)
Ejemplo n.º 2
0
    def _download_client_certificates(self, *args):
        """
        Downloads the EIP client certificate for the given provider
        """
        leap_assert(self._provider_config, "We need a provider configuration!")
        leap_assert(self._eip_config, "We need an eip configuration!")

        logger.debug("Downloading EIP client certificate for %s" %
                     (self._provider_config.get_domain(),))

        client_cert_path = self._eip_config.\
            get_client_cert_path(self._provider_config,
                                 about_to_download=True)

        # For re-download if something is wrong with the cert
        self._download_if_needed = self._download_if_needed and \
            not leap_certs.should_redownload(client_cert_path)

        if self._download_if_needed and \
                os.path.isfile(client_cert_path):
            check_and_fix_urw_only(client_cert_path)
            return

        download_client_cert(
            self._provider_config,
            client_cert_path,
            self._session)
Ejemplo n.º 3
0
    def _download_ca_cert(self, *args):
        """
        Downloads the CA cert that is going to be used for the api URL
        """
        # XXX maybe we can skip this step if
        # we have a fresh one.
        leap_assert(
            self._provider_config, "Cannot download the ca cert "
            "without a provider config!")

        logger.debug("Downloading ca cert for %r at %r" %
                     (self._domain, self._provider_config.get_ca_cert_uri()))

        if not self._should_proceed_cert():
            check_and_fix_urw_only(
                self._provider_config.get_ca_cert_path(about_to_download=True))
            return

        res = self._session.get(self._provider_config.get_ca_cert_uri(),
                                verify=self.verify,
                                timeout=REQUEST_TIMEOUT)
        res.raise_for_status()

        cert_path = self._provider_config.get_ca_cert_path(
            about_to_download=True)
        cert_dir = os.path.dirname(cert_path)
        mkdir_p(cert_dir)
        with open(cert_path, "w") as f:
            f.write(res.content)

        check_and_fix_urw_only(cert_path)
Ejemplo n.º 4
0
    def _download_client_certificates(self, *args):
        """
        Downloads the EIP client certificate for the given provider
        """
        leap_assert(self._provider_config, "We need a provider configuration!")
        leap_assert(self._eip_config, "We need an eip configuration!")

        logger.debug("Downloading EIP client certificate for %s" %
                     (self._provider_config.get_domain(), ))

        client_cert_path = self._eip_config.\
            get_client_cert_path(self._provider_config,
                                 about_to_download=True)

        # For re-download if something is wrong with the cert
        self._download_if_needed = self._download_if_needed and \
            not leap_certs.should_redownload(client_cert_path)

        if self._download_if_needed and \
                os.path.isfile(client_cert_path):
            check_and_fix_urw_only(client_cert_path)
            return

        download_client_cert(self._provider_config, client_cert_path,
                             self._session)
    def _download_ca_cert(self, *args):
        """
        Downloads the CA cert that is going to be used for the api URL
        """
        # XXX maybe we can skip this step if
        # we have a fresh one.
        leap_assert(self._provider_config, "Cannot download the ca cert "
                    "without a provider config!")

        logger.debug("Downloading ca cert for %r at %r" %
                     (self._domain, self._provider_config.get_ca_cert_uri()))

        if not self._should_proceed_cert():
            check_and_fix_urw_only(
                self._provider_config
                .get_ca_cert_path(about_to_download=True))
            return

        res = self._session.get(self._provider_config.get_ca_cert_uri(),
                                verify=self.verify,
                                timeout=REQUEST_TIMEOUT)
        res.raise_for_status()

        cert_path = self._provider_config.get_ca_cert_path(
            about_to_download=True)
        cert_dir = os.path.dirname(cert_path)
        mkdir_p(cert_dir)
        with open(cert_path, "w") as f:
            f.write(res.content)

        check_and_fix_urw_only(cert_path)
Ejemplo n.º 6
0
    def _download_config_and_cert(self):
        """
        Downloads the SMTP config and cert for the given provider.
        """
        leap_assert(self._provider_config,
                    "We need a provider configuration!")

        logger.debug("Downloading SMTP config for %s" %
                     (self._provider_config.get_domain(),))

        download_service_config(
            self._provider_config,
            self._smtp_config,
            self._session,
            self._download_if_needed)

        hosts = self._smtp_config.get_hosts()

        if len(hosts) == 0:
            raise NoSMTPHosts()

        # TODO handle more than one host and define how to choose
        hostname = hosts.keys()[0]
        logger.debug("Using hostname %s for SMTP" % (hostname,))

        client_cert_path = self._smtp_config.get_client_cert_path(
            self._userid, self._provider_config, about_to_download=True)

        needs_download = leap_certs.should_redownload(client_cert_path)

        if needs_download:
            # For re-download if something is wrong with the cert
            # FIXME this doesn't read well. should reword the logic here.
            self._download_if_needed = (
                self._download_if_needed and not needs_download)

            if self._download_if_needed and os.path.isfile(client_cert_path):
                check_and_fix_urw_only(client_cert_path)
                return

            try:
                download_client_cert(self._provider_config,
                                     client_cert_path,
                                     self._session, kind="smtp")
            except HTTPError as exc:
                if exc.message.startswith('403 Client Error'):
                    logger.debug(
                        'Auth problem downloading smtp certificate... '
                        'It might be a provider problem, will try '
                        'fetching from vpn pool')
                    warnings.warn(
                        'Compatibility hack for platform 0.7 not fully '
                        'supporting smtp certificates. Will be deprecated in '
                        'bitmask 0.10')
                    download_client_cert(self._provider_config,
                                         client_cert_path,
                                         self._session, kind="vpn")
                else:
                    raise
Ejemplo n.º 7
0
    def chmod600(self, filepath):
        """
        Chmods 600 a file

        :param filepath: filepath to be chmodded
        :type filepath: str
        """
        check_and_fix_urw_only(filepath)
Ejemplo n.º 8
0
    def chmod600(self, filepath):
        """
        Chmods 600 a file

        :param filepath: filepath to be chmodded
        :type filepath: str
        """
        check_and_fix_urw_only(filepath)
Ejemplo n.º 9
0
    def _download_config_and_cert(self):
        """
        Downloads the SMTP config and cert for the given provider.
        """
        leap_assert(self._provider_config, "We need a provider configuration!")

        logger.debug("Downloading SMTP config for %s" %
                     (self._provider_config.get_domain(), ))

        download_service_config(self._provider_config, self._smtp_config,
                                self._session, self._download_if_needed)

        hosts = self._smtp_config.get_hosts()

        if len(hosts) == 0:
            raise NoSMTPHosts()

        # TODO handle more than one host and define how to choose
        hostname = hosts.keys()[0]
        logger.debug("Using hostname %s for SMTP" % (hostname, ))

        client_cert_path = self._smtp_config.get_client_cert_path(
            self._userid, self._provider_config, about_to_download=True)

        needs_download = leap_certs.should_redownload(client_cert_path)

        if needs_download:
            # For re-download if something is wrong with the cert
            # FIXME this doesn't read well. should reword the logic here.
            self._download_if_needed = (self._download_if_needed
                                        and not needs_download)

            if self._download_if_needed and os.path.isfile(client_cert_path):
                check_and_fix_urw_only(client_cert_path)
                return

            try:
                download_client_cert(self._provider_config,
                                     client_cert_path,
                                     self._session,
                                     kind="smtp")
            except HTTPError as exc:
                if exc.message.startswith('403 Client Error'):
                    logger.debug(
                        'Auth problem downloading smtp certificate... '
                        'It might be a provider problem, will try '
                        'fetching from vpn pool')
                    warnings.warn(
                        'Compatibility hack for platform 0.7 not fully '
                        'supporting smtp certificates. Will be deprecated in '
                        'bitmask 0.10')
                    download_client_cert(self._provider_config,
                                         client_cert_path,
                                         self._session,
                                         kind="vpn")
                else:
                    raise
Ejemplo n.º 10
0
def download_client_cert(provider_config, path, session):
    """
    Downloads the client certificate for each service.

    :param provider_config: instance of a ProviderConfig
    :type provider_config: ProviderConfig
    :param path: the path to download the cert to.
    :type path: str
    :param session: a fetcher.session instance. For the moment we only
                   support requests.sessions
    :type session: requests.sessions.Session
    """
    # TODO we should implement the @with_srp_auth decorator
    # again.
    srp_auth = SRPAuth(provider_config)
    session_id = srp_auth.get_session_id()
    token = srp_auth.get_token()
    cookies = None
    if session_id is not None:
        cookies = {"_session_id": session_id}
    cert_uri = "%s/%s/cert" % (
        provider_config.get_api_uri(),
        provider_config.get_api_version())
    logger.debug('getting cert from uri: %s' % cert_uri)

    headers = {}

    # API v2 will only support token auth, but in v1 we can send both
    if token is not None:
        headers["Authorization"] = 'Token token="{0}"'.format(token)

    res = session.get(cert_uri,
                      verify=provider_config
                      .get_ca_cert_path(),
                      cookies=cookies,
                      timeout=REQUEST_TIMEOUT,
                      headers=headers)
    res.raise_for_status()
    client_cert = res.content

    if not leap_certs.is_valid_pemfile(client_cert):
        # XXX raise more specific exception.
        raise Exception("The downloaded certificate is not a "
                        "valid PEM file")

    mkdir_p(os.path.dirname(path))

    try:
        with open(path, "w") as f:
            f.write(client_cert)
    except IOError as exc:
        logger.error(
            "Error saving client cert: %r" % (exc,))
        raise

    check_and_fix_urw_only(path)
Ejemplo n.º 11
0
def download_client_cert(provider_config, path, session):
    """
    Downloads the client certificate for each service.

    :param provider_config: instance of a ProviderConfig
    :type provider_config: ProviderConfig
    :param path: the path to download the cert to.
    :type path: str
    :param session: a fetcher.session instance. For the moment we only
                   support requests.sessions
    :type session: requests.sessions.Session
    """
    # TODO we should implement the @with_srp_auth decorator
    # again.
    srp_auth = SRPAuth(provider_config)
    session_id = srp_auth.get_session_id()
    token = srp_auth.get_token()
    cookies = None
    if session_id is not None:
        cookies = {"_session_id": session_id}
    cert_uri = "%s/%s/cert" % (provider_config.get_api_uri(),
                               provider_config.get_api_version())
    logger.debug('getting cert from uri: %s' % cert_uri)

    headers = {}

    # API v2 will only support token auth, but in v1 we can send both
    if token is not None:
        headers["Authorization"] = 'Token token="{0}"'.format(token)

    res = session.get(cert_uri,
                      verify=provider_config.get_ca_cert_path(),
                      cookies=cookies,
                      timeout=REQUEST_TIMEOUT,
                      headers=headers)
    res.raise_for_status()
    client_cert = res.content

    if not leap_certs.is_valid_pemfile(client_cert):
        # XXX raise more specific exception.
        raise Exception("The downloaded certificate is not a "
                        "valid PEM file")

    mkdir_p(os.path.dirname(path))

    try:
        with open(path, "w") as f:
            f.write(client_cert)
    except IOError as exc:
        logger.error("Error saving client cert: %r" % (exc, ))
        raise

    check_and_fix_urw_only(path)
Ejemplo n.º 12
0
    def _download_client_certificates(self, *args):
        """
        Downloads the EIP client certificate for the given provider
        """
        leap_assert(self._provider_config, "We need a provider configuration!")
        leap_assert(self._eip_config, "We need an eip configuration!")

        logger.debug("Downloading EIP client certificate for %s" %
                     (self._provider_config.get_domain(),))

        client_cert_path = self._eip_config.\
            get_client_cert_path(self._provider_config,
                                 about_to_download=True)

        # For re-download if something is wrong with the cert
        self._download_if_needed = self._download_if_needed and \
            not certs.should_redownload(client_cert_path)

        if self._download_if_needed and \
                os.path.exists(client_cert_path):
            check_and_fix_urw_only(client_cert_path)
            return

        srp_auth = SRPAuth(self._provider_config)
        session_id = srp_auth.get_session_id()
        cookies = None
        if session_id:
            cookies = {"_session_id": session_id}
        cert_uri = "%s/%s/cert" % (
            self._provider_config.get_api_uri(),
            self._provider_config.get_api_version())
        logger.debug('getting cert from uri: %s' % cert_uri)
        res = self._session.get(cert_uri,
                                verify=self._provider_config
                                .get_ca_cert_path(),
                                cookies=cookies,
                                timeout=REQUEST_TIMEOUT)
        res.raise_for_status()
        client_cert = res.content

        if not certs.is_valid_pemfile(client_cert):
            raise Exception(self.tr("The downloaded certificate is not a "
                                    "valid PEM file"))

        mkdir_p(os.path.dirname(client_cert_path))

        with open(client_cert_path, "w") as f:
            f.write(client_cert)

        check_and_fix_urw_only(client_cert_path)
Ejemplo n.º 13
0
    def _maybe_fetch_smtp_certificate(self, userid):
        # check if smtp cert exists
        username, provider = userid.split('@')
        cert_path = _get_smtp_client_cert_path(self._basedir, provider,
                                               username)
        if os.path.exists(cert_path):
            defer.returnValue(None)

        # fetch smtp cert and store
        bonafide = self.parent.getServiceNamed("bonafide")
        _, cert_str = yield bonafide.do_get_smtp_cert(userid)

        cert_dir = os.path.dirname(cert_path)
        if not os.path.exists(cert_dir):
            os.makedirs(cert_dir, mode=0700)
        with open(cert_path, 'w') as outf:
            outf.write(cert_str)
        check_and_fix_urw_only(cert_path)
Ejemplo n.º 14
0
    def _download_config_and_cert(self):
        """
        Downloads the SMTP config and cert for the given provider.
        """
        leap_assert(self._provider_config,
                    "We need a provider configuration!")

        logger.debug("Downloading SMTP config for %s" %
                     (self._provider_config.get_domain(),))

        download_service_config(
            self._provider_config,
            self._smtp_config,
            self._session,
            self._download_if_needed)

        hosts = self._smtp_config.get_hosts()

        if len(hosts) == 0:
            raise NoSMTPHosts()

        # TODO handle more than one host and define how to choose
        hostname = hosts.keys()[0]
        logger.debug("Using hostname %s for SMTP" % (hostname,))

        client_cert_path = self._smtp_config.get_client_cert_path(
            self._provider_config, about_to_download=True)

        if not is_file(client_cert_path):
            # For re-download if something is wrong with the cert
            self._download_if_needed = (
                self._download_if_needed and
                not leap_certs.should_redownload(client_cert_path))

            if self._download_if_needed and os.path.isfile(client_cert_path):
                check_and_fix_urw_only(client_cert_path)
                return

            download_client_cert(self._provider_config,
                                 client_cert_path,
                                 self._session)
Ejemplo n.º 15
0
    def do_get_cert(self, username):
        try:
            _, provider = username.split('@')
        except ValueError:
            if not username:
                raise ValueError('Need an username. are you logged in?')
            raise ValueError(username + ' is not a valid username, it should'
                             ' contain an @')

        # fetch vpn cert and store
        bonafide = self.parent.getServiceNamed("bonafide")
        _, cert_str = yield bonafide.do_get_vpn_cert(username)

        cert_path = get_vpn_cert_path(provider)
        cert_dir = os.path.dirname(cert_path)
        if not os.path.exists(cert_dir):
            os.makedirs(cert_dir, mode=0700)
        with open(cert_path, 'w') as outf:
            outf.write(cert_str)
        check_and_fix_urw_only(cert_path)
        defer.returnValue({'get_cert': 'ok'})
Ejemplo n.º 16
0
    def _download_config_and_cert(self):
        """
        Downloads the SMTP config and cert for the given provider.
        """
        leap_assert(self._provider_config, "We need a provider configuration!")

        logger.debug("Downloading SMTP config for %s" %
                     (self._provider_config.get_domain(), ))

        download_service_config(self._provider_config, self._smtp_config,
                                self._session, self._download_if_needed)

        hosts = self._smtp_config.get_hosts()

        if len(hosts) == 0:
            raise NoSMTPHosts()

        # TODO handle more than one host and define how to choose
        hostname = hosts.keys()[0]
        logger.debug("Using hostname %s for SMTP" % (hostname, ))

        client_cert_path = self._smtp_config.get_client_cert_path(
            self._provider_config, about_to_download=True)

        if not is_file(client_cert_path):
            # For re-download if something is wrong with the cert
            self._download_if_needed = (
                self._download_if_needed
                and not leap_certs.should_redownload(client_cert_path))

            if self._download_if_needed and os.path.isfile(client_cert_path):
                check_and_fix_urw_only(client_cert_path)
                return

            download_client_cert(self._provider_config, client_cert_path,
                                 self._session)
Ejemplo n.º 17
0
def download_client_cert(provider_config, path, session, kind="vpn"):
    """
    Downloads the client certificate for each service.

    :param provider_config: instance of a ProviderConfig
    :type provider_config: ProviderConfig
    :param path: the path to download the cert to.
    :type path: str
    :param session: a fetcher.session instance. For the moment we only
                   support requests.sessions
    :type session: requests.sessions.Session
    :param kind: the kind of certificate being requested. Valid values are
                 "vpn" or "smtp".
    :type kind: string
    """
    srp_auth = SRPAuth(provider_config)
    session_id = srp_auth.get_session_id()
    token = srp_auth.get_token()
    cookies = None
    if session_id is not None:
        cookies = {"_session_id": session_id}

    if kind == "vpn":
        cert_uri_template = "%s/%s/cert"
        method = 'get'
        params = {}
    elif kind == 'smtp':
        cert_uri_template = "%s/%s/smtp_cert"
        method = 'post'
        params = {'address': srp_auth.get_username()}
    else:
        raise ValueError("Incorrect value passed to kind parameter")

    cert_uri = cert_uri_template % (
        provider_config.get_api_uri(),
        provider_config.get_api_version())

    logger.debug('getting %s cert from uri: %s' % (kind, cert_uri))

    headers = {}

    # API v2 will only support token auth, but in v1 we can send both
    if token is not None:
        headers["Authorization"] = 'Token token={0}'.format(token)

    call = getattr(session, method)
    res = call(cert_uri, verify=provider_config.get_ca_cert_path(),
               cookies=cookies, params=params,
               timeout=REQUEST_TIMEOUT,
               headers=headers, data=params)
    res.raise_for_status()
    client_cert = res.content

    if not leap_certs.is_valid_pemfile(client_cert):
        # XXX raise more specific exception.
        raise Exception("The downloaded certificate is not a "
                        "valid PEM file")
    mkdir_p(os.path.dirname(path))

    try:
        with open(path, "w") as f:
            f.write(client_cert)
    except IOError as exc:
        logger.error(
            "Error saving client cert: %r" % (exc,))
        raise

    check_and_fix_urw_only(path)
Ejemplo n.º 18
0
 def chmod600(self, filepath):
     check_and_fix_urw_only(filepath)
Ejemplo n.º 19
0
def download_client_cert(provider_config, path, session, kind="vpn"):
    """
    Downloads the client certificate for each service.

    :param provider_config: instance of a ProviderConfig
    :type provider_config: ProviderConfig
    :param path: the path to download the cert to.
    :type path: str
    :param session: a fetcher.session instance. For the moment we only
                   support requests.sessions
    :type session: requests.sessions.Session
    :param kind: the kind of certificate being requested. Valid values are
                 "vpn" or "smtp".
    :type kind: string
    """
    srp_auth = SRPAuth(provider_config)
    session_id = srp_auth.get_session_id()
    token = srp_auth.get_token()
    cookies = None
    if session_id is not None:
        cookies = {"_session_id": session_id}

    if kind == "vpn":
        cert_uri_template = "%s/%s/cert"
        method = "get"
        params = {}
    elif kind == "smtp":
        cert_uri_template = "%s/%s/smtp_cert"
        method = "post"
        params = {"address": srp_auth.get_username()}
    else:
        raise ValueError("Incorrect value passed to kind parameter")

    cert_uri = cert_uri_template % (provider_config.get_api_uri(), provider_config.get_api_version())

    logger.debug("getting %s cert from uri: %s" % (kind, cert_uri))

    headers = {}

    # API v2 will only support token auth, but in v1 we can send both
    if token is not None:
        headers["Authorization"] = "Token token={0}".format(token)

    call = getattr(session, method)
    res = call(
        cert_uri,
        verify=provider_config.get_ca_cert_path(),
        cookies=cookies,
        params=params,
        timeout=REQUEST_TIMEOUT,
        headers=headers,
        data=params,
    )
    res.raise_for_status()
    client_cert = res.content

    if not leap_certs.is_valid_pemfile(client_cert):
        # XXX raise more specific exception.
        raise Exception("The downloaded certificate is not a " "valid PEM file")
    mkdir_p(os.path.dirname(path))

    try:
        with open(path, "w") as f:
            f.write(client_cert)
    except IOError as exc:
        logger.error("Error saving client cert: %r" % (exc,))
        raise

    check_and_fix_urw_only(path)