155 lines
8.2 KiB
Python
155 lines
8.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Lab 7, research track 1: attacker holds the worker's credentials. What can they do?
|
|
|
|
--profile after the worker identity of this stand: DB role messenger_worker, S3 key svc-worker, Kafka cert CN=worker, AppRole "worker"
|
|
--profile before model of the lab 6 flat trust: one over-privileged credential set shared by everything (DB owner, S3 root, Kafka admin identity)
|
|
|
|
Runs inside the backend network (security-tests/run_in_net.sh worker_compromise.py --profile after --out /t/../evidence/x.json is not
|
|
writable: results are printed as JSON on stdout; redirect on the host). No secret value is printed.
|
|
Hypothesis: with least privilege the compromised worker can only touch job state, staging reads and attachments writes; everything else is denied.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import os
|
|
import socket
|
|
import ssl
|
|
import sys
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
P = "/pki"
|
|
CA = f"{P}/ca/ca.crt"
|
|
OPS = "/ops"
|
|
|
|
|
|
def rd(path):
|
|
return open(path, encoding="utf-8").read().strip()
|
|
|
|
|
|
def classify_db(sql, user, password):
|
|
import psycopg
|
|
try:
|
|
with psycopg.connect(host="postgres", dbname="messenger", user=user, password=password, sslmode="verify-full", sslrootcert=CA,
|
|
connect_timeout=5, autocommit=True) as conn:
|
|
conn.execute(sql)
|
|
return "allowed"
|
|
except psycopg.errors.InsufficientPrivilege:
|
|
return "denied"
|
|
except psycopg.Error as exc:
|
|
return "error:" + type(exc).__name__
|
|
|
|
|
|
def classify_s3(op, 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))
|
|
b = "messenger-attachments"
|
|
try:
|
|
{"get": lambda k: s3.get_object(Bucket=b, Key=k), "put": lambda k: s3.put_object(Bucket=b, Key=k, Body=b"probe"),
|
|
"delete": lambda k: s3.delete_object(Bucket=b, Key=k), "list": lambda k: s3.list_objects_v2(Bucket=b, MaxKeys=1)}[op](key_of[op])
|
|
return "allowed"
|
|
except ClientError as exc:
|
|
code = exc.response["Error"]["Code"]
|
|
return "allowed" if code in ("NoSuchKey", "404") else ("denied" if code in ("AccessDenied", "403") else "error:" + code)
|
|
|
|
|
|
key_of = {}
|
|
|
|
|
|
def kafka(identity, action):
|
|
from confluent_kafka import Consumer, Producer
|
|
base = {"bootstrap.servers": "kafka:9092", "security.protocol": "SSL", "ssl.ca.location": CA,
|
|
"ssl.certificate.location": f"{P}/{identity}/tls.crt", "ssl.key.location": f"{P}/{identity}/tls.key"}
|
|
if action == "produce":
|
|
out = []
|
|
p = Producer({**base, "message.timeout.ms": 8000})
|
|
p.produce("attachment-jobs", b"compromise-probe", on_delivery=lambda e, m: out.append(str(e) if e else "OK"))
|
|
p.flush(10)
|
|
return "allowed" if out and out[0] == "OK" else ("denied" if out and "AUTHORIZATION" in out[0].upper() else "error:" + (out[0] if out else "none"))
|
|
group = "attachment-workers" if action == "consume_own_group" else "attacker-group"
|
|
errs = []
|
|
c = Consumer({**base, "group.id": group, "enable.auto.commit": False, "auto.offset.reset": "latest", "error_cb": lambda e: errs.append(str(e))})
|
|
c.subscribe(["attachment-jobs"])
|
|
for _ in range(6):
|
|
m = c.poll(1.0)
|
|
if m is not None and m.error():
|
|
errs.append(str(m.error()))
|
|
c.close()
|
|
text = " ".join(errs).upper()
|
|
return "denied" if "AUTHORIZATION" in text else "allowed"
|
|
|
|
|
|
def bao(method, path, token=None, body=None):
|
|
ctx = ssl.create_default_context(cafile=CA)
|
|
req = urllib.request.Request("https://openbao:8200/v1/" + path, method=method, data=json.dumps(body).encode() if body is not None else None)
|
|
if token:
|
|
req.add_header("X-Vault-Token", token)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=5, context=ctx) as r:
|
|
return r.status, json.loads(r.read() or b"{}")
|
|
except urllib.error.HTTPError as exc:
|
|
return exc.code, {}
|
|
|
|
|
|
def tls_status(host, port, cert):
|
|
c = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
|
c.load_verify_locations(CA)
|
|
c.load_cert_chain(f"{P}/{cert}/tls.crt", f"{P}/{cert}/tls.key")
|
|
try:
|
|
with socket.create_connection((host, port), timeout=5) as raw, c.wrap_socket(raw, server_hostname=host) as s:
|
|
s.sendall(b"GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n")
|
|
return "allowed" if s.recv(16).startswith(b"HTTP") else "denied"
|
|
except (ssl.SSLError, OSError):
|
|
return "denied"
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--profile", choices=["after", "before"], required=True)
|
|
a = ap.parse_args()
|
|
after = a.profile == "after"
|
|
if after: # the attacker logs in with the stolen AppRole material exactly like the worker does
|
|
_, login = bao("POST", "auth/approle/login", body={"role_id": rd("/approle/role_id"), "secret_id": rd("/approle/secret_id")})
|
|
token = login["auth"]["client_token"]
|
|
_, kv = bao("GET", "kv/data/worker", token)
|
|
db_user, db_pw, s3k, s3s, kid = "messenger_worker", kv["data"]["data"]["db_password"], kv["data"]["data"]["s3_access_key"], kv["data"]["data"]["s3_secret_key"], "worker"
|
|
else:
|
|
token = None
|
|
db_user, db_pw, s3k, s3s, kid = "messenger", rd(f"{OPS}/postgres_password"), rd(f"{OPS}/s3_root_user"), rd(f"{OPS}/s3_root_password"), "kafka-admin"
|
|
r = {}
|
|
r["db: SELECT attachment_jobs (job state)"] = ("allowed", classify_db("SELECT 1 FROM attachment_jobs LIMIT 1", db_user, db_pw))
|
|
r["db: UPDATE attachments (status)"] = ("allowed", classify_db("UPDATE attachments SET status=status WHERE false", db_user, db_pw))
|
|
r["db: SELECT users.password_hash"] = ("denied", classify_db("SELECT password_hash FROM users LIMIT 1", db_user, db_pw))
|
|
r["db: SELECT messages (content)"] = ("denied", classify_db("SELECT text FROM messages LIMIT 1", db_user, db_pw))
|
|
r["db: DELETE FROM attachment_jobs"] = ("denied", classify_db("DELETE FROM attachment_jobs WHERE false", db_user, db_pw))
|
|
r["db: CREATE TABLE / DDL"] = ("denied", classify_db("CREATE TABLE attacker_probe(x int)", db_user, db_pw))
|
|
key_of.update({"get": "staging/probe-none", "put": "attachments/probe-worker.txt", "delete": "attachments/probe-worker.txt", "list": ""})
|
|
r["s3: GET staging/*"] = ("allowed", classify_s3("get", s3k, s3s))
|
|
key_of["get"] = "attachments/probe-none"
|
|
r["s3: GET attachments/* (finished files)"] = ("denied", classify_s3("get", s3k, s3s))
|
|
r["s3: PUT attachments/*"] = ("allowed", classify_s3("put", s3k, s3s))
|
|
r["s3: DELETE attachments/*"] = ("denied", classify_s3("delete", s3k, s3s))
|
|
key_of["put"] = "staging/probe-worker.txt"
|
|
r["s3: PUT staging/* (forge input)"] = ("denied", classify_s3("put", s3k, s3s))
|
|
r["s3: ListBucket"] = ("denied", classify_s3("list", s3k, s3s))
|
|
r["kafka: consume jobs topic, own group"] = ("allowed", kafka(kid, "consume_own_group"))
|
|
r["kafka: produce to jobs topic (forge jobs)"] = ("denied", kafka(kid, "produce"))
|
|
r["kafka: consume with another group"] = ("denied", kafka(kid, "consume_other_group"))
|
|
if after:
|
|
r["bao: read kv/data/worker (own secret)"] = ("allowed", "allowed" if bao("GET", "kv/data/worker", token)[0] == 200 else "denied")
|
|
r["bao: read kv/data/api"] = ("denied", "allowed" if bao("GET", "kv/data/api", token)[0] == 200 else "denied")
|
|
r["bao: write sys policy"] = ("denied", "allowed" if bao("PUT", "sys/policies/acl/evil", token, {"policy": 'path "*" {capabilities=["sudo"]}'})[0] in (200, 204) else "denied")
|
|
r["api: connect to api:8443 with worker certificate"] = ("denied", tls_status("api", 8443, "worker"))
|
|
out = {"profile": a.profile, "probes": [{"probe": k, "expected_after": e, "observed": o} for k, (e, o) in r.items()]}
|
|
print(json.dumps(out, indent=1, ensure_ascii=False))
|
|
if after:
|
|
bad = [k for k, (e, o) in r.items() if e != o]
|
|
print("MISMATCH: " + "; ".join(bad) if bad else "PASS: every probe matches the least-privilege expectation", file=sys.stderr)
|
|
sys.exit(1 if bad else 0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|