def _create_emergency_ssl_context(self) -> ssl.SSLContext: """Create an emergency ssl certificate so we can still startup.""" context = ssl_util.server_context_modern() host: str try: host = cast(str, URL(get_url(self.hass, prefer_external=True)).host) except NoURLAvailableError: host = "homeassistant.local" key = rsa.generate_private_key( public_exponent=65537, key_size=2048, ) subject = issuer = x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Home Assistant Emergency Certificate"), x509.NameAttribute(NameOID.COMMON_NAME, host), ]) 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=30)).add_extension( x509.SubjectAlternativeName([x509.DNSName(host)]), critical=False, ).sign(key, hashes.SHA256())) with NamedTemporaryFile() as cert_pem, NamedTemporaryFile() as key_pem: cert_pem.write(cert.public_bytes(serialization.Encoding.PEM)) key_pem.write( key.private_bytes( serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption(), )) cert_pem.flush() key_pem.flush() context.load_cert_chain(cert_pem.name, key_pem.name) return context
def certificate(self): if not self._certificate: subject = issuer = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, "US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"California"), x509.NameAttribute(NameOID.LOCALITY_NAME, "San Francisco"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, "My Company"), x509.NameAttribute(NameOID.COMMON_NAME, "localhost"), ]) self._certificate = x509.CertificateBuilder() \ .subject_name(subject) \ .issuer_name(issuer) \ .public_key(self.tls_key.public_key()) \ .serial_number(x509.random_serial_number()) \ .not_valid_before(datetime.datetime.utcnow()) \ .not_valid_after( # Our certificate will be valid for 10 days datetime.datetime.utcnow() + datetime.timedelta(days=10) ) \ .add_extension(x509.SubjectAlternativeName([x509.DNSName("localhost")]), critical=False, ).sign(self.tls_key, hashes.SHA256()) return self._certificate
def create_certificate(subject_name, private_key, signing_certificate, signing_key, hostName="", 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 hostName != "": try: builder = builder.add_extension(x509.SubjectAlternativeName([ x509.IPAddress(hostName), ]), critical=True) except TypeError: builder = builder.add_extension(x509.SubjectAlternativeName([ x509.DNSName(hostName), ]), critical=True) 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
def generate_adhoc_ssl_pair( cn: t.Optional[str] = None, ) -> t.Tuple["Certificate", "RSAPrivateKeyWithSerialization"]: 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.") backend = default_backend() pkey = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=backend) # pretty damn sure that this is not actually accepted by anyone if cn is None: cn = "*" subject = x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Dummy Certificate"), x509.NameAttribute(NameOID.COMMON_NAME, cn), ]) backend = default_backend() cert = (x509.CertificateBuilder().subject_name(subject).issuer_name( subject).public_key(pkey.public_key()).serial_number( x509.random_serial_number()).not_valid_before(dt.now( timezone.utc)).not_valid_after( dt.now(timezone.utc) + timedelta(days=365)).add_extension( x509.ExtendedKeyUsage([x509.OID_SERVER_AUTH]), critical=False).add_extension( x509.SubjectAlternativeName([x509.DNSName("*")]), critical=False).sign(pkey, hashes.SHA256(), backend)) return cert, pkey
def generate_cert(key): subject = issuer = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"California"), x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"My Company"), x509.NameAttribute(NameOID.COMMON_NAME, u"mysite.com"), ]) 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=10)).add_extension( x509.SubjectAlternativeName( [x509.DNSName(u"localhost")]), critical=False, ).sign(key, hashes.SHA256(), default_backend()) with open("certificate.pem", "wb") as f: f.write(cert.public_bytes(serialization.Encoding.PEM)) with open("certificate.pem", "rb") as c: certificate = c.read()
def test_certificate_input_schema_parse_csr(authority): from lemur.certificates.schemas import CertificateInputSchema test_san_dns = "foobar.com" extensions = { "sub_alt_names": { "names": x509.SubjectAlternativeName([x509.DNSName(test_san_dns)]) } } csr, private_key = create_csr( owner="*****@*****.**", common_name="ACommonName", organization="test", organizational_unit="Meters", country="NL", state="Noord-Holland", location="Amsterdam", key_type="RSA2048", extensions=extensions, ) input_data = { "commonName": "test.example.com", "owner": "*****@*****.**", "authority": { "id": authority.id }, "description": "testtestest", "csr": csr, "dnsProvider": None, } data, errors = CertificateInputSchema().load(input_data) assert not errors for san in data["extensions"]["sub_alt_names"]["names"]: assert san.value == test_san_dns assert data["key_type"] == "RSA2048"
def test_add_unsupported_extension_in_backend(self, backend): private_key = RSA_KEY_2048.private_key(backend) builder = x509.CertificateSigningRequestBuilder() builder = builder.subject_name( x509.Name([ x509.NameAttribute(x509.OID_COUNTRY_NAME, u'US'), ])).add_extension( x509.SubjectAlternativeName([x509.DNSName(u"cryptography.io") ]), critical=False, ).add_extension(x509.KeyUsage(digital_signature=True, content_commitment=True, key_encipherment=False, data_encipherment=False, key_agreement=False, key_cert_sign=True, crl_sign=False, encipher_only=False, decipher_only=False), critical=False) with pytest.raises(NotImplementedError): builder.sign(private_key, hashes.SHA256(), backend)
def csRequest(self): # Generate a CSR csr = 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"San Francisco"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"My Company"), x509.NameAttribute(NameOID.COMMON_NAME, u"mysite.com"), ])).add_extension( x509.SubjectAlternativeName([ # Describe what sites we want this certificate for. x509.DNSName(u"mysite.com"), ]), critical=False, # Sign the CSR with our private key. ).sign(self.key, hashes.SHA256()) # Write our CSR out to disk. with open(self.path, "wb") as f: # path = path/to/store/csr.pem f.write(csr.public_bytes(serialization.Encoding.PEM))
def test_CN(): ca = CA() # Since we have to emulate kwonly args here, I guess we should test the # emulation logic with pytest.raises(TypeError): ca.issue_cert(comon_nam=u"wrong kwarg name") # Must be unicode with pytest.raises(TypeError): ca.issue_cert(common_name=b"bad kwarg value") # Default is no common name pem = ca.issue_cert(u"example.com").cert_chain_pems[0].bytes() cert = x509.load_pem_x509_certificate(pem, default_backend()) common_names = cert.subject.get_attributes_for_oid( x509.oid.NameOID.COMMON_NAME ) assert common_names == [] # Common name on its own is valid pem = ca.issue_cert(common_name=u"woo").cert_chain_pems[0].bytes() cert = x509.load_pem_x509_certificate(pem, default_backend()) common_names = cert.subject.get_attributes_for_oid( x509.oid.NameOID.COMMON_NAME ) assert common_names[0].value == u"woo" # Common name + SAN pem = ca.issue_cert(u"example.com", common_name=u"woo").cert_chain_pems[0].bytes() cert = x509.load_pem_x509_certificate(pem, default_backend()) san = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ) assert san.value[0] == x509.DNSName(u"example.com") common_names = cert.subject.get_attributes_for_oid( x509.oid.NameOID.COMMON_NAME ) assert common_names[0].value == u"woo"
def generate_csr(CN: str, private_key: rsa.RSAPrivateKey, path: Path, names: typing.List[str]): """Generates a certificate signing request. :param CN: The requested common name. :param private_key: The private key to sign the CSR with. :param path: The path to write the PEM-serialized CSR to. :param names: The requested names in the CSR. :return: The generated CSR. """ csr = (x509.CertificateSigningRequestBuilder().subject_name( x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, CN) ])).add_extension( x509.SubjectAlternativeName( [x509.DNSName(name) for name in names]), critical=False, ).sign(private_key, hashes.SHA256())) with open(path, "wb") as pem_out: pem_out.write(csr.public_bytes(serialization.Encoding.PEM)) return csr
def loadPrivateKey(): #only create private key if not stored in file on disk! try: f = open("privateKey.pem", "rb") data = f.read() f.close() return serialization.load_pem_private_key(data, PRIVATE_KEY_PASS, default_backend()) except FileNotFoundError: # Generate our key on first use key = rsa.generate_private_key(public_exponent=65537, key_size=4096, backend=default_backend()) # Write our key to disk for safe keeping -> should be stored securely in production with open("privateKey.pem", "wb") as f: f.write( key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.BestAvailableEncryption( PRIVATE_KEY_PASS), )) #Create CA.pem certificate t be copied to clients! cert = x509.CertificateBuilder().subject_name(issuer).issuer_name( issuer).public_key(key.public_key()).serial_number( x509.random_serial_number()).not_valid_before( datetime.datetime.utcnow()).not_valid_after( # Our certificate will be valid for 10 years datetime.datetime.utcnow() + datetime.timedelta(days=3650)).add_extension( x509.SubjectAlternativeName( [x509.DNSName(u"localhost")]), critical=False, # Sign our certificate with our private key ).sign(key, hashes.SHA256(), default_backend()) # Write our certificate out to disk. with open("CA.pem", "wb") as f: f.write(cert.public_bytes(serialization.Encoding.PEM)) return key
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)
def make_key_cert_pair(self, hostname, ip): private_key = rsa.generate_private_key( backend=crypto_default_backend(), public_exponent=65537, key_size=2048) public_key = private_key.public_key() builder = x509.CertificateBuilder() builder = builder.subject_name( x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, hostname), ])) builder = builder.issuer_name( x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, hostname), ])) builder = builder.not_valid_before(datetime.datetime.today() - day) builder = builder.not_valid_after(datetime.datetime.today() + EXPIRE_TIME) builder = builder.serial_number(x509.random_serial_number()) builder = builder.public_key(public_key) builder = builder.add_extension(x509.SubjectAlternativeName( [x509.DNSName(ip)]), critical=True) certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA256(), backend=crypto_default_backend()) ser_private_key = private_key.private_bytes( crypto_serialization.Encoding.PEM, crypto_serialization.PrivateFormat.PKCS8, crypto_serialization.NoEncryption()) ser_public_key = certificate.public_bytes( crypto_serialization.Encoding.PEM) return ser_private_key, ser_public_key
def sns_certificate(sns_privatekey, sns_publickey): one_day = datetime.timedelta(1, 0, 0) private_key = load_pem_private_key( sns_privatekey, password=None, backend=default_backend(), ) public_key = load_pem_public_key(sns_publickey, backend=default_backend()) builder = x509.CertificateBuilder() builder = builder.subject_name( x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, "sns.amazonaws.com"), ]), ) builder = builder.issuer_name( x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, "sns.amazonaws.com"), ]), ) builder = builder.not_valid_before(datetime.datetime.today() - one_day) builder = builder.not_valid_after(datetime.datetime.today() + one_day) builder = builder.serial_number(x509.random_serial_number()) builder = builder.public_key(public_key) builder = builder.add_extension( x509.SubjectAlternativeName([x509.DNSName("sns.amazonaws.com")]), critical=False, ) builder = builder.add_extension( x509.BasicConstraints(ca=False, path_length=None), critical=True, ) cert = builder.sign( private_key=private_key, algorithm=hashes.SHA256(), backend=default_backend(), ) return cert.public_bytes(Encoding.PEM)
def __init__( self, names: List[str], ips: List[IPv4Address] = [], key_size: int = 2048, validity: int = 365, ): """Initialise a new self-signed certificate. Args: names: A list of FQDNs that should be placed in the Subject Alternative Name field of the certificate. The first name in the list will be used as the Common Name, Subject and Issuer field. ips: A list of IPv4Address objects that should be present in the list of Subject Alternative Names of the certificate. key_size: Size of the RSA Private Key to be generated. Defaults to 2048 validity: Period in days the certificate is valid for. Default is 365. Raises: ValueError: is raised if an empty list of names is provided to the constructor. """ # Ensure that at least one FQDN was provided # TODO: Do some validation on any provided names if not names: raise ValueError("Must provide at least one name for the certificate") # Create a list of x509.DNSName objects from the list of FQDNs provided self.names = [x509.DNSName(n) for n in names] # Create a list of x509IPAdress objects from the list of IPv4Addresses self.ips = [x509.IPAddress(i) for i in ips] if ips else [] # Initialise some values self.key_size = key_size self.validity = validity self.cert = None self.key = None # Generate the certificate self._generate()
def build_root_certificate(options): private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) subject = issuer = x509.Name([ x509.NameAttribute(x509.OID_COUNTRY_NAME, options['country']), x509.NameAttribute(x509.OID_STATE_OR_PROVINCE_NAME, options['state']), x509.NameAttribute(x509.OID_LOCALITY_NAME, options['location']), x509.NameAttribute(x509.OID_ORGANIZATION_NAME, options['organization']), x509.NameAttribute(x509.OID_ORGANIZATIONAL_UNIT_NAME, options['organizational_unit']), x509.NameAttribute(x509.OID_COMMON_NAME, options['common_name']) ]) builder = x509.CertificateBuilder( subject_name=subject, issuer_name=issuer, public_key=private_key.public_key(), not_valid_after=options['validity_end'], not_valid_before=options['validity_start'], serial_number=options['first_serial']) builder.add_extension(x509.SubjectAlternativeName( [x509.DNSName(options['common_name'])]), critical=False) cert = builder.sign(private_key, hashes.SHA256(), default_backend()) cert_pem = cert.public_bytes(encoding=serialization.Encoding.PEM) private_key_pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat. TraditionalOpenSSL, # would like to use PKCS8 but AWS ELBs don't like it encryption_algorithm=serialization.NoEncryption()) return cert_pem, private_key_pem
def test_external_ca_constrained(self): install_server_external_ca_step1(self.master) # name constraints for IPA DNS domain (dot prefix) nameconstraint = x509.NameConstraints(permitted_subtrees=[ x509.DNSName("." + self.master.domain.name), ], excluded_subtrees=None) root_ca_fname, ipa_ca_fname = tasks.sign_ca_and_transport( self.master, paths.ROOT_IPA_CSR, ROOT_CA, IPA_CA, root_ca_extensions=[nameconstraint], ) install_server_external_ca_step2(self.master, ipa_ca_fname, root_ca_fname) tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'ping'])
def test_add_multiple_extensions(self, backend): serial_number = 333 revocation_date = datetime.datetime(2002, 1, 1, 12, 1) invalidity_date = x509.InvalidityDate( datetime.datetime(2015, 1, 1, 0, 0)) certificate_issuer = x509.CertificateIssuer([ x509.DNSName(u"cryptography.io"), ]) crl_reason = x509.CRLReason(x509.ReasonFlags.aa_compromise) builder = x509.RevokedCertificateBuilder().serial_number( serial_number).revocation_date(revocation_date).add_extension( invalidity_date, True).add_extension(crl_reason, True).add_extension( certificate_issuer, True) revoked_certificate = builder.build(backend) assert len(revoked_certificate.extensions) == 3 for ext_data in [invalidity_date, certificate_issuer, crl_reason]: ext = revoked_certificate.extensions.get_extension_for_class( type(ext_data)) assert ext.critical is True assert ext.value == ext_data
def generate_server_cert_and_key(ca_cert, ca_key, server_uuid): """Creates a server cert and key for testing. :param ca_cert: A cryptography CA certificate (x509) object. :param ca_key: A cryptography CA key (x509) object. :param server_uuid: A UUID identifying the server. :returns: The cryptography server cert and key objects. """ server_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) subject = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"Denial"), x509.NameAttribute(NameOID.LOCALITY_NAME, u"Corvallis"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"OpenStack"), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u"Octavia"), x509.NameAttribute(NameOID.COMMON_NAME, u"{}.example.com".format(server_uuid)), ]) server_cert = x509.CertificateBuilder().subject_name(subject).issuer_name( ca_cert.subject).public_key(server_key.public_key()).serial_number( x509.random_serial_number()).not_valid_before( datetime.datetime.utcnow()).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=10)).add_extension( x509.SubjectAlternativeName([ x509.DNSName(u"{}.example.com".format(server_uuid)) ]), critical=False, ).add_extension( x509.BasicConstraints(ca=False, path_length=None), critical=True, ).sign(ca_key, hashes.SHA256(), default_backend()) return server_cert, server_key
def signed_certificate(known_private_key, known_private_key_2): """Return a signed certificate.""" subject = x509.Name([ x509.NameAttribute(x509.oid.NameOID.COUNTRY_NAME, "DK"), x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, "example.com"), ]) issuer = x509.Name([ x509.NameAttribute(x509.oid.NameOID.COUNTRY_NAME, "DK"), x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, "example.net"), ]) cert = (x509.CertificateBuilder().subject_name(subject).issuer_name( issuer).public_key(known_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=90)).add_extension( x509.SubjectAlternativeName( [x509.DNSName("example.com")]), critical=False).sign(known_private_key_2, primitives.hashes.SHA256(), default_backend())) return cert
def test_unicode_domains(self): """Test some unicode domains.""" self.assertEqual(parse_general_name('https://exämple.com/test'), x509.UniformResourceIdentifier('https://xn--exmple-cua.com/test')) self.assertEqual(parse_general_name('https://exämple.com:8000/test'), x509.UniformResourceIdentifier('https://xn--exmple-cua.com:8000/test')) self.assertEqual(parse_general_name('https://exämple.com:8000/test'), x509.UniformResourceIdentifier('https://xn--exmple-cua.com:8000/test')) self.assertEqual(parse_general_name('uri:https://exämple.com:8000/test'), x509.UniformResourceIdentifier('https://xn--exmple-cua.com:8000/test')) self.assertEqual(parse_general_name('exämple.com'), x509.DNSName('xn--exmple-cua.com')) self.assertEqual(parse_general_name('.exämple.com'), x509.DNSName('.xn--exmple-cua.com')) self.assertEqual(parse_general_name('*.exämple.com'), x509.DNSName('*.xn--exmple-cua.com')) self.assertEqual(parse_general_name('dns:exämple.com'), x509.DNSName('xn--exmple-cua.com')) self.assertEqual(parse_general_name('dns:.exämple.com'), x509.DNSName('.xn--exmple-cua.com')) self.assertEqual(parse_general_name('dns:*.exämple.com'), x509.DNSName('*.xn--exmple-cua.com'))
def generate_selfsigned_cert(hostname, public_ip=None, private_ip=None): # Generate our key key = rsa.generate_private_key(public_exponent=65537, key_size=1024, backend=default_backend()) name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, hostname)]) alt_names = x509.SubjectAlternativeName([ # best practice seem to be to include the hostname in the SAN, which *SHOULD* mean COMMON_NAME is ignored. x509.DNSName(hostname), # allow addressing by IP, for when you don't have real DNS (common in most testing scenarios) # openssl wants DNSnames for ips... #x509.DNSName(public_ip), #x509.DNSName(private_ip), # ... whereas golang's crypto/tls is stricter, and needs IPAddresses #x509.IPAddress(public_ip), #x509.IPAddress(private_ip), ]) # path_len=0 means this cert can only sign itself, not other certs. basic_contraints = x509.BasicConstraints(ca=True, path_length=None) now = datetime.utcnow() cert = (x509.CertificateBuilder().subject_name(name).issuer_name( name).public_key(key.public_key()).serial_number( uuid.uuid4().int).not_valid_before(now - timedelta(hours=1)). not_valid_after(now + timedelta(days=10 * 365)).add_extension( basic_contraints, False).add_extension(alt_names, False).sign(key, hashes.SHA256(), default_backend())) cert_pem = cert.public_bytes(encoding=serialization.Encoding.PEM) key_pem = key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption(), ) return cert_pem, key_pem
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))
def generate_certificate(key: EllipticCurvePrivateKeyWithSerialization): hostname = 'localhost' subject = issuer = x509.Name( [x509.NameAttribute(x509.NameOID.COMMON_NAME, hostname)]) cert: Certificate = x509.CertificateBuilder().subject_name( subject).issuer_name(issuer).public_key( key.public_key()).serial_number( x509.random_serial_number()).not_valid_before( utcnow() - datetime.timedelta(seconds=60)).not_valid_after( utcnow() + datetime.timedelta(days=1)).add_extension( x509.BasicConstraints(ca=True, path_length=None), critical=True).add_extension( x509.KeyUsage( digital_signature=True, content_commitment=False, key_encipherment=True, data_encipherment=False, key_agreement=True, key_cert_sign=True, crl_sign=False, encipher_only=False, decipher_only=False, ), critical=True, ).add_extension(x509.ExtendedKeyUsage([ x509.ExtendedKeyUsageOID.SERVER_AUTH, x509.ExtendedKeyUsageOID.CLIENT_AUTH, ]), critical=False).add_extension( x509.SubjectAlternativeName([ x509.DNSName(hostname), ]), critical=False).sign( key, hashes.SHA256(), default_backend()) return cert
def gencert(): filename = os.path.dirname(os.path.abspath(__file__)) + '/tempcert.pem' certfile = open(filename, 'wb') # Generate our key key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) certfile.write( key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption())) subject = issuer = 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"My Company"), x509.NameAttribute(NameOID.COMMON_NAME, u"example.com"), ]) 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=365)).add_extension( x509.SubjectAlternativeName( [x509.DNSName(u"localhost")]), critical=False, ).sign(key, hashes.SHA256(), default_backend())) certfile.write(cert.public_bytes(serialization.Encoding.PEM)) certfile.close() return filename
def createSSL(self): # Various details about who we are. For a self-signed certificate the # subject and issuer are always the same. subject = issuer = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"California"), x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"My Company"), x509.NameAttribute(NameOID.COMMON_NAME, u"mysite.com"), ]) cert = x509.CertificateBuilder().subject_name( subject ).issuer_name( issuer ).public_key( self.key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( # Our certificate will be valid for 10 days datetime.datetime.utcnow() + datetime.timedelta(days=10) ).add_extension( x509.SubjectAlternativeName([x509.DNSName(u"localhost")]), critical=False, # Sign our certificate with our private key ).sign(self.key, hashes.SHA256()) # Write our certificate out to disk. with open(self.path, "wb") as f: # path = path/to/store/certificate.pem f.write(cert.public_bytes(serialization.Encoding.PEM))
def generate_ca_signed_cert(ca_crt: bytes, ca_key: bytes, cert_out: Path, key_out: Path): one_day = datetime.timedelta(1, 0, 0) root_cert = x509.load_pem_x509_certificate(ca_crt, default_backend()) root_key = load_pem_private_key(ca_key, None, default_backend()) cert_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) new_subject = x509.Name( [ x509.NameAttribute(NameOID.COMMON_NAME, "Chia"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Chia"), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, "Organic Farming Division"), ] ) cert = ( x509.CertificateBuilder() .subject_name(new_subject) .issuer_name(root_cert.issuer) .public_key(cert_key.public_key()) .serial_number(x509.random_serial_number()) .not_valid_before(datetime.datetime.today() - one_day) .not_valid_after(datetime.datetime(2100, 8, 2)) .add_extension( x509.SubjectAlternativeName([x509.DNSName("chia.net")]), critical=False, ) .sign(root_key, hashes.SHA256(), default_backend()) ) cert_pem = cert.public_bytes(encoding=serialization.Encoding.PEM) key_pem = cert_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption(), ) cert_out.write_bytes(cert_pem) key_out.write_bytes(key_pem)
def issue_certificate(server, domains, cert_key, key): # generate csr from cryptography import x509 from cryptography.x509 import NameOID assert domains try: domains = [unicode(domain) for domain in domains] except NameError: pass name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, domains[0])]) san = x509.SubjectAlternativeName( [x509.DNSName(domain) for domain in domains]) csr = x509.CertificateSigningRequestBuilder().subject_name(name) \ .add_extension(san, critical=False).sign(cert_key, hashes.SHA256(), default_backend()) csr = csr.public_bytes(serialization.Encoding.DER) # requests header = generate_header(key) nonce = get_nonce(server) payload = { 'resource': 'new-cert', 'csr': base64url_encode(csr), } r = requests.post(lookup(server, 'new-cert'), json=sign_request(payload, nonce, key)) if r.status_code == 201: # Created cert = x509.load_der_x509_certificate(r.content, default_backend()).public_bytes( serialization.Encoding.PEM) chain = r.links.get('up') if chain: inter_cert = requests.get(chain['url']).content inter_cert = x509.load_der_x509_certificate( inter_cert, default_backend()).public_bytes(serialization.Encoding.PEM) return cert + (inter_cert or b'') else: raise IOError('Issue Certificate Failed: {} {}: {}'.format( r.status_code, r.reason, r.text))
def generate_self_signed_certificate(private_key, certificate_path): """Generate a self signed certificate using a generated private key. The certificate will be created in 'CONFIG_PATH/ssl/server.crt'. Parameters ---------- private_key : RSAPrivateKey Private key. certificate_path : str Path where the self signed certificate will be generated. """ # Generate private key # Various details about who we are. For a self-signed certificate the # subject and issuer are always the same. subject = issuer = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"California"), x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Wazuh"), x509.NameAttribute(NameOID.COMMON_NAME, u"wazuh.com"), ]) cert = x509.CertificateBuilder().subject_name(subject).issuer_name( issuer).public_key(private_key.public_key()).serial_number( x509.random_serial_number()).not_valid_before( datetime.datetime.utcnow()).not_valid_after( # Our certificate will be valid for 10 days datetime.datetime.utcnow() + datetime.timedelta(days=365)).add_extension( x509.SubjectAlternativeName( [x509.DNSName(u"localhost")]), critical=False, # Sign our certificate with our private key ).sign(private_key, hashes.SHA256(), crypto_default_backend()) # Write our certificate out to disk. with open(certificate_path, 'wb') as f: f.write(cert.public_bytes(serialization.Encoding.PEM)) os.chmod(certificate_path, 0o400)
def generate_certificate_request(common_name, country=None, state=None, locality=None, organization=None, organization_unit=None, email=None, passphrase=None, _backend=None): attribs = { "common_name": common_name, "country": country, "state": state, "locality": locality, "organization": organization, "organization_unit": organization_unit, "email": email, } backend = _backend or default_backend() private_key = generate_private_key(common_name + ".key", passphrase, backend) builder = x509.CertificateSigningRequestBuilder() builder = builder.subject_name(x509.Name(_convert_attributes(attribs))) builder = builder.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) builder = builder.add_extension(x509.SubjectAlternativeName( [x509.DNSName(common_name)]), critical=True) request = builder.sign(private_key, hashes.SHA256(), backend) with open(common_name + ".csr.pem", "wb") as fo: fo.write(request.public_bytes(serialization.Encoding.PEM)) return private_key, request