358 lines
18 KiB
Python
358 lines
18 KiB
Python
#!/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()
|