Esempio n. 1
0
def _sign_csr(
    csr: CertificateSigningRequest,
    days_valid: int,
    signing_cert: Certificate,
    signing_private_key: RSAPrivateKeyWithSerialization,
) -> Certificate:
    common_name = csr.subject.get_attributes_for_oid(
        NameOID.COMMON_NAME)[0].value
    return (_make_cert_builder(
        csr.subject,
        days_valid,
        _rsa_public_key_from_cert_or_csr(csr),
    ).issuer_name(signing_cert.issuer).add_extension(
        SubjectAlternativeName([DNSName(common_name)]),
        critical=False,
    ).add_extension(
        BasicConstraints(
            ca=False,
            path_length=None,
        ),
        critical=True,
    ).sign(
        signing_private_key,
        SHA256(),
    ))
    def _create_x509_certificate(
        key_der, subject_name
    ):  #type(Union[EllipticCurvePrivateKey,RSAPrivateKey], str) -> Certificate
        signing_key = serialization.load_der_private_key(
            key_der, password=None, backend=default_backend())
        builder = CertificateBuilder()
        builder = builder.subject_name(
            x509.Name([
                x509.NameAttribute(NameOID.COMMON_NAME, subject_name),
            ]))
        builder = builder.issuer_name(
            x509.Name([
                x509.NameAttribute(NameOID.COMMON_NAME, subject_name),
            ]))

        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 * 30))
        builder = builder.serial_number(x509.random_serial_number())
        builder = builder.public_key(signing_key.public_key())
        builder = builder.add_extension(SubjectAlternativeName(
            [x509.DNSName(subject_name)]),
                                        critical=False)
        builder = builder.add_extension(BasicConstraints(ca=False,
                                                         path_length=None),
                                        critical=True)
        return builder.sign(private_key=signing_key,
                            algorithm=hashes.SHA256(),
                            backend=default_backend()).public_bytes(
                                serialization.Encoding.DER)
Esempio n. 3
0
def _make_root_certificate(
    subject_name: Name,
    days_valid: int,
    private_key: RSAPrivateKeyWithSerialization,
) -> Certificate:
    return (_make_cert_builder(
        subject_name,
        days_valid,
        private_key.public_key(),
    ).issuer_name(subject_name).add_extension(
        SubjectKeyIdentifier.from_public_key(private_key.public_key()),
        critical=False,
    ).add_extension(
        BasicConstraints(
            ca=True,
            path_length=0,
        ),
        critical=True,
    ).add_extension(
        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,
    ).sign(
        private_key,
        SHA256(),
    ))
Esempio n. 4
0
def selfsigned(key, common_name, san):
    subject = issuer = Name([
        NameAttribute(NameOID.COMMON_NAME, common_name),
        NameAttribute(NameOID.ORGANIZATION_NAME, "Sanic Org"),
    ])
    cert = (CertificateBuilder().subject_name(subject).issuer_name(
        issuer).public_key(key.public_key()).serial_number(
            random_serial_number()).not_valid_before(
                datetime.utcnow()).not_valid_after(
                    datetime.utcnow() +
                    timedelta(days=365.25 * 8)).add_extension(
                        KeyUsage(True, False, False, False, False, False,
                                 False, False, False),
                        critical=True,
                    ).add_extension(
                        ExtendedKeyUsage([
                            ExtendedKeyUsageOID.SERVER_AUTH,
                            ExtendedKeyUsageOID.CLIENT_AUTH,
                        ]),
                        critical=False,
                    ).add_extension(
                        BasicConstraints(ca=True, path_length=None),
                        critical=True,
                    ).add_extension(
                        SubjectAlternativeName([
                            IPAddress(ip_address(n))
                            if n[0].isdigit() or ":" in n else DNSName(n)
                            for n in san
                        ]),
                        critical=False,
                    ).sign(key, hashes.SHA256()))
    return cert
def create_x509_certificate(key_pem, subject_name):  # type: (str, str) -> str
    """
    Given an RSA or ECDS private key, create a self-signed X.509 certificate
    with the specified subject name signed with that key.
    """
    signing_key = serialization.load_pem_private_key(key_pem.encode("ascii"),
                                                     password=None,
                                                     backend=default_backend())
    builder = CertificateBuilder()
    builder = builder.subject_name(
        x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, subject_name),
        ]))
    builder = builder.issuer_name(
        x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, subject_name),
        ]))

    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 * 30))
    builder = builder.serial_number(x509.random_serial_number())
    builder = builder.public_key(signing_key.public_key())
    builder = builder.add_extension(SubjectAlternativeName(
        [x509.DNSName(subject_name)]),
                                    critical=False)
    builder = builder.add_extension(BasicConstraints(ca=False,
                                                     path_length=None),
                                    critical=True)
    return (builder.sign(
        private_key=signing_key,
        algorithm=hashes.SHA256(),
        backend=default_backend(),
    ).public_bytes(serialization.Encoding.PEM).decode("ascii"))
Esempio n. 6
0
def _generate_certs(path: Union[Path, str],
                    days: int = 3652,
                    key_size: int = 2048,
                    separate_key: bool = False) -> None:
    # DO NOT USE THIS FOR ANYTHING PRODUCTION RELATED, EVER!
    # Generate private key
    # 2048 is the minimum that works as of 3.9
    key = rsa.generate_private_key(public_exponent=65537, key_size=key_size)
    key_file = "key.pem" if separate_key else "cert.pem"
    key_path = Path(path).joinpath(key_file)
    with open(key_path, "ab") as f:
        f.write(key.private_bytes(
            encoding=serialization.Encoding.PEM,
            encryption_algorithm=serialization.NoEncryption(),
            format=serialization.PrivateFormat.TraditionalOpenSSL
        ))
    log.debug("Private key generated")

    # Generate public certificate
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)
    subject = Name([NameAttribute(NameOID.COMMON_NAME, "smtpdfix_cert")])
    alt_names = [
        DNSName("localhost"),
        DNSName("localhost.localdomain"),
        DNSName(hostname),
        IPAddress(ip_address("127.0.0.1")),
        IPAddress(ip_address("0.0.0.1")),
        IPAddress(ip_address("::1")),
        IPAddress(ip_address(ip)),
    ]
    # Set it so the certificate can be a root certificate with
    # ca=true, path_length=0 means it can only sign itself.
    constraints = BasicConstraints(ca=True, path_length=0)

    cert = (CertificateBuilder()
            .issuer_name(subject)
            .subject_name(subject)
            .serial_number(random_serial_number())
            .not_valid_before(datetime.utcnow())
            .not_valid_after(datetime.utcnow() + timedelta(days=days))
            .add_extension(SubjectAlternativeName(alt_names), critical=False)
            .public_key(key.public_key())
            .add_extension(constraints, critical=False)
            .sign(private_key=key, algorithm=hashes.SHA256()))

    cert_path = Path(path).joinpath("cert.pem")
    with open(cert_path, "ab") as f:
        f.write(cert.public_bytes(serialization.Encoding.PEM))
    log.debug("Certificate generated")
Esempio n. 7
0
def cert(issuer, subject, pubkey, privkey, ca):
    builder = CertificateBuilder().issuer_name(
        Name([NameAttribute(NameOID.COMMON_NAME, issuer)]), ).subject_name(
            Name([NameAttribute(NameOID.COMMON_NAME,
                                subject)]), ).add_extension(
                                    SubjectAlternativeName([DNSName(subject)]),
                                    critical=False,
                                )
    if ca:
        builder = builder.add_extension(
            BasicConstraints(True, None),
            critical=True,
        )
    return builder.public_key(
        pubkey, ).serial_number(random_serial_number(), ).not_valid_before(
            datetime.utcnow(), ).not_valid_after(
                datetime.utcnow() + timedelta(seconds=1), ).sign(
                    privkey,
                    SHA256(),
                    default_backend(),
                )
Esempio n. 8
0
def self_signed_certificate(*hostname, **oid):
    """
    Generates a self signed ssl_cert_key.

    Args:
        hostname (str): host name or IP address.
        oid (str): Object Identifiers. See "cryptography.x509.oid.NameOID"

    Returns:
        tuple of bytes: certificate and private key in PEM format.
    """
    # Python 2: Unicode are required
    if version_info[0] == 2:
        oid = {key: unicode(value) for key, value in oid.items()}
        hostname = [unicode(value) for value in hostname]

    # Requester information
    name = Name([
        NameAttribute(getattr(NameOID, key.upper()), value)
        for key, value in oid.items()
    ])

    # IP addresses
    alternatives_names = []
    for host in hostname:
        # DNS host name
        alternatives_names.append(DNSName(host))
        # Host IP address
        try:
            alternatives_names.append(IPAddress(ip_address(host)))
        except ValueError:
            pass

    # Validity start date
    valid_from = datetime.utcnow()

    # Generates private RSA key
    private_key = generate_private_key(public_exponent=65537,
                                       key_size=2048,
                                       backend=default_backend())

    # Generates ssl_cert_key
    certificate = (
        CertificateBuilder()
        # Requester information
        # Subject = Issuer on self signed certificates
        .subject_name(name).issuer_name(name)

        # Public key and serial number
        .public_key(private_key.public_key()).serial_number(
            random_serial_number())

        # Validity
        .not_valid_before(valid_from).not_valid_after(valid_from +
                                                      timedelta(days=VALIDITY))

        # This ssl_cert_key can only sign itself
        .add_extension(BasicConstraints(ca=True, path_length=0),
                       critical=False)

        # IP addresses
        .add_extension(SubjectAlternativeName(alternatives_names),
                       critical=False)

        # Sign ssl_cert_key with private key
        .sign(private_key, SHA256(), default_backend()))

    # Generates public ssl_cert_key file
    certificate_bytes = certificate.public_bytes(encoding=Encoding.PEM)

    # Generates private key file
    private_key_bytes = private_key.private_bytes(
        encoding=Encoding.PEM,
        format=PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=NoEncryption())

    return certificate_bytes, private_key_bytes