Python cryptography.x509.KeyUsage() Examples

The following are 28 code examples of cryptography.x509.KeyUsage(). 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: validator.py    From magnum with Apache License 2.0 6 votes vote down vote up
def _merge_key_usage(key_usage, allowed_key_usage):
    critical = key_usage.critical
    key_usage_value = key_usage.value

    usages = []
    for usage in extensions.KeyUsages:
        k, v = usage.value
        try:
            value = getattr(key_usage_value, v)
        except ValueError:
            # ValueError is raised when encipher_only/decipher_only is
            # retrieved but key_agreement is False
            value = False
        if value:
            if k not in allowed_key_usage:
                if critical:
                    raise exception.CertificateValidationError(
                        extension=key_usage)
                else:
                    value = False
        usages.append(value)

    rtn = x509.KeyUsage(*usages)
    return x509.Extension(rtn.oid, critical, rtn) 
Example #2
Source File: decode_asn1.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _decode_key_usage(backend, bit_string):
    bit_string = backend._ffi.cast("ASN1_BIT_STRING *", bit_string)
    bit_string = backend._ffi.gc(bit_string, backend._lib.ASN1_BIT_STRING_free)
    get_bit = backend._lib.ASN1_BIT_STRING_get_bit
    digital_signature = get_bit(bit_string, 0) == 1
    content_commitment = get_bit(bit_string, 1) == 1
    key_encipherment = get_bit(bit_string, 2) == 1
    data_encipherment = get_bit(bit_string, 3) == 1
    key_agreement = get_bit(bit_string, 4) == 1
    key_cert_sign = get_bit(bit_string, 5) == 1
    crl_sign = get_bit(bit_string, 6) == 1
    encipher_only = get_bit(bit_string, 7) == 1
    decipher_only = get_bit(bit_string, 8) == 1
    return x509.KeyUsage(
        digital_signature,
        content_commitment,
        key_encipherment,
        data_encipherment,
        key_agreement,
        key_cert_sign,
        crl_sign,
        encipher_only,
        decipher_only
    ) 
Example #3
Source File: decode_asn1.py    From quickstart-redhat-openshift with Apache License 2.0 6 votes vote down vote up
def _decode_key_usage(backend, bit_string):
    bit_string = backend._ffi.cast("ASN1_BIT_STRING *", bit_string)
    bit_string = backend._ffi.gc(bit_string, backend._lib.ASN1_BIT_STRING_free)
    get_bit = backend._lib.ASN1_BIT_STRING_get_bit
    digital_signature = get_bit(bit_string, 0) == 1
    content_commitment = get_bit(bit_string, 1) == 1
    key_encipherment = get_bit(bit_string, 2) == 1
    data_encipherment = get_bit(bit_string, 3) == 1
    key_agreement = get_bit(bit_string, 4) == 1
    key_cert_sign = get_bit(bit_string, 5) == 1
    crl_sign = get_bit(bit_string, 6) == 1
    encipher_only = get_bit(bit_string, 7) == 1
    decipher_only = get_bit(bit_string, 8) == 1
    return x509.KeyUsage(
        digital_signature,
        content_commitment,
        key_encipherment,
        data_encipherment,
        key_agreement,
        key_cert_sign,
        crl_sign,
        encipher_only,
        decipher_only
    ) 
Example #4
Source File: decode_asn1.py    From quickstart-git2s3 with Apache License 2.0 6 votes vote down vote up
def _decode_key_usage(backend, bit_string):
    bit_string = backend._ffi.cast("ASN1_BIT_STRING *", bit_string)
    bit_string = backend._ffi.gc(bit_string, backend._lib.ASN1_BIT_STRING_free)
    get_bit = backend._lib.ASN1_BIT_STRING_get_bit
    digital_signature = get_bit(bit_string, 0) == 1
    content_commitment = get_bit(bit_string, 1) == 1
    key_encipherment = get_bit(bit_string, 2) == 1
    data_encipherment = get_bit(bit_string, 3) == 1
    key_agreement = get_bit(bit_string, 4) == 1
    key_cert_sign = get_bit(bit_string, 5) == 1
    crl_sign = get_bit(bit_string, 6) == 1
    encipher_only = get_bit(bit_string, 7) == 1
    decipher_only = get_bit(bit_string, 8) == 1
    return x509.KeyUsage(
        digital_signature,
        content_commitment,
        key_encipherment,
        data_encipherment,
        key_agreement,
        key_cert_sign,
        crl_sign,
        encipher_only,
        decipher_only
    ) 
Example #5
Source File: decode_asn1.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _decode_key_usage(backend, bit_string):
    bit_string = backend._ffi.cast("ASN1_BIT_STRING *", bit_string)
    bit_string = backend._ffi.gc(bit_string, backend._lib.ASN1_BIT_STRING_free)
    get_bit = backend._lib.ASN1_BIT_STRING_get_bit
    digital_signature = get_bit(bit_string, 0) == 1
    content_commitment = get_bit(bit_string, 1) == 1
    key_encipherment = get_bit(bit_string, 2) == 1
    data_encipherment = get_bit(bit_string, 3) == 1
    key_agreement = get_bit(bit_string, 4) == 1
    key_cert_sign = get_bit(bit_string, 5) == 1
    crl_sign = get_bit(bit_string, 6) == 1
    encipher_only = get_bit(bit_string, 7) == 1
    decipher_only = get_bit(bit_string, 8) == 1
    return x509.KeyUsage(
        digital_signature,
        content_commitment,
        key_encipherment,
        data_encipherment,
        key_agreement,
        key_cert_sign,
        crl_sign,
        encipher_only,
        decipher_only
    ) 
Example #6
Source File: decode_asn1.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _decode_key_usage(backend, bit_string):
    bit_string = backend._ffi.cast("ASN1_BIT_STRING *", bit_string)
    bit_string = backend._ffi.gc(bit_string, backend._lib.ASN1_BIT_STRING_free)
    get_bit = backend._lib.ASN1_BIT_STRING_get_bit
    digital_signature = get_bit(bit_string, 0) == 1
    content_commitment = get_bit(bit_string, 1) == 1
    key_encipherment = get_bit(bit_string, 2) == 1
    data_encipherment = get_bit(bit_string, 3) == 1
    key_agreement = get_bit(bit_string, 4) == 1
    key_cert_sign = get_bit(bit_string, 5) == 1
    crl_sign = get_bit(bit_string, 6) == 1
    encipher_only = get_bit(bit_string, 7) == 1
    decipher_only = get_bit(bit_string, 8) == 1
    return x509.KeyUsage(
        digital_signature,
        content_commitment,
        key_encipherment,
        data_encipherment,
        key_agreement,
        key_cert_sign,
        crl_sign,
        encipher_only,
        decipher_only
    ) 
Example #7
Source File: decode_asn1.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _decode_key_usage(backend, bit_string):
    bit_string = backend._ffi.cast("ASN1_BIT_STRING *", bit_string)
    bit_string = backend._ffi.gc(bit_string, backend._lib.ASN1_BIT_STRING_free)
    get_bit = backend._lib.ASN1_BIT_STRING_get_bit
    digital_signature = get_bit(bit_string, 0) == 1
    content_commitment = get_bit(bit_string, 1) == 1
    key_encipherment = get_bit(bit_string, 2) == 1
    data_encipherment = get_bit(bit_string, 3) == 1
    key_agreement = get_bit(bit_string, 4) == 1
    key_cert_sign = get_bit(bit_string, 5) == 1
    crl_sign = get_bit(bit_string, 6) == 1
    encipher_only = get_bit(bit_string, 7) == 1
    decipher_only = get_bit(bit_string, 8) == 1
    return x509.KeyUsage(
        digital_signature,
        content_commitment,
        key_encipherment,
        data_encipherment,
        key_agreement,
        key_cert_sign,
        crl_sign,
        encipher_only,
        decipher_only
    ) 
Example #8
Source File: x509.py    From oss-ftp with MIT License 6 votes vote down vote up
def _decode_key_usage(backend, bit_string):
    bit_string = backend._ffi.cast("ASN1_BIT_STRING *", bit_string)
    bit_string = backend._ffi.gc(bit_string, backend._lib.ASN1_BIT_STRING_free)
    get_bit = backend._lib.ASN1_BIT_STRING_get_bit
    digital_signature = get_bit(bit_string, 0) == 1
    content_commitment = get_bit(bit_string, 1) == 1
    key_encipherment = get_bit(bit_string, 2) == 1
    data_encipherment = get_bit(bit_string, 3) == 1
    key_agreement = get_bit(bit_string, 4) == 1
    key_cert_sign = get_bit(bit_string, 5) == 1
    crl_sign = get_bit(bit_string, 6) == 1
    encipher_only = get_bit(bit_string, 7) == 1
    decipher_only = get_bit(bit_string, 8) == 1
    return x509.KeyUsage(
        digital_signature,
        content_commitment,
        key_encipherment,
        data_encipherment,
        key_agreement,
        key_cert_sign,
        crl_sign,
        encipher_only,
        decipher_only
    ) 
Example #9
Source File: decode_asn1.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _decode_key_usage(backend, bit_string):
    bit_string = backend._ffi.cast("ASN1_BIT_STRING *", bit_string)
    bit_string = backend._ffi.gc(bit_string, backend._lib.ASN1_BIT_STRING_free)
    get_bit = backend._lib.ASN1_BIT_STRING_get_bit
    digital_signature = get_bit(bit_string, 0) == 1
    content_commitment = get_bit(bit_string, 1) == 1
    key_encipherment = get_bit(bit_string, 2) == 1
    data_encipherment = get_bit(bit_string, 3) == 1
    key_agreement = get_bit(bit_string, 4) == 1
    key_cert_sign = get_bit(bit_string, 5) == 1
    crl_sign = get_bit(bit_string, 6) == 1
    encipher_only = get_bit(bit_string, 7) == 1
    decipher_only = get_bit(bit_string, 8) == 1
    return x509.KeyUsage(
        digital_signature,
        content_commitment,
        key_encipherment,
        data_encipherment,
        key_agreement,
        key_cert_sign,
        crl_sign,
        encipher_only,
        decipher_only
    ) 
Example #10
Source File: decode_asn1.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _decode_key_usage(backend, bit_string):
    bit_string = backend._ffi.cast("ASN1_BIT_STRING *", bit_string)
    bit_string = backend._ffi.gc(bit_string, backend._lib.ASN1_BIT_STRING_free)
    get_bit = backend._lib.ASN1_BIT_STRING_get_bit
    digital_signature = get_bit(bit_string, 0) == 1
    content_commitment = get_bit(bit_string, 1) == 1
    key_encipherment = get_bit(bit_string, 2) == 1
    data_encipherment = get_bit(bit_string, 3) == 1
    key_agreement = get_bit(bit_string, 4) == 1
    key_cert_sign = get_bit(bit_string, 5) == 1
    crl_sign = get_bit(bit_string, 6) == 1
    encipher_only = get_bit(bit_string, 7) == 1
    decipher_only = get_bit(bit_string, 8) == 1
    return x509.KeyUsage(
        digital_signature,
        content_commitment,
        key_encipherment,
        data_encipherment,
        key_agreement,
        key_cert_sign,
        crl_sign,
        encipher_only,
        decipher_only
    ) 
Example #11
Source File: extensions.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def for_builder(self):
        """Return kwargs suitable for a :py:class:`~cg:cryptography.x509.CertificateBuilder`.

        Example::

            >>> kwargs = KeyUsage({'value': ['keyAgreement', 'keyEncipherment']}).for_builder()
            >>> builder.add_extension(**kwargs)  # doctest: +SKIP
        """
        return {'extension': self.extension_type, 'critical': self.critical} 
Example #12
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def cert_key_usage(**kwargs):
    """
    Helper to create x509.KeyUsage object. Function provide defaults (False)
    for unspecified KeyUsage arguments.

    Args:
        x509.KeyUsage keys. If not provided False is used for each arg.

    Return:
        x509.KeyUsage
    """
    required = [
        'digital_signature',
        'content_commitment',
        'key_encipherment',
        'data_encipherment',
        'key_agreement',
        'key_cert_sign',
        'crl_sign',
        'encipher_only',
        'decipher_only',
    ]
    for name in required:
        kwargs.setdefault(name, False)

    return x509.KeyUsage(**kwargs) 
Example #13
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def cert_key_usage(**kwargs):
    """
    Helper to create x509.KeyUsage object. Function provide defaults (False)
    for unspecified KeyUsage arguments.

    Args:
        x509.KeyUsage keys. If not provided False is used for each arg.

    Return:
        x509.KeyUsage
    """
    required = [
        'digital_signature',
        'content_commitment',
        'key_encipherment',
        'data_encipherment',
        'key_agreement',
        'key_cert_sign',
        'crl_sign',
        'encipher_only',
        'decipher_only',
    ]
    for name in required:
        kwargs.setdefault(name, False)

    return x509.KeyUsage(**kwargs) 
Example #14
Source File: tests_extensions.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_auto_add(self):
        # decipher/encipher_only automatically add key_agreement
        self.assertEqual(KeyUsage({'value': ['decipher_only']}),
                         KeyUsage({'value': ['decipher_only', 'key_agreement']}))
        self.assertEqual(KeyUsage({'value': ['encipher_only']}),
                         KeyUsage({'value': ['encipher_only', 'key_agreement']})) 
Example #15
Source File: tests_extensions.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_completeness(self):
        # make sure whe haven't forgotton any keys anywhere
        self.assertEqual(set(KeyUsage.CRYPTOGRAPHY_MAPPING.keys()),
                         set([e[0] for e in KeyUsage.CHOICES])) 
Example #16
Source File: extensions.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def extension_type(self):
        kwargs = {v: (v in self.value) for v in self.KNOWN_VALUES}
        return x509.KeyUsage(**kwargs) 
Example #17
Source File: extensions.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def serialize(self):
        """Serialize this extension to a string in a way that it can be passed to a constructor again.

        For example, this should always be True::

            >>> ku = KeyUsage({'value': ['keyAgreement', 'keyEncipherment']})
            >>> ku == KeyUsage(ku.serialize())
            True
        """

        return {
            'critical': self.critical,
            'value': self.value,
        } 
Example #18
Source File: operations.py    From magnum with Apache License 2.0 5 votes vote down vote up
def _build_ca_extentions():
    # Certificate Sign is enabled
    key_usage = x509.KeyUsage(False, False, False, False, False, True, False,
                              False, False)
    key_usage = x509.Extension(key_usage.oid, True, key_usage)

    basic_constraints = x509.BasicConstraints(ca=True, path_length=0)
    basic_constraints = x509.Extension(basic_constraints.oid, True,
                                       basic_constraints)

    return [basic_constraints, key_usage] 
Example #19
Source File: local.py    From octavia with Apache License 2.0 5 votes vote down vote up
def _generate_csr(cls, cn, private_key, passphrase=None):
        pk = serialization.load_pem_private_key(
            data=private_key, password=passphrase,
            backend=backends.default_backend())
        csr = x509.CertificateSigningRequestBuilder().subject_name(
            x509.Name([
                x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, cn),
            ])
        )
        csr = csr.add_extension(
            x509.BasicConstraints(
                ca=False,
                path_length=None
            ),
            critical=True
        )
        csr = csr.add_extension(
            x509.KeyUsage(
                digital_signature=True,
                key_encipherment=True,
                data_encipherment=True,
                key_agreement=True,
                content_commitment=False,
                key_cert_sign=False,
                crl_sign=False,
                encipher_only=False,
                decipher_only=False
            ),
            critical=True
        )
        csr = csr.add_extension(
            x509.SubjectAlternativeName([x509.DNSName(cn)]),
            critical=False
        )
        signed_csr = csr.sign(
            pk,
            getattr(hashes, CONF.certificates.signing_digest.upper())(),
            backends.default_backend())
        return signed_csr.public_bytes(serialization.Encoding.PEM) 
Example #20
Source File: test_sign.py    From magnum with Apache License 2.0 5 votes vote down vote up
def test_generate_ca_certificate_set_extentions_as_ca(self):
        cert, _ = self._generate_ca_certificate(self.issuer_name)

        key_usage = c_x509.KeyUsage(False, False, False, False, False, True,
                                    False, False, False)
        key_usage = c_x509.Extension(key_usage.oid, True, key_usage)
        basic_constraints = c_x509.BasicConstraints(ca=True, path_length=0)
        basic_constraints = c_x509.Extension(basic_constraints.oid, True,
                                             basic_constraints)

        self.assertIn(key_usage, cert.extensions)
        self.assertIn(basic_constraints, cert.extensions) 
Example #21
Source File: test_sign.py    From magnum with Apache License 2.0 5 votes vote down vote up
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 #22
Source File: test_validator.py    From magnum with Apache License 2.0 5 votes vote down vote up
def test_merge_key_usage_disallowed_but_not_critical(self):
        key_usage = self._build_key_usage()
        expected = c_x509.KeyUsage(
            True, False, False, False, False, False, False, False, False)
        expected = c_x509.Extension(expected.oid, False, expected)

        self.assertEqual(expected,
                         v._merge_key_usage(key_usage,
                                            ['Digital Signature'])) 
Example #23
Source File: test_validator.py    From magnum with Apache License 2.0 5 votes vote down vote up
def _build_key_usage(self, critical=False):
        # Digital Signature and Key Encipherment are enabled
        key_usage = c_x509.KeyUsage(
            True, False, True, False, False, False, False, False, False)
        return c_x509.Extension(key_usage.oid, critical, key_usage) 
Example #24
Source File: mkcerts.py    From postfix-mta-sts-resolver with MIT License 4 votes vote down vote up
def ensure_ca_cert(output_dir, ca_private_key):
    ca_cert_filename = os.path.join(output_dir, CA_FILENAME + '.' + CERT_EXT)
    ca_public_key = ca_private_key.public_key()
    if os.path.exists(ca_cert_filename):
        with open(ca_cert_filename, "rb") as ca_cert_file:
            ca_cert = x509.load_pem_x509_certificate(
                ca_cert_file.read(),
                backend=default_backend())
    else:
        iname = x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, 'Test CA'),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME,
                'postfix-mta-sts-resolver dev'),
            x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME,
                'postfix-mta-sts-resolver testsuite'),
        ])
        ca_cert = x509.CertificateBuilder().\
            subject_name(iname).\
            issuer_name(iname).\
            not_valid_before(datetime.datetime.today() - DAY).\
            not_valid_after(datetime.datetime.today() + 3650 * DAY).\
            serial_number(x509.random_serial_number()).\
            public_key(ca_public_key).\
            add_extension(
                x509.BasicConstraints(ca=True, path_length=None),
                critical=True).\
            add_extension(
                x509.KeyUsage(digital_signature=False,
                              content_commitment=False,
                              key_encipherment=False,
                              data_encipherment=False,
                              key_agreement=False,
                              key_cert_sign=True,
                              crl_sign=True,
                              encipher_only=False,
                              decipher_only=False),
                critical=True).\
            add_extension(
                x509.SubjectKeyIdentifier.from_public_key(ca_public_key),
                critical=False).\
            sign(
                private_key=ca_private_key,
                algorithm=hashes.SHA256(),
                backend=default_backend()
            )
        with open(ca_cert_filename, "wb") as ca_cert_file:
            ca_cert_file.write(
                ca_cert.public_bytes(encoding=serialization.Encoding.PEM))
    assert isinstance(ca_cert, x509.Certificate)
    return ca_cert 
Example #25
Source File: mkcerts.py    From postfix-mta-sts-resolver with MIT License 4 votes vote down vote up
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: fields.py    From lemur with Apache License 2.0 4 votes vote down vote up
def _deserialize(self, value, attr, data):
        keyusages = {
            "digital_signature": False,
            "content_commitment": False,
            "key_encipherment": False,
            "data_encipherment": False,
            "key_agreement": False,
            "key_cert_sign": False,
            "crl_sign": False,
            "encipher_only": False,
            "decipher_only": False,
        }

        for k, v in value.items():
            if k == "useDigitalSignature":
                keyusages["digital_signature"] = v

            elif k == "useNonRepudiation":
                keyusages["content_commitment"] = v

            elif k == "useKeyEncipherment":
                keyusages["key_encipherment"] = v

            elif k == "useDataEncipherment":
                keyusages["data_encipherment"] = v

            elif k == "useKeyCertSign":
                keyusages["key_cert_sign"] = v

            elif k == "useCRLSign":
                keyusages["crl_sign"] = v

            elif k == "useKeyAgreement":
                keyusages["key_agreement"] = v

            elif k == "useEncipherOnly" and v:
                keyusages["encipher_only"] = True
                keyusages["key_agreement"] = True

            elif k == "useDecipherOnly" and v:
                keyusages["decipher_only"] = True
                keyusages["key_agreement"] = True

        if keyusages["encipher_only"] and keyusages["decipher_only"]:
            raise ValidationError(
                "A certificate cannot have both Encipher Only and Decipher Only Extended Key Usages."
            )

        return x509.KeyUsage(
            digital_signature=keyusages["digital_signature"],
            content_commitment=keyusages["content_commitment"],
            key_encipherment=keyusages["key_encipherment"],
            data_encipherment=keyusages["data_encipherment"],
            key_agreement=keyusages["key_agreement"],
            key_cert_sign=keyusages["key_cert_sign"],
            crl_sign=keyusages["crl_sign"],
            encipher_only=keyusages["encipher_only"],
            decipher_only=keyusages["decipher_only"],
        ) 
Example #27
Source File: models.py    From lemur with Apache License 2.0 4 votes vote down vote up
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 #28
Source File: _certificate_generator.py    From webviz-config with MIT License 4 votes vote down vote up
def create_certificate(directory: str) -> None:
    ca_directory = user_data_dir()
    ca_key_path = os.path.join(ca_directory, CA_KEY_FILENAME)
    ca_crt_path = os.path.join(ca_directory, CA_CRT_FILENAME)

    server_key_path = os.path.join(directory, SERVER_KEY_FILENAME)
    server_crt_path = os.path.join(directory, SERVER_CRT_FILENAME)

    if not os.path.isfile(ca_key_path) or not os.path.isfile(ca_crt_path):
        raise RuntimeError(
            "Could not find CA key and certificate. Please "
            'run the command "webviz certificate --auto-install" and '
            "try again"
        )

    with open(ca_key_path, "rb") as filehandle:
        ca_key = serialization.load_pem_private_key(
            data=filehandle.read(), password=None, backend=default_backend()
        )

    with open(ca_crt_path, "rb") as filehandle:
        ca_crt = x509.load_pem_x509_certificate(
            data=filehandle.read(), backend=default_backend()
        )

    server_key = create_key(server_key_path)

    crt = (
        certificate_template(NAME, ca_crt.subject, server_key.public_key())
        .add_extension(
            critical=True,
            extension=x509.KeyUsage(
                digital_signature=True,
                key_encipherment=True,
                content_commitment=True,
                data_encipherment=False,
                key_agreement=False,
                encipher_only=False,
                decipher_only=False,
                key_cert_sign=False,
                crl_sign=False,
            ),
        )
        .add_extension(
            critical=False,
            extension=x509.AuthorityKeyIdentifier.from_issuer_public_key(
                ca_key.public_key()
            ),
        )
        .sign(private_key=ca_key, algorithm=hashes.SHA256(), backend=default_backend())
    )

    with open(server_crt_path, "wb") as filehandle:
        filehandle.write(crt.public_bytes(encoding=serialization.Encoding.PEM))