142 lines
6.6 KiB
Python
142 lines
6.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Verify application JWT key isolation using real Kubernetes and Vault identities.
|
|
|
|
Creates short-lived ServiceAccount tokens and revokes every test Vault token.
|
|
Never prints credentials, secret values, or JWTs. Requires kubectl and the Vault
|
|
CLI in the selected Vault pod; it does not apply or modify application manifests.
|
|
"""
|
|
import argparse
|
|
import concurrent.futures
|
|
import json
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--kubeconfig", required=True)
|
|
parser.add_argument("--context")
|
|
parser.add_argument("--vault-namespace", default="vault")
|
|
parser.add_argument("--vault-pod", default="vault-vault-contour-0")
|
|
parser.add_argument("--vault-container", default="vault")
|
|
parser.add_argument("--backend-role", default="django-backend")
|
|
parser.add_argument("--backend-namespace", default="django")
|
|
parser.add_argument("--backend-service-account", default="django-backend-vault")
|
|
parser.add_argument("--celery-role", default="django-celery")
|
|
parser.add_argument("--output", type=Path)
|
|
args = parser.parse_args()
|
|
kube = ["kubectl", "--kubeconfig", args.kubeconfig, "--request-timeout=30s"]
|
|
if args.context:
|
|
kube += ["--context", args.context]
|
|
vault = kube + ["-n", args.vault_namespace, "exec", "-i", args.vault_pod,
|
|
"-c", args.vault_container, "--", "sh", "-ec"]
|
|
|
|
def execute(command, payload=None):
|
|
return subprocess.run(command, input=payload, capture_output=True, text=True, timeout=90)
|
|
|
|
def login(jwt, role):
|
|
result = execute(vault + [
|
|
"export VAULT_ADDR=http://127.0.0.1:8200; "
|
|
"exec vault write -format=json auth/kubernetes/login -"
|
|
], json.dumps({"role": role, "jwt": jwt}))
|
|
if result.returncode:
|
|
return None, 403 if "Code: 403" in result.stderr else "error"
|
|
return json.loads(result.stdout)["auth"]["client_token"], 200
|
|
|
|
def authorized(token, command):
|
|
return execute(vault + [
|
|
"IFS= read -r VAULT_TOKEN; export VAULT_TOKEN; "
|
|
"export VAULT_ADDR=http://127.0.0.1:8200; " + command
|
|
], token + "\n")
|
|
|
|
def read_status(token, command):
|
|
result = authorized(token, command)
|
|
return 200 if result.returncode == 0 else 403 if "Code: 403" in result.stderr else "error"
|
|
|
|
def check(identity):
|
|
namespace, account, role = identity
|
|
row = {"namespace": namespace, "service_account": account, "role": role}
|
|
token = None
|
|
try:
|
|
result = execute(kube + ["-n", namespace, "create", "token", account, "--duration=10m"])
|
|
if result.returncode:
|
|
row["error"] = "TokenRequest failed"
|
|
return row
|
|
service_jwt = result.stdout.strip()
|
|
token, row["login"] = login(service_jwt, role)
|
|
if not token:
|
|
return row
|
|
paths = {
|
|
"public": "vault/common/jwt_public",
|
|
"private": "vault/apps/django/jwt_private",
|
|
"legacy": "vault/common/rsa_keys",
|
|
"signer_client": "vault/apps/django/jwt_signer_client",
|
|
}
|
|
for label, path in paths.items():
|
|
row[label] = read_status(token, "exec vault read -format=json secrets/data/" + path)
|
|
row["legacy_version_1"] = read_status(
|
|
token, "exec vault kv get -mount=secrets -version=1 -format=json vault/common/rsa_keys")
|
|
expected_backend = (namespace, account, role) == (
|
|
args.backend_namespace, args.backend_service_account, args.backend_role)
|
|
if not expected_backend:
|
|
other, row["backend_role_impersonation"] = login(service_jwt, args.backend_role)
|
|
if other:
|
|
authorized(other, "exec vault token revoke -self")
|
|
except Exception as error:
|
|
# Exception messages can include credentials or server responses.
|
|
row["error"] = type(error).__name__
|
|
finally:
|
|
if token:
|
|
authorized(token, "exec vault token revoke -self")
|
|
return row
|
|
|
|
result = execute(kube + ["get", "deployments", "-A", "-o", "json"])
|
|
if result.returncode:
|
|
raise SystemExit("Cannot list deployments in the selected cluster")
|
|
identities = set()
|
|
public_identities = set()
|
|
for deployment in json.loads(result.stdout)["items"]:
|
|
template = deployment["spec"]["template"]
|
|
role = template["metadata"].get("annotations", {}).get("vault.hashicorp.com/role")
|
|
if role:
|
|
identity = (deployment["metadata"]["namespace"],
|
|
template["spec"].get("serviceAccountName", "default"), role)
|
|
identities.add(identity)
|
|
if any("vault/common/jwt_public" in str(value) for key, value in
|
|
template["metadata"].get("annotations", {}).items()
|
|
if "agent-inject-secret" in key):
|
|
public_identities.add(identity)
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
|
|
rows = list(executor.map(check, sorted(identities)))
|
|
failures = []
|
|
for row in rows:
|
|
backend = (row["namespace"], row["service_account"], row["role"]) == (
|
|
args.backend_namespace, args.backend_service_account, args.backend_role)
|
|
signer = row["namespace"] == args.backend_namespace and row["role"] in (
|
|
args.backend_role, args.celery_role)
|
|
passed = (
|
|
not row.get("error") and row.get("login") == 200
|
|
and (row.get("public") == 200 if (row["namespace"], row["service_account"], row["role"])
|
|
in public_identities else row.get("public") in (200, 403))
|
|
and row.get("private") == (200 if backend else 403)
|
|
and row.get("signer_client") == (200 if signer else 403)
|
|
and row.get("legacy") == 403 and row.get("legacy_version_1") == 403
|
|
and (backend or row.get("backend_role_impersonation") == 403)
|
|
)
|
|
if not passed:
|
|
failures.append(row)
|
|
backend_found = any((r["namespace"], r["service_account"], r["role"]) == (
|
|
args.backend_namespace, args.backend_service_account, args.backend_role) for r in rows)
|
|
report = {"service_accounts": len(rows), "backend_found": backend_found,
|
|
"unexpected_results": len(failures), "results": rows}
|
|
content = json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
|
if args.output:
|
|
args.output.write_text(content)
|
|
else:
|
|
print(content)
|
|
raise SystemExit(0 if rows and backend_found and not failures else 1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|