mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-29 06:17:25 +00:00
Merge pull request #2095 from infinito-nexus/fix/sys-ctl-hlth-runtime/host-scan-nfs-timeout
fix(sys-ctl-hlth-runtime): skip network mounts in the host scan
This commit is contained in:
10 files changed
+573
-12
No files matched your search
@@ -21,6 +21,7 @@ DIR_CACHE: "/var/cache/infinito/core/cache"
|
||||
|
||||
DIR_VAR_LIB: "/var/lib/infinito"
|
||||
DIR_BACKUPS: "{{ [DIR_VAR_LIB, 'backup'] | path_join }}"
|
||||
DIR_BACKUPS_NODE: "{{ DIR_VAR_LIB ~ '-backup' }}"
|
||||
BACKUP_REPOSITORIES:
|
||||
- backup-docker-to-local
|
||||
- backup-nfs-to-local
|
||||
|
||||
@@ -124,14 +124,14 @@
|
||||
|
||||
- name: "✅ Ensure the node-local backup store exists"
|
||||
ansible.builtin.file:
|
||||
path: "{{ SVC_STORAGE_NFS_CLIENT_BACKUPS_DIR }}"
|
||||
path: "{{ DIR_BACKUPS_NODE }}"
|
||||
state: directory
|
||||
mode: "0755"
|
||||
|
||||
- name: "🔗 Keep {{ DIR_BACKUPS }} node-local over the shared state"
|
||||
ansible.posix.mount:
|
||||
path: "{{ DIR_BACKUPS }}"
|
||||
src: "{{ SVC_STORAGE_NFS_CLIENT_BACKUPS_DIR }}"
|
||||
src: "{{ DIR_BACKUPS_NODE }}"
|
||||
fstype: none
|
||||
opts: bind,_netdev
|
||||
state: mounted
|
||||
@@ -2,4 +2,3 @@
|
||||
application_id: "svc-storage-nfs-client"
|
||||
|
||||
SVC_STORAGE_NFS_CLIENT_PROBE_DIR: /run/svc-storage-nfs-client/probe
|
||||
SVC_STORAGE_NFS_CLIENT_BACKUPS_DIR: "{{ DIR_VAR_LIB ~ '-backup' }}"
|
||||
@@ -27,7 +27,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (
|
||||
|
||||
## Features
|
||||
|
||||
- **Targets:** `container` scans the image of every running container through the read-only Docker socket, `host` scans the host root filesystem mounted read-only. In swarm every node scans itself.
|
||||
- **Targets:** `container` scans the image of every running container through the read-only Docker socket, `host` scans the host root filesystem mounted read-only. In swarm every node scans itself. The host scan skips the paths in `HEALTH_RUNTIME_HOST_EXCLUDES` of [vars/main.yml](./vars/main.yml): kernel and temporary filesystems, the container engine's data root, removable media, the backups including the node-local store `DIR_BACKUPS_NODE`, and the NFS export base. It also skips every mount other than `/` whose type is one of the network or automount filesystem types listed in `NETWORK_FSTYPES` of [script.py](./files/python/script.py), read from `/proc/self/mountinfo`, so a slow or dead remote server cannot stall it, and prints one `ℹ️` line per skipped mount. The `autofs` type also covers local automounts, such as a systemd automount of `/boot` or `/efi`. Software on such a mount is not scanned: a host that mounts `/opt`, `/home`, `/usr/local` or `/var` from NFS, CIFS or sshfs loses the findings there, and a remote `/var` also hides the dpkg, pacman or rpm package database under `/var/lib`. On a swarm node with `storage.backend` `nfs`, `DIR_VAR_LIB` is such a mount and holds the cluster-shared volumes; a compose host keeps its volumes in the skipped Docker data root. Volume content is therefore scanned in neither compose nor swarm mode, and the container scan covers only the image. That leaves out software a service installs into a volume at runtime, such as Nextcloud apps, Odoo addons or agent packages, and the image content Docker copies into an empty named volume on its first mount, such as `hermes_data` at `/opt/data` of [web-app-hermes](../web-app-hermes/meta/volumes.yml): that copy stays at its first version after every image upgrade, and no image scan sees it.
|
||||
- **Engine runtime:** An engine run that reads the host Docker socket runs on `runc`, also on a swarm worker that [`svc-virt-kata`](../svc-virt-kata/README.md) defaults to gVisor or Kata, because those runtimes refuse the bind-mounted socket and every container scan would fail there. Every other engine run, the host scan included, keeps the node's default runtime.
|
||||
- **Engines:** Syft builds one SBOM per target, Grype and OSV-Scanner read it, Trivy reads the target itself. Without `syft` in `engines`, Grype and OSV-Scanner read the target directly; `osv` then scans containers only. While Grype runs, Trivy leaves the OS packages of every OS release listed under `trivy.unmatched_os` to Grype until the entry's `until`, because Trivy matches no Red Hat advisory for CentOS Stream 10 and Red Hat Enterprise Linux 10 yet and fails with `unable to find CPE indices`, see [aquasecurity/trivy-db#435](https://github.com/aquasecurity/trivy-db/issues/435) and [aquasecurity/trivy#7452](https://github.com/aquasecurity/trivy/issues/7452).
|
||||
- **Source-built runtimes:** A runtime compiled into the image, such as the PHP of the official `php` images, is matched by Grype only. With `syft` but without `grype` in `engines`, Grype still scans the binary-classified packages of every SBOM.
|
||||
|
||||
@@ -1330,8 +1330,22 @@ def scratch_of(engine: str, subject: str) -> str:
|
||||
return f"tmp-{engine}-{subject}"
|
||||
|
||||
|
||||
GLOB_SPECIAL = re.compile(r"([\\*?\[\]{}])")
|
||||
|
||||
|
||||
def glob_literal(path: str) -> str:
|
||||
"""
|
||||
Args:
|
||||
path: a path to hand to Trivy, Syft or Grype as a skip pattern.
|
||||
|
||||
Returns:
|
||||
The doublestar pattern that matches exactly ``path``.
|
||||
"""
|
||||
return GLOB_SPECIAL.sub(r"\\\1", path)
|
||||
|
||||
|
||||
def _relative_excludes(layout: Layout) -> list[str]:
|
||||
return [f"./{path.strip('/')}" for path in layout.excludes]
|
||||
return [f"./{glob_literal(path.strip('/'))}" for path in layout.excludes]
|
||||
|
||||
|
||||
def db_steps(engine: str, layout: Layout, image: str) -> list[Step]:
|
||||
@@ -1486,11 +1500,10 @@ def trivy_step(
|
||||
if not config.db_update:
|
||||
args += ["--cache-backend", "memory"]
|
||||
if target.kind == "host":
|
||||
args += [
|
||||
"--skip-dirs",
|
||||
",".join(f"{HOST_ROOT}{path}" for path in layout.excludes),
|
||||
HOST_ROOT,
|
||||
]
|
||||
for path in layout.excludes:
|
||||
quoted = glob_literal(f"{HOST_ROOT}{path}").replace('"', '""')
|
||||
args += ["--skip-dirs", f'"{quoted}"']
|
||||
args.append(HOST_ROOT)
|
||||
else:
|
||||
args += ["--image-src", "docker", target.ref]
|
||||
scratch = scratch_of("trivy", target.key)
|
||||
@@ -1970,6 +1983,73 @@ def docker_root() -> str:
|
||||
).stdout.strip()
|
||||
|
||||
|
||||
MOUNTINFO = Path("/proc/self/mountinfo")
|
||||
NETWORK_FSTYPES = frozenset(
|
||||
{
|
||||
"nfs",
|
||||
"nfs4",
|
||||
"cifs",
|
||||
"smb3",
|
||||
"smbfs",
|
||||
"ceph",
|
||||
"fuse.ceph-fuse",
|
||||
"glusterfs",
|
||||
"fuse.glusterfs",
|
||||
"fuse.sshfs",
|
||||
"fuse.s3fs",
|
||||
"fuse.rclone",
|
||||
"afs",
|
||||
"lustre",
|
||||
"autofs",
|
||||
"davfs",
|
||||
"fuse.gcsfuse",
|
||||
"fuse.juicefs",
|
||||
}
|
||||
)
|
||||
MOUNTINFO_ESCAPE = re.compile(r"\\([0-7]{3})")
|
||||
|
||||
|
||||
def network_mounts(mountinfo: str) -> list[str]:
|
||||
"""
|
||||
Args:
|
||||
mountinfo: the text of a ``/proc/<pid>/mountinfo``.
|
||||
|
||||
Returns:
|
||||
The mount points of every network filesystem in it, sorted, except
|
||||
``/``: a host whose root is remote still scans its root.
|
||||
"""
|
||||
points = set()
|
||||
for line in mountinfo.splitlines():
|
||||
fields = line.split(" ")
|
||||
if "-" not in fields[6:]:
|
||||
continue
|
||||
fstype = fields[fields.index("-", 6) + 1]
|
||||
point = MOUNTINFO_ESCAPE.sub(lambda m: chr(int(m.group(1), 8)), fields[4])
|
||||
if fstype in NETWORK_FSTYPES and point != "/":
|
||||
points.add(point)
|
||||
return sorted(points)
|
||||
|
||||
|
||||
def host_network_mounts() -> list[str]:
|
||||
return network_mounts(
|
||||
MOUNTINFO.read_text(encoding="utf-8", errors="surrogateescape")
|
||||
)
|
||||
|
||||
|
||||
def printable(path: str) -> str:
|
||||
"""
|
||||
Args:
|
||||
path: a mount point as decoded from mountinfo.
|
||||
|
||||
Returns:
|
||||
``path`` with every undecodable byte as ``\\xNN`` and every other
|
||||
non-printable character in its Python escape form, so it prints as
|
||||
exactly one line.
|
||||
"""
|
||||
text = os.fsencode(path).decode(errors="backslashreplace")
|
||||
return "".join(char if char.isprintable() else ascii(char)[1:-1] for char in text)
|
||||
|
||||
|
||||
def vulnerability_check(
|
||||
containers: Sequence[Container],
|
||||
config: ScanConfig,
|
||||
@@ -2043,6 +2123,11 @@ def main(argv=None) -> int:
|
||||
print(f"❌ listing the running containers failed: {exc}")
|
||||
return 1
|
||||
failures, infos = check(containers, hardened, probe_php)
|
||||
remote = host_network_mounts() if "host" in config.targets else []
|
||||
infos += [
|
||||
f"host scan skips the network or automounted filesystem at {printable(point)}"
|
||||
for point in remote
|
||||
]
|
||||
targets, judged, errors = vulnerability_check(
|
||||
containers,
|
||||
config,
|
||||
@@ -2050,7 +2135,7 @@ def main(argv=None) -> int:
|
||||
suppressions_from_json(json.loads(args.suppressions)),
|
||||
Path(args.cache_dir),
|
||||
Path(args.database_dir),
|
||||
json.loads(args.host_excludes),
|
||||
[*json.loads(args.host_excludes), *remote],
|
||||
default_runner,
|
||||
run,
|
||||
)
|
||||
|
||||
@@ -33,4 +33,5 @@ HEALTH_RUNTIME_HOST_EXCLUDES:
|
||||
- /mnt
|
||||
- /media
|
||||
- "{{ DIR_BACKUPS }}"
|
||||
- "{{ DIR_BACKUPS_NODE }}"
|
||||
- "{{ lookup('nfs_export_base') }}"
|
||||
@@ -0,0 +1,301 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest import TestCase, main, mock
|
||||
|
||||
from utils.storage.nfs import fstype
|
||||
|
||||
from .test_script import MAIN_SCAN, NO_SUPPRESSIONS, SCRIPT, _config
|
||||
|
||||
MOUNTINFO_FIELDS = (
|
||||
("22", "1", "0:21", "/", "/", "rw", "shared:1", "-", "overlay", "overlay", "rw"),
|
||||
("25", "22", "0:5", "/", "/proc", "rw", "shared:12", "-", "proc", "proc", "rw"),
|
||||
("30", "22", "0:31", "/", "/mnt/docker-fs", "rw", "-", "zfs", "pool/node", "rw"),
|
||||
(
|
||||
"310",
|
||||
"22",
|
||||
"0:60",
|
||||
"/",
|
||||
"/var/lib/infinito",
|
||||
"rw,relatime",
|
||||
"shared:150",
|
||||
"-",
|
||||
"nfs4",
|
||||
"10.100.1.11:/srv/nfs/infinito-state",
|
||||
"rw,vers=4.2,soft,timeo=50,retrans=3",
|
||||
),
|
||||
(
|
||||
"311",
|
||||
"310",
|
||||
"0:31",
|
||||
"/var/lib/infinito-backup",
|
||||
"/var/lib/infinito/backup",
|
||||
"rw",
|
||||
"shared:1",
|
||||
"-",
|
||||
"zfs",
|
||||
"pool/node",
|
||||
"rw",
|
||||
),
|
||||
(
|
||||
"312",
|
||||
"30",
|
||||
"0:61",
|
||||
"/",
|
||||
"/mnt/docker-fs/docker/volumes/hermes_redis/_data",
|
||||
"rw",
|
||||
"-",
|
||||
"nfs4",
|
||||
"10.100.1.11:/srv/nfs/infinito-state/hermes_redis",
|
||||
"rw",
|
||||
),
|
||||
(
|
||||
"313",
|
||||
"22",
|
||||
"0:62",
|
||||
"/",
|
||||
"/srv/team\\040share",
|
||||
"rw",
|
||||
"shared:160",
|
||||
"master:3",
|
||||
"-",
|
||||
"cifs",
|
||||
"//files/team",
|
||||
"rw",
|
||||
),
|
||||
(
|
||||
"314",
|
||||
"22",
|
||||
"0:63",
|
||||
"/",
|
||||
"/home/admin/remote",
|
||||
"rw,nosuid",
|
||||
"-",
|
||||
"fuse.sshfs",
|
||||
"admin@backup:",
|
||||
"rw",
|
||||
),
|
||||
("315", "22", "0:64", "/", "/run/user/1000", "rw", "-", "tmpfs", "tmpfs", "rw"),
|
||||
("316", "22", "0:65", "/", "/srv/a,b", "rw", "-", "cifs", "//files/ab", "rw"),
|
||||
)
|
||||
SWARM_NODE_MOUNTINFO = "\n".join(" ".join(fields) for fields in MOUNTINFO_FIELDS)
|
||||
REMOTE = [
|
||||
"/home/admin/remote",
|
||||
"/mnt/docker-fs/docker/volumes/hermes_redis/_data",
|
||||
"/srv/a,b",
|
||||
"/srv/team share",
|
||||
"/var/lib/infinito",
|
||||
]
|
||||
NOT_UTF8_MOUNTINFO = b"1 0 0:20 / /srv/caf\xe9 rw - nfs4 server:/cafe rw\n"
|
||||
GLOB_MOUNTS = ("/srv/q{a,b}]?*\\w", "/srv/x[y", "/var/lib/docker")
|
||||
|
||||
|
||||
def _values(argv, flag):
|
||||
return [argv[index + 1] for index, arg in enumerate(argv) if arg == flag]
|
||||
|
||||
|
||||
def _literal(pattern):
|
||||
"""
|
||||
Args:
|
||||
pattern: a doublestar pattern as Trivy, Syft and Grype match it.
|
||||
|
||||
Returns:
|
||||
The one path the pattern matches, or None while it holds an unescaped
|
||||
glob character or ends in a lone backslash.
|
||||
"""
|
||||
chars = iter(pattern)
|
||||
path = []
|
||||
for char in chars:
|
||||
if char == "\\":
|
||||
escaped = next(chars, None)
|
||||
if escaped is None:
|
||||
return None
|
||||
path.append(escaped)
|
||||
elif char in "*?[]{}":
|
||||
return None
|
||||
else:
|
||||
path.append(char)
|
||||
return "".join(path)
|
||||
|
||||
|
||||
def _layout(*excludes):
|
||||
return SCRIPT.Layout(
|
||||
runtime=("container", "run"),
|
||||
databases=Path("/var/cache/v/db"),
|
||||
sbom=Path("/var/cache/v/sbom"),
|
||||
work=Path("/var/cache/v/run"),
|
||||
excludes=excludes,
|
||||
)
|
||||
|
||||
|
||||
def _main(mountinfo, targets):
|
||||
"""
|
||||
Args:
|
||||
mountinfo: the bytes of the host's mountinfo, or None for no file.
|
||||
targets: the scan targets.
|
||||
|
||||
Returns:
|
||||
``(output, layouts)``: what the check printed and the layout of every
|
||||
scan it started.
|
||||
"""
|
||||
layouts = []
|
||||
|
||||
def scan(targets, config, images, layout, runner):
|
||||
layouts.append(layout)
|
||||
return [], []
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
for name in ("report", "log"):
|
||||
(root / name).mkdir()
|
||||
if mountinfo is not None:
|
||||
(root / "mountinfo").write_bytes(mountinfo)
|
||||
argv = [
|
||||
"--scan",
|
||||
json.dumps({**MAIN_SCAN, "targets": targets}),
|
||||
"--hardened",
|
||||
"{}",
|
||||
"--images",
|
||||
"{}",
|
||||
"--suppressions",
|
||||
json.dumps(NO_SUPPRESSIONS),
|
||||
"--cache-dir",
|
||||
str(root / "cache"),
|
||||
"--database-dir",
|
||||
str(root / "cache" / "db"),
|
||||
"--host-excludes",
|
||||
'["/proc"]',
|
||||
"--environment",
|
||||
"production",
|
||||
"--report-dir",
|
||||
str(root / "report"),
|
||||
"--log-dir",
|
||||
str(root / "log"),
|
||||
]
|
||||
with (
|
||||
mock.patch.object(SCRIPT, "MOUNTINFO", root / "mountinfo"),
|
||||
mock.patch.object(SCRIPT, "running_containers", return_value=[]),
|
||||
mock.patch.object(SCRIPT, "check", return_value=([], [])),
|
||||
mock.patch.object(SCRIPT, "docker_root", return_value="/var/lib/docker"),
|
||||
mock.patch.object(SCRIPT, "scan", side_effect=scan),
|
||||
mock.patch.object(SCRIPT.socket, "gethostname", return_value="node"),
|
||||
contextlib.redirect_stdout(io.StringIO()) as out,
|
||||
):
|
||||
SCRIPT.main(argv)
|
||||
return out.getvalue(), layouts
|
||||
|
||||
|
||||
def _engine_skips(layout):
|
||||
host = SCRIPT.host_target("node")
|
||||
trivy = SCRIPT.trivy_step(layout, "trivy:1", host, _config(), [])
|
||||
syft = SCRIPT.sbom_step(layout, "syft:1", host)
|
||||
grype = SCRIPT.grype_step(layout, "grype:1", host, _config(engines=["grype"]))
|
||||
return {
|
||||
"trivy": [
|
||||
_literal(pattern)
|
||||
for value in _values(trivy.argv, "--skip-dirs")
|
||||
for pattern in next(csv.reader([value]))
|
||||
],
|
||||
"syft": [_literal(pattern) for pattern in _values(syft.argv, "--exclude")],
|
||||
"grype": [_literal(pattern) for pattern in _values(grype.argv, "--exclude")],
|
||||
}
|
||||
|
||||
|
||||
def _expected_skips(point):
|
||||
return {
|
||||
"trivy": f"{SCRIPT.HOST_ROOT}{point}",
|
||||
"syft": f"./{point.strip('/')}",
|
||||
"grype": f"./{point.strip('/')}",
|
||||
}
|
||||
|
||||
|
||||
class TestNetworkMounts(TestCase):
|
||||
def test_every_network_filesystem_is_found_with_its_escaped_path(self):
|
||||
self.assertEqual(SCRIPT.network_mounts(SWARM_NODE_MOUNTINFO), REMOTE)
|
||||
|
||||
def test_local_filesystems_and_binds_of_local_trees_are_kept(self):
|
||||
found = SCRIPT.network_mounts(SWARM_NODE_MOUNTINFO)
|
||||
for point in ("/", "/proc", "/mnt/docker-fs", "/var/lib/infinito/backup"):
|
||||
with self.subTest(point=point):
|
||||
self.assertNotIn(point, found)
|
||||
|
||||
def test_a_network_root_is_still_scanned(self):
|
||||
self.assertEqual(
|
||||
SCRIPT.network_mounts("1 0 0:20 / / rw - nfs4 server:/root rw"), []
|
||||
)
|
||||
|
||||
def test_the_shared_state_mount_of_every_nfs_version_is_found(self):
|
||||
for version in (3, 4):
|
||||
with self.subTest(version=version):
|
||||
self.assertIn(fstype(version), SCRIPT.NETWORK_FSTYPES)
|
||||
|
||||
|
||||
class TestSkipPatterns(TestCase):
|
||||
def test_a_mount_point_with_a_comma_stays_one_skip_dir(self):
|
||||
self.assertEqual(
|
||||
_engine_skips(_layout("/srv/a,b"))["trivy"],
|
||||
[f"{SCRIPT.HOST_ROOT}/srv/a,b"],
|
||||
)
|
||||
|
||||
def test_a_mount_point_with_glob_characters_matches_only_itself(self):
|
||||
skips = _engine_skips(_layout(*GLOB_MOUNTS))
|
||||
for engine in ("trivy", "syft", "grype"):
|
||||
with self.subTest(engine=engine):
|
||||
self.assertEqual(
|
||||
skips[engine],
|
||||
[_expected_skips(point)[engine] for point in GLOB_MOUNTS],
|
||||
)
|
||||
|
||||
|
||||
class TestHostScanSkipsNetworkMounts(TestCase):
|
||||
def test_every_engine_skips_each_network_mount_and_the_check_reports_it(self):
|
||||
output, layouts = _main(SWARM_NODE_MOUNTINFO.encode(), ["host"])
|
||||
skips = _engine_skips(layouts[0])
|
||||
for point in REMOTE:
|
||||
with self.subTest(point=point):
|
||||
self.assertIn(
|
||||
f"ℹ️ host scan skips the network or automounted filesystem at {point}",
|
||||
output.splitlines(),
|
||||
)
|
||||
for engine, path in _expected_skips(point).items():
|
||||
self.assertIn(path, skips[engine], engine)
|
||||
for engine, path in _expected_skips("/mnt/docker-fs").items():
|
||||
self.assertNotIn(path, skips[engine], engine)
|
||||
|
||||
def test_a_mount_point_that_is_not_utf8_is_skipped_and_printed_escaped(self):
|
||||
output, layouts = _main(NOT_UTF8_MOUNTINFO, ["host"])
|
||||
point = os.fsdecode(b"/srv/caf\xe9")
|
||||
skips = _engine_skips(layouts[0])
|
||||
for engine, path in _expected_skips(point).items():
|
||||
self.assertIn(path, skips[engine], engine)
|
||||
self.assertIn(
|
||||
"ℹ️ host scan skips the network or automounted filesystem at /srv/caf\\xe9",
|
||||
output.splitlines(),
|
||||
)
|
||||
output.encode("utf-8")
|
||||
|
||||
def test_a_mount_point_with_a_newline_prints_as_one_escaped_line(self):
|
||||
output, _layouts = _main(
|
||||
b"1 0 0:20 / /srv/a\\012forged rw - nfs4 server:/a rw\n", ["host"]
|
||||
)
|
||||
lines = output.splitlines()
|
||||
self.assertIn(
|
||||
"ℹ️ host scan skips the network or automounted filesystem at "
|
||||
"/srv/a\\nforged",
|
||||
lines,
|
||||
)
|
||||
self.assertNotIn("forged", [line.strip() for line in lines])
|
||||
|
||||
def test_a_scan_without_the_host_reads_and_reports_no_mount(self):
|
||||
output, _layouts = _main(None, ["container"])
|
||||
self.assertNotIn("host scan skips", output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1834,7 +1834,14 @@ class TestCommands(TestCase):
|
||||
|
||||
def test_the_host_scan_skips_the_excluded_paths(self):
|
||||
step = SCRIPT.trivy_step(self.layout, "trivy:1", self.host, _config(), [])
|
||||
self.assertIn("/host/proc,/host/var/lib/docker", step.argv)
|
||||
self.assertEqual(
|
||||
[
|
||||
step.argv[i + 1]
|
||||
for i, arg in enumerate(step.argv)
|
||||
if arg == "--skip-dirs"
|
||||
],
|
||||
['"/host/proc"', '"/host/var/lib/docker"'],
|
||||
)
|
||||
|
||||
def test_syft_scans_the_host_with_the_image_catalogers(self):
|
||||
step = SCRIPT.sbom_step(self.layout, "syft:1", self.host)
|
||||
@@ -2394,6 +2401,7 @@ class TestMain(TestCase):
|
||||
mock.patch.object(SCRIPT, "running_containers", return_value=[]),
|
||||
mock.patch.object(SCRIPT, "check", return_value=([], [])),
|
||||
mock.patch.object(SCRIPT, "docker_root", return_value="/var/lib/docker"),
|
||||
mock.patch.object(SCRIPT, "host_network_mounts", return_value=[]),
|
||||
mock.patch.object(
|
||||
SCRIPT, "scan", return_value=(list(findings), list(errors))
|
||||
),
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_ROOT: Path = Path(__file__).resolve().parents[6]
|
||||
|
||||
__all__ = ["PROJECT_ROOT"]
|
||||
@@ -0,0 +1,161 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import posixpath
|
||||
import unittest
|
||||
from collections.abc import Iterator, Mapping
|
||||
from pathlib import PurePosixPath
|
||||
from typing import Any
|
||||
|
||||
from jinja2 import Environment, StrictUndefined, select_autoescape
|
||||
|
||||
from utils.cache.files import iter_project_files
|
||||
from utils.cache.yaml import load_yaml, load_yaml_any
|
||||
from utils.roles.mapping import ROLE_FILE_VARS_MAIN
|
||||
from utils.storage.nfs import get_export_base
|
||||
|
||||
from . import PROJECT_ROOT
|
||||
|
||||
_ROLES = PROJECT_ROOT / "roles"
|
||||
_GROUP_PATHS = PROJECT_ROOT / "group_vars" / "all" / "05_paths.yml"
|
||||
_GROUP_PATH_KEYS = ("DIR_VAR_LIB", "DIR_BACKUPS", "DIR_BACKUPS_NODE")
|
||||
_NFS_CLIENT = "svc-storage-nfs-client"
|
||||
_NFS_MOUNT_ROLES = (_NFS_CLIENT, "svc-storage-nfs-server")
|
||||
_NFS_FSTYPE = "{{ STORAGE_NFS_FSTYPE }}"
|
||||
_INSTALLED_SOFTWARE = (
|
||||
"/usr",
|
||||
"/etc",
|
||||
"/opt",
|
||||
"/var/lib/dpkg",
|
||||
"/var/lib/pacman",
|
||||
"/var/lib/rpm",
|
||||
"/usr/lib/sysimage/rpm",
|
||||
"/lib/apk/db",
|
||||
)
|
||||
|
||||
|
||||
def _lookup(name: str) -> str:
|
||||
if name == "nfs_export_base":
|
||||
return get_export_base()
|
||||
raise KeyError(f"no stub for lookup({name!r})")
|
||||
|
||||
|
||||
def _render(template: str, context: Mapping[str, Any]) -> str:
|
||||
env = Environment(
|
||||
undefined=StrictUndefined,
|
||||
autoescape=select_autoescape(default_for_string=False),
|
||||
)
|
||||
env.filters["path_join"] = lambda parts: posixpath.join(*parts)
|
||||
env.globals["lookup"] = _lookup
|
||||
return env.from_string(template).render(**context)
|
||||
|
||||
|
||||
def _context() -> dict[str, str]:
|
||||
paths = load_yaml(str(_GROUP_PATHS))
|
||||
context: dict[str, str] = {}
|
||||
for key in _GROUP_PATH_KEYS:
|
||||
context[key] = _render(paths[key], context)
|
||||
for role in _NFS_MOUNT_ROLES:
|
||||
role_vars = load_yaml(str(_ROLES / role / ROLE_FILE_VARS_MAIN))
|
||||
context.update(
|
||||
(key, value)
|
||||
for key, value in role_vars.items()
|
||||
if isinstance(value, str) and "{{" not in value
|
||||
)
|
||||
return context
|
||||
|
||||
|
||||
def _tasks(node: Any) -> Iterator[Mapping[str, Any]]:
|
||||
if isinstance(node, list):
|
||||
for item in node:
|
||||
yield from _tasks(item)
|
||||
elif isinstance(node, Mapping):
|
||||
yield node
|
||||
for key in ("block", "rescue", "always"):
|
||||
yield from _tasks(node.get(key))
|
||||
|
||||
|
||||
def _mounts(role: str) -> Iterator[Mapping[str, Any]]:
|
||||
tasks_dir = f"{_ROLES / role / 'tasks'}{os.sep}"
|
||||
task_files = (
|
||||
path
|
||||
for path in iter_project_files(extensions=(".yml",))
|
||||
if path.startswith(tasks_dir)
|
||||
)
|
||||
for task_file in sorted(task_files):
|
||||
for task in _tasks(load_yaml_any(task_file)):
|
||||
mount = task.get("ansible.posix.mount")
|
||||
if isinstance(mount, Mapping) and mount.get("state") != "unmounted":
|
||||
yield mount
|
||||
|
||||
|
||||
def _nfs_mount_paths(context: Mapping[str, Any]) -> list[str]:
|
||||
"""
|
||||
Returns:
|
||||
Every host path, rendered, where the NFS roles mount the shared state.
|
||||
"""
|
||||
return [
|
||||
_render(mount["path"], context)
|
||||
for role in _NFS_MOUNT_ROLES
|
||||
for mount in _mounts(role)
|
||||
if mount.get("fstype") == _NFS_FSTYPE
|
||||
]
|
||||
|
||||
|
||||
def _local_bind_paths(context: Mapping[str, Any]) -> list[str]:
|
||||
"""
|
||||
Returns:
|
||||
Every host path, rendered, where the NFS client binds a node-local
|
||||
tree over the shared state, with that tree.
|
||||
"""
|
||||
return [
|
||||
_render(mount[key], context)
|
||||
for mount in _mounts(_NFS_CLIENT)
|
||||
if "bind" in str(mount.get("opts", "")).split(",")
|
||||
for key in ("path", "src")
|
||||
]
|
||||
|
||||
|
||||
def _host_excludes(context: Mapping[str, Any]) -> list[PurePosixPath]:
|
||||
declared = load_yaml(str(_ROLES / "sys-ctl-hlth-runtime" / ROLE_FILE_VARS_MAIN))[
|
||||
"HEALTH_RUNTIME_HOST_EXCLUDES"
|
||||
]
|
||||
return [PurePosixPath(_render(str(entry), context)) for entry in declared]
|
||||
|
||||
|
||||
def _skipped(path: str, excludes: list[PurePosixPath]) -> bool:
|
||||
candidate = PurePosixPath(path)
|
||||
return any(
|
||||
candidate == exclude or exclude in candidate.parents for exclude in excludes
|
||||
)
|
||||
|
||||
|
||||
class TestHostScanExcludes(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.context = _context()
|
||||
self.excludes = _host_excludes(self.context)
|
||||
|
||||
def test_the_shared_state_and_the_node_backup_store_are_found(self) -> None:
|
||||
self.assertIn(self.context["DIR_VAR_LIB"], _nfs_mount_paths(self.context))
|
||||
self.assertIn(self.context["DIR_BACKUPS_NODE"], _local_bind_paths(self.context))
|
||||
|
||||
def test_the_host_scan_skips_the_node_local_backup_store(self) -> None:
|
||||
for path in _local_bind_paths(self.context):
|
||||
with self.subTest(path=path):
|
||||
self.assertTrue(
|
||||
_skipped(path, self.excludes),
|
||||
f"the host scan walks {path} on every swarm node: a local "
|
||||
"tree the network mount detection does not see",
|
||||
)
|
||||
|
||||
def test_the_host_scan_keeps_installed_software(self) -> None:
|
||||
for path in _INSTALLED_SOFTWARE:
|
||||
with self.subTest(path=path):
|
||||
self.assertFalse(
|
||||
_skipped(path, self.excludes),
|
||||
f"{path} holds installed packages the host scan must read",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user