Esempio n. 1
0
    def signCert(self, csr, server=False, valid_from=None, valid_to=None):

        if valid_from is None:
            valid_from = datetime.datetime.now() - ONE_DAY

        if valid_to is None:
            valid_to = datetime.datetime.now() + datetime.timedelta(days=365)

        if valid_to > self.cert.not_valid_after:
            valid_to = self.cert.not_valid_after

        cert = x509.CertificateBuilder() \
            .subject_name(csr.subject) \
            .serial_number(self.nextSequence()) \
            .not_valid_before(valid_from) \
            .not_valid_after(valid_to) \
            .issuer_name(self.cert.subject) \
            .public_key(csr.public_key())

        if server:
            cert = cert.add_extension(
                x509.BasicConstraints(ca=False, path_length=None),
                critical=True,
            )
            cert = cert.add_extension(
                x509.ExtendedKeyUsage([x509.ExtendedKeyUsageOID.SERVER_AUTH]),
                critical=False,
            )
        else:
            cert = cert.add_extension(
                x509.ExtendedKeyUsage([x509.ExtendedKeyUsageOID.CLIENT_AUTH]),
                critical=False,
            )

        return self.sign(cert)
def generate_csr(common_name, server=False):
    """Issue certificate signing request for server and client."""
    # Generate private key
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=3072,
        backend=default_backend()
    )

    builder = x509.CertificateSigningRequestBuilder()
    subject = x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, common_name),
    ])
    builder = builder.subject_name(subject)
    builder = builder.add_extension(
        x509.BasicConstraints(ca=False, path_length=None), critical=True,
    )
    if server:
        builder = builder.add_extension(
            x509.ExtendedKeyUsage([x509.ExtendedKeyUsageOID.SERVER_AUTH]),
            critical=True
        )

    else:
        builder = builder.add_extension(
            x509.ExtendedKeyUsage([x509.ExtendedKeyUsageOID.CLIENT_AUTH]),
            critical=True
        )

    builder = builder.add_extension(
        x509.KeyUsage(
            digital_signature=True,
            key_encipherment=True,
            data_encipherment=False,
            key_agreement=False,
            content_commitment=False,
            key_cert_sign=False,
            crl_sign=False,
            encipher_only=False,
            decipher_only=False
        ),
        critical=True
    )

    builder = builder.add_extension(
        x509.SubjectAlternativeName([x509.DNSName(common_name)]),
        critical=False
    )

    # Sign the CSR
    csr = builder.sign(
        private_key=private_key, algorithm=hashes.SHA256(),
        backend=default_backend()
    )

    return private_key, csr
Esempio n. 3
0
def _get_certificate_extensions(is_server, is_ca):
    """
    Returns a list that contains all of the certificate extensions based on the
    certificate type.
    :return: List[x509.Extension]
    """
    extensions = []

    # path length for CA is 0
    path_length = None
    if is_ca:
        path_length = 0

    # BasicConstraints
    extensions.append(
        x509.Extension(oid=x509.BasicConstraints.oid,
                       critical=True,
                       value=x509.BasicConstraints(is_ca, path_length)))

    # KeyUsage
    extensions.append(
        x509.Extension(oid=x509.KeyUsage.oid,
                       critical=True,
                       value=x509.KeyUsage(digital_signature=True,
                                           content_commitment=False,
                                           key_encipherment=is_server,
                                           data_encipherment=False,
                                           key_agreement=True,
                                           key_cert_sign=is_ca,
                                           crl_sign=is_ca,
                                           encipher_only=False,
                                           decipher_only=False)))

    # add server certificate and client certificate specific extensions
    if is_server:
        extensions.append(
            x509.Extension(oid=x509.ExtendedKeyUsage.oid,
                           critical=True,
                           value=x509.ExtendedKeyUsage([
                               x509.ExtendedKeyUsageOID.SERVER_AUTH,
                           ])))
    elif not is_ca:
        # if this is not a server certificate and not a certificate autority
        # certificate then it's assumed to be a client certificate
        extensions.append(
            x509.Extension(oid=x509.ExtendedKeyUsage.oid,
                           critical=True,
                           value=x509.ExtendedKeyUsage([
                               x509.ExtendedKeyUsageOID.CLIENT_AUTH,
                           ])))
    return extensions
Esempio n. 4
0
def _make_cert(subject_name, subject_key, issuer_name, issuer_key,
               extended_key_usage_oid):
    return x509.CertificateBuilder().subject_name(
        _make_name(subject_name)).issuer_name(issuer_name).public_key(
            subject_key.public_key()).serial_number(x509.random_serial_number(
            )).not_valid_before(datetime.datetime.utcnow()).not_valid_after(
                datetime.datetime.utcnow() + datetime.timedelta(
                    days=settings.VPN_KEYGEN_CONFIG.KEY_EXPIRE)).add_extension(
                        x509.SubjectAlternativeName(
                            [x509.DNSName(subject_name)]),
                        critical=False,
                    ).add_extension(
                        x509.AuthorityKeyIdentifier.from_issuer_public_key(
                            issuer_key.public_key()),
                        critical=False,
                    ).add_extension(
                        x509.SubjectKeyIdentifier.from_public_key(
                            subject_key.public_key()),
                        critical=False,
                    ).add_extension(
                        # digital_signature
                        x509.KeyUsage(True, False, False, False, False, False,
                                      False, False, False),
                        critical=True,
                    ).add_extension(
                        x509.ExtendedKeyUsage([extended_key_usage_oid]),
                        critical=True,
                    ).add_extension(
                        x509.BasicConstraints(ca=False, path_length=None),
                        critical=True,
                    ).sign(issuer_key, hashes.SHA256(), default_backend())
Esempio n. 5
0
def delegated_signer_certificate_no_ocsp_perm(known_private_key_3,
                                              known_private_key_2):
    """Return a signed certificate with eku but no ocsp signing permission."""
    subject = x509.Name([
        x509.NameAttribute(x509.oid.NameOID.COUNTRY_NAME, "DK"),
        x509.NameAttribute(x509.oid.NameOID.COMMON_NAME,
                           "delegatedresponder.example"),
    ])
    issuer = x509.Name([
        x509.NameAttribute(x509.oid.NameOID.COUNTRY_NAME, "DK"),
        x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, "example.com"),
    ])
    cert = (x509.CertificateBuilder().subject_name(subject).issuer_name(
        issuer).public_key(known_private_key_3.public_key()).serial_number(
            x509.random_serial_number()).not_valid_before(
                datetime.datetime.utcnow()).
            not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(
                days=90)).add_extension(
                    x509.SubjectAlternativeName(
                        [x509.DNSName("delegatedresponder.example")]),
                    critical=True,
                ).add_extension(
                    x509.ExtendedKeyUsage(
                        usages=[x509.oid.ExtendedKeyUsageOID.CODE_SIGNING]),
                    critical=True,
                ).sign(known_private_key_2, primitives.hashes.SHA256(),
                       default_backend()))
    return cert
Esempio n. 6
0
    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)
Esempio n. 7
0
    def _create_ocsp_certificate(self, cert: CertificateType, private_key: Key,
                                 issuer_key: Key) -> x509.Certificate:

        Certificate._check_issuer_provided(cert)
        Certificate._check_policies(cert)
        self._builder = x509.CertificateBuilder()
        self._set_basic(cert, private_key, issuer_key)
        self._builder = self._builder.add_extension(
            x509.KeyUsage(
                digital_signature=True,
                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,
            ),
            critical=True,
        )

        self._builder = self._builder.add_extension(
            x509.ExtendedKeyUsage([ExtendedKeyUsageOID.OCSP_SIGNING]),
            critical=True,
        )

        return self._sign_certificate(issuer_key)
Esempio n. 8
0
def sign_csr(csr, **kwargs):
    if kwargs.get("ca_crt") == "self":
        issuer_subject = csr.subject
        ca_key = kwargs.get("ca_key")
    else:
        # load private/public key from pem
        ca_key = serialization.load_pem_private_key(kwargs.get("ca_key"), None)
        ca_crt = x509.load_pem_x509_certificate(kwargs.get("ca_crt"))
        issuer_subject = ca_crt.subject

    # set ca constraint to true/false
    bc = (x509.BasicConstraints(ca=kwargs.get("ca"), path_length=None), True)

    valdity = kwargs.get("validity", 30)
    valid_from = datetime.datetime.utcnow() - datetime.timedelta(hours=1)
    valid_to = datetime.datetime.utcnow() + datetime.timedelta(days=valdity)

    builder = x509.CertificateBuilder(
        issuer_name=issuer_subject,
        subject_name=csr.subject,
        public_key=csr.public_key(),
        not_valid_before=valid_from,
        not_valid_after=valid_to,
        serial_number=x509.random_serial_number(),
    )

    builder = builder.add_extension(*bc)
    builder = builder.add_extension(x509.ExtendedKeyUsage(
        [x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH]),
                                    critical=True)

    for e in csr.extensions:
        builder = builder.add_extension(e.value, e.critical)

    return builder.sign(ca_key, hashes.SHA256())
Esempio n. 9
0
File: ca.py Progetto: pyzh/blackout
def create_cert(cn, serial_number, key_path, cert_path, ca_key, ca_cert):
    key = generate_key()
    write_private(key, key_path)

    subject = x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, cn),
    ])

    cert = (
        create_cert_builder(key, subject, ca_cert.subject, serial_number, False)
        .add_extension(
            x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(
                ca_cert.extensions.get_extension_for_class(x509.SubjectKeyIdentifier)
            ),
            critical=False
        )
        .add_extension(
            x509.ExtendedKeyUsage(
                [x509.oid.ExtendedKeyUsageOID.SERVER_AUTH,
                 x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH,
                 x509.oid.ExtendedKeyUsageOID.EMAIL_PROTECTION
                ]
            ),
            critical=True
        )
        .sign(ca_key, hashes.SHA256(), default_backend())
    )

    write_public(cert, cert_path)
Esempio n. 10
0
def generate_self_signed_certificate() -> typing.Tuple[str, str]:
    cert = generate_builder({
        'crypto_subject_name': {
            'country_name': 'US',
            'organization_name': 'iXsystems',
            'common_name': 'localhost',
            'email_address': '*****@*****.**',
            'state_or_province_name': 'Tennessee',
            'locality_name': 'Maryville',
        },
        'lifetime': DEFAULT_LIFETIME_DAYS,
        'san': normalize_san(['localhost'])
    })
    key = generate_private_key({
        'serialize': False,
        'key_length': 2048,
        'type': 'RSA'
    })

    cert = cert.public_key(
        key.public_key()
    ).add_extension(
        x509.ExtendedKeyUsage([x509.oid.ExtendedKeyUsageOID.SERVER_AUTH]), False
    ).sign(
        key, hashes.SHA256(), default_backend()
    )

    return (
        cert.public_bytes(serialization.Encoding.PEM).decode(),
        key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()
        ).decode()
    )
Esempio n. 11
0
 def test_iter_len(self):
     eku = x509.ExtendedKeyUsage([
         x509.ObjectIdentifier("1.3.6.1.5.5.7.3.1"),
         x509.ObjectIdentifier("1.3.6.1.5.5.7.3.2"),
     ])
     assert len(eku) == 2
     assert list(eku) == [x509.OID_SERVER_AUTH, x509.OID_CLIENT_AUTH]
Esempio n. 12
0
def create_client_cert(result_dir, client_name):
    # If the key exists, we assume there is a valid keypair and certificate.
    if os.path.isfile("{}/client-configs/{}.key".format(
            result_dir, client_name)):
        logging.info("Client key already exists, not creating a new one..")
        return
    key = create_RSA_keypair("{}/client-configs/{}.key".format(
        result_dir, client_name))

    with open("{}/ca.crt".format(result_dir), "rb") as f:
        data = f.read()
        ca_cert = x509.load_pem_x509_certificate(data, default_backend())
    with open("{}/ca.key".format(result_dir), "rb") as f:
        data = f.read()
        ca_key = load_pem_private_key(data, None, default_backend())

    subject = x509.Name([
        x509.NameAttribute(NameOID.COUNTRY_NAME, u"BE"),
        x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"East Flanders"),
        x509.NameAttribute(NameOID.LOCALITY_NAME, u"Ghent"),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Easy OpenVPN Server"),
        x509.NameAttribute(NameOID.COMMON_NAME, client_name),
    ])
    cert = x509.CertificateBuilder().subject_name(subject).issuer_name(
        ca_cert.issuer
    ).public_key(key.public_key()).serial_number(x509.random_serial_number(
    )).not_valid_before(datetime.datetime.utcnow()).not_valid_after(
        # This certificate will be valid for about 100 years
        datetime.datetime.utcnow() + datetime.timedelta(days=36500)
    ).add_extension(
        x509.BasicConstraints(ca=False, path_length=None),
        critical=False,
    ).add_extension(
        # Make sure this key can only be used for clients
        # This is to prevent man-in-the-middle attack
        # with client certificate.
        # More info:
        #  - https://openvpn.net/community-resources/how-to
        #  - https://openvpn.net/community-resources/reference-manual-for-openvpn-2-4/
        x509.KeyUsage(
            digital_signature=True,
            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,
        ),
        critical=True,
    ).add_extension(
        x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]),
        critical=True,
        # Sign the certificate with ca key
    ).sign(ca_key, hashes.SHA256(), default_backend())
    # Write the certificate out to disk.
    with open("{}/client-configs/{}.crt".format(result_dir, client_name),
              "wb") as f:
        f.write(cert.public_bytes(serialization.Encoding.PEM))
Esempio n. 13
0
def generate_selfsigned_cert(cert_file: str, key_file: str,
                             config: Config) -> None:
    """Generate self signed certificate compatible with Philips HUE."""

    dec_serial = int(config.bridge_id, 16)

    root_key = ec.generate_private_key(ec.SECP256R1(), default_backend())
    subject = issuer = x509.Name([
        x509.NameAttribute(NameOID.COUNTRY_NAME, u"NL"),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Philips Hue"),
        x509.NameAttribute(NameOID.COMMON_NAME, config.bridge_id),
    ])
    root_cert = (x509.CertificateBuilder(
    ).subject_name(subject).issuer_name(issuer).public_key(
        root_key.public_key()).serial_number(dec_serial).not_valid_before(
            datetime.utcnow()).not_valid_after(datetime.utcnow() + timedelta(
                days=3650)).add_extension(
                    x509.BasicConstraints(ca=False, path_length=None),
                    critical=True).add_extension(
                        x509.SubjectKeyIdentifier(b"hash").from_public_key(
                            root_key.public_key()),
                        critical=False,
                    ).add_extension(
                        x509.AuthorityKeyIdentifier(
                            key_identifier=b"keyid,issuer",
                            authority_cert_issuer=None,
                            authority_cert_serial_number=None,
                        ).from_issuer_public_key(root_key.public_key()),
                        critical=False,
                    ).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([x509.OID_SERVER_AUTH]),
                        critical=False).sign(root_key, hashes.SHA256(),
                                             default_backend()))

    cert_pem = root_cert.public_bytes(encoding=serialization.Encoding.PEM)

    key_pem = root_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    )

    with open(cert_file, "w") as fileobj:
        fileobj.write(cert_pem.decode("utf-8"))
    with open(key_file, "w") as fileobj:
        fileobj.write(key_pem.decode("utf-8"))
    LOGGER.debug("Certificate generated")
Esempio n. 14
0
def generate_adhoc_ssl_pair(cn=None):
    try:
        from cryptography import x509
        from cryptography.x509.oid import NameOID
        from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives import hashes
        from cryptography.hazmat.primitives.asymmetric import rsa
    except ImportError:
        raise TypeError(
            "Using ad-hoc certificates requires the cryptography library.")
    pkey = rsa.generate_private_key(public_exponent=65537,
                                    key_size=2048,
                                    backend=default_backend())

    # pretty damn sure that this is not actually accepted by anyone
    if cn is None:
        cn = u"*"

    subject = x509.Name([
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Dummy Certificate"),
        x509.NameAttribute(NameOID.COMMON_NAME, cn),
    ])

    cert = (x509.CertificateBuilder().subject_name(subject).issuer_name(
        subject).public_key(pkey.public_key()).serial_number(
            x509.random_serial_number()).not_valid_before(
                dt.utcnow()).not_valid_after(dt.utcnow() + timedelta(
                    days=365)).add_extension(
                        x509.ExtendedKeyUsage([x509.OID_SERVER_AUTH]),
                        critical=False).add_extension(
                            x509.SubjectAlternativeName([x509.DNSName(u"*")]),
                            critical=False).sign(pkey, hashes.SHA256(),
                                                 default_backend()))
    return cert, pkey
Esempio n. 15
0
def ensure_end_entity_cert(output_dir,
                           names,
                           ca_private_key,
                           ca_cert,
                           end_entity_public_key,
                           is_server=True):
    name = names[0]
    end_entity_cert_filename = os.path.join(
        output_dir,
        safe_filename(name) + '.' + CERT_EXT)
    if os.path.exists(end_entity_cert_filename):
        return
    ca_public_key = ca_private_key.public_key()
    end_entity_cert_builder = 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 if is_server else 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)
    if is_server:
        end_entity_cert_builder.add_extension(x509.SubjectAlternativeName(
            [x509.DNSName(name) for name in names]),
                                              critical=False)
    end_entity_cert = end_entity_cert_builder.\
        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
Esempio n. 16
0
def generate_client_cert(name, passphrase):
    key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
    )

    cert = base_cert(name, key).add_extension(
        x509.ExtendedKeyUsage([
            ExtendedKeyUsageOID.CLIENT_AUTH,
        ]),
        critical=True,
    ).sign(key, hashes.SHA256())

    p12 = serialize_key_and_certificates(
        b'client',
        key,
        cert,
        None,
        encryption_algorithm=serialization.BestAvailableEncryption(
            passphrase.encode('utf-8')))

    return (
        cert.public_bytes(serialization.Encoding.PEM),
        p12,
    )
Esempio n. 17
0
def generate_server_cert(name, passphrase):
    """
    """
    key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
    )

    cert = base_cert(name, key).add_extension(
        x509.SubjectAlternativeName([x509.IPAddress(IPv4Address("127.0.0.1"))
                                     ]),
        critical=False).add_extension(
            x509.ExtendedKeyUsage([
                ExtendedKeyUsageOID.SERVER_AUTH,
            ]),
            critical=True,
        ).sign(key, hashes.SHA256())

    return (
        cert.public_bytes(serialization.Encoding.PEM),
        key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.BestAvailableEncryption(
                passphrase.encode('utf-8'))),
    )
Esempio n. 18
0
def _build_extensions_as(subject_key: ec.EllipticCurvePrivateKey,
                         issuer_key: ec.EllipticCurvePrivateKey) -> Extensions:
    """
    Returns a list of Extension with the extension and its criticality
    """
    return [
        Extension(x509.KeyUsage(digital_signature=True,
                                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),
                  critical=True),
        Extension(x509.SubjectKeyIdentifier.from_public_key(
            subject_key.public_key()),
                  critical=False),
        Extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(
            issuer_key.public_key()),
                  critical=False),
        Extension(x509.ExtendedKeyUsage([
            x509.ExtendedKeyUsageOID.SERVER_AUTH,
            x509.ExtendedKeyUsageOID.CLIENT_AUTH,
            x509.ExtendedKeyUsageOID.TIME_STAMPING
        ]),
                  critical=False)
    ]
Esempio n. 19
0
    def _issue_new_cert(self,
                        key=None,
                        names=[x509.DNSName("example.com")],
                        issuer=None,
                        not_valid_before=None,
                        not_valid_after=None,
                        signature_hash_algorithm=None,
                        key_usage=None,
                        extended_key_usages=[ANY_EXTENDED_KEY_USAGE_OID],
                        ca_issuers=None,
                        extra_extensions=[]):

        if key is None:
            key = self._key_cache.generate_rsa_key()

        subject_name = x509.Name([])

        if issuer is not None:
            issuer_name = issuer.cert.subject
            ca_key = issuer.key
        else:
            issuer_name = subject_name
            ca_key = key

        if not_valid_before is None:
            not_valid_before = datetime.datetime.utcnow()
        if not_valid_after is None:
            not_valid_after = (datetime.datetime.utcnow() +
                               datetime.timedelta(hours=1))

        if signature_hash_algorithm is None:
            signature_hash_algorithm = hashes.SHA256()

        builder = x509.CertificateBuilder().serial_number(1).public_key(
            key.public_key()).not_valid_before(
                not_valid_before).not_valid_after(
                    not_valid_after).subject_name(subject_name).issuer_name(
                        issuer_name)
        if names is not None:
            builder = builder.add_extension(
                x509.SubjectAlternativeName(names),
                critical=False,
            )
        if key_usage is not None:
            builder = builder.add_extension(key_usage, critical=False)
        if extended_key_usages is not None:
            builder = builder.add_extension(
                x509.ExtendedKeyUsage(extended_key_usages),
                critical=False,
            )
        if ca_issuers is not None:
            builder = builder.add_extension(
                x509.AuthorityInformationAccess(ca_issuers),
                critical=False,
            )
        for ext in extra_extensions:
            builder = builder.add_extension(ext.value, critical=ext.critical)
        cert = builder.sign(ca_key, signature_hash_algorithm,
                            default_backend())
        return CertificatePair(cert, key)
Esempio n. 20
0
def sign_csr(ca_cert, ca_key, csr):
    if not csr.is_signature_valid:
        raise ValueError("CSR has an invalid signature, not signing!")
    if len(csr.extensions) > 0:
        raise ValueError("CSR has extensions, we forbid this for simplicity")
    cb = (x509.CertificateBuilder().subject_name(csr.subject).issuer_name(
        ca_cert.subject).not_valid_before(datetime.datetime.today() -
                                          datetime.timedelta(days=1)).
          not_valid_after(datetime.datetime.today() +
                          datetime.timedelta(days=365)).serial_number(
                              x509.random_serial_number()).public_key(
                                  csr.public_key()).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.CLIENT_AUTH]),
                                      critical=True,
                                  ))
    # for extension in csr.extensions:
    #     cb = cb.add_extension(extension.value, critical=extension.critical)
    certificate = cb.sign(private_key=ca_key,
                          algorithm=hashes.SHA256(),
                          backend=default_backend())
    return certificate
Esempio n. 21
0
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)
Esempio n. 22
0
def create_root_ca_cert(path, key, name):
    print("...    Creating Root CA Certificate")
    subject = issuer = x509.Name([
        x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, name),
    ])

    cert = (x509.CertificateBuilder().subject_name(subject).issuer_name(
        issuer).public_key(key.public_key()).serial_number(
            x509.random_serial_number()).not_valid_before(
                datetime.datetime.utcnow()).not_valid_after(
                    datetime.datetime.utcnow() +
                    datetime.timedelta(days=3650)).add_extension(
                        x509.BasicConstraints(ca=True, path_length=0),
                        critical=True).add_extension(
                            x509.KeyUsage(digital_signature=True,
                                          content_commitment=False,
                                          key_encipherment=False,
                                          data_encipherment=False,
                                          key_agreement=False,
                                          key_cert_sign=True,
                                          crl_sign=False,
                                          encipher_only=False,
                                          decipher_only=False),
                            critical=True).add_extension(
                                x509.ExtendedKeyUsage([
                                    x509.oid.ExtendedKeyUsageOID.SERVER_AUTH,
                                    x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH
                                ]),
                                critical=True).sign(key, hashes.SHA256(),
                                                    default_backend()))
    with open(path, "wb") as f:
        f.write(cert.public_bytes(serialization.Encoding.PEM))
    return cert
Esempio n. 23
0
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
Esempio n. 24
0
def build_certificate(common_names,
                      include_extension=True,
                      bad_extension=False):
    """
    Programmatically generate a self-signed certificate for testing purposes.

    Args:
        common_names (list): A list of strings for the common names of the
            cert.
        include_extension (boolean): A flag enabling/disabling the inclusion
            of certificate extensions.
        bad_extension (boolean): A flag enabling/disabling the setting of
            invalid certificate extension values.

    Returns:
        x509.Certificate: The newly generated certificate object.
    """
    names = []
    for common_name in common_names:
        names.append(
            x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, common_name))
    name = x509.Name(names)

    t = datetime.datetime.now()
    delta = datetime.timedelta(days=30)
    not_valid_before = t - delta
    not_valid_after = t + delta

    private_key = rsa.generate_private_key(public_exponent=65537,
                                           key_size=2048,
                                           backend=default_backend())

    builder = x509.CertificateBuilder().serial_number(
        1
    ).issuer_name(
        name
    ).subject_name(
        name
    ).not_valid_before(
        not_valid_before
    ).not_valid_after(
        not_valid_after
    ).public_key(
        private_key.public_key()
    )\

    extended_key_usage_values = []
    if bad_extension:
        extended_key_usage_values.append(
            x509.oid.ExtendedKeyUsageOID.SERVER_AUTH)
    else:
        extended_key_usage_values.append(
            x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH)

    if include_extension:
        builder = builder.add_extension(
            x509.ExtendedKeyUsage(extended_key_usage_values), True)

    return builder.sign(private_key, hashes.SHA256(), default_backend())
Esempio n. 25
0
    def __init__(
        self,
        parent_cert=None,
        path_length=9,
        organization_name=None,
        organization_unit_name=None,
    ):
        self.parent_cert = parent_cert
        self._private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=_KEY_SIZE,
            backend=default_backend()
        )
        self._path_length = path_length

        name = _name(
            organization_unit_name or u"Testing CA #" + random_text(),
            organization_name=organization_name,
        )
        issuer = name
        sign_key = self._private_key
        if self.parent_cert is not None:
            sign_key = parent_cert._private_key
            issuer = parent_cert._certificate.subject

        self._certificate = (
            _cert_builder_common(name, issuer, self._private_key.public_key())
            .add_extension(
                x509.BasicConstraints(ca=True, path_length=path_length),
                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.ExtendedKeyUsage([
                    ExtendedKeyUsageOID.CLIENT_AUTH,
                    ExtendedKeyUsageOID.SERVER_AUTH,
                    ExtendedKeyUsageOID.CODE_SIGNING,
                ]),
                critical=True
            )
            .sign(
                private_key=sign_key,
                algorithm=hashes.SHA256(),
                backend=default_backend(),
            )
        )
Esempio n. 26
0
 def test_repr(self):
     eku = x509.ExtendedKeyUsage([
         x509.ObjectIdentifier("1.3.6.1.5.5.7.3.1"),
         x509.ObjectIdentifier("1.3.6.1.5.5.7.3.2"),
     ])
     assert repr(eku) == (
         "<ExtendedKeyUsage([<ObjectIdentifier(oid=1.3.6.1.5.5.7.3.1, name="
         "serverAuth)>, <ObjectIdentifier(oid=1.3.6.1.5.5.7.3.2, name=clien"
         "tAuth)>])>")
Esempio n. 27
0
    def _create_server_certificate(self, cert: Certificate_model,
                                   private_key: Key,
                                   issuer_key: Key) -> x509.Certificate:
        # TODO implement checks
        # countryName = match
        # stateOrProvinceName = match
        # localityName = match
        # organizationName = match
        # organizationalUnitName = optional
        # commonName = supplied
        # emailAddress = optional
        if cert.parent.type != CertificateTypes.INTERMEDIATE and cert.parent.type != CertificateTypes.ROOT:
            raise RuntimeError("A root or intermediate parent is expected ")

        self._builder = x509.CertificateBuilder()
        self._set_basic(cert, private_key, issuer_key)

        self._builder = self._builder.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,
        )

        self._builder = self._builder.add_extension(
            x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]),
            critical=False,
        )

        if cert.dn.subjectAltNames:
            alts = []
            for altname in cert.dn.subjectAltNames:
                try:
                    alt = x509.IPAddress(ipaddress.ip_address(altname))
                    alts.append(alt)
                    continue
                except:
                    pass
                try:
                    alt = x509.DNSName(altname)
                    alts.append(alt)
                    continue
                except:
                    pass

            self._builder = self._builder.add_extension(
                x509.SubjectAlternativeName(alts),
                critical=False,
            )

        return self._sign_certificate(issuer_key)
Esempio n. 28
0
 def extcb(cert):
     cert = CertificateAuthority.extcb_noca(cert)
     cert = cert.add_extension(
         x509.ExtendedKeyUsage(usages=[
             x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH,
         ], ),
         critical=True,
     )
     return cert
Esempio n. 29
0
    def _setExtendedKeyUsage(self, extConf: dict) -> None:
        eku = []
        for el in extConf["items"]:
            eku.append(self.conf.extendedKeyUsageMapping[el.upper()])

        isCritical = True if extConf.get("critical") == "true" else False

        self.builder = self.builder.add_extension(x509.ExtendedKeyUsage(eku),
                                                  critical=isCritical)
Esempio n. 30
0
def _build_extensions_voting(key: ec.EllipticCurvePrivateKey,
                             issuer_key_type: ObjectIdentifier) -> Extensions:
    return [
        Extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),
                  critical=False),
        Extension(x509.ExtendedKeyUsage(
            [issuer_key_type, x509.ExtendedKeyUsageOID.TIME_STAMPING]),
                  critical=False)
    ]