def _download_config(self, *args):
        """
        Downloads the SMTP config 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(),))

        headers = {}
        mtime = get_mtime(os.path.join(self._smtp_config
                                       .get_path_prefix(),
                                       "leap",
                                       "providers",
                                       self._provider_config.get_domain(),
                                       "smtp-service.json"))

        if self._download_if_needed and mtime:
            headers['if-modified-since'] = mtime

        api_version = self._provider_config.get_api_version()

        # there is some confusion with this uri,
        config_uri = "%s/%s/config/smtp-service.json" % (
            self._provider_config.get_api_uri(), api_version)

        logger.debug('Downloading SMTP config from: %s' % config_uri)

        srp_auth = SRPAuth(self._provider_config)
        session_id = srp_auth.get_session_id()
        cookies = None
        if session_id:
            cookies = {"_session_id": session_id}

        res = self._session.get(config_uri,
                                verify=self._provider_config
                                .get_ca_cert_path(),
                                headers=headers,
                                cookies=cookies)
        res.raise_for_status()

        self._smtp_config.set_api_version(api_version)

        # Not modified
        if res.status_code == 304:
            logger.debug("SMTP definition has not been modified")
            self._smtp_config.load(os.path.join(
                "leap", "providers",
                self._provider_config.get_domain(),
                "smtp-service.json"))
        else:
            smtp_definition, mtime = get_content(res)

            self._smtp_config.load(data=smtp_definition, mtime=mtime)
            self._smtp_config.save(["leap",
                                    "providers",
                                    self._provider_config.get_domain(),
                                    "smtp-service.json"])
Esempio n. 2
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)
Esempio n. 3
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)
    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)
Esempio n. 5
0
def download_service_config(provider_config, service_config,
                            session,
                            download_if_needed=True):
    """
    Downloads config for a given service.

    :param provider_config: an instance of ProviderConfig
    :type provider_config: ProviderConfig

    :param service_config: an instance of a particular Service config.
    :type service_config: BaseConfig

    :param session: an instance of a fetcher.session
                    (currently we're using requests only, but it can be
                    anything that implements that interface)
    :type session: requests.sessions.Session
    """
    service_name = service_config.name
    service_json = "{0}-service.json".format(service_name)
    headers = {}
    mtime = get_mtime(os.path.join(util.get_path_prefix(),
                                   "leap", "providers",
                                   provider_config.get_domain(),
                                   service_json))

    if download_if_needed and mtime:
        headers['if-modified-since'] = mtime

    api_version = provider_config.get_api_version()

    config_uri = "%s/%s/config/%s-service.json" % (
        provider_config.get_api_uri(),
        api_version,
        service_name)
    logger.debug('Downloading %s config from: %s' % (
        service_name.upper(),
        config_uri))

    # XXX make and use @with_srp_auth decorator
    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}

    # 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)

    verify = provider_config.get_ca_cert_path()
    if verify:
        verify = verify.encode(sys.getfilesystemencoding())

    res = session.get(config_uri,
                      verify=verify,
                      headers=headers,
                      timeout=REQUEST_TIMEOUT,
                      cookies=cookies)
    res.raise_for_status()

    service_config.set_api_version(api_version)

    # Not modified
    service_path = ("leap", "providers", provider_config.get_domain(),
                    service_json)
    if res.status_code == 304:
        logger.debug(
            "{0} definition has not been modified".format(
                service_name.upper()))
        service_config.load(os.path.join(*service_path))
    else:
        service_definition, mtime = get_content(res)
        service_config.load(data=service_definition, mtime=mtime)
        service_config.save(service_path)
Esempio n. 6
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)
Esempio n. 7
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)