Python cryptography.x509.BasicConstraints() Examples

The following are 30 code examples of cryptography.x509.BasicConstraints(). 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 vote down vote up
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: create_x509_chain_crypto.py    From azure-iot-sdk-python with MIT License 7 votes vote down vote up
def create_cert_builder(subject, issuer_name, public_key, days=365, is_ca=False):
    """
    The method to create a builder for all types of certificates.
    :param subject: The subject of the certificate.
    :param issuer_name: The name of the issuer.
    :param public_key: The public key of the certificate.
    :param days: The number of days for which the certificate is valid. The default is 1 year or 365 days.
    :param is_ca: Boolean to indicate if a cert is ca or non ca.
    :return: The certificate builder.
    :rtype: :class `x509.CertificateBuilder`
    """
    builder = x509.CertificateBuilder()

    builder = builder.subject_name(subject)
    builder = builder.issuer_name(issuer_name)
    builder = builder.public_key(public_key)
    builder = builder.not_valid_before(datetime.today())

    builder = builder.not_valid_after(datetime.today() + timedelta(days=days))
    builder = builder.serial_number(int(uuid.uuid4()))
    builder = builder.add_extension(
        x509.BasicConstraints(ca=is_ca, path_length=None), critical=True
    )
    return builder 
Example #3
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 #4
Source File: tls.py    From dcos-e2e with Apache License 2.0 6 votes vote down vote up
def ca_cert_builder(
        public_key,
        common_name="Root CA",
        issuer=None,
        basic_constraints=x509.BasicConstraints(
            ca=True, path_length=None),
        key_usage=cert_key_usage(
            key_cert_sign=True),
        subject_alternative_names=None,
        not_valid_before=None,
        not_valid_after=None,
        valid_days=3650,
        ):
    return cert_builder(
        public_key=public_key,
        common_name=common_name,
        issuer=issuer,
        basic_constraints=basic_constraints,
        key_usage=key_usage,
        subject_alternative_names=subject_alternative_names,
        not_valid_before=not_valid_before,
        not_valid_after=not_valid_after,
        valid_days=valid_days,
    ) 
Example #5
Source File: tls.py    From dcos-e2e with Apache License 2.0 6 votes vote down vote up
def ca_cert_builder(
        public_key,
        common_name="Root CA",
        issuer=None,
        basic_constraints=x509.BasicConstraints(
            ca=True, path_length=None),
        key_usage=cert_key_usage(
            key_cert_sign=True),
        subject_alternative_names=None,
        not_valid_before=None,
        not_valid_after=None,
        valid_days=3650,
        ):
    return cert_builder(
        public_key=public_key,
        common_name=common_name,
        issuer=issuer,
        basic_constraints=basic_constraints,
        key_usage=key_usage,
        subject_alternative_names=subject_alternative_names,
        not_valid_before=not_valid_before,
        not_valid_after=not_valid_after,
        valid_days=valid_days,
    ) 
Example #6
Source File: create_certificates.py    From PyKMIP with Apache License 2.0 6 votes vote down vote up
def create_self_signed_certificate(subject_name, private_key, days_valid=365):
    subject = x509.Name([
        x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Test, Inc."),
        x509.NameAttribute(x509.NameOID.COMMON_NAME, subject_name)
    ])
    certificate = x509.CertificateBuilder().subject_name(
        subject
    ).issuer_name(
        subject
    ).public_key(
        private_key.public_key()
    ).serial_number(
        x509.random_serial_number()
    ).add_extension(
        x509.BasicConstraints(ca=True, path_length=None), critical=True
    ).not_valid_before(
        datetime.datetime.utcnow()
    ).not_valid_after(
        datetime.datetime.utcnow() + datetime.timedelta(days=days_valid)
    ).sign(private_key, hashes.SHA256(), backends.default_backend())

    return certificate 
Example #7
Source File: dep.py    From zentral with Apache License 2.0 5 votes vote down vote up
def build_dep_token_certificate(dep_token):
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )
    public_key = private_key.public_key()
    builder = x509.CertificateBuilder()
    builder = builder.subject_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u'zentral-dep-token-{}'.format(dep_token.pk)),
    ]))
    builder = builder.issuer_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u'zentral'),
    ]))
    now = timezone.now()
    one_day = datetime.timedelta(days=1)
    builder = builder.not_valid_before(now - one_day)
    builder = builder.not_valid_after(now + 2 * one_day)
    builder = builder.serial_number(x509.random_serial_number())
    builder = builder.public_key(public_key)
    builder = builder.add_extension(
        x509.BasicConstraints(ca=False, path_length=None), critical=True,
    )
    certificate = builder.sign(
        private_key=private_key, algorithm=hashes.SHA256(),
        backend=default_backend()
    )
    return certificate, private_key 
Example #8
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 #9
Source File: models.py    From commandment with MIT License 5 votes vote down vote up
def create(cls, common_name: str = 'COMMANDMENT-CA', key_size=2048):
        ca = cls()
        ca.common_name = common_name
        name = x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, common_name),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment')
        ])

        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=key_size,
            backend=default_backend(),
        )
        ca.rsa_private_key = RSAPrivateKey.from_crypto(private_key)
        db.session.add(ca.rsa_private_key)

        certificate = x509.CertificateBuilder().subject_name(
            name
        ).issuer_name(
            name
        ).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=365)
        ).add_extension(
            x509.BasicConstraints(ca=True, path_length=None), True
        ).sign(private_key, hashes.SHA256(), default_backend())

        ca_certificate_model = CACertificate.from_crypto(certificate)
        ca_certificate_model.rsa_private_key = ca.rsa_private_key
        ca.certificate = ca_certificate_model

        db.session.add(ca)
        db.session.commit()

        return ca 
Example #10
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 
Example #11
Source File: extensions.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def extension_type(self):
        return x509.BasicConstraints(ca=self.value['ca'], path_length=self.value['pathlen']) 
Example #12
Source File: tests_extensions.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_from_extension(self):
        ext = x509.Extension(oid=x509.ExtensionOID.BASIC_CONSTRAINTS, critical=True,
                             value=x509.BasicConstraints(ca=True, path_length=3))
        with self.assertRaises(NotImplementedError):
            Extension(ext) 
Example #13
Source File: tests_extensions.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_setters(self):
        ext = BasicConstraints({'value': {'ca': False, 'pathlen': None}})
        self.assertFalse(ext.ca)
        self.assertIsNone(ext.pathlen)

        ext.ca = True
        ext.pathlen = 3
        self.assertTrue(ext.ca)
        self.assertEqual(ext.pathlen, 3) 
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_invalid_pathlen(self):
        with self.assertRaisesRegex(ValueError, r'^Could not parse pathlen: "foo"$'):
            BasicConstraints({'value': {'ca': True, 'pathlen': 'foo'}})

        with self.assertRaisesRegex(ValueError, r'^Could not parse pathlen: ""$'):
            BasicConstraints({'value': {'ca': True, 'pathlen': ''}})

        with self.assertRaisesRegex(ValueError, r'^Could not parse pathlen: "foobar"$'):
            BasicConstraints({'value': {'ca': True, 'pathlen': 'foobar'}}) 
Example #15
Source File: _utilities.py    From sros2 with Apache License 2.0 5 votes vote down vote up
def build_key_and_cert(subject_name, *, ca=False, ca_key=None, issuer_name=''):
    if not issuer_name:
        issuer_name = subject_name

    # DDS-Security section 9.3.1 calls for prime256v1, for which SECP256R1 is an alias
    private_key = ec.generate_private_key(ec.SECP256R1, cryptography_backend())
    if not ca_key:
        ca_key = private_key

    if ca:
        extension = x509.BasicConstraints(ca=True, path_length=1)
    else:
        extension = x509.BasicConstraints(ca=False, path_length=None)

    utcnow = datetime.datetime.utcnow()
    builder = x509.CertificateBuilder(
        ).issuer_name(
            issuer_name
        ).serial_number(
            x509.random_serial_number()
        ).not_valid_before(
            # Using a day earlier here to prevent Connext (5.3.1) from complaining
            # when extracting it from the permissions file and thinking it's in the future
            # https://github.com/ros2/ci/pull/436#issuecomment-624874296
            utcnow - datetime.timedelta(days=1)
        ).not_valid_after(
            # TODO: This should not be hard-coded
            utcnow + datetime.timedelta(days=3650)
        ).public_key(
            private_key.public_key()
        ).subject_name(
            subject_name
        ).add_extension(
            extension, critical=ca
        )
    cert = builder.sign(ca_key, hashes.SHA256(), cryptography_backend())

    return (cert, private_key) 
Example #16
Source File: test_create_key.py    From sros2 with Apache License 2.0 5 votes vote down vote up
def test_cert_pem(enclave_keys_dir):
    cert = _utilities.load_cert(enclave_keys_dir / 'cert.pem')
    check_common_name(cert.subject, u'/test_enclave')
    check_common_name(cert.issuer, _keystore._DEFAULT_COMMON_NAME)

    # Verify that the hash algorithm is as expected
    assert isinstance(cert.signature_hash_algorithm, hashes.SHA256)

    # Verify the cert is valid for the expected timespan
    utcnow = datetime.datetime.utcnow()

    # Using a day earlier here to prevent Connext (5.3.1) from complaining
    # when extracting it from the permissions file and thinking it's in the future
    # https://github.com/ros2/ci/pull/436#issuecomment-624874296
    assert _datetimes_are_close(cert.not_valid_before, utcnow - datetime.timedelta(days=1))
    assert _datetimes_are_close(cert.not_valid_after, utcnow + datetime.timedelta(days=3650))

    # Verify that the cert ensures this key cannot be used to sign others as a CA
    assert len(cert.extensions) == 1
    extension = cert.extensions[0]
    assert extension.critical is False
    value = extension.value
    assert isinstance(value, x509.BasicConstraints)
    assert value.ca is False
    assert value.path_length is None

    # Verify this cert is indeed signed by the keystore CA
    signatory = _utilities.load_cert(enclave_keys_dir / 'identity_ca.cert.pem')
    assert verify_signature(cert, signatory) 
Example #17
Source File: decode_asn1.py    From quickstart-git2s3 with Apache License 2.0 5 votes vote down vote up
def _decode_basic_constraints(backend, bc_st):
    basic_constraints = backend._ffi.cast("BASIC_CONSTRAINTS *", bc_st)
    basic_constraints = backend._ffi.gc(
        basic_constraints, backend._lib.BASIC_CONSTRAINTS_free
    )
    # The byte representation of an ASN.1 boolean true is \xff. OpenSSL
    # chooses to just map this to its ordinal value, so true is 255 and
    # false is 0.
    ca = basic_constraints.ca == 255
    path_length = _asn1_integer_to_int_or_none(
        backend, basic_constraints.pathlen
    )

    return x509.BasicConstraints(ca, path_length) 
Example #18
Source File: test_ssl.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def ca_file(tmpdir):
    """
    Create a valid PEM file with CA certificates and return the path.
    """
    key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )
    public_key = key.public_key()

    builder = x509.CertificateBuilder()
    builder = builder.subject_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u"pyopenssl.org"),
    ]))
    builder = builder.issuer_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u"pyopenssl.org"),
    ]))
    one_day = datetime.timedelta(1, 0, 0)
    builder = builder.not_valid_before(datetime.datetime.today() - one_day)
    builder = builder.not_valid_after(datetime.datetime.today() + one_day)
    builder = builder.serial_number(int(uuid.uuid4()))
    builder = builder.public_key(public_key)
    builder = builder.add_extension(
        x509.BasicConstraints(ca=True, path_length=None), critical=True,
    )

    certificate = builder.sign(
        private_key=key, algorithm=hashes.SHA256(),
        backend=default_backend()
    )

    ca_file = tmpdir.join("test.pem")
    ca_file.write_binary(
        certificate.public_bytes(
            encoding=serialization.Encoding.PEM,
        )
    )

    return str(ca_file).encode("ascii") 
Example #19
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def external_cert_builder(
        public_key,
        common_name="Web Server Cert",
        issuer=None,
        basic_constraints=x509.BasicConstraints(
            ca=False, path_length=None),
        key_usage=cert_key_usage(
            key_cert_sign=False, digital_signature=True, key_encipherment=True),
        extended_key_usage=cert_extended_key_usage(server_auth=True),
        subject_alternative_names=[
            x509.DNSName('maryna.example.com'),
        ],
        not_valid_before=None,
        not_valid_after=None,
        valid_days=3650,
        ):
    return cert_builder(
        public_key=public_key,
        common_name=common_name,
        issuer=issuer,
        basic_constraints=basic_constraints,
        key_usage=key_usage,
        extended_key_usage=extended_key_usage,
        subject_alternative_names=subject_alternative_names,
        not_valid_before=not_valid_before,
        not_valid_after=not_valid_after,
        valid_days=valid_days,
    ) 
Example #20
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def external_cert_builder(
        public_key,
        common_name="Web Server Cert",
        issuer=None,
        basic_constraints=x509.BasicConstraints(
            ca=False, path_length=None),
        key_usage=cert_key_usage(
            key_cert_sign=False, digital_signature=True, key_encipherment=True),
        extended_key_usage=cert_extended_key_usage(server_auth=True),
        subject_alternative_names=[
            x509.DNSName('maryna.example.com'),
        ],
        not_valid_before=None,
        not_valid_after=None,
        valid_days=3650,
        ):
    return cert_builder(
        public_key=public_key,
        common_name=common_name,
        issuer=issuer,
        basic_constraints=basic_constraints,
        key_usage=key_usage,
        extended_key_usage=extended_key_usage,
        subject_alternative_names=subject_alternative_names,
        not_valid_before=not_valid_before,
        not_valid_after=not_valid_after,
        valid_days=valid_days,
    ) 
Example #21
Source File: cert.py    From lxd-image-server with Apache License 2.0 5 votes vote down vote up
def generate_cert(path):
    key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )

    name = x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u"lxd-image-server.localhost")])

    now = datetime.utcnow()
    basic_contraints = x509.BasicConstraints(ca=True, path_length=0)
    ip_address = get_address()
    cert = (
        x509.CertificateBuilder()
        .subject_name(name)
        .issuer_name(name)
        .public_key(key.public_key())
        .serial_number(1000)
        .not_valid_before(now - timedelta(days=10))
        .not_valid_after(now + timedelta(days=10 * 365))
        .add_extension(basic_contraints, False)
        .add_extension(
            x509.SubjectAlternativeName([
                x509.DNSName(u"lxd.localhost")]),
            critical=False,)
        .sign(key, hashes.SHA256(), default_backend()))

    with open(join(path, KEY_FILE), 'wb') as f:
        f.write(key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption(),))

    with open(join(path, CERT_FILE), 'wb') as f:
        f.write(cert.public_bytes(serialization.Encoding.PEM)) 
Example #22
Source File: decode_asn1.py    From quickstart-redhat-openshift with Apache License 2.0 5 votes vote down vote up
def _decode_basic_constraints(backend, bc_st):
    basic_constraints = backend._ffi.cast("BASIC_CONSTRAINTS *", bc_st)
    basic_constraints = backend._ffi.gc(
        basic_constraints, backend._lib.BASIC_CONSTRAINTS_free
    )
    # The byte representation of an ASN.1 boolean true is \xff. OpenSSL
    # chooses to just map this to its ordinal value, so true is 255 and
    # false is 0.
    ca = basic_constraints.ca == 255
    path_length = _asn1_integer_to_int_or_none(
        backend, basic_constraints.pathlen
    )

    return x509.BasicConstraints(ca, path_length) 
Example #23
Source File: decode_asn1.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _decode_basic_constraints(backend, bc_st):
    basic_constraints = backend._ffi.cast("BASIC_CONSTRAINTS *", bc_st)
    basic_constraints = backend._ffi.gc(
        basic_constraints, backend._lib.BASIC_CONSTRAINTS_free
    )
    # The byte representation of an ASN.1 boolean true is \xff. OpenSSL
    # chooses to just map this to its ordinal value, so true is 255 and
    # false is 0.
    ca = basic_constraints.ca == 255
    path_length = _asn1_integer_to_int_or_none(
        backend, basic_constraints.pathlen
    )

    return x509.BasicConstraints(ca, path_length) 
Example #24
Source File: sslutils.py    From rpaas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_admin_crt(config, host):
    private_key = generate_key()
    public_key = private_key.public_key()
    one_day = datetime.timedelta(1, 0, 0)
    ca_cert = config.get("CA_CERT", None)
    ca_key = config.get("CA_KEY", None)
    cert_expiration = config.get("CERT_ADMIN_EXPIRE", 1825)
    if not ca_cert or not ca_key:
        raise Exception('CA_CERT or CA_KEY not defined')
    ca_key = serialization.load_pem_private_key(str(ca_key), password=None, backend=default_backend())
    ca_cert = x509.load_pem_x509_certificate(str(ca_cert), backend=default_backend())
    builder = x509.CertificateBuilder()
    builder = builder.subject_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, host),
    ]))
    builder = builder.issuer_name(ca_cert.subject)
    builder = builder.not_valid_before(datetime.datetime.today() - one_day)
    builder = builder.not_valid_after(datetime.datetime.today() + datetime.timedelta(days=cert_expiration))
    builder = builder.serial_number(x509.random_serial_number())
    builder = builder.public_key(public_key)
    builder = builder.add_extension(
        x509.SubjectAlternativeName(
            [x509.IPAddress(ipaddress.IPv4Address(host))]
        ),
        critical=False
    )
    builder = builder.add_extension(
        x509.BasicConstraints(ca=False, path_length=None), critical=True,
    )
    certificate = builder.sign(
        private_key=ca_key, algorithm=hashes.SHA256(),
        backend=default_backend()
    )
    private_key = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption(),
        )
    certificate = certificate.public_bytes(serialization.Encoding.PEM)
    return private_key, certificate 
Example #25
Source File: default.py    From rpaas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def download_crt(self, key=None):
        one_day = datetime.timedelta(1, 0, 0)

        private_key = serialization.load_pem_private_key(
            key,
            password=None,
            backend=default_backend()
        )

        public_key = private_key.public_key()

        builder = x509.CertificateBuilder()
        builder = builder.subject_name(x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, self.domain),
        ]))
        builder = builder.issuer_name(x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, self.domain),
        ]))
        builder = builder.not_valid_before(datetime.datetime.today() - one_day)
        builder = builder.not_valid_after(datetime.datetime(2018, 8, 2))
        builder = builder.serial_number(int(uuid.uuid4()))
        builder = builder.public_key(public_key)
        builder = builder.add_extension(
            x509.BasicConstraints(ca=False, path_length=None), critical=True,
        )
        certificate = builder.sign(
            private_key=private_key, algorithm=hashes.SHA256(),
            backend=default_backend()
        )

        return certificate.public_bytes(serialization.Encoding.PEM) 
Example #26
Source File: decode_asn1.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _decode_basic_constraints(backend, bc_st):
    basic_constraints = backend._ffi.cast("BASIC_CONSTRAINTS *", bc_st)
    basic_constraints = backend._ffi.gc(
        basic_constraints, backend._lib.BASIC_CONSTRAINTS_free
    )
    # The byte representation of an ASN.1 boolean true is \xff. OpenSSL
    # chooses to just map this to its ordinal value, so true is 255 and
    # false is 0.
    ca = basic_constraints.ca == 255
    path_length = _asn1_integer_to_int_or_none(
        backend, basic_constraints.pathlen
    )

    return x509.BasicConstraints(ca, path_length) 
Example #27
Source File: test_local.py    From octavia with Apache License 2.0 5 votes vote down vote up
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 #28
Source File: _certificate_generator.py    From webviz-config with MIT License 5 votes vote down vote up
def certificate_template(
    subject: x509.name.Name,
    issuer: x509.name.Name,
    public_key: x509.name.Name,
    certauthority: bool = False,
) -> x509.base.CertificateBuilder:

    if certauthority:
        not_valid_after = datetime.datetime.utcnow() + datetime.timedelta(days=365 * 10)

    else:  # shorter valid length for on-the-fly certificates
        not_valid_after = datetime.datetime.utcnow() + datetime.timedelta(days=7)

    return (
        x509.CertificateBuilder()
        .subject_name(subject)
        .issuer_name(issuer)
        .public_key(public_key)
        .serial_number(x509.random_serial_number())
        .not_valid_before(datetime.datetime.utcnow())
        .not_valid_after(not_valid_after)
        .add_extension(
            x509.SubjectAlternativeName([x509.DNSName("localhost")]), critical=True
        )
        .add_extension(
            x509.BasicConstraints(ca=certauthority, path_length=None), critical=True
        )
    ) 
Example #29
Source File: x509.py    From oss-ftp with MIT License 5 votes vote down vote up
def _decode_basic_constraints(backend, bc_st):
    basic_constraints = backend._ffi.cast("BASIC_CONSTRAINTS *", bc_st)
    basic_constraints = backend._ffi.gc(
        basic_constraints, backend._lib.BASIC_CONSTRAINTS_free
    )
    # The byte representation of an ASN.1 boolean true is \xff. OpenSSL
    # chooses to just map this to its ordinal value, so true is 255 and
    # false is 0.
    ca = basic_constraints.ca == 255
    if basic_constraints.pathlen == backend._ffi.NULL:
        path_length = None
    else:
        path_length = backend._asn1_integer_to_int(basic_constraints.pathlen)

    return x509.BasicConstraints(ca, path_length) 
Example #30
Source File: decode_asn1.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _decode_basic_constraints(backend, bc_st):
    basic_constraints = backend._ffi.cast("BASIC_CONSTRAINTS *", bc_st)
    basic_constraints = backend._ffi.gc(
        basic_constraints, backend._lib.BASIC_CONSTRAINTS_free
    )
    # The byte representation of an ASN.1 boolean true is \xff. OpenSSL
    # chooses to just map this to its ordinal value, so true is 255 and
    # false is 0.
    ca = basic_constraints.ca == 255
    path_length = _asn1_integer_to_int_or_none(
        backend, basic_constraints.pathlen
    )

    return x509.BasicConstraints(ca, path_length)