43 lines
1.7 KiB
Python
43 lines
1.7 KiB
Python
"""Self-signed certificate generation for the first start."""
|
|
|
|
import datetime
|
|
import ipaddress
|
|
import os
|
|
import socket
|
|
|
|
from cryptography import x509
|
|
from cryptography.hazmat.primitives import hashes, serialization
|
|
from cryptography.hazmat.primitives.asymmetric import ec
|
|
from cryptography.x509.oid import NameOID
|
|
|
|
|
|
def ensure_cert(cert_path, key_path):
|
|
if os.path.exists(cert_path) and os.path.exists(key_path):
|
|
return False
|
|
host = socket.gethostname()
|
|
key = ec.generate_private_key(ec.SECP256R1())
|
|
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, host),
|
|
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "PatchBay")])
|
|
sans = [x509.DNSName(host), x509.DNSName("localhost"), x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]
|
|
now = datetime.datetime.now(datetime.timezone.utc)
|
|
cert = (x509.CertificateBuilder()
|
|
.subject_name(name).issuer_name(name)
|
|
.public_key(key.public_key())
|
|
.serial_number(x509.random_serial_number())
|
|
.not_valid_before(now - datetime.timedelta(minutes=5))
|
|
.not_valid_after(now + datetime.timedelta(days=3650))
|
|
.add_extension(x509.SubjectAlternativeName(sans), critical=False)
|
|
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
|
|
.sign(key, hashes.SHA256()))
|
|
|
|
old = os.umask(0o077)
|
|
try:
|
|
with open(key_path, "wb") as f:
|
|
f.write(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
|
|
serialization.NoEncryption()))
|
|
finally:
|
|
os.umask(old)
|
|
with open(cert_path, "wb") as f:
|
|
f.write(cert.public_bytes(serialization.Encoding.PEM))
|
|
return True
|