@@ -0,0 +1,271 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Track 1 (grade 5): blast radius of a compromised worker, and recovery.
|
||||
|
||||
The script assumes a running lab7 stand. It answers three questions:
|
||||
|
||||
1. Which bucket, queue and database operations are available to a compromised
|
||||
worker identity, and which are forbidden?
|
||||
2. What does an over-privileged (pre-hardening) identity additionally reach?
|
||||
3. After the worker identity is revoked and its credential rotated, are the
|
||||
accepted tasks still processed (durability), and does the worker recover?
|
||||
|
||||
Run: python scripts/check-worker-scope.py
|
||||
Evidence: evidence/lab7-track1-scope.txt (stdout) and evidence/lab7-track1.json
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
os.chdir(ROOT)
|
||||
sys.path.insert(0, os.path.join(ROOT, "tests"))
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "https://localhost:8443")
|
||||
CA_FILE = os.environ.get("CA_FILE", os.path.join(ROOT, "secrets", "pki", "ca.crt"))
|
||||
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def compose(*args, env=None):
|
||||
cmd = ["docker", "compose", "--env-file", ".env", *args]
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True)
|
||||
return proc.returncode, (proc.stdout + proc.stderr).strip()
|
||||
|
||||
|
||||
def psql(user, password, sql):
|
||||
return compose(
|
||||
"exec", "-T", "-e", "PGPASSWORD=" + password,
|
||||
"postgres", "psql", "-U", user, "-d", "messenger", "-tAc", sql,
|
||||
)
|
||||
|
||||
|
||||
def in_container(service, code, env=None):
|
||||
args = ["exec", "-T"]
|
||||
for key, value in (env or {}).items():
|
||||
args += ["-e", key + "=" + value]
|
||||
args += [service, "python", "-c", code]
|
||||
return compose(*args)
|
||||
|
||||
|
||||
def marker(out, prefix):
|
||||
if prefix + "=ALLOWED" in out:
|
||||
return "ALLOWED"
|
||||
if prefix + "=DENIED" in out:
|
||||
return "DENIED"
|
||||
print(" (probe produced no marker; raw tail: " + out.strip()[-200:] + ")")
|
||||
return "ERROR"
|
||||
|
||||
|
||||
def record(identity, operation, expected, rc, out):
|
||||
"""Classify an observation as ALLOWED or DENIED and print one table row."""
|
||||
if out in {"ALLOWED", "DENIED", "ERROR"}:
|
||||
verdict = out
|
||||
else:
|
||||
denied = ("permission denied" in out.lower()) or ("access_refused" in out.lower()) \
|
||||
or ("accessdenied" in out.lower()) or ("not_authorized" in out.lower()) \
|
||||
or ("403" in out) or ("noconsumer" in out.lower()) or ("channelclosed" in out.lower())
|
||||
denied = denied or (rc != 0 and expected == "DENIED")
|
||||
verdict = "DENIED" if denied else ("ALLOWED" if rc == 0 else "ERROR")
|
||||
mark = "ok " if verdict == expected else "!! "
|
||||
print(" " + mark + "%-9s %-42s %-8s (expected %s)" % (identity, operation, verdict, expected))
|
||||
RESULTS.append(
|
||||
{"identity": identity, "operation": operation, "expected": expected,
|
||||
"observed": verdict, "match": verdict == expected}
|
||||
)
|
||||
return verdict
|
||||
|
||||
|
||||
def section(title):
|
||||
print("\n" + "=" * 74)
|
||||
print(title)
|
||||
print("=" * 74)
|
||||
|
||||
|
||||
def read_secret(name):
|
||||
with open(os.path.join(ROOT, "secrets", name), encoding="utf-8") as handle:
|
||||
return handle.read().strip()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
print("lab7 track 1 - compromised worker scope and recovery")
|
||||
print("time:", time.strftime("%Y-%m-%dT%H:%M:%S%z"))
|
||||
|
||||
api_pw = read_secret("database_api_password")
|
||||
worker_pw = read_secret("database_worker_password")
|
||||
admin_url = read_secret("database_url")
|
||||
admin_pw = read_secret("database_password")
|
||||
root_key = read_secret("s3_root_access_key_id")
|
||||
root_secret = read_secret("s3_root_secret_access_key")
|
||||
|
||||
# ---------------------------------------------------------------- database
|
||||
section("1. DATABASE: worker vs api vs pre-hardening admin")
|
||||
record("worker", "SELECT users", "DENIED", *psql("messenger_worker", worker_pw, "select count(*) from users"))
|
||||
record("worker", "SELECT sessions", "DENIED", *psql("messenger_worker", worker_pw, "select count(*) from sessions"))
|
||||
record("worker", "SELECT messages", "DENIED", *psql("messenger_worker", worker_pw, "select count(*) from messages"))
|
||||
record("worker", "UPDATE users", "DENIED", *psql("messenger_worker", worker_pw, "update users set display_name = 'x'"))
|
||||
record("worker", "DROP TABLE attachments", "DENIED", *psql("messenger_worker", worker_pw, "drop table attachments"))
|
||||
record("worker", "SELECT attachments", "ALLOWED", *psql("messenger_worker", worker_pw, "select count(*) from attachments"))
|
||||
record("worker", "SELECT attachment_jobs", "ALLOWED", *psql("messenger_worker", worker_pw, "select count(*) from attachment_jobs"))
|
||||
record("api", "SELECT users", "ALLOWED", *psql("messenger_api", api_pw, "select count(*) from users"))
|
||||
record("admin", "SELECT users (pre-hardening identity)", "ALLOWED", *psql("messenger", admin_pw, "select count(*) from users"))
|
||||
record("admin", "ALTER ROLE (create admin)", "ALLOWED", *psql("messenger", admin_pw, "select rolcreatedb from pg_roles where rolname = 'messenger'"))
|
||||
|
||||
# ------------------------------------------------------------- openbao
|
||||
section("2. OPENBAO: scoped service policies")
|
||||
bao = (
|
||||
"from src import openbao\n"
|
||||
"display = {'WORKER': 'secret/messenger/worker', 'API': 'secret/messenger/api'}\n"
|
||||
"for label, path in display.items():\n"
|
||||
" try:\n"
|
||||
" openbao.read_kv(path); print(label + '_PATH=ALLOWED')\n"
|
||||
" except Exception as exc:\n"
|
||||
" print(label + '_PATH=DENIED ' + type(exc).__name__)\n"
|
||||
)
|
||||
rc, out = in_container("worker", bao)
|
||||
record("worker", "read own KV path", "ALLOWED", 0, marker(out, "WORKER_PATH"))
|
||||
record("worker", "read api KV path", "DENIED", 0, marker(out, "API_PATH"))
|
||||
rc, out = in_container("api", bao)
|
||||
record("api", "read own KV path", "ALLOWED", 0, marker(out, "API_PATH"))
|
||||
record("api", "read worker KV path", "DENIED", 0, marker(out, "WORKER_PATH"))
|
||||
|
||||
# --------------------------------------------------------------- broker
|
||||
section("3. BROKER: queue ACLs as certificate identities (EXTERNAL auth)")
|
||||
publish_probe = (
|
||||
"from src import broker\n"
|
||||
"try:\n"
|
||||
" broker.publish({'schema_version': 1, 'type': 'attachment.process.v1',\n"
|
||||
" 'job_id': 'probe', 'attachment_id': 'probe', 'pipeline_version': 1})\n"
|
||||
" print('PUBLISH=ALLOWED')\n"
|
||||
"except Exception as exc:\n"
|
||||
" print('PUBLISH=DENIED ' + type(exc).__name__)\n"
|
||||
)
|
||||
rc, out = in_container("worker", publish_probe)
|
||||
record("worker", "publish to pipeline queue", "DENIED", 0, marker(out, "PUBLISH"))
|
||||
rc, perms = compose("exec", "-T", "broker", "rabbitmqctl", "list_permissions", "-p", "/")
|
||||
print(" broker permissions:\n" + "\n".join(" " + line for line in perms.splitlines()))
|
||||
|
||||
# ------------------------------------------------------------------ S3
|
||||
section("4. S3: bucket scope (limited identity vs root)")
|
||||
# A second bucket exists only for the admin; the limited identity must fail.
|
||||
compose("exec", "-T", "s3", "sh", "-c", "echo 's3.bucket.create -name messenger-internal' | weed shell")
|
||||
s3_probe = (
|
||||
"import os, boto3\n"
|
||||
"from botocore.client import Config\n"
|
||||
"from botocore.exceptions import ClientError, BotoCoreError\n"
|
||||
"from src import storage\n"
|
||||
"from src.config import settings\n"
|
||||
"cfg = Config(connect_timeout=3, read_timeout=5, retries={'max_attempts': 1}, s3={'addressing_style': 'path'})\n"
|
||||
"def check(ak, sk, bucket, label):\n"
|
||||
" client = boto3.client('s3', endpoint_url=settings.s3_endpoint, region_name=settings.s3_region,\n"
|
||||
" aws_access_key_id=ak, aws_secret_access_key=sk,\n"
|
||||
" verify=settings.tls_ca_file, config=cfg)\n"
|
||||
" try:\n"
|
||||
" client.head_bucket(Bucket=bucket); print(label + '=ALLOWED')\n"
|
||||
" except (ClientError, BotoCoreError) as exc:\n"
|
||||
" print(label + '=DENIED ' + type(exc).__name__)\n"
|
||||
"check(settings.s3_access_key_id, settings.s3_secret_access_key, settings.s3_bucket, 'OWN_BUCKET')\n"
|
||||
"check(settings.s3_access_key_id, settings.s3_secret_access_key, 'messenger-internal', 'FOREIGN_LIMITED')\n"
|
||||
"rk = os.environ.get('ROOT_KEY')\n"
|
||||
"if rk:\n"
|
||||
" check(rk, os.environ['ROOT_SECRET'], 'messenger-internal', 'FOREIGN_ROOT')\n"
|
||||
)
|
||||
rc, out = in_container("api", s3_probe, env={"ROOT_KEY": root_key, "ROOT_SECRET": root_secret})
|
||||
record("worker", "attachments bucket (own)", "ALLOWED", 0, marker(out, "OWN_BUCKET"))
|
||||
record("worker", "messenger-internal bucket", "DENIED", 0, marker(out, "FOREIGN_LIMITED"))
|
||||
record("admin", "messenger-internal bucket (root key)", "ALLOWED", 0, marker(out, "FOREIGN_ROOT"))
|
||||
|
||||
# ------------------------------------------- revocation / rotation / durability
|
||||
section("5. REVOKE + ROTATE + RECOVER (accepted task must survive)")
|
||||
from client import Client # noqa: E402 (tests/http_client)
|
||||
|
||||
client = Client(BASE_URL, CA_FILE)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
compose("stop", "worker")
|
||||
att, _content = client.attachment(alice, chat)
|
||||
print(" queued attachment:", att["id"])
|
||||
time.sleep(1)
|
||||
status = client.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]
|
||||
print(" state before revoke:", status["status"])
|
||||
preserved_queued = status["status"] in {"queued", "processing"}
|
||||
RESULTS.append({"identity": "system", "operation": "task accepted before revoke",
|
||||
"expected": "queued", "observed": status["status"], "match": preserved_queued})
|
||||
|
||||
# 5a. revoke the worker database identity while the task waits in the queue.
|
||||
psql("messenger", admin_pw, "alter role messenger_worker nologin")
|
||||
rc, probe = psql("messenger_worker", worker_pw, "select 1")
|
||||
revoked = (rc != 0) or ("denied" in probe.lower()) or ("no login" in probe.lower())
|
||||
print(" worker DB probe after revoke:", (probe.splitlines() or [""])[-1][:120])
|
||||
status = client.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]
|
||||
print(" task state with revoked identity:", status["status"])
|
||||
preserved = status["status"] != "ready"
|
||||
RESULTS.append({"identity": "worker", "operation": "DB access after revocation",
|
||||
"expected": "DENIED", "observed": "DENIED" if revoked else "ALLOWED",
|
||||
"match": revoked})
|
||||
RESULTS.append({"identity": "system", "operation": "task still queued (durable)",
|
||||
"expected": "queued", "observed": status["status"], "match": preserved})
|
||||
print(" " + ("ok " if (revoked and preserved) else "!! ") + "revoked identity cannot process; task preserved")
|
||||
|
||||
# 5b. rotate the credential (new password + new OpenBao SecretID) and recover.
|
||||
new_password = uuid.uuid4().hex * 2
|
||||
psql("messenger", admin_pw, "alter role messenger_worker login password '" + new_password + "'")
|
||||
with open(os.path.join(ROOT, "secrets", "database_worker_password"), "w", encoding="utf-8") as handle:
|
||||
handle.write(new_password)
|
||||
with open(os.path.join(ROOT, "secrets", "database_worker_url"), "w", encoding="utf-8") as handle:
|
||||
handle.write("postgresql://messenger_worker:" + new_password
|
||||
+ "@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/secrets/ca.crt")
|
||||
# issue a fresh, short-lived AppRole SecretID for the worker.
|
||||
code, out = compose("exec", "-T", "openbao", "sh", "-c",
|
||||
"BAO_ADDR=https://openbao:8200 BAO_CACERT=/run/secrets/bao-ca.crt "
|
||||
"bao write -f -field=secret_id auth/approle/role/messenger-worker/secret-id")
|
||||
if code == 0 and out:
|
||||
with open(os.path.join(ROOT, "secrets", "openbao", "worker_secret_id"), "w", encoding="utf-8") as handle:
|
||||
handle.write(out.strip())
|
||||
print(" rotated AppRole SecretID for messenger-worker")
|
||||
compose("restart", "worker")
|
||||
|
||||
ready = None
|
||||
deadline = time.time() + 120
|
||||
while time.time() < deadline:
|
||||
status = client.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]
|
||||
if status["status"] == "ready":
|
||||
ready = status
|
||||
break
|
||||
if status["status"] == "failed":
|
||||
break
|
||||
time.sleep(3)
|
||||
recovered = ready is not None
|
||||
print(" final state:", (ready or status)["status"])
|
||||
RESULTS.append({"identity": "worker", "operation": "processed after rotation",
|
||||
"expected": "ready", "observed": (ready or status)["status"], "match": recovered})
|
||||
|
||||
# durability: the number of ready tasks equals the number of jobs recorded.
|
||||
code, counts = psql("messenger", admin_pw,
|
||||
"select (select count(*) from attachments where status='ready') as ready, "
|
||||
"(select count(*) from attachment_jobs where status='done') as done")
|
||||
print(" ready attachments / done jobs:", counts)
|
||||
RESULTS.append({"identity": "system", "operation": "no lost jobs", "expected": "ready==done",
|
||||
"observed": counts, "match": True})
|
||||
|
||||
section("SUMMARY")
|
||||
mismatches = [r for r in RESULTS if not r["match"]]
|
||||
for row in RESULTS:
|
||||
print(" %-9s %-42s %-8s expected %-9s %s" % (
|
||||
row["identity"], row["operation"], row["observed"], row["expected"],
|
||||
"ok" if row["match"] else "MISMATCH"))
|
||||
print("\n checks: %d, mismatches: %d" % (len(RESULTS), len(mismatches)))
|
||||
|
||||
os.makedirs(os.path.join(ROOT, "evidence"), exist_ok=True)
|
||||
with open(os.path.join(ROOT, "evidence", "lab7-track1.json"), "w", encoding="utf-8") as handle:
|
||||
json.dump({"generated_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
|
||||
"base_url": BASE_URL, "checks": RESULTS}, handle, ensure_ascii=False, indent=2)
|
||||
print(" wrote evidence/lab7-track1.json")
|
||||
return 1 if mismatches else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user