Exemplo n.º 1
0
 def verify_cert(self, cert_pem):
     certificate = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem)
     # Create a X590StoreContext with the cert and trusted certs
     # and verify the the chain of trust
     store_ctx = crypto.X509StoreContext(self.store, certificate)
     # Returns None if certificate can be validated
     try:
         result = store_ctx.verify_certificate()
     except:
         result = False
     return result is None
Exemplo n.º 2
0
def verify(CA, cert):
    """This functions checks two certificates,
       which are OpenSSL.crypto.X509 variables
    """
    store = crypto.X509Store()
    store.add_cert(CA)
    store_context = crypto.X509StoreContext(store, cert)
    if store_context.verify_certificate() is None:
        return True
    else:
        return False
Exemplo n.º 3
0
    def verify_cert_trust(self, pychain, pycerts):
        store = self.init_cert_store(pychain)

        for pycert in pycerts:
            store_ctx = crypto.X509StoreContext(store, pycert)
            try:
                store_ctx.verify_certificate()
            except crypto.X509StoreContextError:
                return False

        return True
Exemplo n.º 4
0
 def check_certif_signature(self, cert, index):
     """ Certificate signature check. """
     # 15. Validate signature using local issuer
     # Note : use openssl StoreContext object which should do this plus a
     # bunch of other checks.
     try:
         store_ctx = crypto.X509StoreContext(self.cert_store, cert)
         store_ctx.verify_certificate()
     except crypto.X509StoreContextError as e:
         raise CheckException(
             "Certificate signature check failure : {}".format(str(e)))
Exemplo n.º 5
0
    def validate(self):
        # Create a X590StoreContext with the cert and trusted certs
        # and verify the the chain of trust
        store_ctx = crypto.X509StoreContext(self._trusted_pem_store, self._pem)
        # Returns None if certificate can be validated
        result = store_ctx.verify_certificate()

        if result is None:
            return True
        else:
            return False
Exemplo n.º 6
0
def verify_chain_of_trust(cert,rootcert):
    certificado = crypto.load_certificate(crypto.FILETYPE_PEM,cert)
    ca_certificado = crypto.load_certificate(crypto.FILETYPE_ASN1,rootcert)
    st = crypto.X509Store()
    st.add_cert(certificado)
    st.add_cert(ca_certificado)
    st_ct = crypto.X509StoreContext(st,certificado)
    out = st_ct.verify_certificate()
    if out is None:
        return True
    else:
        return False
Exemplo n.º 7
0
def check_if_trusted(cert_data: bytes) -> bool:
    try:
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_data)
    except crypto.Error:
        raise InvalidCredentials(
            'problem loading certificate - certificate is invalid')
    store_ctx = crypto.X509StoreContext(DevRootCertificateStore().store, cert)
    try:
        store_ctx.verify_certificate()
        return True
    except crypto.Error:
        return False
Exemplo n.º 8
0
def is_selfsigned(cert):
    '''
  cert: X509 object
  '''
    if cert.get_subject().CN == cert.get_issuer().CN:
        store = crypto.X509Store()
        store.add_cert(cert)

        store_ctx = crypto.X509StoreContext(store, cert)
        if store_ctx.verify_certificate() is None:
            return True
    return False
Exemplo n.º 9
0
    def _verify_certificate(self, vcert):
        """Confirm this certificate is in a chain of trust

        We have a CA, and we want to know we're seeing a certificate
        that this CA has signed.
        """
        certificate = crypto.load_certificate(crypto.FILETYPE_PEM, vcert)

        store_ctx = crypto.X509StoreContext(self.store, certificate)
        result = store_ctx.verify_certificate()
        if result is not None:
            raise JWTSigningFailed(_("Certificate is not trusted"))
Exemplo n.º 10
0
 def _verify_certificate_chain(cls, cert):
     """Verify certificate using chain of trust shipped with sdk
     """
     from OpenSSL import crypto
     store = cls._get_certificate_store()
     try:
         store_ctx = crypto.X509StoreContext(store, cert)
         store_ctx.verify_certificate()
         return True
     except Exception as e:
         print(e)
         return False
Exemplo n.º 11
0
    def _certificate_chain_verify(self, cert, ca_cert):
        """ verify certificate chain """
        self.logger.debug('CAhandler._certificate_chain_verify()')

        error = None
        pem_file = build_pem_file(self.logger, None,
                                  b64_url_recode(self.logger, cert), True)

        try:
            cert = crypto.load_certificate(crypto.FILETYPE_PEM, pem_file)
        except Exception as err_:
            cert = None
            error = err_

        if not error:
            # Create a certificate store and add ca cert(s)
            try:
                store = crypto.X509Store()
                store.add_cert(ca_cert)
            except Exception:
                error = 'issuing certificate could not be added to trust-store'

            if not error:
                # add ca chain to truststore
                for cert_name in self.ca_cert_chain_list:
                    try:
                        with open(cert_name, 'r') as fso:
                            cain_cert = crypto.load_certificate(
                                crypto.FILETYPE_PEM, fso.read())
                        store.add_cert(cain_cert)
                    except Exception:
                        error = 'certificate {0} could not be added to trust store'.format(
                            cert_name)

            if not error:
                # Create a certificate context using the store and the downloaded certificate
                store_ctx = crypto.X509StoreContext(store, cert)
                # Verify the certificate, returns None if it can validate the certificate
                try:
                    # pylint: disable=E1111
                    result = store_ctx.verify_certificate()
                except Exception as err_:
                    result = str(err_)
            else:
                result = error
        else:
            result = 'certificate could not get parsed'

        self.logger.debug(
            'CAhandler._certificate_chain_verify() ended with {0}'.format(
                result))
        return result
Exemplo n.º 12
0
    def test_cert_validate_valid(self):
        """ Test cert chain validation """
        client_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                              VALID_CLIENT_CERT)
        ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, CA_CERT)

        store = crypto.X509Store()
        store.add_cert(ca_cert)

        ctx = crypto.X509StoreContext(store, client_cert)
        result = ctx.verify_certificate()
        # None means valid
        self.assertIsNone(result)
def verifyChain(store, cert):
    #print "verify chain"
    #print cert.get_subject().__getattr__('CN')
    ctx = crypto.X509StoreContext(store, cert)
    try:
        # returns None if the certificate was validated, error otherwise
        result = ctx.verify_certificate()
        #print result == None
        return result
    except crypto.X509StoreContextError as e:
        print "certificado: %s; mensagem: %s" % (
            e.certificate.get_subject().__getattr__('CN'), e.message)
        return e.message
Exemplo n.º 14
0
def verify_cert(cert):
    try:
        store = crypto.X509Store()
        store.add_cert(CA_cert)

        store_ctx = crypto.X509StoreContext(store, cert)

        store_ctx.verify_certificate()

        return True
    except Exception as e:
        print(e)
        return False
Exemplo n.º 15
0
    def test_cert_validate_expired(self):
        """ Test cert chain validation with expired certificate"""
        client_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                              EXPIRED_CLIENT_CERT)
        ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, CA_CERT)

        store = crypto.X509Store()
        store.add_cert(ca_cert)

        ctx = crypto.X509StoreContext(store, client_cert)
        with self.assertRaises(crypto.X509StoreContextError) as exc:
            ctx.verify_certificate()
        self.assertIn('certificate has expired', str(exc.exception))
Exemplo n.º 16
0
def _is_trusted_attestation_cert(trust_path, trust_anchors):
    store = crypto.X509Store()
    for _ta in trust_anchors:
        store.add_cert(_ta)
    store_ctx = crypto.X509StoreContext(store, trust_path)

    try:
        store_ctx.verify_certificate()
        return True
    except Exception as e:
        print('Unable to verify certificate: {}.'.format(e))

    return False
def verify_chain_of_trust(cert, trusted_certs):
    certificado = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
    st = crypto.X509Store()
    for trusted_cert in trusted_certs:
        trust_certificado = crypto.load_certificate(crypto.FILETYPE_PEM,
                                                    trusted_cert)
        st.add_cert(trust_certificado)
    st.add_cert(certificado)
    st_ct = crypto.X509StoreContext(st, certificado)
    out = st_ct.verify_certificate()
    if out is None:
        return True
    else:
        return False
Exemplo n.º 18
0
    def verify(self, x509_cert):
        """
        Verifies that the x509.Certificate was signed with by this Signer and its parents.
        Override this if your Signer has a way to verify certificates without iterating
        through the authority chain here.  E.g. if your Signer has an HTTP API for verifying.

        Args:
            x509_cert (cryptography.x509.Certificate): Certificate to verify

        Returns:
            bool: True, or raises a CertificateVerificationError

        Raises:
            CertificateVerificationError: if this Signer fails to verify the x509_cert
        """

        # The cryptography library doesn't have a good way to verify certificates, so
        # we convert the x509.Certificates into pyopenssl crypto x509 certificates and use
        # the pyopenssl library instead.
        store = crypto.X509Store()

        # Add the cert to verify to the store.
        store.add_cert(from_cryptography(x509_cert))

        # Add any authority certs in the chain to the store, without
        # double adding the x509_cert (in the case where this is a self signed cert)
        for authority in [a for a in self.chain() if a.cert != x509_cert]:
            store.add_cert(from_cryptography(authority.cert))

        # Create a new store context with the above store,
        # finally using the root authority to verify the chain of certs in the store.
        store_ctx = crypto.X509StoreContext(store,
                                            from_cryptography(self.root.cert))

        # If store_ctx.verify_certificate() raises a X509StoreContextError,
        # then the certificate did not verify against its authority chain.
        # Otherwise, it did!
        try:
            store_ctx.verify_certificate()
        except crypto.X509StoreContextError as e:
            # Re-raise the error with more information.
            raise CertificateVerificationError(
                'Verification of certificate with common name \'{}\' with chain {} '
                # X509StoreContextError.certificate is a pyopenssl crypto X509 object.
                'failed.'.format(e.certificate.get_subject().commonName,
                                 self.chain_names()),
                self,
                x509_cert) from e

        return True
Exemplo n.º 19
0
def verify_certificate_chain(ca_pem_data, cert_pem_data):
    try:
        ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, ca_pem_data)
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem_data)

        store = crypto.X509Store()
        store.add_cert(ca_cert)

        store_ctx = crypto.X509StoreContext(store, cert)
        store_ctx.verify_certificate()
    except crypto.Error as e:
        raise InvalidCertificate('Broken certificate') from e
    except crypto.X509StoreContextError as e:
        raise InvalidCertificate('Invalid certificate chain: ' + str(e)) from e
Exemplo n.º 20
0
 def _verify_ca(self):
     """
     (internal use only)
     verifies the current x509 is signed
     by the associated CA
     """
     store = crypto.X509Store()
     store.add_cert(self.ca.x509)
     store_ctx = crypto.X509StoreContext(store, self.x509)
     try:
         store_ctx.verify_certificate()
     except crypto.X509StoreContextError as e:
         raise ValidationError(_("CA doesn't match, got the "
                                 "following error from pyOpenSSL: \"%s\"") % e.args[0][2])
Exemplo n.º 21
0
def verify_chain_of_trust(cert, rootcert):
    certificado = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
    ca_certificado = crypto.load_certificate(crypto.FILETYPE_ASN1, rootcert)
    st = crypto.X509Store()
    #concatenação do cliente.pem + ca.pem
    st.add_cert(certificado)
    st.add_cert(ca_certificado)
    st_ctx = crypto.X509StoreContext(st, certificado)
    result = st_ctx.verify_certificate()

    if result is None:
        return True
    else:
        return False
Exemplo n.º 22
0
    def validate(self, cert):
        parsed = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
        self.refresh_cache(parsed)
        context = crypto.X509StoreContext(self.store, parsed)
        try:
            context.verify_certificate()
            return True

        except crypto.X509StoreContextError as err:
            self.errors.append(
                "Certificate revoked or errored. Error: {}. Args: {}".format(
                    type(err), err.args
                )
            )
            return False
def check_certificate_data(certificate):
    try:
        certificate = crypto.load_certificate(crypto.FILETYPE_PEM, certificate)
        store = crypto.X509Store()

        trusted_certs = get_trusted_certs()

        for cert in trusted_certs:
            store.add_cert(cert)

        store_ctx = crypto.X509StoreContext(store, certificate)
        store_ctx.verify_certificate()
        return True
    except Exception:
        return False
Exemplo n.º 24
0
def verify(ca_cert_pem, crl_pem, cert_pem):
    store = crypto.X509Store()
    store.add_cert(crypto.load_certificate(crypto.FILETYPE_PEM, ca_cert_pem))
    cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem)
    ctx = crypto.X509StoreContext(store, cert)
    ctx.verify_certificate()

    # Until `X509StoreContext` accepts CRLs
    crl = crypto.load_crl(crypto.FILETYPE_PEM, crl_pem)
    revoked = crl.get_revoked() or []
    for r in revoked:
        r_serial = r.get_serial()
        c_serial = "%X" % (cert.get_serial_number(), )
        if r_serial == c_serial:
            raise Exception("Certificate revoked")
Exemplo n.º 25
0
def verify_certificate_chain(certificates):
    """
    Verifys the the specified certificate chain.

    Args:
        certificates (list of cryptography X.509 certificates) : Certificate chain to verify.
    """
    try:
        store = crypto.X509Store()
        for certificate in certificates[1:]: store.add_cert(crypto.X509.from_cryptography(certificate))
        store_ctx = crypto.X509StoreContext(store, crypto.X509.from_cryptography(certificates[0]))
        store_ctx.verify_certificate()
    except Exception as e:
        log_debug("Verifying certificate chain failed: {0}".format(e))
        raise CertificateChainError("Verifying certificate chain failed.")
Exemplo n.º 26
0
    def validate_cert_with_chain(self, cert, chain):
        check_cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
        store = crypto.X509Store()
        for chain_cert in itertools.chain.from_iterable(
                map(lambda c: RE_CERTIFICATE.findall(c), chain)):
            store.add_cert(
                crypto.load_certificate(crypto.FILETYPE_PEM, chain_cert))

        store_ctx = crypto.X509StoreContext(store, check_cert)
        try:
            store_ctx.verify_certificate()
        except crypto.X509StoreContextError:
            return False
        else:
            return True
Exemplo n.º 27
0
 def verify_certificate_chain(self, certificate_str):
     """
     Verifies a certificate using the trusted certificates contained in
     trusted_cert_store
     """
     if not certificate_str:
         return False
     certificate = crypto.load_certificate(crypto.FILETYPE_PEM, certificate_str)
     try:
         store_context = crypto.X509StoreContext(trusted_cert_store, certificate)
         store_context.verify_certificate() # returns None if valid
         return True
     except Exception as e:
         print(e)
         return False
Exemplo n.º 28
0
def certVerify(flag):

    if (flag == 0):
        cert = serverCert()
    else:
        cert = clientCert()

    # Criação dum X509StoreContext entre a nossa store o certificado a verificar.
    store_ctx = crypto.X509StoreContext(store, cert)

    # Verificação do chain of trust.
    try:
        store_ctx.verify_certificate()
        return True
    except Exception:
        return False
Exemplo n.º 29
0
 def verify_node(self, node):
     # assuming self.a.ca_cert is the crypto.load_certificate
     # node_cert is the string content
     store = crypto.X509Store()
     node_certificate = crypto.load_certificate(crypto.FILETYPE_PEM,
                                                node.cert)
     store.add_cert(node_certificate)
     store_context = crypto.X509StoreContext(store, self.a.ca_cert)
     try:
         store_context.verify_certificate()
     except crypto.X509StoreContextError as ex:
         print("Cannot validate certificate for node {0}".format(node.name))
         # returning True for now
         return True
     print("Certificate for node {} validated".format(node.name))
     return True
Exemplo n.º 30
0
def validate_cert_chain(cert_chain):
    store = crypto.X509Store()
    n = len(cert_chain)
    for i in range(1, n):
        store.add_cert(cert_chain[i])
    root_hash = cert_chain[-1].get_issuer().hash()
    if root_hash not in certs_map:
        return False
    store.add_cert(certs_map[root_hash])
    store_ctx = crypto.X509StoreContext(store, cert_chain[0])
    try:
        store_ctx.verify_certificate()
    except Exception:
        return False
    else:
        return True