forked from mtusi2026/mtusi2026lab7
Every service of the stand gets the x-hardening anchor (cap_drop ALL, no-new-privileges, read-only root) with an empty exception table, tmpfs with size limits, pids limits by measurement and non-root users for PostgreSQL, Valkey, RabbitMQ and SeaweedFS. The S3 gateway gRPC accepts only mTLS with the stand CA. make hardening_check checks inspect data, processes and listeners against the compose model; a fast test keeps the override files from removing restrictions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
327 lines
13 KiB
Python
327 lines
13 KiB
Python
"""Ограничения контейнеров в compose и override стендов (change
|
||
`container-hardening`, design, решения 2–5, 7, 11; спек `container-security`,
|
||
«Одинаковые ограничения на всех стендах проекта», сценарий «Override не
|
||
снимает ограничения»).
|
||
|
||
Без docker: файлы читает PyYAML (якорь `<<: *hardening` раскрывает
|
||
SafeLoader, теги `!override` / `!reset` — свой конструктор). Тест сверяет:
|
||
|
||
- у каждого сервиса `docker-compose.yml` — сброс всех capabilities,
|
||
`no-new-privileges`, корень только на чтение (или строка
|
||
`x-hardening-exceptions` с причиной), лимиты `cpus`, `memory`, `pids`,
|
||
tmpfs только ключом `tmpfs:` с `size=` и `mode=`; нет `privileged`,
|
||
`cap_add` (кроме строки исключений; `SYS_ADMIN`, `NET_ADMIN`, `SYS_PTRACE`,
|
||
`SYS_MODULE` — никогда), `network_mode: host`, `pid` / `ipc: host`,
|
||
`devices`, `seccomp=unconfined`, bind сокета Docker, bind на запись и
|
||
порта не на `127.0.0.1`; опубликованные порты — ровно список (ingress,
|
||
Grafana, OpenBao, TLS-порты хранилищ и брокера, по одному);
|
||
- строка исключений — сервис модели, ключ `read_only` или `cap_add`,
|
||
непустая причина; процессов приложения и bootstrap в таблице основного
|
||
файла нет;
|
||
- override стенда отказов, `bench/` и CI не трогают сброс capabilities,
|
||
`no-new-privileges`, пользователя, tmpfs и пределы (`deploy` без
|
||
`!override` / `!reset`, `pids` не обнуляется), привилегий и пространств
|
||
хоста не добавляют, порты — только сброс или `127.0.0.1`; `read_only`
|
||
меняет только override CI, только на `false`, только у сервисов с
|
||
`configs` / `secrets` из окружения и со строкой исключений своего файла.
|
||
|
||
Контроли — на изменённой копии текста: сервис без якоря, без `pids`, строка
|
||
исключений без причины, `read_only: false` в override стенда отказов.
|
||
"""
|
||
|
||
import re
|
||
from dataclasses import dataclass
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
import yaml
|
||
|
||
from src.config.settings import BASE_DIR
|
||
|
||
COMPOSE = BASE_DIR / "docker-compose.yml"
|
||
FAILURES = BASE_DIR / "student-tests" / "failures.compose.yml"
|
||
BENCH = BASE_DIR / "bench" / "bench.compose.yml"
|
||
CI = BASE_DIR / ".github" / "ci" / "compose.yml"
|
||
EXCEPTIONS = "x-hardening-exceptions"
|
||
EXCEPTION_KEYS = ("read_only", "cap_add")
|
||
FORBIDDEN_CAPS = ("SYS_ADMIN", "NET_ADMIN", "SYS_PTRACE", "SYS_MODULE")
|
||
# процессы приложения и bootstrap — без исключений корня в основном файле
|
||
NO_EXCEPTIONS = (
|
||
"api",
|
||
"worker",
|
||
"relay",
|
||
"cleaner",
|
||
"migrate",
|
||
"postgres-bootstrap",
|
||
"s3-bootstrap",
|
||
)
|
||
# опубликованные на хосте порты (capability container-run): по одному
|
||
PUBLISHED = (
|
||
"haproxy",
|
||
"grafana",
|
||
"openbao",
|
||
"postgres",
|
||
"valkey",
|
||
"s3",
|
||
"rabbitmq",
|
||
)
|
||
# ключи ограничений, которые override стендов не трогают
|
||
GUARDED = (
|
||
"cap_drop",
|
||
"cap_add",
|
||
"security_opt",
|
||
"user",
|
||
"tmpfs",
|
||
"privileged",
|
||
"pid",
|
||
"ipc",
|
||
"devices",
|
||
"userns_mode",
|
||
)
|
||
SIZE_RE = re.compile(r"(^|,)size=\d+[kmg]?(,|$)")
|
||
MODE_RE = re.compile(r"(^|,)mode=[0-7]{3,4}(,|$)")
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class Tagged:
|
||
"""Значение с тегом слияния Compose (`!override`, `!reset`)."""
|
||
|
||
tag: str
|
||
value: Any
|
||
|
||
|
||
class ComposeLoader(yaml.SafeLoader):
|
||
"""SafeLoader с тегами слияния Compose ≥ 2.24."""
|
||
|
||
|
||
def _tagged(loader: ComposeLoader, node: yaml.Node) -> Tagged:
|
||
if isinstance(node, yaml.MappingNode):
|
||
value: Any = loader.construct_mapping(node, deep=True)
|
||
elif isinstance(node, yaml.SequenceNode):
|
||
value = loader.construct_sequence(node, deep=True)
|
||
else:
|
||
value = loader.construct_scalar(node)
|
||
return Tagged(node.tag, value)
|
||
|
||
|
||
for _tag in ("!override", "!reset"):
|
||
ComposeLoader.add_constructor(_tag, _tagged)
|
||
|
||
|
||
def load(text: str) -> dict[str, Any]:
|
||
return yaml.load(text, Loader=ComposeLoader) # noqa: S506 — SafeLoader
|
||
|
||
|
||
def plain(value: Any) -> Any:
|
||
return value.value if isinstance(value, Tagged) else value
|
||
|
||
|
||
def read(path: Path) -> str:
|
||
return path.read_text(encoding="utf-8")
|
||
|
||
|
||
def limits(service: dict) -> dict:
|
||
return (
|
||
plain((plain(service.get("deploy") or {}).get("resources")) or {}).get(
|
||
"limits",
|
||
)
|
||
or {}
|
||
)
|
||
|
||
|
||
def exception_problems(
|
||
data: dict,
|
||
services: dict,
|
||
*,
|
||
main: bool,
|
||
) -> list[str]:
|
||
"""Строки таблицы исключений: сервис, ключ, причина."""
|
||
problems = []
|
||
table = data.get(EXCEPTIONS)
|
||
if table is None:
|
||
return [f"no top-level {EXCEPTIONS}"] if main else []
|
||
for name, keys in (table or {}).items():
|
||
if name not in services:
|
||
problems.append(f"exception {name}: no such service")
|
||
for key, reason in (keys or {}).items():
|
||
if key not in EXCEPTION_KEYS:
|
||
problems.append(f"exception {name}.{key}: unknown key")
|
||
if not str(reason or "").strip():
|
||
problems.append(f"exception {name}.{key}: no reason")
|
||
if main and name in NO_EXCEPTIONS:
|
||
problems.append(f"exception {name}.{key}: application")
|
||
return problems
|
||
|
||
|
||
def main_problems(text: str) -> list[str]:
|
||
"""Инварианты основного файла."""
|
||
data = load(text)
|
||
services = data.get("services") or {}
|
||
problems = exception_problems(data, services, main=True)
|
||
table = data.get(EXCEPTIONS) or {}
|
||
published: dict[str, int] = {}
|
||
for name, service in services.items():
|
||
allowed = table.get(name) or {}
|
||
if service.get("cap_drop") != ["ALL"]:
|
||
problems.append(f"{name}: cap_drop is not [ALL]")
|
||
caps = [str(c).upper() for c in service.get("cap_add") or []]
|
||
if caps and "cap_add" not in allowed:
|
||
problems.append(f"{name}: cap_add without exception")
|
||
for cap in caps:
|
||
if cap.removeprefix("CAP_") in FORBIDDEN_CAPS:
|
||
problems.append(f"{name}: forbidden capability {cap}")
|
||
opts = [str(o) for o in service.get("security_opt") or []]
|
||
if "no-new-privileges:true" not in opts:
|
||
problems.append(f"{name}: no no-new-privileges")
|
||
if any("unconfined" in o for o in opts):
|
||
problems.append(f"{name}: unconfined security option")
|
||
if service.get("read_only") is not True and "read_only" not in allowed:
|
||
problems.append(f"{name}: root is writable without exception")
|
||
if service.get("privileged"):
|
||
problems.append(f"{name}: privileged")
|
||
if service.get("network_mode") == "host":
|
||
problems.append(f"{name}: host network")
|
||
for key in ("pid", "ipc", "uts", "userns_mode"):
|
||
if service.get(key) == "host":
|
||
problems.append(f"{name}: {key} host")
|
||
if service.get("devices"):
|
||
problems.append(f"{name}: devices")
|
||
lim = limits(service)
|
||
for key in ("cpus", "memory"):
|
||
if not lim.get(key):
|
||
problems.append(f"{name}: no {key} limit")
|
||
if not isinstance(lim.get("pids"), int) or lim["pids"] <= 0:
|
||
problems.append(f"{name}: no pids limit")
|
||
for item in service.get("tmpfs") or []:
|
||
options = str(item).partition(":")[2]
|
||
if not SIZE_RE.search(options) or not MODE_RE.search(options):
|
||
problems.append(f"{name}: tmpfs {item} without size= / mode=")
|
||
if re.search(r"(^|,)(suid|dev|exec)(,|$)", options):
|
||
problems.append(f"{name}: tmpfs {item} allows suid/dev/exec")
|
||
for volume in service.get("volumes") or []:
|
||
if isinstance(volume, dict):
|
||
kind = volume.get("type")
|
||
source = str(volume.get("source") or "")
|
||
if kind == "tmpfs":
|
||
problems.append(f"{name}: tmpfs in volumes")
|
||
if kind == "bind" and not volume.get("read_only"):
|
||
problems.append(f"{name}: writable bind {source}")
|
||
else:
|
||
source = str(volume).split(":", 1)[0]
|
||
if "docker.sock" in source:
|
||
problems.append(f"{name}: docker socket")
|
||
for port in service.get("ports") or []:
|
||
if not str(port).startswith("127.0.0.1:"):
|
||
problems.append(f"{name}: port {port} not on 127.0.0.1")
|
||
published[name] = published.get(name, 0) + 1
|
||
if published != dict.fromkeys(PUBLISHED, 1):
|
||
problems.append(f"published ports {sorted(published.items())}")
|
||
return problems
|
||
|
||
|
||
def override_problems(text: str, main_text: str, *, ci: bool) -> list[str]:
|
||
"""Override стенда не снимает ограничений основного файла."""
|
||
data = load(text)
|
||
services = data.get("services") or {}
|
||
main_services = load(main_text).get("services") or {}
|
||
problems = exception_problems(data, main_services, main=False)
|
||
table = data.get(EXCEPTIONS) or {}
|
||
for name, service in services.items():
|
||
for key in GUARDED:
|
||
if key in service:
|
||
problems.append(f"{name}: override sets {key}")
|
||
net = service.get("network_mode")
|
||
if net is not None and net != main_services.get(name, {}).get(
|
||
"network_mode",
|
||
):
|
||
problems.append(f"{name}: override sets network_mode {net}")
|
||
if "read_only" in service:
|
||
delivers = bool(service.get("configs") or service.get("secrets"))
|
||
reason = str((table.get(name) or {}).get("read_only") or "")
|
||
if not ci:
|
||
problems.append(f"{name}: read_only outside CI")
|
||
elif service["read_only"] is not False or not delivers:
|
||
problems.append(f"{name}: read_only without files from env")
|
||
elif not reason.strip():
|
||
problems.append(f"{name}: read_only without exception")
|
||
deploy = service.get("deploy")
|
||
if deploy is not None:
|
||
resources = plain(deploy).get("resources")
|
||
for part in (
|
||
deploy,
|
||
resources,
|
||
(plain(resources) or {}).get("limits"),
|
||
):
|
||
if isinstance(part, Tagged):
|
||
problems.append(f"{name}: deploy {part.tag}")
|
||
if "pids" in limits(service) and not limits(service)["pids"]:
|
||
problems.append(f"{name}: pids limit removed")
|
||
ports = service.get("ports")
|
||
if ports is not None and not (
|
||
isinstance(ports, Tagged) and ports.tag == "!reset"
|
||
):
|
||
for port in plain(ports) or []:
|
||
if not str(port).startswith("127.0.0.1:"):
|
||
problems.append(f"{name}: port {port} not on 127.0.0.1")
|
||
return problems
|
||
|
||
|
||
def test_main_file_hardening() -> None:
|
||
assert main_problems(read(COMPOSE)) == []
|
||
|
||
|
||
def test_main_exceptions_table_empty() -> None:
|
||
"""Цель design (решение 2): якорь совместим со всеми сервисами рабочего
|
||
стенда — таблица исключений основного файла пуста."""
|
||
assert load(read(COMPOSE))[EXCEPTIONS] == {}
|
||
|
||
|
||
def test_failures_override_keeps_hardening() -> None:
|
||
assert override_problems(read(FAILURES), read(COMPOSE), ci=False) == []
|
||
|
||
|
||
def test_bench_override_keeps_hardening() -> None:
|
||
assert override_problems(read(BENCH), read(COMPOSE), ci=False) == []
|
||
|
||
|
||
def test_ci_override_only_read_only() -> None:
|
||
assert override_problems(read(CI), read(COMPOSE), ci=True) == []
|
||
|
||
|
||
def test_control_service_without_anchor() -> None:
|
||
text = read(COMPOSE)
|
||
block = " relay:\n <<: *hardening\n"
|
||
assert block in text
|
||
problems = main_problems(text.replace(block, " relay:\n", 1))
|
||
assert "relay: cap_drop is not [ALL]" in problems
|
||
assert "relay: no no-new-privileges" in problems
|
||
assert "relay: root is writable without exception" in problems
|
||
|
||
|
||
def test_control_service_without_pids() -> None:
|
||
text = read(COMPOSE)
|
||
line = " pids: 512\n"
|
||
assert line in text
|
||
problems = main_problems(text.replace(line, "", 1))
|
||
assert "postgres: no pids limit" in problems
|
||
|
||
|
||
def test_control_exception_without_reason() -> None:
|
||
text = read(COMPOSE).replace(
|
||
"x-hardening-exceptions: {}",
|
||
"x-hardening-exceptions:\n grafana:\n read_only: ''",
|
||
1,
|
||
)
|
||
problems = main_problems(text)
|
||
assert "exception grafana.read_only: no reason" in problems
|
||
|
||
|
||
def test_control_read_only_in_failures_override() -> None:
|
||
text = read(FAILURES).replace(
|
||
" valkey:\n",
|
||
" valkey:\n read_only: false\n",
|
||
1,
|
||
)
|
||
problems = override_problems(text, read(COMPOSE), ci=False)
|
||
assert "valkey: read_only outside CI" in problems
|