lab7: PKI, mTLS infra, OpenBao non-dev, hardening, lifecycle scripts

This commit is contained in:
2026-11-26 16:47:23 +03:00
parent cda6e27fb8
commit 16accda962
45 changed files with 3593 additions and 660 deletions
+232
View File
@@ -0,0 +1,232 @@
#!/usr/bin/env bash
# Lab 7 Grade 5 Track 1 («Компрометация worker»): Full Containment & Recovery.
# Zero image rebuild, zero root token (uses operator mTLS cert).
# Usage: scripts/revoke-worker.sh [--no-start] [--old-cn <cn>] [--new-cn <cn>]
#
# Containment actions across ALL control planes:
# 1. OpenSSL CA revoke old worker cert -> regenerate & distribute ca.crl ->
# upload CRL to OpenBao auth/cert/crls/lab7-ca -> reload api/haproxy/postgres.
# 2. Selectively revoke active OpenBao token accessors for messenger-worker
# (leaves messenger-api and messenger-operator tokens completely intact).
# 3. OTel Gateway: remove old CN from allowed-otlp-cn.lst, add new CN, SIGUSR2.
# 4. RabbitMQ: delete_user <old_cn> (kills active AMQPS connections immediately)
# and create passwordless EXTERNAL user <new_cn> with consumer-only ACL.
# 5. PostgreSQL: rotate messenger_worker password + pg_terminate_backend on
# active messenger_worker sessions.
# 6. MinIO: create new worker-<hex> IAM user with messenger-worker policy and
# delete old worker IAM user over HTTPS + CA.
# 7. PKI: issue new worker leaf cert (<new_cn>, SAN=DNS:messenger-worker).
# 8. OpenBao KV v2: write version N+1 to secret/messenger/worker.
# 9. Unless --no-start is set, start/restart worker with --no-build --wait.
# Never prints secrets, passwords, keys, or tokens.
set -euo pipefail
cd "$(dirname "$0")/.."
NO_START=0
OLD_CN=""
NEW_CN=""
while [ $# -gt 0 ]; do
case "$1" in
--no-start) NO_START=1 ;;
--old-cn)
shift
OLD_CN="${1:?missing value for --old-cn}"
;;
--new-cn)
shift
NEW_CN="${1:?missing value for --new-cn}"
;;
-h|--help)
echo "Usage: $0 [--no-start] [--old-cn <cn>] [--new-cn <cn>]"
exit 0
;;
*)
echo "Unknown argument: $1" >&2
exit 2
;;
esac
shift
done
if [ -f .env ]; then
# shellcheck disable=SC1091
set -a; . ./.env; set +a
fi
OPERATOR_DIR="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
OP_CERT="${OPERATOR_DIR}/operator/operator.crt"
OP_KEY="${OPERATOR_DIR}/operator/operator.key"
RUNTIME_PKI_DIR="$(pwd)/secrets/pki"
CA_CERT="${CA_FILE:-${RUNTIME_PKI_DIR}/ca.crt}"
WORKER_CRT="${RUNTIME_PKI_DIR}/worker/client.crt"
BAO_ADDR="${BAO_ADDR_HOST:-https://localhost:${OPENBAO_PORT:-8200}}"
COMPOSE=(docker compose --env-file "${COMPOSE_ENV_FILE:-.env}")
MC_IMAGE="minio/mc:RELEASE.2025-08-13T08-35-41Z@sha256:a7fe349ef4bd8521fb8497f55c6042871b2ae640607cf99d9bede5e9bdf11727"
if [ ! -s "$WORKER_CRT" ]; then
echo "error: current worker certificate not found at ${WORKER_CRT}" >&2
exit 1
fi
if [ -z "$OLD_CN" ]; then
OLD_CN="$(openssl x509 -in "$WORKER_CRT" -noout -subject -nameopt RFC2253 | sed -n 's/.*CN=\([^,]*\).*/\1/p')"
fi
OLD_CN="${OLD_CN:-messenger-worker-g1}"
if [ -z "$NEW_CN" ]; then
if [[ "$OLD_CN" =~ ^(.*-g)([0-9]+)$ ]]; then
NEW_CN="${BASH_REMATCH[1]}$((BASH_REMATCH[2] + 1))"
else
NEW_CN="messenger-worker-g2"
fi
fi
OLD_SERIAL="$(openssl x509 -in "$WORKER_CRT" -noout -serial | cut -d= -f2)"
umask 077
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/lab7-revoke-wrk.XXXXXX")"
OP_CFG="${TMP_DIR}/op-auth.cfg"
cleanup() {
if [ -s "$OP_CFG" ]; then
curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
"${BAO_ADDR}/v1/auth/token/revoke-self" >/dev/null 2>&1 || true
fi
rm -rf "$TMP_DIR"
}
trap cleanup EXIT
# Authenticate as operator via mTLS cert (zero root token)
login_json="$(curl -fsS --cacert "$CA_CERT" --cert "$OP_CERT" --key "$OP_KEY" \
-X POST -H 'Content-Type: application/json' \
--data '{"name":"messenger-operator"}' \
"${BAO_ADDR}/v1/auth/cert/login")"
op_token="$(printf '%s' "$login_json" | jq -r '.auth.client_token // empty')"
if [ -z "$op_token" ]; then
echo "error: operator mTLS login to OpenBao failed" >&2
exit 1
fi
printf 'header = "X-Vault-Token: %s"\n' "$op_token" > "$OP_CFG"
chmod 0600 "$OP_CFG"
unset login_json op_token
# 1. Read existing worker KV secret (to identify old MinIO IAM user)
cur_worker_kv="$(curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" \
"${BAO_ADDR}/v1/secret/data/messenger/worker" | jq -c '.data.data')"
old_s3_key="$(printf '%s' "$cur_worker_kv" | jq -r '.s3_access_key_id // empty')"
# 2. Rotate worker leaf cert WITH CRL revocation & OTel Gateway allowlist update
# (handles OpenSSL ca -revoke, ca.crl distribution, OpenBao CRL upload,
# OTel allowed-otlp-cn.lst replacement + SIGUSR2, api SIGHUP, haproxy SIGUSR2, postgres reload)
rot_out="$(./scripts/rotate-cert.sh worker --revoke --cn "$NEW_CN")"
NEW_SERIAL="$(printf '%s' "$rot_out" | sed -n 's/.*new_serial=\([^ ]*\).*/\1/p')"
# 3. Selectively revoke active OpenBao token accessors for messenger-worker ONLY
revoked_accessors=0
accessors_json="$(curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X LIST \
"${BAO_ADDR}/v1/auth/token/accessors" 2>/dev/null || echo '{"data":{"keys":[]}}')"
for acc in $(printf '%s' "$accessors_json" | jq -r '.data.keys[]? // empty'); do
lookup="$(jq -n --arg a "$acc" '{accessor: $a}' \
| curl -sS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
-H 'Content-Type: application/json' --data-binary @- \
"${BAO_ADDR}/v1/auth/token/lookup-accessor" 2>/dev/null || true)"
cert_name="$(printf '%s' "$lookup" | jq -r '.data.meta.cert_name // empty' 2>/dev/null || true)"
common_name="$(printf '%s' "$lookup" | jq -r '.data.meta.common_name // empty' 2>/dev/null || true)"
if [ "$cert_name" = "messenger-worker" ] || [ "$common_name" = "$OLD_CN" ]; then
jq -n --arg a "$acc" '{accessor: $a}' \
| curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
-H 'Content-Type: application/json' --data-binary @- \
"${BAO_ADDR}/v1/auth/token/revoke-accessor" >/dev/null 2>&1 || true
revoked_accessors=$((revoked_accessors + 1))
fi
done
# 4. RabbitMQ: delete compromised EXTERNAL user (closes active connections) & create new generation user
"${COMPOSE[@]}" exec -T broker sh -eu -c '
old_cn=$1
new_cn=$2
if rabbitmqctl -q list_users | awk "{print \$1}" | grep -Fxq "$old_cn"; then
rabbitmqctl -q delete_user "$old_cn"
fi
if ! rabbitmqctl -q list_users | awk "{print \$1}" | grep -Fxq "$new_cn"; then
rabbitmqctl -q add_user "$new_cn" "tmp-$(head -c 16 /dev/urandom | od -An -tx1 | tr -d " \n")"
fi
rabbitmqctl -q clear_password "$new_cn"
rabbitmqctl -q set_user_tags "$new_cn"
rabbitmqctl -q set_permissions -p messenger "$new_cn" "^$" "^$" "^attachments\.process$"
' _ "$OLD_CN" "$NEW_CN"
# 5. PostgreSQL: rotate messenger_worker password & terminate active worker sessions
new_pg_pass="$(openssl rand -hex 24)"
{
printf "SET password_encryption = 'scram-sha-256';\n"
printf "ALTER ROLE messenger_worker WITH LOGIN PASSWORD '%s';\n" "$new_pg_pass"
printf "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'messenger_worker' AND pid <> pg_backend_pid();\n"
} | "${COMPOSE[@]}" exec -T postgres psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" -v ON_ERROR_STOP=1 >/dev/null
# 6. MinIO: add new scoped worker IAM user & immediately remove old compromised IAM user (HTTPS + CA)
new_s3_key="worker-$(openssl rand -hex 8)"
new_s3_sec="$(openssl rand -hex 24)"
s3_cid="$("${COMPOSE[@]}" ps -q s3 | head -n 1)"
app_data_net="$(docker inspect --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$s3_cid" \
| tr ' ' '\n' | grep '_app_data$' | head -n 1)"
printf '%s\n%s\n%s\n' "$new_s3_key" "$new_s3_sec" "$old_s3_key" \
| docker run --rm -i \
--network "$app_data_net" \
--user 1000:1000 \
--read-only \
--cap-drop ALL \
--security-opt no-new-privileges:true \
--tmpfs /tmp:size=16m,noexec,nosuid,nodev \
-v "$(pwd)/secrets/pki/ca.crt:/run/certs/ca.crt:ro" \
-v "$(pwd)/secrets/infra/minio_root_user:/run/secrets/minio_root_user:ro" \
-v "$(pwd)/secrets/infra/minio_root_password:/run/secrets/minio_root_password:ro" \
--entrypoint /bin/sh \
"$MC_IMAGE" -c '
set -eu
IFS= read -r ru < /run/secrets/minio_root_user || [ -n "$ru" ]
IFS= read -r rp < /run/secrets/minio_root_password || [ -n "$rp" ]
IFS= read -r nk; IFS= read -r ns; IFS= read -r ok || true
export HOME=/tmp MC_CONFIG_DIR=/tmp/.mc
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
cp /run/certs/ca.crt "$MC_CONFIG_DIR/certs/CAs/ca.crt"
export MC_HOST_stand="https://${ru}:${rp}@s3:9000"
mc admin user add stand "$nk" "$ns" >/dev/null
mc admin policy attach stand messenger-worker --user "$nk" >/dev/null
if [ -n "$ok" ] && [ "$ok" != "$nk" ]; then
mc admin user remove stand "$ok" >/dev/null 2>&1 || true
fi
'
# 7. Write OpenBao KV v2 version N+1 for messenger/worker
kv_ver="$(jq -n \
--arg db_pass "$new_pg_pass" \
--arg s3_key "$new_s3_key" \
--arg s3_sec "$new_s3_sec" \
--arg broker_user "$NEW_CN" \
'{
data: {
db_user: "messenger_worker",
db_password: $db_pass,
s3_access_key_id: $s3_key,
s3_secret_access_key: $s3_sec,
broker_user: $broker_user
}
}' \
| curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
-H 'Content-Type: application/json' --data-binary @- \
"${BAO_ADDR}/v1/secret/data/messenger/worker" \
| jq -r '.data.version')"
# 8. Recover worker without image rebuild (unless --no-start was requested)
worker_started="false"
if [ "$NO_START" -eq 0 ]; then
if [ -n "$("${COMPOSE[@]}" ps -q --status running worker 2>/dev/null || true)" ]; then
"${COMPOSE[@]}" restart worker >/dev/null
fi
"${COMPOSE[@]}" up -d --no-build --no-deps --wait worker >/dev/null
worker_started="true"
fi
echo "revoke-worker ok: old_cn=${OLD_CN} new_cn=${NEW_CN} old_serial=${OLD_SERIAL} new_serial=${NEW_SERIAL} revoked_accessors=${revoked_accessors} kv_version=${kv_ver} worker_started=${worker_started}"