Добавить стенд лабораторной 7 с mTLS, OpenBao и least privilege worker.

Закрывает обязательный минимум и трек 1: ротация leaf и секрета, sealed OpenBao и сохранность queued-задачи.
This commit is contained in:
2026-11-07 20:46:02 +03:00
parent 20afc2c790
commit baafe2a3ae
76 changed files with 6473 additions and 65 deletions
+125
View File
@@ -0,0 +1,125 @@
"""Least-privilege probe for the worker identity. Output contains statuses, not secret values."""
import json
import ssl
import urllib.request
import boto3
import psycopg
from botocore.config import Config
from botocore.exceptions import ClientError
import pika
def bao_login():
ctx = ssl.create_default_context(cafile="/probe/ca.crt")
ctx.load_cert_chain("/probe/worker.crt", "/probe/worker.key")
request = urllib.request.Request(
"https://openbao:8200/v1/auth/cert/login",
data=b"{}",
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, context=ctx, timeout=8) as response:
payload = json.loads(response.read().decode("utf-8"))
return payload["auth"]["client_token"], ctx
def read_secret(token, ctx, path):
request = urllib.request.Request(
"https://openbao:8200/v1/secret/data/" + path,
headers={"X-Vault-Token": token},
)
with urllib.request.urlopen(request, context=ctx, timeout=8) as response:
payload = json.loads(response.read().decode("utf-8"))
return payload["data"]["data"]
def sql(dsn, statement):
try:
with psycopg.connect(dsn, connect_timeout=5, autocommit=True) as conn:
conn.execute(statement)
return "allow"
except Exception as exc:
code = getattr(getattr(exc, "diag", None), "sqlstate", None) or type(exc).__name__
return "deny:" + str(code)
def s3_put(client, key):
try:
client.put_object(Bucket="messenger-attachments", Key=key, Body=b"probe")
return "allow"
except ClientError as exc:
return "deny:" + str(exc.response.get("Error", {}).get("Code", "error"))
def s3_get(client, key):
try:
client.get_object(Bucket="messenger-attachments", Key=key)["Body"].read(32)
return "allow"
except ClientError as exc:
return "deny:" + str(exc.response.get("Error", {}).get("Code", "error"))
def publish():
ctx = ssl.create_default_context(cafile="/probe/ca.crt")
ctx.load_cert_chain("/probe/worker.crt", "/probe/worker.key")
params = pika.ConnectionParameters(
host="rabbitmq",
port=5671,
credentials=pika.credentials.ExternalCredentials(),
ssl_options=pika.SSLOptions(ctx, "rabbitmq"),
socket_timeout=5,
connection_attempts=1,
)
try:
connection = pika.BlockingConnection(params)
channel = connection.channel()
channel.confirm_delivery()
channel.basic_publish(exchange="", routing_key="attachment.process.v1", body=b"{}")
connection.close()
return "allow"
except pika.exceptions.ChannelClosedByBroker as exc:
return "deny:" + str(exc.reply_code)
except Exception as exc:
return "deny:" + type(exc).__name__
def main():
token, ctx = bao_login()
db = read_secret(token, ctx, "worker/db")
s3 = read_secret(token, ctx, "worker/s3")
dsn = "postgresql://{username}:{password}@{host}:5432/{dbname}?sslmode=verify-full&sslrootcert=/probe/ca.crt".format(**db)
client = boto3.client(
"s3",
endpoint_url="https://minio:8333",
aws_access_key_id=s3["access_key"],
aws_secret_access_key=s3["secret_key"],
region_name="us-east-1",
verify="/probe/ca.crt",
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=3, read_timeout=8),
)
report = {
"db_select_attachment_metadata": sql(dsn, "SELECT id FROM attachments LIMIT 1"),
"db_select_password_hash": sql(dsn, "SELECT password_hash FROM users LIMIT 1"),
"db_insert_user": sql(
dsn,
"INSERT INTO users (id, username, display_name, password_hash, created_at) "
"VALUES (gen_random_uuid(), 'evil', 'e', 'x', NOW())",
),
"db_delete_message": sql(dsn, "DELETE FROM messages WHERE false"),
"s3_put_original": s3_put(client, "originals/privilege-probe"),
"s3_get_canary": s3_get(client, "canary/marker"),
"s3_put_canary": s3_put(client, "canary/owned-by-worker"),
"queue_publish": publish(),
}
print(json.dumps(report, sort_keys=True))
denied = ["db_select_password_hash", "db_insert_user", "db_delete_message", "s3_get_canary", "s3_put_canary", "queue_publish"]
allowed = ["db_select_attachment_metadata", "s3_put_original"]
bad = [name for name in denied if not str(report[name]).startswith("deny")]
bad += [name for name in allowed if report[name] != "allow"]
if bad:
raise SystemExit("unexpected privilege result")
if __name__ == "__main__":
main()