Python cryptography.x509.Certificate() Examples

The following are 30 code examples of cryptography.x509.Certificate(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cryptography.x509 , or try the search function .
Example #1
Source File: _symantec.py    From sslyze with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_distrust_timeline(
        cls, verified_certificate_chain: List[Certificate]
    ) -> Optional[SymantecDistrustTimelineEnum]:
        has_whitelisted_cert = False
        has_blacklisted_cert = False

        # Is there a Symantec root certificate in the chain?
        for certificate in verified_certificate_chain:
            key_hash = binascii.hexlify(get_public_key_sha256(certificate)).decode("ascii")
            if key_hash in cls._CA_KEYS_BLACKLIST:
                has_blacklisted_cert = True
            if key_hash in cls._CA_KEYS_WHITELIST:
                has_whitelisted_cert = True

        distrust_enum = None
        if has_blacklisted_cert and not has_whitelisted_cert:
            leaf_cert = verified_certificate_chain[0]
            if leaf_cert.not_valid_before < datetime(year=2016, month=6, day=1):
                distrust_enum = SymantecDistrustTimelineEnum.MARCH_2018
            else:
                distrust_enum = SymantecDistrustTimelineEnum.SEPTEMBER_2018
        return distrust_enum 
Example #2
Source File: _certificate_utils.py    From sslyze with GNU Affero General Public License v3.0 6 votes vote down vote up
def extract_dns_subject_alternative_names(certificate: x509.Certificate) -> List[str]:
    """Retrieve all the DNS entries of the Subject Alternative Name extension.
    """
    subj_alt_names: List[str] = []
    try:
        san_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
        san_ext_value = cast(x509.SubjectAlternativeName, san_ext.value)
        subj_alt_names = san_ext_value.get_values_for_type(DNSName)
    except ExtensionNotFound:
        pass
    except DuplicateExtension:
        # Fix for https://github.com/nabla-c0d3/sslyze/issues/420
        # Not sure how browsers behave in this case but having a duplicate extension makes the certificate invalid
        # so we just return no SANs (likely to make hostname validation fail, which is fine)
        pass

    return subj_alt_names 
Example #3
Source File: crypto.py    From pyopenssl with Apache License 2.0 6 votes vote down vote up
def from_cryptography(cls, crypto_cert):
        """
        Construct based on a ``cryptography`` *crypto_cert*.

        :param crypto_key: A ``cryptography`` X.509 certificate.
        :type crypto_key: ``cryptography.x509.Certificate``

        :rtype: X509

        .. versionadded:: 17.1.0
        """
        if not isinstance(crypto_cert, x509.Certificate):
            raise TypeError("Must be a certificate")

        cert = cls()
        cert._x509 = crypto_cert._x509
        return cert 
Example #4
Source File: _cert_chain_analyzer.py    From sslyze with GNU Affero General Public License v3.0 6 votes vote down vote up
def _verify_certificate_chain(server_certificate_chain: List[str], trust_store: TrustStore) -> PathValidationResult:
    server_chain_as_x509s = [X509(pem_cert) for pem_cert in server_certificate_chain]
    chain_verifier = CertificateChainVerifier.from_file(trust_store.path)

    verified_chain: Optional[List[Certificate]]
    try:
        openssl_verify_str = None
        verified_chain_as_509s = chain_verifier.verify(server_chain_as_x509s)
        verified_chain = [
            load_pem_x509_certificate(x509_cert.as_pem().encode("ascii"), backend=default_backend())
            for x509_cert in verified_chain_as_509s
        ]
    except CertificateChainVerificationFailed as e:
        verified_chain = None
        openssl_verify_str = e.openssl_error_string

    return PathValidationResult(
        trust_store=trust_store, verified_certificate_chain=verified_chain, openssl_error_string=openssl_verify_str
    ) 
Example #5
Source File: tests_command_regenerate_ocsp_keys.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def assertKey(self, ca, key_type=RSAPrivateKey, password=None):
        priv_path = 'ocsp/%s.key' % ca.serial
        cert_path = 'ocsp/%s.pem' % ca.serial

        self.assertTrue(ca_storage.exists(priv_path))
        self.assertTrue(ca_storage.exists(cert_path))

        with ca_storage.open(priv_path, 'rb') as stream:
            priv = stream.read()
        priv = load_pem_private_key(priv, password, default_backend())
        self.assertIsInstance(priv, key_type)

        with ca_storage.open(cert_path, 'rb') as stream:
            cert = stream.read()
        cert = x509.load_pem_x509_certificate(cert, default_backend())
        self.assertIsInstance(cert, x509.Certificate)

        db_cert = Certificate.objects.exclude(pk__in=self.existing_certs).first()
        self.assertEqual(db_cert.authority_information_access.ocsp, [])

        return priv, cert 
Example #6
Source File: conftest.py    From commandment with MIT License 6 votes vote down vote up
def certificate(private_key: rsa.RSAPrivateKey) -> x509.Certificate:
    b = x509.CertificateBuilder()
    name = x509.Name([
        x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
        x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"CA"),
        x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Commandment"),
        x509.NameAttribute(NameOID.COMMON_NAME, u"CA-CERTIFICATE"),
    ])

    cer = b.subject_name(name).issuer_name(name).public_key(
        private_key.public_key()
    ).serial_number(1).not_valid_before(
        datetime.datetime.utcnow()
    ).not_valid_after(
        datetime.datetime.utcnow() + datetime.timedelta(days=10)
    ).add_extension(
        x509.BasicConstraints(ca=False, path_length=None), True
    ).sign(private_key, hashes.SHA256(), default_backend())

    return cer 
Example #7
Source File: app.py    From commandment with MIT License 6 votes vote down vote up
def anchor_certs():
    """Download a list of certificates to trust the MDM

    The response is a JSON array of base64 encoded DER certs as described in the DEP profile creation documentation."""
    anchors = []

    if 'CA_CERTIFICATE' in current_app.config:
        with open(current_app.config['CA_CERTIFICATE'], 'rb') as fd:
            pem_data = fd.read()
            c: x509.Certificate = x509.load_pem_x509_certificate(pem_data, backend=default_backend())
            der = c.public_bytes(Encoding.DER)
            anchors.append(urlsafe_b64encode(der))

    if 'SSL_CERTIFICATE' in current_app.config:
        with open(current_app.config['SSL_CERTIFICATE'], 'rb') as fd:
            pem_data = fd.read()
            c: x509.Certificate = x509.load_pem_x509_certificate(pem_data, backend=default_backend())
            der = c.public_bytes(Encoding.DER)
            anchors.append(urlsafe_b64encode(der))

    return jsonify(anchors) 
Example #8
Source File: models.py    From commandment with MIT License 6 votes vote down vote up
def from_crypto(cls, certificate: x509.Certificate):
        m = cls()
        m.serial = certificate.serial_number
        m.pem_data = certificate.public_bytes(encoding=serialization.Encoding.PEM)
        m.not_after = certificate.not_valid_after
        m.not_before = certificate.not_valid_before
        m.fingerprint = certificate.fingerprint(hashes.SHA256())

        subject: x509.Name = certificate.subject

        cns = subject.get_attributes_for_oid(NameOID.COMMON_NAME)
        if cns is not None:
            m.x509_cn = cns[0].value

        # m.x509_c = subject.get_attributes_for_oid(NameOID.COUNTRY_NAME)
        # m.x509_o = subject.get_attributes_for_oid(NameOID.ORGANIZATION_NAME)
        # m.x509_ou = subject.get_attributes_for_oid(NameOID.ORGANIZATIONAL_UNIT_NAME)
        # m.x509_st = subject.get_attributes_for_oid(NameOID.STATE_OR_PROVINCE_NAME)

        return m 
Example #9
Source File: models.py    From commandment with MIT License 6 votes vote down vote up
def from_crypto(cls, csr: x509.CertificateSigningRequest):
        # type: (type, x509.CertificateSigningRequest, CertificateType) -> Certificate
        m = cls()
        m.pem_data = csr.public_bytes(serialization.Encoding.PEM)
        m.not_before = datetime.datetime.utcnow()
        m.not_after = datetime.datetime.utcnow() + datetime.timedelta(days=700)
        h = hashes.Hash(hashes.SHA256(), default_backend())
        h.update(m.pem_data)
        m.fingerprint = h.finalize()

        m.discriminator = CertificateType.CSR.value

        subject: x509.Name = csr.subject
        cns = subject.get_attributes_for_oid(NameOID.COMMON_NAME)
        if cns is not None:
            m.x509_cn = cns[0].value

        return m 
Example #10
Source File: models.py    From commandment with MIT License 6 votes vote down vote up
def from_crypto_type(cls, certificate: x509.Certificate, certtype: CertificateType):
        # type: (certtype, x509.Certificate, CertificateType) -> Certificate
        m = cls()
        m.serial = certificate.serial_number
        m.pem_data = certificate.public_bytes(serialization.Encoding.PEM)
        m.not_after = certificate.not_valid_after
        m.not_before = certificate.not_valid_before
        m.fingerprint = certificate.fingerprint(hashes.SHA256())
        m.discriminator = certtype.value
        m.serial = str(certificate.serial_number)

        subject: x509.Name = certificate.subject
        cns = subject.get_attributes_for_oid(NameOID.COMMON_NAME)
        if cns is not None:
            m.x509_cn = cns[0].value

        return m 
Example #11
Source File: crypto.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def from_cryptography(cls, crypto_cert):
        """
        Construct based on a ``cryptography`` *crypto_cert*.

        :param crypto_key: A ``cryptography`` X.509 certificate.
        :type crypto_key: ``cryptography.x509.Certificate``

        :rtype: X509

        .. versionadded:: 17.1.0
        """
        if not isinstance(crypto_cert, x509.Certificate):
            raise TypeError("Must be a certificate")

        cert = cls()
        cert._x509 = crypto_cert._x509
        return cert 
Example #12
Source File: profiles.py    From commandment with MIT License 6 votes vote down vote up
def ssl_trust_payload_from_configuration() -> PEMCertificatePayload:
    """Generate a PEM certificate payload in order to trust this host.

    """
    try:
        org = db.session.query(Organization).one()
    except NoResultFound:
        abort(500, 'No organization is configured, cannot generate enrollment profile.')
    except MultipleResultsFound:
        abort(500, 'Multiple organizations, backup your database and start again')

    basepath = os.path.dirname(__file__)
    certpath = os.path.join(basepath, current_app.config['SSL_CERTIFICATE'])

    with open(certpath, 'rb') as fd:
        pem_payload = PEMCertificatePayload(
            uuid=uuid4(),
            identifier=org.payload_prefix + '.ssl',
            payload_content=fd.read(),
            display_name='Web Server Certificate',
            description='Required for your device to trust the server',
            type='com.apple.security.pkcs1',
            version=1
        )
        return pem_payload 
Example #13
Source File: profiles.py    From commandment with MIT License 6 votes vote down vote up
def ca_trust_payload_from_configuration() -> PEMCertificatePayload:
    """Create a CA payload with the PEM representation of the Certificate Authority used by this instance.

    You need to check whether the app config contains 'CA_CERTIFICATE' before invoking this.
    """
    try:
        org = db.session.query(Organization).one()
    except NoResultFound:
        abort(500, 'No organization is configured, cannot generate enrollment profile.')
    except MultipleResultsFound:
        abort(500, 'Multiple organizations, backup your database and start again')

    with open(current_app.config['CA_CERTIFICATE'], 'rb') as fd:
        pem_data = fd.read()
        pem_payload = PEMCertificatePayload(
            uuid=uuid4(),
            identifier=org.payload_prefix + '.ca',
            payload_content=pem_data,
            display_name='Certificate Authority',
            description='Required for your device to trust the server',
            type='com.apple.security.root',
            version=1
        )

        return pem_payload 
Example #14
Source File: views.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def get_responder_cert_data(self):
        if self.responder_cert.startswith('-----BEGIN CERTIFICATE-----\n'):
            return self.responder_cert.encode('utf-8')

        if SERIAL_RE.match(self.responder_cert):
            serial = self.responder_cert.replace(':', '')
            return Certificate.objects.get(serial=serial).pub.encode('utf-8')

        if os.path.isabs(self.responder_cert):
            log.warning('%s: OCSP responder uses absolute path to certificate. Please see %s.',
                        self.responder_cert, ca_settings.CA_FILE_STORAGE_URL)

        return read_file(self.responder_cert) 
Example #15
Source File: tests_command_regenerate_ocsp_keys.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(RegenerateOCSPKeyTestCase, self).setUp()
        self.load_usable_cas()
        self.existing_certs = list(Certificate.objects.values_list('pk', flat=True)) 
Example #16
Source File: views.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def get_responder_cert(self):
        # User configured a loaded certificate
        if isinstance(self.responder_cert, x509.Certificate):
            return self.responder_cert

        responder_cert = self.get_responder_cert_data()
        return load_pem_x509_certificate(responder_cert, default_backend()) 
Example #17
Source File: views.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def get_cert(self, ca, serial):
        if self.ca_ocsp is True:
            return CertificateAuthority.objects.filter(parent=ca).get(serial=serial)
        else:
            return Certificate.objects.filter(ca=ca).get(serial=serial) 
Example #18
Source File: models.py    From commandment with MIT License 5 votes vote down vote up
def from_crypto(cls, certificate: x509.Certificate):
        # TODO: sometimes serial numbers are too large even for SQLite BIGINT
        m = cls()
        m.serial = certificate.serial_number
        m.pem_data = certificate.public_bytes(encoding=serialization.Encoding.PEM)
        m.not_after = certificate.not_valid_after
        m.not_before = certificate.not_valid_before
        m.fingerprint = certificate.fingerprint(hashes.SHA256())

        subject: x509.Name = certificate.subject

        cns = subject.get_attributes_for_oid(NameOID.COMMON_NAME)
        if cns is not None:
            m.x509_cn = cns[0].value
        return m 
Example #19
Source File: crypto.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def to_cryptography(self):
        """
        Export as a ``cryptography`` certificate.

        :rtype: ``cryptography.x509.Certificate``

        .. versionadded:: 17.1.0
        """
        from cryptography.hazmat.backends.openssl.x509 import _Certificate
        backend = _get_backend()
        return _Certificate(backend, self._x509) 
Example #20
Source File: models.py    From commandment with MIT License 5 votes vote down vote up
def from_crypto(cls, certificate: x509.Certificate):  # type: () -> CACertificate
        m = cls.from_crypto_type(certificate, CertificateType.CA)
        return m 
Example #21
Source File: serialization.py    From commandment with MIT License 5 votes vote down vote up
def to_der(certificate: x509.Certificate) -> bytes:
    """Convert an instance of x509.Certificate to DER bytes
    
    Args:
          certificate (x509.Certificate): Cert to convert
    Returns:
          DER bytes    
    """
    serialized = certificate.public_bytes(
        encoding=serialization.Encoding.DER,
        format=serialization.PublicFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    )

    return serialized 
Example #22
Source File: serialization.py    From commandment with MIT License 5 votes vote down vote up
def from_der(der_data: bytes) -> x509.Certificate:
    return x509.load_der_x509_certificate(der_data, default_backend()) 
Example #23
Source File: crypto.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def load_crl(type, buffer):
    """
    Load Certificate Revocation List (CRL) data from a string *buffer*.
    *buffer* encoded with the type *type*.

    :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
    :param buffer: The buffer the CRL is stored in

    :return: The PKey object
    """
    if isinstance(buffer, _text_type):
        buffer = buffer.encode("ascii")

    bio = _new_mem_buf(buffer)

    if type == FILETYPE_PEM:
        crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
    elif type == FILETYPE_ASN1:
        crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
    else:
        raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")

    if crl == _ffi.NULL:
        _raise_current_error()

    result = CRL.__new__(CRL)
    result._crl = _ffi.gc(crl, _lib.X509_CRL_free)
    return result 
Example #24
Source File: serialization.py    From commandment with MIT License 5 votes vote down vote up
def from_pem(pem_data: str) -> x509.Certificate:
    return x509.load_pem_x509_certificate(pem_data, default_backend()) 
Example #25
Source File: profiles.py    From commandment with MIT License 5 votes vote down vote up
def identity_payload(private_key: rsa.RSAPrivateKeyWithSerialization,
                     certificate: x509.Certificate,
                     passphrase: Optional[str] = None) -> PKCS12CertificatePayload:
    """Generate a PKCS#12 certificate payload for device identity."""
    try:
        org = db.session.query(Organization).one()
    except NoResultFound:
        abort(500, 'No organization is configured, cannot generate enrollment profile.')
    except MultipleResultsFound:
        abort(500, 'Multiple organizations, backup your database and start again')

    pkcs12_data = create_pkcs12(private_key, certificate, passphrase)

    pkcs12_payload = PKCS12CertificatePayload(
        uuid=uuid4(),
        certificate_file_name='device_identity.p12',
        identifier=org.payload_prefix + '.identity',
        display_name='Device Identity Certificate',
        description='Required to identify your device to the MDM',
        type='com.apple.security.pkcs12',
        password=passphrase,
        payload_content=pkcs12_data,
        version=1
    )

    return pkcs12_payload 
Example #26
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def test_convert_to_cryptography_key(self):
        cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
        crypto_cert = cert.to_cryptography()

        assert isinstance(crypto_cert, x509.Certificate)
        assert crypto_cert.version.value == cert.get_version() 
Example #27
Source File: x509.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def public_key(self):
        pkey = self._backend._lib.X509_get_pubkey(self._x509)
        if pkey == self._backend._ffi.NULL:
            # Remove errors from the stack.
            self._backend._consume_errors()
            raise ValueError("Certificate public key is of an unknown type")

        pkey = self._backend._ffi.gc(pkey, self._backend._lib.EVP_PKEY_free)

        return self._backend._evp_pkey_to_public_key(pkey) 
Example #28
Source File: test_utils.py    From PyKMIP with Apache License 2.0 5 votes vote down vote up
def test_get_certificate_from_connection(self):
        """
        Test that the certificate can be retrieved from a provided connection.
        """
        mock_connection = mock.MagicMock(ssl.SSLSocket)
        mock_connection.getpeercert.return_value = self.certificate_bytes
        result = utils.get_certificate_from_connection(
            mock_connection
        )

        self.assertIsInstance(result, x509.Certificate) 
Example #29
Source File: _cli_connector.py    From sslyze with GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_basic_certificate_text(cls, certificate: Certificate) -> List[str]:
        text_output = [
            cls._format_field(
                "SHA1 Fingerprint:", binascii.hexlify(certificate.fingerprint(hashes.SHA1())).decode("ascii")
            ),
            cls._format_field("Common Name:", _get_name_as_short_text(certificate.subject)),
            cls._format_field("Issuer:", _get_name_as_short_text(certificate.issuer)),
            cls._format_field("Serial Number:", str(certificate.serial_number)),
            cls._format_field("Not Before:", certificate.not_valid_before.date().isoformat()),
            cls._format_field("Not After:", certificate.not_valid_after.date().isoformat()),
            cls._format_field("Public Key Algorithm:", certificate.public_key().__class__.__name__),
        ]

        if certificate.signature_hash_algorithm:
            # The signature_hash_algorithm can be None if signature did not use separate hash (ED25519, ED448)
            # https://cryptography.io/en/latest/x509/reference/#cryptography.x509.Certificate.signature_hash_algorithm
            text_output.append(cls._format_field("Signature Algorithm:", certificate.signature_hash_algorithm.name))

        public_key = certificate.public_key()
        if isinstance(public_key, EllipticCurvePublicKey):
            text_output.append(cls._format_field("Key Size:", str(public_key.curve.key_size)))
            text_output.append(cls._format_field("Curve:", str(public_key.curve.name)))
        elif isinstance(public_key, RSAPublicKey):
            text_output.append(cls._format_field("Key Size:", str(public_key.key_size)))
            text_output.append(cls._format_field("Exponent:", str(public_key.public_numbers().e)))  # type: ignore
        else:
            # DSA Key? https://github.com/nabla-c0d3/sslyze/issues/314
            pass

        try:
            # Print the SAN extension if there's one
            text_output.append(
                cls._format_field(
                    "DNS Subject Alternative Names:", str(extract_dns_subject_alternative_names(certificate))
                )
            )
        except KeyError:
            pass

        return text_output 
Example #30
Source File: ssl.py    From commandment with MIT License 5 votes vote down vote up
def generate_signing_request(cn: str, dnsname: Optional[str] = None) -> (rsa.RSAPrivateKey, x509.CertificateSigningRequest):
    """Generate a Private Key + Certificate Signing Request using the given dnsname as the CN and SAN dNSName.
    
    Args:
            cn (str): The certificate common name
          dnsname (str): The public facing dns name of the MDM server.
    Returns:
          Tuple of rsa private key, csr
    """
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend(),
    )

    name = x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, cn),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment')
    ])

    builder = x509.CertificateSigningRequestBuilder()
    builder = builder.subject_name(name)

    if dnsname is not None:
        san = x509.SubjectAlternativeName([
            x509.DNSName(dnsname)
        ])
        builder = builder.add_extension(san, critical=True)

    builder = builder.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
    
    request = builder.sign(
        private_key,
        hashes.SHA256(),
        default_backend()
    )

    return private_key, request