Beispiel #1
0
    def checkCertificates(self, certs):
        certs = json.loads(certs)
        depth = len(certs.keys())

        leaf = crypto.load_certificate(crypto.FILETYPE_PEM,
                                       certs[str(depth - 1)])

        intermediates = []
        for i in range(1, depth - 1):
            intermediates.append(
                crypto.load_certificate(crypto.FILETYPE_PEM, certs[str(i)]))

        bad_store = crypto.X509Store()
        # add the AC root
        f = open('AC.pem')
        acCert = f.read()
        f.close()

        bad_store.add_cert(crypto.load_certificate(crypto.FILETYPE_PEM,
                                                   acCert))
        for intermediate in intermediates:
            bad_store.add_cert(intermediate)
        bad_store_ctx = crypto.X509StoreContext(bad_store, leaf)

        try:
            bad_store_ctx.verify_certificate()
            print("== CHAIN IS VALID ==")
        except Exception as e:
            print("== CHAIN FAILED VALIDATION ==")
            return False

        return True
Beispiel #2
0
def verify_certificate_chain(cert_str, trusted_certs, ignore_self_signed=True):
    """ Verify a given certificate against a trust store"""

    # Load the certificate
    certificate = crypto.load_certificate(crypto.FILETYPE_ASN1, cert_str)

    # Create a certificate store and add your trusted certs
    try:
        store = crypto.X509Store()

        if ignore_self_signed:
            store.add_cert(certificate)

        # Assuming the certificates are in PEM format in a trusted_certs list
        for _cert in trusted_certs:
            store.add_cert(crypto.load_certificate(crypto.FILETYPE_ASN1,
                                                   _cert))

        # Create a certificate context using the store and the certificate
        store_ctx = crypto.X509StoreContext(store, certificate)

        # Verify the certificate, returns None if certificate is not valid
        store_ctx.verify_certificate()

        return True

    except crypto.X509StoreContextError as e:
        raise AS2Exception('Partner Certificate Invalid: %s' % e.args[-1][-1])
Beispiel #3
0
 def test_new(self):
     cert = self._create_cert()
     self.assertNotEqual(cert.certificate, '')
     self.assertNotEqual(cert.private_key, '')
     x509 = cert.x509
     self.assertEqual(x509.get_serial_number(), cert.serial_number)
     subject = x509.get_subject()
     # check subject
     self.assertEqual(subject.countryName, cert.country_code)
     self.assertEqual(subject.stateOrProvinceName, cert.state)
     self.assertEqual(subject.localityName, cert.city)
     self.assertEqual(subject.organizationName, cert.organization_name)
     self.assertEqual(subject.emailAddress, cert.email)
     self.assertEqual(subject.commonName, cert.common_name)
     # check issuer
     issuer = x509.get_issuer()
     ca = cert.ca
     self.assertEqual(issuer.countryName, ca.country_code)
     self.assertEqual(issuer.stateOrProvinceName, ca.state)
     self.assertEqual(issuer.localityName, ca.city)
     self.assertEqual(issuer.organizationName, ca.organization_name)
     self.assertEqual(issuer.emailAddress, ca.email)
     self.assertEqual(issuer.commonName, ca.common_name)
     # check signature
     store = crypto.X509Store()
     store.add_cert(ca.x509)
     store_ctx = crypto.X509StoreContext(store, cert.x509)
     store_ctx.verify_certificate()
     # ensure version is 3 (indexed 0 based counting)
     self.assertEqual(x509.get_version(), 2)
     # basic constraints
     e = cert.x509.get_extension(0)
     self.assertEqual(e.get_critical(), 0)
     self.assertEqual(e.get_short_name().decode(), 'basicConstraints')
     self.assertEqual(e.get_data(), b'0\x00')
def load_ssl_certs(ssl_cert_path):
    """Opens, validates, and returns a dict containing one or more SSL certificates.
    Self-signed certs will check out fine. Cert chain order will not be checked here.
    Args:
        ssl_cert_path (str): Possibly empty path to SSL certificate
    Returns:
        (SslCertFileResult, [certificates]): the result of the test and the actual certificate data
    """
    if not ssl_cert_path:
        return SslCertFileResult(False, ssl_cert_path), None
    try:
        with open(ssl_cert_path) as fd:
            cert_input = fd.read()
            if _contains_truncated_certs(cert_input):
                raise Exception(
                    "Certificate at {0} contains a mismatched number of BEGIN and END CERTIFICATE lines. "
                    "Please re-check your certificate to make sure all contained certificates begin with "
                    "'-----BEGIN CERTIFICATE-----' and end with '-----END CERTIFICATE-----'."
                    .format(ssl_cert_path))

            ssl_certs = load_ca_bundle(cert_input)

            cert_store = crypto.X509Store()
            for cert in ssl_certs:
                cert_store.add_cert(cert)

            cert_context = crypto.X509StoreContext(cert_store, ssl_certs[0])
            cert_context.verify_certificate()

            return SslCertFileResult(True, ssl_cert_path), ssl_certs
    except Exception as e:  # can be IOError, crypto.Error, and possibly others
        return SslCertFileResult(False, ssl_cert_path, exception=e), None
def create_cert_store():
    """
    Create the Certificate Store to use for Validation
    """

    trust_chain1 = crypto.load_certificate(crypto.FILETYPE_PEM, TRUST_CHAIN_PEM1)
    trust_chain2 = crypto.load_certificate(crypto.FILETYPE_PEM, TRUST_CHAIN_PEM2)
    trust_chain3 = crypto.load_certificate(crypto.FILETYPE_PEM, TRUST_CHAIN_PEM3)
    trust_chain4 = crypto.load_certificate(crypto.FILETYPE_PEM, TRUST_CHAIN_PEM4)
    trust_chain5 = crypto.load_certificate(crypto.FILETYPE_PEM, TRUST_CHAIN_PEM5)
    trust_chain6 = crypto.load_certificate(crypto.FILETYPE_PEM, TRUST_CHAIN_PEM6)
    trust_chain7 = crypto.load_certificate(crypto.FILETYPE_PEM, TRUST_CHAIN_PEM7)
    trust_chain8 = crypto.load_certificate(crypto.FILETYPE_PEM, TRUST_CHAIN_PEM8)
    trust_chain9 = crypto.load_certificate(crypto.FILETYPE_PEM, TRUST_CHAIN_PEM9)
    trust_chain10 = crypto.load_certificate(crypto.FILETYPE_PEM, TRUST_CHAIN_PEM10)
    trust_chain11 = crypto.load_certificate(crypto.FILETYPE_PEM, TRUST_CHAIN_PEM11)
    trust_chain12 = crypto.load_certificate(crypto.FILETYPE_PEM, TRUST_CHAIN_PEM12)
    store = crypto.X509Store()
    store.add_cert(trust_chain1)
    store.add_cert(trust_chain2)
    store.add_cert(trust_chain3)
    store.add_cert(trust_chain4)
    store.add_cert(trust_chain5)
    store.add_cert(trust_chain6)
    store.add_cert(trust_chain7)
    store.add_cert(trust_chain8)
    store.add_cert(trust_chain9)
    store.add_cert(trust_chain10)
    store.add_cert(trust_chain11)
    store.add_cert(trust_chain12)
    return store
Beispiel #6
0
    def verify_certificate(self, cert_pem):
        '''
        Verifies whether a provided Portuguese Citizenship Card Certificate is valid
        :param cert_pem: The to-be validated certificate
        :return: True or False
        '''
        certificate = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem)

        # Create and fill a X509Sore with trusted certs
        store = crypto.X509Store()
        path = "./certs_dev/"
        for c in os.listdir(path):
            pem = open(path + c, 'r').read()
            store.add_cert(crypto.load_certificate(crypto.FILETYPE_PEM, pem))

        # Now we add the crls to the X509 store
        #crl = crypto.load_crl(crypto.FILETYPE_PEM, CRL_CERTS)
        #store.add_crl(crl)
        context = crypto.X509StoreContext(store, certificate)
        context.set_store(store)
        # Create a X590StoreContext with the cert and trusted certs
        # and verify the the chain of trust
        # verify_certificate() returns None if certificate can be validated
        valid = False
        try:
            valid = context.verify_certificate()
        except crypto.X509StoreContextError as e:
            print e.message
            print e.certificate.get_subject()
        else:
            valid = True
        return valid
Beispiel #7
0
def verify(cert, trusted_certs):
    store = crypto.X509Store()

    # Obtenemos los certificados del fichero a analizar
    # El primero asumimos que es el que queremos analizar
    # El resto se pasan como autoridades certificadoras
    certificates = read_cert(cert)
    certificate = certificates.pop(0)
    for c in certificates:
        print(
            "Pasando un certificado del fichero a analizar como autoridad certificadora"
        )
        store.add_cert(c)

    # Puede que un trusted_certs este compuesto por varios certs
    for tc in trusted_certs:
        for c in read_cert(tc):
            store.add_cert(c)

    # Create a X590StoreContext with the cert and trusted certs
    # and verify the the chain of trust
    store_ctx = crypto.X509StoreContext(store, certificate)
    # Returns None if certificate can be validated
    try:
        result = store_ctx.verify_certificate()
    except crypto.X509StoreContextError:
        return False

    return True
Beispiel #8
0
 def validate(self, certificate0, certificate1, certificate2):
     #cert = x509.load_pem_x509_certificate(str.encode(certificate[0]), default_backend())
     self.certificate = []
     self.certificate.append(certificate0)
     self.certificate.append(certificate1)
     self.certificate.append(certificate2)
     cert1 = crypto.load_certificate(crypto.FILETYPE_PEM, certificate0)
     clientIssuer = str(cert1.get_issuer())
     IntermediateIssuer = "<X509Name object '/C=US/ST=MD/L=Baltimore/O=JHUNetworkSecurityFall2017/OU=PETF/CN=20174.1.666/[email protected]'>"
     if clientIssuer == IntermediateIssuer:
         print("Issuer verified.")
         try:
             cert_store = crypto.X509Store()
             certpub = crypto.load_certificate(crypto.FILETYPE_PEM,
                                               certificate1)
             certroot = crypto.load_certificate(crypto.FILETYPE_PEM,
                                                certificate2)
             cert_store.add_cert(certpub)
             cert_store.add_cert(certroot)
             print("Client certificates added to the trust store.")
             store_ctx = crypto.X509StoreContext(cert_store, cert1)
             store_ctx.verify_certificate()
             return True
         except Exception as e:
             print(e)
             return True
def verify_certificate_chain(cert_path, trusted_certs):
    # Download the certificate from the url and load the certificate
    certificate = _load_certificate(cert_path)

    logging.debug(trusted_certs)
    # Create a certificate store and add your trusted certs
    try:
        store = crypto.X509Store()

        # Assuming the certificates are in PEM format in a trusted_certs list
        for _cert in trusted_certs:
            logging.debug(_cert)
            client_certificate = _load_certificate(_cert)
            store.add_cert(client_certificate)

        # Create a certificate context using the store and the downloaded certificate
        store_ctx = crypto.X509StoreContext(store, certificate)

        # Verify the certificate, returns None if it can validate the certificate
        logging.debug(store_ctx.verify_certificate())

        return True

    except Exception as e:
        print(e)
        return False
Beispiel #10
0
    def registerOrdererAdminTuple(self, userName, ordererName,
                                  organizationName):
        ' Assign the user as orderer admin'
        ordererAdminTuple = NodeAdminTuple(user=userName,
                                           nodeName=ordererName,
                                           organization=organizationName)
        assert ordererAdminTuple not in self.ordererAdminTuples, "Orderer admin tuple already registered {0}".format(
            ordererAdminTuple)
        assert organizationName in self.organizations, "Orderer Organization not defined {0}".format(
            organizationName)

        user = self.getUser(userName, shouldCreate=True)
        certReq = user.createCertRequest(ordererAdminTuple.nodeName)
        userCert = self.getOrganization(organizationName).createCertificate(
            certReq)

        # Verify the newly created certificate
        store = crypto.X509Store()
        # Assuming a list of trusted certs
        for trustedCert in [self.getOrganization(organizationName).signedCert]:
            store.add_cert(trustedCert)
        # Create a certificate context using the store and the certificate to verify
        store_ctx = crypto.X509StoreContext(store, userCert)
        # Verify the certificate, returns None if it can validate the certificate
        store_ctx.verify_certificate()

        print(
            "new Certificate for '{0}' on orderer '{1}' signed by '{2}': \n{3}"
            .format(userName, ordererName, organizationName,
                    crypto.dump_certificate(crypto.FILETYPE_PEM, userCert)))
        self.ordererAdminTuples[ordererAdminTuple] = userCert
    def basic_assertions(self, cdir, cert, key, cacert=None):
        '''
        test basic certificate assumptions

        Args:
            cdir (s_certdir.CertDir): certdir object
            cert (crypto.X509): Cert to test
            key (crypto.PKey): Key for the certification
            cacert (crypto.X509): Corresponding CA cert (optional)
        '''
        self.nn(cert)
        self.nn(key)

        # Make sure the certs were generated with the expected number of bits
        self.eq(cert.get_pubkey().bits(), cdir.crypto_numbits)
        self.eq(key.bits(), cdir.crypto_numbits)

        # Make sure the certs were generated with the correct version number
        self.eq(cert.get_version(), 2)

        # ensure we can sign / verify data with our keypair
        buf = b'The quick brown fox jumps over the lazy dog.'
        sig = crypto.sign(key, buf, 'sha256')
        sig2 = crypto.sign(key, buf + b'wut', 'sha256')
        self.none(crypto.verify(cert, sig, buf, 'sha256'))
        self.raises(crypto.Error, crypto.verify, cert, sig2, buf, 'sha256')

        # ensure that a ssl context using both cert/key match
        sslcontext = SSL.Context(SSL.TLSv1_2_METHOD)
        sslcontext.use_certificate(cert)
        sslcontext.use_privatekey(key)
        self.none(sslcontext.check_privatekey())

        if cacert:

            # Make sure the cert was signed by the CA
            self.eq(cert.get_issuer().der(), cacert.get_subject().der())

            store = crypto.X509Store()
            ctx = crypto.X509StoreContext(store, cert)

            # OpenSSL should NOT be able to verify the certificate if its CA is not loaded
            store.add_cert(cert)
            self.raises(crypto.X509StoreContextError, ctx.verify_certificate
                        )  # unable to get local issuer certificate

            # Generate a separate CA that did not sign the certificate
            try:
                cdir.genCaCert('otherca')
            except s_exc.DupFileName:
                pass

            # OpenSSL should NOT be able to verify the certificate if its CA is not loaded
            store.add_cert(cdir.getCaCert('otherca'))
            self.raises(crypto.X509StoreContextError, ctx.verify_certificate
                        )  # unable to get local issuer certificate

            # OpenSSL should be able to verify the certificate, once its CA is loaded
            store.add_cert(cacert)
            self.none(ctx.verify_certificate())  # valid
Beispiel #12
0
def make_trust_store(trusted_cert_paths):
    cert_store = crypto.X509Store()
    for trusted_cert_path in trusted_cert_paths:
        trusted_cert = open(trusted_cert_path, 'rt').read()
        cert_store.add_cert(
            crypto.load_certificate(crypto.FILETYPE_PEM, trusted_cert))
    return cert_store
def verify_certificate_chain(cert_path, trusted_certs):
    # Download the certificate from the url and load the certificate
    cert_file = open(cert_path, 'r')
    cert_data = cert_file.read()
    certificate = crypto.load_certificate(crypto.FILETYPE_PEM, cert_data)

    #Create a certificate store and add your trusted certs
    try:
        store = crypto.X509Store()

        # Assuming the certificates are in PEM format in a trusted_certs list
        for _cert in trusted_certs:
            cert_file = open(_cert, 'r')
            cert_data = cert_file.read()
            client_certificate = crypto.load_certificate(crypto.FILETYPE_PEM, cert_data)
            store.add_cert(client_certificate)

        # Create a certificate context using the store and the downloaded certificate
        store_ctx = crypto.X509StoreContext(store, certificate)

        # Verify the certificate, returns None if it can validate the certificate
        store_ctx.verify_certificate()

        return True

    except Exception as e:
        print(e)
        #return False
        raise e
Beispiel #14
0
    def verify_chain_of_trust(self, cert_pem, trusted_cert_pems):
        try:
            print(cert_pem)
            #cert = x509.load_pem_x509_certificate(cert_pem, default_backend())
            #print(cert)
            #base64.b64decode(cert_pem)
            certificate = crypto.load_certificate(crypto.FILETYPE_PEM,
                                                  cert_pem)

            # Create and fill a X509Sore with trusted certs
            store = crypto.X509Store()
            for trusted_cert_pem in trusted_cert_pems:
                trusted_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                                       trusted_cert_pem)
                store.add_cert(trusted_cert)

            # Create a X590StoreContext with the cert and trusted certs
            # and verify the the chain of trust
            store_ctx = crypto.X509StoreContext(store, certificate)
            # Returns None if certificate can be validated

            result = store_ctx.verify_certificate()

            if result is None:
                return True
            else:
                return False
        except:
            return False
Beispiel #15
0
    def ca_store(cls):

        crt_paths = os.environ.get('CRT_PATH', '/etc/ssl')
        crt_flush = os.environ.get('CRT_FLUSH')

        if hasattr(cls, 'store') and not crt_flush:
            return cls.store

        else:
            cls.store = crypto.X509Store()
            suffix = r'(.+)\.(crt|pem)$'

            for crt_path in crt_paths.split(':'):
                for root, ds, fs in os.walk(crt_path):
                    for p in filter(lambda f: re.match(suffix, f), fs):
                        for cert in pem.parse_file(os.path.join(root, p)):

                            try:
                                cls.store.add_cert(
                                    crypto.load_certificate(
                                        crypto.FILETYPE_PEM, cert.as_bytes()))

                            except crypto.Error:
                                pass

            return cls.store
Beispiel #16
0
    def __verify_chain_of_trust(self, is_mfr):
        """Verify the CVC chain.

        :is_mfr:
        :return: True or False.

        """
        # Create and fill a X509Sore with trusted certs
        store = c.X509Store()

        if is_mfr == True:
            cert = self.mfr_cvc
            cert_ca = self.mfr_cvc_ca
        else:
            cert = self.mso_cvc
            cert_ca = self.mso_cvc_ca

        store.add_cert(cert_ca)
        store.add_cert(self.root_cert)

        # Create a X590StoreContext with the cert and trusted certs
        # and verify the the chain of trust
        store_ctx = c.X509StoreContext(store, cert)
        # Returns None if certificate can be validated
        result = store_ctx.verify_certificate()

        if result is None:
            return True
        else:
            return False
Beispiel #17
0
def verify_chain_of_trust(certificate):
    #Carregar o ficheiro CA.cer
    cert = crypto.load_certificate(crypto.FILETYPE_ASN1,
                                           open('CA.cer', "rb").read())
    print(certificate)
    #Converter CA.cer em CA.pem
    trusted_cert_pem = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)


    # Create and fill a X509Sore with trusted certs
    store = crypto.X509Store()
    
    trusted_cert = crypto.load_certificate(crypto.FILETYPE_PEM, trusted_cert_pem)
    store.add_cert(trusted_cert)

    # Create a X590StoreContext with the cert and trusted certs
    # and verify the the chain of trust
    store_ctx = crypto.X509StoreContext(store, certificate)
    # Returns None if certificate can be validated
    result = store_ctx.verify_certificate()

    if result is None:
        print("OK")
        return True
    else:
        print("ERRO")
        return False
Beispiel #18
0
def verify_chain_of_trust(certificate):
    #Carregar o ficheiro da CA intermédia
    cert_int = crypto.load_certificate(crypto.FILETYPE_PEM,
                                           open('./root/ca/intermediate/certs/intermediate.cert.pem', "rb").read())
    #Converter CA.cer em CA.pem
    trusted_cert_pem_int = crypto.dump_certificate(crypto.FILETYPE_PEM, cert_int)

    cert_root = crypto.load_certificate(crypto.FILETYPE_PEM,
                                           open('./root/ca/certs/ca.cert.pem', "rb").read())
    #Converter CA.cer em CA.pem
    trusted_cert_pem_root = crypto.dump_certificate(crypto.FILETYPE_PEM, cert_root)

    # Create and fill a X509Sore with trusted certs
    store = crypto.X509Store()
 
    trusted_cert_root = crypto.load_certificate(crypto.FILETYPE_PEM, trusted_cert_pem_root)
    store.add_cert(trusted_cert_root)
    
    trusted_cert_int = crypto.load_certificate(crypto.FILETYPE_PEM, trusted_cert_pem_int)
    store.add_cert(trusted_cert_int)

    # Create a X590StoreContext with the cert and trusted certs
    # and verify the the chain of trust
    store_ctx = crypto.X509StoreContext(store, certificate)
    # Returns None if certificate can be validated
    result = store_ctx.verify_certificate()

    if result is None:
        print("OK")
        return True
    else:
        print("ERRO")
        return False
def generateCertChain(cert):
    #print "generate chain"
    store = crypto.X509Store()
    while True:
        # print "Subject"
        subject = cert.get_subject().__getattr__('CN')
        #print subject
        issuer = cert.get_issuer().__getattr__('CN')
        #print issuer
        new_cert = None
        if issuer == subject:
            break
        elif issuer == 'Baltimore CyberTrust Root':
            new_cert = crypto.load_certificate(
                crypto.FILETYPE_PEM,
                open('/etc/ssl/certs/Baltimore_CyberTrust_Root.pem').read())
        else:
            new_cert = getCertificateFromName(issuer)
        if new_cert != None:
            store.add_cert(new_cert)
        else:
            print "Cannot load cert " + new_cert
        cert = new_cert

    store.set_flags(crypto.X509StoreFlags.CRL_CHECK_ALL)
    store.set_flags(crypto.X509StoreFlags.CHECK_SS_SIGNATURE)
    store.set_flags(crypto.X509StoreFlags.X509_STRICT)

    return store
Beispiel #20
0
 def loadCAFromPFX(self, pfx):
     CAcerts = pfx.get_ca_certificates()
     if len(CAcerts) != 1:
         LOG.error("Incompatible Root CA structure!")
         raise IncompatibleRootCAException
     self.CA = crypto.X509Store()
     self.CA.add_cert(CAcerts[0])
Beispiel #21
0
    def verify_certificate_chain(self, cert, chain, crl_list, datetime):
        crl_list = self.crl_files_to_objects(crl_list)
        certificate = cert

        try:
                    
            store = crypto.X509Store()
            store.set_flags(crypto.X509StoreFlags.CRL_CHECK_ALL)

            for cert in chain:
                store.add_cert(cert)

            for crl in crl_list:
                store.add_crl(crl)


            if datetime:
                store.set_time(datetime)

            store_ctx = crypto.X509StoreContext(store, certificate)



            store_ctx.verify_certificate()

            return True

        except Exception as e:
            raise e
Beispiel #22
0
def verify():

    p12_client = crypto.load_pkcs12(open("Servidor.p12", 'rb').read(), "1234")
    
    client_certific = crypto.dump_certificate(crypto.FILETYPE_PEM, p12_client.get_certificate())
    public_key_ssl_client = x509.load_pem_x509_certificate(client_certific, default_backend()).public_key()
    print(len(client_certific))
    #p12_server = crypto.load_pkcs12(open("Servidor.p12", 'rb').read(), "1234")
    #p12_server.get_certificate()

    ca = crypto.load_certificate(crypto.FILETYPE_ASN1, open("CA.cer", 'rb').read())
    cert = crypto.dump_certificate(crypto.FILETYPE_PEM, ca)

    #manda para a funçao    
    try:
        trusted = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
        c = crypto.load_certificate(crypto.FILETYPE_PEM, client_certific)

        store = crypto.X509Store()

        store.add_cert(trusted)

        store_ctx = crypto.X509StoreContext(store, c)

        store_ctx.verify_certificate()

        print("certificado confirmado")


    except Exception as e:
        print(e)
        print("com e")    
Beispiel #23
0
    def valUserCert(self, byts, cacerts=None):
        '''
        Validate the PEM encoded x509 user certificate bytes and return it.

        Args:
            byts (bytes): The bytes for the User Certificate.
            cacerts (tuple): A tuple of OpenSSL.crypto.X509 CA Certificates.

        Raises:
            OpenSSL.crypto.X509StoreContextError: If the certificate is not valid.

        Returns:
            OpenSSL.crypto.X509: The certificate, if it is valid.

        '''
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, byts)

        if cacerts is None:
            cacerts = self.getCaCerts()

        store = crypto.X509Store()
        [store.add_cert(cacert) for cacert in cacerts]

        ctx = crypto.X509StoreContext(store, cert)
        ctx.verify_certificate()  # raises X509StoreContextError if unable to verify
        return cert
Beispiel #24
0
def test_openssl():
    codeur_bundle = SSLCABundle('c:/private/tranquilit-codeur.crt')
    codeur = codeur_bundle.certificates()[0]
    trusted_ca = SSLCABundle(certifi.where())
    print codeur_bundle.certificate_chain(codeur)

    codeur.verify_signature_with(codeur_bundle)

    print trusted_ca.certificate_chain(codeur)

    for ca in codeur_bundle.certificate_chain(codeur):
        print ca.crl_urls()

    for ca in trusted_ca.certificates():
        print ca.crl_urls()

    store = crypto.X509Store()
    store.set_flags( (
        crypto.X509StoreFlags.CRL_CHECK |
        crypto.X509StoreFlags.CB_ISSUER_CHECK
        ))
    for cert in trusted_ca.certificates():
        store.add_cert(cert.as_X509())

    # load all the crl...
    issuer = trusted_ca.is_known_issuer(codeur)
    crl = requests.get('http://crl.usertrust.com/UTN-USERFirst-Object.crl').content
    crlcert = crypto.load_crl(crypto.FILETYPE_ASN1,crl)
    store.add_crl(crlcert)

    store_ctx = crypto.X509StoreContext(store,cert.as_X509())
    try:
        print store_ctx.verify_certificate()
    except Exception as e:
        print e
Beispiel #25
0
def verify_certificate_chain(cert, trusted_certs):
    # Download the certificate from the url and load the certificate
    assert (len(trusted_certs) != 0)
    certificate = x509.load_pem_x509_certificate(cert, default_backend())

    # Create a certificate store and add your trusted certs
    try:
        store = crypto.X509Store()

        # Assuming the certificates are in PEM format in a trusted_certs list
        for _cert in trusted_certs:
            cert_data = _cert
            client_certificate = crypto.load_certificate(
                crypto.FILETYPE_PEM, cert_data)
            store.add_cert(client_certificate)
        # Create a certificate context using the store and the downloaded certificate
        store_ctx = crypto.X509StoreContext(store, certificate)

        # Verify the certificate, returns None if it can validate the certificate
        store_ctx.verify_certificate()

        return True
    except Exception as e:
        print(e)
        return False
 def __init__(self, trustedCerts=None):
     self.store = crypto.X509Store()
     if trustedCerts is not None:
         for cert in trustedCerts:
             cert = crypto.load_certificate(crypto.FILETYPE_ASN1,
                                            bytes(cert))
             self.add_cert(cert)
Beispiel #27
0
    def init_cert_store(self, pychain):
        store= crypto.X509Store()
        
        for tcert in pychain:
            store.add_cert(tcert)

        return store
Beispiel #28
0
def verify_certs_chain(certs_chain: List[crypto.X509],
                       amazon_cert: crypto.X509) -> bool:
    """Verifies if Amazon and additional certificates creates chain of trust to a root CA.

    Args:
        certs_chain: List of pycrypto X509 intermediate certificates from signature chain URL.
        amazon_cert: Pycrypto X509 Amazon certificate.

    Returns:
        result: True if verification was successful, False if not.
    """
    store = crypto.X509Store()

    # add certificates from Amazon provided certs chain
    for cert in certs_chain:
        store.add_cert(cert)

    # add CA certificates
    default_verify_paths = ssl.get_default_verify_paths()

    default_verify_file = default_verify_paths.cafile
    default_verify_file = Path(
        default_verify_file).resolve() if default_verify_file else None

    default_verify_path = default_verify_paths.capath
    default_verify_path = Path(
        default_verify_path).resolve() if default_verify_path else None

    ca_files = [ca_file for ca_file in default_verify_path.iterdir()
                ] if default_verify_path else []
    if default_verify_file:
        ca_files.append(default_verify_file)

    for ca_file in ca_files:
        ca_file: Path
        if ca_file.is_file():
            with ca_file.open('r', encoding='ascii') as crt_f:
                ca_certs_txt = crt_f.read()
                ca_certs = extract_certs(ca_certs_txt)
                for cert in ca_certs:
                    store.add_cert(cert)

    # add CA certificates (Windows)
    ssl_context = ssl.create_default_context()
    der_certs = ssl_context.get_ca_certs(binary_form=True)
    pem_certs = '\n'.join(
        [ssl.DER_cert_to_PEM_cert(der_cert) for der_cert in der_certs])
    ca_certs = extract_certs(pem_certs)
    for ca_cert in ca_certs:
        store.add_cert(ca_cert)

    store_context = crypto.X509StoreContext(store, amazon_cert)

    try:
        store_context.verify_certificate()
        result = True
    except crypto.X509StoreContextError:
        result = False

    return result
Beispiel #29
0
    def verify_chain_of_trust(cert_pem, trusted_cert_pems):
        '''
        This method uses the pyOpenSSL module to verify the chain of X509 PEM encoded certificates
        NOTE: This requires a newer version of pyOpenSSL that does not come with CentOS/RHEL
        Need to install an updated version of pyOpenSSL using pip install pyopenssl
        Tested with version: pyopenssl-17.5.0
        '''
        certificate = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem)

        # Create and fill a X509Sore with trusted certs
        store = crypto.X509Store()
        for trusted_cert_pem in trusted_cert_pems:
            trusted_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                                   trusted_cert_pem)
            store.add_cert(trusted_cert)

        # Create a X590StoreContext with the cert and trusted certs
        # and verify the the chain of trust
        store_ctx = crypto.X509StoreContext(store, certificate)
        # Returns None if certificate can be validated
        result = store_ctx.verify_certificate()

        if result is None:
            return True
        else:
            return False
Beispiel #30
0
def verify_chain_of_trust(cert_pem, trusted_cert_pems):
    #Transformar o pkcs12 em pem
    p12 = crypto.load_pkcs12(open(cert_pem, 'rb').read(), "1234")
    privatekey = p12.get_privatekey()
    cert = p12.get_certificate()
    pem = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)

    certificate = crypto.load_certificate(crypto.FILETYPE_PEM, pem)
    #print(cert_pem.load_privatekey(crypto.FILETYPE_PEM, "1234"))

    # Create and fill a X509Sore with trusted certs
    store = crypto.X509Store()
    for trusted_cert_pem in trusted_cert_pems:
        trusted_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                               trusted_cert_pem)
    store.add_cert(trusted_cert)

    # Create a X590StoreContext with the cert and trusted certs
    # and verify the the chain of trust
    store_ctx = crypto.X509StoreContext(store, certificate)
    # Returns None if certificate can be validated
    result = store_ctx.verify_certificate()

    if result is None:
        print("OK")
        return True
    else:
        print("ERRO")
        return False