116 lines
4.0 KiB
Python
116 lines
4.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Explicit operator init/unseal/configuration. Never prints credential values."""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import ssl
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
PRIVATE = ROOT / "secrets"
|
|
OPERATOR = ROOT / "operator-private"
|
|
|
|
|
|
def call(path, data=None, *, method=None, token=True):
|
|
ctx = ssl.create_default_context(cafile=str(PRIVATE / "ca.pem"))
|
|
ctx.load_cert_chain(PRIVATE / "pki/operator/cert.pem", PRIVATE / "pki/operator/key.pem")
|
|
headers = {"Content-Type": "application/json"}
|
|
if token:
|
|
headers["X-Vault-Token"] = (OPERATOR / "root-token").read_text().strip()
|
|
req = urllib.request.Request(
|
|
os.getenv("BAO_OPERATOR_ADDR", "https://localhost:18207") + "/v1/" + path,
|
|
data=json.dumps(data).encode() if data is not None else None,
|
|
headers=headers,
|
|
method=method,
|
|
)
|
|
with urllib.request.urlopen(req, context=ctx, timeout=5) as response:
|
|
raw = response.read()
|
|
return json.loads(raw) if raw else {}
|
|
|
|
|
|
def unseal():
|
|
for share in json.loads((OPERATOR / "unseal-shares.json").read_text())[:2]:
|
|
result = call("sys/unseal", {"key": share}, token=False)
|
|
if result["sealed"]:
|
|
raise RuntimeError("OpenBao remained sealed")
|
|
|
|
|
|
def configure():
|
|
try:
|
|
call("sys/mounts/secret", {"type": "kv", "options": {"version": "2"}})
|
|
except urllib.error.HTTPError as exc:
|
|
if exc.code != 400:
|
|
raise
|
|
try:
|
|
call("sys/auth/cert", {"type": "cert"})
|
|
except urllib.error.HTTPError as exc:
|
|
if exc.code != 400:
|
|
raise
|
|
seed = json.loads((PRIVATE / "bao_seed.json").read_text())
|
|
for role, values in seed.items():
|
|
policy = (
|
|
'path "secret/data/services/'
|
|
+ role
|
|
+ '" { capabilities = ["read"] }\npath "auth/token/lookup-self" { capabilities = ["read"] }\npath "auth/token/renew-self" { capabilities = ["update"] }\n'
|
|
)
|
|
call("sys/policies/acl/" + role, {"policy": policy}, method="PUT")
|
|
call(
|
|
"auth/cert/certs/" + role,
|
|
{
|
|
"display_name": role,
|
|
"certificate": (PRIVATE / "pki" / role / "cert.pem").read_text(),
|
|
"allowed_common_names": role,
|
|
"token_policies": [role],
|
|
"token_no_default_policy": True,
|
|
"token_ttl": "30s",
|
|
"token_max_ttl": "60s",
|
|
},
|
|
)
|
|
call("secret/data/services/" + role, {"data": values})
|
|
try:
|
|
call("sys/audit/file", {"type": "file", "options": {"file_path": "/bao/data/audit.jsonl"}})
|
|
except urllib.error.HTTPError as exc:
|
|
if exc.code != 400:
|
|
raise
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("action", choices=["init", "unseal", "configure", "seal"])
|
|
args = parser.parse_args()
|
|
os.umask(0o077)
|
|
if args.action == "init":
|
|
for _attempt in range(30):
|
|
try:
|
|
status = call("sys/init", token=False)
|
|
break
|
|
except (OSError, urllib.error.URLError):
|
|
time.sleep(1)
|
|
else:
|
|
raise RuntimeError("OpenBao TLS endpoint unavailable")
|
|
if not status["initialized"]:
|
|
result = call(
|
|
"sys/init", {"secret_shares": 3, "secret_threshold": 2}, method="PUT", token=False
|
|
)
|
|
(OPERATOR / "root-token").write_text(result["root_token"])
|
|
(OPERATOR / "unseal-shares.json").write_text(json.dumps(result["keys_base64"]))
|
|
(OPERATOR / "root-token").chmod(0o600)
|
|
(OPERATOR / "unseal-shares.json").chmod(0o600)
|
|
unseal()
|
|
configure()
|
|
elif args.action == "unseal":
|
|
unseal()
|
|
elif args.action == "configure":
|
|
configure()
|
|
else:
|
|
call("sys/seal", {}, method="PUT")
|
|
print("OpenBao operator action complete; credential values were not printed.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|