399 lines
19 KiB
Python
399 lines
19 KiB
Python
"""Лаба 7: ограничения контейнеров (перенос container-hardening).
|
||
|
||
Без стенда: инварианты `compose.yaml` и override стендов. У каждого сервиса —
|
||
якорь `x-hardened` (cap_drop ALL, no-new-privileges, корень только на чтение);
|
||
отклонение — только строкой `x-hardening-exceptions` с причиной, процессам
|
||
приложения и bootstrap — никогда; лимиты CPU, памяти и `pids` (не меньше 64, у Go —
|
||
128); tmpfs — только ключом `tmpfs:` с `size=` и `mode=`; хранилища — от своего
|
||
пользователя; нет privileged, cap_add, пространств хоста, устройств, сокета
|
||
Docker, портов не на 127.0.0.1; опубликованные порты = таблица
|
||
`scripts/lab7.py` (HC_PUBLISHED); gRPC шлюза S3 — mTLS (`infra/s3/security.toml`),
|
||
CN — только имя разовой пробы `make s3-check`, которого нет среди identity стенда;
|
||
override временных стендов и bench/ ничего из этого не снимают. Проверки —
|
||
функции над корнем репозитория: их зовут на рабочем дереве и на копии с внесённой
|
||
ошибкой (контроль). Поведение на настоящих контейнерах — `make hardening-check`.
|
||
|
||
YAML разбирается построчно: PyYAML — не прямая зависимость проекта.
|
||
"""
|
||
|
||
import importlib.util
|
||
import re
|
||
import shutil
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
|
||
pytestmark = pytest.mark.unit
|
||
|
||
ROOT = Path(__file__).resolve().parents[2]
|
||
COMPOSE = "compose.yaml"
|
||
OVERRIDES = ("student-tests/stand.compose.yml", "bench/bench.compose.yml")
|
||
SECURITY = "infra/s3/security.toml"
|
||
IDENTITIES = "infra/pki/identities.conf"
|
||
LAB7 = "scripts/lab7.py"
|
||
ANCHOR = "hardened"
|
||
# хранилища — сразу от пользователя образа (uid:gid), без шагов от root
|
||
STORAGE_USERS = {
|
||
"postgres": "999:999",
|
||
"valkey": "999:999",
|
||
"rabbitmq": "100:101",
|
||
"s3": "1000:1000",
|
||
}
|
||
# процессы приложения и bootstrap: исключений из якоря нет никогда
|
||
NO_EXCEPTIONS = (
|
||
"api", "worker", "relay", "cleaner", "migrate", "postgres-bootstrap",
|
||
"s3-bootstrap",
|
||
) # fmt: skip
|
||
EXCEPTION_KEYS = ("read_only", "cap_add")
|
||
# рантайм Go: GOMAXPROCS потоков и потоки в системных вызовах, отказ создать поток
|
||
# — фатальная ошибка процесса; нижняя граница pids — 128
|
||
GO_SERVICES = (
|
||
"s3", "s3-bootstrap", "openbao", "otel-collector", "prometheus", "loki",
|
||
"tempo", "grafana",
|
||
) # fmt: skip
|
||
# ключи, которые override стенда трогать не может (снимут ограничения)
|
||
OVERRIDE_FORBIDDEN = (
|
||
"read_only", "cap_add", "cap_drop", "security_opt", "privileged", "user",
|
||
"network_mode", "pid", "ipc", "devices", "pids",
|
||
) # fmt: skip
|
||
|
||
|
||
def _read(root: Path, rel: str) -> str:
|
||
"""Файл без строк-комментариев."""
|
||
lines = (root / rel).read_text(encoding="utf-8").splitlines()
|
||
return "\n".join(line for line in lines if not line.lstrip().startswith("#")) + "\n"
|
||
|
||
|
||
def _blocks(text: str, indent: int) -> dict[str, str]:
|
||
"""Ключи YAML с отступом `indent` → их тела (до следующего ключа того же
|
||
уровня или меньше)."""
|
||
pad = " " * indent
|
||
out: dict[str, str] = {}
|
||
pattern = rf"^{pad}([A-Za-z0-9_.-]+):(.*)\n((?:(?:{pad} .*)?\n)*)"
|
||
for match in re.finditer(pattern, text, re.M):
|
||
out[match.group(1)] = match.group(2) + "\n" + match.group(3)
|
||
return out
|
||
|
||
|
||
def _services(root: Path, rel: str) -> dict[str, str]:
|
||
section = re.search(r"^services:\n((?:(?: .*)?\n)*)", _read(root, rel), re.M)
|
||
return _blocks(section.group(1), 2) if section else {}
|
||
|
||
|
||
def _anchors(text: str) -> dict[str, str]:
|
||
"""Якорь → тело верхнеуровневого `x-…: &якорь`."""
|
||
out = {}
|
||
for match in re.finditer(r"^x-[a-z-]+: &([a-z-]+)\n((?:(?: .*)?\n)*)", text, re.M):
|
||
out[match.group(1)] = match.group(2)
|
||
return out
|
||
|
||
|
||
def _merged(block: str, anchors: dict[str, str]) -> tuple[list[str], str]:
|
||
"""Якоря из `<<:` сервиса и его текст вместе с их телами."""
|
||
match = re.search(r"^ <<: (\[.*\]|\*\S+)", block, re.M)
|
||
names = re.findall(r"\*([a-z-]+)", match.group(1)) if match else []
|
||
return names, block + "".join(anchors.get(name, "") for name in names)
|
||
|
||
|
||
def _items(block: str, key: str) -> list[str]:
|
||
"""Элементы списка `key:` сервиса (` key:` и ` - …`)."""
|
||
match = re.search(rf"^ {key}:(.*)\n((?: - .*\n)*)", block, re.M)
|
||
if not match:
|
||
return []
|
||
return [line.strip()[2:].strip("\"'") for line in match.group(2).splitlines()]
|
||
|
||
|
||
def _exceptions(text: str) -> dict[str, dict[str, str]]:
|
||
match = re.search(r"^x-hardening-exceptions:(.*)\n((?:(?: .*)?\n)*)", text, re.M)
|
||
if not match:
|
||
return {}
|
||
out: dict[str, dict[str, str]] = {}
|
||
for service, body in _blocks(match.group(2), 2).items():
|
||
out[service] = {
|
||
key: value.strip().strip("\"'")
|
||
for key, value in re.findall(r"^ ([a-z_]+):(.*)$", body, re.M)
|
||
}
|
||
return out
|
||
|
||
|
||
def _lab7():
|
||
spec = importlib.util.spec_from_file_location("lab7", ROOT / LAB7)
|
||
assert spec is not None
|
||
assert spec.loader is not None
|
||
module = importlib.util.module_from_spec(spec)
|
||
spec.loader.exec_module(module)
|
||
return module
|
||
|
||
|
||
def anchor_problems(root: Path) -> list[str]:
|
||
text = _read(root, COMPOSE)
|
||
body = _anchors(text).get(ANCHOR, "")
|
||
problems = []
|
||
for needed in (
|
||
" read_only: true\n",
|
||
" cap_drop:\n - ALL\n",
|
||
" security_opt:\n - no-new-privileges:true\n",
|
||
):
|
||
if needed not in body:
|
||
problems.append(f"{COMPOSE}: x-{ANCHOR} without {needed.strip()!r}")
|
||
if not re.search(r"^x-hardening-exceptions:", text, re.M):
|
||
problems.append(f"{COMPOSE}: no x-hardening-exceptions table")
|
||
for service, keys in _exceptions(text).items():
|
||
if service in NO_EXCEPTIONS:
|
||
problems.append(f"{COMPOSE}: exception for {service}")
|
||
for key, reason in keys.items():
|
||
if key not in EXCEPTION_KEYS or not reason:
|
||
problems.append(f"{COMPOSE}: exception {service}.{key} {reason!r}")
|
||
return problems
|
||
|
||
|
||
def service_problems(root: Path) -> list[str]:
|
||
"""Каждый сервис: якорь, ничего, что его снимает, лимиты, tmpfs, порты."""
|
||
text = _read(root, COMPOSE)
|
||
anchors = _anchors(text)
|
||
exceptions = _exceptions(text)
|
||
problems = []
|
||
for service, block in _services(root, COMPOSE).items():
|
||
where = f"{COMPOSE}: {service}"
|
||
names, merged = _merged(block, anchors)
|
||
if ANCHOR not in names:
|
||
problems.append(f"{where} without <<: *{ANCHOR}")
|
||
allowed = exceptions.get(service, {})
|
||
for key in ("cap_drop", "security_opt", "privileged", "devices"):
|
||
if re.search(rf"^ {key}:", block, re.M):
|
||
problems.append(f"{where} sets {key} itself")
|
||
if re.search(r"^ cap_add:", block, re.M) and "cap_add" not in allowed:
|
||
problems.append(f"{where} adds capabilities")
|
||
if re.search(r"^ read_only:", block, re.M) and "read_only" not in allowed:
|
||
problems.append(f"{where} sets read_only itself")
|
||
for key in ("network_mode", "pid", "ipc"):
|
||
if re.search(rf"^ {key}: \"?host", block, re.M):
|
||
problems.append(f"{where} {key}: host")
|
||
if "docker.sock" in block:
|
||
problems.append(f"{where} mounts the Docker socket")
|
||
if re.search(r"^ volumes:\n(?: .*\n)* - type: tmpfs", block, re.M):
|
||
problems.append(f"{where} tmpfs in volumes (override would drop it)")
|
||
user = re.search(r"^ user: \"?([^\"\n]+)", block, re.M)
|
||
if user and user.group(1).split(":")[0] in ("0", "root"):
|
||
problems.append(f"{where} runs as root")
|
||
if service in STORAGE_USERS and (
|
||
not user or user.group(1) != STORAGE_USERS[service]
|
||
):
|
||
problems.append(f"{where} user is not {STORAGE_USERS[service]}")
|
||
for key in ("cpus", "memory", "pids"):
|
||
if not re.search(rf"^ +{key}: ", merged, re.M):
|
||
problems.append(f"{where} without limit {key}")
|
||
pids = re.search(r"^ +pids: (\d+)", merged, re.M)
|
||
floor = 128 if service in GO_SERVICES else 64
|
||
if pids and int(pids.group(1)) < floor:
|
||
problems.append(f"{where} pids {pids.group(1)} < {floor}")
|
||
tmpfs = re.search(r"^ tmpfs:(.*)\n((?: - .*\n)*)", block, re.M)
|
||
if tmpfs and tmpfs.group(1).strip():
|
||
problems.append(f"{where} tmpfs is not a list")
|
||
for item in _items(block, "tmpfs"):
|
||
options = item.split(":", 1)[1].split(",") if ":" in item else []
|
||
keys = {option.split("=", 1)[0] for option in options}
|
||
if not {"size", "mode"} <= keys:
|
||
problems.append(f"{where} tmpfs {item} without size= and mode=")
|
||
for port in _items(block, "ports"):
|
||
if not port.startswith("127.0.0.1:"):
|
||
problems.append(f"{where} port {port} not on 127.0.0.1")
|
||
return problems
|
||
|
||
|
||
def published_problems(root: Path) -> list[str]:
|
||
"""Опубликованные порты = таблица HC_PUBLISHED проверки (сервис → порт
|
||
контейнера)."""
|
||
got = {}
|
||
for service, block in _services(root, COMPOSE).items():
|
||
for port in _items(block, "ports"):
|
||
got[service] = int(port.rsplit(":", 1)[1])
|
||
want = _lab7().HC_PUBLISHED
|
||
if got != want:
|
||
return [f"{COMPOSE}: published ports {got} != {LAB7} HC_PUBLISHED {want}"]
|
||
return []
|
||
|
||
|
||
def storage_problems(root: Path) -> list[str]:
|
||
"""Хранилища без шагов от root: healthcheck брокера без su-exec, Grafana —
|
||
журнал только в stdout, gRPC шлюза S3 — mTLS из security.toml."""
|
||
services = _services(root, COMPOSE)
|
||
problems = []
|
||
for service, block in services.items():
|
||
if re.search(r"\b(su-exec|gosu|setpriv)\b", block):
|
||
problems.append(f"{COMPOSE}: {service} switches users in its commands")
|
||
if "GF_LOG_MODE: console" not in services.get("grafana", ""):
|
||
problems.append(f"{COMPOSE}: grafana writes its log to a file")
|
||
if f"source: ./{SECURITY}" not in services.get("s3", "") or (
|
||
"target: /etc/seaweedfs/security.toml" not in services.get("s3", "")
|
||
):
|
||
problems.append(f"{COMPOSE}: s3 does not mount {SECURITY}")
|
||
security = _read(root, SECURITY)
|
||
for needed in (
|
||
'[grpc]\nca = "/run/secrets/ca.crt"',
|
||
'[grpc.s3]\ncert = "/run/secrets/s3.crt"\nkey = "/run/secrets/s3.key"',
|
||
):
|
||
if needed not in security:
|
||
problems.append(f"{SECURITY}: no {needed.splitlines()[0]}")
|
||
if "[grpc.client]" in security:
|
||
problems.append(f"{SECURITY}: [grpc.client] breaks the filer (split leaf)")
|
||
# CRL порт не читает: допущено только имя разовой пробы s3-check, а не
|
||
# identity стенда (перенос 15); ключ — только в секции слушателя шлюза
|
||
section = security.split("[grpc.s3]", 1)[-1].split("\n[", 1)[0]
|
||
names = re.findall(r'^allowed_commonNames = "([^"]*)"$', section, re.M)
|
||
probe = re.search(r'^S3_GRPC_PROBE = "([^"]+)"$', _read(root, LAB7), re.M)
|
||
allowed = names[0].split(",") if len(names) == 1 else []
|
||
if security.count("allowed_commonNames") != len(names):
|
||
problems.append(f"{SECURITY}: allowed_commonNames outside [grpc.s3]")
|
||
if not probe or allowed != [probe.group(1)]:
|
||
problems.append(
|
||
f"{SECURITY}: [grpc.s3] allowed_commonNames {names} != the s3-check "
|
||
f"probe {probe.group(1) if probe else None}"
|
||
)
|
||
listed = {
|
||
line.split()[0] for line in _read(root, IDENTITIES).splitlines() if line.strip()
|
||
}
|
||
for name in sorted(set(allowed) & listed):
|
||
problems.append(f"{SECURITY}: stand identity {name} is allowed on gRPC")
|
||
return problems
|
||
|
||
|
||
def override_problems(root: Path) -> list[str]:
|
||
"""Override стендов не снимают ограничений: ни ключей якоря и пользователя,
|
||
ни tmpfs, ни pids, ни сокета Docker, ни bind на запись, ни портов не на
|
||
127.0.0.1."""
|
||
problems = []
|
||
for rel in OVERRIDES:
|
||
for service, block in _services(root, rel).items():
|
||
where = f"{rel}: {service}"
|
||
for key in OVERRIDE_FORBIDDEN:
|
||
if re.search(rf"^ +{key}:", block, re.M):
|
||
problems.append(f"{where} sets {key}")
|
||
if re.search(r"^ tmpfs: !(reset|override)", block, re.M):
|
||
problems.append(f"{where} resets tmpfs")
|
||
for item in _items(block, "tmpfs"):
|
||
if "size=" not in item or "mode=" not in item:
|
||
problems.append(f"{where} tmpfs {item} without size= and mode=")
|
||
if "docker.sock" in block:
|
||
problems.append(f"{where} mounts the Docker socket")
|
||
if re.search(r"^ +read_only: false", block, re.M) or re.search(
|
||
r"^ - \.?/?[^:\n]+:[^:\n]+:rw", block, re.M
|
||
):
|
||
problems.append(f"{where} bind mount for writing")
|
||
for port in _items(block, "ports"):
|
||
if not port.startswith("127.0.0.1:"):
|
||
problems.append(f"{where} port {port} not on 127.0.0.1")
|
||
return problems
|
||
|
||
|
||
CHECKS = (
|
||
anchor_problems,
|
||
service_problems,
|
||
published_problems,
|
||
storage_problems,
|
||
override_problems,
|
||
)
|
||
|
||
|
||
@pytest.mark.parametrize("check", CHECKS, ids=lambda check: check.__name__)
|
||
def test_configuration(check) -> None:
|
||
assert check(ROOT) == []
|
||
|
||
|
||
def test_every_service_is_parsed() -> None:
|
||
"""Разбор видит все сервисы compose: пропущенный сервис прошёл бы молча."""
|
||
names = set(_services(ROOT, COMPOSE))
|
||
for needed in ("postgres", "api", "worker", "haproxy", "grafana", "tempo"):
|
||
assert needed in names
|
||
section = _read(ROOT, COMPOSE).split("\nservices:\n", 1)[1].split("\nnetworks:")[0]
|
||
assert names == set(re.findall(r"^ ([a-z0-9-]+):$", section, re.M))
|
||
|
||
|
||
def test_check_tables_cover_the_stand() -> None:
|
||
"""Слушатели HC_LISTENERS — сервисы compose без network_mode (владельцы
|
||
сетевых пространств), кроме процессов без портов."""
|
||
lab7 = _lab7()
|
||
services = _services(ROOT, COMPOSE)
|
||
owners = {
|
||
name
|
||
for name, block in services.items()
|
||
if not re.search(r"^ network_mode:", block, re.M)
|
||
}
|
||
silent = {"relay", "worker", "cleaner", "migrate", "postgres-bootstrap"}
|
||
assert set(lab7.HC_LISTENERS) == owners - silent
|
||
assert set(lab7.HC_NO_EXCEPTIONS) == set(NO_EXCEPTIONS)
|
||
assert lab7.HC_LISTENERS["s3"] == (8333, 18333)
|
||
|
||
|
||
def test_s3_grpc_cases_name_the_allowlist() -> None:
|
||
"""`make s3-check`: leaf CA стенда с допущенным именем — ответ HTTP/2, с
|
||
любым другим — отказ; ни одно из двух имён — не identity стенда (перенос 15)."""
|
||
lab7 = _lab7()
|
||
listed = {
|
||
line.split()[0] for line in _read(ROOT, IDENTITIES).splitlines() if line.strip()
|
||
}
|
||
assert {lab7.S3_GRPC_PROBE, lab7.S3_GRPC_DENIED}.isdisjoint(listed)
|
||
assert lab7.S3_GRPC_PROBE != lab7.S3_GRPC_DENIED
|
||
outcomes = {material: want for _, material, want in lab7.S3_GRPC_CASES}
|
||
assert outcomes["probe"] == lab7.S3_GRPC_ANSWER
|
||
assert outcomes["denied"] == lab7.S3_GRPC_REFUSED
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("check", "rel", "old", "new"),
|
||
[
|
||
(anchor_problems, COMPOSE, " read_only: true\n cap_drop:",
|
||
" read_only: false\n cap_drop:"),
|
||
(anchor_problems, COMPOSE, "x-hardening-exceptions: {}",
|
||
"x-hardening-exceptions:\n worker:\n read_only: render"),
|
||
(service_problems, COMPOSE, " postgres:\n <<: *hardened\n",
|
||
" postgres:\n"),
|
||
(service_problems, COMPOSE, "volume tempodata\n <<: *hardened\n",
|
||
"volume tempodata\n <<: *hardened\n cap_add:\n - NET_RAW\n"),
|
||
(service_problems, COMPOSE, ' user: "999:999"\n entrypoint: ["sh", '
|
||
'"/opt/valkey', ' entrypoint: ["sh", "/opt/valkey'),
|
||
(service_problems, COMPOSE, " - /run/valkey:size=1m,uid=999,gid=999,"
|
||
"mode=0700", " - /run/valkey"),
|
||
(service_problems, COMPOSE, " memory: 384M\n pids: 128\n",
|
||
" memory: 384M\n"),
|
||
(service_problems, COMPOSE, '"127.0.0.1:${GRAFANA_HOST_PORT:-3180}:3000"',
|
||
'"${GRAFANA_HOST_PORT:-3180}:3000"'),
|
||
(service_problems, COMPOSE, " grafana:\n <<: *hardened\n",
|
||
" grafana:\n <<: *hardened\n pid: host\n"),
|
||
(published_problems, COMPOSE,
|
||
" - \"127.0.0.1:${BROKER_HOST_PORT:-5673}:5671\"\n", ""),
|
||
(storage_problems, COMPOSE, '["CMD", "rabbitmq-diagnostics"',
|
||
'["CMD", "su-exec", "rabbitmq", "rabbitmq-diagnostics"'),
|
||
(storage_problems, COMPOSE, "GF_LOG_MODE: console", "GF_LOG_MODE: file"),
|
||
(storage_problems, SECURITY, "\n[grpc.s3]\n", "\n[grpc.filer]\n"),
|
||
# перенос 15: пустой список, identity стенда, написание, которое
|
||
# SeaweedFS не видит, ключ вне секции слушателя шлюза
|
||
(storage_problems, SECURITY, 'allowed_commonNames = "s3-grpc-probe"',
|
||
'allowed_commonNames = ""'),
|
||
(storage_problems, SECURITY, 'allowed_commonNames = "s3-grpc-probe"',
|
||
'allowed_commonNames = "s3-grpc-probe,worker"'),
|
||
(storage_problems, SECURITY, 'allowed_commonNames = "s3-grpc-probe"',
|
||
'allowed_commonnames = "s3-grpc-probe"'),
|
||
(storage_problems, SECURITY, 'ca = "/run/secrets/ca.crt"\n',
|
||
'ca = "/run/secrets/ca.crt"\nallowed_commonNames = "s3-grpc-probe"\n'),
|
||
(override_problems, OVERRIDES[0], " openbao:\n restart: \"no\"\n",
|
||
" openbao:\n restart: \"no\"\n read_only: false\n"),
|
||
(override_problems, OVERRIDES[1], " container_name: vlad-bench-worker\n",
|
||
" container_name: vlad-bench-worker\n cap_add:\n - SYS_ADMIN\n"),
|
||
(override_problems, OVERRIDES[1], " container_name: vlad-bench-lb\n",
|
||
" container_name: vlad-bench-lb\n volumes:\n"
|
||
" - /var/run/docker.sock:/var/run/docker.sock\n"),
|
||
],
|
||
) # fmt: skip
|
||
def test_control_is_red(tmp_path: Path, check, rel: str, old: str, new: str) -> None:
|
||
for name in (COMPOSE, *OVERRIDES, SECURITY, IDENTITIES, LAB7):
|
||
target = tmp_path / name
|
||
target.parent.mkdir(parents=True, exist_ok=True)
|
||
shutil.copyfile(ROOT / name, target)
|
||
assert check(tmp_path) == []
|
||
text = (tmp_path / rel).read_text(encoding="utf-8")
|
||
assert old in text, (rel, old)
|
||
(tmp_path / rel).write_text(text.replace(old, new, 1), encoding="utf-8")
|
||
problems = check(tmp_path)
|
||
assert any(rel in problem for problem in problems), problems
|