forked from mtusi2026/mtusi2026lab7
193 lines
9.9 KiB
Python
193 lines
9.9 KiB
Python
"""lab7: минимальные права identity сервисов — изнутри каждого сервиса, его же учётными данными.
|
|
|
|
python student-tests/test_least_privilege.py
|
|
|
|
В контейнерах api / worker / dispatcher / janitor выполняется скрипт, который берёт секреты так же, как сам
|
|
сервис (OpenBao по сертификату сервиса), и пробует разрешённые и запрещённые действия:
|
|
PostgreSQL — своя роль (GRANT из migrations/006_roles.sql), всё в транзакции с ROLLBACK;
|
|
S3 — свой ключ (права по prefix из s3_config), временные ключи probe-<uuid> удаляются;
|
|
OpenBao — свой токен (policy только на свой путь);
|
|
Redis — ACL-пользователь api (только session:* и ratelimit:*, только нужные команды).
|
|
Итог — таблица и evidence/least-privilege.json. Значения секретов не печатаются.
|
|
"""
|
|
import json
|
|
import subprocess
|
|
|
|
from common import EVIDENCE, ROOT, check
|
|
|
|
SCRIPT = r'''
|
|
import io, json, sys, uuid
|
|
import psycopg
|
|
import secretstore
|
|
from secretstore import store, Client, SecretsUnavailable
|
|
import settings
|
|
|
|
store.start()
|
|
role = settings.BAO_ROLE
|
|
results = []
|
|
|
|
def rec(area, action, expect, observed, detail=""):
|
|
results.append({"service": role, "area": area, "action": action, "expect": expect,
|
|
"observed": observed, "pass": observed == expect, "detail": str(detail)[:160]})
|
|
|
|
# ---------- PostgreSQL ----------
|
|
import dbconn
|
|
def sql(action, statement, expect):
|
|
try:
|
|
with dbconn.connect() as conn:
|
|
with conn.transaction():
|
|
conn.execute(statement)
|
|
raise _Rollback()
|
|
except _Rollback:
|
|
rec("postgres", action, expect, "allowed")
|
|
except psycopg.errors.InsufficientPrivilege as exc:
|
|
rec("postgres", action, expect, "denied", exc.diag.message_primary)
|
|
except psycopg.Error as exc:
|
|
rec("postgres", action, expect, "error", type(exc).__name__ + ": " + str(exc).splitlines()[0])
|
|
|
|
class _Rollback(Exception):
|
|
pass
|
|
|
|
PG = {
|
|
"api": [("SELECT users", "SELECT count(*) FROM users", "allowed"),
|
|
("INSERT outbox (enqueue)", "INSERT INTO outbox (job_id) SELECT NULL WHERE false", "allowed"),
|
|
("UPDATE users.username", "UPDATE users SET username = username WHERE false", "denied"),
|
|
("SELECT outbox", "SELECT count(*) FROM outbox", "denied"),
|
|
("DELETE messages", "DELETE FROM messages WHERE false", "denied"),
|
|
("DROP TABLE messages", "DROP TABLE messages", "denied"),
|
|
("CREATE TABLE", "CREATE TABLE probe_evil (x int)", "denied"),
|
|
("ALTER ROLE (escalate)", "ALTER ROLE messenger_api SUPERUSER", "denied")],
|
|
"worker": [("SELECT attachments", "SELECT count(*) FROM attachments", "allowed"),
|
|
("SELECT users (passwords)", "SELECT count(*) FROM users", "denied"),
|
|
("SELECT messages", "SELECT count(*) FROM messages", "denied"),
|
|
("DELETE attachments", "DELETE FROM attachments WHERE false", "denied"),
|
|
("UPDATE outbox", "UPDATE outbox SET published_at = published_at WHERE false", "denied")],
|
|
"dispatcher": [("SELECT outbox", "SELECT count(*) FROM outbox", "allowed"),
|
|
("SELECT users", "SELECT count(*) FROM users", "denied"),
|
|
("SELECT messages", "SELECT count(*) FROM messages", "denied"),
|
|
("DELETE attachments", "DELETE FROM attachments WHERE false", "denied")],
|
|
"janitor": [("SELECT attachments", "SELECT count(*) FROM attachments", "allowed"),
|
|
("SELECT users", "SELECT count(*) FROM users", "denied"),
|
|
("INSERT messages", "INSERT INTO messages (id) SELECT NULL WHERE false", "denied"),
|
|
("DELETE chats", "DELETE FROM chats WHERE false", "denied")],
|
|
}
|
|
for action, statement, expect in PG.get(role, []):
|
|
sql(action, statement, expect)
|
|
|
|
# ---------- S3 ----------
|
|
if role in ("api", "worker", "janitor"):
|
|
from botocore.exceptions import ClientError
|
|
import storage
|
|
client, bucket = storage._clients.get(), settings.S3_BUCKET
|
|
def s3(action, fn, expect):
|
|
try:
|
|
fn()
|
|
rec("s3", action, expect, "allowed")
|
|
except ClientError as exc:
|
|
code = exc.response.get("Error", {}).get("Code", "?")
|
|
rec("s3", action, expect, "denied" if code in ("AccessDenied", "403", "Forbidden") else "error", code)
|
|
tag = "probe-" + uuid.uuid4().hex
|
|
put = lambda key: client.put_object(Bucket=bucket, Key=key, Body=b"probe")
|
|
get = lambda key: client.get_object(Bucket=bucket, Key=key)["Body"].read()
|
|
if role == "api":
|
|
s3("PUT staging/", lambda: put(f"staging/{tag}"), "allowed")
|
|
s3("DELETE staging/ (rollback)", lambda: client.delete_object(Bucket=bucket, Key=f"staging/{tag}"), "allowed")
|
|
s3("PUT attachments/ (worker's prefix)", lambda: put(f"attachments/{tag}"), "denied")
|
|
s3("GET staging/ (upload sources)", lambda: get("staging/none"), "denied")
|
|
s3("LIST bucket", lambda: client.list_objects_v2(Bucket=bucket, MaxKeys=1), "denied")
|
|
s3("DELETE attachments/", lambda: client.delete_object(Bucket=bucket, Key=f"attachments/{tag}"), "denied")
|
|
s3("CREATE bucket", lambda: client.create_bucket(Bucket="probe-" + uuid.uuid4().hex[:8]), "denied")
|
|
if role == "worker":
|
|
s3("PUT attachments/", lambda: put(f"attachments/{tag}"), "allowed")
|
|
s3("LIST attachments/", lambda: client.list_objects_v2(Bucket=bucket, Prefix="attachments/", MaxKeys=1),
|
|
"allowed")
|
|
s3("LIST bucket root", lambda: client.list_objects_v2(Bucket=bucket, MaxKeys=1), "denied")
|
|
s3("PUT outside known prefixes", lambda: put(f"evil/{tag}"), "denied")
|
|
s3("CREATE bucket", lambda: client.create_bucket(Bucket="probe-" + uuid.uuid4().hex[:8]), "denied")
|
|
try: # убрать за собой: у worker нет права удалить attachments/ — сделает janitor (сирота старше grace)
|
|
pass
|
|
finally:
|
|
pass
|
|
if role == "janitor":
|
|
s3("LIST bucket", lambda: client.list_objects_v2(Bucket=bucket, MaxKeys=1), "allowed")
|
|
s3("GET object content", lambda: get("staging/none"), "denied")
|
|
s3("CREATE bucket", lambda: client.create_bucket(Bucket="probe-" + uuid.uuid4().hex[:8]), "denied")
|
|
|
|
# ---------- OpenBao ----------
|
|
c = store._client
|
|
def bao(action, method, path, expect, body=None):
|
|
try:
|
|
c.request(method, path, body, token=c.token)
|
|
rec("openbao", action, expect, "allowed")
|
|
except SecretsUnavailable as exc:
|
|
rec("openbao", action, expect, "denied" if "HTTP 403" in str(exc) else "error", exc)
|
|
own = store._values.get(role, {})
|
|
rec("openbao", "own secret keys (no admin credentials)", "ok",
|
|
"ok" if not any(k.startswith(("db_owner", "s3_admin")) for k in own) else "has_admin_keys", sorted(own))
|
|
for other in ("api", "worker", "dispatcher", "janitor", "migrate", "s3-init"):
|
|
if other != role:
|
|
bao(f"read messenger/{other}", "GET", f"/v1/messenger/data/{other}", "denied")
|
|
bao("write own secret", "POST", f"/v1/messenger/data/{role}", "denied", {"data": {"x": "y"}})
|
|
bao("write ACL policy", "PUT", "/v1/sys/policies/acl/probe-evil", "denied", {"policy": 'path "*" {capabilities=["read"]}'})
|
|
bao("list auth methods", "GET", "/v1/sys/auth", "denied")
|
|
bao("create token", "POST", "/v1/auth/token/create", "denied", {"policies": ["api"]})
|
|
|
|
# ---------- Redis (только api) ----------
|
|
if role == "api":
|
|
import redis
|
|
import auth
|
|
r = auth._redis
|
|
def red(action, fn, expect):
|
|
try:
|
|
fn()
|
|
rec("redis", action, expect, "allowed")
|
|
except redis.exceptions.NoPermissionError as exc:
|
|
rec("redis", action, expect, "denied", exc)
|
|
except redis.RedisError as exc:
|
|
rec("redis", action, expect, "error", type(exc).__name__)
|
|
red("GET session:*", lambda: r.get("session:probe"), "allowed")
|
|
red("GET other key", lambda: r.get("probe:other"), "denied")
|
|
red("KEYS *", lambda: r.keys("*"), "denied")
|
|
red("FLUSHALL", lambda: r.flushall(), "denied")
|
|
red("CONFIG GET", lambda: r.config_get("*"), "denied")
|
|
red("ACL LIST", lambda: r.acl_list(), "denied")
|
|
red("SUBSCRIBE / PUBLISH", lambda: r.publish("probe", "x"), "denied")
|
|
|
|
print(json.dumps(results))
|
|
'''
|
|
|
|
|
|
def run_in(service):
|
|
result = subprocess.run(["docker", "compose", "exec", "-T", service, "python", "-"], cwd=ROOT,
|
|
input=SCRIPT.encode(), capture_output=True, check=False)
|
|
check(result.returncode == 0, f"{service}: {result.stderr.decode('utf-8', 'replace')[-600:]}")
|
|
return json.loads(result.stdout.decode("utf-8").strip().splitlines()[-1])
|
|
|
|
|
|
def main():
|
|
rows = []
|
|
for service in ("api", "worker", "dispatcher", "janitor"):
|
|
rows += run_in(service)
|
|
current = None
|
|
for row in rows:
|
|
if (row["service"], row["area"]) != current:
|
|
current = (row["service"], row["area"])
|
|
print(f"\n{row['service']} -> {row['area']}")
|
|
mark = "PASS" if row["pass"] else "FAIL"
|
|
print(f" {mark} {row['action']:<42} expect {row['expect']:<8} observed {row['observed']}"
|
|
+ ("" if row["pass"] else f" ({row['detail']})"))
|
|
(EVIDENCE / "least-privilege.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1),
|
|
encoding="utf-8")
|
|
failed = [r for r in rows if not r["pass"]]
|
|
print(f"\n{len(rows)} checks, {len(failed)} failed; saved to evidence/least-privilege.json")
|
|
check(not failed, "least privilege violated")
|
|
print("PASS: every service identity can do its job and nothing else that was probed")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except AssertionError as exc:
|
|
print(f"FAIL: {exc}")
|
|
raise SystemExit(1)
|