Files
mtusi2026lab7/scripts/security_inventory.py

57 lines
1.9 KiB
Python

import json
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def command(*args):
return subprocess.run(args, capture_output=True, text=True, check=True).stdout
def inventory():
identifiers = command("docker", "compose", "ps", "-q").split()
containers = json.loads(command("docker", "inspect", *identifiers))
rows = []
for item in containers:
config, host = item["Config"], item["HostConfig"]
service = config["Labels"]["com.docker.compose.service"]
mounts = item["Mounts"]
base = (
not host["Privileged"]
and host["NetworkMode"] != "host"
and not any("docker.sock" in mount["Source"] for mount in mounts)
)
app = service in ["api", "relay", "worker"]
restricted = not app or (
config["User"] == "10001:10001"
and host["ReadonlyRootfs"]
and "ALL" in host["CapDrop"]
and "no-new-privileges:true" in host["SecurityOpt"]
and host["Memory"] > 0
and host["NanoCpus"] > 0
)
own_keys = not app or all(
"/secrets/pki/" + service in mount["Source"]
for mount in mounts
if "/secrets/" in mount["Source"]
)
rows.append(
{
"service": service,
"user": config["User"],
"readonly": host["ReadonlyRootfs"],
"memory_bytes": host["Memory"],
"cpu_quota": host["NanoCpus"] / 1e9,
"only_own_keys": own_keys,
"passed": base and restricted and own_keys,
}
)
return {"containers": rows, "passed": all(row["passed"] for row in rows)}
if __name__ == "__main__":
result = inventory()
print(json.dumps(result, indent=2))
raise SystemExit(0 if result["passed"] else 1)