feat(containers): lab7 restrict application privileges and worker resources
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
"""Проверить ограничения запущенных контейнеров без вывода переменных окружения."""
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.check_output(["docker", *args], cwd=ROOT, text=True).strip()
|
||||
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise SystemExit(message)
|
||||
|
||||
|
||||
ids = docker("compose", "ps", "-aq").split()
|
||||
require(ids, "Проект не запущен.")
|
||||
seen = set()
|
||||
for c in json.loads(docker("inspect", *ids)):
|
||||
name = c["Name"]
|
||||
role = c["Config"]["Labels"]["com.docker.compose.service"]
|
||||
host = c["HostConfig"]
|
||||
require(not host["Privileged"] and host["NetworkMode"] != "host", name + ": избыточные права")
|
||||
require(not any("docker.sock" in (m["Source"] + m["Destination"]) for m in c["Mounts"]), name + ": Docker socket")
|
||||
if role not in {"api", "worker", "reconciler", "migrate"}:
|
||||
continue
|
||||
seen.add(role)
|
||||
require(host["ReadonlyRootfs"] and "ALL" in (host["CapDrop"] or []), name + ": rootfs/capabilities")
|
||||
require(any(x in ("no-new-privileges", "no-new-privileges:true") for x in host["SecurityOpt"] or []), name + ": no-new-privileges")
|
||||
require("/tmp" in host["Tmpfs"], name + ": tmpfs /tmp")
|
||||
if role == "migrate":
|
||||
require(not c["State"]["Running"] and c["State"]["ExitCode"] == 0, name + ": миграции")
|
||||
else:
|
||||
require("/run/bao" in host["Tmpfs"], name + ": tmpfs секретов")
|
||||
require(docker("exec", c["Id"], "id", "-u") != "0", name + ": UID 0")
|
||||
if role == "worker":
|
||||
require(host["NanoCpus"] > 0 and host["Memory"] > 0, name + ": нет лимита CPU/RAM")
|
||||
print(f"Worker: {host['NanoCpus']/1e9:g} CPU, {host['Memory']//(1024**2)} МиБ")
|
||||
print("PASS", name)
|
||||
require(seen == {"api", "worker", "reconciler", "migrate"}, "Отсутствует контейнер приложения.")
|
||||
Reference in New Issue
Block a user