forked from mtusi2026/mtusi2026lab7
lab 7 openbao
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab 7, track 1: proof that REVOKED worker credentials are dead on NEW connections, and the rotated ones work.
|
||||
|
||||
Runs inside the backend network (called by scripts/incident_worker.sh).
|
||||
Mounts: /pki (public CA at /pki/ca/ca.crt), /old (the worker secrets saved BEFORE the incident: secret_id, db_password, s3_secret),
|
||||
/approle (the NEW role_id + secret_id issued after the incident).
|
||||
Every probe opens a fresh TCP/TLS connection / performs a fresh login: an already open session or a cached token would prove nothing.
|
||||
No secret value is printed. Exit code 0 only if all 6 probes behave as expected.
|
||||
"""
|
||||
import json
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
CA = "/pki/ca/ca.crt"
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def rd(path):
|
||||
return open(path, encoding="utf-8").read().strip()
|
||||
|
||||
|
||||
def bao_login(role_id, secret_id):
|
||||
req = urllib.request.Request("https://openbao:8200/v1/auth/approle/login", method="POST",
|
||||
data=json.dumps({"role_id": role_id, "secret_id": secret_id}).encode())
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=5, context=ssl.create_default_context(cafile=CA)) as r:
|
||||
return r.status, json.loads(r.read())["auth"]["client_token"]
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code, None
|
||||
|
||||
|
||||
def bao_kv(token):
|
||||
req = urllib.request.Request("https://openbao:8200/v1/kv/data/worker", headers={"X-Vault-Token": token})
|
||||
with urllib.request.urlopen(req, timeout=5, context=ssl.create_default_context(cafile=CA)) as r:
|
||||
return json.loads(r.read())["data"]["data"]
|
||||
|
||||
|
||||
def db_connect(password):
|
||||
import psycopg
|
||||
try:
|
||||
with psycopg.connect(host="postgres", dbname="messenger", user="messenger_worker", password=password, sslmode="verify-full",
|
||||
sslrootcert=CA, connect_timeout=5) as conn:
|
||||
conn.execute("SELECT 1 FROM attachment_jobs LIMIT 1")
|
||||
return "connected"
|
||||
except psycopg.OperationalError as exc:
|
||||
return "rejected" if "password authentication failed" in str(exc) else "error:" + type(exc).__name__
|
||||
|
||||
|
||||
def s3_call(key, secret):
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
s3 = boto3.client("s3", endpoint_url="https://s3:9000", region_name="us-east-1", aws_access_key_id=key, aws_secret_access_key=secret, verify=CA,
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, retries={"max_attempts": 1}, connect_timeout=3))
|
||||
try:
|
||||
s3.get_object(Bucket="messenger-attachments", Key="staging/revocation-probe")
|
||||
return "accepted"
|
||||
except ClientError as exc:
|
||||
code = exc.response["Error"]["Code"]
|
||||
if code in ("NoSuchKey", "404"):
|
||||
return "accepted" # authenticated and authorised; the object simply does not exist
|
||||
return "rejected" if code in ("SignatureDoesNotMatch", "InvalidAccessKeyId", "AccessDenied", "403") else "error:" + code
|
||||
|
||||
|
||||
def expect(name, got, want):
|
||||
ok = got == want
|
||||
RESULTS.append(ok)
|
||||
print(("PASS " if ok else "FAIL ") + f"{name}: {got} (expected {want})")
|
||||
|
||||
|
||||
def main():
|
||||
role_id = rd("/approle/role_id")
|
||||
# old material (saved before the incident) -> must be dead on a NEW connection
|
||||
status, _ = bao_login(role_id, rd("/old/secret_id"))
|
||||
expect("OpenBao: login with OLD SecretID", "rejected" if status in (400, 403) else f"HTTP {status}", "rejected")
|
||||
expect("PostgreSQL: new connection with OLD role password", db_connect(rd("/old/db_password")), "rejected")
|
||||
expect("S3: new request with OLD svc-worker secret", s3_call("svc-worker", rd("/old/s3_secret")), "rejected")
|
||||
# new material -> must work, otherwise "rejected" above could simply mean "everything is down"
|
||||
status, token = bao_login(role_id, rd("/approle/secret_id"))
|
||||
expect("OpenBao: login with NEW SecretID", "accepted" if status == 200 else f"HTTP {status}", "accepted")
|
||||
if token:
|
||||
kv = bao_kv(token)
|
||||
expect("PostgreSQL: new connection with NEW role password", "accepted" if db_connect(kv["db_password"]) == "connected" else "rejected", "accepted")
|
||||
expect("S3: new request with NEW svc-worker secret", s3_call(kv["s3_access_key"], kv["s3_secret_key"]), "accepted")
|
||||
else:
|
||||
expect("PostgreSQL: new connection with NEW role password", "skipped (no token)", "accepted")
|
||||
expect("S3: new request with NEW svc-worker secret", "skipped (no token)", "accepted")
|
||||
print(f"\n{sum(RESULTS)}/{len(RESULTS)} probes as expected")
|
||||
sys.exit(0 if all(RESULTS) else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user