Exemplo n.º 1
0
 def _get(self, server_name):
     if server_name not in self._data["hosts"]:
         raise KeyError(server_name)
     pem = self._path.child(server_name+".pem")
     if pem.isfile():
         return parse(pem.getContent())
     return parse(b"")
Exemplo n.º 2
0
def network_kubernetes_from_context(
        reactor, context=None, path=None, environ=None,
        default_config_path=FilePath(expanduser(u"~/.kube/config")),
):
    """
    Create a new ``IKubernetes`` provider based on a kube config file.

    :param reactor: A Twisted reactor which will be used for I/O and
        scheduling.

    :param unicode context: The name of the kube config context from which to
        load configuration details.  Or, ``None`` to respect the current
        context setting from the configuration.

    :param FilePath path: The location of the kube config file to use.

    :param dict environ: A environment direction in which to look up
        ``KUBECONFIG``.  If ``None``, the real process environment will be
        inspected.  This is used only if ``path`` is ``None``.

    :return IKubernetes: The Kubernetes service described by the named
        context.
    """
    if path is None:
        if environ is None:
            from os import environ
        try:
            kubeconfigs = environ[u"KUBECONFIG"]
        except KeyError:
            config = KubeConfig.from_file(default_config_path.path)
        else:
            config = _merge_configs_from_env(kubeconfigs)
    else:
        config = KubeConfig.from_file(path.path)

    if context is None:
        context = config.doc[u"current-context"]

    context = config.contexts[context]
    cluster = config.clusters[context[u"cluster"]]
    user = config.users[context[u"user"]]

    if isinstance(cluster[u"server"], bytes):
        base_url = URL.fromText(cluster[u"server"].decode("ascii"))
    else:
        base_url = URL.fromText(cluster[u"server"])
    [ca_cert] = parse(cluster[u"certificate-authority"].bytes())

    client_chain = parse(user[u"client-certificate"].bytes())
    [client_key] = parse(user[u"client-key"].bytes())

    agent = authenticate_with_certificate_chain(
        reactor, base_url, client_chain, client_key, ca_cert,
    )

    return network_kubernetes(
        base_url=base_url,
        agent=agent,
    )
Exemplo n.º 3
0
    def test_certificateOptionsFromPEMs(self, tmpdir, recwarn):
        """
        pem.certificateOptionsFromPEMs raises a deprecation warning.
        """
        with pytest.warns(DeprecationWarning) as ws:
            pem.certificateOptionsFromPEMs(
                pem.parse(CERT_PEMS[0]) + pem.parse(KEY_PEM), )

            assert "certificateOptionsFromPEMs" in str(ws[0].message)
Exemplo n.º 4
0
    def test_certificateOptionsFromPEMs(self, tmpdir, recwarn):
        """
        pem.certificateOptionsFromPEMs raises a deprecation warning.
        """
        with pytest.warns(DeprecationWarning) as ws:
            pem.certificateOptionsFromPEMs(
                pem.parse(CERT_PEMS[0]) + pem.parse(KEY_PEM),
            )

            assert "certificateOptionsFromPEMs" in str(ws[0].message)
Exemplo n.º 5
0
def _convert_oldsecrets(oldsecrets):
    if oldsecrets:
        if oldsecrets["introducer_node_pem"] is not None:
            oldsecrets["introducer_node_pem"] = parse(
                oldsecrets["introducer_node_pem"])
        if oldsecrets["server_node_pem"] is not None:
            oldsecrets["server_node_pem"] = parse(
                oldsecrets["server_node_pem"])
        return oldsecrets
    return {}
Exemplo n.º 6
0
 def test_certificate_no_new_line(self):
     """
     Parses a PEM string without a new line at the end
     """
     cert, = pem.parse(CERT_NO_NEW_LINE)
     assert isinstance(cert, pem.Certificate)
     assert CERT_NO_NEW_LINE == str(cert)
Exemplo n.º 7
0
 def test_allows_lf(self):
     """
     \n and \r\n are treated equal.
     """
     lf_pem = KEY_PEM.replace("\n", "\r\n")
     rv, = pem.parse(lf_pem)
     assert str(rv) == lf_pem
Exemplo n.º 8
0
 def test_allows_lf(self):
     """
     \n and \r\n are treated equal.
     """
     lf_pem = KEY_PEM.replace(b"\n", b"\r\n")
     rv, = pem.parse(lf_pem)
     assert rv.as_bytes() == lf_pem
Exemplo n.º 9
0
    def create_certificate(self, csr, issuer_options):
        """Create a DigiCert certificate."""
        base_url = current_app.config.get("DIGICERT_CIS_URL")

        # make certificate request
        create_url = "{0}/platform/cis/certificate".format(base_url)

        data = map_cis_fields(issuer_options, csr)
        response = self.session.post(create_url, data=json.dumps(data))
        data = handle_cis_response(response)

        # retrieve certificate
        certificate_pem = get_cis_certificate(self.session, base_url,
                                              data["id"])

        self.session.headers.pop("Accept")
        end_entity = pem.parse(certificate_pem)[0]

        if "ECC" in issuer_options["key_type"]:
            return (
                "\n".join(str(end_entity).splitlines()),
                current_app.config.get("DIGICERT_ECC_CIS_INTERMEDIATES",
                                       {}).get(
                                           issuer_options['authority'].name),
                data["id"],
            )

        # By default return RSA
        return (
            "\n".join(str(end_entity).splitlines()),
            current_app.config.get("DIGICERT_CIS_INTERMEDIATES",
                                   {}).get(issuer_options['authority'].name),
            data["id"],
        )
Exemplo n.º 10
0
    def validate_certificate(self,
                             certificate: str,
                             chain: str,
                             crl: str = None) -> None:
        """
        Tests if a certificate has been signed by the chain, is not revoked
        and has not yet been expired.
        :param certificate: the certificate to test as string
        :param chain: the certificate chain file content as string
        :param crl: the certificate revocation list file content as string
        :raises: InvalidCertificateException if the certificate is invalid
        :return: None
        """
        # root and intermediary certificate need to be split
        cas = pem.parse(chain.encode())
        store = X509Store()
        for ca in cas:
            store.add_cert(self._to_cert(str(ca)))

        cert = self._to_cert(certificate)

        if crl:
            parsed_crl = load_crl(FILETYPE_PEM, crl)
            store.set_flags(X509StoreFlags.CRL_CHECK)
            store.add_crl(parsed_crl)

        ctx = X509StoreContext(store, cert)
        err_msg = 'Certificate is invalid'

        try:
            result = ctx.verify_certificate()
            if result is not None:
                raise InvalidCertificateException(err_msg)
        except Exception as e:
            raise InvalidCertificateException('%s: %s' % (err_msg, str(e)))
Exemplo n.º 11
0
 def fake_get_peer_cert_chain(chain):
     with open(chain, "rb") as chain_file:
         chain_certs = []
         for _ca in pem.parse(chain_file.read()):
             chain_certs.append(
                 crypto.load_certificate(crypto.FILETYPE_PEM, str(_ca)))
         return chain_certs
Exemplo n.º 12
0
    def check_config_certificate_chain(self):
        """
        Check if both the certificate and the chain
        in the configuration are compatible with each other.

        :return: Boolean true or raises an exception
        """
        with open(self.cert, "rb") as certificate_file, \
                open(self.chain, "rb") as chain_file:

            certificate_raw = certificate_file.read()
            chain_raw = chain_file.read()
            certificate_obj = crypto.load_certificate(crypto.FILETYPE_PEM,
                                                      certificate_raw)
            certificates_chain = crypto.X509Store()
            for certificate in pem.parse(chain_raw):
                certificates_chain.add_cert(
                    crypto.load_certificate(crypto.FILETYPE_PEM,
                                            str(certificate)))
            store_ctx = crypto.X509StoreContext(certificates_chain,
                                                certificate_obj)
        try:
            store_ctx.verify_certificate()
        except crypto.X509StoreContextError as message:
            raise DevoSenderException(
                "Error in config, the chain: " + self.chain +
                " is not compatible with the certificate: " + self.cert +
                "\noriginal error: " + str(message))
        return True
Exemplo n.º 13
0
def load_root_ca_list():
    """ load all certificates found in openssl cert.pem (via certifi.where())
        
        :return: returns X509store obj loaded with trusted Cert.  
        :rtype: X509store
    """
    try:
        # Mac shipps with 175 root CA certs vs. 139 from pyOpenssl.  In my testing, the 175s vs. 139
        # didn't result in increase in validation count across 10k certs.  However your mileage may vary
        # reaplce apple-system-root.pem w/ certifi.where() to use openssl cert store
        with open("apple-system-root.pem", "rb") as f:
            certs = pem.parse(f.read())
            store = crypto.X509Store()
            for cert in certs:
                cacert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                                 cert.as_text())
                store.add_cert(cacert)
                log(f"loading root CA store w/ {cacert.get_subject().CN} ",
                    "DEBUG")
            return store
    except EnvironmentError:  # parent of IOError, OSError *and* WindowsError where available
        log(f"No CA Store found at {certifi.where()}, can not validate\n\n",
            "ERROR")
        raise FileNotFoundError
    return None
Exemplo n.º 14
0
    def test_ordering(self):
        """
        Each certificate in ``Chain`` must be signed by the following certificate.
        """
        a_key, b_key, c_key = tuple(
            rsa.generate_private_key(
                public_exponent=65537,
                key_size=512,
                backend=default_backend(),
            ) for i in range(3))

        a_cert = cert(u"a.invalid", u"a.invalid", a_key.public_key(), a_key,
                      True)
        b_cert = cert(u"a.invalid", u"b.invalid", b_key.public_key(), a_key,
                      True)
        c_cert = cert(u"b.invalid", u"c.invalid", c_key.public_key(), b_key,
                      False)

        a, b, c = pem.parse(b"\n".join(
            cert.public_bytes(serialization.Encoding.PEM)
            for cert in (a_cert, b_cert, c_cert)))

        # a is not signed by b.  Rather, the reverse.  Therefore this ordering
        # is an error.
        self.expectThat(
            lambda: Chain(certificates=Certificates([c, a, b])),
            raises(InvariantException),
        )
        # c is signed by b and b is signed by a.  Therefore this is perfect.
        self.expectThat(
            Chain(certificates=Certificates([c, b, a])),
            IsInstance(Chain),
        )
Exemplo n.º 15
0
def parse_pem_certificates(pem_bytes: bytes) -> List[Certificate]:
    """Parses a list of certificates from PEM bytes.

    Args:
        pem_bytes: List of X.509 certificates as PEM blocks bytes.

    Returns:
        A list of Certificate objects.

    Raises:
        X509CertificateError: In case the certificates cannot be parsed from the pem_bytes.
    """

    parsed_certs = pem.parse(pem_bytes)
    if not parsed_certs:
        raise X509CertificateError('Unable to parse PEM X.509 certificate')

    result = []
    for cert in parsed_certs:
        try:
            x509_cert = x509.load_pem_x509_certificate(cert.as_bytes(),
                                                       default_backend())
            result.append(x509_cert)
        except Exception:
            raise X509CertificateError('Unable to parse PEM X.509 certificate')

    return result
Exemplo n.º 16
0
def get_pemfile(cert_url):
    """
    Acquire the keyfile
    SNS keys expire and Amazon does not promise they will use the same key
    for all SNS requests. So we need to keep a copy of the cert in our
    cache
    """
    key_cache = caches[getattr(settings, 'AWS_PEM_CACHE', 'default')]

    pemfile = key_cache.get(cert_url)
    if not pemfile:
        try:
            response = requests.get(cert_url)
            response.raise_for_status()
        except HTTPError as e:
            logger.error('Unable to fetch the keyfile: %s' % e)
            raise
        pemfile = response.text
        # Extract the first certificate in the file and confirm it's a valid
        # PEM certificate
        certificates = pem.parse(smart_bytes(pemfile))
        # A proper certificate file will contain 1 certificate
        if len(certificates) != 1:
            logger.error('Invalid Certificate File: URL %s', cert_url)
            raise ValueError('Invalid Certificate File')

        key_cache.set(cert_url, pemfile)
    return pemfile
    def test_interface(self, cert_and_key):
        """
        ``makeService`` returns an object that provides ``IService``.
        """
        scratch = FilePath(self.mktemp())
        scratch.makedirs()

        cert, key = pem.parse(cert_and_key)

        config = write_kubernetes_configuration(
            scratch, cert, key,
        )

        access_key_id_path = FilePath(self.mktemp())
        access_key_id_path.setContent(b"foo")
        secret_access_key_path = FilePath(self.mktemp())
        secret_access_key_path.setContent(b"bar")
        options = Options()
        options.parseOptions([
            b"--domain", b"s4.example.com",
            b"--kubernetes-namespace", b"testing",
            b"--endpoint", b"http://localhost:8000/",
            b"--aws-access-key-id-path", access_key_id_path.path,
            b"--aws-secret-access-key-path", secret_access_key_path.path,
            b"--introducer-image", b"introducer",
            b"--storageserver-image", b"storageserver",
            b"--kubernetes", b"kubernetes",
            b"--k8s-context", u"testing",
            b"--k8s-config", config.path,
        ])
        service = makeService(options)
        verifyObject(IService, service)
Exemplo n.º 18
0
    def create_certificate(self, csr, issuer_options):
        """Create a DigiCert certificate."""
        base_url = current_app.config.get('DIGICERT_CIS_URL')

        # make certificate request
        create_url = '{0}/platform/cis/certificate'.format(base_url)

        data = map_cis_fields(issuer_options, csr)
        response = self.session.post(create_url, data=json.dumps(data))
        data = handle_cis_response(response)

        # retrieve certificate
        certificate_pem = get_cis_certificate(self.session, base_url,
                                              data['id'])

        self.session.headers.pop('Accept')
        end_entity = pem.parse(certificate_pem)[0]

        if 'ECC' in issuer_options['key_type']:
            return "\n".join(
                str(end_entity).splitlines()), current_app.config.get(
                    'DIGICERT_ECC_CIS_INTERMEDIATE'), data['id']

        # By default return RSA
        return "\n".join(str(end_entity).splitlines()), current_app.config.get(
            'DIGICERT_CIS_INTERMEDIATE'), data['id']
Exemplo n.º 19
0
    def create_certificate(self, csr, issuer_options):
        """Create a DigiCert certificate.

        :param csr:
        :param issuer_options:
        :return: :raise Exception:
        """
        base_url = current_app.config.get('DIGICERT_URL')

        # make certificate request
        determinator_url = "{0}/services/v2/order/certificate/ssl".format(
            base_url)
        data = map_fields(issuer_options, csr)
        response = self.session.post(determinator_url, data=json.dumps(data))

        if response.status_code > 399:
            raise Exception(response.json()['message'])

        order_id = response.json()['id']

        certificate_id = get_certificate_id(self.session, base_url, order_id)

        # retrieve ceqrtificate
        certificate_url = "{0}/services/v2/certificate/{1}/download/format/pem_all".format(
            base_url, certificate_id)
        end_entity, intermediate, root = pem.parse(
            self.session.get(certificate_url).content)
        return str(end_entity), str(intermediate)
Exemplo n.º 20
0
 def got_cert(certr):
     """
     Called when we got a certificate.
     """
     # The certificate is returned as chain.
     objects.extend(pem.parse(certr.body))
     self.cert_store.store(','.join(names), objects)
Exemplo n.º 21
0
    def test_ec_private_key(self):
        """
        Detects and loads EC private keys.
        """
        key = pem.parse(KEY_PEM_EC_PRIVATE)[0]

        assert isinstance(key, pem.ECPrivateKey)
Exemplo n.º 22
0
 def test_allows_lf(self):
     """
     \n and \r\n are treated equal.
     """
     lf_pem = KEY_PEM.replace(b"\n", b"\r\n")
     rv, = pem.parse(lf_pem)
     assert rv.as_bytes() == lf_pem
Exemplo n.º 23
0
    def add_chain(self):
        from redo import retry
        import requests
        import pem

        def get_chain():
            r = requests.get(self.chain_url)
            r.raise_for_status()
            return r.text

        chain = retry(get_chain)

        req = {"chain": []}
        chain = pem.parse(chain)
        for i in range(len(chain)):
            cert = crypto.load_certificate(crypto.FILETYPE_PEM, str(chain[i]))
            der = crypto.dump_certificate(crypto.FILETYPE_ASN1, cert)
            req["chain"].append(base64.b64encode(der))

        def post_chain():
            r = requests.post(self.log_url + '/ct/v1/add-chain', json=req)
            r.raise_for_status()
            return r.json()

        resp = retry(post_chain)
        sct = SignedCertificateTimestamp(resp)
        self.write_to_file(self.sct_filename, sct.to_rfc6962())
Exemplo n.º 24
0
def grab_keyfile(cert_url):
    """
    Function to acqure the keyfile

    SNS keys expire and Amazon does not promise they will use the same key
    for all SNS requests. So we need to keep a copy of the cert in our
    cache
    """
    key_cache = caches[getattr(settings, 'BOUNCY_KEY_CACHE', 'default')]

    pemfile = key_cache.get(cert_url)
    if not pemfile:
        response = urlopen(cert_url)
        pemfile = response.read()
        # Extract the first certificate in the file and confirm it's a valid
        # PEM certificate
        certificates = pem.parse(smart_str(pemfile))

        # A proper certificate file will contain 1 certificate
        if len(certificates) != 1:
            logger.error('Invalid Certificate File: URL %s', cert_url)
            raise ValueError('Invalid Certificate File')

        key_cache.set(cert_url, pemfile)
    return pemfile
Exemplo n.º 25
0
    def validate_certificate(self, certificate: str, chain: str,
                             crl: str = None) -> None:
        """
        Tests if a certificate has been signed by the chain, is not revoked
        and has not yet been expired.
        :param certificate: the certificate to test as string
        :param chain: the certificate chain file content as string
        :param crl: the certificate revocation list file content as string
        :raises: InvalidCertificateException if the certificate is invalid
        :return: None
        """
        # root and intermediary certificate need to be split
        cas = pem.parse(chain.encode())
        store = X509Store()
        for ca in cas:
            store.add_cert(self._to_cert(str(ca)))

        cert = self._to_cert(certificate)

        if crl:
            parsed_crl = load_crl(FILETYPE_PEM, crl)
            store.set_flags(X509StoreFlags.CRL_CHECK)
            store.add_crl(parsed_crl)

        ctx = X509StoreContext(store, cert)
        err_msg = 'Certificate is invalid'

        try:
            result = ctx.verify_certificate()
            if result is not None:
                raise InvalidCertificateException(err_msg)
        except Exception as e:
            raise InvalidCertificateException('%s: %s' % (err_msg, str(e)))
Exemplo n.º 26
0
    def add_chain(self):
        from redo import retry
        import requests
        import pem

        def get_chain():
            r = requests.get(self.chain_url)
            r.raise_for_status()
            return r.text

        chain = retry(get_chain)

        req = {"chain": []}
        chain = pem.parse(chain)
        for i in range(len(chain)):
            cert = crypto.load_certificate(crypto.FILETYPE_PEM, str(chain[i]))
            der = crypto.dump_certificate(crypto.FILETYPE_ASN1, cert)
            req["chain"].append(base64.b64encode(der))

        def post_chain():
            r = requests.post(self.log_url + '/ct/v1/add-chain', json=req)
            r.raise_for_status()
            return r.json()

        resp = retry(post_chain)
        sct = SignedCertificateTimestamp(resp)
        self.write_to_file(self.sct_filename, sct.to_rfc6962())
Exemplo n.º 27
0
    def test_openshh_private_key(self):
        """
        Detects and loads private keys in the new OpenSSH private key format.
        """
        (key, ) = pem.parse(KEY_PEM_OPENSSH)

        assert isinstance(key, pem.OpenSSHPrivateKey)
Exemplo n.º 28
0
    def create_certificate(self, csr, issuer_options):
        """Create a DigiCert certificate.

        :param csr:
        :param issuer_options:
        :return: :raise Exception:
        """
        base_url = current_app.config.get("DIGICERT_URL")
        cert_type = current_app.config.get("DIGICERT_ORDER_TYPE")

        # make certificate request
        determinator_url = "{0}/services/v2/order/certificate/{1}".format(
            base_url, cert_type)
        data = map_fields(issuer_options, csr)
        response = self.session.post(determinator_url, data=json.dumps(data))

        if response.status_code > 399:
            raise Exception(response.json()["errors"][0]["message"])

        order_id = response.json()["id"]

        certificate_id = get_certificate_id(self.session, base_url, order_id)

        # retrieve certificate
        certificate_url = "{0}/services/v2/certificate/{1}/download/format/pem_all".format(
            base_url, certificate_id)
        end_entity, intermediate, root = pem.parse(
            self.session.get(certificate_url).content)
        return (
            "\n".join(str(end_entity).splitlines()),
            "\n".join(str(intermediate).splitlines()),
            certificate_id,
        )
Exemplo n.º 29
0
    def verify_pem(self, pem_text, req, ca_store=None):

        if ca_store is None:
            ca_store = self.ca_store()

        ca_certs, certs = [], pem.parse(pem_text)
        for i, cert in enumerate(certs):
            ca_certs.append(
                crypto.load_certificate(crypto.FILETYPE_PEM, cert.as_bytes()))

            try:
                crypto.X509StoreContext(ca_store, ca_certs[i]) \
                      .verify_certificate()

            except crypto.X509StoreContextError as ex:
                logging.error('issuer:{} and subject:{}'.format(
                    ca_certs[i].get_subject(), ca_certs[i].get_issuer()))
                logging.error(ex)
                ca_certs.pop()
                break

        if len(ca_certs) != len(certs):
            raise falcon.HTTPBadRequest(
                description='certificate verification failed',
                headers={
                    'SignatureCertChainUrl': self.certificate_url(req),
                    'Signature': self.signature(req)
                })
        else:
            return ca_certs[0]
Exemplo n.º 30
0
 def test_certificate_no_new_line(self):
     """
     Parses a PEM string without a new line at the end
     """
     cert, = pem.parse(CERT_NO_NEW_LINE)
     assert isinstance(cert, pem.Certificate)
     assert CERT_NO_NEW_LINE == cert.as_bytes()
Exemplo n.º 31
0
    def run(cls, _input: Decodable, **kwargs) -> Optional[bytes]:
        """Decodes PEM certificate as bytes containing
         certificate info in DER format.

        :param _input: String or bytes
        :param kwargs:
        :return: Bytes string if decoded successfully, else None
        """
        if isinstance(_input, str):
            _input = _input.encode("utf-8")

        if not _input.startswith(b"-----"):
            return None

        try:
            pems = pem.parse(_input)
        except:
            return None

        res = []
        for p in pems:
            try:
                res.append(
                    base64.b64decode(b"".join(
                        p.as_bytes().splitlines()[1:-1])))
            except:
                continue

        return b"\n\n".join(res)
Exemplo n.º 32
0
def cert_to_jwk(certificates: str, public_key: str) -> str:
    """
    coverts a pem public key and a pem certificate chain to a jwk with a x5c element
    :param certificates: the certificates for the x5c as pem key list
    :param public_key: the pem public key as string
    :return: the jwk as string
    """

    # convert public key to jwk
    public_key = crypto.load_publickey(crypto.FILETYPE_PEM, public_key)
    jwk = JWK.load(crypto.dump_publickey(crypto.FILETYPE_PEM, public_key))

    # covert cert chain to base64 encoded ASN1 according to https://tools.ietf.org/html/rfc7517#section-4.7
    x5c = []
    for cert in pem.parse(str.encode(certificates)):
        cert_pem = crypto.load_certificate(crypto.FILETYPE_PEM,
                                           cert.as_bytes())
        x5c.append(
            base64.b64encode(
                crypto.dump_certificate(crypto.FILETYPE_ASN1,
                                        cert_pem)).decode())

    # dump jwk obj to json and add x5c cer chain
    jwk_j = jwk.to_json()
    jwk_j["x5c"] = x5c
    return json.dumps(jwk_j)
Exemplo n.º 33
0
    def test_generic_public_key(self):
        """
        Detects and loads generic public keys.
        """
        key = pem.parse(KEY_PEM_PUBLIC)[0]

        assert isinstance(key, pem.PublicKey)
Exemplo n.º 34
0
def grab_keyfile(cert_url):
    """
    Function to acqure the keyfile

    SNS keys expire and Amazon does not promise they will use the same key
    for all SNS requests. So we need to keep a copy of the cert in our
    cache
    """
    key_cache = caches[getattr(settings, 'BOUNCY_KEY_CACHE', 'default')]

    pemfile = key_cache.get(cert_url)
    if not pemfile:
        response = urlopen(cert_url)
        pemfile = response.read()
        # Extract the first certificate in the file and confirm it's a valid
        # PEM certificate
        certificates = pem.parse(smart_str(pemfile))

        # A proper certificate file will contain 1 certificate
        if len(certificates) != 1:
            logger.error('Invalid Certificate File: URL %s', cert_url)
            raise ValueError('Invalid Certificate File')

        key_cache.set(cert_url, pemfile)
    return pemfile
Exemplo n.º 35
0
    def create_certificate(self, csr, issuer_options):
        """Create a DigiCert certificate.

        :param csr:
        :param issuer_options:
        :return: :raise Exception:
        """
        base_url = current_app.config.get('DIGICERT_URL')

        # make certificate request
        determinator_url = "{0}/services/v2/order/certificate/ssl".format(base_url)
        data = map_fields(issuer_options, csr)
        response = self.session.post(determinator_url, data=json.dumps(data))

        if response.status_code > 399:
            raise Exception(response.json()['errors'][0]['message'])

        order_id = response.json()['id']

        certificate_id = get_certificate_id(self.session, base_url, order_id)

        # retrieve certificate
        certificate_url = "{0}/services/v2/certificate/{1}/download/format/pem_all".format(base_url, certificate_id)
        end_entity, intermediate, root = pem.parse(self.session.get(certificate_url).content)
        return "\n".join(str(end_entity).splitlines()), "\n".join(str(intermediate).splitlines())
Exemplo n.º 36
0
    def test_generic_public_key(self):
        """
        Detects and loads generic public keys.
        """
        key = pem.parse(KEY_PEM_PUBLIC)[0]

        assert isinstance(key, pem.PublicKey)
Exemplo n.º 37
0
 def _parse_pem(data: str) -> str:
     pems = pem.parse(data.encode())
     if not pems:
         raise BadRequest("data not PEM")
     lines = pems[0].as_text().strip().split("\n")
     pem_cert = "".join(lines[1:-1])
     return pem_cert
Exemplo n.º 38
0
 def test_certificates_no_new_line(self):
     """
     Parses a PEM string with multiple certificates without a new line
     at the end into a list of corresponding Certificates.
     """
     certs = pem.parse(''.join(CERT_PEMS_NO_NEW_LINE))
     assert all(isinstance(c, pem.Certificate) for c in certs)
     assert CERT_PEMS_NO_NEW_LINE == [str(cert) for cert in certs]
Exemplo n.º 39
0
 def test_dh(self):
     """
     Parses a PEM string with with DH parameters into a DHParameters.
     """
     rv = pem.parse(DH_PEM)
     dh, = rv
     assert isinstance(dh, pem.DHParameters)
     assert DH_PEM == dh.as_bytes()
Exemplo n.º 40
0
 def test_dh(self):
     """
     Parses a PEM string with with DH parameters into a DHParameters.
     """
     rv = pem.parse(DH_PEM)
     dh, = rv
     assert isinstance(dh, pem.DHParameters)
     assert DH_PEM == str(dh)
Exemplo n.º 41
0
 def test_certificates(self):
     """
     Parses a PEM string with multiple certificates into a list of
     corresponding Certificates.
     """
     certs = pem.parse(''.join(CERT_PEMS))
     assert all(isinstance(c, pem.Certificate) for c in certs)
     assert CERT_PEMS == [str(cert) for cert in certs]
Exemplo n.º 42
0
 def test_key(self):
     """
     Parses a PEM string with a key into an RSAPrivateKey.
     """
     rv = pem.parse(KEY_PEM)
     key, = rv
     assert isinstance(key, pem.RSAPrivateKey)
     assert KEY_PEM == str(key)
Exemplo n.º 43
0
    def test_rsa_public_key(self):
        """
        Detects and loads RSA public keys.
        """
        key = pem.parse(KEY_PEM_RSA_PUBLIC)[0]

        assert isinstance(key, pem.PublicKey)
        assert isinstance(key, pem.RSAPublicKey)
Exemplo n.º 44
0
    def test_rsa_public_key(self):
        """
        Detects and loads RSA public keys.
        """
        key = pem.parse(KEY_PEM_RSA_PUBLIC)[0]

        assert isinstance(key, pem.PublicKey)
        assert isinstance(key, pem.RSAPublicKey)
Exemplo n.º 45
0
    def test_crl(self):
        """
        Parses a PEM string with multiple certificate revocation lists into a
        list of corresponding CertificateRevocationLists
        """
        crls = pem.parse(b"".join(CRL_PEMS))

        assert all(isinstance(c, pem.CertificateRevocationList) for c in crls)
        assert CRL_PEMS == [crl.as_bytes() for crl in crls]
Exemplo n.º 46
0
 def _get(self, server_name):
     """
     Synchronously retrieve an entry.
     """
     p = self.path.child(server_name + u'.pem')
     if p.isfile():
         return parse(p.getContent())
     else:
         raise KeyError(server_name)
Exemplo n.º 47
0
 def get_ordered_certificate(self, pending_cert):
     """ Retrieve a certificate via order id """
     order_id = pending_cert.external_id
     base_url = current_app.config.get('DIGICERT_URL')
     try:
         certificate_id = get_certificate_id(self.session, base_url, order_id)
     except Exception as ex:
         return None
     certificate_url = "{0}/services/v2/certificate/{1}/download/format/pem_all".format(base_url, certificate_id)
     end_entity, intermediate, root = pem.parse(self.session.get(certificate_url).content)
     cert = {'body': "\n".join(str(end_entity).splitlines()),
             'chain': "\n".join(str(intermediate).splitlines()),
             'external_id': str(certificate_id)}
     return cert
Exemplo n.º 48
0
    def test_key_pkcs8_encrypted(self):
        """
        It can load an encrypted PKCS#8 RSA key as PEM string
        as an Key.
        """
        rv = pem.parse(KEY_PEM_PKCS8_ENCRYPTED)
        key, = rv

        assert isinstance(key, pem.Key)
        assert KEY_PEM_PKCS8_ENCRYPTED == key.as_bytes()

        crypto_key = load_rsa_key(key, password=b"test")

        assert isinstance(crypto_key, RSAPrivateKey)
        assert 512, crypto_key.key_size()
Exemplo n.º 49
0
    def test_key_pkcs5_unencrypted(self):
        """
        It can load an unencrypted PKCS#5 RSA key as PEM string
        as an RSAPrivateKey.
        """
        rv = pem.parse(KEY_PEM_PKCS5_UNENCRYPTED)
        key, = rv

        assert isinstance(key, pem.RSAPrivateKey)
        assert KEY_PEM_PKCS5_UNENCRYPTED == key.as_bytes()

        crypto_key = load_rsa_key(key)

        assert isinstance(crypto_key, RSAPrivateKey)
        assert 512, crypto_key.key_size()
Exemplo n.º 50
0
    def create_certificate(self, csr, issuer_options):
        """Create a DigiCert certificate."""
        base_url = current_app.config.get('DIGICERT_CIS_URL')

        # make certificate request
        create_url = '{0}/platform/cis/certificate'.format(base_url)

        data = map_cis_fields(issuer_options, csr)
        response = self.session.post(create_url, data=json.dumps(data))
        data = handle_cis_response(response)

        # retrieve certificate
        certificate_pem = get_cis_certificate(self.session, base_url, data['id'])

        self.session.headers.pop('Accept')
        end_entity = pem.parse(certificate_pem)[0]
        return "\n".join(str(end_entity).splitlines()), current_app.config.get('DIGICERT_CIS_INTERMEDIATE')
Exemplo n.º 51
0
def main():
    payload = os.environ["ACME_PAYLOAD"]
    domain = os.environ["ACME_DOMAIN"]
    h = json.loads(payload)

    chain = pem.parse(h["fullchain"])
    assert len(chain) > 1, "Chain has invalid length: {0}".format(len(chain))

    cert = crypto.load_certificate(crypto.FILETYPE_PEM, chain[0].as_bytes())
    cn = cert.get_subject().CN
    assert cn == domain, "Cert has invalid CN: {0}".format(cn)

    key = crypto.load_privatekey(crypto.FILETYPE_PEM, h["key"])

    # Verify key:
    # http://docs.ganeti.org/ganeti/2.14/html/design-x509-ca.html
    ctx = SSL.Context(SSL.TLSv1_METHOD)
    ctx.use_certificate(cert)
    ctx.use_privatekey(key)
    ctx.check_privatekey()
def test_generate_wildcard_pem_bytes():
    """
    When we generate a self-signed wildcard certificate's PEM data, that data
    should be deserializable and the deserilized certificate should have the
    expected parameters.
    """
    pem_bytes = generate_wildcard_pem_bytes()

    # Parse the concatenated bytes into a list of object
    pem_objects = pem.parse(pem_bytes)

    assert_that(pem_objects, HasLength(2))

    # Deserialize the private key and assert that it is the right type (the
    # other details we trust txacme with)
    key = serialization.load_pem_private_key(
        pem_objects[0].as_bytes(),
        password=None,
        backend=default_backend()
    )
    assert_that(key, IsInstance(rsa.RSAPrivateKey))

    # Deserialize the certificate and validate all the options we set
    cert = x509.load_pem_x509_certificate(
        pem_objects[1].as_bytes(), backend=default_backend()
    )
    expected_before = datetime.today() - timedelta(days=1)
    expected_after = datetime.now() + timedelta(days=3650)
    assert_that(cert, MatchesStructure(
        issuer=MatchesListwise([
            MatchesStructure(value=Equals(u'*'))
        ]),
        subject=MatchesListwise([
            MatchesStructure(value=Equals(u'*'))
        ]),
        not_valid_before=matches_time_or_just_before(expected_before),
        not_valid_after=matches_time_or_just_before(expected_after),
        signature_hash_algorithm=IsInstance(hashes.SHA256)
    ))
    assert_that(cert.public_key().public_numbers(), Equals(
                key.public_key().public_numbers()))
Exemplo n.º 53
0
 def test_certificates(self):
     certs = pem.parse(''.join(CERT_PEMS))
     assert CERT_PEMS == [str(cert) for cert in certs]
Exemplo n.º 54
0
 def test_key(self):
     keys = pem.parse(KEY_PEM)
     assert 1 == len(keys)
     key = keys[0]
     assert isinstance(key, pem.RSAPrivateKey)
     assert KEY_PEM == str(key)
Exemplo n.º 55
0
import pem

# the actual html/css/js... files being served are all located here
DOCUMENTS = FilePath(__file__).parent().child("public")
ERROR_RESOURCE = DOCUMENTS.child("error").child("index.html")

INSECURE_PORT = os.environ.get("INSECURE_PORT")
SECURE_PORT = os.environ.get("SECURE_PORT")

# all certificates are passed in as environment variables
PRIVATE_KEY = os.environ.get("PRIVATE_KEY")
CERTIFICATE_CHAIN = os.environ.get("CERTIFICATE_CHAIN")
DH_PARAMETER = os.environ.get("DH_PARAMETER")

ctxFactory = pem.certificateOptionsFromPEMs(
    pem.parse(PRIVATE_KEY),
    pem.parse(CERTIFICATE_CHAIN),
    dhParameters=pem.DiffieHellmanParameters(DH_PARAMETER)
)


class RedirectResource(Resource):
    isLeaf = True

    def render(self, request):
        host = request.requestHeaders.getRawHeaders('host')[0].split(':', 1)[0]
        port = ''
        if SECURE_PORT is not None:
            port = ':{0}'.format(SECURE_PORT)
        return redirectTo(
            'https://{0}{1}{2}'.format(host, port, request.uri),