From 01a11c9a7932e00038369e36bd50041e5e2d561f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Mon, 23 Nov 2026 21:38:32 +0200 Subject: [PATCH 01/19] feat(ami): enforce file policy on images Add file_policy.yml and file_policy_check.py. The check runs at stage2 through permission_check.py and on every Docker image in the image test workflow. Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/docker-image-test.yml | 8 + ansible/files/file_policy.yml | 43 +++++ ansible/files/file_policy_check.py | 215 ++++++++++++++++++++++++ ansible/files/permission_check.py | 13 ++ 4 files changed, 279 insertions(+) create mode 100644 ansible/files/file_policy.yml create mode 100644 ansible/files/file_policy_check.py diff --git a/.github/workflows/docker-image-test.yml b/.github/workflows/docker-image-test.yml index 29b79719b7..b75f192a09 100644 --- a/.github/workflows/docker-image-test.yml +++ b/.github/workflows/docker-image-test.yml @@ -82,6 +82,14 @@ jobs: -t "supabase-postgres:${{ matrix.name }}-analyze" \ . + - name: Check file policy + run: | + set -o pipefail + echo "=== File policy check for ${{ matrix.name }} ===" + container=$(docker create "pg-docker-test:${{ matrix.name }}") + trap 'docker rm "$container" >/dev/null' EXIT + docker export "$container" | python3 ansible/files/file_policy_check.py --tar - + - name: Run image size analysis if: ${{ matrix.target == '' }} run: | diff --git a/ansible/files/file_policy.yml b/ansible/files/file_policy.yml new file mode 100644 index 0000000000..92da3b5350 --- /dev/null +++ b/ansible/files/file_policy.yml @@ -0,0 +1,43 @@ +modes: + files: ["0644", "0640", "0600", "0440", "0755"] + dirs: ["0755", "0750", "0700"] + +roots: + - /etc + - /usr/local + - /opt + - /data + - /var/lib + +owners: + /etc/wal-g: wal-g:wal-g + /etc/postgresql: postgres:postgres + /etc/postgresql-custom: postgres:postgres + /data/pgdata: postgres:postgres + /home/postgres: postgres:postgres + /var/lib/postgresql: postgres:postgres + /var/log/postgresql: postgres:postgres + +setuid: + - /usr/lib/dbus-1.0/dbus-daemon-launch-helper + - /usr/lib/polkit-1/polkit-agent-helper-1 + - /usr/sbin/pam_extrausers_chkpwd + - /usr/sbin/unix_chkpwd + +exceptions: + - path: /etc/nix + reason: nix config directory ships 0555 + - path: /usr/local/bin/gosu + reason: gosu binary installed 0711 + - path: /usr/local/bin/wal-g + reason: wal-g binary installed 0555 + - path: /var/local + reason: Ubuntu base default 2775 + - path: /var/mail + reason: Ubuntu base default 2775 + - path: /var/log/btmp + reason: Ubuntu base default 0660 + - path: /var/log/lastlog + reason: Ubuntu base default 0664 + - path: /var/log/wtmp + reason: Ubuntu base default 0664 diff --git a/ansible/files/file_policy_check.py b/ansible/files/file_policy_check.py new file mode 100644 index 0000000000..8400c99409 --- /dev/null +++ b/ansible/files/file_policy_check.py @@ -0,0 +1,215 @@ +import argparse +import os +import stat +import sys +import tarfile +from pathlib import Path + +try: + import yaml +except ImportError: + sys.exit("file_policy_check.py requires PyYAML (apt install python3-yaml)") + +DEFAULT_POLICY = Path(__file__).with_name("file_policy.yml") +SKIPPED_TREES = ( + "/proc", + "/sys", + "/dev", + "/run", + "/tmp", + "/var/tmp", + "/nix/store", +) + + +def under(path, tree): + return path == tree or path.startswith(tree.rstrip("/") + "/") + + +def parse_mode(value): + return value if isinstance(value, int) else int(value, 8) + + +def load_policy(path): + raw = yaml.safe_load(Path(path).read_text()) + exceptions = [] + for entry in raw.get("exceptions") or []: + exceptions.append(entry["path"] if isinstance(entry, dict) else entry) + return { + "files": {parse_mode(m) for m in raw["modes"]["files"]}, + "dirs": {parse_mode(m) for m in raw["modes"]["dirs"]}, + "roots": raw.get("roots") or [], + "owners": raw.get("owners") or {}, + "setuid": set(raw.get("setuid") or []), + "exceptions": exceptions, + } + + +def excepted(path, exceptions): + for pattern in exceptions: + if pattern.endswith("/**"): + if under(path, pattern[:-3]): + return True + elif path == pattern: + return True + return False + + +def parse_id_map(text): + ids = {} + for line in text.splitlines(): + fields = line.split(":") + if len(fields) >= 3 and fields[2].isdigit(): + ids.setdefault(int(fields[2]), fields[0]) + return ids + + +def walk_root(root): + entries = [] + errors = [] + root = os.path.abspath(root) + + def to_path(real): + rel = os.path.relpath(real, root) + return "/" if rel == "." else "/" + rel + + def record(real): + path = to_path(real) + try: + st = os.lstat(real) + except FileNotFoundError: + return + except OSError as e: + errors.append(f"{path}: cannot stat: {e}") + return + if stat.S_ISDIR(st.st_mode): + kind = "dir" + elif stat.S_ISREG(st.st_mode): + kind = "file" + else: + return + entries.append((path, stat.S_IMODE(st.st_mode), kind, st.st_uid, st.st_gid)) + + def on_error(e): + if not isinstance(e, FileNotFoundError): + errors.append(f"{to_path(e.filename)}: cannot read: {e}") + + for dirpath, dirnames, filenames in os.walk(root, onerror=on_error): + dirnames[:] = [ + d + for d in dirnames + if not any( + under(to_path(os.path.join(dirpath, d)), t) for t in SKIPPED_TREES + ) + ] + if not any(under(to_path(dirpath), t) for t in SKIPPED_TREES): + record(dirpath) + for name in filenames: + path = to_path(os.path.join(dirpath, name)) + if not any(under(path, t) for t in SKIPPED_TREES): + record(os.path.join(dirpath, name)) + + users = groups = {} + try: + users = parse_id_map((Path(root) / "etc/passwd").read_text()) + groups = parse_id_map((Path(root) / "etc/group").read_text()) + except OSError as e: + errors.append(f"cannot read passwd or group under {root}: {e}") + return entries, users, groups, errors + + +def walk_tar(source): + entries = [] + users = groups = {} + with tarfile.open( + name=None if source == "-" else source, + fileobj=sys.stdin.buffer if source == "-" else None, + mode="r|*", + ) as tf: + for member in tf: + name = member.name + while name.startswith("./"): + name = name[2:] + name = name.rstrip("/") + path = "/" + name if name not in ("", ".") else "/" + if path == "/etc/passwd" and member.isreg(): + users = parse_id_map(tf.extractfile(member).read().decode()) + elif path == "/etc/group" and member.isreg(): + groups = parse_id_map(tf.extractfile(member).read().decode()) + if any(under(path, t) for t in SKIPPED_TREES): + continue + if member.isdir(): + kind = "dir" + elif member.isreg() or member.islnk(): + kind = "file" + else: + continue + entries.append((path, member.mode & 0o7777, kind, member.uid, member.gid)) + return entries, users, groups, [] + + +def check(entries, users, groups, policy): + violations = [] + by_path = {path: (mode, uid, gid) for path, mode, _, uid, gid in entries} + excepted_paths = policy["exceptions"] + + for path, mode, kind, uid, gid in entries: + if excepted(path, excepted_paths): + continue + if kind == "file" and mode & 0o6000 and path not in policy["setuid"]: + violations.append(f"{path}: setuid/setgid {mode:04o} not in setuid list") + sticky_dir = kind == "dir" and mode & 0o1000 + if mode & 0o002 and not sticky_dir: + violations.append(f"{path}: world-writable {mode:04o}") + if mode & 0o020 and not sticky_dir: + violations.append(f"{path}: group-writable {mode:04o}") + if uid not in users: + violations.append(f"{path}: owner id {uid} has no passwd entry") + if gid not in groups: + violations.append(f"{path}: group id {gid} has no group entry") + if any(under(path, r) for r in policy["roots"]): + allowed = policy["files"] if kind == "file" else policy["dirs"] + if mode & 0o777 not in allowed: + violations.append(f"{path}: mode {mode & 0o777:04o} not in allowlist") + + for path, expected in policy["owners"].items(): + if path not in by_path or excepted(path, excepted_paths): + continue + _, uid, gid = by_path[path] + actual = f"{users.get(uid, uid)}:{groups.get(gid, gid)}" + if actual != expected: + violations.append(f"{path}: owner {actual}, expected {expected}") + return violations + + +def main(): + parser = argparse.ArgumentParser( + description="Check file modes and owners against file_policy.yml" + ) + source = parser.add_mutually_exclusive_group(required=True) + source.add_argument("--root", help="directory to walk") + source.add_argument("--tar", help="tar file to read, or - for stdin") + parser.add_argument("--policy", default=str(DEFAULT_POLICY)) + args = parser.parse_args() + + policy = load_policy(args.policy) + if args.root: + entries, users, groups, errors = walk_root(args.root) + else: + entries, users, groups, errors = walk_tar(args.tar) + + violations = errors + check(entries, users, groups, policy) + if violations: + print("=" * 80) + print("FILE POLICY VIOLATIONS:") + print("=" * 80) + for violation in violations: + print(violation) + print("=" * 80) + print(f"{len(violations)} violation(s) in {len(entries)} entries") + sys.exit(1) + print(f"File policy check passed: {len(entries)} entries") + + +if __name__ == "__main__": + main() diff --git a/ansible/files/permission_check.py b/ansible/files/permission_check.py index c286bd388f..2ffba077eb 100644 --- a/ansible/files/permission_check.py +++ b/ansible/files/permission_check.py @@ -4,6 +4,7 @@ import stat import pwd import grp +import subprocess # Expected groups for each user @@ -330,6 +331,16 @@ def check_directory_permissions(): print("\nAll directory permissions are correct.") +def check_file_policy(): + """Check modes and owners across the filesystem against file_policy.yml.""" + script = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "file_policy_check.py" + ) + result = subprocess.run([sys.executable, script, "--root", "/"], check=False) + if result.returncode != 0: + sys.exit(result.returncode) + + def main(): parser = argparse.ArgumentParser( prog="Supabase Postgres Artifact Permissions Checker", @@ -399,6 +410,8 @@ def main(): # Check directory permissions for security-critical paths check_directory_permissions() + check_file_policy() + if __name__ == "__main__": main() From b136c372d5e221150c8d9e40ae46a3bbb332825c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Wed, 25 Nov 2026 03:03:11 +0200 Subject: [PATCH 02/19] refactor(ami): drop standalone file policy check Remove file_policy_check.py and its callers. The discovery rules move into supascan. Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/docker-image-test.yml | 8 - ansible/files/file_policy.yml | 43 ----- ansible/files/file_policy_check.py | 215 ------------------------ ansible/files/permission_check.py | 13 -- 4 files changed, 279 deletions(-) delete mode 100644 ansible/files/file_policy.yml delete mode 100644 ansible/files/file_policy_check.py diff --git a/.github/workflows/docker-image-test.yml b/.github/workflows/docker-image-test.yml index b75f192a09..29b79719b7 100644 --- a/.github/workflows/docker-image-test.yml +++ b/.github/workflows/docker-image-test.yml @@ -82,14 +82,6 @@ jobs: -t "supabase-postgres:${{ matrix.name }}-analyze" \ . - - name: Check file policy - run: | - set -o pipefail - echo "=== File policy check for ${{ matrix.name }} ===" - container=$(docker create "pg-docker-test:${{ matrix.name }}") - trap 'docker rm "$container" >/dev/null' EXIT - docker export "$container" | python3 ansible/files/file_policy_check.py --tar - - - name: Run image size analysis if: ${{ matrix.target == '' }} run: | diff --git a/ansible/files/file_policy.yml b/ansible/files/file_policy.yml deleted file mode 100644 index 92da3b5350..0000000000 --- a/ansible/files/file_policy.yml +++ /dev/null @@ -1,43 +0,0 @@ -modes: - files: ["0644", "0640", "0600", "0440", "0755"] - dirs: ["0755", "0750", "0700"] - -roots: - - /etc - - /usr/local - - /opt - - /data - - /var/lib - -owners: - /etc/wal-g: wal-g:wal-g - /etc/postgresql: postgres:postgres - /etc/postgresql-custom: postgres:postgres - /data/pgdata: postgres:postgres - /home/postgres: postgres:postgres - /var/lib/postgresql: postgres:postgres - /var/log/postgresql: postgres:postgres - -setuid: - - /usr/lib/dbus-1.0/dbus-daemon-launch-helper - - /usr/lib/polkit-1/polkit-agent-helper-1 - - /usr/sbin/pam_extrausers_chkpwd - - /usr/sbin/unix_chkpwd - -exceptions: - - path: /etc/nix - reason: nix config directory ships 0555 - - path: /usr/local/bin/gosu - reason: gosu binary installed 0711 - - path: /usr/local/bin/wal-g - reason: wal-g binary installed 0555 - - path: /var/local - reason: Ubuntu base default 2775 - - path: /var/mail - reason: Ubuntu base default 2775 - - path: /var/log/btmp - reason: Ubuntu base default 0660 - - path: /var/log/lastlog - reason: Ubuntu base default 0664 - - path: /var/log/wtmp - reason: Ubuntu base default 0664 diff --git a/ansible/files/file_policy_check.py b/ansible/files/file_policy_check.py deleted file mode 100644 index 8400c99409..0000000000 --- a/ansible/files/file_policy_check.py +++ /dev/null @@ -1,215 +0,0 @@ -import argparse -import os -import stat -import sys -import tarfile -from pathlib import Path - -try: - import yaml -except ImportError: - sys.exit("file_policy_check.py requires PyYAML (apt install python3-yaml)") - -DEFAULT_POLICY = Path(__file__).with_name("file_policy.yml") -SKIPPED_TREES = ( - "/proc", - "/sys", - "/dev", - "/run", - "/tmp", - "/var/tmp", - "/nix/store", -) - - -def under(path, tree): - return path == tree or path.startswith(tree.rstrip("/") + "/") - - -def parse_mode(value): - return value if isinstance(value, int) else int(value, 8) - - -def load_policy(path): - raw = yaml.safe_load(Path(path).read_text()) - exceptions = [] - for entry in raw.get("exceptions") or []: - exceptions.append(entry["path"] if isinstance(entry, dict) else entry) - return { - "files": {parse_mode(m) for m in raw["modes"]["files"]}, - "dirs": {parse_mode(m) for m in raw["modes"]["dirs"]}, - "roots": raw.get("roots") or [], - "owners": raw.get("owners") or {}, - "setuid": set(raw.get("setuid") or []), - "exceptions": exceptions, - } - - -def excepted(path, exceptions): - for pattern in exceptions: - if pattern.endswith("/**"): - if under(path, pattern[:-3]): - return True - elif path == pattern: - return True - return False - - -def parse_id_map(text): - ids = {} - for line in text.splitlines(): - fields = line.split(":") - if len(fields) >= 3 and fields[2].isdigit(): - ids.setdefault(int(fields[2]), fields[0]) - return ids - - -def walk_root(root): - entries = [] - errors = [] - root = os.path.abspath(root) - - def to_path(real): - rel = os.path.relpath(real, root) - return "/" if rel == "." else "/" + rel - - def record(real): - path = to_path(real) - try: - st = os.lstat(real) - except FileNotFoundError: - return - except OSError as e: - errors.append(f"{path}: cannot stat: {e}") - return - if stat.S_ISDIR(st.st_mode): - kind = "dir" - elif stat.S_ISREG(st.st_mode): - kind = "file" - else: - return - entries.append((path, stat.S_IMODE(st.st_mode), kind, st.st_uid, st.st_gid)) - - def on_error(e): - if not isinstance(e, FileNotFoundError): - errors.append(f"{to_path(e.filename)}: cannot read: {e}") - - for dirpath, dirnames, filenames in os.walk(root, onerror=on_error): - dirnames[:] = [ - d - for d in dirnames - if not any( - under(to_path(os.path.join(dirpath, d)), t) for t in SKIPPED_TREES - ) - ] - if not any(under(to_path(dirpath), t) for t in SKIPPED_TREES): - record(dirpath) - for name in filenames: - path = to_path(os.path.join(dirpath, name)) - if not any(under(path, t) for t in SKIPPED_TREES): - record(os.path.join(dirpath, name)) - - users = groups = {} - try: - users = parse_id_map((Path(root) / "etc/passwd").read_text()) - groups = parse_id_map((Path(root) / "etc/group").read_text()) - except OSError as e: - errors.append(f"cannot read passwd or group under {root}: {e}") - return entries, users, groups, errors - - -def walk_tar(source): - entries = [] - users = groups = {} - with tarfile.open( - name=None if source == "-" else source, - fileobj=sys.stdin.buffer if source == "-" else None, - mode="r|*", - ) as tf: - for member in tf: - name = member.name - while name.startswith("./"): - name = name[2:] - name = name.rstrip("/") - path = "/" + name if name not in ("", ".") else "/" - if path == "/etc/passwd" and member.isreg(): - users = parse_id_map(tf.extractfile(member).read().decode()) - elif path == "/etc/group" and member.isreg(): - groups = parse_id_map(tf.extractfile(member).read().decode()) - if any(under(path, t) for t in SKIPPED_TREES): - continue - if member.isdir(): - kind = "dir" - elif member.isreg() or member.islnk(): - kind = "file" - else: - continue - entries.append((path, member.mode & 0o7777, kind, member.uid, member.gid)) - return entries, users, groups, [] - - -def check(entries, users, groups, policy): - violations = [] - by_path = {path: (mode, uid, gid) for path, mode, _, uid, gid in entries} - excepted_paths = policy["exceptions"] - - for path, mode, kind, uid, gid in entries: - if excepted(path, excepted_paths): - continue - if kind == "file" and mode & 0o6000 and path not in policy["setuid"]: - violations.append(f"{path}: setuid/setgid {mode:04o} not in setuid list") - sticky_dir = kind == "dir" and mode & 0o1000 - if mode & 0o002 and not sticky_dir: - violations.append(f"{path}: world-writable {mode:04o}") - if mode & 0o020 and not sticky_dir: - violations.append(f"{path}: group-writable {mode:04o}") - if uid not in users: - violations.append(f"{path}: owner id {uid} has no passwd entry") - if gid not in groups: - violations.append(f"{path}: group id {gid} has no group entry") - if any(under(path, r) for r in policy["roots"]): - allowed = policy["files"] if kind == "file" else policy["dirs"] - if mode & 0o777 not in allowed: - violations.append(f"{path}: mode {mode & 0o777:04o} not in allowlist") - - for path, expected in policy["owners"].items(): - if path not in by_path or excepted(path, excepted_paths): - continue - _, uid, gid = by_path[path] - actual = f"{users.get(uid, uid)}:{groups.get(gid, gid)}" - if actual != expected: - violations.append(f"{path}: owner {actual}, expected {expected}") - return violations - - -def main(): - parser = argparse.ArgumentParser( - description="Check file modes and owners against file_policy.yml" - ) - source = parser.add_mutually_exclusive_group(required=True) - source.add_argument("--root", help="directory to walk") - source.add_argument("--tar", help="tar file to read, or - for stdin") - parser.add_argument("--policy", default=str(DEFAULT_POLICY)) - args = parser.parse_args() - - policy = load_policy(args.policy) - if args.root: - entries, users, groups, errors = walk_root(args.root) - else: - entries, users, groups, errors = walk_tar(args.tar) - - violations = errors + check(entries, users, groups, policy) - if violations: - print("=" * 80) - print("FILE POLICY VIOLATIONS:") - print("=" * 80) - for violation in violations: - print(violation) - print("=" * 80) - print(f"{len(violations)} violation(s) in {len(entries)} entries") - sys.exit(1) - print(f"File policy check passed: {len(entries)} entries") - - -if __name__ == "__main__": - main() diff --git a/ansible/files/permission_check.py b/ansible/files/permission_check.py index 2ffba077eb..c286bd388f 100644 --- a/ansible/files/permission_check.py +++ b/ansible/files/permission_check.py @@ -4,7 +4,6 @@ import stat import pwd import grp -import subprocess # Expected groups for each user @@ -331,16 +330,6 @@ def check_directory_permissions(): print("\nAll directory permissions are correct.") -def check_file_policy(): - """Check modes and owners across the filesystem against file_policy.yml.""" - script = os.path.join( - os.path.dirname(os.path.abspath(__file__)), "file_policy_check.py" - ) - result = subprocess.run([sys.executable, script, "--root", "/"], check=False) - if result.returncode != 0: - sys.exit(result.returncode) - - def main(): parser = argparse.ArgumentParser( prog="Supabase Postgres Artifact Permissions Checker", @@ -410,8 +399,6 @@ def main(): # Check directory permissions for security-critical paths check_directory_permissions() - check_file_policy() - if __name__ == "__main__": main() From c09d890c51b7a63e569e67a553967e6e88f6f450 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Wed, 25 Nov 2026 01:08:29 +0200 Subject: [PATCH 03/19] feat(supascan): add filesystem discovery check Add `supascan discover` and run it from `validate` when a baselines directory has file-discovery.yml. It reports setuid or setgid files outside an allowlist, world-writable paths other than sticky directories, group-writable paths, owner or group ids with no passwd or group entry, and modes outside an allowlist under the policy roots. Seed file-discovery.yml for the AMI and qemu baselines. Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- .../ami-build-amd64/file-discovery.yml | 124 ++++++++ .../ami-build-arm64/file-discovery.yml | 124 ++++++++ .../qemu-build-amd64/file-discovery.yml | 124 ++++++++ .../qemu-build-arm64/file-discovery.yml | 124 ++++++++ nix/packages/supascan/README.md | 12 + .../supascan/cmd/supascan/discover.go | 66 +++++ nix/packages/supascan/cmd/supascan/main.go | 1 + .../supascan/cmd/supascan/validate.go | 1 + .../supascan/internal/discovery/discovery.go | 276 ++++++++++++++++++ .../internal/discovery/discovery_test.go | 192 ++++++++++++ .../supascan/internal/validator/validator.go | 43 +++ .../internal/validator/validator_test.go | 11 + 12 files changed, 1098 insertions(+) create mode 100644 audit-specs/baselines/ami-build-amd64/file-discovery.yml create mode 100644 audit-specs/baselines/ami-build-arm64/file-discovery.yml create mode 100644 audit-specs/baselines/qemu-build-amd64/file-discovery.yml create mode 100644 audit-specs/baselines/qemu-build-arm64/file-discovery.yml create mode 100644 nix/packages/supascan/cmd/supascan/discover.go create mode 100644 nix/packages/supascan/internal/discovery/discovery.go create mode 100644 nix/packages/supascan/internal/discovery/discovery_test.go diff --git a/audit-specs/baselines/ami-build-amd64/file-discovery.yml b/audit-specs/baselines/ami-build-amd64/file-discovery.yml new file mode 100644 index 0000000000..00d50d40fe --- /dev/null +++ b/audit-specs/baselines/ami-build-amd64/file-discovery.yml @@ -0,0 +1,124 @@ +# Filesystem discovery policy for supascan validate. +# Exceptions below were derived from audit-specs/baselines/baseline.yml +# (AMI arm64 capture) and Ubuntu defaults. Directory modes and setuid bits +# are not in that capture, so the first run on a built image may report more. +roots: [/etc, /usr/local, /opt, /data, /var/lib] +file_modes: ["0644", "0640", "0600", "0440", "0755"] +dir_modes: ["0755", "0750", "0700"] +setuid: + - /usr/bin/chage + - /usr/bin/chfn + - /usr/bin/chsh + - /usr/bin/crontab + - /usr/bin/dotlockfile + - /usr/bin/expiry + - /usr/bin/fusermount3 + - /usr/bin/gpasswd + - /usr/bin/mount + - /usr/bin/newgrp + - /usr/bin/passwd + - /usr/bin/pkexec + - /usr/bin/ssh-agent + - /usr/bin/su + - /usr/bin/sudo + - /usr/bin/umount + - /usr/bin/wall + - /usr/bin/write.ul + - /usr/lib/dbus-1.0/dbus-daemon-launch-helper + - /usr/lib/openssh/ssh-keysign + - /usr/lib/polkit-1/polkit-agent-helper-1 + - /usr/sbin/pam_extrausers_chkpwd + - /usr/sbin/unix_chkpwd +exceptions: + - path: /var/local + reason: Ubuntu base default or cloud-init state + - path: /var/mail + reason: Ubuntu base default or cloud-init state + - path: /var/log/btmp + reason: Ubuntu base default or cloud-init state + - path: /var/log/lastlog + reason: Ubuntu base default or cloud-init state + - path: /var/log/wtmp + reason: Ubuntu base default or cloud-init state + - path: /var/lib/cloud/instances/** + reason: Ubuntu base default or cloud-init state + - path: /usr/local/kong/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /usr/local/openresty/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/vector/examples/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/pgbouncer-custom/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/postgresql-custom/extension-custom-scripts/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/envoy/envoy.yaml + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/envoy/lds.yaml + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/gotrue.env + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.conf.default + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.logrotate + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres-auth.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres-csv.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-walg.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/machine-id + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/pgbouncer/userlist.txt + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/custom-overrides.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/generated-optimizations.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/read-replica.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/supautils.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/wal-g.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql/pg_hba.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgrest/base.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgrest/merge.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/ssl/adminapi/server.crt + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/ssl/adminapi/server.key + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/wal-g/config.json + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/envoy + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/envoy-hot-restarter.py + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/start-envoy.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/lib/systemd/system/kong.service + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/kong + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/lapis + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/luarocks + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/luarocks-admin + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/project-init.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/systemd-networkd-check-and-fix.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/etc/luarocks/config-5.1.lua + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /var/lib/cloud/scripts/per-boot/supaboot.sh + reason: Group-writable or non-allowlisted mode in baseline.yml diff --git a/audit-specs/baselines/ami-build-arm64/file-discovery.yml b/audit-specs/baselines/ami-build-arm64/file-discovery.yml new file mode 100644 index 0000000000..00d50d40fe --- /dev/null +++ b/audit-specs/baselines/ami-build-arm64/file-discovery.yml @@ -0,0 +1,124 @@ +# Filesystem discovery policy for supascan validate. +# Exceptions below were derived from audit-specs/baselines/baseline.yml +# (AMI arm64 capture) and Ubuntu defaults. Directory modes and setuid bits +# are not in that capture, so the first run on a built image may report more. +roots: [/etc, /usr/local, /opt, /data, /var/lib] +file_modes: ["0644", "0640", "0600", "0440", "0755"] +dir_modes: ["0755", "0750", "0700"] +setuid: + - /usr/bin/chage + - /usr/bin/chfn + - /usr/bin/chsh + - /usr/bin/crontab + - /usr/bin/dotlockfile + - /usr/bin/expiry + - /usr/bin/fusermount3 + - /usr/bin/gpasswd + - /usr/bin/mount + - /usr/bin/newgrp + - /usr/bin/passwd + - /usr/bin/pkexec + - /usr/bin/ssh-agent + - /usr/bin/su + - /usr/bin/sudo + - /usr/bin/umount + - /usr/bin/wall + - /usr/bin/write.ul + - /usr/lib/dbus-1.0/dbus-daemon-launch-helper + - /usr/lib/openssh/ssh-keysign + - /usr/lib/polkit-1/polkit-agent-helper-1 + - /usr/sbin/pam_extrausers_chkpwd + - /usr/sbin/unix_chkpwd +exceptions: + - path: /var/local + reason: Ubuntu base default or cloud-init state + - path: /var/mail + reason: Ubuntu base default or cloud-init state + - path: /var/log/btmp + reason: Ubuntu base default or cloud-init state + - path: /var/log/lastlog + reason: Ubuntu base default or cloud-init state + - path: /var/log/wtmp + reason: Ubuntu base default or cloud-init state + - path: /var/lib/cloud/instances/** + reason: Ubuntu base default or cloud-init state + - path: /usr/local/kong/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /usr/local/openresty/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/vector/examples/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/pgbouncer-custom/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/postgresql-custom/extension-custom-scripts/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/envoy/envoy.yaml + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/envoy/lds.yaml + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/gotrue.env + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.conf.default + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.logrotate + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres-auth.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres-csv.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-walg.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/machine-id + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/pgbouncer/userlist.txt + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/custom-overrides.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/generated-optimizations.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/read-replica.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/supautils.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/wal-g.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql/pg_hba.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgrest/base.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgrest/merge.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/ssl/adminapi/server.crt + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/ssl/adminapi/server.key + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/wal-g/config.json + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/envoy + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/envoy-hot-restarter.py + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/start-envoy.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/lib/systemd/system/kong.service + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/kong + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/lapis + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/luarocks + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/luarocks-admin + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/project-init.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/systemd-networkd-check-and-fix.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/etc/luarocks/config-5.1.lua + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /var/lib/cloud/scripts/per-boot/supaboot.sh + reason: Group-writable or non-allowlisted mode in baseline.yml diff --git a/audit-specs/baselines/qemu-build-amd64/file-discovery.yml b/audit-specs/baselines/qemu-build-amd64/file-discovery.yml new file mode 100644 index 0000000000..00d50d40fe --- /dev/null +++ b/audit-specs/baselines/qemu-build-amd64/file-discovery.yml @@ -0,0 +1,124 @@ +# Filesystem discovery policy for supascan validate. +# Exceptions below were derived from audit-specs/baselines/baseline.yml +# (AMI arm64 capture) and Ubuntu defaults. Directory modes and setuid bits +# are not in that capture, so the first run on a built image may report more. +roots: [/etc, /usr/local, /opt, /data, /var/lib] +file_modes: ["0644", "0640", "0600", "0440", "0755"] +dir_modes: ["0755", "0750", "0700"] +setuid: + - /usr/bin/chage + - /usr/bin/chfn + - /usr/bin/chsh + - /usr/bin/crontab + - /usr/bin/dotlockfile + - /usr/bin/expiry + - /usr/bin/fusermount3 + - /usr/bin/gpasswd + - /usr/bin/mount + - /usr/bin/newgrp + - /usr/bin/passwd + - /usr/bin/pkexec + - /usr/bin/ssh-agent + - /usr/bin/su + - /usr/bin/sudo + - /usr/bin/umount + - /usr/bin/wall + - /usr/bin/write.ul + - /usr/lib/dbus-1.0/dbus-daemon-launch-helper + - /usr/lib/openssh/ssh-keysign + - /usr/lib/polkit-1/polkit-agent-helper-1 + - /usr/sbin/pam_extrausers_chkpwd + - /usr/sbin/unix_chkpwd +exceptions: + - path: /var/local + reason: Ubuntu base default or cloud-init state + - path: /var/mail + reason: Ubuntu base default or cloud-init state + - path: /var/log/btmp + reason: Ubuntu base default or cloud-init state + - path: /var/log/lastlog + reason: Ubuntu base default or cloud-init state + - path: /var/log/wtmp + reason: Ubuntu base default or cloud-init state + - path: /var/lib/cloud/instances/** + reason: Ubuntu base default or cloud-init state + - path: /usr/local/kong/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /usr/local/openresty/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/vector/examples/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/pgbouncer-custom/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/postgresql-custom/extension-custom-scripts/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/envoy/envoy.yaml + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/envoy/lds.yaml + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/gotrue.env + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.conf.default + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.logrotate + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres-auth.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres-csv.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-walg.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/machine-id + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/pgbouncer/userlist.txt + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/custom-overrides.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/generated-optimizations.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/read-replica.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/supautils.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/wal-g.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql/pg_hba.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgrest/base.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgrest/merge.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/ssl/adminapi/server.crt + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/ssl/adminapi/server.key + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/wal-g/config.json + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/envoy + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/envoy-hot-restarter.py + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/start-envoy.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/lib/systemd/system/kong.service + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/kong + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/lapis + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/luarocks + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/luarocks-admin + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/project-init.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/systemd-networkd-check-and-fix.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/etc/luarocks/config-5.1.lua + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /var/lib/cloud/scripts/per-boot/supaboot.sh + reason: Group-writable or non-allowlisted mode in baseline.yml diff --git a/audit-specs/baselines/qemu-build-arm64/file-discovery.yml b/audit-specs/baselines/qemu-build-arm64/file-discovery.yml new file mode 100644 index 0000000000..00d50d40fe --- /dev/null +++ b/audit-specs/baselines/qemu-build-arm64/file-discovery.yml @@ -0,0 +1,124 @@ +# Filesystem discovery policy for supascan validate. +# Exceptions below were derived from audit-specs/baselines/baseline.yml +# (AMI arm64 capture) and Ubuntu defaults. Directory modes and setuid bits +# are not in that capture, so the first run on a built image may report more. +roots: [/etc, /usr/local, /opt, /data, /var/lib] +file_modes: ["0644", "0640", "0600", "0440", "0755"] +dir_modes: ["0755", "0750", "0700"] +setuid: + - /usr/bin/chage + - /usr/bin/chfn + - /usr/bin/chsh + - /usr/bin/crontab + - /usr/bin/dotlockfile + - /usr/bin/expiry + - /usr/bin/fusermount3 + - /usr/bin/gpasswd + - /usr/bin/mount + - /usr/bin/newgrp + - /usr/bin/passwd + - /usr/bin/pkexec + - /usr/bin/ssh-agent + - /usr/bin/su + - /usr/bin/sudo + - /usr/bin/umount + - /usr/bin/wall + - /usr/bin/write.ul + - /usr/lib/dbus-1.0/dbus-daemon-launch-helper + - /usr/lib/openssh/ssh-keysign + - /usr/lib/polkit-1/polkit-agent-helper-1 + - /usr/sbin/pam_extrausers_chkpwd + - /usr/sbin/unix_chkpwd +exceptions: + - path: /var/local + reason: Ubuntu base default or cloud-init state + - path: /var/mail + reason: Ubuntu base default or cloud-init state + - path: /var/log/btmp + reason: Ubuntu base default or cloud-init state + - path: /var/log/lastlog + reason: Ubuntu base default or cloud-init state + - path: /var/log/wtmp + reason: Ubuntu base default or cloud-init state + - path: /var/lib/cloud/instances/** + reason: Ubuntu base default or cloud-init state + - path: /usr/local/kong/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /usr/local/openresty/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/vector/examples/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/pgbouncer-custom/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/postgresql-custom/extension-custom-scripts/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/envoy/envoy.yaml + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/envoy/lds.yaml + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/gotrue.env + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.conf.default + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.logrotate + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres-auth.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres-csv.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-walg.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/machine-id + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/pgbouncer/userlist.txt + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/custom-overrides.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/generated-optimizations.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/read-replica.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/supautils.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/wal-g.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql/pg_hba.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgrest/base.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgrest/merge.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/ssl/adminapi/server.crt + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/ssl/adminapi/server.key + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/wal-g/config.json + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/envoy + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/envoy-hot-restarter.py + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/start-envoy.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/lib/systemd/system/kong.service + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/kong + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/lapis + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/luarocks + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/luarocks-admin + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/project-init.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/systemd-networkd-check-and-fix.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/etc/luarocks/config-5.1.lua + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /var/lib/cloud/scripts/per-boot/supaboot.sh + reason: Group-writable or non-allowlisted mode in baseline.yml diff --git a/nix/packages/supascan/README.md b/nix/packages/supascan/README.md index ee9d2659db..8a445128d1 100644 --- a/nix/packages/supascan/README.md +++ b/nix/packages/supascan/README.md @@ -7,6 +7,7 @@ A comprehensive system auditing toolkit for generating and validating baseline s **One Unified CLI with Three Commands:** - **`supascan genspec`** - Generate complete machine baseline (packages, services, configs, users, groups, mounts, kernel params) - **`supascan validate`** - Validate machines against baseline specifications with critical/advisory categorization +- **`supascan discover`** - Scan the filesystem for setuid files, world or group-writable paths, orphaned owner ids, and modes outside an allowlist - **`supascan split`** - Split a monolithic baseline into separate section files for easier auditing **Use Cases:** @@ -50,6 +51,17 @@ sudo nix run .#supascan -- validate --verbose /path/to/baselines sudo nix run .#supascan -- validate --format documentation /path/to/baselines ``` +### Filesystem discovery + +`validate` also runs `discover` when the baselines directory has a `file-discovery.yml`. goss only checks listed paths, so discovery walks the filesystem and reports setuid or setgid files outside `setuid`, world-writable paths other than sticky directories, group-writable paths, owner or group ids with no passwd or group entry, and modes outside `file_modes` and `dir_modes` under `roots`. Paths in `exceptions` are skipped. An entry ending in `/**` covers the whole subtree. + +```bash +sudo supascan discover audit-specs/baselines/ami-build-amd64/file-discovery.yml + +# Scan an extracted image +sudo supascan discover --root /mnt/image policy.yml +``` + ## Installation ### Using Nix Flake diff --git a/nix/packages/supascan/cmd/supascan/discover.go b/nix/packages/supascan/cmd/supascan/discover.go new file mode 100644 index 0000000000..b7250a4685 --- /dev/null +++ b/nix/packages/supascan/cmd/supascan/discover.go @@ -0,0 +1,66 @@ +package main + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "github.com/supabase/supascan/internal/discovery" +) + +var discoverRoot string + +var discoverCmd = &cobra.Command{ + Use: "discover ", + Short: "Scan the filesystem for permission and ownership drift", + Long: `Walk the filesystem and report paths that goss specs cannot cover because +they are not listed: setuid or setgid files outside the allowlist, world-writable +paths other than sticky directories, group-writable paths without an exception, +owner or group ids with no passwd or group entry, and modes outside the allowlist +under the policy roots. + +Exits non-zero when anything is reported. Run as root to read every directory. + +Examples: + sudo supascan discover audit-specs/baselines/ami-build-amd64/file-discovery.yml + + # Scan an extracted image + sudo supascan discover --root /mnt/image policy.yml +`, + Args: cobra.ExactArgs(1), + RunE: runDiscover, +} + +func init() { + discoverCmd.Flags().StringVar(&discoverRoot, "root", "/", "Filesystem root to scan") + rootCmd.AddCommand(discoverCmd) +} + +func runDiscover(cmd *cobra.Command, args []string) error { + policy, err := discovery.LoadPolicy(args[0]) + if err != nil { + return fmt.Errorf("failed to load policy: %w", err) + } + + res, err := discovery.Scan(context.Background(), discoverRoot, policy) + if err != nil { + return fmt.Errorf("scan failed: %w", err) + } + + out := cmd.OutOrStdout() + for _, e := range res.Errors { + fmt.Fprintf(out, "warning: %s\n", e) + } + for _, f := range res.Findings { + fmt.Fprintln(out, f) + } + fmt.Fprintf(out, "%d finding(s) in %d entries\n", len(res.Findings), res.Scanned) + + if len(res.Findings) > 0 { + cmd.SilenceUsage = true + cmd.SilenceErrors = true + return fmt.Errorf("%d finding(s)", len(res.Findings)) + } + return nil +} diff --git a/nix/packages/supascan/cmd/supascan/main.go b/nix/packages/supascan/cmd/supascan/main.go index 68eae12451..847cff47ab 100644 --- a/nix/packages/supascan/cmd/supascan/main.go +++ b/nix/packages/supascan/cmd/supascan/main.go @@ -22,6 +22,7 @@ Commands: genspec Generate a baseline specification from the current system validate Validate the system against baseline specifications split Split a baseline file into separate section files + discover Scan the filesystem for permission and ownership drift Examples: # Generate a baseline spec diff --git a/nix/packages/supascan/cmd/supascan/validate.go b/nix/packages/supascan/cmd/supascan/validate.go index be8fde8cb3..bbc4b96745 100644 --- a/nix/packages/supascan/cmd/supascan/validate.go +++ b/nix/packages/supascan/cmd/supascan/validate.go @@ -32,6 +32,7 @@ Critical specs (must pass): - service.yml, user.yml, group.yml, mount.yml, package.yml - files-security.yml, files-ssl.yml - files-postgres-config.yml, files-postgres-data.yml + - file-discovery.yml (filesystem scan, runs when present) Advisory specs (informational): - kernel-param.yml, files-*.yml (non-critical paths) diff --git a/nix/packages/supascan/internal/discovery/discovery.go b/nix/packages/supascan/internal/discovery/discovery.go new file mode 100644 index 0000000000..5e65c36fd4 --- /dev/null +++ b/nix/packages/supascan/internal/discovery/discovery.go @@ -0,0 +1,276 @@ +package discovery + +import ( + "bufio" + "context" + "fmt" + "io/fs" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "syscall" + + "gopkg.in/yaml.v3" +) + +var skippedTrees = []string{ + "/proc", + "/sys", + "/dev", + "/run", + "/tmp", + "/var/tmp", + "/nix/store", +} + +type Exception struct { + Path string `yaml:"path"` + Reason string `yaml:"reason,omitempty"` +} + +type Policy struct { + Roots []string `yaml:"roots"` + FileModes []string `yaml:"file_modes"` + DirModes []string `yaml:"dir_modes"` + Setuid []string `yaml:"setuid"` + Exceptions []Exception `yaml:"exceptions"` +} + +type Finding struct { + Path string + Detail string +} + +func (f Finding) String() string { + return f.Path + ": " + f.Detail +} + +type Result struct { + Findings []Finding + Scanned int + Errors []string +} + +func LoadPolicy(path string) (*Policy, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var p Policy + if err := yaml.Unmarshal(data, &p); err != nil { + return nil, fmt.Errorf("parse %s: %w", path, err) + } + for _, m := range append(append([]string{}, p.FileModes...), p.DirModes...) { + if _, err := strconv.ParseUint(m, 8, 32); err != nil { + return nil, fmt.Errorf("invalid mode %q in %s", m, path) + } + } + return &p, nil +} + +type entry struct { + path string + mode fs.FileMode + isDir bool + uid uint32 + gid uint32 +} + +func under(path, tree string) bool { + return path == tree || strings.HasPrefix(path, strings.TrimRight(tree, "/")+"/") +} + +func (p *Policy) excepted(path string) bool { + for _, e := range p.Exceptions { + if base, ok := strings.CutSuffix(e.Path, "/**"); ok { + if under(path, base) { + return true + } + } else if path == e.Path { + return true + } + } + return false +} + +func modeSet(values []string) map[fs.FileMode]bool { + set := make(map[fs.FileMode]bool, len(values)) + for _, v := range values { + n, _ := strconv.ParseUint(v, 8, 32) + set[fs.FileMode(n)] = true + } + return set +} + +func parseIDs(path string) (map[uint32]bool, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + ids := make(map[uint32]bool) + sc := bufio.NewScanner(f) + for sc.Scan() { + fields := strings.Split(sc.Text(), ":") + if len(fields) < 3 { + continue + } + if n, err := strconv.ParseUint(fields[2], 10, 32); err == nil { + ids[uint32(n)] = true + } + } + return ids, sc.Err() +} + +// Scan walks root and reports entries that break the policy. Paths in the +// result are relative to root with a leading slash, so a mounted image can +// be scanned in place. +func Scan(ctx context.Context, root string, p *Policy) (*Result, error) { + root = filepath.Clean(root) + users, err := parseIDs(filepath.Join(root, "etc/passwd")) + if err != nil { + return nil, fmt.Errorf("read passwd: %w", err) + } + groups, err := parseIDs(filepath.Join(root, "etc/group")) + if err != nil { + return nil, fmt.Errorf("read group: %w", err) + } + + res := &Result{} + toPath := func(real string) string { + rel, err := filepath.Rel(root, real) + if err != nil || rel == "." { + return "/" + } + return "/" + filepath.ToSlash(rel) + } + + err = filepath.WalkDir(root, func(real string, d fs.DirEntry, walkErr error) error { + if ctx.Err() != nil { + return ctx.Err() + } + path := toPath(real) + for _, t := range skippedTrees { + if under(path, t) { + if d != nil && d.IsDir() { + return filepath.SkipDir + } + return nil + } + } + if walkErr != nil { + if !os.IsNotExist(walkErr) { + res.Errors = append(res.Errors, fmt.Sprintf("%s: %v", path, walkErr)) + } + if d != nil && d.IsDir() { + return filepath.SkipDir + } + return nil + } + if !d.IsDir() && !d.Type().IsRegular() { + return nil + } + info, err := d.Info() + if err != nil { + if !os.IsNotExist(err) { + res.Errors = append(res.Errors, fmt.Sprintf("%s: %v", path, err)) + } + return nil + } + st, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return fmt.Errorf("no stat data for %s", path) + } + res.Scanned++ + res.Findings = append(res.Findings, p.check(entry{ + path: path, + mode: info.Mode(), + isDir: d.IsDir(), + uid: st.Uid, + gid: st.Gid, + }, users, groups)...) + return nil + }) + if err != nil { + return res, err + } + sort.Slice(res.Findings, func(i, j int) bool { + if res.Findings[i].Path != res.Findings[j].Path { + return res.Findings[i].Path < res.Findings[j].Path + } + return res.Findings[i].Detail < res.Findings[j].Detail + }) + return res, nil +} + +func (p *Policy) check(e entry, users, groups map[uint32]bool) []Finding { + if p.excepted(e.path) { + return nil + } + var out []Finding + add := func(format string, args ...any) { + out = append(out, Finding{Path: e.path, Detail: fmt.Sprintf(format, args...)}) + } + + perm := e.mode.Perm() + sticky := e.isDir && e.mode&fs.ModeSticky != 0 + if !e.isDir && e.mode&(fs.ModeSetuid|fs.ModeSetgid) != 0 && !p.isSetuidAllowed(e.path) { + add("setuid or setgid file %04o not in setuid list", unixMode(e.mode)) + } + if perm&0o002 != 0 && !sticky { + add("world-writable %04o", unixMode(e.mode)) + } + if perm&0o020 != 0 && !sticky { + add("group-writable %04o", unixMode(e.mode)) + } + if !users[e.uid] { + add("owner id %d has no passwd entry", e.uid) + } + if !groups[e.gid] { + add("group id %d has no group entry", e.gid) + } + if p.inRoots(e.path) { + allowed := p.FileModes + if e.isDir { + allowed = p.DirModes + } + if !modeSet(allowed)[perm] { + add("mode %04o not in allowlist", perm) + } + } + return out +} + +func (p *Policy) isSetuidAllowed(path string) bool { + for _, s := range p.Setuid { + if s == path { + return true + } + } + return false +} + +func (p *Policy) inRoots(path string) bool { + for _, r := range p.Roots { + if under(path, r) { + return true + } + } + return false +} + +func unixMode(m fs.FileMode) uint32 { + out := uint32(m.Perm()) + if m&fs.ModeSetuid != 0 { + out |= 0o4000 + } + if m&fs.ModeSetgid != 0 { + out |= 0o2000 + } + if m&fs.ModeSticky != 0 { + out |= 0o1000 + } + return out +} diff --git a/nix/packages/supascan/internal/discovery/discovery_test.go b/nix/packages/supascan/internal/discovery/discovery_test.go new file mode 100644 index 0000000000..4c4c3b6d95 --- /dev/null +++ b/nix/packages/supascan/internal/discovery/discovery_test.go @@ -0,0 +1,192 @@ +package discovery + +import ( + "context" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" + "syscall" + "testing" +) + +func testPolicy() *Policy { + return &Policy{ + Roots: []string{"/etc", "/opt"}, + FileModes: []string{"0644", "0600"}, + DirModes: []string{"0755"}, + Setuid: []string{"/usr/bin/allowed"}, + Exceptions: []Exception{ + {Path: "/etc/loose.conf"}, + {Path: "/opt/vendor/**"}, + }, + } +} + +func details(findings []Finding) string { + var parts []string + for _, f := range findings { + parts = append(parts, f.String()) + } + return strings.Join(parts, "\n") +} + +func TestCheck(t *testing.T) { + known := map[uint32]bool{0: true} + tests := []struct { + name string + entry entry + want []string + }{ + {"clean file", entry{path: "/etc/a", mode: 0o644}, nil}, + {"setuid not listed", entry{path: "/usr/bin/x", mode: 0o755 | fs.ModeSetuid}, []string{"setuid or setgid file 4755"}}, + {"setgid not listed", entry{path: "/usr/bin/x", mode: 0o755 | fs.ModeSetgid}, []string{"setuid or setgid file 2755"}}, + {"setuid listed", entry{path: "/usr/bin/allowed", mode: 0o755 | fs.ModeSetuid}, nil}, + {"world-writable file", entry{path: "/srv/x", mode: 0o666}, []string{"world-writable 0666", "group-writable 0666"}}, + {"sticky world-writable dir", entry{path: "/srv/t", mode: 0o777 | fs.ModeSticky, isDir: true}, nil}, + {"world-writable dir", entry{path: "/srv/t", mode: 0o777, isDir: true}, []string{"world-writable 0777", "group-writable 0777"}}, + {"group-writable file", entry{path: "/srv/x", mode: 0o664}, []string{"group-writable 0664"}}, + {"group-writable excepted", entry{path: "/etc/loose.conf", mode: 0o664}, nil}, + {"subtree excepted", entry{path: "/opt/vendor/deep/bin", mode: 0o775}, nil}, + {"subtree root excepted", entry{path: "/opt/vendor", mode: 0o775, isDir: true}, nil}, + {"sibling of subtree", entry{path: "/opt/vendor2/bin", mode: 0o755}, []string{"mode 0755 not in allowlist"}}, + {"orphan uid", entry{path: "/srv/x", mode: 0o644, uid: 42}, []string{"owner id 42 has no passwd entry"}}, + {"orphan gid", entry{path: "/srv/x", mode: 0o644, gid: 43}, []string{"group id 43 has no group entry"}}, + {"mode outside allowlist", entry{path: "/etc/x", mode: 0o640}, []string{"mode 0640 not in allowlist"}}, + {"mode outside roots", entry{path: "/srv/x", mode: 0o640}, nil}, + {"dir mode outside allowlist", entry{path: "/etc/d", mode: 0o700, isDir: true}, []string{"mode 0700 not in allowlist"}}, + {"dir mode allowed", entry{path: "/etc/d", mode: 0o755, isDir: true}, nil}, + } + p := testPolicy() + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := p.check(tt.entry, known, known) + if len(got) != len(tt.want) { + t.Fatalf("got %d findings, want %d:\n%s", len(got), len(tt.want), details(got)) + } + for i, w := range tt.want { + if !strings.Contains(got[i].Detail, w) { + t.Errorf("finding %d = %q, want it to contain %q", i, got[i].Detail, w) + } + } + }) + } +} + +func TestLoadPolicy(t *testing.T) { + dir := t.TempDir() + good := filepath.Join(dir, "good.yml") + os.WriteFile(good, []byte("roots: [/etc]\nfile_modes: ['0644']\ndir_modes: ['0755']\nsetuid: [/usr/bin/su]\nexceptions:\n - path: /etc/x\n reason: test\n"), 0o644) + p, err := LoadPolicy(good) + if err != nil { + t.Fatal(err) + } + if len(p.Exceptions) != 1 || p.Exceptions[0].Reason != "test" || p.Setuid[0] != "/usr/bin/su" { + t.Errorf("unexpected policy: %+v", p) + } + + bad := filepath.Join(dir, "bad.yml") + os.WriteFile(bad, []byte("file_modes: ['rw-r--r--']\n"), 0o644) + if _, err := LoadPolicy(bad); err == nil { + t.Error("expected error for invalid mode") + } + if _, err := LoadPolicy(filepath.Join(dir, "missing.yml")); err == nil { + t.Error("expected error for missing file") + } +} + +func ownerOf(t *testing.T, path string) (int, int) { + t.Helper() + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + st := info.Sys().(*syscall.Stat_t) + return int(st.Uid), int(st.Gid) +} + +func writeIDs(t *testing.T, root string, uid, gid int) { + t.Helper() + etc := filepath.Join(root, "etc") + if err := os.MkdirAll(etc, 0o755); err != nil { + t.Fatal(err) + } + os.WriteFile(filepath.Join(etc, "passwd"), []byte(fmt.Sprintf("me:x:%d:%d:::\n", uid, gid)), 0o644) + os.WriteFile(filepath.Join(etc, "group"), []byte(fmt.Sprintf("me:x:%d:\n", gid)), 0o644) +} + +func TestScan(t *testing.T) { + root := t.TempDir() + uid, gid := ownerOf(t, root) + writeIDs(t, root, uid, gid) + for path, mode := range map[string]fs.FileMode{ + "etc/ok.conf": 0o644, + "etc/loose.conf": 0o664, + "etc/bad.conf": 0o664, + "srv/suid": 0o755 | fs.ModeSetuid, + "srv/world": 0o666, + "tmp/ignored": 0o666, + "nix/store/ignored": 0o666, + "usr/bin/allowed": 0o755 | fs.ModeSetuid, + "usr/bin/not-listed": 0o755 | fs.ModeSetuid, + } { + full := filepath.Join(root, path) + os.MkdirAll(filepath.Dir(full), 0o755) + if err := os.WriteFile(full, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Chmod(full, mode); err != nil { + t.Fatal(err) + } + } + os.Symlink("/etc/ok.conf", filepath.Join(root, "srv/link")) + + p := testPolicy() + p.Roots = []string{"/etc"} + res, err := Scan(context.Background(), root, p) + if err != nil { + t.Fatal(err) + } + got := details(res.Findings) + for _, want := range []string{ + "/etc/bad.conf: group-writable 0664", + "/etc/bad.conf: mode 0664 not in allowlist", + "/srv/suid: setuid or setgid file 4755", + "/srv/world: world-writable 0666", + "/usr/bin/not-listed: setuid or setgid file 4755", + } { + if !strings.Contains(got, want) { + t.Errorf("missing finding %q in:\n%s", want, got) + } + } + for _, unwanted := range []string{"/etc/ok.conf", "/etc/loose.conf", "/tmp/", "/nix/store", "/usr/bin/allowed", "srv/link"} { + if strings.Contains(got, unwanted) { + t.Errorf("unexpected finding for %q in:\n%s", unwanted, got) + } + } + if res.Scanned == 0 { + t.Error("expected scanned entries") + } +} + +func TestScanOrphanIDs(t *testing.T) { + root := t.TempDir() + uid, gid := ownerOf(t, root) + writeIDs(t, root, uid+1000, gid+1000) + os.WriteFile(filepath.Join(root, "file"), []byte("x"), 0o644) + res, err := Scan(context.Background(), root, &Policy{}) + if err != nil { + t.Fatal(err) + } + got := details(res.Findings) + if !strings.Contains(got, "/file: owner id") || !strings.Contains(got, "/file: group id") { + t.Errorf("expected orphan id findings, got:\n%s", got) + } +} + +func TestScanMissingPasswd(t *testing.T) { + if _, err := Scan(context.Background(), t.TempDir(), &Policy{}); err == nil { + t.Error("expected error without etc/passwd") + } +} diff --git a/nix/packages/supascan/internal/validator/validator.go b/nix/packages/supascan/internal/validator/validator.go index e1c60e67fb..17a7df6132 100644 --- a/nix/packages/supascan/internal/validator/validator.go +++ b/nix/packages/supascan/internal/validator/validator.go @@ -9,6 +9,9 @@ import ( "strings" ) +// DiscoveryPolicy is the filesystem discovery policy in a baselines directory. +const DiscoveryPolicy = "file-discovery.yml" + // Spec categories var ( CriticalSpecs = []string{ @@ -110,6 +113,18 @@ func (v *Validator) Run() (*Result, error) { } } + discoveryResult := v.runDiscovery() + result.Specs = append(result.Specs, discoveryResult) + v.printSpecResult(discoveryResult) + if discoveryResult.Skipped { + result.CriticalSkipped++ + } else if discoveryResult.Passed { + result.CriticalPassed++ + } else { + result.CriticalFailed++ + result.FailedCritical = append(result.FailedCritical, discoveryResult.Spec) + } + fmt.Println() fmt.Println("============================================================") fmt.Println("ADVISORY CHECKS (informational)") @@ -244,6 +259,34 @@ func (v *Validator) runSpec(specFile, category, gossPath string) SpecResult { return result } +// runDiscovery re-executes supascan under sudo so the walk can read every +// directory, the same way goss specs run. +func (v *Validator) runDiscovery() SpecResult { + result := SpecResult{Spec: "file-discovery", Category: "critical"} + + policyPath := filepath.Join(v.opts.BaselinesDir, DiscoveryPolicy) + if _, err := os.Stat(policyPath); os.IsNotExist(err) { + result.Skipped = true + return result + } + + self, err := os.Executable() + if err != nil { + result.Error = err + return result + } + + cmd := exec.Command("sudo", self, "discover", policyPath) + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + err = cmd.Run() + result.Output = stdout.String() + stderr.String() + result.Error = err + result.Passed = err == nil + return result +} + func (v *Validator) printSpecResult(r SpecResult) { if r.Skipped { fmt.Printf(" ⊘ %s: skipped (file not found)\n", r.Spec) diff --git a/nix/packages/supascan/internal/validator/validator_test.go b/nix/packages/supascan/internal/validator/validator_test.go index e6449b1ec2..98dfa4f344 100644 --- a/nix/packages/supascan/internal/validator/validator_test.go +++ b/nix/packages/supascan/internal/validator/validator_test.go @@ -101,3 +101,14 @@ func TestResultCounts(t *testing.T) { t.Errorf("Expected 1 failed critical, got %d", len(result.FailedCritical)) } } + +func TestRunDiscoverySkippedWithoutPolicy(t *testing.T) { + v := New(Options{BaselinesDir: t.TempDir()}) + r := v.runDiscovery() + if !r.Skipped { + t.Error("expected discovery to be skipped when the policy file is missing") + } + if r.Spec != "file-discovery" || r.Category != "critical" { + t.Errorf("unexpected result: %+v", r) + } +} From 9803c2f06bf2d8c936bae034cc1cb90e296f5f49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Wed, 25 Nov 2026 03:05:27 +0200 Subject: [PATCH 04/19] feat(supascan): support include in discovery policy Move the shared exceptions to audit-specs/baselines/file-discovery.yml and have each build directory include it. Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- .../ami-build-amd64/file-discovery.yml | 126 +----------------- .../ami-build-arm64/file-discovery.yml | 126 +----------------- audit-specs/baselines/file-discovery.yml | 125 +++++++++++++++++ .../qemu-build-amd64/file-discovery.yml | 126 +----------------- .../qemu-build-arm64/file-discovery.yml | 126 +----------------- nix/packages/supascan/README.md | 2 +- .../supascan/internal/discovery/discovery.go | 44 +++++- .../internal/discovery/discovery_test.go | 28 ++++ 8 files changed, 202 insertions(+), 501 deletions(-) create mode 100644 audit-specs/baselines/file-discovery.yml diff --git a/audit-specs/baselines/ami-build-amd64/file-discovery.yml b/audit-specs/baselines/ami-build-amd64/file-discovery.yml index 00d50d40fe..1c9c3b0273 100644 --- a/audit-specs/baselines/ami-build-amd64/file-discovery.yml +++ b/audit-specs/baselines/ami-build-amd64/file-discovery.yml @@ -1,124 +1,2 @@ -# Filesystem discovery policy for supascan validate. -# Exceptions below were derived from audit-specs/baselines/baseline.yml -# (AMI arm64 capture) and Ubuntu defaults. Directory modes and setuid bits -# are not in that capture, so the first run on a built image may report more. -roots: [/etc, /usr/local, /opt, /data, /var/lib] -file_modes: ["0644", "0640", "0600", "0440", "0755"] -dir_modes: ["0755", "0750", "0700"] -setuid: - - /usr/bin/chage - - /usr/bin/chfn - - /usr/bin/chsh - - /usr/bin/crontab - - /usr/bin/dotlockfile - - /usr/bin/expiry - - /usr/bin/fusermount3 - - /usr/bin/gpasswd - - /usr/bin/mount - - /usr/bin/newgrp - - /usr/bin/passwd - - /usr/bin/pkexec - - /usr/bin/ssh-agent - - /usr/bin/su - - /usr/bin/sudo - - /usr/bin/umount - - /usr/bin/wall - - /usr/bin/write.ul - - /usr/lib/dbus-1.0/dbus-daemon-launch-helper - - /usr/lib/openssh/ssh-keysign - - /usr/lib/polkit-1/polkit-agent-helper-1 - - /usr/sbin/pam_extrausers_chkpwd - - /usr/sbin/unix_chkpwd -exceptions: - - path: /var/local - reason: Ubuntu base default or cloud-init state - - path: /var/mail - reason: Ubuntu base default or cloud-init state - - path: /var/log/btmp - reason: Ubuntu base default or cloud-init state - - path: /var/log/lastlog - reason: Ubuntu base default or cloud-init state - - path: /var/log/wtmp - reason: Ubuntu base default or cloud-init state - - path: /var/lib/cloud/instances/** - reason: Ubuntu base default or cloud-init state - - path: /usr/local/kong/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /usr/local/openresty/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/vector/examples/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/pgbouncer-custom/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/postgresql-custom/extension-custom-scripts/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/envoy/envoy.yaml - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/envoy/lds.yaml - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/gotrue.env - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.conf.default - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.logrotate - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres-auth.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres-csv.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-walg.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/machine-id - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/pgbouncer/userlist.txt - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/custom-overrides.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/generated-optimizations.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/read-replica.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/supautils.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/wal-g.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql/pg_hba.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgrest/base.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgrest/merge.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/ssl/adminapi/server.crt - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/ssl/adminapi/server.key - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/wal-g/config.json - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/envoy - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/envoy-hot-restarter.py - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/start-envoy.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/lib/systemd/system/kong.service - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/kong - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/lapis - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/luarocks - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/luarocks-admin - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/project-init.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/systemd-networkd-check-and-fix.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/etc/luarocks/config-5.1.lua - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /var/lib/cloud/scripts/per-boot/supaboot.sh - reason: Group-writable or non-allowlisted mode in baseline.yml +include: + - ../file-discovery.yml diff --git a/audit-specs/baselines/ami-build-arm64/file-discovery.yml b/audit-specs/baselines/ami-build-arm64/file-discovery.yml index 00d50d40fe..1c9c3b0273 100644 --- a/audit-specs/baselines/ami-build-arm64/file-discovery.yml +++ b/audit-specs/baselines/ami-build-arm64/file-discovery.yml @@ -1,124 +1,2 @@ -# Filesystem discovery policy for supascan validate. -# Exceptions below were derived from audit-specs/baselines/baseline.yml -# (AMI arm64 capture) and Ubuntu defaults. Directory modes and setuid bits -# are not in that capture, so the first run on a built image may report more. -roots: [/etc, /usr/local, /opt, /data, /var/lib] -file_modes: ["0644", "0640", "0600", "0440", "0755"] -dir_modes: ["0755", "0750", "0700"] -setuid: - - /usr/bin/chage - - /usr/bin/chfn - - /usr/bin/chsh - - /usr/bin/crontab - - /usr/bin/dotlockfile - - /usr/bin/expiry - - /usr/bin/fusermount3 - - /usr/bin/gpasswd - - /usr/bin/mount - - /usr/bin/newgrp - - /usr/bin/passwd - - /usr/bin/pkexec - - /usr/bin/ssh-agent - - /usr/bin/su - - /usr/bin/sudo - - /usr/bin/umount - - /usr/bin/wall - - /usr/bin/write.ul - - /usr/lib/dbus-1.0/dbus-daemon-launch-helper - - /usr/lib/openssh/ssh-keysign - - /usr/lib/polkit-1/polkit-agent-helper-1 - - /usr/sbin/pam_extrausers_chkpwd - - /usr/sbin/unix_chkpwd -exceptions: - - path: /var/local - reason: Ubuntu base default or cloud-init state - - path: /var/mail - reason: Ubuntu base default or cloud-init state - - path: /var/log/btmp - reason: Ubuntu base default or cloud-init state - - path: /var/log/lastlog - reason: Ubuntu base default or cloud-init state - - path: /var/log/wtmp - reason: Ubuntu base default or cloud-init state - - path: /var/lib/cloud/instances/** - reason: Ubuntu base default or cloud-init state - - path: /usr/local/kong/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /usr/local/openresty/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/vector/examples/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/pgbouncer-custom/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/postgresql-custom/extension-custom-scripts/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/envoy/envoy.yaml - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/envoy/lds.yaml - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/gotrue.env - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.conf.default - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.logrotate - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres-auth.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres-csv.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-walg.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/machine-id - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/pgbouncer/userlist.txt - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/custom-overrides.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/generated-optimizations.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/read-replica.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/supautils.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/wal-g.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql/pg_hba.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgrest/base.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgrest/merge.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/ssl/adminapi/server.crt - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/ssl/adminapi/server.key - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/wal-g/config.json - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/envoy - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/envoy-hot-restarter.py - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/start-envoy.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/lib/systemd/system/kong.service - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/kong - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/lapis - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/luarocks - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/luarocks-admin - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/project-init.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/systemd-networkd-check-and-fix.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/etc/luarocks/config-5.1.lua - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /var/lib/cloud/scripts/per-boot/supaboot.sh - reason: Group-writable or non-allowlisted mode in baseline.yml +include: + - ../file-discovery.yml diff --git a/audit-specs/baselines/file-discovery.yml b/audit-specs/baselines/file-discovery.yml new file mode 100644 index 0000000000..5ad6bb4f09 --- /dev/null +++ b/audit-specs/baselines/file-discovery.yml @@ -0,0 +1,125 @@ +# Shared filesystem discovery policy for supascan validate. +# Each build directory includes this file from its own file-discovery.yml. +# Exceptions below were derived from audit-specs/baselines/baseline.yml +# (AMI arm64 capture) and Ubuntu defaults. Directory modes and setuid bits +# are not in that capture, so the first run on a built image may report more. +roots: [/etc, /usr/local, /opt, /data, /var/lib] +file_modes: ["0644", "0640", "0600", "0440", "0755"] +dir_modes: ["0755", "0750", "0700"] +setuid: + - /usr/bin/chage + - /usr/bin/chfn + - /usr/bin/chsh + - /usr/bin/crontab + - /usr/bin/dotlockfile + - /usr/bin/expiry + - /usr/bin/fusermount3 + - /usr/bin/gpasswd + - /usr/bin/mount + - /usr/bin/newgrp + - /usr/bin/passwd + - /usr/bin/pkexec + - /usr/bin/ssh-agent + - /usr/bin/su + - /usr/bin/sudo + - /usr/bin/umount + - /usr/bin/wall + - /usr/bin/write.ul + - /usr/lib/dbus-1.0/dbus-daemon-launch-helper + - /usr/lib/openssh/ssh-keysign + - /usr/lib/polkit-1/polkit-agent-helper-1 + - /usr/sbin/pam_extrausers_chkpwd + - /usr/sbin/unix_chkpwd +exceptions: + - path: /var/local + reason: Ubuntu base default or cloud-init state + - path: /var/mail + reason: Ubuntu base default or cloud-init state + - path: /var/log/btmp + reason: Ubuntu base default or cloud-init state + - path: /var/log/lastlog + reason: Ubuntu base default or cloud-init state + - path: /var/log/wtmp + reason: Ubuntu base default or cloud-init state + - path: /var/lib/cloud/instances/** + reason: Ubuntu base default or cloud-init state + - path: /usr/local/kong/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /usr/local/openresty/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/vector/examples/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/pgbouncer-custom/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/postgresql-custom/extension-custom-scripts/** + reason: Group-writable or non-allowlisted modes in baseline.yml + - path: /etc/envoy/envoy.yaml + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/envoy/lds.yaml + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/gotrue.env + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.conf.default + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/kong/kong.logrotate + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres-auth.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres-csv.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-postgres.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/logrotate.d/logrotate-walg.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/machine-id + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/pgbouncer/userlist.txt + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/custom-overrides.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/generated-optimizations.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/read-replica.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/supautils.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql-custom/wal-g.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgresql/pg_hba.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgrest/base.conf + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/postgrest/merge.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/ssl/adminapi/server.crt + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/ssl/adminapi/server.key + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /etc/wal-g/config.json + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/envoy + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/envoy-hot-restarter.py + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /opt/start-envoy.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/lib/systemd/system/kong.service + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/kong + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/lapis + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/luarocks + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/luarocks-admin + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/project-init.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/bin/systemd-networkd-check-and-fix.sh + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /usr/local/etc/luarocks/config-5.1.lua + reason: Group-writable or non-allowlisted mode in baseline.yml + - path: /var/lib/cloud/scripts/per-boot/supaboot.sh + reason: Group-writable or non-allowlisted mode in baseline.yml diff --git a/audit-specs/baselines/qemu-build-amd64/file-discovery.yml b/audit-specs/baselines/qemu-build-amd64/file-discovery.yml index 00d50d40fe..1c9c3b0273 100644 --- a/audit-specs/baselines/qemu-build-amd64/file-discovery.yml +++ b/audit-specs/baselines/qemu-build-amd64/file-discovery.yml @@ -1,124 +1,2 @@ -# Filesystem discovery policy for supascan validate. -# Exceptions below were derived from audit-specs/baselines/baseline.yml -# (AMI arm64 capture) and Ubuntu defaults. Directory modes and setuid bits -# are not in that capture, so the first run on a built image may report more. -roots: [/etc, /usr/local, /opt, /data, /var/lib] -file_modes: ["0644", "0640", "0600", "0440", "0755"] -dir_modes: ["0755", "0750", "0700"] -setuid: - - /usr/bin/chage - - /usr/bin/chfn - - /usr/bin/chsh - - /usr/bin/crontab - - /usr/bin/dotlockfile - - /usr/bin/expiry - - /usr/bin/fusermount3 - - /usr/bin/gpasswd - - /usr/bin/mount - - /usr/bin/newgrp - - /usr/bin/passwd - - /usr/bin/pkexec - - /usr/bin/ssh-agent - - /usr/bin/su - - /usr/bin/sudo - - /usr/bin/umount - - /usr/bin/wall - - /usr/bin/write.ul - - /usr/lib/dbus-1.0/dbus-daemon-launch-helper - - /usr/lib/openssh/ssh-keysign - - /usr/lib/polkit-1/polkit-agent-helper-1 - - /usr/sbin/pam_extrausers_chkpwd - - /usr/sbin/unix_chkpwd -exceptions: - - path: /var/local - reason: Ubuntu base default or cloud-init state - - path: /var/mail - reason: Ubuntu base default or cloud-init state - - path: /var/log/btmp - reason: Ubuntu base default or cloud-init state - - path: /var/log/lastlog - reason: Ubuntu base default or cloud-init state - - path: /var/log/wtmp - reason: Ubuntu base default or cloud-init state - - path: /var/lib/cloud/instances/** - reason: Ubuntu base default or cloud-init state - - path: /usr/local/kong/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /usr/local/openresty/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/vector/examples/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/pgbouncer-custom/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/postgresql-custom/extension-custom-scripts/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/envoy/envoy.yaml - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/envoy/lds.yaml - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/gotrue.env - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.conf.default - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.logrotate - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres-auth.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres-csv.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-walg.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/machine-id - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/pgbouncer/userlist.txt - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/custom-overrides.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/generated-optimizations.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/read-replica.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/supautils.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/wal-g.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql/pg_hba.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgrest/base.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgrest/merge.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/ssl/adminapi/server.crt - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/ssl/adminapi/server.key - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/wal-g/config.json - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/envoy - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/envoy-hot-restarter.py - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/start-envoy.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/lib/systemd/system/kong.service - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/kong - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/lapis - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/luarocks - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/luarocks-admin - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/project-init.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/systemd-networkd-check-and-fix.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/etc/luarocks/config-5.1.lua - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /var/lib/cloud/scripts/per-boot/supaboot.sh - reason: Group-writable or non-allowlisted mode in baseline.yml +include: + - ../file-discovery.yml diff --git a/audit-specs/baselines/qemu-build-arm64/file-discovery.yml b/audit-specs/baselines/qemu-build-arm64/file-discovery.yml index 00d50d40fe..1c9c3b0273 100644 --- a/audit-specs/baselines/qemu-build-arm64/file-discovery.yml +++ b/audit-specs/baselines/qemu-build-arm64/file-discovery.yml @@ -1,124 +1,2 @@ -# Filesystem discovery policy for supascan validate. -# Exceptions below were derived from audit-specs/baselines/baseline.yml -# (AMI arm64 capture) and Ubuntu defaults. Directory modes and setuid bits -# are not in that capture, so the first run on a built image may report more. -roots: [/etc, /usr/local, /opt, /data, /var/lib] -file_modes: ["0644", "0640", "0600", "0440", "0755"] -dir_modes: ["0755", "0750", "0700"] -setuid: - - /usr/bin/chage - - /usr/bin/chfn - - /usr/bin/chsh - - /usr/bin/crontab - - /usr/bin/dotlockfile - - /usr/bin/expiry - - /usr/bin/fusermount3 - - /usr/bin/gpasswd - - /usr/bin/mount - - /usr/bin/newgrp - - /usr/bin/passwd - - /usr/bin/pkexec - - /usr/bin/ssh-agent - - /usr/bin/su - - /usr/bin/sudo - - /usr/bin/umount - - /usr/bin/wall - - /usr/bin/write.ul - - /usr/lib/dbus-1.0/dbus-daemon-launch-helper - - /usr/lib/openssh/ssh-keysign - - /usr/lib/polkit-1/polkit-agent-helper-1 - - /usr/sbin/pam_extrausers_chkpwd - - /usr/sbin/unix_chkpwd -exceptions: - - path: /var/local - reason: Ubuntu base default or cloud-init state - - path: /var/mail - reason: Ubuntu base default or cloud-init state - - path: /var/log/btmp - reason: Ubuntu base default or cloud-init state - - path: /var/log/lastlog - reason: Ubuntu base default or cloud-init state - - path: /var/log/wtmp - reason: Ubuntu base default or cloud-init state - - path: /var/lib/cloud/instances/** - reason: Ubuntu base default or cloud-init state - - path: /usr/local/kong/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /usr/local/openresty/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/vector/examples/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/pgbouncer-custom/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/postgresql-custom/extension-custom-scripts/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/envoy/envoy.yaml - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/envoy/lds.yaml - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/gotrue.env - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.conf.default - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.logrotate - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres-auth.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres-csv.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-walg.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/machine-id - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/pgbouncer/userlist.txt - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/custom-overrides.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/generated-optimizations.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/read-replica.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/supautils.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/wal-g.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql/pg_hba.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgrest/base.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgrest/merge.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/ssl/adminapi/server.crt - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/ssl/adminapi/server.key - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/wal-g/config.json - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/envoy - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/envoy-hot-restarter.py - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/start-envoy.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/lib/systemd/system/kong.service - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/kong - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/lapis - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/luarocks - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/luarocks-admin - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/project-init.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/systemd-networkd-check-and-fix.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/etc/luarocks/config-5.1.lua - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /var/lib/cloud/scripts/per-boot/supaboot.sh - reason: Group-writable or non-allowlisted mode in baseline.yml +include: + - ../file-discovery.yml diff --git a/nix/packages/supascan/README.md b/nix/packages/supascan/README.md index 8a445128d1..c36378f6b8 100644 --- a/nix/packages/supascan/README.md +++ b/nix/packages/supascan/README.md @@ -53,7 +53,7 @@ sudo nix run .#supascan -- validate --format documentation /path/to/baselines ### Filesystem discovery -`validate` also runs `discover` when the baselines directory has a `file-discovery.yml`. goss only checks listed paths, so discovery walks the filesystem and reports setuid or setgid files outside `setuid`, world-writable paths other than sticky directories, group-writable paths, owner or group ids with no passwd or group entry, and modes outside `file_modes` and `dir_modes` under `roots`. Paths in `exceptions` are skipped. An entry ending in `/**` covers the whole subtree. +`validate` also runs `discover` when the baselines directory has a `file-discovery.yml`. goss only checks listed paths, so discovery walks the filesystem and reports setuid or setgid files outside `setuid`, world-writable paths other than sticky directories, group-writable paths, owner or group ids with no passwd or group entry, and modes outside `file_modes` and `dir_modes` under `roots`. Paths in `exceptions` are skipped. An entry ending in `/**` covers the whole subtree. `include: [../file-discovery.yml]` merges another policy file, resolved relative to the including file. ```bash sudo supascan discover audit-specs/baselines/ami-build-amd64/file-discovery.yml diff --git a/nix/packages/supascan/internal/discovery/discovery.go b/nix/packages/supascan/internal/discovery/discovery.go index 5e65c36fd4..bc84be8973 100644 --- a/nix/packages/supascan/internal/discovery/discovery.go +++ b/nix/packages/supascan/internal/discovery/discovery.go @@ -54,20 +54,56 @@ type Result struct { } func LoadPolicy(path string) (*Policy, error) { + return loadPolicy(path, map[string]bool{}) +} + +func loadPolicy(path string, active map[string]bool) (*Policy, error) { + abs, err := filepath.Abs(path) + if err != nil { + return nil, err + } + if active[abs] { + return nil, fmt.Errorf("include cycle at %s", path) + } + active[abs] = true + defer delete(active, abs) + data, err := os.ReadFile(path) if err != nil { return nil, err } - var p Policy - if err := yaml.Unmarshal(data, &p); err != nil { + var raw struct { + Include []string `yaml:"include"` + Policy `yaml:",inline"` + } + if err := yaml.Unmarshal(data, &raw); err != nil { return nil, fmt.Errorf("parse %s: %w", path, err) } - for _, m := range append(append([]string{}, p.FileModes...), p.DirModes...) { + + merged := &Policy{} + for _, inc := range raw.Include { + base, err := loadPolicy(filepath.Join(filepath.Dir(path), inc), active) + if err != nil { + return nil, err + } + merged.merge(base) + } + merged.merge(&raw.Policy) + + for _, m := range append(append([]string{}, merged.FileModes...), merged.DirModes...) { if _, err := strconv.ParseUint(m, 8, 32); err != nil { return nil, fmt.Errorf("invalid mode %q in %s", m, path) } } - return &p, nil + return merged, nil +} + +func (p *Policy) merge(o *Policy) { + p.Roots = append(p.Roots, o.Roots...) + p.FileModes = append(p.FileModes, o.FileModes...) + p.DirModes = append(p.DirModes, o.DirModes...) + p.Setuid = append(p.Setuid, o.Setuid...) + p.Exceptions = append(p.Exceptions, o.Exceptions...) } type entry struct { diff --git a/nix/packages/supascan/internal/discovery/discovery_test.go b/nix/packages/supascan/internal/discovery/discovery_test.go index 4c4c3b6d95..221652aef7 100644 --- a/nix/packages/supascan/internal/discovery/discovery_test.go +++ b/nix/packages/supascan/internal/discovery/discovery_test.go @@ -96,6 +96,34 @@ func TestLoadPolicy(t *testing.T) { } } +func TestLoadPolicyInclude(t *testing.T) { + dir := t.TempDir() + os.MkdirAll(filepath.Join(dir, "build"), 0o755) + os.WriteFile(filepath.Join(dir, "common.yml"), []byte("roots: [/etc]\nfile_modes: ['0644']\nsetuid: [/usr/bin/su]\nexceptions:\n - path: /etc/a\n"), 0o644) + child := filepath.Join(dir, "build", "policy.yml") + os.WriteFile(child, []byte("include: [../common.yml]\nsetuid: [/usr/bin/sudo]\nexceptions:\n - path: /etc/b\n"), 0o644) + p, err := LoadPolicy(child) + if err != nil { + t.Fatal(err) + } + if len(p.Roots) != 1 || len(p.FileModes) != 1 || len(p.Setuid) != 2 || len(p.Exceptions) != 2 { + t.Errorf("unexpected merge: %+v", p) + } + if !p.excepted("/etc/a") || !p.excepted("/etc/b") || !p.isSetuidAllowed("/usr/bin/sudo") { + t.Errorf("merged policy missing entries: %+v", p) + } +} + +func TestLoadPolicyIncludeCycle(t *testing.T) { + dir := t.TempDir() + a, b := filepath.Join(dir, "a.yml"), filepath.Join(dir, "b.yml") + os.WriteFile(a, []byte("include: [b.yml]\n"), 0o644) + os.WriteFile(b, []byte("include: [a.yml]\n"), 0o644) + if _, err := LoadPolicy(a); err == nil || !strings.Contains(err.Error(), "cycle") { + t.Errorf("expected include cycle error, got %v", err) + } +} + func ownerOf(t *testing.T, path string) (int, int) { t.Helper() info, err := os.Stat(path) From 1bc6ae436d245bf06c66782249c7287521f9f783 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Wed, 25 Nov 2026 03:16:05 +0200 Subject: [PATCH 05/19] refactor(supascan): slim discovery check Drop include, per-build policy files, and exception reasons. Use one shared policy that validate finds in the baselines directory or its parent. Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- .../ami-build-amd64/file-discovery.yml | 2 - .../ami-build-arm64/file-discovery.yml | 2 - audit-specs/baselines/file-discovery.yml | 145 +++------ .../qemu-build-amd64/file-discovery.yml | 2 - .../qemu-build-arm64/file-discovery.yml | 2 - nix/packages/supascan/README.md | 10 +- .../supascan/cmd/supascan/discover.go | 41 +-- .../supascan/internal/discovery/discovery.go | 274 ++++-------------- .../internal/discovery/discovery_test.go | 227 ++++----------- .../supascan/internal/validator/validator.go | 38 ++- .../internal/validator/validator_test.go | 9 +- 11 files changed, 194 insertions(+), 558 deletions(-) delete mode 100644 audit-specs/baselines/ami-build-amd64/file-discovery.yml delete mode 100644 audit-specs/baselines/ami-build-arm64/file-discovery.yml delete mode 100644 audit-specs/baselines/qemu-build-amd64/file-discovery.yml delete mode 100644 audit-specs/baselines/qemu-build-arm64/file-discovery.yml diff --git a/audit-specs/baselines/ami-build-amd64/file-discovery.yml b/audit-specs/baselines/ami-build-amd64/file-discovery.yml deleted file mode 100644 index 1c9c3b0273..0000000000 --- a/audit-specs/baselines/ami-build-amd64/file-discovery.yml +++ /dev/null @@ -1,2 +0,0 @@ -include: - - ../file-discovery.yml diff --git a/audit-specs/baselines/ami-build-arm64/file-discovery.yml b/audit-specs/baselines/ami-build-arm64/file-discovery.yml deleted file mode 100644 index 1c9c3b0273..0000000000 --- a/audit-specs/baselines/ami-build-arm64/file-discovery.yml +++ /dev/null @@ -1,2 +0,0 @@ -include: - - ../file-discovery.yml diff --git a/audit-specs/baselines/file-discovery.yml b/audit-specs/baselines/file-discovery.yml index 5ad6bb4f09..16cea1b4df 100644 --- a/audit-specs/baselines/file-discovery.yml +++ b/audit-specs/baselines/file-discovery.yml @@ -1,8 +1,5 @@ -# Shared filesystem discovery policy for supascan validate. -# Each build directory includes this file from its own file-discovery.yml. -# Exceptions below were derived from audit-specs/baselines/baseline.yml -# (AMI arm64 capture) and Ubuntu defaults. Directory modes and setuid bits -# are not in that capture, so the first run on a built image may report more. +# Filesystem discovery policy for supascan validate. +# Exceptions come from baseline.yml (AMI arm64) and Ubuntu defaults. roots: [/etc, /usr/local, /opt, /data, /var/lib] file_modes: ["0644", "0640", "0600", "0440", "0755"] dir_modes: ["0755", "0750", "0700"] @@ -31,95 +28,49 @@ setuid: - /usr/sbin/pam_extrausers_chkpwd - /usr/sbin/unix_chkpwd exceptions: - - path: /var/local - reason: Ubuntu base default or cloud-init state - - path: /var/mail - reason: Ubuntu base default or cloud-init state - - path: /var/log/btmp - reason: Ubuntu base default or cloud-init state - - path: /var/log/lastlog - reason: Ubuntu base default or cloud-init state - - path: /var/log/wtmp - reason: Ubuntu base default or cloud-init state - - path: /var/lib/cloud/instances/** - reason: Ubuntu base default or cloud-init state - - path: /usr/local/kong/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /usr/local/openresty/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/vector/examples/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/pgbouncer-custom/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/postgresql-custom/extension-custom-scripts/** - reason: Group-writable or non-allowlisted modes in baseline.yml - - path: /etc/envoy/envoy.yaml - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/envoy/lds.yaml - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/gotrue.env - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.conf.default - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/kong/kong.logrotate - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres-auth.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres-csv.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-postgres.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/logrotate.d/logrotate-walg.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/machine-id - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/pgbouncer/userlist.txt - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/custom-overrides.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/generated-optimizations.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/read-replica.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/supautils.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql-custom/wal-g.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgresql/pg_hba.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgrest/base.conf - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/postgrest/merge.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/ssl/adminapi/server.crt - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/ssl/adminapi/server.key - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /etc/wal-g/config.json - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/envoy - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/envoy-hot-restarter.py - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /opt/start-envoy.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/lib/systemd/system/kong.service - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/kong - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/lapis - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/luarocks - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/luarocks-admin - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/project-init.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/bin/systemd-networkd-check-and-fix.sh - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /usr/local/etc/luarocks/config-5.1.lua - reason: Group-writable or non-allowlisted mode in baseline.yml - - path: /var/lib/cloud/scripts/per-boot/supaboot.sh - reason: Group-writable or non-allowlisted mode in baseline.yml + - /var/local + - /var/mail + - /var/log/btmp + - /var/log/lastlog + - /var/log/wtmp + - /var/lib/cloud/instances/** + - /usr/local/kong/** + - /usr/local/openresty/** + - /etc/vector/examples/** + - /etc/pgbouncer-custom/** + - /etc/postgresql-custom/extension-custom-scripts/** + - /etc/envoy/envoy.yaml + - /etc/envoy/lds.yaml + - /etc/gotrue.env + - /etc/kong/kong.conf + - /etc/kong/kong.conf.default + - /etc/kong/kong.logrotate + - /etc/logrotate.d/logrotate-postgres-auth.conf + - /etc/logrotate.d/logrotate-postgres-csv.conf + - /etc/logrotate.d/logrotate-postgres.conf + - /etc/logrotate.d/logrotate-walg.conf + - /etc/machine-id + - /etc/pgbouncer/userlist.txt + - /etc/postgresql-custom/custom-overrides.conf + - /etc/postgresql-custom/generated-optimizations.conf + - /etc/postgresql-custom/read-replica.conf + - /etc/postgresql-custom/supautils.conf + - /etc/postgresql-custom/wal-g.conf + - /etc/postgresql/pg_hba.conf + - /etc/postgrest/base.conf + - /etc/postgrest/merge.sh + - /etc/ssl/adminapi/server.crt + - /etc/ssl/adminapi/server.key + - /etc/wal-g/config.json + - /opt/envoy + - /opt/envoy-hot-restarter.py + - /opt/start-envoy.sh + - /usr/lib/systemd/system/kong.service + - /usr/local/bin/kong + - /usr/local/bin/lapis + - /usr/local/bin/luarocks + - /usr/local/bin/luarocks-admin + - /usr/local/bin/project-init.sh + - /usr/local/bin/systemd-networkd-check-and-fix.sh + - /usr/local/etc/luarocks/config-5.1.lua + - /var/lib/cloud/scripts/per-boot/supaboot.sh diff --git a/audit-specs/baselines/qemu-build-amd64/file-discovery.yml b/audit-specs/baselines/qemu-build-amd64/file-discovery.yml deleted file mode 100644 index 1c9c3b0273..0000000000 --- a/audit-specs/baselines/qemu-build-amd64/file-discovery.yml +++ /dev/null @@ -1,2 +0,0 @@ -include: - - ../file-discovery.yml diff --git a/audit-specs/baselines/qemu-build-arm64/file-discovery.yml b/audit-specs/baselines/qemu-build-arm64/file-discovery.yml deleted file mode 100644 index 1c9c3b0273..0000000000 --- a/audit-specs/baselines/qemu-build-arm64/file-discovery.yml +++ /dev/null @@ -1,2 +0,0 @@ -include: - - ../file-discovery.yml diff --git a/nix/packages/supascan/README.md b/nix/packages/supascan/README.md index 4fe0b0b327..2c2d51d37f 100644 --- a/nix/packages/supascan/README.md +++ b/nix/packages/supascan/README.md @@ -8,7 +8,6 @@ A comprehensive system auditing toolkit for generating and validating baseline s - **`supascan genspec`** - Generate complete machine baseline (packages, services, configs, users, groups, mounts, kernel params) - **`supascan validate`** - Validate machines against baseline specifications with critical/advisory categorization -- **`supascan discover`** - Scan the filesystem for setuid files, world or group-writable paths, orphaned owner ids, and modes outside an allowlist - **`supascan split`** - Split a monolithic baseline into separate section files for easier auditing **Use Cases:** @@ -58,14 +57,7 @@ sudo nix run .#supascan -- validate --format documentation /path/to/baselines ### Filesystem discovery -`validate` also runs `discover` when the baselines directory has a `file-discovery.yml`. goss only checks listed paths, so discovery walks the filesystem and reports setuid or setgid files outside `setuid`, world-writable paths other than sticky directories, group-writable paths, owner or group ids with no passwd or group entry, and modes outside `file_modes` and `dir_modes` under `roots`. Paths in `exceptions` are skipped. An entry ending in `/**` covers the whole subtree. `include: [../file-discovery.yml]` merges another policy file, resolved relative to the including file. - -```bash -sudo supascan discover audit-specs/baselines/ami-build-amd64/file-discovery.yml - -# Scan an extracted image -sudo supascan discover --root /mnt/image policy.yml -``` +`validate` also runs `discover` when `file-discovery.yml` is in the baselines directory or its parent. It reports setuid or setgid files, world-writable and group-writable paths, unknown owner or group ids, and modes outside the allowlist, skipping `exceptions`. An entry ending in `/**` covers a subtree. Use `--root` to scan an extracted image. ## Installation diff --git a/nix/packages/supascan/cmd/supascan/discover.go b/nix/packages/supascan/cmd/supascan/discover.go index b7250a4685..ac586fa688 100644 --- a/nix/packages/supascan/cmd/supascan/discover.go +++ b/nix/packages/supascan/cmd/supascan/discover.go @@ -14,20 +14,10 @@ var discoverRoot string var discoverCmd = &cobra.Command{ Use: "discover ", Short: "Scan the filesystem for permission and ownership drift", - Long: `Walk the filesystem and report paths that goss specs cannot cover because -they are not listed: setuid or setgid files outside the allowlist, world-writable -paths other than sticky directories, group-writable paths without an exception, -owner or group ids with no passwd or group entry, and modes outside the allowlist -under the policy roots. - -Exits non-zero when anything is reported. Run as root to read every directory. - -Examples: - sudo supascan discover audit-specs/baselines/ami-build-amd64/file-discovery.yml - - # Scan an extracted image - sudo supascan discover --root /mnt/image policy.yml -`, + Long: `Walk the filesystem and report setuid or setgid files outside the allowlist, +world-writable paths other than sticky directories, group-writable paths, owner or +group ids with no passwd or group entry, and modes outside the allowlist under the +policy roots. Exits non-zero when anything is reported. Run as root.`, Args: cobra.ExactArgs(1), RunE: runDiscover, } @@ -40,27 +30,18 @@ func init() { func runDiscover(cmd *cobra.Command, args []string) error { policy, err := discovery.LoadPolicy(args[0]) if err != nil { - return fmt.Errorf("failed to load policy: %w", err) + return err } - - res, err := discovery.Scan(context.Background(), discoverRoot, policy) + findings, err := discovery.Scan(context.Background(), discoverRoot, policy) if err != nil { - return fmt.Errorf("scan failed: %w", err) + return err } - - out := cmd.OutOrStdout() - for _, e := range res.Errors { - fmt.Fprintf(out, "warning: %s\n", e) - } - for _, f := range res.Findings { - fmt.Fprintln(out, f) + for _, f := range findings { + fmt.Fprintln(cmd.OutOrStdout(), f) } - fmt.Fprintf(out, "%d finding(s) in %d entries\n", len(res.Findings), res.Scanned) - - if len(res.Findings) > 0 { + if len(findings) > 0 { cmd.SilenceUsage = true - cmd.SilenceErrors = true - return fmt.Errorf("%d finding(s)", len(res.Findings)) + return fmt.Errorf("%d finding(s)", len(findings)) } return nil } diff --git a/nix/packages/supascan/internal/discovery/discovery.go b/nix/packages/supascan/internal/discovery/discovery.go index bc84be8973..3bad5a4aa1 100644 --- a/nix/packages/supascan/internal/discovery/discovery.go +++ b/nix/packages/supascan/internal/discovery/discovery.go @@ -7,7 +7,7 @@ import ( "io/fs" "os" "path/filepath" - "sort" + "slices" "strconv" "strings" "syscall" @@ -15,103 +15,26 @@ import ( "gopkg.in/yaml.v3" ) -var skippedTrees = []string{ - "/proc", - "/sys", - "/dev", - "/run", - "/tmp", - "/var/tmp", - "/nix/store", -} - -type Exception struct { - Path string `yaml:"path"` - Reason string `yaml:"reason,omitempty"` -} +var skippedTrees = []string{"/proc", "/sys", "/dev", "/run", "/tmp", "/var/tmp", "/nix/store"} type Policy struct { - Roots []string `yaml:"roots"` - FileModes []string `yaml:"file_modes"` - DirModes []string `yaml:"dir_modes"` - Setuid []string `yaml:"setuid"` - Exceptions []Exception `yaml:"exceptions"` -} - -type Finding struct { - Path string - Detail string -} - -func (f Finding) String() string { - return f.Path + ": " + f.Detail -} - -type Result struct { - Findings []Finding - Scanned int - Errors []string + Roots []string `yaml:"roots"` + FileModes []string `yaml:"file_modes"` + DirModes []string `yaml:"dir_modes"` + Setuid []string `yaml:"setuid"` + Exceptions []string `yaml:"exceptions"` } func LoadPolicy(path string) (*Policy, error) { - return loadPolicy(path, map[string]bool{}) -} - -func loadPolicy(path string, active map[string]bool) (*Policy, error) { - abs, err := filepath.Abs(path) - if err != nil { - return nil, err - } - if active[abs] { - return nil, fmt.Errorf("include cycle at %s", path) - } - active[abs] = true - defer delete(active, abs) - data, err := os.ReadFile(path) if err != nil { return nil, err } - var raw struct { - Include []string `yaml:"include"` - Policy `yaml:",inline"` - } - if err := yaml.Unmarshal(data, &raw); err != nil { + var p Policy + if err := yaml.Unmarshal(data, &p); err != nil { return nil, fmt.Errorf("parse %s: %w", path, err) } - - merged := &Policy{} - for _, inc := range raw.Include { - base, err := loadPolicy(filepath.Join(filepath.Dir(path), inc), active) - if err != nil { - return nil, err - } - merged.merge(base) - } - merged.merge(&raw.Policy) - - for _, m := range append(append([]string{}, merged.FileModes...), merged.DirModes...) { - if _, err := strconv.ParseUint(m, 8, 32); err != nil { - return nil, fmt.Errorf("invalid mode %q in %s", m, path) - } - } - return merged, nil -} - -func (p *Policy) merge(o *Policy) { - p.Roots = append(p.Roots, o.Roots...) - p.FileModes = append(p.FileModes, o.FileModes...) - p.DirModes = append(p.DirModes, o.DirModes...) - p.Setuid = append(p.Setuid, o.Setuid...) - p.Exceptions = append(p.Exceptions, o.Exceptions...) -} - -type entry struct { - path string - mode fs.FileMode - isDir bool - uid uint32 - gid uint32 + return &p, nil } func under(path, tree string) bool { @@ -120,193 +43,112 @@ func under(path, tree string) bool { func (p *Policy) excepted(path string) bool { for _, e := range p.Exceptions { - if base, ok := strings.CutSuffix(e.Path, "/**"); ok { + if base, ok := strings.CutSuffix(e, "/**"); ok { if under(path, base) { return true } - } else if path == e.Path { + } else if path == e { return true } } return false } -func modeSet(values []string) map[fs.FileMode]bool { - set := make(map[fs.FileMode]bool, len(values)) - for _, v := range values { - n, _ := strconv.ParseUint(v, 8, 32) - set[fs.FileMode(n)] = true - } - return set +func allowed(modes []string, perm fs.FileMode) bool { + return slices.ContainsFunc(modes, func(m string) bool { + n, err := strconv.ParseUint(m, 8, 32) + return err == nil && fs.FileMode(n) == perm + }) } -func parseIDs(path string) (map[uint32]bool, error) { +func readIDs(path string) (map[uint32]bool, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() - ids := make(map[uint32]bool) + ids := map[uint32]bool{} sc := bufio.NewScanner(f) for sc.Scan() { - fields := strings.Split(sc.Text(), ":") - if len(fields) < 3 { - continue - } - if n, err := strconv.ParseUint(fields[2], 10, 32); err == nil { - ids[uint32(n)] = true + if fields := strings.Split(sc.Text(), ":"); len(fields) >= 3 { + if n, err := strconv.ParseUint(fields[2], 10, 32); err == nil { + ids[uint32(n)] = true + } } } return ids, sc.Err() } -// Scan walks root and reports entries that break the policy. Paths in the -// result are relative to root with a leading slash, so a mounted image can -// be scanned in place. -func Scan(ctx context.Context, root string, p *Policy) (*Result, error) { - root = filepath.Clean(root) - users, err := parseIDs(filepath.Join(root, "etc/passwd")) +// Scan walks root and returns "path: problem" lines. Paths are relative to +// root with a leading slash, so an extracted image can be scanned in place. +func Scan(ctx context.Context, root string, p *Policy) ([]string, error) { + users, err := readIDs(filepath.Join(root, "etc/passwd")) if err != nil { - return nil, fmt.Errorf("read passwd: %w", err) + return nil, err } - groups, err := parseIDs(filepath.Join(root, "etc/group")) + groups, err := readIDs(filepath.Join(root, "etc/group")) if err != nil { - return nil, fmt.Errorf("read group: %w", err) - } - - res := &Result{} - toPath := func(real string) string { - rel, err := filepath.Rel(root, real) - if err != nil || rel == "." { - return "/" - } - return "/" + filepath.ToSlash(rel) + return nil, err } + var findings []string err = filepath.WalkDir(root, func(real string, d fs.DirEntry, walkErr error) error { if ctx.Err() != nil { return ctx.Err() } - path := toPath(real) - for _, t := range skippedTrees { - if under(path, t) { - if d != nil && d.IsDir() { - return filepath.SkipDir - } - return nil - } + path := "/" + if rel, _ := filepath.Rel(root, real); rel != "." { + path = "/" + filepath.ToSlash(rel) } - if walkErr != nil { - if !os.IsNotExist(walkErr) { - res.Errors = append(res.Errors, fmt.Sprintf("%s: %v", path, walkErr)) - } + if slices.ContainsFunc(skippedTrees, func(t string) bool { return under(path, t) }) { if d != nil && d.IsDir() { return filepath.SkipDir } return nil } - if !d.IsDir() && !d.Type().IsRegular() { + if walkErr != nil || (!d.IsDir() && !d.Type().IsRegular()) || p.excepted(path) { return nil } info, err := d.Info() if err != nil { - if !os.IsNotExist(err) { - res.Errors = append(res.Errors, fmt.Sprintf("%s: %v", path, err)) - } return nil } - st, ok := info.Sys().(*syscall.Stat_t) - if !ok { - return fmt.Errorf("no stat data for %s", path) + st := info.Sys().(*syscall.Stat_t) + for _, problem := range p.check(path, info.Mode(), d.IsDir(), st.Uid, st.Gid, users, groups) { + findings = append(findings, path+": "+problem) } - res.Scanned++ - res.Findings = append(res.Findings, p.check(entry{ - path: path, - mode: info.Mode(), - isDir: d.IsDir(), - uid: st.Uid, - gid: st.Gid, - }, users, groups)...) return nil }) - if err != nil { - return res, err - } - sort.Slice(res.Findings, func(i, j int) bool { - if res.Findings[i].Path != res.Findings[j].Path { - return res.Findings[i].Path < res.Findings[j].Path - } - return res.Findings[i].Detail < res.Findings[j].Detail - }) - return res, nil + return findings, err } -func (p *Policy) check(e entry, users, groups map[uint32]bool) []Finding { - if p.excepted(e.path) { - return nil - } - var out []Finding - add := func(format string, args ...any) { - out = append(out, Finding{Path: e.path, Detail: fmt.Sprintf(format, args...)}) - } - - perm := e.mode.Perm() - sticky := e.isDir && e.mode&fs.ModeSticky != 0 - if !e.isDir && e.mode&(fs.ModeSetuid|fs.ModeSetgid) != 0 && !p.isSetuidAllowed(e.path) { - add("setuid or setgid file %04o not in setuid list", unixMode(e.mode)) +func (p *Policy) check(path string, mode fs.FileMode, isDir bool, uid, gid uint32, users, groups map[uint32]bool) []string { + var out []string + perm := mode.Perm() + sticky := isDir && mode&fs.ModeSticky != 0 + if !isDir && mode&(fs.ModeSetuid|fs.ModeSetgid) != 0 && !slices.Contains(p.Setuid, path) { + out = append(out, "setuid or setgid file not in setuid list") } if perm&0o002 != 0 && !sticky { - add("world-writable %04o", unixMode(e.mode)) + out = append(out, fmt.Sprintf("world-writable %04o", perm)) } if perm&0o020 != 0 && !sticky { - add("group-writable %04o", unixMode(e.mode)) + out = append(out, fmt.Sprintf("group-writable %04o", perm)) } - if !users[e.uid] { - add("owner id %d has no passwd entry", e.uid) + if !users[uid] { + out = append(out, fmt.Sprintf("owner id %d has no passwd entry", uid)) } - if !groups[e.gid] { - add("group id %d has no group entry", e.gid) + if !groups[gid] { + out = append(out, fmt.Sprintf("group id %d has no group entry", gid)) } - if p.inRoots(e.path) { - allowed := p.FileModes - if e.isDir { - allowed = p.DirModes + if slices.ContainsFunc(p.Roots, func(r string) bool { return under(path, r) }) { + modes := p.FileModes + if isDir { + modes = p.DirModes } - if !modeSet(allowed)[perm] { - add("mode %04o not in allowlist", perm) + if !allowed(modes, perm) { + out = append(out, fmt.Sprintf("mode %04o not in allowlist", perm)) } } return out } - -func (p *Policy) isSetuidAllowed(path string) bool { - for _, s := range p.Setuid { - if s == path { - return true - } - } - return false -} - -func (p *Policy) inRoots(path string) bool { - for _, r := range p.Roots { - if under(path, r) { - return true - } - } - return false -} - -func unixMode(m fs.FileMode) uint32 { - out := uint32(m.Perm()) - if m&fs.ModeSetuid != 0 { - out |= 0o4000 - } - if m&fs.ModeSetgid != 0 { - out |= 0o2000 - } - if m&fs.ModeSticky != 0 { - out |= 0o1000 - } - return out -} diff --git a/nix/packages/supascan/internal/discovery/discovery_test.go b/nix/packages/supascan/internal/discovery/discovery_test.go index 221652aef7..f4d95a7296 100644 --- a/nix/packages/supascan/internal/discovery/discovery_test.go +++ b/nix/packages/supascan/internal/discovery/discovery_test.go @@ -11,210 +11,85 @@ import ( "testing" ) -func testPolicy() *Policy { - return &Policy{ - Roots: []string{"/etc", "/opt"}, - FileModes: []string{"0644", "0600"}, +func TestCheck(t *testing.T) { + p := &Policy{ + Roots: []string{"/etc"}, + FileModes: []string{"0644"}, DirModes: []string{"0755"}, Setuid: []string{"/usr/bin/allowed"}, - Exceptions: []Exception{ - {Path: "/etc/loose.conf"}, - {Path: "/opt/vendor/**"}, - }, - } -} - -func details(findings []Finding) string { - var parts []string - for _, f := range findings { - parts = append(parts, f.String()) } - return strings.Join(parts, "\n") -} - -func TestCheck(t *testing.T) { known := map[uint32]bool{0: true} tests := []struct { name string - entry entry - want []string + path string + mode fs.FileMode + isDir bool + uid uint32 + want string }{ - {"clean file", entry{path: "/etc/a", mode: 0o644}, nil}, - {"setuid not listed", entry{path: "/usr/bin/x", mode: 0o755 | fs.ModeSetuid}, []string{"setuid or setgid file 4755"}}, - {"setgid not listed", entry{path: "/usr/bin/x", mode: 0o755 | fs.ModeSetgid}, []string{"setuid or setgid file 2755"}}, - {"setuid listed", entry{path: "/usr/bin/allowed", mode: 0o755 | fs.ModeSetuid}, nil}, - {"world-writable file", entry{path: "/srv/x", mode: 0o666}, []string{"world-writable 0666", "group-writable 0666"}}, - {"sticky world-writable dir", entry{path: "/srv/t", mode: 0o777 | fs.ModeSticky, isDir: true}, nil}, - {"world-writable dir", entry{path: "/srv/t", mode: 0o777, isDir: true}, []string{"world-writable 0777", "group-writable 0777"}}, - {"group-writable file", entry{path: "/srv/x", mode: 0o664}, []string{"group-writable 0664"}}, - {"group-writable excepted", entry{path: "/etc/loose.conf", mode: 0o664}, nil}, - {"subtree excepted", entry{path: "/opt/vendor/deep/bin", mode: 0o775}, nil}, - {"subtree root excepted", entry{path: "/opt/vendor", mode: 0o775, isDir: true}, nil}, - {"sibling of subtree", entry{path: "/opt/vendor2/bin", mode: 0o755}, []string{"mode 0755 not in allowlist"}}, - {"orphan uid", entry{path: "/srv/x", mode: 0o644, uid: 42}, []string{"owner id 42 has no passwd entry"}}, - {"orphan gid", entry{path: "/srv/x", mode: 0o644, gid: 43}, []string{"group id 43 has no group entry"}}, - {"mode outside allowlist", entry{path: "/etc/x", mode: 0o640}, []string{"mode 0640 not in allowlist"}}, - {"mode outside roots", entry{path: "/srv/x", mode: 0o640}, nil}, - {"dir mode outside allowlist", entry{path: "/etc/d", mode: 0o700, isDir: true}, []string{"mode 0700 not in allowlist"}}, - {"dir mode allowed", entry{path: "/etc/d", mode: 0o755, isDir: true}, nil}, + {"clean", "/etc/a", 0o644, false, 0, ""}, + {"setuid not listed", "/usr/bin/x", 0o755 | fs.ModeSetuid, false, 0, "setuid"}, + {"setgid not listed", "/usr/bin/x", 0o755 | fs.ModeSetgid, false, 0, "setuid"}, + {"setuid listed", "/usr/bin/allowed", 0o755 | fs.ModeSetuid, false, 0, ""}, + {"world-writable", "/srv/x", 0o646, false, 0, "world-writable"}, + {"sticky dir", "/srv/t", 0o777 | fs.ModeSticky, true, 0, ""}, + {"group-writable", "/srv/x", 0o664, false, 0, "group-writable"}, + {"orphan uid", "/srv/x", 0o644, false, 42, "owner id 42"}, + {"mode outside allowlist", "/etc/x", 0o640, false, 0, "not in allowlist"}, + {"mode outside roots", "/srv/x", 0o640, false, 0, ""}, + {"dir mode", "/etc/d", 0o700, true, 0, "not in allowlist"}, } - p := testPolicy() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got := p.check(tt.entry, known, known) - if len(got) != len(tt.want) { - t.Fatalf("got %d findings, want %d:\n%s", len(got), len(tt.want), details(got)) - } - for i, w := range tt.want { - if !strings.Contains(got[i].Detail, w) { - t.Errorf("finding %d = %q, want it to contain %q", i, got[i].Detail, w) - } + got := strings.Join(p.check(tt.path, tt.mode, tt.isDir, tt.uid, 0, known, known), ";") + if tt.want == "" && got != "" || !strings.Contains(got, tt.want) { + t.Errorf("got %q, want %q", got, tt.want) } }) } } -func TestLoadPolicy(t *testing.T) { - dir := t.TempDir() - good := filepath.Join(dir, "good.yml") - os.WriteFile(good, []byte("roots: [/etc]\nfile_modes: ['0644']\ndir_modes: ['0755']\nsetuid: [/usr/bin/su]\nexceptions:\n - path: /etc/x\n reason: test\n"), 0o644) - p, err := LoadPolicy(good) - if err != nil { - t.Fatal(err) - } - if len(p.Exceptions) != 1 || p.Exceptions[0].Reason != "test" || p.Setuid[0] != "/usr/bin/su" { - t.Errorf("unexpected policy: %+v", p) - } - - bad := filepath.Join(dir, "bad.yml") - os.WriteFile(bad, []byte("file_modes: ['rw-r--r--']\n"), 0o644) - if _, err := LoadPolicy(bad); err == nil { - t.Error("expected error for invalid mode") - } - if _, err := LoadPolicy(filepath.Join(dir, "missing.yml")); err == nil { - t.Error("expected error for missing file") - } -} - -func TestLoadPolicyInclude(t *testing.T) { - dir := t.TempDir() - os.MkdirAll(filepath.Join(dir, "build"), 0o755) - os.WriteFile(filepath.Join(dir, "common.yml"), []byte("roots: [/etc]\nfile_modes: ['0644']\nsetuid: [/usr/bin/su]\nexceptions:\n - path: /etc/a\n"), 0o644) - child := filepath.Join(dir, "build", "policy.yml") - os.WriteFile(child, []byte("include: [../common.yml]\nsetuid: [/usr/bin/sudo]\nexceptions:\n - path: /etc/b\n"), 0o644) - p, err := LoadPolicy(child) - if err != nil { - t.Fatal(err) - } - if len(p.Roots) != 1 || len(p.FileModes) != 1 || len(p.Setuid) != 2 || len(p.Exceptions) != 2 { - t.Errorf("unexpected merge: %+v", p) - } - if !p.excepted("/etc/a") || !p.excepted("/etc/b") || !p.isSetuidAllowed("/usr/bin/sudo") { - t.Errorf("merged policy missing entries: %+v", p) - } -} - -func TestLoadPolicyIncludeCycle(t *testing.T) { - dir := t.TempDir() - a, b := filepath.Join(dir, "a.yml"), filepath.Join(dir, "b.yml") - os.WriteFile(a, []byte("include: [b.yml]\n"), 0o644) - os.WriteFile(b, []byte("include: [a.yml]\n"), 0o644) - if _, err := LoadPolicy(a); err == nil || !strings.Contains(err.Error(), "cycle") { - t.Errorf("expected include cycle error, got %v", err) - } -} - -func ownerOf(t *testing.T, path string) (int, int) { - t.Helper() - info, err := os.Stat(path) - if err != nil { - t.Fatal(err) - } - st := info.Sys().(*syscall.Stat_t) - return int(st.Uid), int(st.Gid) -} - -func writeIDs(t *testing.T, root string, uid, gid int) { - t.Helper() - etc := filepath.Join(root, "etc") - if err := os.MkdirAll(etc, 0o755); err != nil { - t.Fatal(err) +func TestExcepted(t *testing.T) { + p := &Policy{Exceptions: []string{"/etc/a", "/opt/v/**"}} + for path, want := range map[string]bool{"/etc/a": true, "/etc/ab": false, "/opt/v": true, "/opt/v/x/y": true, "/opt/vx": false} { + if p.excepted(path) != want { + t.Errorf("excepted(%q) = %v, want %v", path, !want, want) + } } - os.WriteFile(filepath.Join(etc, "passwd"), []byte(fmt.Sprintf("me:x:%d:%d:::\n", uid, gid)), 0o644) - os.WriteFile(filepath.Join(etc, "group"), []byte(fmt.Sprintf("me:x:%d:\n", gid)), 0o644) } func TestScan(t *testing.T) { root := t.TempDir() - uid, gid := ownerOf(t, root) - writeIDs(t, root, uid, gid) - for path, mode := range map[string]fs.FileMode{ - "etc/ok.conf": 0o644, - "etc/loose.conf": 0o664, - "etc/bad.conf": 0o664, - "srv/suid": 0o755 | fs.ModeSetuid, - "srv/world": 0o666, - "tmp/ignored": 0o666, - "nix/store/ignored": 0o666, - "usr/bin/allowed": 0o755 | fs.ModeSetuid, - "usr/bin/not-listed": 0o755 | fs.ModeSetuid, - } { - full := filepath.Join(root, path) + info, _ := os.Stat(root) + st := info.Sys().(*syscall.Stat_t) + etc := filepath.Join(root, "etc") + os.MkdirAll(etc, 0o755) + writeID := func(name string, id uint32) { + line := fmt.Sprintf("me:x:%d:\n", id) + os.WriteFile(filepath.Join(etc, name), []byte(line), 0o644) + } + writeID("passwd", st.Uid) + writeID("group", st.Gid) + for name, mode := range map[string]fs.FileMode{"etc/loose": 0o664, "etc/skip": 0o664, "srv/suid": 0o755 | fs.ModeSetuid, "tmp/ignored": 0o666} { + full := filepath.Join(root, name) os.MkdirAll(filepath.Dir(full), 0o755) - if err := os.WriteFile(full, []byte("x"), 0o600); err != nil { - t.Fatal(err) - } - if err := os.Chmod(full, mode); err != nil { - t.Fatal(err) - } + os.WriteFile(full, nil, 0o600) + os.Chmod(full, mode) } - os.Symlink("/etc/ok.conf", filepath.Join(root, "srv/link")) - p := testPolicy() - p.Roots = []string{"/etc"} - res, err := Scan(context.Background(), root, p) + got, err := Scan(context.Background(), root, &Policy{Exceptions: []string{"/etc/skip"}}) if err != nil { t.Fatal(err) } - got := details(res.Findings) - for _, want := range []string{ - "/etc/bad.conf: group-writable 0664", - "/etc/bad.conf: mode 0664 not in allowlist", - "/srv/suid: setuid or setgid file 4755", - "/srv/world: world-writable 0666", - "/usr/bin/not-listed: setuid or setgid file 4755", - } { - if !strings.Contains(got, want) { - t.Errorf("missing finding %q in:\n%s", want, got) + text := strings.Join(got, "\n") + for _, want := range []string{"/etc/loose: group-writable", "/srv/suid: setuid"} { + if !strings.Contains(text, want) { + t.Errorf("missing %q in:\n%s", want, text) } } - for _, unwanted := range []string{"/etc/ok.conf", "/etc/loose.conf", "/tmp/", "/nix/store", "/usr/bin/allowed", "srv/link"} { - if strings.Contains(got, unwanted) { - t.Errorf("unexpected finding for %q in:\n%s", unwanted, got) + for _, unwanted := range []string{"/etc/skip", "/tmp"} { + if strings.Contains(text, unwanted) { + t.Errorf("unexpected %q in:\n%s", unwanted, text) } } - if res.Scanned == 0 { - t.Error("expected scanned entries") - } -} - -func TestScanOrphanIDs(t *testing.T) { - root := t.TempDir() - uid, gid := ownerOf(t, root) - writeIDs(t, root, uid+1000, gid+1000) - os.WriteFile(filepath.Join(root, "file"), []byte("x"), 0o644) - res, err := Scan(context.Background(), root, &Policy{}) - if err != nil { - t.Fatal(err) - } - got := details(res.Findings) - if !strings.Contains(got, "/file: owner id") || !strings.Contains(got, "/file: group id") { - t.Errorf("expected orphan id findings, got:\n%s", got) - } -} - -func TestScanMissingPasswd(t *testing.T) { - if _, err := Scan(context.Background(), t.TempDir(), &Policy{}); err == nil { - t.Error("expected error without etc/passwd") - } } diff --git a/nix/packages/supascan/internal/validator/validator.go b/nix/packages/supascan/internal/validator/validator.go index 17a7df6132..13e10c4af6 100644 --- a/nix/packages/supascan/internal/validator/validator.go +++ b/nix/packages/supascan/internal/validator/validator.go @@ -259,34 +259,40 @@ func (v *Validator) runSpec(specFile, category, gossPath string) SpecResult { return result } -// runDiscovery re-executes supascan under sudo so the walk can read every -// directory, the same way goss specs run. +// runDiscovery re-executes supascan under sudo, like goss specs, so the walk +// can read every directory. The policy comes from the baselines directory or +// its parent. func (v *Validator) runDiscovery() SpecResult { result := SpecResult{Spec: "file-discovery", Category: "critical"} - policyPath := filepath.Join(v.opts.BaselinesDir, DiscoveryPolicy) - if _, err := os.Stat(policyPath); os.IsNotExist(err) { - result.Skipped = true - return result + policy := "" + for _, dir := range []string{v.opts.BaselinesDir, filepath.Dir(v.opts.BaselinesDir)} { + if p := filepath.Join(dir, DiscoveryPolicy); fileExists(p) { + policy = p + break + } } - self, err := os.Executable() - if err != nil { + if policy == "" || err != nil { + result.Skipped = policy == "" result.Error = err return result } - cmd := exec.Command("sudo", self, "discover", policyPath) - var stdout, stderr bytes.Buffer - cmd.Stdout = &stdout - cmd.Stderr = &stderr - err = cmd.Run() - result.Output = stdout.String() + stderr.String() - result.Error = err - result.Passed = err == nil + var out bytes.Buffer + cmd := exec.Command("sudo", self, "discover", policy) + cmd.Stdout, cmd.Stderr = &out, &out + result.Error = cmd.Run() + result.Passed = result.Error == nil + result.Output = out.String() return result } +func fileExists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + func (v *Validator) printSpecResult(r SpecResult) { if r.Skipped { fmt.Printf(" ⊘ %s: skipped (file not found)\n", r.Spec) diff --git a/nix/packages/supascan/internal/validator/validator_test.go b/nix/packages/supascan/internal/validator/validator_test.go index 98dfa4f344..8bd379f9f3 100644 --- a/nix/packages/supascan/internal/validator/validator_test.go +++ b/nix/packages/supascan/internal/validator/validator_test.go @@ -1,6 +1,7 @@ package validator import ( + "path/filepath" "testing" ) @@ -103,12 +104,8 @@ func TestResultCounts(t *testing.T) { } func TestRunDiscoverySkippedWithoutPolicy(t *testing.T) { - v := New(Options{BaselinesDir: t.TempDir()}) - r := v.runDiscovery() + r := New(Options{BaselinesDir: filepath.Join(t.TempDir(), "build")}).runDiscovery() if !r.Skipped { - t.Error("expected discovery to be skipped when the policy file is missing") - } - if r.Spec != "file-discovery" || r.Category != "critical" { - t.Errorf("unexpected result: %+v", r) + t.Error("expected discovery to be skipped when no policy file exists") } } From ba4f634231ba137689d54018c3ca9f6cd9d34415 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Wed, 25 Nov 2026 03:20:51 +0200 Subject: [PATCH 06/19] refactor(audit-specs): share identical baselines across builds Move the five specs that match in all four build directories up one level. validate looks in the build directory, then its parent. Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- .../ami-build-arm64/files-postgres-config.yml | 97 ------------------- .../ami-build-arm64/files-postgres-data.yml | 19 ---- .../ami-build-arm64/files-security.yml | 77 --------------- .../baselines/ami-build-arm64/files-ssl.yml | 42 -------- .../ami-build-arm64/kernel-param.yml | 11 --- .../files-postgres-config.yml | 0 .../files-postgres-data.yml | 0 .../{ami-build-amd64 => }/files-security.yml | 0 .../{ami-build-amd64 => }/files-ssl.yml | 0 .../{ami-build-amd64 => }/kernel-param.yml | 0 .../files-postgres-config.yml | 97 ------------------- .../qemu-build-amd64/files-postgres-data.yml | 19 ---- .../qemu-build-amd64/files-security.yml | 77 --------------- .../baselines/qemu-build-amd64/files-ssl.yml | 42 -------- .../qemu-build-amd64/kernel-param.yml | 11 --- .../files-postgres-config.yml | 97 ------------------- .../qemu-build-arm64/files-postgres-data.yml | 19 ---- .../qemu-build-arm64/files-security.yml | 77 --------------- .../baselines/qemu-build-arm64/files-ssl.yml | 42 -------- .../qemu-build-arm64/kernel-param.yml | 11 --- .../supascan/internal/validator/validator.go | 25 ++--- .../internal/validator/validator_test.go | 21 ++++ 22 files changed, 34 insertions(+), 750 deletions(-) delete mode 100644 audit-specs/baselines/ami-build-arm64/files-postgres-config.yml delete mode 100644 audit-specs/baselines/ami-build-arm64/files-postgres-data.yml delete mode 100644 audit-specs/baselines/ami-build-arm64/files-security.yml delete mode 100644 audit-specs/baselines/ami-build-arm64/files-ssl.yml delete mode 100644 audit-specs/baselines/ami-build-arm64/kernel-param.yml rename audit-specs/baselines/{ami-build-amd64 => }/files-postgres-config.yml (100%) rename audit-specs/baselines/{ami-build-amd64 => }/files-postgres-data.yml (100%) rename audit-specs/baselines/{ami-build-amd64 => }/files-security.yml (100%) rename audit-specs/baselines/{ami-build-amd64 => }/files-ssl.yml (100%) rename audit-specs/baselines/{ami-build-amd64 => }/kernel-param.yml (100%) delete mode 100644 audit-specs/baselines/qemu-build-amd64/files-postgres-config.yml delete mode 100644 audit-specs/baselines/qemu-build-amd64/files-postgres-data.yml delete mode 100644 audit-specs/baselines/qemu-build-amd64/files-security.yml delete mode 100644 audit-specs/baselines/qemu-build-amd64/files-ssl.yml delete mode 100644 audit-specs/baselines/qemu-build-amd64/kernel-param.yml delete mode 100644 audit-specs/baselines/qemu-build-arm64/files-postgres-config.yml delete mode 100644 audit-specs/baselines/qemu-build-arm64/files-postgres-data.yml delete mode 100644 audit-specs/baselines/qemu-build-arm64/files-security.yml delete mode 100644 audit-specs/baselines/qemu-build-arm64/files-ssl.yml delete mode 100644 audit-specs/baselines/qemu-build-arm64/kernel-param.yml diff --git a/audit-specs/baselines/ami-build-arm64/files-postgres-config.yml b/audit-specs/baselines/ami-build-arm64/files-postgres-config.yml deleted file mode 100644 index 1bdce6e965..0000000000 --- a/audit-specs/baselines/ami-build-arm64/files-postgres-config.yml +++ /dev/null @@ -1,97 +0,0 @@ -# File baseline: postgres-config -# PostgreSQL configuration files for AMI build -# Uses string names for owner/group (not numeric IDs) -file: - # Main PostgreSQL config directory - /etc/postgresql: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0775" - /etc/postgresql/postgresql.conf: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - /etc/postgresql/pg_hba.conf: - exists: true - filetype: file - owner: root - group: postgres - mode: "0664" - /etc/postgresql/pg_ident.conf: - exists: true - filetype: file - owner: root - group: postgres - mode: "0644" - /etc/postgresql/logging.conf: - exists: true - filetype: file - owner: root - group: postgres - mode: "0644" - - # Custom PostgreSQL config directory - /etc/postgresql-custom: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0775" - # Note: platform-defaults.conf, pgsodium_root.key, custom-overrides.conf, and - # generated-optimizations.conf are created at deploy time (not during AMI build) - /etc/postgresql-custom/supautils.conf: - exists: true - filetype: file - owner: postgres - group: postgres - mode: "0664" - /etc/postgresql-custom/conf.d: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0775" - /etc/postgresql-custom/wal-g.conf: - exists: true - filetype: file - owner: postgres - group: postgres - mode: "0664" - /etc/postgresql-custom/read-replica.conf: - exists: true - filetype: file - owner: postgres - group: postgres - mode: "0664" - - # Extension custom scripts directory - /etc/postgresql-custom/extension-custom-scripts: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0775" - /etc/postgresql-custom/extension-custom-scripts/before-create.sql: - exists: true - filetype: file - owner: postgres - group: postgres - mode: "0775" - - # PostgREST config directory - /etc/postgrest: - exists: true - filetype: directory - owner: postgrest - group: postgrest - mode: "0775" - /etc/postgrest/base.conf: - exists: true - filetype: file - owner: postgrest - group: postgrest - mode: "0644" diff --git a/audit-specs/baselines/ami-build-arm64/files-postgres-data.yml b/audit-specs/baselines/ami-build-arm64/files-postgres-data.yml deleted file mode 100644 index 6d1c290097..0000000000 --- a/audit-specs/baselines/ami-build-arm64/files-postgres-data.yml +++ /dev/null @@ -1,19 +0,0 @@ -# File baseline: postgres-data -# PostgreSQL data directory for AMI build -# Uses string names for owner/group (not numeric IDs) -file: - # PostgreSQL data directory - /var/lib/postgresql: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0755" - # Note: /var/lib/postgresql/data is a symlink during AMI build (points to /data/...) - # The actual data directory is created at deploy time - /var/lib/postgresql/data: - exists: true - filetype: symlink - owner: root - group: root - mode: "0777" diff --git a/audit-specs/baselines/ami-build-arm64/files-security.yml b/audit-specs/baselines/ami-build-arm64/files-security.yml deleted file mode 100644 index 6cb4be8d19..0000000000 --- a/audit-specs/baselines/ami-build-arm64/files-security.yml +++ /dev/null @@ -1,77 +0,0 @@ -# File baseline: security -# Critical security-related files for AMI build -# Uses string names for owner/group (not numeric IDs) -file: - # fail2ban configuration directory - /etc/fail2ban: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - /etc/fail2ban/jail.local: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - - # AppArmor - /etc/apparmor.d: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - - # UFW firewall - /etc/ufw: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - /etc/ufw/ufw.conf: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - - # SSH configuration - /etc/ssh/sshd_config: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - - # PAM configuration - /etc/pam.d: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - - # Sudoers - /etc/sudoers: - exists: true - filetype: file - owner: root - group: root - mode: "0440" - /etc/sudoers.d: - exists: true - filetype: directory - owner: root - group: root - mode: "0750" - - # Security limits - /etc/security/limits.conf: - exists: true - filetype: file - owner: root - group: root - mode: "0644" diff --git a/audit-specs/baselines/ami-build-arm64/files-ssl.yml b/audit-specs/baselines/ami-build-arm64/files-ssl.yml deleted file mode 100644 index 693b369f8f..0000000000 --- a/audit-specs/baselines/ami-build-arm64/files-ssl.yml +++ /dev/null @@ -1,42 +0,0 @@ -# File baseline: ssl -# SSL certificate and key directories for AMI build -# Uses string names for owner/group (not numeric IDs) -file: - # System SSL directory - /etc/ssl: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - /etc/ssl/certs: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - /etc/ssl/private: - exists: true - filetype: directory - owner: root - group: postgres - mode: "0750" - /etc/ssl/openssl.cnf: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - # eMudhra's emSign ECC Root CA - G3 is distrusted after intermediate CA key - # compromise (https://emudhra.we-have-a-problem.com/). Removed in Ubuntu - # ca-certificates 20260816ubuntu0.24.04.1. - /usr/share/ca-certificates/mozilla/emSign_ECC_Root_CA_-_G3.crt: - exists: false - /etc/ssl/certs/emSign_ECC_Root_CA_-_G3.pem: - exists: false - /etc/ssl/certs/ca-certificates.crt: - exists: true - contents: - # Start of the emSign ECC Root CA - G3 public key - - "!djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0" - # Note: /etc/ssl/adminapi is created at deploy time, not during AMI build diff --git a/audit-specs/baselines/ami-build-arm64/kernel-param.yml b/audit-specs/baselines/ami-build-arm64/kernel-param.yml deleted file mode 100644 index 23296f9b6f..0000000000 --- a/audit-specs/baselines/ami-build-arm64/kernel-param.yml +++ /dev/null @@ -1,11 +0,0 @@ -# kernel-param baseline for AMI build -# Checks that critical kernel parameters haven't changed -kernel-param: - vm.page-cluster: - value: "3" # kernel default; assert to catch if kernel upgrade changes it - kernel.panic: - value: "10" # set by setup-system.yml - vm.panic_on_oom: - value: "1" # set by setup-system.yml - vm.swappiness: - value: "10" # intentionally lowered from kernel default (60) for DB + zswap diff --git a/audit-specs/baselines/ami-build-amd64/files-postgres-config.yml b/audit-specs/baselines/files-postgres-config.yml similarity index 100% rename from audit-specs/baselines/ami-build-amd64/files-postgres-config.yml rename to audit-specs/baselines/files-postgres-config.yml diff --git a/audit-specs/baselines/ami-build-amd64/files-postgres-data.yml b/audit-specs/baselines/files-postgres-data.yml similarity index 100% rename from audit-specs/baselines/ami-build-amd64/files-postgres-data.yml rename to audit-specs/baselines/files-postgres-data.yml diff --git a/audit-specs/baselines/ami-build-amd64/files-security.yml b/audit-specs/baselines/files-security.yml similarity index 100% rename from audit-specs/baselines/ami-build-amd64/files-security.yml rename to audit-specs/baselines/files-security.yml diff --git a/audit-specs/baselines/ami-build-amd64/files-ssl.yml b/audit-specs/baselines/files-ssl.yml similarity index 100% rename from audit-specs/baselines/ami-build-amd64/files-ssl.yml rename to audit-specs/baselines/files-ssl.yml diff --git a/audit-specs/baselines/ami-build-amd64/kernel-param.yml b/audit-specs/baselines/kernel-param.yml similarity index 100% rename from audit-specs/baselines/ami-build-amd64/kernel-param.yml rename to audit-specs/baselines/kernel-param.yml diff --git a/audit-specs/baselines/qemu-build-amd64/files-postgres-config.yml b/audit-specs/baselines/qemu-build-amd64/files-postgres-config.yml deleted file mode 100644 index 1bdce6e965..0000000000 --- a/audit-specs/baselines/qemu-build-amd64/files-postgres-config.yml +++ /dev/null @@ -1,97 +0,0 @@ -# File baseline: postgres-config -# PostgreSQL configuration files for AMI build -# Uses string names for owner/group (not numeric IDs) -file: - # Main PostgreSQL config directory - /etc/postgresql: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0775" - /etc/postgresql/postgresql.conf: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - /etc/postgresql/pg_hba.conf: - exists: true - filetype: file - owner: root - group: postgres - mode: "0664" - /etc/postgresql/pg_ident.conf: - exists: true - filetype: file - owner: root - group: postgres - mode: "0644" - /etc/postgresql/logging.conf: - exists: true - filetype: file - owner: root - group: postgres - mode: "0644" - - # Custom PostgreSQL config directory - /etc/postgresql-custom: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0775" - # Note: platform-defaults.conf, pgsodium_root.key, custom-overrides.conf, and - # generated-optimizations.conf are created at deploy time (not during AMI build) - /etc/postgresql-custom/supautils.conf: - exists: true - filetype: file - owner: postgres - group: postgres - mode: "0664" - /etc/postgresql-custom/conf.d: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0775" - /etc/postgresql-custom/wal-g.conf: - exists: true - filetype: file - owner: postgres - group: postgres - mode: "0664" - /etc/postgresql-custom/read-replica.conf: - exists: true - filetype: file - owner: postgres - group: postgres - mode: "0664" - - # Extension custom scripts directory - /etc/postgresql-custom/extension-custom-scripts: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0775" - /etc/postgresql-custom/extension-custom-scripts/before-create.sql: - exists: true - filetype: file - owner: postgres - group: postgres - mode: "0775" - - # PostgREST config directory - /etc/postgrest: - exists: true - filetype: directory - owner: postgrest - group: postgrest - mode: "0775" - /etc/postgrest/base.conf: - exists: true - filetype: file - owner: postgrest - group: postgrest - mode: "0644" diff --git a/audit-specs/baselines/qemu-build-amd64/files-postgres-data.yml b/audit-specs/baselines/qemu-build-amd64/files-postgres-data.yml deleted file mode 100644 index 6d1c290097..0000000000 --- a/audit-specs/baselines/qemu-build-amd64/files-postgres-data.yml +++ /dev/null @@ -1,19 +0,0 @@ -# File baseline: postgres-data -# PostgreSQL data directory for AMI build -# Uses string names for owner/group (not numeric IDs) -file: - # PostgreSQL data directory - /var/lib/postgresql: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0755" - # Note: /var/lib/postgresql/data is a symlink during AMI build (points to /data/...) - # The actual data directory is created at deploy time - /var/lib/postgresql/data: - exists: true - filetype: symlink - owner: root - group: root - mode: "0777" diff --git a/audit-specs/baselines/qemu-build-amd64/files-security.yml b/audit-specs/baselines/qemu-build-amd64/files-security.yml deleted file mode 100644 index 6cb4be8d19..0000000000 --- a/audit-specs/baselines/qemu-build-amd64/files-security.yml +++ /dev/null @@ -1,77 +0,0 @@ -# File baseline: security -# Critical security-related files for AMI build -# Uses string names for owner/group (not numeric IDs) -file: - # fail2ban configuration directory - /etc/fail2ban: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - /etc/fail2ban/jail.local: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - - # AppArmor - /etc/apparmor.d: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - - # UFW firewall - /etc/ufw: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - /etc/ufw/ufw.conf: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - - # SSH configuration - /etc/ssh/sshd_config: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - - # PAM configuration - /etc/pam.d: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - - # Sudoers - /etc/sudoers: - exists: true - filetype: file - owner: root - group: root - mode: "0440" - /etc/sudoers.d: - exists: true - filetype: directory - owner: root - group: root - mode: "0750" - - # Security limits - /etc/security/limits.conf: - exists: true - filetype: file - owner: root - group: root - mode: "0644" diff --git a/audit-specs/baselines/qemu-build-amd64/files-ssl.yml b/audit-specs/baselines/qemu-build-amd64/files-ssl.yml deleted file mode 100644 index 693b369f8f..0000000000 --- a/audit-specs/baselines/qemu-build-amd64/files-ssl.yml +++ /dev/null @@ -1,42 +0,0 @@ -# File baseline: ssl -# SSL certificate and key directories for AMI build -# Uses string names for owner/group (not numeric IDs) -file: - # System SSL directory - /etc/ssl: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - /etc/ssl/certs: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - /etc/ssl/private: - exists: true - filetype: directory - owner: root - group: postgres - mode: "0750" - /etc/ssl/openssl.cnf: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - # eMudhra's emSign ECC Root CA - G3 is distrusted after intermediate CA key - # compromise (https://emudhra.we-have-a-problem.com/). Removed in Ubuntu - # ca-certificates 20260816ubuntu0.24.04.1. - /usr/share/ca-certificates/mozilla/emSign_ECC_Root_CA_-_G3.crt: - exists: false - /etc/ssl/certs/emSign_ECC_Root_CA_-_G3.pem: - exists: false - /etc/ssl/certs/ca-certificates.crt: - exists: true - contents: - # Start of the emSign ECC Root CA - G3 public key - - "!djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0" - # Note: /etc/ssl/adminapi is created at deploy time, not during AMI build diff --git a/audit-specs/baselines/qemu-build-amd64/kernel-param.yml b/audit-specs/baselines/qemu-build-amd64/kernel-param.yml deleted file mode 100644 index 23296f9b6f..0000000000 --- a/audit-specs/baselines/qemu-build-amd64/kernel-param.yml +++ /dev/null @@ -1,11 +0,0 @@ -# kernel-param baseline for AMI build -# Checks that critical kernel parameters haven't changed -kernel-param: - vm.page-cluster: - value: "3" # kernel default; assert to catch if kernel upgrade changes it - kernel.panic: - value: "10" # set by setup-system.yml - vm.panic_on_oom: - value: "1" # set by setup-system.yml - vm.swappiness: - value: "10" # intentionally lowered from kernel default (60) for DB + zswap diff --git a/audit-specs/baselines/qemu-build-arm64/files-postgres-config.yml b/audit-specs/baselines/qemu-build-arm64/files-postgres-config.yml deleted file mode 100644 index 1bdce6e965..0000000000 --- a/audit-specs/baselines/qemu-build-arm64/files-postgres-config.yml +++ /dev/null @@ -1,97 +0,0 @@ -# File baseline: postgres-config -# PostgreSQL configuration files for AMI build -# Uses string names for owner/group (not numeric IDs) -file: - # Main PostgreSQL config directory - /etc/postgresql: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0775" - /etc/postgresql/postgresql.conf: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - /etc/postgresql/pg_hba.conf: - exists: true - filetype: file - owner: root - group: postgres - mode: "0664" - /etc/postgresql/pg_ident.conf: - exists: true - filetype: file - owner: root - group: postgres - mode: "0644" - /etc/postgresql/logging.conf: - exists: true - filetype: file - owner: root - group: postgres - mode: "0644" - - # Custom PostgreSQL config directory - /etc/postgresql-custom: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0775" - # Note: platform-defaults.conf, pgsodium_root.key, custom-overrides.conf, and - # generated-optimizations.conf are created at deploy time (not during AMI build) - /etc/postgresql-custom/supautils.conf: - exists: true - filetype: file - owner: postgres - group: postgres - mode: "0664" - /etc/postgresql-custom/conf.d: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0775" - /etc/postgresql-custom/wal-g.conf: - exists: true - filetype: file - owner: postgres - group: postgres - mode: "0664" - /etc/postgresql-custom/read-replica.conf: - exists: true - filetype: file - owner: postgres - group: postgres - mode: "0664" - - # Extension custom scripts directory - /etc/postgresql-custom/extension-custom-scripts: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0775" - /etc/postgresql-custom/extension-custom-scripts/before-create.sql: - exists: true - filetype: file - owner: postgres - group: postgres - mode: "0775" - - # PostgREST config directory - /etc/postgrest: - exists: true - filetype: directory - owner: postgrest - group: postgrest - mode: "0775" - /etc/postgrest/base.conf: - exists: true - filetype: file - owner: postgrest - group: postgrest - mode: "0644" diff --git a/audit-specs/baselines/qemu-build-arm64/files-postgres-data.yml b/audit-specs/baselines/qemu-build-arm64/files-postgres-data.yml deleted file mode 100644 index 6d1c290097..0000000000 --- a/audit-specs/baselines/qemu-build-arm64/files-postgres-data.yml +++ /dev/null @@ -1,19 +0,0 @@ -# File baseline: postgres-data -# PostgreSQL data directory for AMI build -# Uses string names for owner/group (not numeric IDs) -file: - # PostgreSQL data directory - /var/lib/postgresql: - exists: true - filetype: directory - owner: postgres - group: postgres - mode: "0755" - # Note: /var/lib/postgresql/data is a symlink during AMI build (points to /data/...) - # The actual data directory is created at deploy time - /var/lib/postgresql/data: - exists: true - filetype: symlink - owner: root - group: root - mode: "0777" diff --git a/audit-specs/baselines/qemu-build-arm64/files-security.yml b/audit-specs/baselines/qemu-build-arm64/files-security.yml deleted file mode 100644 index 6cb4be8d19..0000000000 --- a/audit-specs/baselines/qemu-build-arm64/files-security.yml +++ /dev/null @@ -1,77 +0,0 @@ -# File baseline: security -# Critical security-related files for AMI build -# Uses string names for owner/group (not numeric IDs) -file: - # fail2ban configuration directory - /etc/fail2ban: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - /etc/fail2ban/jail.local: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - - # AppArmor - /etc/apparmor.d: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - - # UFW firewall - /etc/ufw: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - /etc/ufw/ufw.conf: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - - # SSH configuration - /etc/ssh/sshd_config: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - - # PAM configuration - /etc/pam.d: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - - # Sudoers - /etc/sudoers: - exists: true - filetype: file - owner: root - group: root - mode: "0440" - /etc/sudoers.d: - exists: true - filetype: directory - owner: root - group: root - mode: "0750" - - # Security limits - /etc/security/limits.conf: - exists: true - filetype: file - owner: root - group: root - mode: "0644" diff --git a/audit-specs/baselines/qemu-build-arm64/files-ssl.yml b/audit-specs/baselines/qemu-build-arm64/files-ssl.yml deleted file mode 100644 index 693b369f8f..0000000000 --- a/audit-specs/baselines/qemu-build-arm64/files-ssl.yml +++ /dev/null @@ -1,42 +0,0 @@ -# File baseline: ssl -# SSL certificate and key directories for AMI build -# Uses string names for owner/group (not numeric IDs) -file: - # System SSL directory - /etc/ssl: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - /etc/ssl/certs: - exists: true - filetype: directory - owner: root - group: root - mode: "0755" - /etc/ssl/private: - exists: true - filetype: directory - owner: root - group: postgres - mode: "0750" - /etc/ssl/openssl.cnf: - exists: true - filetype: file - owner: root - group: root - mode: "0644" - # eMudhra's emSign ECC Root CA - G3 is distrusted after intermediate CA key - # compromise (https://emudhra.we-have-a-problem.com/). Removed in Ubuntu - # ca-certificates 20260816ubuntu0.24.04.1. - /usr/share/ca-certificates/mozilla/emSign_ECC_Root_CA_-_G3.crt: - exists: false - /etc/ssl/certs/emSign_ECC_Root_CA_-_G3.pem: - exists: false - /etc/ssl/certs/ca-certificates.crt: - exists: true - contents: - # Start of the emSign ECC Root CA - G3 public key - - "!djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0" - # Note: /etc/ssl/adminapi is created at deploy time, not during AMI build diff --git a/audit-specs/baselines/qemu-build-arm64/kernel-param.yml b/audit-specs/baselines/qemu-build-arm64/kernel-param.yml deleted file mode 100644 index 23296f9b6f..0000000000 --- a/audit-specs/baselines/qemu-build-arm64/kernel-param.yml +++ /dev/null @@ -1,11 +0,0 @@ -# kernel-param baseline for AMI build -# Checks that critical kernel parameters haven't changed -kernel-param: - vm.page-cluster: - value: "3" # kernel default; assert to catch if kernel upgrade changes it - kernel.panic: - value: "10" # set by setup-system.yml - vm.panic_on_oom: - value: "1" # set by setup-system.yml - vm.swappiness: - value: "10" # intentionally lowered from kernel default (60) for DB + zswap diff --git a/nix/packages/supascan/internal/validator/validator.go b/nix/packages/supascan/internal/validator/validator.go index 13e10c4af6..02c10bedca 100644 --- a/nix/packages/supascan/internal/validator/validator.go +++ b/nix/packages/supascan/internal/validator/validator.go @@ -223,7 +223,7 @@ func (v *Validator) findGoss() (string, error) { } func (v *Validator) runSpec(specFile, category, gossPath string) SpecResult { - specPath := filepath.Join(v.opts.BaselinesDir, specFile) + specPath := v.resolve(specFile) specName := strings.TrimSuffix(specFile, ".yml") result := SpecResult{ @@ -232,7 +232,7 @@ func (v *Validator) runSpec(specFile, category, gossPath string) SpecResult { } // Check if spec file exists - if _, err := os.Stat(specPath); os.IsNotExist(err) { + if specPath == "" { result.Skipped = true return result } @@ -265,13 +265,7 @@ func (v *Validator) runSpec(specFile, category, gossPath string) SpecResult { func (v *Validator) runDiscovery() SpecResult { result := SpecResult{Spec: "file-discovery", Category: "critical"} - policy := "" - for _, dir := range []string{v.opts.BaselinesDir, filepath.Dir(v.opts.BaselinesDir)} { - if p := filepath.Join(dir, DiscoveryPolicy); fileExists(p) { - policy = p - break - } - } + policy := v.resolve(DiscoveryPolicy) self, err := os.Executable() if policy == "" || err != nil { result.Skipped = policy == "" @@ -288,9 +282,16 @@ func (v *Validator) runDiscovery() SpecResult { return result } -func fileExists(path string) bool { - _, err := os.Stat(path) - return err == nil +// resolve finds a spec in the baselines directory, then in its parent, so +// files shared by every build live once in the parent. +func (v *Validator) resolve(name string) string { + for _, dir := range []string{v.opts.BaselinesDir, filepath.Dir(v.opts.BaselinesDir)} { + p := filepath.Join(dir, name) + if _, err := os.Stat(p); err == nil { + return p + } + } + return "" } func (v *Validator) printSpecResult(r SpecResult) { diff --git a/nix/packages/supascan/internal/validator/validator_test.go b/nix/packages/supascan/internal/validator/validator_test.go index 8bd379f9f3..471e86ac5a 100644 --- a/nix/packages/supascan/internal/validator/validator_test.go +++ b/nix/packages/supascan/internal/validator/validator_test.go @@ -1,6 +1,7 @@ package validator import ( + "os" "path/filepath" "testing" ) @@ -109,3 +110,23 @@ func TestRunDiscoverySkippedWithoutPolicy(t *testing.T) { t.Error("expected discovery to be skipped when no policy file exists") } } + +func TestResolvePrefersBuildDirOverParent(t *testing.T) { + parent := t.TempDir() + build := filepath.Join(parent, "build") + os.Mkdir(build, 0o755) + os.WriteFile(filepath.Join(parent, "shared.yml"), nil, 0o644) + os.WriteFile(filepath.Join(parent, "both.yml"), nil, 0o644) + os.WriteFile(filepath.Join(build, "both.yml"), nil, 0o644) + + v := New(Options{BaselinesDir: build}) + if got := v.resolve("shared.yml"); got != filepath.Join(parent, "shared.yml") { + t.Errorf("shared.yml resolved to %q", got) + } + if got := v.resolve("both.yml"); got != filepath.Join(build, "both.yml") { + t.Errorf("both.yml resolved to %q", got) + } + if got := v.resolve("missing.yml"); got != "" { + t.Errorf("missing.yml resolved to %q", got) + } +} From 40ae2a0a8375bae80a9c72a70adef26168574d23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Wed, 25 Nov 2026 03:24:37 +0200 Subject: [PATCH 07/19] feat(supascan): scope discovery exceptions to rules Exceptions map a path to the rules it is excused from. Unknown rule names are rejected when the policy loads. Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- audit-specs/baselines/file-discovery.yml | 92 +++++++++---------- .../supascan/internal/discovery/discovery.go | 45 ++++++--- .../internal/discovery/discovery_test.go | 29 +++++- 3 files changed, 101 insertions(+), 65 deletions(-) diff --git a/audit-specs/baselines/file-discovery.yml b/audit-specs/baselines/file-discovery.yml index 16cea1b4df..066d56b77a 100644 --- a/audit-specs/baselines/file-discovery.yml +++ b/audit-specs/baselines/file-discovery.yml @@ -28,49 +28,49 @@ setuid: - /usr/sbin/pam_extrausers_chkpwd - /usr/sbin/unix_chkpwd exceptions: - - /var/local - - /var/mail - - /var/log/btmp - - /var/log/lastlog - - /var/log/wtmp - - /var/lib/cloud/instances/** - - /usr/local/kong/** - - /usr/local/openresty/** - - /etc/vector/examples/** - - /etc/pgbouncer-custom/** - - /etc/postgresql-custom/extension-custom-scripts/** - - /etc/envoy/envoy.yaml - - /etc/envoy/lds.yaml - - /etc/gotrue.env - - /etc/kong/kong.conf - - /etc/kong/kong.conf.default - - /etc/kong/kong.logrotate - - /etc/logrotate.d/logrotate-postgres-auth.conf - - /etc/logrotate.d/logrotate-postgres-csv.conf - - /etc/logrotate.d/logrotate-postgres.conf - - /etc/logrotate.d/logrotate-walg.conf - - /etc/machine-id - - /etc/pgbouncer/userlist.txt - - /etc/postgresql-custom/custom-overrides.conf - - /etc/postgresql-custom/generated-optimizations.conf - - /etc/postgresql-custom/read-replica.conf - - /etc/postgresql-custom/supautils.conf - - /etc/postgresql-custom/wal-g.conf - - /etc/postgresql/pg_hba.conf - - /etc/postgrest/base.conf - - /etc/postgrest/merge.sh - - /etc/ssl/adminapi/server.crt - - /etc/ssl/adminapi/server.key - - /etc/wal-g/config.json - - /opt/envoy - - /opt/envoy-hot-restarter.py - - /opt/start-envoy.sh - - /usr/lib/systemd/system/kong.service - - /usr/local/bin/kong - - /usr/local/bin/lapis - - /usr/local/bin/luarocks - - /usr/local/bin/luarocks-admin - - /usr/local/bin/project-init.sh - - /usr/local/bin/systemd-networkd-check-and-fix.sh - - /usr/local/etc/luarocks/config-5.1.lua - - /var/lib/cloud/scripts/per-boot/supaboot.sh + /var/local: [group-writable] + /var/mail: [group-writable] + /var/log/btmp: [group-writable] + /var/log/lastlog: [group-writable] + /var/log/wtmp: [group-writable] + /var/lib/cloud/instances/**: [mode] + /usr/local/kong/**: [group-writable, mode] + /usr/local/openresty/**: [group-writable, mode] + /etc/vector/examples/**: [group-writable, mode] + /etc/pgbouncer-custom/**: [group-writable, mode] + /etc/postgresql-custom/extension-custom-scripts/**: [group-writable, mode] + /etc/envoy/envoy.yaml: [group-writable, mode] + /etc/envoy/lds.yaml: [group-writable, mode] + /etc/gotrue.env: [group-writable, mode] + /etc/kong/kong.conf: [group-writable, mode] + /etc/kong/kong.conf.default: [group-writable, mode] + /etc/kong/kong.logrotate: [group-writable, mode] + /etc/logrotate.d/logrotate-postgres-auth.conf: [mode] + /etc/logrotate.d/logrotate-postgres-csv.conf: [mode] + /etc/logrotate.d/logrotate-postgres.conf: [mode] + /etc/logrotate.d/logrotate-walg.conf: [mode] + /etc/machine-id: [mode] + /etc/pgbouncer/userlist.txt: [group-writable, mode] + /etc/postgresql-custom/custom-overrides.conf: [group-writable, mode] + /etc/postgresql-custom/generated-optimizations.conf: [group-writable, mode] + /etc/postgresql-custom/read-replica.conf: [group-writable, mode] + /etc/postgresql-custom/supautils.conf: [group-writable, mode] + /etc/postgresql-custom/wal-g.conf: [group-writable, mode] + /etc/postgresql/pg_hba.conf: [group-writable, mode] + /etc/postgrest/base.conf: [group-writable, mode] + /etc/postgrest/merge.sh: [mode] + /etc/ssl/adminapi/server.crt: [mode] + /etc/ssl/adminapi/server.key: [mode] + /etc/wal-g/config.json: [group-writable, mode] + /opt/envoy: [mode] + /opt/envoy-hot-restarter.py: [mode] + /opt/start-envoy.sh: [mode] + /usr/lib/systemd/system/kong.service: [group-writable] + /usr/local/bin/kong: [group-writable, mode] + /usr/local/bin/lapis: [group-writable, mode] + /usr/local/bin/luarocks: [group-writable, mode] + /usr/local/bin/luarocks-admin: [group-writable, mode] + /usr/local/bin/project-init.sh: [mode] + /usr/local/bin/systemd-networkd-check-and-fix.sh: [mode] + /usr/local/etc/luarocks/config-5.1.lua: [group-writable, mode] + /var/lib/cloud/scripts/per-boot/supaboot.sh: [mode] diff --git a/nix/packages/supascan/internal/discovery/discovery.go b/nix/packages/supascan/internal/discovery/discovery.go index 3bad5a4aa1..9860e36bae 100644 --- a/nix/packages/supascan/internal/discovery/discovery.go +++ b/nix/packages/supascan/internal/discovery/discovery.go @@ -15,14 +15,16 @@ import ( "gopkg.in/yaml.v3" ) +var rules = []string{"setuid", "world-writable", "group-writable", "owner", "group", "mode"} + var skippedTrees = []string{"/proc", "/sys", "/dev", "/run", "/tmp", "/var/tmp", "/nix/store"} type Policy struct { - Roots []string `yaml:"roots"` - FileModes []string `yaml:"file_modes"` - DirModes []string `yaml:"dir_modes"` - Setuid []string `yaml:"setuid"` - Exceptions []string `yaml:"exceptions"` + Roots []string `yaml:"roots"` + FileModes []string `yaml:"file_modes"` + DirModes []string `yaml:"dir_modes"` + Setuid []string `yaml:"setuid"` + Exceptions map[string][]string `yaml:"exceptions"` } func LoadPolicy(path string) (*Policy, error) { @@ -34,6 +36,13 @@ func LoadPolicy(path string) (*Policy, error) { if err := yaml.Unmarshal(data, &p); err != nil { return nil, fmt.Errorf("parse %s: %w", path, err) } + for path, rs := range p.Exceptions { + for _, r := range rs { + if !slices.Contains(rules, r) { + return nil, fmt.Errorf("exception %s: unknown rule %q", path, r) + } + } + } return &p, nil } @@ -41,8 +50,11 @@ func under(path, tree string) bool { return path == tree || strings.HasPrefix(path, strings.TrimRight(tree, "/")+"/") } -func (p *Policy) excepted(path string) bool { - for _, e := range p.Exceptions { +func (p *Policy) excepted(path, rule string) bool { + for e, rs := range p.Exceptions { + if !slices.Contains(rs, rule) { + continue + } if base, ok := strings.CutSuffix(e, "/**"); ok { if under(path, base) { return true @@ -106,7 +118,7 @@ func Scan(ctx context.Context, root string, p *Policy) ([]string, error) { } return nil } - if walkErr != nil || (!d.IsDir() && !d.Type().IsRegular()) || p.excepted(path) { + if walkErr != nil || (!d.IsDir() && !d.Type().IsRegular()) { return nil } info, err := d.Info() @@ -124,22 +136,27 @@ func Scan(ctx context.Context, root string, p *Policy) ([]string, error) { func (p *Policy) check(path string, mode fs.FileMode, isDir bool, uid, gid uint32, users, groups map[uint32]bool) []string { var out []string + add := func(rule, format string, args ...any) { + if !p.excepted(path, rule) { + out = append(out, fmt.Sprintf(format, args...)) + } + } perm := mode.Perm() sticky := isDir && mode&fs.ModeSticky != 0 if !isDir && mode&(fs.ModeSetuid|fs.ModeSetgid) != 0 && !slices.Contains(p.Setuid, path) { - out = append(out, "setuid or setgid file not in setuid list") + add("setuid", "setuid or setgid file not in setuid list") } if perm&0o002 != 0 && !sticky { - out = append(out, fmt.Sprintf("world-writable %04o", perm)) + add("world-writable", "world-writable %04o", perm) } if perm&0o020 != 0 && !sticky { - out = append(out, fmt.Sprintf("group-writable %04o", perm)) + add("group-writable", "group-writable %04o", perm) } if !users[uid] { - out = append(out, fmt.Sprintf("owner id %d has no passwd entry", uid)) + add("owner", "owner id %d has no passwd entry", uid) } if !groups[gid] { - out = append(out, fmt.Sprintf("group id %d has no group entry", gid)) + add("group", "group id %d has no group entry", gid) } if slices.ContainsFunc(p.Roots, func(r string) bool { return under(path, r) }) { modes := p.FileModes @@ -147,7 +164,7 @@ func (p *Policy) check(path string, mode fs.FileMode, isDir bool, uid, gid uint3 modes = p.DirModes } if !allowed(modes, perm) { - out = append(out, fmt.Sprintf("mode %04o not in allowlist", perm)) + add("mode", "mode %04o not in allowlist", perm) } } return out diff --git a/nix/packages/supascan/internal/discovery/discovery_test.go b/nix/packages/supascan/internal/discovery/discovery_test.go index f4d95a7296..b3c7cb5d8e 100644 --- a/nix/packages/supascan/internal/discovery/discovery_test.go +++ b/nix/packages/supascan/internal/discovery/discovery_test.go @@ -50,14 +50,33 @@ func TestCheck(t *testing.T) { } func TestExcepted(t *testing.T) { - p := &Policy{Exceptions: []string{"/etc/a", "/opt/v/**"}} - for path, want := range map[string]bool{"/etc/a": true, "/etc/ab": false, "/opt/v": true, "/opt/v/x/y": true, "/opt/vx": false} { - if p.excepted(path) != want { - t.Errorf("excepted(%q) = %v, want %v", path, !want, want) + p := &Policy{Exceptions: map[string][]string{"/etc/a": {"mode"}, "/opt/v/**": {"mode", "group-writable"}}} + for _, tt := range []struct { + path, rule string + want bool + }{ + {"/etc/a", "mode", true}, + {"/etc/a", "group-writable", false}, + {"/etc/ab", "mode", false}, + {"/opt/v", "group-writable", true}, + {"/opt/v/x/y", "mode", true}, + {"/opt/v/x", "setuid", false}, + {"/opt/vx", "mode", false}, + } { + if got := p.excepted(tt.path, tt.rule); got != tt.want { + t.Errorf("excepted(%q, %q) = %v, want %v", tt.path, tt.rule, got, tt.want) } } } +func TestLoadPolicyRejectsUnknownRule(t *testing.T) { + path := filepath.Join(t.TempDir(), "p.yml") + os.WriteFile(path, []byte("exceptions:\n /etc/a: [modee]\n"), 0o644) + if _, err := LoadPolicy(path); err == nil { + t.Error("expected error for unknown rule") + } +} + func TestScan(t *testing.T) { root := t.TempDir() info, _ := os.Stat(root) @@ -77,7 +96,7 @@ func TestScan(t *testing.T) { os.Chmod(full, mode) } - got, err := Scan(context.Background(), root, &Policy{Exceptions: []string{"/etc/skip"}}) + got, err := Scan(context.Background(), root, &Policy{Exceptions: map[string][]string{"/etc/skip": {"group-writable"}}}) if err != nil { t.Fatal(err) } From 2010e096e38fb0c6468b74442a7d827e09fbb027 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Wed, 25 Nov 2026 03:27:08 +0200 Subject: [PATCH 08/19] refactor(supascan): trim discovery code Drop the context argument, the mode parse helper, and rule name validation. Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- .../supascan/cmd/supascan/discover.go | 11 +++------ .../supascan/internal/discovery/discovery.go | 24 ++----------------- .../internal/discovery/discovery_test.go | 11 +-------- .../supascan/internal/validator/validator.go | 7 +++--- 4 files changed, 9 insertions(+), 44 deletions(-) diff --git a/nix/packages/supascan/cmd/supascan/discover.go b/nix/packages/supascan/cmd/supascan/discover.go index ac586fa688..05df787885 100644 --- a/nix/packages/supascan/cmd/supascan/discover.go +++ b/nix/packages/supascan/cmd/supascan/discover.go @@ -1,7 +1,6 @@ package main import ( - "context" "fmt" "github.com/spf13/cobra" @@ -14,12 +13,8 @@ var discoverRoot string var discoverCmd = &cobra.Command{ Use: "discover ", Short: "Scan the filesystem for permission and ownership drift", - Long: `Walk the filesystem and report setuid or setgid files outside the allowlist, -world-writable paths other than sticky directories, group-writable paths, owner or -group ids with no passwd or group entry, and modes outside the allowlist under the -policy roots. Exits non-zero when anything is reported. Run as root.`, - Args: cobra.ExactArgs(1), - RunE: runDiscover, + Args: cobra.ExactArgs(1), + RunE: runDiscover, } func init() { @@ -32,7 +27,7 @@ func runDiscover(cmd *cobra.Command, args []string) error { if err != nil { return err } - findings, err := discovery.Scan(context.Background(), discoverRoot, policy) + findings, err := discovery.Scan(discoverRoot, policy) if err != nil { return err } diff --git a/nix/packages/supascan/internal/discovery/discovery.go b/nix/packages/supascan/internal/discovery/discovery.go index 9860e36bae..761e2d6b80 100644 --- a/nix/packages/supascan/internal/discovery/discovery.go +++ b/nix/packages/supascan/internal/discovery/discovery.go @@ -2,7 +2,6 @@ package discovery import ( "bufio" - "context" "fmt" "io/fs" "os" @@ -15,8 +14,6 @@ import ( "gopkg.in/yaml.v3" ) -var rules = []string{"setuid", "world-writable", "group-writable", "owner", "group", "mode"} - var skippedTrees = []string{"/proc", "/sys", "/dev", "/run", "/tmp", "/var/tmp", "/nix/store"} type Policy struct { @@ -36,13 +33,6 @@ func LoadPolicy(path string) (*Policy, error) { if err := yaml.Unmarshal(data, &p); err != nil { return nil, fmt.Errorf("parse %s: %w", path, err) } - for path, rs := range p.Exceptions { - for _, r := range rs { - if !slices.Contains(rules, r) { - return nil, fmt.Errorf("exception %s: unknown rule %q", path, r) - } - } - } return &p, nil } @@ -66,13 +56,6 @@ func (p *Policy) excepted(path, rule string) bool { return false } -func allowed(modes []string, perm fs.FileMode) bool { - return slices.ContainsFunc(modes, func(m string) bool { - n, err := strconv.ParseUint(m, 8, 32) - return err == nil && fs.FileMode(n) == perm - }) -} - func readIDs(path string) (map[uint32]bool, error) { f, err := os.Open(path) if err != nil { @@ -93,7 +76,7 @@ func readIDs(path string) (map[uint32]bool, error) { // Scan walks root and returns "path: problem" lines. Paths are relative to // root with a leading slash, so an extracted image can be scanned in place. -func Scan(ctx context.Context, root string, p *Policy) ([]string, error) { +func Scan(root string, p *Policy) ([]string, error) { users, err := readIDs(filepath.Join(root, "etc/passwd")) if err != nil { return nil, err @@ -105,9 +88,6 @@ func Scan(ctx context.Context, root string, p *Policy) ([]string, error) { var findings []string err = filepath.WalkDir(root, func(real string, d fs.DirEntry, walkErr error) error { - if ctx.Err() != nil { - return ctx.Err() - } path := "/" if rel, _ := filepath.Rel(root, real); rel != "." { path = "/" + filepath.ToSlash(rel) @@ -163,7 +143,7 @@ func (p *Policy) check(path string, mode fs.FileMode, isDir bool, uid, gid uint3 if isDir { modes = p.DirModes } - if !allowed(modes, perm) { + if !slices.Contains(modes, fmt.Sprintf("%04o", perm)) { add("mode", "mode %04o not in allowlist", perm) } } diff --git a/nix/packages/supascan/internal/discovery/discovery_test.go b/nix/packages/supascan/internal/discovery/discovery_test.go index b3c7cb5d8e..93ed8142a5 100644 --- a/nix/packages/supascan/internal/discovery/discovery_test.go +++ b/nix/packages/supascan/internal/discovery/discovery_test.go @@ -1,7 +1,6 @@ package discovery import ( - "context" "fmt" "io/fs" "os" @@ -69,14 +68,6 @@ func TestExcepted(t *testing.T) { } } -func TestLoadPolicyRejectsUnknownRule(t *testing.T) { - path := filepath.Join(t.TempDir(), "p.yml") - os.WriteFile(path, []byte("exceptions:\n /etc/a: [modee]\n"), 0o644) - if _, err := LoadPolicy(path); err == nil { - t.Error("expected error for unknown rule") - } -} - func TestScan(t *testing.T) { root := t.TempDir() info, _ := os.Stat(root) @@ -96,7 +87,7 @@ func TestScan(t *testing.T) { os.Chmod(full, mode) } - got, err := Scan(context.Background(), root, &Policy{Exceptions: map[string][]string{"/etc/skip": {"group-writable"}}}) + got, err := Scan(root, &Policy{Exceptions: map[string][]string{"/etc/skip": {"group-writable"}}}) if err != nil { t.Fatal(err) } diff --git a/nix/packages/supascan/internal/validator/validator.go b/nix/packages/supascan/internal/validator/validator.go index 02c10bedca..219babd454 100644 --- a/nix/packages/supascan/internal/validator/validator.go +++ b/nix/packages/supascan/internal/validator/validator.go @@ -266,12 +266,11 @@ func (v *Validator) runDiscovery() SpecResult { result := SpecResult{Spec: "file-discovery", Category: "critical"} policy := v.resolve(DiscoveryPolicy) - self, err := os.Executable() - if policy == "" || err != nil { - result.Skipped = policy == "" - result.Error = err + if policy == "" { + result.Skipped = true return result } + self, _ := os.Executable() var out bytes.Buffer cmd := exec.Command("sudo", self, "discover", policy) From f36367310d0aa747dc1ef73fe3589daa37c7f2a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Wed, 25 Nov 2026 03:38:10 +0200 Subject: [PATCH 09/19] docs(supascan): list discovery rules Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- nix/packages/supascan/README.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/nix/packages/supascan/README.md b/nix/packages/supascan/README.md index 2c2d51d37f..152f41ce10 100644 --- a/nix/packages/supascan/README.md +++ b/nix/packages/supascan/README.md @@ -57,7 +57,16 @@ sudo nix run .#supascan -- validate --format documentation /path/to/baselines ### Filesystem discovery -`validate` also runs `discover` when `file-discovery.yml` is in the baselines directory or its parent. It reports setuid or setgid files, world-writable and group-writable paths, unknown owner or group ids, and modes outside the allowlist, skipping `exceptions`. An entry ending in `/**` covers a subtree. Use `--root` to scan an extracted image. +`validate` also runs `discover` when `file-discovery.yml` is in the baselines directory or its parent. It reports these rules: + +- `setuid`: setuid or setgid files not in the `setuid` list. +- `world-writable`: world-writable paths other than sticky directories. +- `group-writable`: group-writable paths other than sticky directories. +- `owner`: owner ids with no passwd entry. +- `group`: group ids with no group entry. +- `mode`: modes outside `file_modes` and `dir_modes` under `roots`. + +`exceptions` maps a path to the rules it is excused from, for example `/etc/a: [mode]`. A path ending in `/**` covers a subtree. Use `--root` to scan an extracted image. ## Installation From ca5876410b24c9e7bc95a708c901a25531c8b3ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Wed, 25 Nov 2026 03:44:12 +0200 Subject: [PATCH 10/19] feat(supascan): re-run discover under sudo discover replaces itself with sudo -n when not root. The validator calls it directly. Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- nix/packages/supascan/README.md | 2 +- .../supascan/cmd/supascan/discover.go | 24 +++++++++++++++++++ .../supascan/internal/validator/validator.go | 7 +++--- 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/nix/packages/supascan/README.md b/nix/packages/supascan/README.md index 152f41ce10..11ba084e4b 100644 --- a/nix/packages/supascan/README.md +++ b/nix/packages/supascan/README.md @@ -66,7 +66,7 @@ sudo nix run .#supascan -- validate --format documentation /path/to/baselines - `group`: group ids with no group entry. - `mode`: modes outside `file_modes` and `dir_modes` under `roots`. -`exceptions` maps a path to the rules it is excused from, for example `/etc/a: [mode]`. A path ending in `/**` covers a subtree. Use `--root` to scan an extracted image. +`exceptions` maps a path to the rules it is excused from, for example `/etc/a: [mode]`. A path ending in `/**` covers a subtree. `discover` re-runs itself under `sudo -n` when not root. Use `--root` to scan an extracted image. ## Installation diff --git a/nix/packages/supascan/cmd/supascan/discover.go b/nix/packages/supascan/cmd/supascan/discover.go index 05df787885..798abf6638 100644 --- a/nix/packages/supascan/cmd/supascan/discover.go +++ b/nix/packages/supascan/cmd/supascan/discover.go @@ -2,6 +2,9 @@ package main import ( "fmt" + "os" + "path/filepath" + "syscall" "github.com/spf13/cobra" @@ -22,7 +25,28 @@ func init() { rootCmd.AddCommand(discoverCmd) } +// escalate replaces the process with `sudo -n supascan discover ...` so the +// walk can read every directory. It uses fixed paths and a minimal +// environment, and -n fails instead of prompting. +func escalate() error { + if os.Geteuid() == 0 { + return nil + } + self, err := os.Executable() + if err == nil { + self, err = filepath.EvalSymlinks(self) + } + if err != nil { + return err + } + argv := append([]string{"sudo", "-n", "--", self}, os.Args[1:]...) + return syscall.Exec("/usr/bin/sudo", argv, []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin"}) +} + func runDiscover(cmd *cobra.Command, args []string) error { + if err := escalate(); err != nil { + return fmt.Errorf("re-run under sudo: %w", err) + } policy, err := discovery.LoadPolicy(args[0]) if err != nil { return err diff --git a/nix/packages/supascan/internal/validator/validator.go b/nix/packages/supascan/internal/validator/validator.go index 219babd454..2347d717ed 100644 --- a/nix/packages/supascan/internal/validator/validator.go +++ b/nix/packages/supascan/internal/validator/validator.go @@ -259,9 +259,8 @@ func (v *Validator) runSpec(specFile, category, gossPath string) SpecResult { return result } -// runDiscovery re-executes supascan under sudo, like goss specs, so the walk -// can read every directory. The policy comes from the baselines directory or -// its parent. +// runDiscovery runs `supascan discover`, which re-runs itself under sudo. The +// policy comes from the baselines directory or its parent. func (v *Validator) runDiscovery() SpecResult { result := SpecResult{Spec: "file-discovery", Category: "critical"} @@ -273,7 +272,7 @@ func (v *Validator) runDiscovery() SpecResult { self, _ := os.Executable() var out bytes.Buffer - cmd := exec.Command("sudo", self, "discover", policy) + cmd := exec.Command(self, "discover", policy) cmd.Stdout, cmd.Stderr = &out, &out result.Error = cmd.Run() result.Passed = result.Error == nil From 5e187cda544541fab52aeee812ee38556c9fa1cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Wed, 25 Nov 2026 03:45:32 +0200 Subject: [PATCH 11/19] refactor(supascan): shorten comments Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- audit-specs/baselines/file-discovery.yml | 1 - nix/packages/supascan/cmd/supascan/discover.go | 4 +--- nix/packages/supascan/internal/discovery/discovery.go | 3 +-- nix/packages/supascan/internal/validator/validator.go | 6 +----- 4 files changed, 3 insertions(+), 11 deletions(-) diff --git a/audit-specs/baselines/file-discovery.yml b/audit-specs/baselines/file-discovery.yml index 066d56b77a..cdf2a7f3c1 100644 --- a/audit-specs/baselines/file-discovery.yml +++ b/audit-specs/baselines/file-discovery.yml @@ -1,4 +1,3 @@ -# Filesystem discovery policy for supascan validate. # Exceptions come from baseline.yml (AMI arm64) and Ubuntu defaults. roots: [/etc, /usr/local, /opt, /data, /var/lib] file_modes: ["0644", "0640", "0600", "0440", "0755"] diff --git a/nix/packages/supascan/cmd/supascan/discover.go b/nix/packages/supascan/cmd/supascan/discover.go index 798abf6638..0318b9be9c 100644 --- a/nix/packages/supascan/cmd/supascan/discover.go +++ b/nix/packages/supascan/cmd/supascan/discover.go @@ -25,9 +25,7 @@ func init() { rootCmd.AddCommand(discoverCmd) } -// escalate replaces the process with `sudo -n supascan discover ...` so the -// walk can read every directory. It uses fixed paths and a minimal -// environment, and -n fails instead of prompting. +// escalate re-runs discover under sudo -n with a fixed path and minimal environment. func escalate() error { if os.Geteuid() == 0 { return nil diff --git a/nix/packages/supascan/internal/discovery/discovery.go b/nix/packages/supascan/internal/discovery/discovery.go index 761e2d6b80..6b2a8058e0 100644 --- a/nix/packages/supascan/internal/discovery/discovery.go +++ b/nix/packages/supascan/internal/discovery/discovery.go @@ -74,8 +74,7 @@ func readIDs(path string) (map[uint32]bool, error) { return ids, sc.Err() } -// Scan walks root and returns "path: problem" lines. Paths are relative to -// root with a leading slash, so an extracted image can be scanned in place. +// Scan reports paths relative to root, so an extracted image can be scanned in place. func Scan(root string, p *Policy) ([]string, error) { users, err := readIDs(filepath.Join(root, "etc/passwd")) if err != nil { diff --git a/nix/packages/supascan/internal/validator/validator.go b/nix/packages/supascan/internal/validator/validator.go index 2347d717ed..fa9faaae5b 100644 --- a/nix/packages/supascan/internal/validator/validator.go +++ b/nix/packages/supascan/internal/validator/validator.go @@ -9,7 +9,6 @@ import ( "strings" ) -// DiscoveryPolicy is the filesystem discovery policy in a baselines directory. const DiscoveryPolicy = "file-discovery.yml" // Spec categories @@ -259,8 +258,6 @@ func (v *Validator) runSpec(specFile, category, gossPath string) SpecResult { return result } -// runDiscovery runs `supascan discover`, which re-runs itself under sudo. The -// policy comes from the baselines directory or its parent. func (v *Validator) runDiscovery() SpecResult { result := SpecResult{Spec: "file-discovery", Category: "critical"} @@ -280,8 +277,7 @@ func (v *Validator) runDiscovery() SpecResult { return result } -// resolve finds a spec in the baselines directory, then in its parent, so -// files shared by every build live once in the parent. +// resolve looks in the baselines directory, then its parent. func (v *Validator) resolve(name string) string { for _, dir := range []string{v.opts.BaselinesDir, filepath.Dir(v.opts.BaselinesDir)} { p := filepath.Join(dir, name) From ac308bbdc9142f454b39afee0a6a35c7ff01924e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Wed, 25 Nov 2026 04:16:32 +0200 Subject: [PATCH 12/19] fix(supascan): skip setuid assertion when the bit is not kept Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- .../supascan/internal/discovery/discovery_test.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/nix/packages/supascan/internal/discovery/discovery_test.go b/nix/packages/supascan/internal/discovery/discovery_test.go index 93ed8142a5..a79488511a 100644 --- a/nix/packages/supascan/internal/discovery/discovery_test.go +++ b/nix/packages/supascan/internal/discovery/discovery_test.go @@ -87,12 +87,21 @@ func TestScan(t *testing.T) { os.Chmod(full, mode) } + suidKept := false + if info, err := os.Stat(filepath.Join(root, "srv/suid")); err == nil { + suidKept = info.Mode()&fs.ModeSetuid != 0 + } + got, err := Scan(root, &Policy{Exceptions: map[string][]string{"/etc/skip": {"group-writable"}}}) if err != nil { t.Fatal(err) } text := strings.Join(got, "\n") - for _, want := range []string{"/etc/loose: group-writable", "/srv/suid: setuid"} { + wants := []string{"/etc/loose: group-writable"} + if suidKept { + wants = append(wants, "/srv/suid: setuid") + } + for _, want := range wants { if !strings.Contains(text, want) { t.Errorf("missing %q in:\n%s", want, text) } From bf81469eadce8692d2ac228ba0c3d25b64b9e013 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Wed, 25 Nov 2026 05:02:50 +0200 Subject: [PATCH 13/19] refactor(supascan): fold setuid list into exceptions Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- audit-specs/baselines/file-discovery.yml | 47 +++++++++---------- nix/packages/supascan/README.md | 2 +- .../supascan/internal/discovery/discovery.go | 26 ++++------ .../internal/discovery/discovery_test.go | 8 ++-- 4 files changed, 36 insertions(+), 47 deletions(-) diff --git a/audit-specs/baselines/file-discovery.yml b/audit-specs/baselines/file-discovery.yml index cdf2a7f3c1..3fb93d2dcf 100644 --- a/audit-specs/baselines/file-discovery.yml +++ b/audit-specs/baselines/file-discovery.yml @@ -2,31 +2,30 @@ roots: [/etc, /usr/local, /opt, /data, /var/lib] file_modes: ["0644", "0640", "0600", "0440", "0755"] dir_modes: ["0755", "0750", "0700"] -setuid: - - /usr/bin/chage - - /usr/bin/chfn - - /usr/bin/chsh - - /usr/bin/crontab - - /usr/bin/dotlockfile - - /usr/bin/expiry - - /usr/bin/fusermount3 - - /usr/bin/gpasswd - - /usr/bin/mount - - /usr/bin/newgrp - - /usr/bin/passwd - - /usr/bin/pkexec - - /usr/bin/ssh-agent - - /usr/bin/su - - /usr/bin/sudo - - /usr/bin/umount - - /usr/bin/wall - - /usr/bin/write.ul - - /usr/lib/dbus-1.0/dbus-daemon-launch-helper - - /usr/lib/openssh/ssh-keysign - - /usr/lib/polkit-1/polkit-agent-helper-1 - - /usr/sbin/pam_extrausers_chkpwd - - /usr/sbin/unix_chkpwd exceptions: + /usr/bin/chage: [setuid] + /usr/bin/chfn: [setuid] + /usr/bin/chsh: [setuid] + /usr/bin/crontab: [setuid] + /usr/bin/dotlockfile: [setuid] + /usr/bin/expiry: [setuid] + /usr/bin/fusermount3: [setuid] + /usr/bin/gpasswd: [setuid] + /usr/bin/mount: [setuid] + /usr/bin/newgrp: [setuid] + /usr/bin/passwd: [setuid] + /usr/bin/pkexec: [setuid] + /usr/bin/ssh-agent: [setuid] + /usr/bin/su: [setuid] + /usr/bin/sudo: [setuid] + /usr/bin/umount: [setuid] + /usr/bin/wall: [setuid] + /usr/bin/write.ul: [setuid] + /usr/lib/dbus-1.0/dbus-daemon-launch-helper: [setuid] + /usr/lib/openssh/ssh-keysign: [setuid] + /usr/lib/polkit-1/polkit-agent-helper-1: [setuid] + /usr/sbin/pam_extrausers_chkpwd: [setuid] + /usr/sbin/unix_chkpwd: [setuid] /var/local: [group-writable] /var/mail: [group-writable] /var/log/btmp: [group-writable] diff --git a/nix/packages/supascan/README.md b/nix/packages/supascan/README.md index 11ba084e4b..98df4655ef 100644 --- a/nix/packages/supascan/README.md +++ b/nix/packages/supascan/README.md @@ -59,7 +59,7 @@ sudo nix run .#supascan -- validate --format documentation /path/to/baselines `validate` also runs `discover` when `file-discovery.yml` is in the baselines directory or its parent. It reports these rules: -- `setuid`: setuid or setgid files not in the `setuid` list. +- `setuid`: setuid or setgid files. - `world-writable`: world-writable paths other than sticky directories. - `group-writable`: group-writable paths other than sticky directories. - `owner`: owner ids with no passwd entry. diff --git a/nix/packages/supascan/internal/discovery/discovery.go b/nix/packages/supascan/internal/discovery/discovery.go index 6b2a8058e0..8d79bbaff1 100644 --- a/nix/packages/supascan/internal/discovery/discovery.go +++ b/nix/packages/supascan/internal/discovery/discovery.go @@ -1,7 +1,6 @@ package discovery import ( - "bufio" "fmt" "io/fs" "os" @@ -20,7 +19,6 @@ type Policy struct { Roots []string `yaml:"roots"` FileModes []string `yaml:"file_modes"` DirModes []string `yaml:"dir_modes"` - Setuid []string `yaml:"setuid"` Exceptions map[string][]string `yaml:"exceptions"` } @@ -42,14 +40,8 @@ func under(path, tree string) bool { func (p *Policy) excepted(path, rule string) bool { for e, rs := range p.Exceptions { - if !slices.Contains(rs, rule) { - continue - } - if base, ok := strings.CutSuffix(e, "/**"); ok { - if under(path, base) { - return true - } - } else if path == e { + base, glob := strings.CutSuffix(e, "/**") + if slices.Contains(rs, rule) && (path == e || glob && under(path, base)) { return true } } @@ -57,21 +49,19 @@ func (p *Policy) excepted(path, rule string) bool { } func readIDs(path string) (map[uint32]bool, error) { - f, err := os.Open(path) + data, err := os.ReadFile(path) if err != nil { return nil, err } - defer f.Close() ids := map[uint32]bool{} - sc := bufio.NewScanner(f) - for sc.Scan() { - if fields := strings.Split(sc.Text(), ":"); len(fields) >= 3 { + for _, line := range strings.Split(string(data), "\n") { + if fields := strings.Split(line, ":"); len(fields) >= 3 { if n, err := strconv.ParseUint(fields[2], 10, 32); err == nil { ids[uint32(n)] = true } } } - return ids, sc.Err() + return ids, nil } // Scan reports paths relative to root, so an extracted image can be scanned in place. @@ -122,8 +112,8 @@ func (p *Policy) check(path string, mode fs.FileMode, isDir bool, uid, gid uint3 } perm := mode.Perm() sticky := isDir && mode&fs.ModeSticky != 0 - if !isDir && mode&(fs.ModeSetuid|fs.ModeSetgid) != 0 && !slices.Contains(p.Setuid, path) { - add("setuid", "setuid or setgid file not in setuid list") + if !isDir && mode&(fs.ModeSetuid|fs.ModeSetgid) != 0 { + add("setuid", "setuid or setgid file") } if perm&0o002 != 0 && !sticky { add("world-writable", "world-writable %04o", perm) diff --git a/nix/packages/supascan/internal/discovery/discovery_test.go b/nix/packages/supascan/internal/discovery/discovery_test.go index a79488511a..799a3029e5 100644 --- a/nix/packages/supascan/internal/discovery/discovery_test.go +++ b/nix/packages/supascan/internal/discovery/discovery_test.go @@ -12,10 +12,10 @@ import ( func TestCheck(t *testing.T) { p := &Policy{ - Roots: []string{"/etc"}, - FileModes: []string{"0644"}, - DirModes: []string{"0755"}, - Setuid: []string{"/usr/bin/allowed"}, + Roots: []string{"/etc"}, + FileModes: []string{"0644"}, + DirModes: []string{"0755"}, + Exceptions: map[string][]string{"/usr/bin/allowed": {"setuid"}}, } known := map[uint32]bool{0: true} tests := []struct { From 2748042331e5e2cbb37df219a6d57824e11e96f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Thu, 26 Nov 2026 03:17:00 +0200 Subject: [PATCH 14/19] ci(ansible): print supascan output on failure Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- ansible/playbook.yml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ansible/playbook.yml b/ansible/playbook.yml index 88c86e27cb..f519f3a19f 100644 --- a/ansible/playbook.yml +++ b/ansible/playbook.yml @@ -191,6 +191,18 @@ nix shell {{ nix_store_paths['supascan'] }} --command /tmp/ansible-playbook/ansible/files/supascan_ami.sh /tmp/ansible-playbook/audit-specs/baselines/$baseline + register: supascan + failed_when: false + + - name: Print supascan output + when: stage2 and supascan.rc != 0 + debug: + msg: "{{ supascan.stdout_lines + supascan.stderr_lines }}" + + - name: Fail on supascan errors + when: stage2 and supascan.rc != 0 + fail: + msg: supascan validation failed - name: Tune Swap when: stage2 From a3fd4d033d65e54c9e042d5f3f0d74577e1593c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Thu, 26 Nov 2026 03:41:01 +0200 Subject: [PATCH 15/19] fix(supascan): add discovery exceptions seen on AMI and qemu Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- audit-specs/baselines/file-discovery.yml | 34 ++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/audit-specs/baselines/file-discovery.yml b/audit-specs/baselines/file-discovery.yml index 3fb93d2dcf..85f03f4a2a 100644 --- a/audit-specs/baselines/file-discovery.yml +++ b/audit-specs/baselines/file-discovery.yml @@ -72,3 +72,37 @@ exceptions: /usr/local/bin/systemd-networkd-check-and-fix.sh: [mode] /usr/local/etc/luarocks/config-5.1.lua: [group-writable, mode] /var/lib/cloud/scripts/per-boot/supaboot.sh: [mode] + /usr/bin/at: [setuid] + /usr/sbin/mount.nfs: [setuid] + /usr/lib/aarch64-linux-gnu/utempter/utempter: [setuid] + /usr/lib/x86_64-linux-gnu/utempter/utempter: [setuid] + /var/log/pgbackrest/**: [group-writable] + /var/spool/pgbackrest: [group-writable] + /var/lib/pgbackrest: [group-writable, mode] + /etc: [group-writable, mode] + /etc/auth.d: [group-writable, mode] + /etc/envoy: [group-writable, mode] + /etc/envoy/cds.yaml: [group-writable, mode] + /etc/kong: [group-writable, mode] + /etc/pam.d/postgresql: [group-writable, mode] + /etc/pgbackrest/**: [group-writable, mode] + /etc/postgresql: [group-writable, mode] + /etc/postgresql-custom: [group-writable, mode] + /etc/postgresql-custom/conf.d: [group-writable, mode] + /etc/postgrest: [group-writable, mode] + /etc/vector: [group-writable, mode] + /etc/vector/vector.yaml: [group-writable, mode] + /etc/wal-g: [group-writable, mode] + /etc/cloud/cloud.cfg: [mode] + /etc/logrotate.d/logrotate-pgbackrest.conf: [mode] + /etc/nix: [mode] + /etc/systemd/system/vector.timer: [mode] + /etc/udev/rules.d/70-ec2-nvme-devices.rules: [mode] + /opt/gotrue: [group-writable, mode] + /opt/postgres_exporter: [group-writable, mode] + /usr/local/etc/luarocks: [group-writable, mode] + /usr/local/lib/lua/**: [group-writable, mode] + /usr/local/lib/luarocks/**: [group-writable, mode] + /usr/local/share/lua/**: [group-writable, mode] + /usr/local/share/fonts: [group-writable, mode] + /usr/local/lib/supabase-admin-agent/pgdata-chown: [mode] From 213dab2ea68cb13d40595254a1812defa5ce17fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Thu, 26 Nov 2026 03:44:31 +0200 Subject: [PATCH 16/19] fix(supascan): narrow discovery roots and categorize exceptions Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- audit-specs/baselines/file-discovery.yml | 129 +++++++++++++---------- 1 file changed, 71 insertions(+), 58 deletions(-) diff --git a/audit-specs/baselines/file-discovery.yml b/audit-specs/baselines/file-discovery.yml index 85f03f4a2a..db63b3b455 100644 --- a/audit-specs/baselines/file-discovery.yml +++ b/audit-specs/baselines/file-discovery.yml @@ -1,8 +1,12 @@ -# Exceptions come from baseline.yml (AMI arm64) and Ubuntu defaults. -roots: [/etc, /usr/local, /opt, /data, /var/lib] +# Exceptions come from baseline.yml (AMI arm64), Ubuntu defaults, and CI findings. +# required: set by Ubuntu, Nix, cloud-init, or a shared-group design. Keep. +# to-be-fixed: looser than policy because of how this repo installs it. Tighten, then remove. +roots: [/etc, /opt, /data, /var/lib] file_modes: ["0644", "0640", "0600", "0440", "0755"] dir_modes: ["0755", "0750", "0700"] exceptions: + # required: setuid binaries shipped by Ubuntu packages + /usr/bin/at: [setuid] /usr/bin/chage: [setuid] /usr/bin/chfn: [setuid] /usr/bin/chsh: [setuid] @@ -21,88 +25,97 @@ exceptions: /usr/bin/umount: [setuid] /usr/bin/wall: [setuid] /usr/bin/write.ul: [setuid] + /usr/lib/aarch64-linux-gnu/utempter/utempter: [setuid] /usr/lib/dbus-1.0/dbus-daemon-launch-helper: [setuid] /usr/lib/openssh/ssh-keysign: [setuid] /usr/lib/polkit-1/polkit-agent-helper-1: [setuid] + /usr/lib/x86_64-linux-gnu/utempter/utempter: [setuid] + /usr/sbin/mount.nfs: [setuid] /usr/sbin/pam_extrausers_chkpwd: [setuid] /usr/sbin/unix_chkpwd: [setuid] + + # required: Ubuntu, Nix, and cloud-init defaults + /etc/cloud/cloud.cfg: [mode] + /etc/machine-id: [mode] + /etc/nix: [mode] + /var/lib/cloud/instances/**: [mode] + /var/lib/cloud/scripts/per-boot/supaboot.sh: [mode] /var/local: [group-writable] - /var/mail: [group-writable] /var/log/btmp: [group-writable] /var/log/lastlog: [group-writable] /var/log/wtmp: [group-writable] - /var/lib/cloud/instances/**: [mode] - /usr/local/kong/**: [group-writable, mode] - /usr/local/openresty/**: [group-writable, mode] - /etc/vector/examples/**: [group-writable, mode] - /etc/pgbouncer-custom/**: [group-writable, mode] - /etc/postgresql-custom/extension-custom-scripts/**: [group-writable, mode] + /var/mail: [group-writable] + + # required: directories shared by the postgres and service groups + /etc/pgbackrest: [group-writable, mode] + /etc/pgbackrest/conf.d: [group-writable, mode] + /etc/wal-g: [group-writable, mode] + /var/lib/pgbackrest: [group-writable, mode] + /var/log/pgbackrest/**: [group-writable] + /var/spool/pgbackrest: [group-writable] + + # to-be-fixed: group-writable or 0775 directories created by ansible + /etc: [group-writable, mode] + /etc/auth.d: [group-writable, mode] + /etc/envoy: [group-writable, mode] + /etc/kong: [group-writable, mode] + /etc/postgresql: [group-writable, mode] + /etc/postgresql-custom: [group-writable, mode] + /etc/postgresql-custom/conf.d: [group-writable, mode] + /etc/postgrest: [group-writable, mode] + /etc/vector: [group-writable, mode] + /opt/gotrue: [group-writable, mode] + /opt/postgres_exporter: [group-writable, mode] + + # to-be-fixed: group-writable or 0664 files created by ansible + /etc/envoy/cds.yaml: [group-writable, mode] /etc/envoy/envoy.yaml: [group-writable, mode] /etc/envoy/lds.yaml: [group-writable, mode] /etc/gotrue.env: [group-writable, mode] /etc/kong/kong.conf: [group-writable, mode] /etc/kong/kong.conf.default: [group-writable, mode] /etc/kong/kong.logrotate: [group-writable, mode] - /etc/logrotate.d/logrotate-postgres-auth.conf: [mode] - /etc/logrotate.d/logrotate-postgres-csv.conf: [mode] - /etc/logrotate.d/logrotate-postgres.conf: [mode] - /etc/logrotate.d/logrotate-walg.conf: [mode] - /etc/machine-id: [mode] + /etc/pam.d/postgresql: [group-writable, mode] + /etc/pgbouncer-custom/**: [group-writable, mode] /etc/pgbouncer/userlist.txt: [group-writable, mode] /etc/postgresql-custom/custom-overrides.conf: [group-writable, mode] + /etc/postgresql-custom/extension-custom-scripts/**: [group-writable, mode] /etc/postgresql-custom/generated-optimizations.conf: [group-writable, mode] /etc/postgresql-custom/read-replica.conf: [group-writable, mode] /etc/postgresql-custom/supautils.conf: [group-writable, mode] /etc/postgresql-custom/wal-g.conf: [group-writable, mode] /etc/postgresql/pg_hba.conf: [group-writable, mode] /etc/postgrest/base.conf: [group-writable, mode] + /etc/vector/examples/**: [group-writable, mode] + /etc/vector/vector.yaml: [group-writable, mode] + /etc/wal-g/config.json: [group-writable, mode] + /usr/lib/systemd/system/kong.service: [group-writable] + + # to-be-fixed: modes outside the allowlist + /etc/logrotate.d/logrotate-pgbackrest.conf: [mode] + /etc/logrotate.d/logrotate-postgres-auth.conf: [mode] + /etc/logrotate.d/logrotate-postgres-csv.conf: [mode] + /etc/logrotate.d/logrotate-postgres.conf: [mode] + /etc/logrotate.d/logrotate-walg.conf: [mode] /etc/postgrest/merge.sh: [mode] /etc/ssl/adminapi/server.crt: [mode] /etc/ssl/adminapi/server.key: [mode] - /etc/wal-g/config.json: [group-writable, mode] + /etc/systemd/system/vector.timer: [mode] + /etc/udev/rules.d/70-ec2-nvme-devices.rules: [mode] /opt/envoy: [mode] /opt/envoy-hot-restarter.py: [mode] /opt/start-envoy.sh: [mode] - /usr/lib/systemd/system/kong.service: [group-writable] - /usr/local/bin/kong: [group-writable, mode] - /usr/local/bin/lapis: [group-writable, mode] - /usr/local/bin/luarocks: [group-writable, mode] - /usr/local/bin/luarocks-admin: [group-writable, mode] - /usr/local/bin/project-init.sh: [mode] - /usr/local/bin/systemd-networkd-check-and-fix.sh: [mode] - /usr/local/etc/luarocks/config-5.1.lua: [group-writable, mode] - /var/lib/cloud/scripts/per-boot/supaboot.sh: [mode] - /usr/bin/at: [setuid] - /usr/sbin/mount.nfs: [setuid] - /usr/lib/aarch64-linux-gnu/utempter/utempter: [setuid] - /usr/lib/x86_64-linux-gnu/utempter/utempter: [setuid] - /var/log/pgbackrest/**: [group-writable] - /var/spool/pgbackrest: [group-writable] - /var/lib/pgbackrest: [group-writable, mode] - /etc: [group-writable, mode] - /etc/auth.d: [group-writable, mode] - /etc/envoy: [group-writable, mode] - /etc/envoy/cds.yaml: [group-writable, mode] - /etc/kong: [group-writable, mode] - /etc/pam.d/postgresql: [group-writable, mode] - /etc/pgbackrest/**: [group-writable, mode] - /etc/postgresql: [group-writable, mode] - /etc/postgresql-custom: [group-writable, mode] - /etc/postgresql-custom/conf.d: [group-writable, mode] - /etc/postgrest: [group-writable, mode] - /etc/vector: [group-writable, mode] - /etc/vector/vector.yaml: [group-writable, mode] - /etc/wal-g: [group-writable, mode] - /etc/cloud/cloud.cfg: [mode] - /etc/logrotate.d/logrotate-pgbackrest.conf: [mode] - /etc/nix: [mode] - /etc/systemd/system/vector.timer: [mode] - /etc/udev/rules.d/70-ec2-nvme-devices.rules: [mode] - /opt/gotrue: [group-writable, mode] - /opt/postgres_exporter: [group-writable, mode] - /usr/local/etc/luarocks: [group-writable, mode] - /usr/local/lib/lua/**: [group-writable, mode] - /usr/local/lib/luarocks/**: [group-writable, mode] - /usr/local/share/lua/**: [group-writable, mode] - /usr/local/share/fonts: [group-writable, mode] - /usr/local/lib/supabase-admin-agent/pgdata-chown: [mode] + + # to-be-fixed: group-writable trees under /usr/local, which is outside roots + /usr/local/bin/kong: [group-writable] + /usr/local/bin/lapis: [group-writable] + /usr/local/bin/luarocks: [group-writable] + /usr/local/bin/luarocks-admin: [group-writable] + /usr/local/etc/luarocks: [group-writable] + /usr/local/etc/luarocks/config-5.1.lua: [group-writable] + /usr/local/kong/**: [group-writable] + /usr/local/lib/lua/**: [group-writable] + /usr/local/lib/luarocks/**: [group-writable] + /usr/local/openresty/**: [group-writable] + /usr/local/share/fonts: [group-writable] + /usr/local/share/lua/**: [group-writable] From d645d7b052a1a7bc55eb53b4cc5fad3a353ede4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Thu, 26 Nov 2026 03:53:28 +0200 Subject: [PATCH 17/19] ci(docker): check file policy on docker images Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/docker-image-test.yml | 10 ++++++++++ audit-specs/docker/file-discovery.yml | 17 +++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 audit-specs/docker/file-discovery.yml diff --git a/.github/workflows/docker-image-test.yml b/.github/workflows/docker-image-test.yml index 56d45c406b..70927c2ee2 100644 --- a/.github/workflows/docker-image-test.yml +++ b/.github/workflows/docker-image-test.yml @@ -104,6 +104,16 @@ jobs: echo "=== Running tests for ${{ matrix.name }} ===" nix run .#docker-image-test -- --no-build --target ${{ matrix.target }} ${{ matrix.dockerfile }} + - name: Check file policy + run: | + echo "=== File policy check for ${{ matrix.name }} ===" + root=$(mktemp -d) + container=$(docker create "pg-docker-test:${{ matrix.name }}") + trap 'docker rm "$container" >/dev/null; sudo rm -rf "$root"' EXIT + docker export "$container" | sudo tar -xpf - -C "$root" + supascan=$(nix build .#supascan --no-link --print-out-paths) + sudo "$supascan/bin/supascan" discover audit-specs/docker/file-discovery.yml --root "$root" + - name: Show container logs on failure if: failure() run: | diff --git a/audit-specs/docker/file-discovery.yml b/audit-specs/docker/file-discovery.yml new file mode 100644 index 0000000000..007ad5ae95 --- /dev/null +++ b/audit-specs/docker/file-discovery.yml @@ -0,0 +1,17 @@ +# Policy for the Docker images. They are Alpine, so the AMI exceptions do not apply. +# required: set by Alpine or Nix. Keep. +roots: [/etc, /opt, /data, /var/lib] +file_modes: ["0644", "0640", "0600", "0440", "0755"] +dir_modes: ["0755", "0750", "0700"] +exceptions: + # required: setuid binaries shipped by the Alpine shadow package + /usr/bin/chage: [setuid] + /usr/bin/chfn: [setuid] + /usr/bin/chsh: [setuid] + /usr/bin/expiry: [setuid] + /usr/bin/gpasswd: [setuid] + /usr/bin/passwd: [setuid] + + # required: Alpine and Nix defaults + /etc/network/if-up.d/dad: [group-writable, mode] + /nix/var/nix/gc-socket/socket: [world-writable, group-writable] From d25cabf913a6efaeb63a2fe2bfe62eb007887753 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Thu, 26 Nov 2026 04:59:48 +0200 Subject: [PATCH 18/19] ci(docker): fix file policy extraction root and unix_chkpwd Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/docker-image-test.yml | 1 + audit-specs/docker/file-discovery.yml | 1 + 2 files changed, 2 insertions(+) diff --git a/.github/workflows/docker-image-test.yml b/.github/workflows/docker-image-test.yml index 70927c2ee2..9b590e482a 100644 --- a/.github/workflows/docker-image-test.yml +++ b/.github/workflows/docker-image-test.yml @@ -108,6 +108,7 @@ jobs: run: | echo "=== File policy check for ${{ matrix.name }} ===" root=$(mktemp -d) + sudo chown root:root "$root" container=$(docker create "pg-docker-test:${{ matrix.name }}") trap 'docker rm "$container" >/dev/null; sudo rm -rf "$root"' EXIT docker export "$container" | sudo tar -xpf - -C "$root" diff --git a/audit-specs/docker/file-discovery.yml b/audit-specs/docker/file-discovery.yml index 007ad5ae95..ff623ae5de 100644 --- a/audit-specs/docker/file-discovery.yml +++ b/audit-specs/docker/file-discovery.yml @@ -11,6 +11,7 @@ exceptions: /usr/bin/expiry: [setuid] /usr/bin/gpasswd: [setuid] /usr/bin/passwd: [setuid] + /usr/sbin/unix_chkpwd: [setuid] # required: Alpine and Nix defaults /etc/network/if-up.d/dad: [group-writable, mode] From 085df0c04eb2ef0cf891d4a518fc241d7d99d1f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rton=20Boros?= Date: Thu, 26 Nov 2026 05:06:35 +0200 Subject: [PATCH 19/19] chore(supascan): mark adminapi-written config exceptions as required Refs: MPG-1599 Co-Authored-By: Claude Sonnet 5.5 --- audit-specs/baselines/file-discovery.yml | 34 +++++++++++++----------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/audit-specs/baselines/file-discovery.yml b/audit-specs/baselines/file-discovery.yml index db63b3b455..a10e56657f 100644 --- a/audit-specs/baselines/file-discovery.yml +++ b/audit-specs/baselines/file-discovery.yml @@ -54,41 +54,43 @@ exceptions: /var/log/pgbackrest/**: [group-writable] /var/spool/pgbackrest: [group-writable] - # to-be-fixed: group-writable or 0775 directories created by ansible + # required: config the adminapi service writes through its group membership /etc: [group-writable, mode] /etc/auth.d: [group-writable, mode] /etc/envoy: [group-writable, mode] + /etc/envoy/cds.yaml: [group-writable, mode] + /etc/envoy/envoy.yaml: [group-writable, mode] + /etc/envoy/lds.yaml: [group-writable, mode] /etc/kong: [group-writable, mode] + /etc/pgbouncer-custom/**: [group-writable, mode] /etc/postgresql: [group-writable, mode] /etc/postgresql-custom: [group-writable, mode] /etc/postgresql-custom/conf.d: [group-writable, mode] + /etc/postgresql-custom/custom-overrides.conf: [group-writable, mode] + /etc/postgresql-custom/extension-custom-scripts/**: [group-writable, mode] + /etc/postgresql-custom/generated-optimizations.conf: [group-writable, mode] + /etc/postgresql-custom/read-replica.conf: [group-writable, mode] + /etc/postgresql-custom/supautils.conf: [group-writable, mode] + /etc/postgresql-custom/wal-g.conf: [group-writable, mode] + /etc/postgresql/pg_hba.conf: [group-writable, mode] /etc/postgrest: [group-writable, mode] + /etc/postgrest/base.conf: [group-writable, mode] /etc/vector: [group-writable, mode] + /etc/vector/examples/**: [group-writable, mode] + /etc/vector/vector.yaml: [group-writable, mode] + /etc/wal-g/config.json: [group-writable, mode] /opt/gotrue: [group-writable, mode] + + # to-be-fixed: group-writable or 0775 directories created by ansible /opt/postgres_exporter: [group-writable, mode] # to-be-fixed: group-writable or 0664 files created by ansible - /etc/envoy/cds.yaml: [group-writable, mode] - /etc/envoy/envoy.yaml: [group-writable, mode] - /etc/envoy/lds.yaml: [group-writable, mode] /etc/gotrue.env: [group-writable, mode] /etc/kong/kong.conf: [group-writable, mode] /etc/kong/kong.conf.default: [group-writable, mode] /etc/kong/kong.logrotate: [group-writable, mode] /etc/pam.d/postgresql: [group-writable, mode] - /etc/pgbouncer-custom/**: [group-writable, mode] /etc/pgbouncer/userlist.txt: [group-writable, mode] - /etc/postgresql-custom/custom-overrides.conf: [group-writable, mode] - /etc/postgresql-custom/extension-custom-scripts/**: [group-writable, mode] - /etc/postgresql-custom/generated-optimizations.conf: [group-writable, mode] - /etc/postgresql-custom/read-replica.conf: [group-writable, mode] - /etc/postgresql-custom/supautils.conf: [group-writable, mode] - /etc/postgresql-custom/wal-g.conf: [group-writable, mode] - /etc/postgresql/pg_hba.conf: [group-writable, mode] - /etc/postgrest/base.conf: [group-writable, mode] - /etc/vector/examples/**: [group-writable, mode] - /etc/vector/vector.yaml: [group-writable, mode] - /etc/wal-g/config.json: [group-writable, mode] /usr/lib/systemd/system/kong.service: [group-writable] # to-be-fixed: modes outside the allowlist