feat(openbao): lab7 rotate the reconciler client certificate
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
"""Ротация сертификата reconciler для OpenBao и OTLP."""
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from rotation_common import CA, PRIVATE, Operator, compose, write_file
|
||||
|
||||
tls = PRIVATE / "telemetry"
|
||||
cert = tls / "reconciler-client.crt"
|
||||
key = tls / "reconciler-client.key"
|
||||
pending = tls / ".rotation-reconciler"
|
||||
deny = PRIVATE / "otel-revoked"
|
||||
|
||||
|
||||
def openssl(*args):
|
||||
return subprocess.check_output(["openssl", *args], text=True)
|
||||
|
||||
|
||||
def issue():
|
||||
if pending.exists():
|
||||
return
|
||||
with tempfile.TemporaryDirectory(dir=tls) as temp:
|
||||
stage = Path(temp) / "pending"
|
||||
stage.mkdir()
|
||||
(stage / "old.crt").write_bytes(cert.read_bytes())
|
||||
name = "lab7-telemetry-reconciler"
|
||||
openssl("req", "-new", "-nodes", "-newkey", "rsa:2048", "-subj", "/CN=" + name,
|
||||
"-keyout", stage / "new.key", "-out", stage / "request")
|
||||
ext = stage / "ext"
|
||||
ext.write_text(f"subjectAltName=DNS:{name}\nextendedKeyUsage=clientAuth\nbasicConstraints=critical,CA:FALSE\n")
|
||||
import secrets
|
||||
openssl("x509", "-req", "-sha256", "-days", "30", "-in", stage / "request",
|
||||
"-CA", CA, "-CAkey", CA.with_name("ca.key"), "-set_serial",
|
||||
"0x" + secrets.token_hex(16), "-extfile", ext, "-out", stage / "new.crt")
|
||||
openssl("verify", "-purpose", "sslclient", "-CAfile", CA, stage / "new.crt")
|
||||
stage.rename(pending)
|
||||
|
||||
|
||||
def probe(files, endpoint):
|
||||
# Передаём временную пару по stdin. В аргументах процессов ключа нет.
|
||||
paths = {"bao": ("https://openbao:8200/v1/auth/cert/login", '{"name":"reconciler"}'),
|
||||
"otel": ("https://otel-collector:4318/v1/traces", '{"resourceSpans":[]}')}
|
||||
url, body = paths[endpoint]
|
||||
script = """set -eu
|
||||
umask 077
|
||||
pair=$(mktemp /tmp/rotation.XXXXXX)
|
||||
trap 'rm -f "$pair"' EXIT
|
||||
cat > "$pair"
|
||||
curl -sS --max-time 10 --cacert /tls/ca.crt --cert "$pair" --key "$pair" \\
|
||||
-H 'Content-Type: application/json' --data "$2" -o /dev/null -w '%{http_code}' "$1"
|
||||
"""
|
||||
pem = b"\n".join(f.read_bytes() for f in files)
|
||||
return compose("exec", "-T", "api", "sh", "-c", script, "probe", url, body,
|
||||
input=pem, capture_output=True).stdout.decode()
|
||||
|
||||
|
||||
def main():
|
||||
operator = Operator()
|
||||
issue()
|
||||
deny.mkdir(mode=0o755, exist_ok=True)
|
||||
serial = openssl("x509", "-in", pending / "old.crt", "-noout", "-serial").strip().split("=")[1]
|
||||
if not re.fullmatch("[0-9A-Fa-f]+", serial):
|
||||
raise SystemExit("Некорректный серийный номер.")
|
||||
new = pending / "new.crt", pending / "new.key"
|
||||
operator.request("auth/cert/certs/reconciler", {
|
||||
"certificate": new[0].read_text(), "token_policies": ["lab7-reconciler"],
|
||||
"token_ttl": "2m", "token_max_ttl": "5m"})
|
||||
if probe(new, "bao") != "200":
|
||||
raise SystemExit("OpenBao не принял новый сертификат. Повторите после диагностики.")
|
||||
write_file(cert, new[0].read_bytes(), 0o444)
|
||||
write_file(key, new[1].read_bytes(), 0o444)
|
||||
compose("up", "-d", "--no-deps", "--no-build", "--force-recreate", "reconciler")
|
||||
# Новый процесс должен пройти bootstrap, получив собственные файлы в tmpfs.
|
||||
import time
|
||||
for _ in range(60):
|
||||
try:
|
||||
compose("exec", "-T", "reconciler", "sh", "-c",
|
||||
'test "$(cat /proc/1/comm)" = reconciler && test -s /run/bao/db_reconciler',
|
||||
capture_output=True)
|
||||
break
|
||||
except subprocess.CalledProcessError:
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise SystemExit("Reconciler не завершил bootstrap. Повторите ротацию после диагностики.")
|
||||
rule = f'if ($ssl_client_serial ~* "^{serial}$") {{ return 403; }}\n'
|
||||
write_file(deny / (serial + ".conf"), rule.encode(), 0o444)
|
||||
compose("up", "-d", "--no-deps", "--no-build", "--force-recreate", "otel-collector-tls")
|
||||
for _ in range(20):
|
||||
try:
|
||||
if probe(new, "otel") == "200":
|
||||
break
|
||||
except subprocess.CalledProcessError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise SystemExit("OTLP не принял новый сертификат.")
|
||||
shutil.rmtree(pending)
|
||||
print("Сертификат reconciler заменён, старый серийный номер заблокирован на OTLP.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.umask(0o077)
|
||||
main()
|
||||
Reference in New Issue
Block a user