121 lines
4.6 KiB
Python
121 lines
4.6 KiB
Python
"""Generate local stand identities and credentials, once per secrets volume."""
|
|
|
|
import os
|
|
import secrets
|
|
import shutil
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
ROOT = Path("/state")
|
|
ROLES = {"api": 10, "worker": 5, "relay": 3, "reconciler": 2}
|
|
|
|
|
|
def openssl(*args):
|
|
subprocess.run(["openssl", *args], check=True, stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.PIPE)
|
|
|
|
|
|
def write(path, value):
|
|
path.write_text(value, encoding="utf-8")
|
|
|
|
|
|
def own(directory, uid):
|
|
for path in directory.iterdir():
|
|
path.chmod(0o400)
|
|
os.chown(path, uid, -1)
|
|
os.chown(directory, uid, -1)
|
|
|
|
|
|
def ca(directory, name):
|
|
key, crt = directory / f"{name}.key", directory / f"{name}.crt"
|
|
openssl("req", "-new", "-newkey", "rsa:3072", "-nodes", "-x509", "-sha256",
|
|
"-days", "365", "-subj", f"/CN={name}", "-addext",
|
|
"basicConstraints=critical,CA:TRUE", "-addext", "keyUsage=critical,keyCertSign,cRLSign",
|
|
"-keyout", key, "-out", crt)
|
|
return key, crt
|
|
|
|
|
|
def leaf(directory, name, issuer, purpose="server", extra_san=""):
|
|
key, crt = directory / f"{name}.key", directory / f"{name}.crt"
|
|
csr, ext = directory / "request.csr", directory / "extensions.cnf"
|
|
openssl("req", "-new", "-newkey", "rsa:2048", "-nodes", "-subj", f"/CN={name}",
|
|
"-keyout", key, "-out", csr)
|
|
write(ext, "basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\n"
|
|
"subjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid\n"
|
|
f"extendedKeyUsage={purpose}Auth\nsubjectAltName=DNS:{name}{extra_san}\n")
|
|
openssl("x509", "-req", "-in", csr, "-out", crt, "-CA", issuer[1], "-CAkey",
|
|
issuer[0], "-set_serial", f"0x{secrets.token_hex(16)}", "-sha256",
|
|
"-days", "90", "-extfile", ext)
|
|
csr.unlink()
|
|
ext.unlink()
|
|
return key, crt
|
|
|
|
|
|
def copy_ca(directory, issuer):
|
|
shutil.copyfile(issuer[1], directory / "ca.crt")
|
|
|
|
|
|
def bundle(directory, name, pair):
|
|
write(directory / name, pair[1].read_text() + pair[0].read_text())
|
|
|
|
|
|
def db_url(role, password, limit):
|
|
return (f"postgresql://{role}:{password}@postgres:5432/messenger?"
|
|
f"sslmode=require&sslaccept=strict&sslcert=/run/tls/ca.crt&connection_limit={limit}"
|
|
"&pool_timeout=5&connect_timeout=5&socket_timeout=10"
|
|
f"&application_name={role}&options=-c%20statement_timeout%3D5000")
|
|
|
|
|
|
def main():
|
|
if (ROOT / "initialized").is_file():
|
|
print("Local identities already initialized")
|
|
return
|
|
os.umask(0o077)
|
|
names = ("operator", "lb", "checks", "postgres", "migrate", *ROLES)
|
|
directories = {name: ROOT / name for name in names}
|
|
for directory in directories.values():
|
|
directory.mkdir(exist_ok=True)
|
|
operator = directories["operator"]
|
|
server_ca = ca(operator, "lab7-servers")
|
|
client_ca = ca(operator, "lab7-clients")
|
|
for directory in directories.values():
|
|
copy_ca(directory, server_ca)
|
|
|
|
api = directories["api"]
|
|
lb = directories["lb"]
|
|
checks = directories["checks"]
|
|
leaf(api, "api", server_ca)
|
|
shutil.copyfile(client_ca[1], api / "clients.crt")
|
|
lb_client = leaf(lb, "lb.lab7.internal", client_ca, "client")
|
|
bundle(lb, "client.pem", lb_client)
|
|
for path in lb_client:
|
|
shutil.copyfile(path, checks / path.name)
|
|
bundle(lb, "ingress.pem", leaf(lb, "localhost", server_ca, extra_san=",IP:127.0.0.1"))
|
|
leaf(checks, "unrelated.lab7.internal", client_ca, "client")
|
|
foreign_ca = ca(operator, "lab7-untrusted")
|
|
foreign_dir = checks / "foreign"
|
|
foreign_dir.mkdir(exist_ok=True)
|
|
foreign = leaf(foreign_dir, "lb.lab7.internal", foreign_ca, "client")
|
|
for path in foreign:
|
|
path.rename(checks / f"foreign-{path.name}")
|
|
foreign_dir.rmdir()
|
|
shutil.copyfile(foreign_ca[1], checks / "foreign-ca.crt")
|
|
|
|
leaf(directories["postgres"], "postgres", server_ca)
|
|
passwords = {role: secrets.token_hex(24) for role in (*ROLES, "migrate", "operator")}
|
|
for role, password in passwords.items():
|
|
write(directories["postgres"] / f"{role}_password", password)
|
|
write(directories["migrate"] / "database_url", db_url("migrate", passwords["migrate"], 2))
|
|
for role, limit in ROLES.items():
|
|
write(directories[role] / "database_url", db_url(role, passwords[role], limit))
|
|
shutil.copyfile(api / "api.crt", checks / "api.crt")
|
|
owners = {"lb": 1000, "postgres": 70, "migrate": 1000, **dict.fromkeys(ROLES, 1000)}
|
|
for name, uid in owners.items():
|
|
own(directories[name], uid)
|
|
(ROOT / "initialized").touch()
|
|
print("Generated local TLS identities and stand credentials")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|