コード例 #1
0
ファイル: test_acme.py プロジェクト: titanmen1/lemur
 def test_get_domains_san(self, mock_current_app):
     options = {
         "common_name": "test.netflix.net",
         "extensions": {
             "sub_alt_names": {"names": [DNSName("test.netflix.net"), DNSName("test2.netflix.net")]}
         },
     }
     result = self.acme.get_domains(options)
     self.assertEqual(
         result, [options["common_name"], "test2.netflix.net"]
     )
コード例 #2
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")
コード例 #3
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(),
    ))
コード例 #4
0
def generate_self_signed_certificate(
        cn: str) -> (rsa.RSAPrivateKey, x509.Certificate):
    """Generate an X.509 Certificate with the given Common Name.
    
    Args:
          cn (string): 
    """
    name = x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, cn),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment')
    ])

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

    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.SubjectAlternativeName([DNSName(cn)]),
                        False).sign(private_key, hashes.SHA256(),
                                    default_backend())

    return private_key, certificate
コード例 #5
0
ファイル: __init__.py プロジェクト: wwjiang007/scrapy
def generate_keys():
    folder = os.path.dirname(__file__)

    key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend(),
    )
    with open(os.path.join(folder, 'localhost.key'), "wb") as f:
        f.write(
            key.private_bytes(
                encoding=Encoding.PEM,
                format=PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=NoEncryption(),
            ))

    subject = issuer = Name([
        NameAttribute(NameOID.COUNTRY_NAME, "IE"),
        NameAttribute(NameOID.ORGANIZATION_NAME, "Scrapy"),
        NameAttribute(NameOID.COMMON_NAME, "localhost"),
    ])
    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=10)).add_extension(
                        SubjectAlternativeName([DNSName("localhost")]),
                        critical=False,
                    ).sign(key, SHA256(), default_backend()))
    with open(os.path.join(folder, 'localhost.crt'), "wb") as f:
        f.write(cert.public_bytes(Encoding.PEM))
コード例 #6
0
ファイル: createcerts.py プロジェクト: sanic-org/sanic
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
コード例 #7
0
def generate_tls_keys():
	""" Creates a TLS private key (RSA, 4096 bits, PEM format) and certificate signing request (CSR). """

	# Query the user for CSR attributes
	country = input("Country: ")
	state = input("State or province: ")
	locality = input("Locality: ")
	organization = input("Organization: ")
	organizational_unit = input("Organizational unit: ")
	email = input("Email: ")
	common_name = input("Common name: ")

	print("Enter any subject alternative names (SANs) you wish to attach to the certificate. Leave blank to continue.")
	sans = []
	while True:
		san = input("Subject alternative name: ")
		if san == '':
			break
		sans.append(DNSName(san))

	# Make sure we can open the output files first
	private_key_file = open("private.key", "wb")
	csr_file = open("certificate_signing_request", "wb")

	# Generate the private key
	key = generate_private_key(public_exponent=65537, key_size=4096, backend=default_backend())

	attributes = [
		NameAttribute(NameOID.COUNTRY_NAME, country),
		NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, state),
		NameAttribute(NameOID.LOCALITY_NAME, locality),
		NameAttribute(NameOID.ORGANIZATION_NAME, organization),
		NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, organizational_unit),
		NameAttribute(NameOID.EMAIL_ADDRESS, email),
		NameAttribute(NameOID.COMMON_NAME, common_name),
	]

	# Generate the CSR and sign it with the private key
	csr = CertificateSigningRequestBuilder().subject_name(Name(attributes))
	if sans:
		csr = csr.add_extension(SubjectAlternativeName(sans), critical=False)
	csr = csr.sign(key, SHA256(), default_backend())

	# Write the private key and CSR to disk
	private_key_file.write(key.private_bytes(encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption()))
	csr_file.write(csr.public_bytes(Encoding.PEM))

	private_key_file.close()
	csr_file.close()

	# Success!
	print("Successfully generated a private key and certificate signing request.")
コード例 #8
0
def server_cert(server_key, backend):
    """Generate server certificate."""
    subject = issuer = Name([
        NameAttribute(NameOID.COMMON_NAME, six.u('localhost')),
        NameAttribute(NameOID.ORGANIZATION_NAME, six.u('Bob B. Server'))
    ])
    return CertificateBuilder().subject_name(subject).issuer_name(
        issuer).serial_number(random_serial_number()).public_key(
            server_key.public_key()).not_valid_before(datetime(
                2008, 1,
                1)).not_valid_after(datetime(3020, 1, 1)).add_extension(
                    SubjectAlternativeName([DNSName(six.u('localhost'))]),
                    critical=False).sign(server_key, SHA256(), backend)
コード例 #9
0
def client_cert(client_key, backend):
    """Generate client certificate."""
    subject = issuer = Name([
        NameAttribute(NameOID.COMMON_NAME, six.u('example.org')),
        NameAttribute(NameOID.ORGANIZATION_NAME, six.u('Alice A. Client'))
    ])
    return CertificateBuilder().subject_name(subject).issuer_name(
        issuer).serial_number(random_serial_number()).public_key(
            client_key.public_key()).not_valid_before(datetime(
                3019, 1,
                1)).not_valid_after(datetime(3019, 1, 10)).add_extension(
                    SubjectAlternativeName([DNSName(six.u('localhost'))]),
                    critical=False).sign(client_key, SHA256(), backend)
コード例 #10
0
ファイル: __init__.py プロジェクト: basic-system/txkube
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(),
                )
コード例 #11
0
def generate_csr(cn, csr_path, private_key_path, sans={}, org=None):
    '''
    Returns an X509 CSR in
    cryptography.hazmat.backends.openssl.x509._CertificateSigningRequest
    format. See documentation for more details on how to sign.

    cn (str): Common name.
    csr_path (str): Path to store CSR file.
    private_key_path (str): Path to store private key.
    sans (dict: str -> str): Maps type to value {types, ex. 'IP' -> values, ex. '10.5.1.16'}.
    '''

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

    key_file = open(private_key_path, "wb")
    key_file.write(
        private_key.private_bytes(
            encoding=Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption(),
        ))

    # Add the basic attributes. Includes CN.
    builder = x509.CertificateSigningRequestBuilder().subject_name(
        x509.Name([
            # Provide various details about who we are.
            x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
            x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"California"),
            x509.NameAttribute(NameOID.LOCALITY_NAME, u"Sunnyvale"),
            x509.NameAttribute(NameOID.COMMON_NAME, cn),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, str(org))
        ]))

    # Convert the SANs to Python objects.
    sans_converted = []
    for san in sans:
        if san == 'IP':
            ip_addresses = sans[san]
            for ip in ip_addresses:
                sans_converted.append(IPAddress(ip_address(ip)))
        if san == 'DNS':
            dns_names = sans[san]
            for dns_name in dns_names:
                sans_converted.append(DNSName(dns_name))

    # Add the SANs to the CSR information.
    builder = builder.add_extension(
        x509.SubjectAlternativeName(sans_converted), critical=True)

    builder = builder.add_extension(
        x509.BasicConstraints(ca=False, path_length=None),
        critical=True,
    )

    # Sign the CSR with our private key.
    csr = builder.sign(private_key, hashes.SHA256(), default_backend())

    csr_file = open(csr_path, "wb")
    csr_file.write(csr.public_bytes(Encoding.PEM))

    return csr
コード例 #12
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