ЛР 7: Безопасность, mTLS и OpenBao
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
This commit is contained in:
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Initialize/unseal OpenBao and configure a limited AppRole."""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import time
|
||||
import urllib.request
|
||||
import base64
|
||||
import secrets
|
||||
from urllib.error import HTTPError
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path("/app")
|
||||
SECRETS = ROOT / ".secrets"
|
||||
STATE = SECRETS / "openbao.json"
|
||||
API_POLICY = (ROOT / "infra/openbao/messenger-policy.hcl").read_text(encoding="utf-8")
|
||||
WORKER_POLICY = (ROOT / "infra/openbao/messenger-worker-policy.hcl").read_text(encoding="utf-8")
|
||||
CA = SECRETS / "certs/internal-ca.crt"
|
||||
ADDR = "https://openbao:8200"
|
||||
|
||||
|
||||
def call(path, method="GET", body=None, token=None):
|
||||
context = ssl.create_default_context(cafile=str(CA))
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
data = json.dumps(body).encode("utf-8") if body is not None else None
|
||||
request = urllib.request.Request(
|
||||
ADDR + path,
|
||||
data=data,
|
||||
headers=headers,
|
||||
method=method,
|
||||
)
|
||||
with urllib.request.urlopen(request, context=context, timeout=5) as response:
|
||||
raw = response.read()
|
||||
if not raw:
|
||||
return {}
|
||||
return json.loads(raw)
|
||||
|
||||
|
||||
def wait_ready():
|
||||
for _ in range(60):
|
||||
try:
|
||||
call("/v1/sys/health")
|
||||
except HTTPError as error:
|
||||
if error.code in (429, 472, 473, 501, 503):
|
||||
return
|
||||
time.sleep(1)
|
||||
except Exception:
|
||||
time.sleep(1)
|
||||
else:
|
||||
return
|
||||
raise SystemExit("OpenBao did not become ready")
|
||||
|
||||
|
||||
def root_token_is_valid(root):
|
||||
try:
|
||||
call("/v1/auth/token/lookup-self", "GET", token=root)
|
||||
return True
|
||||
except HTTPError as error:
|
||||
if error.code in (403, 400):
|
||||
return False
|
||||
raise
|
||||
|
||||
|
||||
def recover_root_token(unseal_key):
|
||||
otp_bytes = secrets.token_bytes(16)
|
||||
otp = base64.b64encode(otp_bytes).decode("ascii")
|
||||
attempt = call(
|
||||
"/v1/sys/generate-root/attempt",
|
||||
"PUT",
|
||||
{"otp": otp},
|
||||
)
|
||||
nonce = attempt["nonce"]
|
||||
update = call(
|
||||
"/v1/sys/generate-root/update",
|
||||
"PUT",
|
||||
{"key": unseal_key, "nonce": nonce},
|
||||
)
|
||||
if not update.get("complete"):
|
||||
raise SystemExit("OpenBao root token recovery did not complete")
|
||||
encoded = base64.b64decode(update["encoded_root_token"])
|
||||
decoded = bytes(value ^ otp_bytes[index] for index, value in enumerate(encoded))
|
||||
return decoded.decode("ascii")
|
||||
|
||||
|
||||
def main():
|
||||
SECRETS.mkdir(parents=True, exist_ok=True)
|
||||
SECRETS.chmod(0o700)
|
||||
wait_ready()
|
||||
if STATE.exists():
|
||||
state = json.loads(STATE.read_text(encoding="utf-8"))
|
||||
STATE.chmod(0o600)
|
||||
else:
|
||||
init = call("/v1/sys/init", "PUT", {"secret_shares": 1, "secret_threshold": 1})
|
||||
state = {
|
||||
"unseal_key": init["keys"][0],
|
||||
"root_token": init["root_token"],
|
||||
}
|
||||
STATE.write_text(json.dumps(state), encoding="utf-8")
|
||||
STATE.chmod(0o600)
|
||||
|
||||
try:
|
||||
health = call("/v1/sys/health")
|
||||
except Exception:
|
||||
health = {"sealed": True}
|
||||
if health.get("sealed"):
|
||||
call("/v1/sys/unseal", "PUT", {"key": state["unseal_key"]})
|
||||
|
||||
marker = SECRETS / "approle-created"
|
||||
root = state["root_token"]
|
||||
if not root_token_is_valid(root):
|
||||
root = recover_root_token(state["unseal_key"])
|
||||
state["root_token"] = root
|
||||
STATE.write_text(json.dumps(state), encoding="utf-8")
|
||||
STATE.chmod(0o600)
|
||||
try:
|
||||
call(
|
||||
"/v1/sys/mounts/secret",
|
||||
"POST",
|
||||
{"type": "kv", "options": {"version": "2"}},
|
||||
root,
|
||||
)
|
||||
except HTTPError as error:
|
||||
if error.code != 400:
|
||||
raise
|
||||
call("/v1/sys/policies/acl/messenger-api", "PUT", {"policy": API_POLICY}, root)
|
||||
call("/v1/sys/policies/acl/messenger-worker", "PUT", {"policy": WORKER_POLICY}, root)
|
||||
try:
|
||||
call("/v1/sys/auth/approle", "POST", {"type": "approle"}, root)
|
||||
except HTTPError as error:
|
||||
if error.code != 400:
|
||||
raise
|
||||
call(
|
||||
"/v1/auth/approle/role/messenger-api",
|
||||
"POST",
|
||||
{
|
||||
"token_policies": ["messenger-api"],
|
||||
"token_ttl": "10m",
|
||||
"token_max_ttl": "30m",
|
||||
},
|
||||
root,
|
||||
)
|
||||
call(
|
||||
"/v1/auth/approle/role/messenger-worker",
|
||||
"POST",
|
||||
{
|
||||
"token_policies": ["messenger-worker"],
|
||||
"token_ttl": "10m",
|
||||
"token_max_ttl": "30m",
|
||||
},
|
||||
root,
|
||||
)
|
||||
call(
|
||||
"/v1/secret/data/messenger/api",
|
||||
"POST",
|
||||
{"data": {
|
||||
"role": "api",
|
||||
"pg_user": os.environ["API_DB_USER"],
|
||||
"pg_password": os.environ["API_DB_PASSWORD"],
|
||||
"s3_access": os.environ["S3_API_ACCESS_KEY"],
|
||||
"s3_secret": os.environ["S3_API_SECRET_KEY"],
|
||||
"broker_user": os.environ["BROKER_API_USER"],
|
||||
"broker_password": os.environ["BROKER_API_PASSWORD"],
|
||||
}},
|
||||
root,
|
||||
)
|
||||
call(
|
||||
"/v1/secret/data/messenger/worker",
|
||||
"POST",
|
||||
{"data": {
|
||||
"role": "worker",
|
||||
"pg_user": os.environ["WORKER_DB_USER"],
|
||||
"pg_password": os.environ["WORKER_DB_PASSWORD"],
|
||||
"s3_access": os.environ["S3_WORKER_ACCESS_KEY"],
|
||||
"s3_secret": os.environ["S3_WORKER_SECRET_KEY"],
|
||||
"broker_user": os.environ["BROKER_WORKER_USER"],
|
||||
"broker_password": os.environ["BROKER_WORKER_PASSWORD"],
|
||||
}},
|
||||
root,
|
||||
)
|
||||
api_role = call("/v1/auth/approle/role/messenger-api/role-id", "GET", token=root)
|
||||
worker_role = call("/v1/auth/approle/role/messenger-worker/role-id", "GET", token=root)
|
||||
api_secret = call(
|
||||
"/v1/auth/approle/role/messenger-api/secret-id",
|
||||
"POST",
|
||||
{},
|
||||
root,
|
||||
)
|
||||
worker_secret = call(
|
||||
"/v1/auth/approle/role/messenger-worker/secret-id",
|
||||
"POST",
|
||||
{},
|
||||
root,
|
||||
)
|
||||
for path, value in (
|
||||
(SECRETS / "api-role-id", api_role["data"]["role_id"]),
|
||||
(SECRETS / "api-secret-id", api_secret["data"]["secret_id"]),
|
||||
(SECRETS / "worker-role-id", worker_role["data"]["role_id"]),
|
||||
(SECRETS / "worker-secret-id", worker_secret["data"]["secret_id"]),
|
||||
):
|
||||
path.write_text(value, encoding="utf-8")
|
||||
path.chmod(0o644)
|
||||
marker.write_text("configured", encoding="utf-8")
|
||||
marker.chmod(0o600)
|
||||
print("PASS: OpenBao is unsealed and scoped AppRoles are configured")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user