7 — Т2302 — ебедев — на 5
This commit is contained in:
@@ -0,0 +1,357 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Операторские действия OpenBao (stdlib, Python 3.9+, Linux/macOS/Windows). Выполняет ОПЕРАТОР на хосте.
|
||||
|
||||
python3 scripts/bao_admin.py init # operator init: 3 unseal shares, порог 2 → каталог оператора
|
||||
python3 scripts/bao_admin.py unseal [--prompt]
|
||||
python3 scripts/bao_admin.py status | seal
|
||||
python3 scripts/bao_admin.py bootstrap # KV v2, AppRole, policies, роли, KV-секреты, role_id/secret_id
|
||||
python3 scripts/bao_admin.py rotate-secret-id worker [--keep-old]
|
||||
python3 scripts/bao_admin.py revoke-identity worker # уничтожить все SecretID и токены роли (компрометация)
|
||||
python3 scripts/bao_admin.py revoke-tokens api # отозвать только токены (сервис войдёт заново)
|
||||
python3 scripts/bao_admin.py tokens api # TTL/продления действующих токенов (без значений)
|
||||
python3 scripts/bao_admin.py kv-keys worker # имена ключей и версия (без значений)
|
||||
python3 scripts/bao_admin.py kv-patch worker < new.json # новые значения — только через stdin
|
||||
|
||||
Связь: HTTPS https://127.0.0.1:8200 (порт опубликован только на loopback хоста) с проверкой сертификата по
|
||||
secrets/tls/trust/ca.crt и hostname (SAN 127.0.0.1). Материал оператора (unseal shares, root token) хранится
|
||||
в MTUSI_OPERATOR_DIR (по умолчанию ~/.mtusi-lab7-operator, права 700/600) — вне репозитория, вне томов и
|
||||
образов, в контейнеры не монтируется. Скрипт НИКОГДА не печатает shares, токены и SecretID.
|
||||
"""
|
||||
import argparse
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ADDR = os.environ.get("BAO_ADDR", "https://127.0.0.1:%s" % os.environ.get("BAO_PORT", "8200")).rstrip("/")
|
||||
CACERT = os.environ.get("BAO_CACERT", str(ROOT / "secrets" / "tls" / "trust" / "ca.crt"))
|
||||
OPDIR = Path(os.environ.get("MTUSI_OPERATOR_DIR", str(Path.home() / ".mtusi-lab7-operator")))
|
||||
INIT_FILE = OPDIR / "openbao-init.json"
|
||||
SECRETS = ROOT / "secrets"
|
||||
SERVICES = {
|
||||
# сервис → роль AppRole, policy, путь KV v2 (mount secret/), источники значений (файлы secrets/)
|
||||
"api": {"role": "messenger-api", "policy": "messenger-api", "kv": "messenger/api",
|
||||
"values": {"db_user": "=messenger_api_a", "db_password": "db_api_a_password",
|
||||
"s3_access_key_id": "s3_api_access_key_id", "s3_secret_access_key": "s3_api_secret_access_key",
|
||||
"redis_username": "=messenger-api", "redis_password": "redis_api_password"}},
|
||||
"worker": {"role": "messenger-worker", "policy": "messenger-worker", "kv": "messenger/worker",
|
||||
"values": {"db_user": "=messenger_worker_a", "db_password": "db_worker_a_password",
|
||||
"s3_access_key_id": "s3_worker_access_key_id",
|
||||
"s3_secret_access_key": "s3_worker_secret_access_key"}},
|
||||
}
|
||||
TOKEN_TTL = os.environ.get("BAO_TOKEN_TTL", "5m") # короткий TTL рабочего токена: продление/re-login
|
||||
TOKEN_MAX_TTL = os.environ.get("BAO_TOKEN_MAX_TTL", "30m")
|
||||
SECRET_ID_TTL = os.environ.get("BAO_SECRET_ID_TTL", "168h") # SecretID — «первый секрет», ротируется оператором
|
||||
BOUND_CIDRS = [c for c in os.environ.get("BAO_BOUND_CIDRS", "10.207.70.0/24").split(",") if c]
|
||||
APP_UID = 10001
|
||||
|
||||
|
||||
class BaoError(Exception):
|
||||
def __init__(self, status, errors):
|
||||
super().__init__("HTTP %s: %s" % (status, "; ".join(errors) if errors else ""))
|
||||
self.status, self.errors = status, errors
|
||||
|
||||
|
||||
def ctx():
|
||||
c = ssl.create_default_context(cafile=CACERT) # проверка цепочки и hostname; без «insecure»
|
||||
c.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
return c
|
||||
|
||||
|
||||
def call(method, path, body=None, token=None, ok404=False):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
req = urllib.request.Request(ADDR + "/v1/" + path.lstrip("/"), data=data, method=method)
|
||||
req.add_header("Content-Type", "application/json")
|
||||
if token:
|
||||
req.add_header("X-Vault-Token", token)
|
||||
try:
|
||||
with urllib.request.urlopen(req, context=ctx(), timeout=10) as r:
|
||||
raw = r.read()
|
||||
return json.loads(raw) if raw else {}
|
||||
except urllib.error.HTTPError as e:
|
||||
if ok404 and e.code == 404:
|
||||
return None
|
||||
try:
|
||||
errors = json.loads(e.read() or b"{}").get("errors", [])
|
||||
except ValueError:
|
||||
errors = []
|
||||
raise BaoError(e.code, errors) from None
|
||||
|
||||
|
||||
def write_private(path: Path, text: str, uid=None):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=".tmp-")
|
||||
with os.fdopen(fd, "w") as fh:
|
||||
fh.write(text)
|
||||
mode = 0o600
|
||||
if uid is not None and hasattr(os, "geteuid"):
|
||||
if os.geteuid() == 0:
|
||||
os.chown(tmp, uid, uid) # владелец = uid сервиса (Linux, оператор под root)
|
||||
else:
|
||||
# Linux без root: chown невозможен, а сервис (uid 10001) должен прочитать файл через bind mount.
|
||||
# Защита на хосте — каталог secrets/ (700, только оператор); в контейнер файл монтирует только свой сервис.
|
||||
mode = 0o644
|
||||
os.chmod(tmp, mode)
|
||||
os.replace(tmp, str(path))
|
||||
|
||||
|
||||
def root_token():
|
||||
if not INIT_FILE.exists():
|
||||
sys.exit("нет %s: сначала bao_admin.py init" % INIT_FILE)
|
||||
return json.loads(INIT_FILE.read_text())["root_token"]
|
||||
|
||||
|
||||
def seal_status():
|
||||
return call("GET", "sys/seal-status")
|
||||
|
||||
|
||||
def cmd_wait(a):
|
||||
"""Ждать, пока OpenBao ответит по TLS (sealed или нет) — до a.timeout секунд."""
|
||||
deadline = time.time() + a.timeout
|
||||
while True:
|
||||
try:
|
||||
s = seal_status()
|
||||
print("OpenBao отвечает: initialized=%s sealed=%s" % (s.get("initialized"), s.get("sealed")))
|
||||
return
|
||||
except (urllib.error.URLError, OSError, BaoError) as e:
|
||||
if time.time() > deadline:
|
||||
sys.exit("OpenBao не ответил за %ss: %s" % (a.timeout, getattr(e, "reason", e)))
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def cmd_status(a):
|
||||
s = seal_status()
|
||||
print(json.dumps({k: s.get(k) for k in ("initialized", "sealed", "t", "n", "progress", "version", "storage_type",
|
||||
"cluster_name")}, ensure_ascii=False))
|
||||
|
||||
|
||||
def cmd_init(a):
|
||||
st = call("GET", "sys/init")
|
||||
if st.get("initialized"):
|
||||
print("OpenBao уже инициализирован; материал оператора: %s (%s)" % (INIT_FILE, "есть" if INIT_FILE.exists() else "НЕТ"))
|
||||
return
|
||||
OPDIR.mkdir(parents=True, exist_ok=True)
|
||||
if os.name != "nt":
|
||||
os.chmod(OPDIR, stat.S_IRWXU)
|
||||
res = call("PUT", "sys/init", {"secret_shares": a.shares, "secret_threshold": a.threshold})
|
||||
write_private(INIT_FILE, json.dumps({"unseal_keys_b64": res["keys_base64"], "root_token": res["root_token"],
|
||||
"threshold": a.threshold, "created": time.strftime("%FT%TZ", time.gmtime())}))
|
||||
print("OpenBao инициализирован: %d shares (порог %d) и root token сохранены в %s (0600); значения не выводятся."
|
||||
% (a.shares, a.threshold, INIT_FILE))
|
||||
|
||||
|
||||
def cmd_unseal(a):
|
||||
s = seal_status()
|
||||
if not s.get("sealed"):
|
||||
print("OpenBao не запечатан (sealed=false)")
|
||||
return
|
||||
if a.prompt:
|
||||
keys = [getpass.getpass("unseal share %d/%d: " % (i + 1, s["t"])) for i in range(s["t"])]
|
||||
else:
|
||||
init = json.loads(INIT_FILE.read_text())
|
||||
keys = init["unseal_keys_b64"][: init["threshold"]]
|
||||
for k in keys:
|
||||
s = call("PUT", "sys/unseal", {"key": k})
|
||||
if not s.get("sealed"):
|
||||
break
|
||||
print("sealed=%s progress=%s/%s" % (s.get("sealed"), s.get("progress"), s.get("t")))
|
||||
if s.get("sealed"):
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def cmd_seal(a):
|
||||
call("PUT", "sys/seal", token=root_token())
|
||||
print("OpenBao запечатан (sealed=true): чтение secrets и вход сервисов невозможны до unseal")
|
||||
|
||||
|
||||
def read_value(spec):
|
||||
if spec.startswith("="):
|
||||
return spec[1:]
|
||||
p = SECRETS / spec
|
||||
if not p.exists():
|
||||
sys.exit("нет файла secrets/%s (запустите scripts/init-secrets)" % spec)
|
||||
return p.read_text().strip()
|
||||
|
||||
|
||||
def cmd_bootstrap(a):
|
||||
t = root_token()
|
||||
mounts = call("GET", "sys/mounts", token=t)
|
||||
if "secret/" not in mounts.get("data", mounts):
|
||||
call("POST", "sys/mounts/secret", {"type": "kv", "options": {"version": "2"},
|
||||
"description": "messenger service secrets"}, token=t)
|
||||
auths = call("GET", "sys/auth", token=t)
|
||||
if "approle/" not in auths.get("data", auths):
|
||||
call("POST", "sys/auth/approle", {"type": "approle", "description": "service identities"}, token=t)
|
||||
for f in sorted((ROOT / "infra" / "openbao" / "policies").glob("*.hcl")):
|
||||
call("PUT", "sys/policies/acl/" + f.stem, {"policy": f.read_text()}, token=t)
|
||||
out = {}
|
||||
for svc, spec in SERVICES.items():
|
||||
call("POST", "auth/approle/role/" + spec["role"], {
|
||||
"token_policies": [spec["policy"]], "token_no_default_policy": True, "token_type": "service",
|
||||
"token_ttl": TOKEN_TTL, "token_max_ttl": TOKEN_MAX_TTL, "token_num_uses": 0,
|
||||
"bind_secret_id": True, "secret_id_ttl": SECRET_ID_TTL, "secret_id_num_uses": 0,
|
||||
"secret_id_bound_cidrs": BOUND_CIDRS, "token_bound_cidrs": BOUND_CIDRS}, token=t)
|
||||
existing = call("GET", "secret/data/" + spec["kv"], token=t, ok404=True)
|
||||
if existing is None or a.force_kv:
|
||||
data = {k: read_value(v) for k, v in spec["values"].items()}
|
||||
call("POST", "secret/data/" + spec["kv"], {"data": data}, token=t)
|
||||
role_id = call("GET", "auth/approle/role/%s/role-id" % spec["role"], token=t)["data"]["role_id"]
|
||||
d = SECRETS / "bao" / svc
|
||||
write_private(d / "role_id", role_id + "\n", APP_UID)
|
||||
sid_ok = False
|
||||
acc_file = d / "secret_id_accessor"
|
||||
if (d / "secret_id").exists() and acc_file.exists():
|
||||
r = call("POST", "auth/approle/role/%s/secret-id-accessor/lookup" % spec["role"],
|
||||
{"secret_id_accessor": acc_file.read_text().strip()}, token=t, ok404=True)
|
||||
sid_ok = bool(r and r.get("data"))
|
||||
if not sid_ok:
|
||||
new_secret_id(t, svc, spec)
|
||||
if os.name != "nt":
|
||||
os.chmod(d, 0o755)
|
||||
kv = call("GET", "secret/data/" + spec["kv"], token=t)["data"]
|
||||
out[svc] = {"role": spec["role"], "policy": spec["policy"], "kv_path": "secret/data/" + spec["kv"],
|
||||
"kv_version": kv["metadata"]["version"], "kv_keys": sorted(kv["data"]),
|
||||
"secret_id": "issued" if not sid_ok else "kept (valid)"}
|
||||
print(json.dumps({"bootstrap": "ok", "token_ttl": TOKEN_TTL, "token_max_ttl": TOKEN_MAX_TTL,
|
||||
"secret_id_ttl": SECRET_ID_TTL, "bound_cidrs": BOUND_CIDRS, "services": out},
|
||||
ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
def new_secret_id(t, svc, spec):
|
||||
r = call("POST", "auth/approle/role/%s/secret-id" % spec["role"], {"metadata": json.dumps({"service": svc})},
|
||||
token=t)["data"]
|
||||
d = SECRETS / "bao" / svc
|
||||
write_private(d / "secret_id", r["secret_id"] + "\n", APP_UID)
|
||||
write_private(d / "secret_id_accessor", r["secret_id_accessor"] + "\n", APP_UID)
|
||||
return r["secret_id_accessor"]
|
||||
|
||||
|
||||
def cmd_rotate_secret_id(a):
|
||||
t, spec = root_token(), SERVICES[a.service]
|
||||
d = SECRETS / "bao" / a.service
|
||||
old = (d / "secret_id_accessor").read_text().strip() if (d / "secret_id_accessor").exists() else None
|
||||
new_secret_id(t, a.service, spec)
|
||||
destroyed = False
|
||||
if old and not a.keep_old:
|
||||
try:
|
||||
call("POST", "auth/approle/role/%s/secret-id-accessor/destroy" % spec["role"], {"secret_id_accessor": old},
|
||||
token=t)
|
||||
destroyed = True
|
||||
except BaoError: # уже уничтожен (revoke-identity)
|
||||
destroyed = "already"
|
||||
print(json.dumps({"service": a.service, "secret_id": "rotated (file updated, value not shown)",
|
||||
"old_secret_id_destroyed": destroyed}, ensure_ascii=False))
|
||||
|
||||
|
||||
def role_token_accessors(t, role):
|
||||
accs = call("LIST", "auth/token/accessors", token=t)["data"]["keys"]
|
||||
out = []
|
||||
for acc in accs:
|
||||
try:
|
||||
info = call("POST", "auth/token/lookup-accessor", {"accessor": acc}, token=t)["data"]
|
||||
except BaoError:
|
||||
continue
|
||||
if (info.get("meta") or {}).get("role_name") == role:
|
||||
out.append(acc)
|
||||
return out
|
||||
|
||||
|
||||
def cmd_revoke_identity(a):
|
||||
"""Компрометация: уничтожить ВСЕ SecretID роли и отозвать все её действующие токены."""
|
||||
t, spec = root_token(), SERVICES[a.service]
|
||||
try:
|
||||
sids = call("LIST", "auth/approle/role/%s/secret-id" % spec["role"], token=t)["data"]["keys"]
|
||||
except BaoError as e:
|
||||
sids = [] if e.status == 404 else (_ for _ in ()).throw(e)
|
||||
for acc in sids:
|
||||
call("POST", "auth/approle/role/%s/secret-id-accessor/destroy" % spec["role"], {"secret_id_accessor": acc},
|
||||
token=t)
|
||||
toks = role_token_accessors(t, spec["role"])
|
||||
for acc in toks:
|
||||
call("POST", "auth/token/revoke-accessor", {"accessor": acc}, token=t)
|
||||
print(json.dumps({"service": a.service, "role": spec["role"], "secret_ids_destroyed": len(sids),
|
||||
"tokens_revoked": len(toks)}, ensure_ascii=False))
|
||||
|
||||
|
||||
def cmd_revoke_tokens(a):
|
||||
"""Отозвать действующие токены роли (SecretID остаются): сервис получит 403 и войдёт заново."""
|
||||
t, spec = root_token(), SERVICES[a.service]
|
||||
toks = role_token_accessors(t, spec["role"])
|
||||
for acc in toks:
|
||||
call("POST", "auth/token/revoke-accessor", {"accessor": acc}, token=t)
|
||||
print(json.dumps({"service": a.service, "tokens_revoked": len(toks)}, ensure_ascii=False))
|
||||
|
||||
|
||||
def cmd_tokens(a):
|
||||
t, spec = root_token(), SERVICES[a.service]
|
||||
rows = []
|
||||
for acc in role_token_accessors(t, spec["role"]):
|
||||
info = call("POST", "auth/token/lookup-accessor", {"accessor": acc}, token=t)["data"]
|
||||
rows.append({"policies": info.get("policies"), "ttl": info.get("ttl"), "creation_ttl": info.get("creation_ttl"),
|
||||
"explicit_max_ttl": info.get("explicit_max_ttl"), "renewable": info.get("renewable"),
|
||||
"issue_time": info.get("issue_time"), "last_renewal": info.get("last_renewal_time"),
|
||||
"bound_cidrs": info.get("bound_cidrs")})
|
||||
print(json.dumps({"service": a.service, "tokens": rows}, ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
def cmd_kv_keys(a):
|
||||
t, spec = root_token(), SERVICES[a.service]
|
||||
kv = call("GET", "secret/data/" + spec["kv"], token=t)["data"]
|
||||
print(json.dumps({"path": "secret/data/" + spec["kv"], "version": kv["metadata"]["version"],
|
||||
"keys": sorted(kv["data"]), "db_user": kv["data"].get("db_user")}, ensure_ascii=False))
|
||||
|
||||
|
||||
def cmd_kv_patch(a):
|
||||
"""Новые значения — JSON-объект из stdin (не из argv: не попадают в историю/список процессов)."""
|
||||
t, spec = root_token(), SERVICES[a.service]
|
||||
patch = json.loads(sys.stdin.read())
|
||||
cur = call("GET", "secret/data/" + spec["kv"], token=t)["data"]
|
||||
data = dict(cur["data"], **patch)
|
||||
res = call("POST", "secret/data/" + spec["kv"], {"data": data, "options": {"cas": cur["metadata"]["version"]}},
|
||||
token=t)["data"]
|
||||
print(json.dumps({"path": "secret/data/" + spec["kv"], "version": res["version"], "changed_keys": sorted(patch)},
|
||||
ensure_ascii=False))
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
p = sub.add_parser("init")
|
||||
p.add_argument("--shares", type=int, default=3)
|
||||
p.add_argument("--threshold", type=int, default=2)
|
||||
p = sub.add_parser("unseal")
|
||||
p.add_argument("--prompt", action="store_true", help="ввести shares вручную (не читать файл оператора)")
|
||||
sub.add_parser("status")
|
||||
sub.add_parser("seal")
|
||||
p = sub.add_parser("wait")
|
||||
p.add_argument("--timeout", type=float, default=60)
|
||||
p = sub.add_parser("bootstrap")
|
||||
p.add_argument("--force-kv", action="store_true", help="перезаписать KV значениями из secrets/ (осторожно)")
|
||||
for name in ("rotate-secret-id", "revoke-identity", "revoke-tokens", "kv-keys", "kv-patch", "tokens"):
|
||||
p = sub.add_parser(name)
|
||||
p.add_argument("service", choices=sorted(SERVICES))
|
||||
if name == "rotate-secret-id":
|
||||
p.add_argument("--keep-old", action="store_true")
|
||||
a = ap.parse_args()
|
||||
fn = {"wait": cmd_wait, "init": cmd_init, "unseal": cmd_unseal, "status": cmd_status, "seal": cmd_seal, "bootstrap": cmd_bootstrap,
|
||||
"rotate-secret-id": cmd_rotate_secret_id, "revoke-identity": cmd_revoke_identity,
|
||||
"revoke-tokens": cmd_revoke_tokens, "kv-keys": cmd_kv_keys,
|
||||
"kv-patch": cmd_kv_patch, "tokens": cmd_tokens}[a.cmd]
|
||||
try:
|
||||
fn(a)
|
||||
except BaoError as e:
|
||||
sys.exit("OpenBao: %s" % e)
|
||||
except urllib.error.URLError as e:
|
||||
sys.exit("OpenBao недоступен по %s: %s" % (ADDR, e.reason))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,114 @@
|
||||
# Windows PowerShell 5.1+ equivalent of scripts/collect-evidence.sh (lab7).
|
||||
# Starts the stand (init-secrets -> up: OpenBao init/unseal/bootstrap -> all services), runs every check and writes
|
||||
# outputs to evidence\ (no tokens/passwords/keys). WARNING: restarts containers, rotates certificates/credentials,
|
||||
# seals OpenBao (then unseals with operator material). Volumes are never removed. ~60-75 min
|
||||
# (-SkipRegression: -30 min, -SkipResearch: -8 min). Dependency scan: set $env:GHSA_DB to an advisory-database clone.
|
||||
# powershell -NoProfile -ExecutionPolicy Bypass -File scripts\collect-evidence.ps1 [-SkipRegression] [-SkipResearch]
|
||||
param([switch]$SkipRegression, [switch]$SkipResearch)
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
$env:PYTHONUTF8 = '1'
|
||||
$env:PYTHONIOENCODING = 'utf-8'
|
||||
# IPv4 explicitly: on Windows 'localhost' resolves to ::1 first; the LB listens on 127.0.0.1 only.
|
||||
$env:NO_PROXY = '127.0.0.1,localhost'
|
||||
$B = 'https://127.0.0.1:8443'
|
||||
$CA = Join-Path $root 'secrets\tls\trust\ca.crt'
|
||||
$env:BASE_URL = $B
|
||||
$env:CA_FILE = $CA
|
||||
$env:TTL_BASE_URL = 'https://127.0.0.1:8444'
|
||||
$ev = Join-Path $root 'evidence'
|
||||
New-Item -ItemType Directory -Force -Path $ev, (Join-Path $ev 'track1'), (Join-Path $ev 'scan') | Out-Null
|
||||
|
||||
$pyApp = Get-Command py -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
$pythonApp = Get-Command python -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if ($pyApp) { $script:PyExe = $pyApp.Source; $script:PyPre = @('-3') }
|
||||
elseif ($pythonApp) { $script:PyExe = $pythonApp.Source; $script:PyPre = @() }
|
||||
else { throw 'Python 3.9+ not found (install from python.org, enable "Add to PATH")' }
|
||||
function Invoke-Python { & $script:PyExe @script:PyPre @args }
|
||||
function Dc { & docker compose --env-file .env @args }
|
||||
$hookStop = 'scripts\stop-one.cmd'
|
||||
$hookRestart = 'scripts\restart.cmd'
|
||||
$startReplicas = Join-Path $PSScriptRoot 'start-replicas.ps1'
|
||||
|
||||
function Get-Stamp {
|
||||
$commit = 'n/a'
|
||||
if (Get-Command git -ErrorAction SilentlyContinue) {
|
||||
$c = (& git rev-parse --short HEAD 2>$null)
|
||||
if ($LASTEXITCODE -eq 0 -and $c) { $commit = $c }
|
||||
}
|
||||
'# ' + (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + ' commit=' + $commit + ' host=' + [Environment]::OSVersion.VersionString + ' cpus=' + [Environment]::ProcessorCount
|
||||
}
|
||||
function Invoke-Step([string]$name, [string]$title, [scriptblock]$block) {
|
||||
Write-Host ('>>> ' + $name) -ForegroundColor Cyan
|
||||
$global:LASTEXITCODE = 0
|
||||
$lines = @(& $block 2>&1 | ForEach-Object { "$_" })
|
||||
$code = $global:LASTEXITCODE
|
||||
Set-Content -Path (Join-Path $ev ($name + '.txt')) -Encoding UTF8 -Value (@((Get-Stamp), ('$ ' + $title)) + $lines + @('exit=' + $code))
|
||||
$lines | Select-Object -Last 2 | ForEach-Object { Write-Host (' ' + $_) }
|
||||
if ($code -ne 0) { Write-Host (' exit=' + $code + ' (see evidence\' + $name + '.txt)') -ForegroundColor Yellow }
|
||||
}
|
||||
|
||||
& docker version --format '{{.Server.Version}}' *> $null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Docker is not running: start Docker Desktop first' }
|
||||
& (Join-Path $PSScriptRoot 'init-secrets.ps1')
|
||||
& (Join-Path $PSScriptRoot 'up.ps1') -Profiles ttl
|
||||
Set-Location $root
|
||||
Dc --profile tools up -d ops | Out-Null
|
||||
$mount = (Join-Path $root 'student-tests') + ':/app/student-tests:ro'
|
||||
|
||||
Invoke-Step 'stack' 'docker version; compose images; ps' { & docker version --format 'docker {{.Server.Version}}'; Dc version; Dc --profile ttl images; Dc --profile ttl ps -a }
|
||||
Invoke-Step 'pki-status' 'docker compose --profile tools run --rm pki status' { Dc --profile tools run --rm --no-deps -T pki status }
|
||||
Invoke-Step 'openbao-status' 'bao_admin.py status / kv-keys / tokens (no values)' {
|
||||
Invoke-Python scripts/bao_admin.py status; Invoke-Python scripts/bao_admin.py kv-keys api
|
||||
Invoke-Python scripts/bao_admin.py kv-keys worker; Invoke-Python scripts/bao_admin.py tokens api
|
||||
}
|
||||
Invoke-Step 'migrations' 'schema_migrations; roles; docker compose logs migrate' {
|
||||
Dc exec -T -u postgres postgres psql -d messenger -c 'SELECT version, left(checksum,12) AS checksum, applied_at FROM schema_migrations ORDER BY version' -c '\du'
|
||||
Dc logs --no-log-prefix migrate
|
||||
}
|
||||
Invoke-Step 'broker-bootstrap' 'docker compose logs broker-init' { Dc logs --no-log-prefix broker-init }
|
||||
Invoke-Step 's3-bootstrap' 'docker compose logs s3-init' { Dc logs --no-log-prefix s3-init }
|
||||
Invoke-Step 'published-ports' 'docker compose ps: published ports' { Dc ps --format '{{.Service}} {{.Ports}}' | Sort-Object -Unique }
|
||||
Invoke-Step 'kdf-bench' 'python -m messenger kdf-bench (in api)' { Dc exec -T api python -m messenger kdf-bench }
|
||||
Invoke-Step 'make-check' 'python scripts/check_contract.py' { Invoke-Python scripts/check_contract.py }
|
||||
Invoke-Step 'smoke' "python tests/smoke.py --base-url $B --ca-file CA" { Invoke-Python tests/smoke.py --base-url $B --ca-file $CA }
|
||||
Invoke-Step 'test-security-public' 'python tests/security.py' { Invoke-Python tests/security.py --base-url $B --ca-file $CA }
|
||||
Invoke-Step 'internal-security' 'docker compose --profile tests run --rm probe' { Dc --profile tests run --rm -T probe student-tests/internal_security.py }
|
||||
Invoke-Step 'test-security' 'python student-tests/test_security.py' { Invoke-Python student-tests/test_security.py }
|
||||
Invoke-Step 'test-hardening' 'python student-tests/test_hardening.py' { Invoke-Python student-tests/test_hardening.py --json evidence/hardening.json }
|
||||
if ($env:GHSA_DB -and (Test-Path (Join-Path $env:GHSA_DB 'advisories'))) {
|
||||
Invoke-Step 'dep-scan' 'python scripts/dep_scan.py' { Invoke-Python scripts/dep_scan.py --db $env:GHSA_DB --json evidence/scan/deps.json }
|
||||
}
|
||||
if (-not $SkipRegression) {
|
||||
$env:FAULT_HOOKS = 'lab' # lab5 fault hooks only for the regression run
|
||||
Dc up -d --no-deps --force-recreate --wait api worker | Out-Null
|
||||
foreach ($t in 'test_api', 'test_idempotency', 'test_attachments', 'test_expiry', 'test_pipeline', 'test_failures',
|
||||
'test_observability', 'test_jobs_failures', 'test_storage_failures', 'test_pipeline_idempotency',
|
||||
'test_telemetry_persistence') {
|
||||
Invoke-Step ($t -replace '_', '-') "python student-tests/$t.py" { Invoke-Python "student-tests/$t.py" }
|
||||
}
|
||||
Invoke-Step 'test-cache-race' 'test_cache_race.py in api image' { Dc run --rm --no-deps -T -v $mount --entrypoint python api student-tests/test_cache_race.py }
|
||||
Invoke-Step 'test-imgproc' 'test_imgproc.py in worker image' { Dc run --rm --no-deps -T -v $mount --entrypoint python worker student-tests/test_imgproc.py }
|
||||
Remove-Item Env:FAULT_HOOKS
|
||||
Dc --profile fault stop api-fault | Out-Null
|
||||
Dc up -d --no-deps --force-recreate --wait api worker | Out-Null
|
||||
}
|
||||
Set-Content -Path (Join-Path $ev 'failover-hook.txt') -Value '' -Encoding UTF8
|
||||
Invoke-Step 'failover-1' 'tests/resilience.py --mode failover' { Invoke-Python tests/resilience.py --mode failover --action-script $hookStop --base-url $B --ca-file $CA }
|
||||
Invoke-Step 'restore-1' 'start-replicas.ps1' { & $startReplicas }
|
||||
Invoke-Step 'failover-2' 'tests/resilience.py --mode failover' { Invoke-Python tests/resilience.py --mode failover --action-script $hookStop --base-url $B --ca-file $CA }
|
||||
Invoke-Step 'restore-2' 'start-replicas.ps1' { & $startReplicas }
|
||||
Set-Content -Path (Join-Path $ev 'restart-hook.txt') -Value '' -Encoding UTF8
|
||||
Invoke-Step 'persistence' 'tests/resilience.py --mode persistence' { Invoke-Python tests/resilience.py --mode persistence --action-script $hookRestart --base-url $B --ca-file $CA }
|
||||
Invoke-Step 'test-lifecycle' 'python student-tests/test_lifecycle.py' { Invoke-Python student-tests/test_lifecycle.py --json evidence/lifecycle.json }
|
||||
if (-not $SkipResearch) {
|
||||
Invoke-Step 'track1-worker-compromise' 'python research/worker_compromise.py' { Invoke-Python research/worker_compromise.py --out evidence/track1 }
|
||||
Invoke-Step 'login-dos' 'python research/login_dos.py' { Invoke-Python research/login_dos.py --out evidence/login_dos.json }
|
||||
}
|
||||
Invoke-Step 'internal-security-final' 'probe after rotations' { Dc --profile tests run --rm -T probe student-tests/internal_security.py }
|
||||
Invoke-Step 'smoke-final' 'tests/smoke.py' { Invoke-Python tests/smoke.py --base-url $B --ca-file $CA }
|
||||
Invoke-Step 'jobs-invariants' 'jobs invariants --settled --verify-bytes' { Dc --profile tools exec -T ops python -m messenger jobs invariants --settled --verify-bytes }
|
||||
Invoke-Step 'load' 'tests/load.py 30 s x 4' { Invoke-Python tests/load.py --base-url $B --ca-file $CA --duration 30 --concurrency 4 --output evidence/load.json }
|
||||
Invoke-Step 'secret-scan' 'python scripts/secret_scan.py' { Invoke-Python scripts/secret_scan.py }
|
||||
Write-Host 'evidence collected in evidence\' -ForegroundColor Green
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/bin/sh
|
||||
# Полный прогон доказательств lab7 на Compose-стенде; вывод — evidence/ (без токенов, паролей, ключей).
|
||||
# ВНИМАНИЕ: останавливает/перезапускает контейнеры, ротирует сертификаты и учётные данные, запечатывает OpenBao
|
||||
# (затем распечатывает материалом оператора). Volumes не удаляются. Длительность ≈ 60–75 мин;
|
||||
# SKIP_REGRESSION=1 — без регрессии lab2–lab6 (−30 мин); SKIP_RESEARCH=1 — без трека 1 и login DoS (−8 мин).
|
||||
# Для dependency scan укажите GHSA_DB=/путь/к/advisory-database (см. scripts/dep_scan.py).
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
. scripts/lib.sh
|
||||
PY=${PYTHON:-python3}
|
||||
B=${BASE_URL:-https://127.0.0.1:8443}
|
||||
CA="$PWD/secrets/tls/trust/ca.crt"
|
||||
export BASE_URL=$B CA_FILE=$CA TTL_BASE_URL=${TTL_BASE_URL:-https://127.0.0.1:8444} NO_PROXY=127.0.0.1,localhost no_proxy=127.0.0.1,localhost
|
||||
mkdir -p evidence evidence/track1 evidence/scan
|
||||
stamp() { echo "# $(now) commit=$(git rev-parse --short HEAD 2>/dev/null || echo n/a) host=$(uname -srm) cpus=$(getconf _NPROCESSORS_ONLN)"; }
|
||||
run() { name=$1; shift; { stamp; echo "\$ $*"; "$@" 2>&1; echo "exit=$?"; } > "evidence/$name.txt" || true; tail -2 "evidence/$name.txt"; }
|
||||
IN_WORKER="dc run --rm --no-deps -T -v $PWD/student-tests:/app/student-tests:ro --entrypoint python worker"
|
||||
IN_API="dc run --rm --no-deps -T -v $PWD/student-tests:/app/student-tests:ro --entrypoint python api"
|
||||
|
||||
./scripts/init-secrets.sh
|
||||
PROFILES="--profile ttl" ./scripts/up.sh
|
||||
dc --profile tools up -d ops
|
||||
{ stamp; docker version --format 'docker {{.Server.Version}}'; dc version; dc --profile ttl images; dc --profile ttl ps -a; state; } > evidence/stack.txt 2>&1
|
||||
# ---------------------------------------------------------------- bootstrap (значения секретов не выводятся)
|
||||
run pki-status dc --profile tools run --rm --no-deps -T pki status
|
||||
run openbao-status sh -c "$PY scripts/bao_admin.py status; $PY scripts/bao_admin.py kv-keys api; $PY scripts/bao_admin.py kv-keys worker; $PY scripts/bao_admin.py tokens api"
|
||||
run migrations sh -c "docker compose --env-file .env exec -T -u postgres postgres psql -d messenger -c 'SELECT version, left(checksum,12) AS checksum, applied_at FROM schema_migrations ORDER BY version' -c '\\du'; docker compose --env-file .env logs --no-log-prefix migrate"
|
||||
run broker-bootstrap dc logs --no-log-prefix broker-init
|
||||
run s3-bootstrap dc logs --no-log-prefix s3-init
|
||||
run published-ports sh -c "docker compose --env-file .env ps --format '{{.Service}} {{.Ports}}' | sort -u"
|
||||
run kdf-bench dc exec -T api python -m messenger kdf-bench
|
||||
# ---------------------------------------------------------------- публичные проверки (HTTPS + CA)
|
||||
run make-check make check
|
||||
run smoke $PY tests/smoke.py --base-url "$B" --ca-file "$CA"
|
||||
run test-security-public $PY tests/security.py --base-url "$B" --ca-file "$CA"
|
||||
# ---------------------------------------------------------------- lab7: матрица доверия, внешняя граница, hardening
|
||||
run internal-security dc --profile tests run --rm -T probe student-tests/internal_security.py
|
||||
run test-security $PY student-tests/test_security.py
|
||||
run test-hardening $PY student-tests/test_hardening.py --json evidence/hardening.json
|
||||
if [ -d "${GHSA_DB:-/tmp/ghsa}/advisories" ]; then
|
||||
run dep-scan $PY scripts/dep_scan.py --db "${GHSA_DB:-/tmp/ghsa}" --json evidence/scan/deps.json
|
||||
fi
|
||||
# ---------------------------------------------------------------- регрессия lab2–lab6 (поверх HTTPS/mTLS/OpenBao)
|
||||
if [ "${SKIP_REGRESSION:-0}" != 1 ]; then
|
||||
# Учебные хуки отказов lab5 (маркер в имени файла) по умолчанию ВЫКЛЮЧЕНЫ (это вектор DoS) — включаем только
|
||||
# на время регрессии и выключаем обратно. export: тесты сами пересоздают worker и должны унаследовать значение.
|
||||
export FAULT_HOOKS=lab
|
||||
dc up -d --no-deps --force-recreate --wait api worker >/dev/null 2>&1
|
||||
run test-api $PY student-tests/test_api.py
|
||||
run test-idempotency $PY student-tests/test_idempotency.py
|
||||
run test-attachments $PY student-tests/test_attachments.py
|
||||
run test-expiry $PY student-tests/test_expiry.py
|
||||
run test-cache-race $IN_API student-tests/test_cache_race.py
|
||||
run test-pipeline $PY student-tests/test_pipeline.py
|
||||
run test-imgproc $IN_WORKER student-tests/test_imgproc.py
|
||||
run test-failures $PY student-tests/test_failures.py
|
||||
run test-observability $PY student-tests/test_observability.py
|
||||
run test-jobs-failures $PY student-tests/test_jobs_failures.py
|
||||
run test-storage-failures $PY student-tests/test_storage_failures.py
|
||||
run test-pipeline-idempotency $PY student-tests/test_pipeline_idempotency.py
|
||||
run test-telemetry-persistence $PY student-tests/test_telemetry_persistence.py
|
||||
unset FAULT_HOOKS
|
||||
dc --profile fault stop api-fault >/dev/null 2>&1 || true
|
||||
dc up -d --no-deps --force-recreate --wait api worker >/dev/null 2>&1
|
||||
fi
|
||||
# ---------------------------------------------------------------- отказ реплик и сохранность (публичные hooks)
|
||||
: > evidence/failover-hook.txt
|
||||
run failover-1 $PY tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url "$B" --ca-file "$CA"
|
||||
run restore-1 ./scripts/start-replicas.sh
|
||||
run failover-2 $PY tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url "$B" --ca-file "$CA"
|
||||
run restore-2 ./scripts/start-replicas.sh
|
||||
: > evidence/restart-hook.txt
|
||||
run persistence $PY tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url "$B" --ca-file "$CA"
|
||||
# ---------------------------------------------------------------- уровень 4: lifecycle под нагрузкой
|
||||
run test-lifecycle $PY student-tests/test_lifecycle.py --json evidence/lifecycle.json
|
||||
# ---------------------------------------------------------------- трек 5.1 и бюджет login DoS
|
||||
if [ "${SKIP_RESEARCH:-0}" != 1 ]; then
|
||||
run track1-worker-compromise $PY research/worker_compromise.py --out evidence/track1
|
||||
run login-dos $PY research/login_dos.py --out evidence/login_dos.json
|
||||
fi
|
||||
# ---------------------------------------------------------------- итог: всё ещё работает после ротаций/инцидентов
|
||||
run internal-security-final dc --profile tests run --rm -T probe student-tests/internal_security.py
|
||||
run smoke-final $PY tests/smoke.py --base-url "$B" --ca-file "$CA"
|
||||
run jobs-invariants dc --profile tools exec -T ops python -m messenger jobs invariants --settled --verify-bytes
|
||||
run load $PY tests/load.py --base-url "$B" --ca-file "$CA" --duration 30 --concurrency 4 --output evidence/load.json
|
||||
run secret-scan $PY scripts/secret_scan.py
|
||||
echo "evidence collected in evidence/"
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Оператор: реагирование на компрометацию identity worker (runbook трека 1). Без пересборки образов.
|
||||
|
||||
python3 scripts/compromise_response.py worker [--json evidence/track1/response.json]
|
||||
|
||||
Шаги (порядок важен: сначала отрезать доступ, потом выдать новый материал, потом восстановить работу):
|
||||
1. OpenBao: уничтожить ВСЕ SecretID роли messenger-worker и отозвать все её токены — украденные role_id/SecretID
|
||||
и уже выданный токен перестают работать немедленно;
|
||||
2. PKI: новый ключ+сертификат worker, старый серийный номер → CRL; pinned_certs NATS без старого ключа;
|
||||
reload: NATS закрывает соединения со старым сертификатом, PostgreSQL/шлюз Collector перечитывают CRL;
|
||||
3. PostgreSQL: экстренная смена роли worker (новый пароль на другой blue/green-роли, старая — NOLOGIN,
|
||||
все её сессии закрыты) — секреты, вынесенные из OpenBao до шага 1, бесполезны;
|
||||
4. S3: новый ключ identity messenger-worker, старый удалён из конфигурации (SIGHUP);
|
||||
5. OpenBao: новый SecretID в secrets/bao/worker (файл монтируется только worker);
|
||||
6. worker пересоздаются (новый сертификат/SecretID читаются при старте), обработка возобновляется;
|
||||
7. задания, «съеденные» злоумышленником (сообщения подтверждены без обработки), переопубликуются из
|
||||
PostgreSQL (источник истины) — jobs republish-stuck.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from opslib import ROOT, dc, now, ops_exec
|
||||
|
||||
|
||||
def step(timeline, name, fn):
|
||||
t0 = time.monotonic()
|
||||
out = fn()
|
||||
timeline.append({"step": name, "at": now(), "seconds": round(time.monotonic() - t0, 1), "result": out})
|
||||
print("[%s] %-58s %5.1fs" % (now(), name, timeline[-1]["seconds"]), flush=True)
|
||||
return out
|
||||
|
||||
|
||||
def py(script, *args):
|
||||
r = subprocess.run([sys.executable, str(ROOT / "scripts" / script)] + list(args), cwd=ROOT, capture_output=True,
|
||||
text=True, timeout=600)
|
||||
if r.returncode != 0:
|
||||
raise RuntimeError("%s failed: %s" % (script, (r.stderr or r.stdout)[-400:]))
|
||||
s = r.stdout
|
||||
return json.loads(s[s.find("{"):]) if "{" in s else s.strip()
|
||||
|
||||
|
||||
def wait_healthy(service, timeout=180):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
ids = [x for x in dc("ps", "-q", service).stdout.split() if x]
|
||||
st = [subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", i], capture_output=True,
|
||||
text=True).stdout.strip() for i in ids]
|
||||
if ids and all(x == "healthy" for x in st):
|
||||
return len(ids)
|
||||
time.sleep(1)
|
||||
raise RuntimeError("%s not healthy" % service)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("service", choices=["worker"])
|
||||
ap.add_argument("--json")
|
||||
a = ap.parse_args()
|
||||
tl = []
|
||||
t0 = time.monotonic()
|
||||
step(tl, "1 OpenBao: revoke all SecretID + tokens of messenger-worker", lambda: py("bao_admin.py", "revoke-identity", "worker"))
|
||||
step(tl, "2 PKI: rotate worker leaf, revoke old serial, reload CRL/pins", lambda: py("rotate_cert.py", "worker"))
|
||||
step(tl, "3 PostgreSQL: emergency role switch (old NOLOGIN + kill)", lambda: py("rotate_credentials.py", "db", "worker", "--emergency"))
|
||||
step(tl, "4 S3: emergency key rotation (old key removed)", lambda: py("rotate_credentials.py", "s3", "worker", "--emergency"))
|
||||
cut = round(time.monotonic() - t0, 1)
|
||||
step(tl, "5 OpenBao: issue new SecretID for worker", lambda: py("bao_admin.py", "rotate-secret-id", "worker"))
|
||||
step(tl, "6 recreate worker containers, wait healthy",
|
||||
lambda: (dc("up", "-d", "--no-deps", "--force-recreate", "worker", timeout=300).returncode, wait_healthy("worker"))[1])
|
||||
step(tl, "7 republish jobs lost from the broker (from PostgreSQL)",
|
||||
lambda: json.loads(ops_exec("python", "-m", "messenger", "jobs", "republish-stuck", "--older-than", "0").stdout))
|
||||
res = {"service": a.service, "started": tl[0]["at"], "access_cut_after_s": cut,
|
||||
"processing_restored_after_s": round(time.monotonic() - t0, 1), "timeline": tl}
|
||||
print(json.dumps(res, ensure_ascii=False, indent=1))
|
||||
if a.json:
|
||||
Path(a.json).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(a.json).write_text(json.dumps(res, ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Dependency scan по GitHub Advisory Database (формат OSV, только reviewed): зависимости Python приложения
|
||||
(requirements.txt) и Go-компоненты закреплённых образов (security/components.json). Офлайн: база — git clone.
|
||||
|
||||
git clone --depth 1 --filter=blob:none --sparse https://github.com/github/advisory-database /tmp/ghsa
|
||||
git -C /tmp/ghsa sparse-checkout set advisories/github-reviewed
|
||||
python3 scripts/dep_scan.py --db /tmp/ghsa [--json evidence/scan/deps.json]
|
||||
|
||||
Каждая находка сопоставляется с решением из security/scan-triage.json (applicable / not_applicable /
|
||||
mitigated / fixed_by_upgrade + обоснование). Находка без решения — ошибка (exit 1): новый CVE нельзя
|
||||
«не заметить». Образный (OS-пакеты) скан — scripts/scan.sh (Trivy), разбор — тот же файл triage.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def norm(name):
|
||||
return re.sub(r"[-_.]+", "-", name).lower()
|
||||
|
||||
|
||||
def pep440(v):
|
||||
from packaging.version import Version # noqa: PLC0415 — packaging есть почти везде (pip)
|
||||
return Version(v)
|
||||
|
||||
|
||||
_SEMVER = re.compile(r"^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-(.+))?$")
|
||||
|
||||
|
||||
def gover(v):
|
||||
"""Ключ сравнения Go-версий, включая pseudo-versions vX.Y.Z-YYYYMMDDHHMMSS-hash."""
|
||||
m = _SEMVER.match(v.strip())
|
||||
if not m:
|
||||
return (0, 0, 0, 0, v)
|
||||
pre = m.group(4) or ""
|
||||
ts = re.search(r"(\d{14})-[0-9a-f]{12}$", pre)
|
||||
major, minor, patch = int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0)
|
||||
if ts: # pseudo-version: упорядочивается по времени коммита
|
||||
return (major, minor, patch, -1, ts.group(1))
|
||||
return (major, minor, patch, 0 if pre else 1, pre)
|
||||
|
||||
|
||||
_PSEUDO = re.compile(r"\d{14}-[0-9a-f]{12}$")
|
||||
|
||||
|
||||
def affected(version, ranges, versions, eco, pseudo=None, last_known=None):
|
||||
"""OSV ranges. Для модулей с pseudo-version: граница-pseudo сравнивается с pseudo компонента (время коммита
|
||||
тега), обычная semver-граница — с версией релиза. last_known — database_specific.last_known_affected_version_range
|
||||
GHSA (верхняя граница диапазона без события fixed, например «< 12.3.7»)."""
|
||||
key = pep440 if eco == "PyPI" else gover
|
||||
|
||||
def cmp_value(bound):
|
||||
return key(pseudo) if pseudo and _PSEUDO.search(bound) else key(version)
|
||||
if version in (versions or []):
|
||||
return True
|
||||
for r in ranges or []:
|
||||
if r.get("type") not in ("ECOSYSTEM", "SEMVER"):
|
||||
continue
|
||||
hit = False
|
||||
for ev in r.get("events", []):
|
||||
try:
|
||||
if "introduced" in ev:
|
||||
b = ev["introduced"]
|
||||
hit = b == "0" or cmp_value(b) >= key(b)
|
||||
elif "fixed" in ev and hit:
|
||||
if cmp_value(ev["fixed"]) < key(ev["fixed"]):
|
||||
return True
|
||||
hit = False
|
||||
elif "last_affected" in ev and hit:
|
||||
if cmp_value(ev["last_affected"]) <= key(ev["last_affected"]):
|
||||
return True
|
||||
hit = False
|
||||
except Exception: # noqa: BLE001
|
||||
hit = False
|
||||
if hit:
|
||||
m = re.match(r"^\s*(<=?)\s*(\S+)", last_known or "")
|
||||
if m: # верхняя граница из database_specific
|
||||
v, b = cmp_value(m.group(2)), key(m.group(2))
|
||||
return v <= b if m.group(1) == "<=" else v < b
|
||||
return True # introduced без fixed — уязвимы все последующие
|
||||
return False
|
||||
|
||||
|
||||
def components():
|
||||
out = []
|
||||
for line in (ROOT / "requirements.txt").read_text().splitlines():
|
||||
m = re.match(r"^([A-Za-z0-9_.\-\[\]]+)==([^\s;#]+)", line.strip())
|
||||
if m:
|
||||
out.append({"ecosystem": "PyPI", "name": re.sub(r"\[.*\]", "", m.group(1)), "version": m.group(2),
|
||||
"where": "app image (requirements.txt)"})
|
||||
out += json.loads((ROOT / "security" / "components.json").read_text())["components"]
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--db", required=True)
|
||||
ap.add_argument("--json")
|
||||
a = ap.parse_args()
|
||||
comps = components()
|
||||
want = {(c["ecosystem"], norm(c["name"]) if c["ecosystem"] == "PyPI" else c["name"]) for c in comps}
|
||||
triage = json.loads((ROOT / "security" / "scan-triage.json").read_text())["decisions"]
|
||||
findings = []
|
||||
files = list(Path(a.db, "advisories", "github-reviewed").rglob("*.json"))
|
||||
for f in files:
|
||||
try:
|
||||
d = json.loads(f.read_text())
|
||||
except ValueError:
|
||||
continue
|
||||
if d.get("withdrawn"):
|
||||
continue
|
||||
for aff in d.get("affected", []):
|
||||
pkg = aff.get("package", {})
|
||||
eco = pkg.get("ecosystem")
|
||||
name = norm(pkg.get("name", "")) if eco == "PyPI" else pkg.get("name", "")
|
||||
if (eco, name) not in want:
|
||||
continue
|
||||
for c in comps:
|
||||
cname = norm(c["name"]) if eco == "PyPI" else c["name"]
|
||||
if c["ecosystem"] != eco or cname != name:
|
||||
continue
|
||||
lk = (aff.get("database_specific") or {}).get("last_known_affected_version_range")
|
||||
if affected(c["version"], aff.get("ranges"), aff.get("versions"), eco, c.get("pseudo"), lk):
|
||||
if any(x["id"] == d["id"] and x["package"] == c["name"] for x in findings):
|
||||
continue
|
||||
fixed = [ev["fixed"] for r in aff.get("ranges", []) for ev in r.get("events", []) if "fixed" in ev]
|
||||
sev = (d.get("database_specific") or {}).get("severity", "UNKNOWN")
|
||||
findings.append({"id": d["id"], "aliases": d.get("aliases", []), "severity": sev,
|
||||
"package": c["name"], "version": c["version"], "where": c["where"],
|
||||
"fixed": fixed, "summary": d.get("summary", "")[:160],
|
||||
"triage": triage.get(d["id"])})
|
||||
findings.sort(key=lambda x: (["CRITICAL", "HIGH", "MODERATE", "LOW", "UNKNOWN"].index(x["severity"])
|
||||
if x["severity"] in ("CRITICAL", "HIGH", "MODERATE", "LOW") else 4, x["package"]))
|
||||
untriaged = [x for x in findings if not x["triage"]]
|
||||
print("## dependency scan: %d components, %d advisories in DB, %d findings, %d untriaged" % (
|
||||
len(comps), len(files), len(findings), len(untriaged)))
|
||||
for x in findings:
|
||||
t = x["triage"] or {"decision": "UNTRIAGED", "reason": ""}
|
||||
print("%-9s %-20s %-45s %s %s → fixed %s\n [%s] %s\n triage: %s — %s" % (
|
||||
x["severity"], x["id"], x["package"][:45], x["version"], "/".join(x["aliases"][:1]),
|
||||
",".join(x["fixed"][:2]) or "-", x["where"], x["summary"], t["decision"], t["reason"]))
|
||||
if a.json:
|
||||
Path(a.json).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(a.json).write_text(json.dumps({"components": comps, "findings": findings}, ensure_ascii=False, indent=1))
|
||||
sys.exit(1 if untriaged else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,55 @@
|
||||
# Windows PowerShell 5.1+ version of scripts/init-secrets.sh (lab7, operator).
|
||||
# Creates local synthetic secrets in secrets\ (git-ignored) + .env, then the local PKI (CA, leaf certificates of every
|
||||
# service identity, CRL, negative-test material) in a one-shot container "pki" (no openssl needed on the host).
|
||||
# Idempotent: existing files are NOT overwritten. Values are never printed.
|
||||
# powershell -NoProfile -ExecutionPolicy Bypass -File scripts\init-secrets.ps1
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $root 'secrets') | Out-Null
|
||||
$ascii = New-Object System.Text.ASCIIEncoding
|
||||
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
|
||||
function New-Hex {
|
||||
$bytes = New-Object byte[] 24
|
||||
$rng.GetBytes($bytes)
|
||||
($bytes | ForEach-Object { $_.ToString('x2') }) -join ''
|
||||
}
|
||||
function New-KeyId {
|
||||
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
|
||||
$bytes = New-Object byte[] 20
|
||||
$rng.GetBytes($bytes)
|
||||
-join ($bytes | ForEach-Object { $alphabet[$_ % $alphabet.Length] })
|
||||
}
|
||||
function Set-SecretFile([string]$name, [string]$value) {
|
||||
$path = Join-Path (Join-Path $root 'secrets') $name
|
||||
if (-not (Test-Path $path)) {
|
||||
# No BOM, no trailing CR/LF: the value is read verbatim inside Linux containers.
|
||||
[System.IO.File]::WriteAllText($path, $value, $ascii)
|
||||
}
|
||||
}
|
||||
foreach ($n in 'postgres_password', 'db_owner_password', 'db_api_a_password', 'db_worker_a_password',
|
||||
'redis_api_password', 'redis_ops_password', 'grafana_admin_password') { Set-SecretFile $n (New-Hex) }
|
||||
foreach ($who in 'admin', 'api', 'worker') {
|
||||
Set-SecretFile ("s3_{0}_access_key_id" -f $who) (New-KeyId)
|
||||
Set-SecretFile ("s3_{0}_secret_access_key" -f $who) (New-Hex)
|
||||
}
|
||||
if (-not (Test-Path '.env')) { Copy-Item '.env.example' '.env' }
|
||||
$pyApp = Get-Command py -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
$pythonApp = Get-Command python -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if ($pyApp) { $py = $pyApp.Source; $pre = @('-3') } elseif ($pythonApp) { $py = $pythonApp.Source; $pre = @() }
|
||||
else { throw 'Python 3.9+ not found (install from python.org, enable "Add to PATH")' }
|
||||
$s3cfg = Join-Path $root 'secrets\s3_config.json'
|
||||
if (-not (Test-Path $s3cfg)) {
|
||||
$bucket = 'messenger-attachments'
|
||||
$line = Select-String -Path '.env' -Pattern '^S3_BUCKET=(.+)$' | Select-Object -Last 1
|
||||
if ($line) { $bucket = $line.Matches[0].Groups[1].Value.Trim() }
|
||||
$json = & $py @pre scripts\s3_config.py $bucket
|
||||
if ($LASTEXITCODE -ne 0) { throw 's3_config.py failed' }
|
||||
[System.IO.File]::WriteAllText($s3cfg, ($json -join "`n"), $ascii)
|
||||
}
|
||||
# PKI: CA + leaf certificates + CRL + test material (repeat = only missing ones). CA key stays in secrets\pki.
|
||||
& docker compose --env-file .env --profile tools build -q pki
|
||||
if ($LASTEXITCODE -ne 0) { throw 'docker compose build pki failed' }
|
||||
& docker compose --env-file .env --profile tools run --rm --no-deps -T pki init
|
||||
if ($LASTEXITCODE -ne 0) { throw 'pki init failed' }
|
||||
Write-Output 'secrets\ and .env are ready (values not shown).'
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/bin/sh
|
||||
# Оператор: локальные синтетические secrets и PKI стенда lab7 (каталог secrets/ — в .gitignore).
|
||||
# Идемпотентно: существующие файлы НЕ перезаписываются (иначе пароли разойдутся с уже инициализированными
|
||||
# томами). Значения не печатаются. Сертификаты выпускает одноразовый контейнер `pki` (образ приложения,
|
||||
# пакет cryptography) — на хосте не нужен openssl; CA private key остаётся в secrets/pki/ (только оператор).
|
||||
#
|
||||
# После этого: docker compose up -d openbao && python3 scripts/bao_admin.py init && ... unseal && ... bootstrap
|
||||
# (всё сразу — scripts/up.sh).
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
umask 077
|
||||
mkdir -p secrets
|
||||
chmod 700 secrets
|
||||
gen() { python3 -c 'import secrets; print(secrets.token_hex(24))'; }
|
||||
keyid() { python3 -c 'import secrets,string; print("".join(secrets.choice(string.ascii_uppercase+string.digits) for _ in range(20)))'; }
|
||||
put() { [ -f "secrets/$1" ] || "$2" > "secrets/$1"; }
|
||||
# PostgreSQL: суперпользователь (только оператор, вход peer через unix-socket внутри контейнера),
|
||||
# владелец схемы (one-shot migrate) и ЛОГИН-роли сервисов. Пароли api/worker затем живут в OpenBao.
|
||||
put postgres_password gen
|
||||
put db_owner_password gen
|
||||
put db_api_a_password gen
|
||||
put db_worker_a_password gen
|
||||
# Redis: ACL-пользователи (api — только свои ключи; ops — администратор для оператора/healthcheck).
|
||||
put redis_api_password gen
|
||||
put redis_ops_password gen
|
||||
# S3 (SeaweedFS): admin — только bootstrap bucket/оператор; api и worker — разные identity и prefix-права.
|
||||
for who in admin api worker; do
|
||||
put "s3_${who}_access_key_id" keyid
|
||||
put "s3_${who}_secret_access_key" gen
|
||||
done
|
||||
BUCKET=$(grep -E '^S3_BUCKET=' .env 2>/dev/null | tail -1 | cut -d= -f2 | tr -d '\r '); BUCKET=${BUCKET:-messenger-attachments}
|
||||
[ -f secrets/s3_config.json ] || python3 scripts/s3_config.py "$BUCKET" > secrets/s3_config.json
|
||||
put grafana_admin_password gen
|
||||
# Файлы паролей монтируются как compose secrets в инфраструктурные контейнеры; сервисы приложения их
|
||||
# НЕ получают (берут свои значения из OpenBao). Каталог secrets/ закрыт (700); файлы — 644 внутри него,
|
||||
# т.к. процессы в контейнерах работают под своими uid (Linux bind mount сохраняет владельца хоста).
|
||||
chmod 644 secrets/*_password secrets/*_access_key_id secrets/*_secret_access_key secrets/s3_config.json
|
||||
[ -f .env ] || cp .env.example .env
|
||||
# PKI: CA + leaf всех identity + CRL + материал отрицательных тестов (повтор — только недостающее).
|
||||
docker compose --env-file .env --profile tools build -q pki
|
||||
# PKI_OWNER: на Linux без root созданные контейнером каталоги/публичные файлы передаются оператору (ключи — uid сервисов).
|
||||
docker compose --env-file .env --profile tools run --rm --no-deps -T -e PKI_OWNER="$(id -u):$(id -g)" pki init
|
||||
echo "secrets/ and .env are ready (values not shown)."
|
||||
@@ -0,0 +1,26 @@
|
||||
# Общие функции хуков (POSIX sh). Подключается: . "$(dirname "$0")/lib.sh"
|
||||
cd "$(dirname "$0")/.."
|
||||
ENV_FILE=${ENV_FILE:-.env}
|
||||
dc() { docker compose --env-file "$ENV_FILE" "$@"; }
|
||||
now() { date -u +%FT%TZ; }
|
||||
# Состояние всех контейнеров проекта: сервис, имя, статус, StartedAt, PID, alias реплики API.
|
||||
state() {
|
||||
for cid in $(dc ps -a -q); do
|
||||
docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}} {{.Name}} status={{.State.Status}} started={{.State.StartedAt}} pid={{.State.Pid}}' "$cid" |
|
||||
sed 's# /# #'
|
||||
done | sort
|
||||
}
|
||||
# Контейнер API-реплики по её X-Instance-Id (alias пишется репликой в /tmp/instance-id).
|
||||
container_of() {
|
||||
for cid in $(dc ps -q api); do
|
||||
if [ "$(docker exec "$cid" cat /tmp/instance-id 2>/dev/null)" = "$1" ]; then echo "$cid"; return 0; fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
# Ждать healthy у всех контейнеров сервиса (не дольше 60 с).
|
||||
wait_healthy() {
|
||||
for cid in $(dc ps -q "$1"); do
|
||||
i=0
|
||||
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$cid")" = healthy ] || [ $i -ge 120 ]; do i=$((i + 1)); sleep 0.5; done
|
||||
done
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Общие функции операторских скриптов lab7 (stdlib, Python 3.9+, Linux/macOS/Windows).
|
||||
Команды Docker Compose берутся из COMPOSE (по умолчанию `docker compose --env-file .env`)."""
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DC = shlex.split(os.environ.get("COMPOSE", "docker compose --env-file .env"))
|
||||
|
||||
|
||||
def dc(*args, input=None, check=True, timeout=180, capture=True):
|
||||
"""docker compose …; секреты передаются только через stdin (input), не через argv."""
|
||||
r = subprocess.run(DC + list(args), cwd=ROOT, input=input, capture_output=capture, text=True, timeout=timeout)
|
||||
if check and r.returncode != 0:
|
||||
raise RuntimeError("docker compose %s → %d: %s" % (args[0], r.returncode, (r.stderr or "")[-400:]))
|
||||
return r
|
||||
|
||||
|
||||
def ops_exec(*args, input=None, check=True, timeout=180):
|
||||
"""Команда в контейнере ops (профиль tools; поднимается при необходимости)."""
|
||||
if not dc("--profile", "tools", "ps", "-q", "ops", check=False).stdout.strip():
|
||||
dc("--profile", "tools", "up", "-d", "ops")
|
||||
return dc("--profile", "tools", "exec", "-T", "ops", *args, input=input, check=check, timeout=timeout)
|
||||
|
||||
|
||||
def psql(sql, *, fetch=True):
|
||||
"""SQL суперпользователя postgres через unix-socket внутри контейнера (peer). Текст — через stdin."""
|
||||
r = dc("exec", "-T", "-u", "postgres", "postgres", "psql", "-X", "-q", "-At", "-v", "ON_ERROR_STOP=1",
|
||||
"-d", "messenger", input=sql)
|
||||
return [line for line in r.stdout.splitlines() if line] if fetch else None
|
||||
|
||||
|
||||
def reload_trust(services=None):
|
||||
"""Перечитать CRL/сертификаты/pinned_certs у всех потребителей (без рестарта и пересборки):
|
||||
HAProxy (lb, шлюзы) — seamless reload SIGUSR2; NATS — SIGHUP (закрывает соединения с исключёнными
|
||||
сертификатами); PostgreSQL — pg_reload_conf (ssl_* и CRL); OpenBao — SIGHUP (сертификат listener);
|
||||
API — сам перечитывает CRL/сертификат каждые 2 с; SeaweedFS — сам перечитывает сертификат."""
|
||||
done = []
|
||||
for svc in services or ("lb", "otel-gw", "prometheus-gw", "loki-gw", "tempo-gw"):
|
||||
if dc("kill", "-s", "USR2", svc, check=False).returncode == 0:
|
||||
done.append(svc + ":USR2")
|
||||
if services is None or "nats" in services:
|
||||
dc("kill", "-s", "HUP", "nats", check=False)
|
||||
done.append("nats:HUP")
|
||||
if services is None or "postgres" in services:
|
||||
dc("exec", "-T", "postgres", "sh", "-c", "install -m 600 /run/tls/self/tls.key /tmp/pgtls/tls.key", check=False)
|
||||
psql("SELECT pg_reload_conf();")
|
||||
done.append("postgres:reload")
|
||||
if services is None or "openbao" in services:
|
||||
dc("kill", "-s", "HUP", "openbao", check=False)
|
||||
done.append("openbao:HUP")
|
||||
return done
|
||||
|
||||
|
||||
def bao():
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
import bao_admin # noqa: E402
|
||||
return bao_admin
|
||||
|
||||
|
||||
def now():
|
||||
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
|
||||
|
||||
def out(obj):
|
||||
print(json.dumps(obj, ensure_ascii=False, indent=1))
|
||||
@@ -0,0 +1,21 @@
|
||||
# Windows PowerShell 5.1+ version of scripts/reset.sh: INTENTIONAL deletion of lab7 data (asks for confirmation).
|
||||
# Removes all project volumes (PostgreSQL, S3, NATS, OpenBao raft+audit, Prometheus/Loki/Tempo/Grafana), the OpenBao
|
||||
# operator material (it belongs to the deleted storage) and issued role_id/SecretID (secrets\bao). PKI and passwords in
|
||||
# secrets\ are kept; the next scripts\up.ps1 initializes OpenBao again. Normal stop without data loss:
|
||||
# docker compose --env-file .env --profile ttl --profile fault --profile tools --profile tests down --remove-orphans
|
||||
# powershell -NoProfile -ExecutionPolicy Bypass -File scripts\reset.ps1 [-Force]
|
||||
param([switch]$Force)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
$op = $env:MTUSI_OPERATOR_DIR
|
||||
if (-not $op) { $op = Join-Path $env:USERPROFILE '.mtusi-lab7-operator' }
|
||||
if (-not $Force) {
|
||||
$ans = Read-Host "Delete ALL lab7 data (volumes, $op\openbao-init.json, secrets\bao)? Type yes"
|
||||
if ($ans -ne 'yes') { Write-Output 'cancelled'; exit 1 }
|
||||
}
|
||||
& docker compose --env-file .env --profile ttl --profile fault --profile tools --profile tests down -v --remove-orphans
|
||||
if ($LASTEXITCODE -ne 0) { throw 'docker compose down -v failed' }
|
||||
Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $op 'openbao-init.json')
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue 'secrets\bao'
|
||||
Write-Output 'data deleted; start again: scripts\up.ps1'
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
# НАМЕРЕННОЕ удаление учебных данных стенда lab7 (с подтверждением):
|
||||
# * все volumes проекта (PostgreSQL, S3, NATS JetStream, raft и аудит OpenBao, Prometheus/Loki/Tempo/Grafana);
|
||||
# * материал оператора OpenBao (unseal shares, root token) — он относится к удалённому хранилищу и бесполезен;
|
||||
# * выданные role_id/SecretID (secrets/bao/).
|
||||
# PKI (CA, leaf, CRL) и пароли в secrets/ сохраняются: следующий ./scripts/up.sh инициализирует OpenBao заново
|
||||
# и загрузит в него те же значения. Полный сброс вместе с PKI: дополнительно rm -rf secrets (новый CA).
|
||||
# Обычная остановка без потери данных — make down.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
OP=${MTUSI_OPERATOR_DIR:-$HOME/.mtusi-lab7-operator}
|
||||
if [ "${FORCE:-0}" != 1 ]; then
|
||||
printf "Удалить ВСЕ данные стенда lab7 (volumes, %s/openbao-init.json, secrets/bao)? Введите yes: " "$OP"
|
||||
read -r ans
|
||||
[ "$ans" = yes ] || { echo "отменено"; exit 1; }
|
||||
fi
|
||||
docker compose --env-file .env --profile ttl --profile fault --profile tools --profile tests down -v --remove-orphans
|
||||
rm -f "$OP/openbao-init.json"
|
||||
rm -rf secrets/bao
|
||||
echo "данные удалены; запуск заново: ./scripts/up.sh"
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
rem Windows wrapper: tests\resilience.py starts the hook directly; .cmd runs without a shell.
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0restart.ps1"
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,44 @@
|
||||
# Windows PowerShell version of scripts/restart.sh (persistence hook, lab7): restart LB, ALL API replicas, workers,
|
||||
# PostgreSQL, Redis, S3, NATS JetStream, OpenBao (+ operator unseal) and observability keeping volumes. State before/after -> evidence\restart-hook.txt
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' }
|
||||
$log = Join-Path $root 'evidence\restart-hook.txt'
|
||||
function Dc { & docker compose --env-file $envFile @args 2>$null | Out-Null; if ($LASTEXITCODE -ne 0) { throw ('docker compose ' + ($args -join ' ') + ' failed') } }
|
||||
function Get-State {
|
||||
foreach ($cid in (& docker compose --env-file $envFile ps -a -q)) {
|
||||
& docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}} {{.Name}} status={{.State.Status}} started={{.State.StartedAt}} pid={{.State.Pid}}' $cid
|
||||
}
|
||||
& docker volume ls --filter label=com.docker.compose.project=mtusi-lab7 --format 'volume {{.Name}}'
|
||||
}
|
||||
try {
|
||||
Add-Content -Path $log -Encoding UTF8 -Value ('== ' + (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + ' before restart')
|
||||
Add-Content -Path $log -Encoding UTF8 -Value (Get-State)
|
||||
$ttl = @(& docker compose --env-file $envFile ps -q api-ttl 2>$null).Count -gt 0
|
||||
$workers = @(& docker compose --env-file $envFile ps -q worker 2>$null).Count -gt 0
|
||||
Dc stop lb api worker
|
||||
if ($ttl) { Dc stop api-ttl }
|
||||
Dc restart postgres redis s3 nats openbao otel-gw prometheus-gw loki-gw tempo-gw
|
||||
Dc restart otel-collector prometheus loki tempo grafana
|
||||
$env:NO_PROXY = '127.0.0.1,localhost'
|
||||
& python scripts/bao_admin.py unseal *>> $log # operator: 2 of 3 shares (values are not printed)
|
||||
# Wait for healthy storages (S3: gateway + master leader + writes; NATS: JetStream) before API/worker/LB.
|
||||
foreach ($svc in 'postgres', 'redis', 's3', 'nats', 'openbao', 'prometheus') {
|
||||
$cid = (& docker compose --env-file $envFile ps -q $svc | Select-Object -First 1)
|
||||
for ($i = 0; $i -lt 120; $i++) {
|
||||
if ((& docker inspect -f '{{.State.Health.Status}}' $cid) -eq 'healthy') { break }
|
||||
Start-Sleep -Milliseconds 500
|
||||
}
|
||||
}
|
||||
Dc start api
|
||||
if ($ttl) { Dc start api-ttl }
|
||||
if ($workers) { Dc start worker }
|
||||
Dc start lb
|
||||
Add-Content -Path $log -Encoding UTF8 -Value ('== ' + (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + ' after restart')
|
||||
Add-Content -Path $log -Encoding UTF8 -Value (Get-State)
|
||||
exit 0
|
||||
} catch {
|
||||
[Console]::Error.WriteLine($_.Exception.Message)
|
||||
exit 1
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
# Persistence hook (lab7): перезапускает LB, ВСЕ API-реплики, worker, все хранилища (PostgreSQL, Redis, S3,
|
||||
# NATS JetStream, OpenBao) и наблюдаемость (шлюзы + Collector/Prometheus/Loki/Tempo, Grafana), сохраняя
|
||||
# volumes. OpenBao после рестарта запечатан — хук (его запускает оператор) делает unseal материалом оператора
|
||||
# (~/.mtusi-lab7-operator, значения не печатаются). Никаких down -v / FLUSH / повторного seed.
|
||||
# Состояние контейнеров до/после (StartedAt, PID) — в evidence/restart-hook.txt.
|
||||
set -eu
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
export NO_PROXY="127.0.0.1,localhost" no_proxy="127.0.0.1,localhost"
|
||||
LOG=${RESTART_EVIDENCE:-evidence/restart-hook.txt}
|
||||
vols() { docker volume ls --filter label=com.docker.compose.project=mtusi-lab7 --format 'volume {{.Name}}'; }
|
||||
{ echo "== $(now) before restart"; state; vols; } >> "$LOG"
|
||||
running_ttl=$(dc ps -q api-ttl 2>/dev/null || true)
|
||||
running_worker=$(dc ps -q worker 2>/dev/null || true)
|
||||
dc stop lb api worker >/dev/null 2>&1
|
||||
[ -z "$running_ttl" ] || dc stop api-ttl >/dev/null 2>&1
|
||||
dc restart postgres redis s3 nats openbao otel-gw prometheus-gw loki-gw tempo-gw >/dev/null 2>&1
|
||||
dc restart otel-collector prometheus loki tempo grafana >/dev/null 2>&1
|
||||
python3 scripts/bao_admin.py unseal >> "$LOG" 2>&1 # оператор: 2 из 3 shares
|
||||
for svc in postgres redis s3 nats openbao prometheus; do wait_healthy "$svc"; done
|
||||
dc start api >/dev/null 2>&1
|
||||
[ -z "$running_ttl" ] || dc start api-ttl >/dev/null 2>&1
|
||||
[ -z "$running_worker" ] || dc start worker >/dev/null 2>&1
|
||||
dc start lb >/dev/null 2>&1
|
||||
{ echo "== $(now) after restart"; state; vols; } >> "$LOG"
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Оператор: ротация/отзыв leaf-сертификатов локального PKI БЕЗ пересборки образов.
|
||||
|
||||
python3 scripts/rotate_cert.py lb # новый ключ+сертификат LB, старый — в CRL, seamless reload
|
||||
python3 scripts/rotate_cert.py worker --restart # клиентские identity: + поочерёдный рестарт реплик
|
||||
python3 scripts/rotate_cert.py --revoke <serial|identity> # только отзыв (компрометация)
|
||||
python3 scripts/rotate_cert.py --renew 7 # перевыпуск всех, у кого осталось < 7 дней, + reload
|
||||
|
||||
Что происходит: pki (одноразовый контейнер, CA-ключ доступен только ему) выпускает новый ключ/сертификат в
|
||||
secrets/tls/<id>/ и вносит старые серийные номера в CRL (secrets/tls/trust/crl.pem), пересчитывает
|
||||
pinned_certs NATS. Затем потребители перечитывают: HAProxy (LB и шлюзы) — SIGUSR2 (без обрыва, новые
|
||||
соединения — новый сертификат/CRL), NATS — SIGHUP (соединения с неразрешённым сертификатом закрываются),
|
||||
PostgreSQL — pg_reload_conf, OpenBao — SIGHUP; реплики API сами перечитывают сертификат и CRL каждые 2 с
|
||||
и закрывают живые соединения с отозванным сертификатом. --restart нужен для клиентских сертификатов
|
||||
приложения (они читаются при установлении соединения с зависимостями).
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
|
||||
from opslib import dc, now, out, reload_trust
|
||||
|
||||
RESTARTABLE = {"api": ["api"], "worker": ["worker"], "otel-collector": ["otel-collector"], "grafana": ["grafana"],
|
||||
"prometheus": ["prometheus"], "tempo": ["tempo"], "redis": ["redis"]}
|
||||
|
||||
|
||||
def pki(*args):
|
||||
owner = ["-e", "PKI_OWNER=%d:%d" % (os.getuid(), os.getgid())] if hasattr(os, "getuid") else []
|
||||
r = dc("--profile", "tools", "run", "--rm", "--no-deps", "-T", *owner, "pki", *args)
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
def rolling_restart(service):
|
||||
ids = [x for x in dc("ps", "-q", service).stdout.split() if x]
|
||||
for cid in ids: # по одной реплике: остальные обслуживают трафик
|
||||
import subprocess
|
||||
subprocess.run(["docker", "restart", "-t", "15", cid], check=True, capture_output=True)
|
||||
deadline = time.time() + 120
|
||||
while time.time() < deadline:
|
||||
st = subprocess.run(["docker", "inspect", "-f", "{{if .State.Health}}{{.State.Health.Status}}{{else}}"
|
||||
"{{.State.Status}}{{end}}", cid], capture_output=True, text=True).stdout.strip()
|
||||
if st in ("healthy", "running"):
|
||||
break
|
||||
time.sleep(1)
|
||||
return len(ids)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("identity", nargs="?")
|
||||
ap.add_argument("--restart", action="store_true")
|
||||
ap.add_argument("--revoke")
|
||||
ap.add_argument("--renew", type=float)
|
||||
a = ap.parse_args()
|
||||
t0 = time.monotonic()
|
||||
res = {"at": now()}
|
||||
if a.revoke:
|
||||
res["pki"] = pki("revoke", a.revoke)
|
||||
elif a.renew is not None:
|
||||
res["pki"] = pki("renew", "--within-days", str(a.renew))
|
||||
elif a.identity:
|
||||
res["pki"] = pki("rotate", a.identity)
|
||||
else:
|
||||
ap.error("identity, --revoke or --renew required")
|
||||
res["reloaded"] = reload_trust()
|
||||
if a.restart and a.identity in RESTARTABLE:
|
||||
res["restarted"] = {s: rolling_restart(s) for s in RESTARTABLE[a.identity]}
|
||||
res["total_s"] = round(time.monotonic() - t0, 1)
|
||||
out(res)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,167 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Оператор: ротация рабочего secret сервиса БЕЗ пересборки и рестарта (значения не печатаются).
|
||||
|
||||
python3 scripts/rotate_credentials.py db worker # пароль роли PostgreSQL (blue/green _a ↔ _b)
|
||||
python3 scripts/rotate_credentials.py s3 api # ключ S3 identity (два ключа на время перехода)
|
||||
python3 scripts/rotate_credentials.py db api --emergency # компрометация: старая роль отключается сразу
|
||||
|
||||
Порядок (без простоя): 1) новый credential создаётся и начинает работать в целевой системе, старый ещё
|
||||
действует; 2) новая версия KV в OpenBao; 3) сервисы сами перечитывают KV (BAO_REFRESH_SECONDS) и новые
|
||||
соединения/запросы идут с новым credential — ждём подтверждения (pg_stat_activity / логи credentials_rotated);
|
||||
4) старый credential отключается (NOLOGIN / ключ удаляется из S3 + SIGHUP), оставшиеся сессии старой роли
|
||||
закрываются; 5) проверка: старым credential войти нельзя. --emergency пропускает ожидание шага 3.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import secrets
|
||||
import string
|
||||
import sys
|
||||
import time
|
||||
|
||||
from opslib import ROOT, bao, dc, now, ops_exec, out, psql
|
||||
|
||||
SECRETS = ROOT / "secrets"
|
||||
|
||||
|
||||
def kv_get(b, svc):
|
||||
t = b.root_token()
|
||||
return b.call("GET", "secret/data/" + b.SERVICES[svc]["kv"], token=t)["data"]
|
||||
|
||||
|
||||
def kv_patch(b, svc, patch):
|
||||
t = b.root_token()
|
||||
cur = kv_get(b, svc)
|
||||
data = dict(cur["data"], **patch)
|
||||
return b.call("POST", "secret/data/" + b.SERVICES[svc]["kv"],
|
||||
{"data": data, "options": {"cas": cur["metadata"]["version"]}}, token=t)["data"]["version"]
|
||||
|
||||
|
||||
def lit(value):
|
||||
"""SQL-литерал (значение генерируется здесь же: только [0-9a-f])."""
|
||||
assert all(ch in string.hexdigits for ch in value)
|
||||
return "'" + value + "'"
|
||||
|
||||
|
||||
def rotate_db(svc, grace, emergency):
|
||||
b = bao()
|
||||
cur = kv_get(b, svc)["data"]
|
||||
old = cur["db_user"]
|
||||
base = "messenger_%s_" % svc
|
||||
new = base + ("b" if old.endswith("_a") else "a")
|
||||
pw = secrets.token_hex(24)
|
||||
t0 = time.monotonic()
|
||||
psql("ALTER ROLE %s WITH LOGIN PASSWORD %s;" % (new, lit(pw)), fetch=False) # 1) новая роль работает
|
||||
version = kv_patch(b, svc, {"db_user": new, "db_password": pw}) # 2) новая версия KV
|
||||
(SECRETS / ("db_%s_%s_password" % (svc, new[-1]))).write_text(pw + "\n")
|
||||
switched = None
|
||||
terminated = 0
|
||||
deadline = time.monotonic() + (0 if emergency else grace)
|
||||
while True: # 3) сервисы перешли?
|
||||
rows = psql("SELECT usename, state, count(*) FROM pg_stat_activity WHERE usename IN ('%s','%s')"
|
||||
" GROUP BY 1, 2;" % (old, new))
|
||||
counts = {}
|
||||
for r in rows:
|
||||
u, st, n = r.split("|")
|
||||
counts.setdefault(u, {})[st] = int(n)
|
||||
if counts.get(new) and switched is None:
|
||||
switched = round(time.monotonic() - t0, 1)
|
||||
# простаивающие соединения старой роли закрываем сразу: пул проверит соединение и откроет новое
|
||||
terminated += len(psql("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = '%s'"
|
||||
" AND state = 'idle';" % old))
|
||||
if (switched is not None and not counts.get(old)) or time.monotonic() > deadline:
|
||||
break
|
||||
time.sleep(1)
|
||||
psql("ALTER ROLE %s WITH NOLOGIN PASSWORD NULL;" % old, fetch=False) # 4) старая роль выключена
|
||||
terminated += len(psql("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = '%s';" % old))
|
||||
# 5) проверка: старый пароль больше не даёт входа (новое подключение из контейнера ops — TLS + cert)
|
||||
probe = ops_exec("python", "-c",
|
||||
"import json,sys,psycopg;d=json.load(sys.stdin)\n"
|
||||
"from messenger.tlsconf import private_key_copy as k\n"
|
||||
"try:\n psycopg.connect(host='postgres',dbname='messenger',user=d['u'],password=d['p'],sslmode='verify-full',"
|
||||
"sslrootcert='/run/tls/trust/ca.crt',sslcert='/run/tls/self/tls.crt',sslkey=k('/run/tls/self/tls.key'),"
|
||||
"connect_timeout=3).close();print('LOGIN_OK')\n"
|
||||
"except Exception as e: print('REJECTED', ' '.join(str(e).split())[-90:])",
|
||||
input=json.dumps({"u": old, "p": cur["db_password"]}), check=False)
|
||||
return {"rotated": "db", "service": svc, "at": now(), "old_role": old, "new_role": new, "kv_version": version,
|
||||
"services_switched_after_s": switched, "old_sessions_terminated": terminated,
|
||||
"old_credential_check": probe.stdout.strip()[:140], "total_s": round(time.monotonic() - t0, 1)}
|
||||
|
||||
|
||||
def write_s3_config(keys):
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
import s3_config
|
||||
bucket = "messenger-attachments"
|
||||
try:
|
||||
for line in (ROOT / ".env").read_text().splitlines():
|
||||
if line.startswith("S3_BUCKET="):
|
||||
bucket = line.split("=", 1)[1].strip()
|
||||
except OSError:
|
||||
pass
|
||||
path = SECRETS / "s3_config.json"
|
||||
# запись «на месте» (тот же inode): файл смонтирован в контейнер s3 как compose secret
|
||||
with open(path, "r+") as fh:
|
||||
fh.seek(0)
|
||||
fh.write(json.dumps(s3_config.build(bucket, keys), indent=1))
|
||||
fh.truncate()
|
||||
dc("kill", "-s", "HUP", "s3") # SeaweedFS перечитывает identities без рестарта
|
||||
|
||||
|
||||
def current_s3_keys():
|
||||
rd = lambda n: (SECRETS / n).read_text().strip() # noqa: E731
|
||||
return {who: [(rd("s3_%s_access_key_id" % who), rd("s3_%s_secret_access_key" % who))]
|
||||
for who in ("admin", "api", "worker")}
|
||||
|
||||
|
||||
def count_rotations(svc, since):
|
||||
logs = dc("logs", "--no-log-prefix", "--since", since, svc, check=False).stdout
|
||||
return sum(1 for line in logs.splitlines() if '"credentials_rotated"' in line and "'s3'" in line)
|
||||
|
||||
|
||||
def rotate_s3(svc, grace, emergency):
|
||||
b = bao()
|
||||
cur = kv_get(b, svc)["data"]
|
||||
old = (cur["s3_access_key_id"], cur["s3_secret_access_key"])
|
||||
new = ("".join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(20)), secrets.token_hex(24))
|
||||
keys = current_s3_keys()
|
||||
keys[svc] = [old, new]
|
||||
t0 = time.monotonic()
|
||||
since = now()
|
||||
write_s3_config(keys) # 1) оба ключа действуют
|
||||
time.sleep(1)
|
||||
version = kv_patch(b, svc, {"s3_access_key_id": new[0], "s3_secret_access_key": new[1]}) # 2) KV
|
||||
replicas = len([x for x in dc("ps", "-q", svc).stdout.split() if x])
|
||||
switched = None
|
||||
deadline = time.monotonic() + (0 if emergency else grace)
|
||||
while time.monotonic() < deadline: # 3) все реплики перешли
|
||||
if count_rotations(svc, since) >= replicas:
|
||||
switched = round(time.monotonic() - t0, 1)
|
||||
break
|
||||
time.sleep(1)
|
||||
keys[svc] = [new]
|
||||
write_s3_config(keys) # 4) старый ключ удалён
|
||||
(SECRETS / ("s3_%s_access_key_id" % svc)).write_text(new[0] + "\n")
|
||||
(SECRETS / ("s3_%s_secret_access_key" % svc)).write_text(new[1] + "\n")
|
||||
time.sleep(1)
|
||||
probe = ops_exec("python", "-c",
|
||||
"import asyncio,json,sys\nfrom messenger.s3 import S3Client,S3Error\nd=json.load(sys.stdin)\n"
|
||||
"async def m():\n c=S3Client('https://s3:9000','us-east-1',d['a'],d['s'],timeout=5)\n"
|
||||
" try:\n await c.put_object(d['b'],'staging/rotation-probe',b'x');print('OLD_KEY_WORKS')\n"
|
||||
" except S3Error as e: print('REJECTED',e.status,e.code)\n await c.aclose()\nasyncio.run(m())",
|
||||
input=json.dumps({"a": old[0], "s": old[1], "b": "messenger-attachments"}), check=False)
|
||||
return {"rotated": "s3", "service": svc, "at": now(), "kv_version": version, "replicas": replicas,
|
||||
"services_switched_after_s": switched, "old_credential_check": probe.stdout.strip()[:120],
|
||||
"total_s": round(time.monotonic() - t0, 1)}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("kind", choices=["db", "s3"])
|
||||
ap.add_argument("service", choices=["api", "worker"])
|
||||
ap.add_argument("--grace", type=float, default=60, help="сколько ждать перехода сервисов (с)")
|
||||
ap.add_argument("--emergency", action="store_true", help="не ждать перехода: старый credential — сразу off")
|
||||
a = ap.parse_args()
|
||||
out((rotate_db if a.kind == "db" else rotate_s3)(a.service, a.grace, a.emergency))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Генерирует identities SeaweedFS (s3_config.json) из файлов secrets/. Значения ключей не печатаются в лог —
|
||||
результат пишется в stdout, который init-secrets перенаправляет в secrets/s3_config.json (в .gitignore).
|
||||
|
||||
Права (least privilege по prefix внутри одного приватного bucket; Write в SeaweedFS включает Delete):
|
||||
admin — Admin (создание bucket; только one-shot s3-init и оператор);
|
||||
api — Write staging/* (загрузка, компенсация, janitor); Read originals/*, variants/* (выдача файлов);
|
||||
worker — Read staging/*, originals/* (исходник); Write originals/* (публикация), variants/* (результаты),
|
||||
staging/* (удаление после ready); List staging/ (sweeper осиротевших staging-объектов).
|
||||
Ни api, ни worker не могут: создавать/удалять bucket, читать/писать другие bucket'ы и prefix'ы, менять ACL.
|
||||
Ротация: у identity может быть несколько credentials — новый ключ добавляется, старый удаляется после
|
||||
перехода сервиса (scripts/rotate_credentials.py s3 <service>), применяется SIGHUP без рестарта S3.
|
||||
|
||||
usage: s3_config.py <bucket> [--extra-key service=ACCESS:SECRET_FILE]...
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
SECRETS = Path(__file__).resolve().parents[1] / "secrets"
|
||||
|
||||
|
||||
def rd(name):
|
||||
return (SECRETS / name).read_text().strip()
|
||||
|
||||
|
||||
def build(bucket, keys=None):
|
||||
b = bucket
|
||||
keys = keys or {who: [(rd("s3_%s_access_key_id" % who), rd("s3_%s_secret_access_key" % who))]
|
||||
for who in ("admin", "api", "worker")}
|
||||
cred = lambda who: [{"accessKey": a, "secretKey": s} for a, s in keys[who]] # noqa: E731
|
||||
return {"identities": [
|
||||
{"name": "admin", "credentials": cred("admin"), "actions": ["Admin", "Read", "List", "Tagging", "Write"]},
|
||||
{"name": "messenger-api", "credentials": cred("api"),
|
||||
"actions": ["Write:%s/staging/*" % b, "Read:%s/originals/*" % b, "Read:%s/variants/*" % b]},
|
||||
{"name": "messenger-worker", "credentials": cred("worker"),
|
||||
"actions": ["Read:%s/staging/*" % b, "Read:%s/originals/*" % b, "Write:%s/originals/*" % b,
|
||||
"Write:%s/variants/*" % b, "Write:%s/staging/*" % b, "List:%s/staging/*" % b]},
|
||||
]}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
bucket = sys.argv[1] if len(sys.argv) > 1 else "messenger-attachments"
|
||||
# Имя bucket попадает в правила доступа: мусор (перевод строки из .env и т.п.) сделал бы права неверными.
|
||||
if not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", bucket):
|
||||
sys.exit("недопустимое имя bucket: %r" % bucket)
|
||||
print(json.dumps(build(bucket), indent=1))
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/bin/sh
|
||||
# Скан образов стенда и репозитория Trivy (в контейнере aquasec/trivy, версия закреплена) + dependency scan
|
||||
# по GitHub Advisory Database. Требует доступ к реестрам/БД уязвимостей (на машине студента). Результаты —
|
||||
# evidence/scan/*.json; КАЖДАЯ находка HIGH/CRITICAL разбирается в security/scan-triage.json (применимость,
|
||||
# исправление или обоснование). Скан не печатает секретов: secrets/ исключён (.trivyignore не нужен — --skip-dirs).
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
OUT=evidence/scan
|
||||
mkdir -p "$OUT"
|
||||
TRIVY="docker run --rm -v /var/run/docker.sock:/var/run/docker.sock:ro -v $PWD:/src:ro -v trivy-cache:/root/.cache aquasec/trivy:0.75.0"
|
||||
docker compose --env-file .env build -q api
|
||||
# Образы стенда: приложение (собранное) + закреплённые инфраструктурные (ровно те теги, что в compose.yaml)
|
||||
for img in mtusi-lab7-app:local $(docker compose --env-file .env config --images | grep -v mtusi-lab7 | sort -u); do
|
||||
f="$OUT/image-$(echo "$img" | tr '/:' '__').json"
|
||||
$TRIVY image --quiet --scanners vuln --severity HIGH,CRITICAL --format json --output /dev/stdout "$img" > "$f" || true
|
||||
echo "scanned $img → $f"
|
||||
done
|
||||
# Репозиторий: зависимости, Dockerfile/compose (misconfig) и случайно закоммиченные секреты (кроме secrets/)
|
||||
$TRIVY fs --quiet --scanners vuln,misconfig,secret --skip-dirs /src/secrets --format json /src > "$OUT/repo.json" || true
|
||||
# Dependency scan по GHSA (офлайн-база: git clone, см. scripts/dep_scan.py)
|
||||
if [ -d "${GHSA_DB:-/tmp/ghsa}/advisories" ]; then
|
||||
python3 scripts/dep_scan.py --db "${GHSA_DB:-/tmp/ghsa}" --json "$OUT/deps.json"
|
||||
fi
|
||||
echo "Разберите HIGH/CRITICAL: python3 scripts/scan_summary.py $OUT (сверка с security/scan-triage.json)"
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Сводка Trivy-сканов evidence/scan/*.json: HIGH/CRITICAL по образам и сверка с security/scan-triage.json.
|
||||
Находка без решения (по CVE или GHSA) печатается как UNTRIAGED и даёт exit 1.
|
||||
|
||||
python3 scripts/scan_summary.py evidence/scan
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
triage = json.loads((ROOT / "security" / "scan-triage.json").read_text())
|
||||
decisions = dict(triage["decisions"])
|
||||
for k, v in triage.get("trivy", {}).items():
|
||||
decisions[k] = v
|
||||
d = Path(sys.argv[1] if len(sys.argv) > 1 else ROOT / "evidence" / "scan")
|
||||
untriaged = 0
|
||||
for f in sorted(d.glob("image-*.json")) + [d / "repo.json"]:
|
||||
if not f.exists():
|
||||
continue
|
||||
try:
|
||||
data = json.loads(f.read_text() or "{}")
|
||||
except ValueError:
|
||||
print("%s: not JSON" % f.name)
|
||||
continue
|
||||
rows = []
|
||||
for res in data.get("Results") or []:
|
||||
for v in res.get("Vulnerabilities") or []:
|
||||
if v.get("Severity") not in ("HIGH", "CRITICAL"):
|
||||
continue
|
||||
t = decisions.get(v["VulnerabilityID"]) or decisions.get(v.get("PkgName", "") + ":" + v["VulnerabilityID"])
|
||||
untriaged += t is None
|
||||
rows.append(" %-8s %-18s %-28s %-14s fixed=%-12s %s" % (
|
||||
v["Severity"], v["VulnerabilityID"], v.get("PkgName", "")[:28], v.get("InstalledVersion", "")[:14],
|
||||
(v.get("FixedVersion") or "-")[:12], (t or {"decision": "UNTRIAGED"})["decision"]))
|
||||
for s in res.get("Secrets") or []:
|
||||
untriaged += 1
|
||||
rows.append(" SECRET %s %s:%s" % (s.get("RuleID"), res.get("Target"), s.get("StartLine")))
|
||||
print("%s: %d HIGH/CRITICAL" % (f.name, len(rows)))
|
||||
print("\n".join(rows))
|
||||
sys.exit(1 if untriaged else 0)
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка «секреты не попали в репозиторий/evidence/архив»: ищет закрытые ключи (PEM), значения из secrets/,
|
||||
материал оператора OpenBao (root token, unseal shares), SecretID, токены OpenBao и заголовки Authorization.
|
||||
|
||||
python3 scripts/secret_scan.py [путь ...] # по умолчанию — весь репозиторий, кроме secrets/ и .git/
|
||||
|
||||
Значения секретов используются только для сравнения и не печатаются (печатается файл и тип находки).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SKIP_DIRS = {".git", "secrets", "__pycache__", ".venv", "node_modules"}
|
||||
PATTERNS = {
|
||||
"PEM private key": re.compile(rb"-----BEGIN (?:EC |RSA |ENCRYPTED )?PRIVATE KEY-----"),
|
||||
"OpenBao/Vault token": re.compile(rb"\b(?:s|hvs|hvb)\.[A-Za-z0-9]{24,}\b"),
|
||||
"Authorization: Bearer <token>": re.compile(rb"Authorization:\s*Bearer\s+[A-Za-z0-9_\-]{43}\b"),
|
||||
}
|
||||
|
||||
|
||||
def known_values():
|
||||
vals = {}
|
||||
sec = ROOT / "secrets"
|
||||
for p in sec.rglob("*"):
|
||||
if p.is_file() and p.stat().st_size < 4096 and p.suffix not in (".crt", ".pem", ".json", ".conf"):
|
||||
try:
|
||||
v = p.read_bytes().strip()
|
||||
except PermissionError: # ключи сервисов (0400, uid сервиса): их ловит шаблон PEM
|
||||
continue
|
||||
if len(v) >= 16 and b"BEGIN" not in v:
|
||||
vals[str(p.relative_to(ROOT))] = v
|
||||
op = Path(os.environ.get("MTUSI_OPERATOR_DIR", str(Path.home() / ".mtusi-lab7-operator"))) / "openbao-init.json"
|
||||
if op.exists():
|
||||
d = json.loads(op.read_text())
|
||||
vals["openbao root token"] = d["root_token"].encode()
|
||||
for i, k in enumerate(d["unseal_keys_b64"]):
|
||||
vals["unseal share %d" % (i + 1)] = k.encode()
|
||||
return vals
|
||||
|
||||
|
||||
def main():
|
||||
roots = [Path(x) for x in sys.argv[1:]] or [ROOT]
|
||||
vals = known_values()
|
||||
findings, files = [], 0
|
||||
for root in roots:
|
||||
for dirpath, dirnames, filenames in os.walk(root):
|
||||
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
|
||||
for fn in filenames:
|
||||
p = Path(dirpath) / fn
|
||||
try:
|
||||
data = p.read_bytes()
|
||||
except OSError:
|
||||
continue
|
||||
files += 1
|
||||
rel = str(p.relative_to(ROOT)) if ROOT in p.parents else str(p)
|
||||
for name, rx in PATTERNS.items():
|
||||
if rx.search(data):
|
||||
findings.append((rel, name))
|
||||
for name, v in vals.items():
|
||||
if v in data:
|
||||
findings.append((rel, "value of " + name))
|
||||
for rel, what in findings:
|
||||
print("FOUND %-60s %s" % (rel, what))
|
||||
print("secret scan: %d files, %d known secret values, %d findings" % (files, len(vals), len(findings)))
|
||||
sys.exit(1 if findings else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,14 @@
|
||||
# Windows PowerShell version of scripts/start-replicas.sh: start stopped API replicas, wait for healthy.
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' }
|
||||
$ids = @(& docker compose --env-file $envFile ps -a -q api)
|
||||
foreach ($cid in $ids) { & docker start $cid | Out-Null }
|
||||
for ($i = 0; $i -lt 120; $i++) {
|
||||
$bad = @($ids | Where-Object { (& docker inspect -f '{{.State.Health.Status}}' $_) -ne 'healthy' }).Count
|
||||
if ($bad -eq 0) { break }
|
||||
Start-Sleep -Milliseconds 500
|
||||
}
|
||||
foreach ($cid in $ids) { & docker inspect -f '{{.Name}} {{.State.Status}} {{.State.Health.Status}}' $cid }
|
||||
if ($bad -ne 0) { exit 1 }
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
# Восстанавливает остановленные API-реплики (после stop-one) и ждёт их healthcheck (≤60 с).
|
||||
set -eu
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
for cid in $(dc ps -a -q api); do docker start "$cid" >/dev/null; done
|
||||
i=0
|
||||
while [ $i -lt 120 ]; do
|
||||
bad=0
|
||||
for cid in $(dc ps -a -q api); do
|
||||
[ "$(docker inspect -f '{{.State.Health.Status}}' "$cid")" = healthy ] || bad=1
|
||||
done
|
||||
[ $bad -eq 0 ] && break
|
||||
i=$((i + 1)); sleep 0.5
|
||||
done
|
||||
state | grep '^api '
|
||||
[ $bad -eq 0 ]
|
||||
@@ -0,0 +1,16 @@
|
||||
# Start stopped workers and wait until healthy.
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' }
|
||||
function Wait-Healthy([string]$svc) {
|
||||
foreach ($cid in (& docker compose --env-file $envFile ps -q $svc)) {
|
||||
for ($i = 0; $i -lt 120; $i++) {
|
||||
if ((& docker inspect -f '{{.State.Health.Status}}' $cid) -eq 'healthy') { break }
|
||||
Start-Sleep -Milliseconds 500
|
||||
}
|
||||
}
|
||||
}
|
||||
& docker compose --env-file $envFile start worker 2>$null | Out-Null
|
||||
Wait-Healthy 'worker'
|
||||
& docker compose --env-file $envFile ps -a worker --format '{{.Name}} {{.State}} {{.Health}}'
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Запустить остановленные worker и дождаться healthy.
|
||||
set -eu
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
dc start worker >/dev/null 2>&1
|
||||
wait_healthy worker
|
||||
echo "$(now) workers started:"; dc ps -a worker --format '{{.Name}} {{.State}} {{.Health}}'
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
rem Windows wrapper: tests\resilience.py starts the hook directly; .cmd runs without a shell.
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0stop-one.ps1"
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,30 @@
|
||||
# Windows PowerShell version of scripts/stop-one.sh (failover hook). Stops EXACTLY ONE API replica whose
|
||||
# X-Instance-Id is in $env:TARGET_INSTANCE_ID and leaves it stopped. DB/Redis/LB/volumes untouched.
|
||||
# Restore afterwards: scripts\start-replicas.ps1
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' }
|
||||
$log = Join-Path $root 'evidence\failover-hook.txt'
|
||||
if (-not $env:TARGET_INSTANCE_ID) { [Console]::Error.WriteLine('TARGET_INSTANCE_ID is required'); exit 2 }
|
||||
function Get-State {
|
||||
foreach ($cid in (& docker compose --env-file $envFile ps -a -q)) {
|
||||
& docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}} {{.Name}} status={{.State.Status}} started={{.State.StartedAt}} pid={{.State.Pid}}' $cid
|
||||
}
|
||||
}
|
||||
$target = $null
|
||||
foreach ($cid in (& docker compose --env-file $envFile ps -q api)) {
|
||||
$id = (& docker exec $cid cat /tmp/instance-id 2>$null)
|
||||
if ($id -and $id.Trim() -eq $env:TARGET_INSTANCE_ID) { $target = $cid }
|
||||
}
|
||||
if (-not $target) { [Console]::Error.WriteLine('no running api replica with this id'); exit 1 }
|
||||
$name = (& docker inspect -f '{{.Name}}' $target).TrimStart('/')
|
||||
$stamp = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')
|
||||
Add-Content -Path $log -Encoding UTF8 -Value ("== $stamp stop-one target=" + $env:TARGET_INSTANCE_ID + " container=$name")
|
||||
Add-Content -Path $log -Encoding UTF8 -Value (Get-State)
|
||||
& docker stop -t 15 $target | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { exit 1 }
|
||||
$stamp = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')
|
||||
Add-Content -Path $log -Encoding UTF8 -Value ("== $stamp after stop")
|
||||
Add-Content -Path $log -Encoding UTF8 -Value (Get-State)
|
||||
exit 0
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
# Failover hook: останавливает РОВНО ОДНУ API-реплику — ту, чей X-Instance-Id передан тестом в
|
||||
# TARGET_INSTANCE_ID, — и оставляет её остановленной. БД, Redis, LB и volumes не трогает.
|
||||
# docker stop → SIGTERM → реплика 3 с отвечает 503 на /health/ready (LB выводит её), затем закрывает
|
||||
# listener и дожидается запросов в полёте. Возврат ≈ 4 с (< 10 с). Восстановление: scripts/start-replicas.sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
LOG=${FAILOVER_EVIDENCE:-evidence/failover-hook.txt}
|
||||
cid=$(container_of "$TARGET_INSTANCE_ID") || { echo "no running api replica with id $TARGET_INSTANCE_ID" >&2; exit 1; }
|
||||
name=$(docker inspect -f '{{.Name}}' "$cid" | tr -d /)
|
||||
{ echo "== $(now) stop-one target=$TARGET_INSTANCE_ID container=$name"; state; } >> "$LOG"
|
||||
docker stop -t 15 "$cid" >/dev/null
|
||||
{ echo "== $(now) after stop"; state; } >> "$LOG"
|
||||
@@ -0,0 +1,15 @@
|
||||
# Defense scenario: stop ALL workers and leave them stopped (API, broker, storages untouched).
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' }
|
||||
function Wait-Healthy([string]$svc) {
|
||||
foreach ($cid in (& docker compose --env-file $envFile ps -q $svc)) {
|
||||
for ($i = 0; $i -lt 120; $i++) {
|
||||
if ((& docker inspect -f '{{.State.Health.Status}}' $cid) -eq 'healthy') { break }
|
||||
Start-Sleep -Milliseconds 500
|
||||
}
|
||||
}
|
||||
}
|
||||
& docker compose --env-file $envFile stop worker 2>$null | Out-Null
|
||||
& docker compose --env-file $envFile ps -a worker --format '{{.Name}} {{.State}}'
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Сценарий защиты: остановить ВСЕ worker (SIGTERM → дорабатывают текущее ≤ 20 с, остальное вернёт брокер)
|
||||
# и оставить их остановленными. API, брокер, хранилища и volumes не трогает.
|
||||
set -eu
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
dc stop worker >/dev/null 2>&1
|
||||
echo "$(now) workers stopped:"; dc ps -a worker --format '{{.Name}} {{.State}}'
|
||||
@@ -0,0 +1,27 @@
|
||||
# Windows PowerShell 5.1+ version of scripts/up.sh (lab7, operator): build, OpenBao start -> init (first time) ->
|
||||
# unseal -> bootstrap (policies/AppRole/KV, role_id+SecretID into secrets\bao\<svc>), then all services (--wait).
|
||||
# Operator material (unseal shares, root token) is kept in %USERPROFILE%\.mtusi-lab7-operator, never printed.
|
||||
# powershell -NoProfile -ExecutionPolicy Bypass -File scripts\up.ps1 [-Profiles ttl]
|
||||
param([string[]]$Profiles = @())
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
$env:NO_PROXY = '127.0.0.1,localhost'
|
||||
$env:PYTHONUTF8 = '1'
|
||||
if (-not (Test-Path 'secrets\tls\trust\ca.crt')) { throw 'no secrets\tls: run scripts\init-secrets.ps1 first' }
|
||||
$pyApp = Get-Command py -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
$pythonApp = Get-Command python -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if ($pyApp) { $py = $pyApp.Source; $pre = @('-3') } elseif ($pythonApp) { $py = $pythonApp.Source; $pre = @() }
|
||||
else { throw 'Python 3.9+ not found' }
|
||||
function Dc { & docker compose --env-file .env @args; if ($LASTEXITCODE -ne 0) { throw ('docker compose ' + ($args -join ' ') + ' failed') } }
|
||||
function Bao { & $py @pre scripts\bao_admin.py @args; if ($LASTEXITCODE -ne 0) { throw ('bao_admin ' + ($args -join ' ') + ' failed') } }
|
||||
Dc build -q
|
||||
Dc up -d openbao
|
||||
Bao wait --timeout 90
|
||||
Bao init
|
||||
Bao unseal
|
||||
Bao bootstrap
|
||||
$pargs = @(); foreach ($p in $Profiles) { $pargs += @('--profile', $p) }
|
||||
Dc @pargs up -d --wait --wait-timeout 300
|
||||
& docker compose --env-file .env ps --format 'table {{.Service}}\t{{.Status}}\t{{.Ports}}'
|
||||
Write-Output 'ready: https://127.0.0.1:8443 (CA: secrets\tls\trust\ca.crt)'
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/bin/sh
|
||||
# Оператор: запуск стенда lab7 из готовых secrets (повторный запуск безопасен и идемпотентен).
|
||||
# 1) сборка образа приложения; 2) OpenBao: старт → init (только первый раз) → unseal → bootstrap
|
||||
# (policies/AppRole/KV, role_id+SecretID в secrets/bao/<svc>); 3) остальные сервисы, ожидание healthy.
|
||||
# Материал оператора OpenBao (unseal shares, root token) — в $MTUSI_OPERATOR_DIR (~/.mtusi-lab7-operator),
|
||||
# значения не печатаются. Профили: PROFILES="--profile ttl" ./scripts/up.sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
ENV_FILE=${ENV_FILE:-.env}
|
||||
dc() { docker compose --env-file "$ENV_FILE" "$@"; }
|
||||
[ -f secrets/tls/trust/ca.crt ] || { echo "нет secrets/tls: сначала ./scripts/init-secrets.sh" >&2; exit 2; }
|
||||
export NO_PROXY="127.0.0.1,localhost${NO_PROXY:+,$NO_PROXY}" no_proxy="127.0.0.1,localhost${no_proxy:+,$no_proxy}"
|
||||
dc build -q
|
||||
dc up -d openbao
|
||||
python3 scripts/bao_admin.py wait --timeout 90
|
||||
python3 scripts/bao_admin.py init
|
||||
python3 scripts/bao_admin.py unseal
|
||||
python3 scripts/bao_admin.py bootstrap
|
||||
# shellcheck disable=SC2086
|
||||
dc ${PROFILES:-} up -d --wait --wait-timeout 300
|
||||
dc ps --format 'table {{.Service}}\t{{.Status}}\t{{.Ports}}'
|
||||
echo "ready: https://127.0.0.1:${API_PORT:-8443} (CA: secrets/tls/trust/ca.crt)"
|
||||
Reference in New Issue
Block a user