198 lines
6.7 KiB
Python
198 lines
6.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Create a local CA and service certificates outside Git."""
|
|
from datetime import datetime, timedelta, timezone
|
|
from pathlib import Path
|
|
import ipaddress
|
|
|
|
from cryptography import x509
|
|
from cryptography.hazmat.primitives import hashes, serialization
|
|
from cryptography.hazmat.primitives.asymmetric import rsa
|
|
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
|
|
import argparse
|
|
|
|
|
|
APP_ROOT = Path("/app")
|
|
ROOT = APP_ROOT if (APP_ROOT / ".secrets").exists() else Path(__file__).resolve().parents[1]
|
|
OUT = ROOT / ".secrets" / "certs"
|
|
OUT.mkdir(parents=True, exist_ok=True)
|
|
OUT.parent.chmod(0o700)
|
|
OUT.chmod(0o700)
|
|
|
|
|
|
def key():
|
|
return rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
|
|
|
|
def write_key(path, private_key):
|
|
path.write_bytes(private_key.private_bytes(
|
|
serialization.Encoding.PEM,
|
|
serialization.PrivateFormat.TraditionalOpenSSL,
|
|
serialization.NoEncryption(),
|
|
))
|
|
path.chmod(0o600)
|
|
|
|
|
|
def write_cert(path, cert):
|
|
path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
|
|
|
|
|
def ca(name):
|
|
private_key = key()
|
|
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])
|
|
cert = (
|
|
x509.CertificateBuilder()
|
|
.subject_name(subject)
|
|
.issuer_name(subject)
|
|
.public_key(private_key.public_key())
|
|
.serial_number(x509.random_serial_number())
|
|
.not_valid_before(datetime.now(timezone.utc) - timedelta(minutes=5))
|
|
.not_valid_after(datetime.now(timezone.utc) + timedelta(days=365))
|
|
.add_extension(x509.BasicConstraints(ca=True, path_length=1), critical=True)
|
|
.add_extension(
|
|
x509.KeyUsage(
|
|
digital_signature=True,
|
|
key_encipherment=False,
|
|
key_cert_sign=True,
|
|
crl_sign=True,
|
|
content_commitment=False,
|
|
data_encipherment=False,
|
|
key_agreement=False,
|
|
encipher_only=False,
|
|
decipher_only=False,
|
|
),
|
|
critical=True,
|
|
)
|
|
.add_extension(
|
|
x509.SubjectKeyIdentifier.from_public_key(private_key.public_key()),
|
|
critical=False,
|
|
)
|
|
.add_extension(
|
|
x509.AuthorityKeyIdentifier.from_issuer_public_key(private_key.public_key()),
|
|
critical=False,
|
|
)
|
|
.sign(private_key, hashes.SHA256())
|
|
)
|
|
return private_key, cert
|
|
|
|
|
|
def leaf(ca_key, ca_cert, name, dns_names, ip_names=(), server=True, client=False):
|
|
private_key = key()
|
|
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])
|
|
usages = []
|
|
if server:
|
|
usages.append(ExtendedKeyUsageOID.SERVER_AUTH)
|
|
if client:
|
|
usages.append(ExtendedKeyUsageOID.CLIENT_AUTH)
|
|
builder = (
|
|
x509.CertificateBuilder()
|
|
.subject_name(subject)
|
|
.issuer_name(ca_cert.subject)
|
|
.public_key(private_key.public_key())
|
|
.serial_number(x509.random_serial_number())
|
|
.not_valid_before(datetime.now(timezone.utc) - timedelta(minutes=5))
|
|
.not_valid_after(datetime.now(timezone.utc) + timedelta(days=365))
|
|
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
|
|
.add_extension(
|
|
x509.SubjectAlternativeName(
|
|
[x509.DNSName(value) for value in dns_names]
|
|
+ [x509.IPAddress(ipaddress.ip_address(value)) for value in ip_names]
|
|
),
|
|
critical=False,
|
|
)
|
|
.add_extension(x509.ExtendedKeyUsage(usages), critical=False)
|
|
.add_extension(
|
|
x509.SubjectKeyIdentifier.from_public_key(private_key.public_key()),
|
|
critical=False,
|
|
)
|
|
.add_extension(
|
|
x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()),
|
|
critical=False,
|
|
)
|
|
)
|
|
cert = builder.sign(ca_key, hashes.SHA256())
|
|
return private_key, cert
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--force", action="store_true")
|
|
args = parser.parse_args()
|
|
required = (
|
|
"public-ca.crt", "public-ca.key",
|
|
"public-server.crt", "public-server.key",
|
|
"internal-ca.crt", "internal-ca.key",
|
|
"lb.crt", "lb.key", "api.crt", "api.key",
|
|
"db.crt", "db.key", "s3.crt", "s3.key",
|
|
"broker.crt", "broker.key", "openbao.crt", "openbao.key",
|
|
"otel-collector.crt", "otel-collector.key",
|
|
"loki.crt", "loki.key", "tempo.crt", "tempo.key",
|
|
"prometheus.crt", "prometheus.key",
|
|
)
|
|
if not args.force and all((OUT / name).is_file() for name in required):
|
|
for name in (
|
|
"public-server.key", "lb.key", "rogue.key", "api.key",
|
|
"db.key", "s3.key", "broker.key", "openbao.key",
|
|
"otel-collector.key", "loki.key", "tempo.key", "prometheus.key",
|
|
):
|
|
(OUT / name).chmod(0o644)
|
|
print("PASS: existing local CA and leaf certificates retained")
|
|
return
|
|
|
|
public_key, public_ca = ca("MTUSI Lab7 Public CA")
|
|
write_key(OUT / "public-ca.key", public_key)
|
|
write_cert(OUT / "public-ca.crt", public_ca)
|
|
public_leaf_key, public_leaf = leaf(
|
|
public_key,
|
|
public_ca,
|
|
"localhost",
|
|
["localhost", "lb"],
|
|
["127.0.0.1"],
|
|
server=True,
|
|
client=False,
|
|
)
|
|
write_key(OUT / "public-server.key", public_leaf_key)
|
|
write_cert(OUT / "public-server.crt", public_leaf)
|
|
|
|
internal_key, internal_ca = ca("MTUSI Lab7 Internal CA")
|
|
write_key(OUT / "internal-ca.key", internal_key)
|
|
write_cert(OUT / "internal-ca.crt", internal_ca)
|
|
|
|
lb_key, lb_cert = leaf(
|
|
internal_key, internal_ca, "messenger-lb",
|
|
["lb", "localhost"], client=True, server=False,
|
|
)
|
|
write_key(OUT / "lb.key", lb_key)
|
|
write_cert(OUT / "lb.crt", lb_cert)
|
|
|
|
rogue_key, rogue_cert = leaf(
|
|
internal_key, internal_ca, "rogue-client",
|
|
["rogue", "rogue-client"], client=True, server=False,
|
|
)
|
|
write_key(OUT / "rogue.key", rogue_key)
|
|
write_cert(OUT / "rogue.crt", rogue_cert)
|
|
|
|
api_key, api_cert = leaf(
|
|
internal_key, internal_ca, "messenger-api",
|
|
["api", "messenger-api"], server=True, client=False,
|
|
)
|
|
write_key(OUT / "api.key", api_key)
|
|
write_cert(OUT / "api.crt", api_cert)
|
|
|
|
for name in (
|
|
"db", "s3", "broker", "openbao", "otel-collector",
|
|
"loki", "tempo", "prometheus",
|
|
):
|
|
leaf_key, leaf_cert = leaf(
|
|
internal_key, internal_ca, name,
|
|
[name, "localhost"], ["127.0.0.1"],
|
|
server=True, client=False,
|
|
)
|
|
write_key(OUT / f"{name}.key", leaf_key)
|
|
write_cert(OUT / f"{name}.crt", leaf_cert)
|
|
|
|
print("PASS: local public/internal CA and leaf certificates created")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|