Complete lab 7 security implementation
This commit is contained in:
Executable
+200
@@ -0,0 +1,200 @@
|
||||
"""lab7: OpenBao AppRole policy allow/deny.
|
||||
|
||||
Сценарии:
|
||||
1. API token читает secret/messenger/api → 200
|
||||
2. API token читает secret/messenger/worker → 403
|
||||
3. Worker token читает secret/messenger/worker → 200
|
||||
4. Worker token читает secret/messenger/api → 403
|
||||
5. API token пишет в secret/messenger/api → 403 (policy read-only)
|
||||
6. API token read auth/token/lookup-self → policies = [messenger-api], default
|
||||
|
||||
Запуск (из корня репо, с доступом к OpenBao через docker exec):
|
||||
python3 student_tests/test_openbao_policy.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def docker_exec_bao(args, role_id=None, secret_id=None):
|
||||
"""Запустить `bao <args>` внутри openbao-контейнера с AppRole login."""
|
||||
if role_id and secret_id:
|
||||
# login → token → выполнить args с этим token
|
||||
login_cmd = [
|
||||
"docker", "exec", "mtusi2026lab7-openbao-1", "sh", "-c",
|
||||
f"BAO_ADDR=https://127.0.0.1:8200 BAO_CACERT=/openbao/certs/ca.crt "
|
||||
f"bao write -format=json auth/approle/login role_id={role_id} secret_id={secret_id}",
|
||||
]
|
||||
login = subprocess.run(login_cmd, capture_output=True, text=True, timeout=10)
|
||||
if login.returncode != 0:
|
||||
return None, f"login failed: {login.stderr}"
|
||||
try:
|
||||
token = json.loads(login.stdout)["auth"]["client_token"]
|
||||
except (KeyError, json.JSONDecodeError) as exc:
|
||||
return None, f"login parse error: {exc}"
|
||||
|
||||
cmd = [
|
||||
"docker", "exec", "mtusi2026lab7-openbao-1", "sh", "-c",
|
||||
f"BAO_ADDR=https://127.0.0.1:8200 BAO_CACERT=/openbao/certs/ca.crt "
|
||||
f"BAO_TOKEN={token} bao " + " ".join(args),
|
||||
]
|
||||
else:
|
||||
cmd = [
|
||||
"docker", "exec", "mtusi2026lab7-openbao-1", "sh", "-c",
|
||||
"BAO_ADDR=https://127.0.0.1:8200 BAO_CACERT=/openbao/certs/ca.crt "
|
||||
"bao " + " ".join(args),
|
||||
]
|
||||
r = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
|
||||
return r, None
|
||||
|
||||
|
||||
def kv_read(role_id, secret_id, path):
|
||||
"""KV v2 read: /v1/secret/data/<path>."""
|
||||
args = ["kv", "get", f"secret/{path}"]
|
||||
r, err = docker_exec_bao(args, role_id, secret_id)
|
||||
if err:
|
||||
return None, err
|
||||
if r.returncode != 0:
|
||||
return None, r.stderr.strip()
|
||||
return r.stdout, None
|
||||
|
||||
|
||||
def kv_write(role_id, secret_id, path, key, value):
|
||||
"""KV v2 write: /v1/secret/data/<path>."""
|
||||
args = ["kv", "put", f"secret/{path}", f"{key}={value}"]
|
||||
r, err = docker_exec_bao(args, role_id, secret_id)
|
||||
if err:
|
||||
return None, err
|
||||
if r.returncode != 0:
|
||||
return None, r.stderr.strip()
|
||||
return r.stdout, None
|
||||
|
||||
|
||||
def token_lookup(role_id, secret_id):
|
||||
"""Lookup self: policies."""
|
||||
args = ["token", "lookup", "-format=json"]
|
||||
r, err = docker_exec_bao(args, role_id, secret_id)
|
||||
if err:
|
||||
return None, err
|
||||
if r.returncode != 0:
|
||||
return None, r.stderr.strip()
|
||||
try:
|
||||
return json.loads(r.stdout), None
|
||||
except json.JSONDecodeError as exc:
|
||||
return None, f"parse error: {exc}"
|
||||
|
||||
|
||||
def main():
|
||||
# Читать AppRole credentials
|
||||
def read(path):
|
||||
try:
|
||||
return open(path).read().strip()
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
|
||||
role_api = read("security/bao_role_id_api")
|
||||
secret_api = read("security/bao_secret_id_api")
|
||||
role_worker = read("security/bao_role_id_worker")
|
||||
secret_worker = read("security/bao_secret_id_worker")
|
||||
|
||||
if not all([role_api, secret_api, role_worker, secret_worker]):
|
||||
print("FAIL: security/bao_* files not found. Run scripts/openbao-bootstrap-approle.sh")
|
||||
sys.exit(1)
|
||||
|
||||
failures = 0
|
||||
|
||||
# 1. API читает свой path → 200
|
||||
out, err = kv_read(role_api, secret_api, "messenger/api")
|
||||
if err:
|
||||
print(f"FAIL: API read own path: {err}")
|
||||
failures += 1
|
||||
else:
|
||||
print(f"PASS: API read secret/messenger/api (200)")
|
||||
|
||||
# 2. API читает чужой path (worker) → 403
|
||||
out, err = kv_read(role_api, secret_api, "messenger/worker")
|
||||
if err is None:
|
||||
print(f"FAIL: API прочитал чужой path secret/messenger/worker — ожидали 403")
|
||||
failures += 1
|
||||
elif "403" in err or "permission denied" in err.lower():
|
||||
print(f"PASS: API read чужой path → 403")
|
||||
else:
|
||||
print(f"FAIL: API read чужой path — неожиданная ошибка: {err}")
|
||||
failures += 1
|
||||
|
||||
# 3. Worker читает свой path → 200
|
||||
out, err = kv_read(role_worker, secret_worker, "messenger/worker")
|
||||
if err:
|
||||
print(f"FAIL: Worker read own path: {err}")
|
||||
failures += 1
|
||||
else:
|
||||
print(f"PASS: Worker read secret/messenger/worker (200)")
|
||||
|
||||
# 4. Worker читает чужой path (api) → 403
|
||||
out, err = kv_read(role_worker, secret_worker, "messenger/api")
|
||||
if err is None:
|
||||
print(f"FAIL: Worker прочитал чужой path secret/messenger/api — ожидали 403")
|
||||
failures += 1
|
||||
elif "403" in err or "permission denied" in err.lower():
|
||||
print(f"PASS: Worker read чужой path → 403")
|
||||
else:
|
||||
print(f"FAIL: Worker read чужой path — неожиданная ошибка: {err}")
|
||||
failures += 1
|
||||
|
||||
# 5. API пишет в свой path → 403 (policy read-only)
|
||||
out, err = kv_write(role_api, secret_api, "messenger/api", "test_key", "test_value")
|
||||
if err is None:
|
||||
print(f"FAIL: API записал в secret/messenger/api — ожидали 403 (policy read-only)")
|
||||
failures += 1
|
||||
elif "403" in err or "permission denied" in err.lower():
|
||||
print(f"PASS: API write в свой path → 403 (read-only)")
|
||||
else:
|
||||
print(f"FAIL: API write — неожиданная ошибка: {err}")
|
||||
failures += 1
|
||||
|
||||
# 6. Token lookup self — policies
|
||||
data, err = token_lookup(role_api, secret_api)
|
||||
if err:
|
||||
print(f"FAIL: API token lookup: {err}")
|
||||
failures += 1
|
||||
else:
|
||||
policies = data.get("data", {}).get("policies", [])
|
||||
print(f"API token policies: {policies}")
|
||||
if "messenger-api" not in policies:
|
||||
print(f"FAIL: API token не имеет policy messenger-api")
|
||||
failures += 1
|
||||
elif "root" in policies:
|
||||
print(f"FAIL: API token имеет policy root — избыточные привилегии")
|
||||
failures += 1
|
||||
else:
|
||||
print(f"PASS: API token policies = {policies} (без root)")
|
||||
|
||||
# 7. Worker token lookup — policies
|
||||
data, err = token_lookup(role_worker, secret_worker)
|
||||
if err:
|
||||
print(f"FAIL: Worker token lookup: {err}")
|
||||
failures += 1
|
||||
else:
|
||||
policies = data.get("data", {}).get("policies", [])
|
||||
print(f"Worker token policies: {policies}")
|
||||
if "messenger-worker" not in policies:
|
||||
print(f"FAIL: Worker token не имеет policy messenger-worker")
|
||||
failures += 1
|
||||
elif "root" in policies:
|
||||
print(f"FAIL: Worker token имеет policy root — избыточные привилегии")
|
||||
failures += 1
|
||||
else:
|
||||
print(f"PASS: Worker token policies = {policies} (без root)")
|
||||
|
||||
if failures:
|
||||
print(f"\nFAIL: {failures} проверок провалено")
|
||||
sys.exit(1)
|
||||
|
||||
print("\nPASS: OpenBao AppRole policy allow/deny работает (scoped, read-only, без root)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user