Files
mtusi2026lab7/scripts/pki.py

141 lines
5.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Create an offline CA and individually scoped TLS identities for the local lab."""
import argparse
from datetime import datetime, timedelta, timezone
from ipaddress import ip_address
from pathlib import Path
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
ROOT = Path(__file__).resolve().parents[1]
PRIVATE = ROOT / "certs" / "private"
CA_CERT = PRIVATE / "ca.crt"
CA_KEY = PRIVATE / "ca.key"
SERVER_ROLES = {
"public": ("localhost", "127.0.0.1"),
"api": ("api",),
"db": ("db",),
"s3": ("s3",),
"cache": ("cache",),
"broker": ("broker",),
"collector": ("collector",),
"loki": ("loki",),
"tempo": ("tempo",),
"prometheus": ("prometheus",),
"grafana": ("grafana", "localhost", "127.0.0.1"),
"bao": ("bao", "localhost", "127.0.0.1"),
}
CLIENT_ROLES = (
"lb", "api-client", "worker-client", "relay-client",
"collector-client", "grafana-client", "prom-client", "untrusted-role",
)
def name(label):
return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, label)])
def certificate(subject, issuer, key, days):
now = datetime.now(timezone.utc)
return (x509.CertificateBuilder().subject_name(subject).issuer_name(issuer)
.public_key(key.public_key()).serial_number(x509.random_serial_number())
.not_valid_before(now - timedelta(minutes=2)).not_valid_after(now + timedelta(days=days)))
def key_bytes(key):
return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
serialization.NoEncryption())
def publish(path, content):
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_bytes(content)
temporary.replace(path)
def ensure_ca():
PRIVATE.mkdir(parents=True, mode=0o700, exist_ok=True)
if CA_CERT.is_file() and CA_KEY.is_file():
return
if CA_CERT.exists() or CA_KEY.exists():
raise RuntimeError("Incomplete CA material. Restore the CA before issuing more certificates.")
key = rsa.generate_private_key(public_exponent=65537, key_size=3072)
subject = name("MTUSI-Shemruk-Lab-CA")
ca = (certificate(subject, subject, key, 365)
.add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
.add_extension(x509.KeyUsage(False, False, False, False, False, True, True, False, False), critical=True)
.sign(key, hashes.SHA256()))
publish(CA_KEY, key_bytes(key))
publish(CA_CERT, ca.public_bytes(serialization.Encoding.PEM))
def issue(role, days, rotate=False):
cert = PRIVATE / f"{role}.crt"
key = PRIVATE / f"{role}.key"
if cert.is_file() and key.is_file() and not rotate:
return
if not rotate and (cert.exists() or key.exists()):
raise RuntimeError(f"Incomplete TLS identity {role}")
server = role in SERVER_ROLES
names = SERVER_ROLES[role] if server else (role,)
san = [x509.IPAddress(ip_address(n)) if n == "127.0.0.1" else x509.DNSName(n) for n in names]
usage = ExtendedKeyUsageOID.SERVER_AUTH if server else ExtendedKeyUsageOID.CLIENT_AUTH
ca = x509.load_pem_x509_certificate(CA_CERT.read_bytes())
ca_key = serialization.load_pem_private_key(CA_KEY.read_bytes(), password=None)
leaf_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
leaf = (certificate(name(role), ca.subject, leaf_key, days)
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(x509.KeyUsage(True, False, True, False, False, False, False, False, False), critical=True)
.add_extension(x509.ExtendedKeyUsage([usage]), critical=False)
.add_extension(x509.SubjectAlternativeName(san), critical=False)
.sign(ca_key, hashes.SHA256()))
publish(key, key_bytes(leaf_key))
publish(cert, leaf.public_bytes(serialization.Encoding.PEM))
def bundle(role):
bundle_path = PRIVATE / f"{role}.pem"
cert = (PRIVATE / f"{role}.crt").read_bytes()
key = (PRIVATE / f"{role}.key").read_bytes()
bundle_path.write_bytes(cert + key)
def negative_fixture():
cert_path, key_path = PRIVATE / "foreign-client.crt", PRIVATE / "foreign-client.key"
if cert_path.is_file() and key_path.is_file():
return
ca_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
foreign_name = name("Foreign test CA")
subject = name("foreign-client")
leaf = (certificate(subject, foreign_name, key, 30)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]), critical=False)
.add_extension(x509.SubjectAlternativeName([x509.DNSName("lb")]), critical=False)
.sign(ca_key, hashes.SHA256()))
publish(key_path, key_bytes(key))
publish(cert_path, leaf.public_bytes(serialization.Encoding.PEM))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--rotate", choices=(*SERVER_ROLES, *CLIENT_ROLES))
parser.add_argument("--days", type=int, default=30, choices=range(1, 91), metavar="1–90")
args = parser.parse_args()
ensure_ca()
if args.rotate:
issue(args.rotate, args.days, rotate=True)
else:
for role in (*SERVER_ROLES, *CLIENT_ROLES):
issue(role, args.days)
negative_fixture()
for role in ("public", "lb"):
bundle(role)
print("Локальный CA и сертификаты готовы.")
if __name__ == "__main__":
main()