forked from mtusi2026/mtusi2026lab7
ЛР 7 — БВТ2301 — Курлова — на 4
Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия: - внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial; - TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL), Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA; - OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь; - роли БД, S3-политики и права брокера по принципу минимальных прав; - Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS; - hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия; - отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
This commit is contained in:
Executable
+126
@@ -0,0 +1,126 @@
|
||||
#!/bin/sh
|
||||
# OpenBao operator tool. Unseal shares and the root token live ONLY in secrets/operator/ (git-ignored, 0600) and
|
||||
# are never printed. Values are passed to the CLI through the environment of `docker compose exec`, not argv.
|
||||
#
|
||||
# scripts/bao.sh init initialise once: 3 unseal shares, threshold 2; then unseal
|
||||
# scripts/bao.sh unseal unseal after every OpenBao restart (operator action; the API does not do it)
|
||||
# scripts/bao.sh bootstrap KV v2 mount, policies, cert auth roles, service secrets (idempotent)
|
||||
# scripts/bao.sh status sealed/initialised state
|
||||
# scripts/bao.sh rotate-worker-db new password for DB role app_worker: PostgreSQL + OpenBao (level 4)
|
||||
# scripts/bao.sh seal seal OpenBao (incident drill: services keep cached secrets, new ones must wait)
|
||||
#
|
||||
# Production note: each share would go to a different person; here one operator holds them on one host.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
OP=secrets/operator
|
||||
BS=secrets/bootstrap
|
||||
ENVS="-e BAO_ADDR=https://127.0.0.1:8200 -e BAO_CACERT=/run/secrets/ca.crt"
|
||||
|
||||
bao() { docker compose exec -T $ENVS openbao bao "$@"; }
|
||||
bao_root() { BAO_TOKEN="$(cat "$OP/root-token")" docker compose exec -T $ENVS -e BAO_TOKEN openbao bao "$@"; }
|
||||
|
||||
wait_up() {
|
||||
i=0
|
||||
until docker compose exec -T $ENVS openbao sh -c 'bao status >/dev/null 2>&1; [ $? -ne 1 ]'; do
|
||||
i=$((i + 1)); [ $i -gt 60 ] && { echo "openbao not reachable" >&2; exit 1; }; sleep 1
|
||||
done
|
||||
}
|
||||
|
||||
sealed() { ! docker compose exec -T $ENVS openbao bao status >/dev/null 2>&1; }
|
||||
|
||||
unseal() {
|
||||
wait_up
|
||||
if ! sealed; then echo "openbao: already unsealed"; return 0; fi
|
||||
for n in 1 2; do
|
||||
UNSEAL_KEY="$(cat "$OP/unseal-$n")" docker compose exec -T $ENVS -e UNSEAL_KEY openbao \
|
||||
sh -c 'bao operator unseal "$UNSEAL_KEY" >/dev/null'
|
||||
done
|
||||
sealed && { echo "openbao: still sealed" >&2; exit 1; }
|
||||
echo "openbao: unsealed with 2 of 3 operator shares"
|
||||
}
|
||||
|
||||
init() {
|
||||
wait_up
|
||||
if bao status -format=json 2>/dev/null | python3 -c 'import json,sys;sys.exit(0 if json.load(sys.stdin)["initialized"] else 1)'; then
|
||||
echo "openbao: already initialised"; unseal; return 0
|
||||
fi
|
||||
umask 077; mkdir -p "$OP"
|
||||
bao operator init -key-shares=3 -key-threshold=2 -format=json | python3 -c '
|
||||
import json, sys
|
||||
d = json.load(sys.stdin)
|
||||
for i, key in enumerate(d["unseal_keys_b64"], 1):
|
||||
open("'"$OP"'/unseal-%d" % i, "w").write(key)
|
||||
open("'"$OP"'/root-token", "w").write(d["root_token"])
|
||||
'
|
||||
chmod 600 "$OP"/*
|
||||
echo "openbao: initialised; 3 shares and root token stored in $OP/ (0600, not printed)"
|
||||
unseal
|
||||
}
|
||||
|
||||
bootstrap() {
|
||||
unseal
|
||||
bao_root secrets list -format=json | grep -q '"messenger/"' || bao_root secrets enable -path=messenger -version=2 kv
|
||||
bao_root auth list -format=json | grep -q '"cert/"' || bao_root auth enable cert
|
||||
for p in messenger-api messenger-worker; do
|
||||
docker compose exec -T openbao sh -c "cat > /tmp/$p.hcl" < "infra/openbao/policies/$p.hcl"
|
||||
bao_root policy write "$p" "/tmp/$p.hcl" >/dev/null
|
||||
done
|
||||
docker compose exec -T openbao sh -c 'cp /run/secrets/ca.crt /tmp/ca.crt'
|
||||
# Identity = client certificate chained to the lab root CA AND an exact common name. Short-lived tokens.
|
||||
bao_root write auth/cert/certs/api certificate=@/tmp/ca.crt allowed_common_names=api.client.messenger \
|
||||
token_policies=messenger-api token_ttl=15m token_max_ttl=1h >/dev/null
|
||||
bao_root write auth/cert/certs/worker certificate=@/tmp/ca.crt allowed_common_names=worker.client.messenger \
|
||||
token_policies=messenger-worker token_ttl=15m token_max_ttl=1h >/dev/null
|
||||
kv_api
|
||||
kv_worker
|
||||
echo "openbao: mount messenger/ (kv v2), policies messenger-api/worker, cert roles api/worker, secrets written"
|
||||
}
|
||||
|
||||
# KV values are read from secrets/bootstrap and passed through stdin as JSON (never on a command line).
|
||||
kv_api() {
|
||||
python3 - "$BS" <<'PY' | bao_root kv put -mount=messenger api - >/dev/null
|
||||
import json, sys
|
||||
b = sys.argv[1]
|
||||
r = lambda n: open("%s/%s" % (b, n)).read().strip()
|
||||
print(json.dumps({
|
||||
"database_url": "postgresql://app_api:%s@postgres:5432/messenger" % r("db_api_password"),
|
||||
"s3_access_key_id": r("s3_api_access_key"), "s3_secret_access_key": r("s3_api_secret_key"),
|
||||
"cache_url": "rediss://api:%s@valkey:6379/0" % r("valkey_api_password")}))
|
||||
PY
|
||||
}
|
||||
|
||||
kv_worker() {
|
||||
python3 - "$BS" <<'PY' | bao_root kv put -mount=messenger worker - >/dev/null
|
||||
import json, sys
|
||||
b = sys.argv[1]
|
||||
r = lambda n: open("%s/%s" % (b, n)).read().strip()
|
||||
print(json.dumps({
|
||||
"database_url": "postgresql://app_worker:%s@postgres:5432/messenger" % r("db_worker_password"),
|
||||
"s3_access_key_id": r("s3_worker_access_key"), "s3_secret_access_key": r("s3_worker_secret_key")}))
|
||||
PY
|
||||
}
|
||||
|
||||
rotate_worker_db() {
|
||||
unseal
|
||||
umask 077
|
||||
python3 -c "import secrets;print(secrets.token_urlsafe(24),end='')" > "$BS/db_worker_password.new"
|
||||
chmod 644 "$BS/db_worker_password.new"
|
||||
# 1) PostgreSQL first (open connections keep working), 2) OpenBao: the worker picks up the new version.
|
||||
NEWPW="$(cat "$BS/db_worker_password.new")" docker compose exec -T -e NEWPW postgres sh -c \
|
||||
'psql -v ON_ERROR_STOP=1 -q -U messenger -d messenger -v pw="$NEWPW" <<SQL
|
||||
ALTER ROLE app_worker PASSWORD :'"'"'pw'"'"';
|
||||
SQL'
|
||||
mv "$BS/db_worker_password.new" "$BS/db_worker_password"
|
||||
kv_worker
|
||||
echo "rotated: app_worker password changed in PostgreSQL and OpenBao (messenger/worker, new KV version)"
|
||||
}
|
||||
|
||||
case "${1:-status}" in
|
||||
init) init ;;
|
||||
unseal) unseal ;;
|
||||
bootstrap) bootstrap ;;
|
||||
rotate-worker-db) rotate_worker_db ;;
|
||||
seal) wait_up; bao_root operator seal >/dev/null; echo "openbao: sealed" ;;
|
||||
status) wait_up; bao status | grep -E "Initialized|Sealed|Version|Storage" ;;
|
||||
*) echo "usage: $0 init|unseal|bootstrap|status|rotate-worker-db|seal" >&2; exit 2 ;;
|
||||
esac
|
||||
Reference in New Issue
Block a user