Python cryptography.x509.ExtendedKeyUsage() Examples
The following are 26
code examples of cryptography.x509.ExtendedKeyUsage().
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: certrequest.py From custodia with GNU General Public License v3.0 | 7 votes |
def build_csr(self, hostname, **kwargs): realm = self.plugin.ipa.env.realm builder = x509.CertificateSigningRequestBuilder() builder = builder.subject_name( x509.Name([ x509.NameAttribute(oid.NameOID.COMMON_NAME, hostname), x509.NameAttribute(oid.NameOID.ORGANIZATION_NAME, realm), ]) ) build = builder.add_extension( x509.BasicConstraints(ca=False, path_length=None), critical=True, ) build = builder.add_extension( x509.ExtendedKeyUsage([TLS_SERVERAUTH]), critical=True ) builder = build.add_extension( x509.SubjectAlternativeName([x509.DNSName(hostname)]), critical=False ) return builder # pylint: disable=arguments-differ
Example #2
Source File: tls.py From dcos-e2e with Apache License 2.0 | 6 votes |
def cert_extended_key_usage(**kwargs): """ Helper to create x509.ExtendedKeyUsage object. Args: x509.ExtendedKeyUsage keys. If not provided False is used for each arg. Return: x509.ExtendedKeyUsage """ usages = { 'server_auth': x509.oid.ExtendedKeyUsageOID.SERVER_AUTH, 'client_auth': x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH, 'code_signing': x509.oid.ExtendedKeyUsageOID.CODE_SIGNING, # ... and others, which we do not need. Check e.g. # https://cryptography.io/en/latest/_modules/cryptography/x509/oid/#ExtendedKeyUsageOID # for details. } res = [] for k, v in kwargs.items(): assert k in usages, "unknown exteneded key usage specified" if v: res.append(usages[k]) return x509.ExtendedKeyUsage(res)
Example #3
Source File: tls.py From dcos-e2e with Apache License 2.0 | 6 votes |
def cert_extended_key_usage(**kwargs): """ Helper to create x509.ExtendedKeyUsage object. Args: x509.ExtendedKeyUsage keys. If not provided False is used for each arg. Return: x509.ExtendedKeyUsage """ usages = { 'server_auth': x509.oid.ExtendedKeyUsageOID.SERVER_AUTH, 'client_auth': x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH, 'code_signing': x509.oid.ExtendedKeyUsageOID.CODE_SIGNING, # ... and others, which we do not need. Check e.g. # https://cryptography.io/en/latest/_modules/cryptography/x509/oid/#ExtendedKeyUsageOID # for details. } res = [] for k, v in kwargs.items(): assert k in usages, "unknown exteneded key usage specified" if v: res.append(usages[k]) return x509.ExtendedKeyUsage(res)
Example #4
Source File: test_utils.py From PyKMIP with Apache License 2.0 | 5 votes |
def test_get_extended_key_usage_from_certificate(self): """ Test that the ExtendedKeyUsage extension can be retrieved from a certificate. """ extension = utils.get_extended_key_usage_from_certificate( self.certificate ) self.assertIsInstance(extension, x509.ExtendedKeyUsage) self.assertIn(x509.ExtendedKeyUsageOID.CLIENT_AUTH, extension)
Example #5
Source File: decode_asn1.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _decode_extended_key_usage(backend, sk): sk = backend._ffi.cast("Cryptography_STACK_OF_ASN1_OBJECT *", sk) sk = backend._ffi.gc(sk, backend._lib.sk_ASN1_OBJECT_free) num = backend._lib.sk_ASN1_OBJECT_num(sk) ekus = [] for i in range(num): obj = backend._lib.sk_ASN1_OBJECT_value(sk, i) backend.openssl_assert(obj != backend._ffi.NULL) oid = x509.ObjectIdentifier(_obj2txt(backend, obj)) ekus.append(oid) return x509.ExtendedKeyUsage(ekus)
Example #6
Source File: decode_asn1.py From quickstart-redhat-openshift with Apache License 2.0 | 5 votes |
def _decode_extended_key_usage(backend, sk): sk = backend._ffi.cast("Cryptography_STACK_OF_ASN1_OBJECT *", sk) sk = backend._ffi.gc(sk, backend._lib.sk_ASN1_OBJECT_free) num = backend._lib.sk_ASN1_OBJECT_num(sk) ekus = [] for i in range(num): obj = backend._lib.sk_ASN1_OBJECT_value(sk, i) backend.openssl_assert(obj != backend._ffi.NULL) oid = x509.ObjectIdentifier(_obj2txt(backend, obj)) ekus.append(oid) return x509.ExtendedKeyUsage(ekus)
Example #7
Source File: decode_asn1.py From quickstart-git2s3 with Apache License 2.0 | 5 votes |
def _decode_extended_key_usage(backend, sk): sk = backend._ffi.cast("Cryptography_STACK_OF_ASN1_OBJECT *", sk) sk = backend._ffi.gc(sk, backend._lib.sk_ASN1_OBJECT_free) num = backend._lib.sk_ASN1_OBJECT_num(sk) ekus = [] for i in range(num): obj = backend._lib.sk_ASN1_OBJECT_value(sk, i) backend.openssl_assert(obj != backend._ffi.NULL) oid = x509.ObjectIdentifier(_obj2txt(backend, obj)) ekus.append(oid) return x509.ExtendedKeyUsage(ekus)
Example #8
Source File: tests_extensions.py From django-ca with GNU General Public License v3.0 | 5 votes |
def test_completeness(self): # make sure we support all ExtendedKeyUsageOIDs for attr in [getattr(ExtendedKeyUsageOID, a) for a in dir(ExtendedKeyUsageOID) if a[0] != '_']: if isinstance(attr, ObjectIdentifier): self.assertIn(attr, ExtendedKeyUsage._CRYPTOGRAPHY_MAPPING_REVERSED) # make sure we haven't forgotton any keys in the form selection self.assertEqual(set(ExtendedKeyUsage.CRYPTOGRAPHY_MAPPING.keys()), set([e[0] for e in ExtendedKeyUsage.CHOICES]))
Example #9
Source File: tests_extensions.py From django-ca with GNU General Public License v3.0 | 5 votes |
def test_unknown_values(self): with self.assertRaisesRegex(ValueError, r'^Unknown value: foo$'): ExtendedKeyUsage({'value': ['foo']}) with self.assertRaisesRegex(ValueError, r'^Unknown value: True$'): ExtendedKeyUsage({'value': [True]})
Example #10
Source File: extensions.py From django-ca with GNU General Public License v3.0 | 5 votes |
def extension_type(self): # call serialize_value() to ensure consistent sort order return x509.ExtendedKeyUsage(sorted(self.value, key=lambda v: self.serialize_value(v)))
Example #11
Source File: operations.py From magnum with Apache License 2.0 | 5 votes |
def _build_client_extentions(): # Digital Signature and Key Encipherment are enabled key_usage = x509.KeyUsage(True, False, True, False, False, False, False, False, False) key_usage = x509.Extension(key_usage.oid, True, key_usage) extended_key_usage = x509.ExtendedKeyUsage([x509.OID_CLIENT_AUTH]) extended_key_usage = x509.Extension(extended_key_usage.oid, False, extended_key_usage) basic_constraints = x509.BasicConstraints(ca=False, path_length=None) basic_constraints = x509.Extension(basic_constraints.oid, True, basic_constraints) return [key_usage, extended_key_usage, basic_constraints]
Example #12
Source File: test_sign.py From magnum with Apache License 2.0 | 5 votes |
def assertInClientExtensions(self, cert): key_usage = c_x509.KeyUsage(True, False, True, False, False, False, False, False, False) key_usage = c_x509.Extension(key_usage.oid, True, key_usage) extended_key_usage = c_x509.ExtendedKeyUsage([c_x509.OID_CLIENT_AUTH]) extended_key_usage = c_x509.Extension(extended_key_usage.oid, False, extended_key_usage) basic_constraints = c_x509.BasicConstraints(ca=False, path_length=None) basic_constraints = c_x509.Extension(basic_constraints.oid, True, basic_constraints) self.assertIn(key_usage, cert.extensions) self.assertIn(extended_key_usage, cert.extensions) self.assertIn(basic_constraints, cert.extensions)
Example #13
Source File: test_utils.py From PyKMIP with Apache License 2.0 | 5 votes |
def test_get_extended_key_usage_from_certificate_with_no_extension(self): """ Test that the right value is returned when the ExtendedKeyUsage extension cannot be retrieved from a certificate. """ extension = utils.get_extended_key_usage_from_certificate( self.certificate_no_extension ) self.assertEqual(None, extension)
Example #14
Source File: create_certificates.py From PyKMIP with Apache License 2.0 | 5 votes |
def create_certificate(subject_name, private_key, signing_certificate, signing_key, days_valid=365, client_auth=False): subject = x509.Name([ x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Test, Inc."), x509.NameAttribute(x509.NameOID.COMMON_NAME, subject_name) ]) builder = x509.CertificateBuilder().subject_name( subject ).issuer_name( signing_certificate.subject ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=days_valid) ) if client_auth: builder = builder.add_extension( x509.ExtendedKeyUsage([x509.ExtendedKeyUsageOID.CLIENT_AUTH]), critical=True ) certificate = builder.sign( signing_key, hashes.SHA256(), backends.default_backend() ) return certificate
Example #15
Source File: fields.py From lemur with Apache License 2.0 | 5 votes |
def _deserialize(self, value, attr, data): usage_oids = [] for k, v in value.items(): if k == "useClientAuthentication" and v: usage_oids.append(x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH) elif k == "useServerAuthentication" and v: usage_oids.append(x509.oid.ExtendedKeyUsageOID.SERVER_AUTH) elif k == "useCodeSigning" and v: usage_oids.append(x509.oid.ExtendedKeyUsageOID.CODE_SIGNING) elif k == "useEmailProtection" and v: usage_oids.append(x509.oid.ExtendedKeyUsageOID.EMAIL_PROTECTION) elif k == "useTimestamping" and v: usage_oids.append(x509.oid.ExtendedKeyUsageOID.TIME_STAMPING) elif k == "useOCSPSigning" and v: usage_oids.append(x509.oid.ExtendedKeyUsageOID.OCSP_SIGNING) elif k == "useEapOverLAN" and v: usage_oids.append(x509.oid.ObjectIdentifier("1.3.6.1.5.5.7.3.14")) elif k == "useEapOverPPP" and v: usage_oids.append(x509.oid.ObjectIdentifier("1.3.6.1.5.5.7.3.13")) elif k == "useSmartCardLogon" and v: usage_oids.append(x509.oid.ObjectIdentifier("1.3.6.1.4.1.311.20.2.2")) else: current_app.logger.warning( "Unable to deserialize ExtendedKeyUsage with name: {key}".format( key=k ) ) return x509.ExtendedKeyUsage(usage_oids)
Example #16
Source File: fields.py From lemur with Apache License 2.0 | 5 votes |
def _serialize(self, value, attr, obj): usages = value._usages usage_list = {} for usage in usages: if usage == x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH: usage_list["useClientAuthentication"] = True elif usage == x509.oid.ExtendedKeyUsageOID.SERVER_AUTH: usage_list["useServerAuthentication"] = True elif usage == x509.oid.ExtendedKeyUsageOID.CODE_SIGNING: usage_list["useCodeSigning"] = True elif usage == x509.oid.ExtendedKeyUsageOID.EMAIL_PROTECTION: usage_list["useEmailProtection"] = True elif usage == x509.oid.ExtendedKeyUsageOID.TIME_STAMPING: usage_list["useTimestamping"] = True elif usage == x509.oid.ExtendedKeyUsageOID.OCSP_SIGNING: usage_list["useOCSPSigning"] = True elif usage.dotted_string == "1.3.6.1.5.5.7.3.14": usage_list["useEapOverLAN"] = True elif usage.dotted_string == "1.3.6.1.5.5.7.3.13": usage_list["useEapOverPPP"] = True elif usage.dotted_string == "1.3.6.1.4.1.311.20.2.2": usage_list["useSmartCardLogon"] = True else: current_app.logger.warning( "Unable to serialize ExtendedKeyUsage with OID: {usage}".format( usage=usage.dotted_string ) ) return usage_list
Example #17
Source File: decode_asn1.py From learn_python3_spider with MIT License | 5 votes |
def _decode_extended_key_usage(backend, sk): sk = backend._ffi.cast("Cryptography_STACK_OF_ASN1_OBJECT *", sk) sk = backend._ffi.gc(sk, backend._lib.sk_ASN1_OBJECT_free) num = backend._lib.sk_ASN1_OBJECT_num(sk) ekus = [] for i in range(num): obj = backend._lib.sk_ASN1_OBJECT_value(sk, i) backend.openssl_assert(obj != backend._ffi.NULL) oid = x509.ObjectIdentifier(_obj2txt(backend, obj)) ekus.append(oid) return x509.ExtendedKeyUsage(ekus)
Example #18
Source File: decode_asn1.py From teleport with Apache License 2.0 | 5 votes |
def _decode_extended_key_usage(backend, sk): sk = backend._ffi.cast("Cryptography_STACK_OF_ASN1_OBJECT *", sk) sk = backend._ffi.gc(sk, backend._lib.sk_ASN1_OBJECT_free) num = backend._lib.sk_ASN1_OBJECT_num(sk) ekus = [] for i in range(num): obj = backend._lib.sk_ASN1_OBJECT_value(sk, i) backend.openssl_assert(obj != backend._ffi.NULL) oid = x509.ObjectIdentifier(_obj2txt(backend, obj)) ekus.append(oid) return x509.ExtendedKeyUsage(ekus)
Example #19
Source File: decode_asn1.py From teleport with Apache License 2.0 | 5 votes |
def _decode_extended_key_usage(backend, sk): sk = backend._ffi.cast("Cryptography_STACK_OF_ASN1_OBJECT *", sk) sk = backend._ffi.gc(sk, backend._lib.sk_ASN1_OBJECT_free) num = backend._lib.sk_ASN1_OBJECT_num(sk) ekus = [] for i in range(num): obj = backend._lib.sk_ASN1_OBJECT_value(sk, i) backend.openssl_assert(obj != backend._ffi.NULL) oid = x509.ObjectIdentifier(_obj2txt(backend, obj)) ekus.append(oid) return x509.ExtendedKeyUsage(ekus)
Example #20
Source File: decode_asn1.py From teleport with Apache License 2.0 | 5 votes |
def _decode_extended_key_usage(backend, sk): sk = backend._ffi.cast("Cryptography_STACK_OF_ASN1_OBJECT *", sk) sk = backend._ffi.gc(sk, backend._lib.sk_ASN1_OBJECT_free) num = backend._lib.sk_ASN1_OBJECT_num(sk) ekus = [] for i in range(num): obj = backend._lib.sk_ASN1_OBJECT_value(sk, i) backend.openssl_assert(obj != backend._ffi.NULL) oid = x509.ObjectIdentifier(_obj2txt(backend, obj)) ekus.append(oid) return x509.ExtendedKeyUsage(ekus)
Example #21
Source File: decode_asn1.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def _decode_extended_key_usage(backend, sk): sk = backend._ffi.cast("Cryptography_STACK_OF_ASN1_OBJECT *", sk) sk = backend._ffi.gc(sk, backend._lib.sk_ASN1_OBJECT_free) num = backend._lib.sk_ASN1_OBJECT_num(sk) ekus = [] for i in range(num): obj = backend._lib.sk_ASN1_OBJECT_value(sk, i) backend.openssl_assert(obj != backend._ffi.NULL) oid = x509.ObjectIdentifier(_obj2txt(backend, obj)) ekus.append(oid) return x509.ExtendedKeyUsage(ekus)
Example #22
Source File: x509.py From oss-ftp with MIT License | 5 votes |
def _decode_extended_key_usage(backend, sk): sk = backend._ffi.cast("Cryptography_STACK_OF_ASN1_OBJECT *", sk) sk = backend._ffi.gc(sk, backend._lib.sk_ASN1_OBJECT_free) num = backend._lib.sk_ASN1_OBJECT_num(sk) ekus = [] for i in range(num): obj = backend._lib.sk_ASN1_OBJECT_value(sk, i) backend.openssl_assert(obj != backend._ffi.NULL) oid = x509.ObjectIdentifier(_obj2txt(backend, obj)) ekus.append(oid) return x509.ExtendedKeyUsage(ekus)
Example #23
Source File: test_local.py From octavia with Apache License 2.0 | 5 votes |
def test_sign_cert(self): # Attempt sign a cert signed_cert = self.cert_generator.sign_cert( csr=self.certificate_signing_request, validity=2 * 365 * 24 * 60 * 60, ca_cert=self.ca_certificate, ca_key=self.ca_private_key, ca_key_pass=self.ca_private_key_passphrase, ca_digest=self.signing_digest ) self.assertIn("-----BEGIN CERTIFICATE-----", signed_cert.decode('ascii')) # Load the cert for specific tests cert = x509.load_pem_x509_certificate( data=signed_cert, backend=backends.default_backend()) # Make sure expiry time is accurate should_expire = (datetime.datetime.utcnow() + datetime.timedelta(seconds=2 * 365 * 24 * 60 * 60)) diff = should_expire - cert.not_valid_after self.assertLess(diff, datetime.timedelta(seconds=10)) # Make sure this is a version 3 X509. self.assertEqual('v3', cert.version.name) # Make sure this cert is marked as Server and Client Cert via the # extended Key Usage extension self.assertIn(x509.oid.ExtendedKeyUsageOID.SERVER_AUTH, cert.extensions.get_extension_for_class( x509.ExtendedKeyUsage).value._usages) self.assertIn(x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH, cert.extensions.get_extension_for_class( x509.ExtendedKeyUsage).value._usages) # Make sure this cert can't sign other certs self.assertFalse(cert.extensions.get_extension_for_class( x509.BasicConstraints).value.ca)
Example #24
Source File: models.py From lemur with Apache License 2.0 | 4 votes |
def extensions(self): # setup default values return_extensions = {"sub_alt_names": {"names": []}} try: for extension in self.parsed_cert.extensions: value = extension.value if isinstance(value, x509.BasicConstraints): return_extensions["basic_constraints"] = value elif isinstance(value, x509.SubjectAlternativeName): return_extensions["sub_alt_names"]["names"] = value elif isinstance(value, x509.ExtendedKeyUsage): return_extensions["extended_key_usage"] = value elif isinstance(value, x509.KeyUsage): return_extensions["key_usage"] = value elif isinstance(value, x509.SubjectKeyIdentifier): return_extensions["subject_key_identifier"] = {"include_ski": True} elif isinstance(value, x509.AuthorityInformationAccess): return_extensions["certificate_info_access"] = {"include_aia": True} elif isinstance(value, x509.AuthorityKeyIdentifier): aki = {"use_key_identifier": False, "use_authority_cert": False} if value.key_identifier: aki["use_key_identifier"] = True if value.authority_cert_issuer: aki["use_authority_cert"] = True return_extensions["authority_key_identifier"] = aki elif isinstance(value, x509.CRLDistributionPoints): return_extensions["crl_distribution_points"] = { "include_crl_dp": value } # TODO: Not supporting custom OIDs yet. https://github.com/Netflix/lemur/issues/665 else: current_app.logger.warning( "Custom OIDs not yet supported for clone operation." ) except InvalidCodepoint as e: sentry.captureException() current_app.logger.warning( "Unable to parse extensions due to underscore in dns name" ) except ValueError as e: sentry.captureException() current_app.logger.warning("Unable to parse") current_app.logger.exception(e) return return_extensions
Example #25
Source File: mkcerts.py From postfix-mta-sts-resolver with MIT License | 4 votes |
def ensure_end_entity_cert(output_dir, names, ca_private_key, ca_cert, end_entity_public_key): name = names[0] end_entity_cert_filename = os.path.join(output_dir, name + '.' + CERT_EXT) if os.path.exists(end_entity_cert_filename): return ca_public_key = ca_private_key.public_key() end_entity_cert = x509.CertificateBuilder().\ subject_name(x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, name), ])).\ issuer_name(ca_cert.subject).\ not_valid_before(datetime.datetime.today() - DAY).\ not_valid_after(datetime.datetime.today() + 3650 * DAY).\ serial_number(x509.random_serial_number()).\ public_key(end_entity_public_key).\ add_extension( x509.BasicConstraints(ca=False, path_length=None), critical=True).\ add_extension( x509.KeyUsage(digital_signature=True, content_commitment=False, key_encipherment=True, data_encipherment=False, key_agreement=False, key_cert_sign=False, crl_sign=False, encipher_only=False, decipher_only=False), critical=True).\ add_extension( x509.ExtendedKeyUsage([ ExtendedKeyUsageOID.SERVER_AUTH, ExtendedKeyUsageOID.CLIENT_AUTH, ]), critical=False).\ add_extension( x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_public_key), critical=False).\ add_extension( x509.SubjectKeyIdentifier.from_public_key(end_entity_public_key), critical=False).\ add_extension( x509.SubjectAlternativeName( [x509.DNSName(name) for name in names] ), critical=False ).\ sign( private_key=ca_private_key, algorithm=hashes.SHA256(), backend=default_backend() ) with open(end_entity_cert_filename, "wb") as end_entity_cert_file: end_entity_cert_file.write( end_entity_cert.public_bytes(encoding=serialization.Encoding.PEM)) return end_entity_cert
Example #26
Source File: test_local.py From octavia with Apache License 2.0 | 4 votes |
def test_sign_cert_passphrase_none(self): # Attempt sign a cert ca_private_key = self.ca_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption() ) signed_cert = self.cert_generator.sign_cert( csr=self.certificate_signing_request, validity=2 * 365 * 24 * 60 * 60, ca_cert=self.ca_certificate, ca_key=ca_private_key, ca_key_pass=None, ca_digest=self.signing_digest ) self.assertIn("-----BEGIN CERTIFICATE-----", signed_cert.decode('ascii')) # Load the cert for specific tests cert = x509.load_pem_x509_certificate( data=signed_cert, backend=backends.default_backend()) # Make sure expiry time is accurate should_expire = (datetime.datetime.utcnow() + datetime.timedelta(seconds=2 * 365 * 24 * 60 * 60)) diff = should_expire - cert.not_valid_after self.assertLess(diff, datetime.timedelta(seconds=10)) # Make sure this is a version 3 X509. self.assertEqual('v3', cert.version.name) # Make sure this cert is marked as Server and Client Cert via the # extended Key Usage extension self.assertIn(x509.oid.ExtendedKeyUsageOID.SERVER_AUTH, cert.extensions.get_extension_for_class( x509.ExtendedKeyUsage).value._usages) self.assertIn(x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH, cert.extensions.get_extension_for_class( x509.ExtendedKeyUsage).value._usages) # Make sure this cert can't sign other certs self.assertFalse(cert.extensions.get_extension_for_class( x509.BasicConstraints).value.ca)