From 7da863cfd19b48bc0595f137d23eab5b72c3d50e Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Sun, 22 Nov 2026 07:05:11 -0800 Subject: [PATCH 1/5] Scan only the WHP scan scope: whp-scan-scope + clamscan --file-list, scan attestation in report.json - Dockerfile: multi-stage Go build of whp-scan-scope (CGO off, stdlib only) from a PINNED commit of the WHP repo (ARG WHP_COMMIT, currently the merge of WHP #331; bump it to the merge of the 2000 MiB limit PR before publishing an image meant to enforce it). Private repo: the BuildKit secret whp_token in CI; --build-context whp-src= for local builds. - scan-files.php: whp-scan-scope -> /tmp/scan.list + stats, then clamscan --file-list with --max-filesize=2000M --max-scansize=4000M --max-scantime=0 --alert-exceeds-max=yes --tempdir on the disk scratch. A missing/failing tool, clamscan exit >= 2 or 0 loaded signatures is FATAL (no fall back to an unscoped scan). Writes the attestation (the tool's stats + engine_version, signature_db_version, signatures_loaded, clamscan_exit). - entrypoint.sh: passes --attestation/--scratch, removes the scratch, embeds the attestation as report.json "scan" (objects kept as objects). - Tests: tests/run-tests.sh (stub clamscan, real tool, fail-closed cases), tests/build-scope-tree.sh (polyglot, web-root symlink, docroot under tmp, handler dir, uploads, EICAR, sparse 2001 MiB mp4), tests/image-scope-test.sh (end to end on the built image; CI runs it). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6 --- .gitea/workflows/build-push.yaml | 10 ++ CONTRIBUTING.md | 6 + Dockerfile | 51 ++++++ README.md | 20 +++ scripts/entrypoint.sh | 20 ++- scripts/scan-files.php | 259 +++++++++++++++++-------------- tests/build-scope-tree.sh | 70 +++++++++ tests/image-scope-test.sh | 72 +++++++++ tests/run-tests.sh | 98 +++++++++--- 9 files changed, 469 insertions(+), 137 deletions(-) create mode 100755 tests/build-scope-tree.sh create mode 100755 tests/image-scope-test.sh diff --git a/.gitea/workflows/build-push.yaml b/.gitea/workflows/build-push.yaml index 897439c..099ef2b 100644 --- a/.gitea/workflows/build-push.yaml +++ b/.gitea/workflows/build-push.yaml @@ -115,6 +115,8 @@ jobs: build-args: | BASE_IMAGE=${{ steps.base.outputs.image }} PKG_CACHE=${{ steps.pkgcache.outputs.url }} + secrets: | + whp_token=${{ secrets.CI_TOKEN }} tags: cpanel-importer:smoke no-cache: true @@ -130,6 +132,12 @@ jobs: fi echo "smoke test passed" + # The scan scope end to end: the real entrypoint, ClamAV and whp-scan-scope on a synthetic + # backup (polyglot, symlink, docroot under tmp, handler dir, EICAR, a sparse 2001 MiB mp4); + # checks the report.json `scan` object. Needs only docker + tar on the runner. + - name: Scan scope end-to-end test + run: bash tests/image-scope-test.sh cpanel-importer:smoke + # Lints run inside the just-built image rather than on the runner side. # The Dockerfile already COPYs scripts/ to /scripts/ inside the image, # so we don't need a host bind mount (the original `docker run -v @@ -161,6 +169,8 @@ jobs: build-args: | BASE_IMAGE=${{ steps.base.outputs.image }} PKG_CACHE=${{ steps.pkgcache.outputs.url }} + secrets: | + whp_token=${{ secrets.CI_TOKEN }} tags: ${{ steps.tags.outputs.tags }} cache-from: type=registry,ref=repo.anhonesthost.net/cloud-hosting-platform/cpanel-importer:latest cache-to: type=inline diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f394afc..b180975 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -204,3 +204,9 @@ Pushes to `trunk` build + push the image to before pushing. See `.gitea/workflows/build-push.yaml`. + +## Tests + +- `WHP_SCAN_SCOPE_BIN=/path/to/whp-scan-scope bash tests/run-tests.sh` (or `IMAGE=` to take the binary from it): + host-side, no image build, stub clamscan; covers extract.sh and scan-files.php incl. the scan scope and its fail-closed cases. +- `bash tests/image-scope-test.sh `: end to end on the built image (real ClamAV, real entrypoint, EICAR, sparse 2001 MiB mp4). CI runs it. diff --git a/Dockerfile b/Dockerfile index 6f567c7..2b9565f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,6 +10,56 @@ # so the pkg-cache registry mirror can only serve content-addressed blobs. # Local builds use the tag. Canonical docs: cloud-apache-container docs/pkg-cache.md. ARG BASE_IMAGE=almalinux:10-minimal + +# --- whp-scan-scope: the scan-scope tool of the WHP panel repo ------------- +# Decides which files of the extract clamscan sees (code and risky files; the +# mail tree and clean bulk media are skipped) and writes the scope attestation +# the panel's privd checks. Built from a PINNED commit of the (private) WHP +# repo, stdlib only, CGO off, static. Source: panel/cmd/whp-scan-scope and +# panel/internal/cpimport/scanscope; policy docs: docs/runbooks/account-transfer-scan-scope.md +# in that repo. +# +# WHP_COMMIT MUST be a full 40-hex commit sha and MUST be bumped when the +# scan policy changes. It is currently the merge of WHP PR #331 (limit 256 MiB); +# bump it to the merge commit of the WHP PR that raises the limit to 2000 MiB +# (feat/scan-scope-2gib) BEFORE publishing an image that is meant to enforce it. +# CI passes the repo token as the BuildKit secret `whp_token` (read access to +# cloud-hosting-platform/whp). For a local build without network access to the +# repo, override the whole source stage with a checkout: +# docker buildx build --build-context whp-src=/path/to/whp-checkout ... +ARG GO_IMAGE=golang:1.27-alpine +ARG WHP_REPO=https://repo.anhonesthost.net/cloud-hosting-platform/whp.git +ARG WHP_COMMIT=e668e25dcdc1938d9d9399ea904daba71c0f0778 + +FROM ${GO_IMAGE} AS whp-fetch +ARG WHP_REPO +ARG WHP_COMMIT +RUN apk add --no-cache git +RUN --mount=type=secret,id=whp_token,required=false \ + set -eu; \ + case "${WHP_COMMIT}" in *[!0-9a-f]*|"") echo "WHP_COMMIT must be a full lowercase hex sha" >&2; exit 1;; esac; \ + [ "${#WHP_COMMIT}" -eq 40 ] || { echo "WHP_COMMIT must be 40 hex chars" >&2; exit 1; }; \ + git init -q /whp && cd /whp; \ + if [ -s /run/secrets/whp_token ]; then \ + git -c "http.extraHeader=Authorization: token $(cat /run/secrets/whp_token)" fetch -q --depth 1 "${WHP_REPO}" "${WHP_COMMIT}"; \ + else \ + git fetch -q --depth 1 "${WHP_REPO}" "${WHP_COMMIT}"; \ + fi; \ + git checkout -q FETCH_HEAD; \ + [ "$(git rev-parse HEAD)" = "${WHP_COMMIT}" ] || { echo "fetched commit is not the pinned one" >&2; exit 1; } +# Named context `whp-src` (see above) replaces this stage; its root is a repo root. +FROM scratch AS whp-src +COPY --from=whp-fetch /whp/panel /panel + +FROM ${GO_IMAGE} AS whp-scan-scope-build +COPY --from=whp-src /panel /src/panel +WORKDIR /src/panel +# stdlib only: no module download may be needed (GOFLAGS=-mod=mod and GOPROXY=off prove it). +ENV CGO_ENABLED=0 GOFLAGS=-trimpath GOPROXY=off GOTOOLCHAIN=local +RUN go build -ldflags="-s -w" -o /out/whp-scan-scope ./cmd/whp-scan-scope +# smoke: no arguments is a usage error (exit 2) +RUN set +e; /out/whp-scan-scope 2>/dev/null; test $? -eq 2 + FROM ${BASE_IMAGE} LABEL org.opencontainers.image.title="cpanel-importer" @@ -173,6 +223,7 @@ RUN set -eux; \ chmod -R u=rwX,g=rX,o= /var/lib/clamav ; \ ls -la /var/lib/clamav/ +COPY --from=whp-scan-scope-build /out/whp-scan-scope /usr/local/bin/whp-scan-scope COPY --chown=whp-import:whp-import scripts/ /scripts/ RUN chmod 0755 /scripts/entrypoint.sh /scripts/extract.sh \ /scripts/scan-files.php /scripts/scan-dbs.php diff --git a/README.md b/README.md index 7aeb393..b66d8e9 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,26 @@ message would silently drop mail, and multi-GB maildirs would dominate the run. `report.json` then carries `"mail_included": true`; images older than this option never write the key, which is how WHP tells them apart. +### Scan scope (what ClamAV sees) + +ClamAV does not walk the whole extract. `/usr/local/bin/whp-scan-scope` (built into the image from a +**pinned commit** of the WHP repo: `WHP_COMMIT` in the Dockerfile, packages `panel/cmd/whp-scan-scope` and +`panel/internal/cpimport/scanscope`) lists the code and risky files (policy `code-risky-v1`: code, +exec/ELF files, polyglot-capable media under a web root, handler-mapped directories, symlink targets, docroots +named by `userdata`; NOT the mail tree, logs, clean bulk media or plain data outside web roots) and +`scan-files.php` hands exactly that list to `clamscan --file-list`. Limits: files up to **2000 MiB** are scanned +(`--max-filesize=2000M`; ClamAV 1.4 cannot scan 2 GiB or more at all); above that the tool counts the file +(`oversize_unscanned_files` for clean media/archives: a staff-review warning; `in_scope_unscanned_files` for +anything else: the panel refuses the import). `report.json` carries the tool's whole stats object plus the engine +fields as its `scan` object; the panel's privd validates it. **No tool, no scan:** a missing or failing +`whp-scan-scope`, or clamscan exit >= 2, fails the run (`status: failed`), there is no fall back to an unscoped scan. +`--tempdir` of clamscan is the disk scratch `/host/sanitized//work/clamtmp` (removed after the scan), never the +RAM `/tmp`. + +Bump `WHP_COMMIT` whenever the WHP scan policy or limits change (it must be a full 40-hex sha). Local build without +access to the private repo: `docker buildx build --build-context whp-src=/path/to/whp-checkout -t cpanel-importer:dev .`. +In CI the repo token is the BuildKit secret `whp_token`. + Container exits with status `0` on success, non-zero on any failure (missing/unreadable backup, dangerous symlink found, scanner error). Even on failure, `/host/sanitized//report.json` is written diff --git a/scripts/entrypoint.sh b/scripts/entrypoint.sh index ed2ca83..fa37be2 100755 --- a/scripts/entrypoint.sh +++ b/scripts/entrypoint.sh @@ -162,13 +162,19 @@ if [[ "$IMPORT_INCLUDE_MAIL" == "true" ]]; then # The extracted mail tree is not scanned (see scan-files.php --skip-mail). SCAN_FILES_EXTRA+=(--skip-mail) fi +# clamscan unpacks archives into --tempdir: on the disk-backed bind mount (never the RAM tmpfs /tmp, +# which counts against --memory). Removed again right after the scan. +CLAM_SCRATCH="$WORK_DIR/clamtmp" php /scripts/scan-files.php \ --extract "$EXTRACT_DIR" \ --quarantine "$QUARANTINE_DIR" \ --report /tmp/scan-files-report.json \ + --attestation /tmp/scan-attestation.json \ + --scratch "$CLAM_SCRATCH" \ --import-id "$IMPORT_ID" \ "${SCAN_FILES_EXTRA[@]}" \ - || die "scan-files.php failed; see stderr above" + || { rm -rf "$CLAM_SCRATCH"; die "scan-files.php failed (scope tool or clamscan error: the scan did not complete); see stderr above"; } +rm -rf "$CLAM_SCRATCH" # --- DB engine swap + WP content scan ------------------------------------- @@ -216,6 +222,15 @@ $dbsPath = $argv[4]; $strippedPath = $argv[5]; $outPath = $argv[6]; $mailIncluded = $argv[7] === "true"; +$attestPath = $argv[8]; + +// The scan attestation (engine fields + the whole scope stats of whp-scan-scope), written by scan-files.php. +// Decoded as objects so an empty skipped_by_class stays {} (not []). No attestation = no report. +$scan = is_file($attestPath) ? json_decode(file_get_contents($attestPath)) : null; +if (!is_object($scan)) { + fprintf(STDERR, "report: scan attestation missing or unreadable: %s\n", $attestPath); + exit(1); +} $files = is_file($filesPath) ? json_decode(file_get_contents($filesPath), true) : null; $dbs = is_file($dbsPath) ? json_decode(file_get_contents($dbsPath), true) : null; @@ -280,6 +295,7 @@ $report = [ // mail tree. Older images never write the key; the panel treats a // missing/false value as "mail was not extracted". "mail_included" => $mailIncluded, + "scan" => $scan, "actions" => $actions, "databases" => $databases, "summary_for_panel" => [ @@ -291,7 +307,7 @@ $report = [ file_put_contents($outPath, json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n"); fprintf(STDERR, "report written: %s\n", $outPath); -' "$IMPORT_ID" "$DURATION" /tmp/scan-files-report.json /tmp/scan-dbs-report.json "$STRIPPED_SYMLINKS_FILE" "$SANITIZED_DIR/report.json" "$IMPORT_INCLUDE_MAIL" \ +' "$IMPORT_ID" "$DURATION" /tmp/scan-files-report.json /tmp/scan-dbs-report.json "$STRIPPED_SYMLINKS_FILE" "$SANITIZED_DIR/report.json" "$IMPORT_INCLUDE_MAIL" /tmp/scan-attestation.json \ || die "report merge failed" log "done — exited cleanly after ${DURATION}s" diff --git a/scripts/scan-files.php b/scripts/scan-files.php index 1e5f6c9..f97c94c 100755 --- a/scripts/scan-files.php +++ b/scripts/scan-files.php @@ -6,21 +6,36 @@ * registry (KNOWN_REMOVABLE / REMOVABLE_WITH_BACKUP) is stubbed below * for v1.1 expansion; see CONTRIBUTING.md for how to wire one in. * + * Scope: only code and risky files are scanned. whp-scan-scope (built from the + * WHP panel repo, see the Dockerfile) walks the extract, writes the list of + * files clamscan must see and the stats of what it skipped (policy + * code-risky-v1); clamscan then runs with --file-list. A missing or failing + * whp-scan-scope or clamscan is FATAL (exit 1): there is no fall back to an + * unscoped or partial scan. The merged attestation (the stats plus the engine + * fields) is written to --attestation and becomes report.json's `scan` object. + * * Usage: - * scan-files.php --extract --quarantine --report --import-id [--skip-mail] + * scan-files.php --extract --quarantine --report --attestation + * --import-id [--scratch ] [--skip-mail] [--scope-bin ] * * --skip-mail: do not scan (or count, or quarantine anything in) the * /homedir/mail tree (any top-level dir). entrypoint.sh passes it when the mail tree * was extracted for WHP's mailbox import (IMPORT_INCLUDE_MAIL=true). * + * --scratch: disk-backed directory for clamscan's temp files (archive + * unpacking). /tmp is a RAM tmpfs in the sandbox, so a large archive there + * would blow the memory limit. The caller removes it afterwards. + * --scope-bin: path of whp-scan-scope (tests only; default /usr/local/bin/whp-scan-scope). + * * Exit codes: * 0 — scan completed (regardless of how many hits) - * 1 — fatal scanner error (clamscan binary missing, signature DB unreadable) + * 1 — fatal scanner error (whp-scan-scope or clamscan missing or failed, + * clamscan exit >= 2, signature DB unreadable, unusable stats) * 2 — usage error * * Report shape: matches spec §3, e.g.: * { - * "files_scanned": N, + * "files_scanned": N, // = length of the clamscan file list * "files_clean": N, * "files_cleaned": 0, // always 0 in v1.0 — no cleaners yet * "files_quarantined": N, @@ -30,18 +45,37 @@ require __DIR__ . '/lib/safety-net.php'; -const SCANNER_VERSION = '1.0.0'; +const SCANNER_VERSION = '1.1.0'; -$opts = getopt('', ['extract:', 'quarantine:', 'report:', 'import-id:', 'skip-mail']); -foreach (['extract', 'quarantine', 'report', 'import-id'] as $k) { +// Limits of the clamscan run. MAX_FILESIZE_MIB is the file size above which clamscan skips a +// file; it MUST be >= whp-scan-scope's --max-filesize (default 2000 MiB): a file the tool lists +// is never above it, and one above it is counted by the tool (in_scope_unscanned or +// oversize_unscanned), never silently skipped. ClamAV 1.4 cannot scan a file above 2 GiB - 1 at all +// (it warns "scanning files greater than 2147483647 bytes is not supported"), so 2000 MiB is also +// close to the ceiling: do not raise it past 2047. MAX_SCANSIZE_MIB must be >= MAX_FILESIZE_MIB +// (measured: with 512M a single 1999 MiB file is reported "Heuristics.Limits.Exceeded.MaxScanSize"). +// MAX_SCANTIME_MS 0 = no per-file time limit: with --alert-exceeds-max=yes a file that hit the limit +// would be reported as a detection and QUARANTINED (a good file removed from the customer's site); +// a runaway scan is bounded by the sandbox's own run timeout instead (the run then fails). +const MAX_FILESIZE_MIB = 2000; +const MAX_SCANSIZE_MIB = 4000; +const MAX_SCANTIME_MS = 0; +const MAX_RECURSION = 8; +const MAX_FILES = 10000; + +$opts = getopt('', ['extract:', 'quarantine:', 'report:', 'attestation:', 'import-id:', 'scratch:', 'scope-bin:', 'skip-mail']); +foreach (['extract', 'quarantine', 'report', 'attestation', 'import-id'] as $k) { if (!isset($opts[$k])) { - fwrite(STDERR, "usage: scan-files.php --extract --quarantine --report --import-id [--skip-mail]\n"); + fwrite(STDERR, "usage: scan-files.php --extract --quarantine --report --attestation --import-id [--scratch ] [--skip-mail]\n"); exit(2); } } $extractDir = rtrim($opts['extract'], '/'); $quarantineDir = rtrim($opts['quarantine'], '/'); $reportPath = $opts['report']; +$attestPath = $opts['attestation']; +$scratchDir = isset($opts['scratch']) ? rtrim($opts['scratch'], '/') : ''; +$scopeBin = $opts['scope-bin'] ?? '/usr/local/bin/whp-scan-scope'; $importId = $opts['import-id']; $skipMail = array_key_exists('skip-mail', $opts); @@ -84,29 +118,96 @@ if ($skipMail) { // ]; $cleaners = []; -// -- run clamscan recursively over the extract dir -------------------------- +// -- scope: decide which files clamscan sees -------------------------------- -// We use --infected so the output is only hits, and --recursive so we -// walk subdirectories. We deliberately do NOT use --remove (we never want -// clamscan unlinking files — we control quarantine). -// -// Output format per line on a hit: -// /tmp/extract/foo/bar.php: Some.Signature.Name FOUND -$cmd = sprintf( - 'clamscan --infected --recursive --no-summary --stdout %s%s 2>/dev/null', - $skipMail ? '--exclude-dir=' . escapeshellarg($mailDirEre) . ' ' : '', - escapeshellarg($extractDir) -); - -$fh = popen($cmd, 'r'); -if (!$fh) { - fwrite(STDERR, "scan-files: failed to spawn clamscan\n"); - exit(1); +/** + * Run a command (argv array, no shell); returns [exit code, stdout]. stderr goes to $errTo (a file path) or, + * when null, to ours. Pipes only: open_basedir (safety-net.php) refuses /dev/null. + */ +function run_cmd(array $argv, ?string $errTo): array { + $desc = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => $errTo === null ? STDERR : ['file', $errTo, 'w']]; + $p = @proc_open($argv, $desc, $pipes); + if (!is_resource($p)) return [-1, '']; + fclose($pipes[0]); + $out = stream_get_contents($pipes[1]); + fclose($pipes[1]); + return [proc_close($p), (string) $out]; } +$listPath = '/tmp/scan.list'; +$statsPath = '/tmp/scan-scope.json'; +$scopeArgv = [$scopeBin, '--extract', $extractDir, '--file-list', $listPath, '--stats', $statsPath]; +if ($skipMail) $scopeArgv[] = '--skip-mail'; +// stderr of the tool is our stderr (the import log). Its --max-filesize stays at its default (2000 MiB). +[$rc, ] = run_cmd($scopeArgv, null); +if ($rc !== 0) { + // -1: proc_open could not start it (missing or not executable): never fall back to an unscoped scan + fwrite(STDERR, "scan-files: FATAL: whp-scan-scope ($scopeBin) " . ($rc === -1 ? "could not be started (missing?)" : "exited $rc") . ": the scan scope is unknown, the scan failed\n"); + exit(1); +} +$stats = json_decode((string) @file_get_contents($statsPath)); +$intKeys = ['scope_version', 'files_total', 'files_scanned', 'files_skipped_by_policy', 'in_scope_unscanned', 'oversize_unscanned']; +$bad = !is_object($stats) || !is_string($stats->policy ?? null) || !is_object($stats->skipped_by_class ?? null) + || !is_array($stats->in_scope_unscanned_files ?? null) || !is_array($stats->oversize_unscanned_files ?? null); +foreach ($intKeys as $k) { + if (!isset($stats->$k) || !is_int($stats->$k)) $bad = true; +} +if ($bad) { + fwrite(STDERR, "scan-files: FATAL: whp-scan-scope wrote unusable stats ($statsPath)\n"); + exit(1); +} +$filesScanned = $stats->files_scanned; +fwrite(STDERR, sprintf( + "scan-files: scope %s v%d: total=%d scanned=%d skipped-by-policy=%d in-scope-unscanned=%d oversize-unscanned=%d\n", + $stats->policy, $stats->scope_version, $stats->files_total, $stats->files_scanned, + $stats->files_skipped_by_policy, $stats->in_scope_unscanned, $stats->oversize_unscanned +)); + +// -- clamscan over the file list --------------------------------------------- + +// Engine and database version: "ClamAV 1.4.3/28191/Sun Nov 22 08:25:05 2026". +[$vrc, $vout] = run_cmd(['clamscan', '--version'], null); +$vparts = explode('/', trim($vout)); +if ($vrc !== 0 || count($vparts) < 2 || strpos($vparts[0], 'ClamAV ') !== 0) { + fwrite(STDERR, "scan-files: FATAL: clamscan --version failed (rc=$vrc)\n"); + exit(1); +} +$engineVersion = trim(substr($vparts[0], 7)); +$sigDbVersion = trim($vparts[1]); + +// --infected: only hits (and the summary) on stdout. We never use --remove: we control quarantine. +// --alert-exceeds-max=yes: a limit hit inside an archive (max-scansize, max-files, max-recursion, +// max-scantime) is reported as a "Heuristics.Limits.Exceeded" detection instead of a silent partial scan. +// --tempdir: disk-backed scratch (see the header); the summary is kept for "Known viruses". +// (no is_executable() probes: open_basedir refuses paths outside the container allow-list) +$clamArgv = array_merge(['nice', '-n', '19', 'ionice', '-c3'], [ + 'clamscan', '--infected', '--stdout', + '--file-list=' . $listPath, + '--max-filesize=' . MAX_FILESIZE_MIB . 'M', + '--max-scansize=' . MAX_SCANSIZE_MIB . 'M', + '--max-scantime=' . MAX_SCANTIME_MS, + '--max-recursion=' . MAX_RECURSION, + '--max-files=' . MAX_FILES, + '--alert-exceeds-max=yes', +]); +if ($scratchDir !== '') { + @mkdir($scratchDir, 0700, true); + $clamArgv[] = '--tempdir=' . $scratchDir; +} +$clamErr = '/tmp/clamscan.err'; +[$clamRc, $clamOut] = run_cmd($clamArgv, $clamErr); +if ($clamRc < 0 || $clamRc > 1) { + fwrite(STDERR, "scan-files: FATAL: clamscan exited $clamRc (>= 2 is an error, not a result): the scan failed\n"); + fwrite(STDERR, (string) @file_get_contents($clamErr)); + exit(1); +} +$known = 0; $hits = []; -while (($line = fgets($fh)) !== false) { - $line = rtrim($line, "\r\n"); +foreach (preg_split('/\r?\n/', $clamOut) as $line) { + if (preg_match('/^Known viruses: (\d+)$/', $line, $m)) { + $known = (int) $m[1]; + continue; + } if ($line === '' || !str_ends_with($line, ' FOUND')) continue; // Strip trailing ' FOUND'. $body = substr($line, 0, -6); @@ -115,103 +216,35 @@ while (($line = fgets($fh)) !== false) { $path = substr($body, 0, $colon); $sig = substr($body, $colon + 2); if (!str_starts_with($path, $extractDir)) { - // Defensive: shouldn't happen with our invocation. + // Defensive: the list only holds paths below the extract dir. continue; } if ($skipMail && preg_match($mailDirPcre, $path)) { - // Belt: --exclude-dir should have kept clamscan out of the mail - // tree; never move a message out of a Maildir regardless. + // Belt: the scope never lists the mail tree; never move a message out of a Maildir regardless. fwrite(STDERR, "scan-files: WARN ignoring a hit inside the mail tree: $path\n"); continue; } $hits[] = ['path' => $path, 'signature' => $sig]; } -pclose($fh); - -// File count — we need files_scanned for the report. clamscan's summary -// counting is suppressed; do a fast file count ourselves. -// -// Symlinks are skipped entirely: -// 1. cPanel cpmove tarballs contain symlinks with absolute targets that -// point at the SOURCE server's filesystem (e.g., /home//...) -// which don't exist inside the container. PHP's SplFileInfo::isFile() -// tries to follow the symlink, the resolved target is not under any -// open_basedir-allowed prefix, and PHP throws RuntimeException -// mid-iteration — aborting the whole scan. -// 2. clamscan itself handles symlinks via its own walk (default: does -// NOT follow them — same posture we want). Counting them here would -// double-count vs clamscan's signal anyway. -// 3. Quarantining a symlink-file is meaningless (it's a 0-byte fs entry -// whose target is the actual artifact). -// -// Use a CallbackFilterIterator that performs an lstat-based isLink() check -// BEFORE the iterator hands the entry off to RecursiveIteratorIterator's -// hasChildren / isFile follow-paths. is_link() is open_basedir-safe. -// The try/catch is a defense-in-depth belt: if any other fs-op throws -// (e.g. a symlink that races mid-walk), skip the entry rather than abort. -$filesScanned = 0; -$skippedLinks = 0; -$walkErrors = 0; - -// Silence open_basedir E_WARNINGs during the walk. cPanel cpmove tarballs -// frequently contain symlinks pointing at the SOURCE server's absolute -// paths (db.php -> /home///wp-content/db.php, access-logs -> -// /usr/local/apache/domlogs/, etc.). PHP's open_basedir check -// normalizes via realpath() even for is_link/is_file; when the symlink -// target lies outside the container's allow-list (it does — there's no -// /home or /usr/local in the container), PHP emits a Warning per call. -// Our filter callback STILL returns the right answer (is_link returns -// true even when warning), so the skip-symlink logic works regardless -// of the noise — but the noise floods 100k+ lines into the import log -// for a typical customer account, drowning the actually-useful -// quarantine actions. -// -// set_error_handler limited to E_WARNING with a needle filter is -// narrower than `error_reporting(0)` (we still surface non-open_basedir -// warnings) and narrower than `@`-prefixing every call site (covers -// PHP-internal callbacks invoked deep inside the iterator). -$prevHandler = set_error_handler(function ($errno, $errstr) { - if ($errno === E_WARNING && strpos($errstr, 'open_basedir restriction') !== false) { - return true; // suppress - } - return false; // let PHP handle (or chain to previous handler) -}, E_WARNING); - -$rdi = new RecursiveDirectoryIterator( - $extractDir, - FilesystemIterator::SKIP_DOTS | FilesystemIterator::CURRENT_AS_PATHNAME -); -$filter = new RecursiveCallbackFilterIterator($rdi, function ($pathname, $key, $iterator) use (&$skippedLinks, $skipMail, $mailDirPcre) { - // $pathname is a string when CURRENT_AS_PATHNAME is set. - if (is_link($pathname)) { - $skippedLinks++; - return false; - } - if ($skipMail && preg_match($mailDirPcre, $pathname)) { - return false; // not scanned, so not counted as scanned - } - return true; -}); -$it = new RecursiveIteratorIterator($filter, RecursiveIteratorIterator::LEAVES_ONLY); -foreach ($it as $pathname) { - try { - // is_file() will follow symlinks, but we already filtered links - // out. For regular files this is a cheap stat. - if (is_file($pathname)) { - $filesScanned++; - } - } catch (\Throwable $e) { - // Belt: a race or filesystem oddity here shouldn't bomb the whole - // scanner. Log + continue. - $walkErrors++; - } +if ($known <= 0) { + fwrite(STDERR, "scan-files: FATAL: clamscan loaded no signatures (Known viruses: $known): nothing was scanned\n"); + exit(1); } -restore_error_handler(); -fwrite(STDERR, sprintf( - "scan-files: file walk: counted=%d, symlinks-skipped=%d, walk-errors=%d\n", - $filesScanned, $skippedLinks, $walkErrors -)); +// The attestation the panel's privd reads: the CLI's stats object as written (every key, unchanged) +// plus the engine fields. privd refuses a scope it cannot account for (files_total must equal +// scanned + skipped + in_scope_unscanned + oversize_unscanned). +$attest = clone $stats; +$attest->engine_version = $engineVersion; +$attest->signature_db_version = $sigDbVersion; +$attest->signatures_loaded = $known; +$attest->clamscan_exit = $clamRc; +if (@file_put_contents($attestPath, json_encode($attest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n") === false) { + fwrite(STDERR, "scan-files: FATAL: cannot write $attestPath\n"); + exit(1); +} +fwrite(STDERR, sprintf("scan-files: clamscan %s (db %s, %d signatures): exit %d, %d hit(s) in %d file(s)\n", + $engineVersion, $sigDbVersion, $known, $clamRc, count($hits), $filesScanned)); // -- classify + action each hit -------------------------------------------- diff --git a/tests/build-scope-tree.sh b/tests/build-scope-tree.sh new file mode 100755 index 0000000..68637c6 --- /dev/null +++ b/tests/build-scope-tree.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# +# build-scope-tree.sh [--big] -- a synthetic extracted backup that exercises the scan scope +# (policy code-risky-v1 of whp-scan-scope; the cases come from the six security-review rounds of the +# WHP scanscope package). No customer data. /cpmove-scope/... is the layout of an extract. +# +# --big also add a SPARSE 2001 MiB clean mp4 (just above the 2000 MiB limit): it must show up in +# oversize_unscanned_files (named staff-review warning), never on the clamscan list. +# +# The EXPECT_* lists below are the contract tests check, one path per line relative to . +set -euo pipefail +ROOT="${1:?usage: build-scope-tree.sh [--big]}" +BIG=false; [[ "${2:-}" == "--big" ]] && BIG=true +T="$ROOT/cpmove-scope" +H="$T/homedir" +mkdir -p "$T/userdata" "$H/public_html/hd" "$H/public_html/uploads" "$H/tmp/site" "$H/tmp/work" "$H/etc" \ + "$H/mail/example.com/alice/cur" "$H/logs" + +# userdata: the main docroot and an addon docroot that lives under ~/tmp (served, so a web root) +cat > "$T/userdata/example.com" < "$T/userdata/site.example.com" < "$H/public_html/index.php" # code +printf '\xff\xd8\xff\xe0' > "$H/public_html/polyglot.jpg" # polyglot: JPEG magic + php (media under 20 MiB is always scanned) +printf '\xff\xd8\xff\xe0JFIF clean' > "$H/public_html/clean-small.jpg" # small media under a web root: scanned too +echo 'payload' > "$H/tmp/work/payload.txt" +ln -s ../tmp/work/payload.txt "$H/public_html/link.jpg" # web-root symlink: its TARGET is scanned +echo ' "$H/tmp/site/page.php" # docroot-under-tmp: web root +echo 'plain data in a docroot under tmp' > "$H/tmp/site/notes.txt" # ... so even data is scanned there +printf 'AddHandler application/x-httpd-php .jpg\n' > "$H/public_html/hd/.htaccess" # handler directory: everything below is in scope +printf '\xff\xd8\xff\xe0JFIF in a handler dir' > "$H/public_html/hd/handled.jpg" +echo 'upload blob' > "$H/public_html/uploads/blob.dat" # uploads dir: scanned unless verified media +printf 'X5O!P%%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*' > "$H/public_html/eicar.php" # a real ClamAV hit + +# --- skipped by policy --- +echo 'log line' > "$H/logs/access.log" # data outside a web root +echo 'a=1' > "$H/etc/data.txt" +echo 'Subject: hi' > "$H/mail/example.com/alice/cur/1700000000.M1P1.host,S=12:2,S" # mail (skipped with --skip-mail) +{ printf '\x00\x00\x00\x18ftypmp42'; head -c 22000000 /dev/zero; } > "$H/public_html/video.mp4" # clean media over 20 MiB: skipped (class media) +if $BIG; then + { printf '\x00\x00\x00\x18ftypmp42'; } > "$H/public_html/huge.mp4" + truncate -s 2001M "$H/public_html/huge.mp4" # sparse, above the 2000 MiB limit +fi + +cat > "$ROOT/EXPECT_LISTED" < "$ROOT/EXPECT_NOT_LISTED" < "$ROOT/EXPECT_MAIL" diff --git a/tests/image-scope-test.sh b/tests/image-scope-test.sh new file mode 100755 index 0000000..561af07 --- /dev/null +++ b/tests/image-scope-test.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# +# image-scope-test.sh -- end-to-end test of a BUILT image: the real entrypoint, real ClamAV and the +# real whp-scan-scope, started with the panel's hardening flags (read-only rootfs, RAM /tmp, uid 999, +# --memory 2g), against the synthetic backup of tests/build-scope-tree.sh (including a sparse 2001 MiB mp4 +# and an EICAR file). Needs only docker and tar on the host (the checks run inside the image, so it also +# works on CI runners without php). Uses named volumes and docker cp instead of bind mounts, so it works +# against a remote or sandboxed docker daemon. Takes about a minute (the sparse file is read once). +# +# Run: bash tests/image-scope-test.sh cpanel-importer:dev (exit 0 = all pass) +set -euo pipefail +IMAGE="${1:?usage: image-scope-test.sh }" +REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +WORK="$(mktemp -d)" +SUF="$$" +VOLS=(bk q s) +cleanup() { + docker rm -f "isc-helper-$SUF" >/dev/null 2>&1 || true + for v in "${VOLS[@]}"; do docker volume rm -f "isc-$v-$SUF" >/dev/null 2>&1 || true; done + rm -rf "$WORK" +} +trap cleanup EXIT +FAILS=0 +pass() { printf ' PASS %s\n' "$1"; } +fail() { printf ' FAIL %s\n' "$1"; FAILS=$((FAILS + 1)); } + +bash "$REPO/tests/build-scope-tree.sh" "$WORK/tree" --big +tar czf "$WORK/cpmove-scope.tar.gz" -C "$WORK/tree" --exclude='EXPECT_*' cpmove-scope +for v in "${VOLS[@]}"; do docker volume create "isc-$v-$SUF" >/dev/null; done +docker create --name "isc-helper-$SUF" --user 0 -v "isc-bk-$SUF:/b" --entrypoint sh "$IMAGE" -c true >/dev/null +docker cp "$WORK/cpmove-scope.tar.gz" "isc-helper-$SUF:/b/cpmove-scope.tar.gz" +docker rm "isc-helper-$SUF" >/dev/null +docker run --rm --user 0 -v "isc-q-$SUF:/q" -v "isc-s-$SUF:/s" --entrypoint sh "$IMAGE" -c 'chown 999:999 /q /s; chmod 750 /q /s' + +echo "entrypoint run (panel-style flags)" +rc=0 +docker run --rm --user 999:999 --cap-drop=ALL --security-opt=no-new-privileges --read-only \ + --tmpfs /tmp:rw,nosuid,nodev,exec,size=4g --memory=2g --memory-swap=2g --cpus=2 \ + -v "isc-bk-$SUF:/host/backup:ro" -v "isc-q-$SUF:/host/quarantine" -v "isc-s-$SUF:/host/sanitized" \ + -e IMPORT_ID=t -e IMPORT_USERNAME=scope -e IMPORT_BACKUP_FILE=/host/backup/cpmove-scope.tar.gz \ + -e CLAMAV_REFRESH=false -e IMPORT_INCLUDE_MAIL=true "$IMAGE" >"$WORK/run.log" 2>&1 || rc=$? +if [[ $rc -eq 0 ]]; then pass "entrypoint exits 0"; else fail "entrypoint exits 0 (rc=$rc)"; tail -20 "$WORK/run.log"; fi + +# the checks run inside the image (php + find), on the finished volumes, as root so nothing is unreadable +CHECK=' +$r = json_decode(file_get_contents("/s/t/report.json")); +$s = $r->scan ?? null; +$bad = []; +$need = function ($ok, $what) use (&$bad) { if (!$ok) $bad[] = $what; }; +$need(is_object($s), "report.json has a scan object"); +$need(($r->status ?? "") === "completed", "status completed"); +$need($s->policy === "code-risky-v1" && $s->scope_version === 1, "policy code-risky-v1 / scope_version 1"); +$need($s->files_total === $s->files_scanned + $s->files_skipped_by_policy + $s->in_scope_unscanned + $s->oversize_unscanned, "files_total accounts for every file"); +$need(is_object($s->skipped_by_class) && array_sum((array) $s->skipped_by_class) === $s->files_skipped_by_policy, "skipped_by_class sums to files_skipped_by_policy"); +$need($s->in_scope_unscanned === 0 && $s->in_scope_unscanned_files === [], "nothing in scope was left unscanned"); +$need($s->oversize_unscanned === 1 && $s->oversize_unscanned_files === ["cpmove-scope/homedir/public_html/huge.mp4"], "the 2001 MiB mp4 is named in oversize_unscanned_files"); +$need(is_string($s->engine_version) && is_string($s->signature_db_version) && is_int($s->signatures_loaded) && $s->signatures_loaded > 0, "engine_version, signature_db_version, signatures_loaded > 0"); +$need($s->clamscan_exit === 1, "clamscan_exit 1 (the EICAR hit)"); +$need(($s->skipped_by_class->mail ?? 0) >= 1 && ($s->mail_tree_skipped ?? false) === true, "the mail tree was skipped (include_mail=true)"); +$need($r->files_scanned === $s->files_scanned, "top-level files_scanned = the scope files_scanned"); +$need($r->files_quarantined === 1 && $r->actions[0]->path === "cpmove-scope/homedir/public_html/eicar.php", "only the EICAR file is quarantined"); +$need(!file_exists("/s/t/extracted/cpmove-scope/homedir/public_html/eicar.php"), "the EICAR file is gone from the cleaned tree"); +$need(file_exists("/s/t/extracted/cpmove-scope/homedir/public_html/polyglot.jpg") === true, "the polyglot (no ClamAV signature) is still in the tree: scanned, not removed"); +$need(!is_dir("/s/t/work"), "no scratch left in the sanitized dir"); +echo $bad ? "BAD: " . implode("; ", $bad) . "\n" : "OK\n";' +out="$(docker run --rm --user 0 -v "isc-s-$SUF:/s" -v "isc-q-$SUF:/q" --entrypoint php "$IMAGE" -r "$CHECK" 2>&1 || true)" +if [[ "$out" == "OK" ]]; then pass "report.json scan object: schema, invariants, hits, oversize, scratch"; else fail "report.json scan object: $out"; fi +grep -q 'scan-files: scope code-risky-v1' "$WORK/run.log" && pass "log shows the scope line" || fail "log shows the scope line" + +echo +if [[ $FAILS -eq 0 ]]; then echo "ALL PASS"; else echo "$FAILS FAILURE(S)"; fi +exit $(( FAILS == 0 ? 0 : 1 )) diff --git a/tests/run-tests.sh b/tests/run-tests.sh index ab8577e..62411e9 100755 --- a/tests/run-tests.sh +++ b/tests/run-tests.sh @@ -17,7 +17,7 @@ REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" FIX="$REPO/tests/fixtures" # Under /tmp: scan-files.php sets a container open_basedir that allows /tmp. WORK="$(mktemp -d -p /tmp cpi-tests.XXXXXX)" -trap 'rm -rf "$WORK"' EXIT +trap '[[ -n "${KEEP:-}" ]] || rm -rf "$WORK"' EXIT FAILS=0 pass() { printf ' PASS %s\n' "$1"; } @@ -223,50 +223,61 @@ OUT="$WORK/ex-one" IMPORT_INCLUDE_MAIL=1 bash "$REPO/scripts/extract.sh" "$MAILTAR" "$OUT" testuser "$WORK/ex-one.actions.json" >/dev/null 2>&1 check "IMPORT_INCLUDE_MAIL=1: mail tree skipped" "[[ ! -e '$OUT/$U/homedir/mail' ]]" -# ---- scan-files.php with a stub clamscan ------------------------------------ -# The stub reports one hit inside the mail tree and one in public_html. +# ---- scan-files.php with a stub clamscan and the REAL whp-scan-scope --------- +# The scope tool is the real binary (WHP_SCAN_SCOPE_BIN, or extracted from the built image $IMAGE): +# it decides what clamscan is given. clamscan is a stub: it answers --version, records its argv and +# the file list it was handed, and reports hits for the listed index.php files plus ALWAYS one hit +# inside the mail tree (to prove a hit there is never acted on). +if [[ -z "${WHP_SCAN_SCOPE_BIN:-}" && -n "${IMAGE:-}" ]]; then + cid="$(docker create "$IMAGE")" + docker cp "$cid:/usr/local/bin/whp-scan-scope" "$WORK/whp-scan-scope" && docker rm "$cid" >/dev/null + WHP_SCAN_SCOPE_BIN="$WORK/whp-scan-scope" +fi +if [[ -z "${WHP_SCAN_SCOPE_BIN:-}" || ! -x "$WHP_SCAN_SCOPE_BIN" ]]; then + echo "FATAL: set WHP_SCAN_SCOPE_BIN (a whp-scan-scope binary) or IMAGE (a built image) to run the scan tests" >&2 + exit 2 +fi STUBBIN="$WORK/bin" mkdir -p "$STUBBIN" cat > "$STUBBIN/clamscan" <<'STUB' #!/usr/bin/env bash +if [[ "${1:-}" == "--version" ]]; then echo "ClamAV 1.4.6/28191/Sun Nov 22 06:27:13 2026"; exit 0; fi printf '%s\n' "$@" > "$CLAMSCAN_ARGS_OUT" -dir="${!#}" +for a in "$@"; do case "$a" in --file-list=*) cp "${a#--file-list=}" "$CLAMSCAN_LIST_OUT";; esac; done +echo "Known viruses: ${STUB_SIGS:-3632214}" +[[ -n "${STUB_EXIT:-}" && "$STUB_EXIT" -ge 2 ]] && { echo "ERROR: stub failure" >&2; exit "$STUB_EXIT"; } top="${CLAM_TOP:-cpmove-testuser}" +dir="$CLAM_EXTRACT" echo "$dir/$top/homedir/mail/example.com/alice/cur/1700000000.M1P1.host,S=40:2,S: Test.Mail.Sig FOUND" -echo "$dir/$top/homedir/public_html/index.php: Test.Php.Sig FOUND" +grep -F '/index.php' "$CLAMSCAN_LIST_OUT" | while read -r f; do echo "$f: Test.Php.Sig FOUND"; done +exit 1 STUB chmod +x "$STUBBIN/clamscan" run_scan() { # [extra args] local ex="$1" tag="$2"; shift 2 mkdir -p "$WORK/q-$tag" - CLAMSCAN_ARGS_OUT="$WORK/clam-$tag.args" PATH="$STUBBIN:$PATH" \ + CLAM_EXTRACT="$ex" CLAMSCAN_ARGS_OUT="$WORK/clam-$tag.args" CLAMSCAN_LIST_OUT="$WORK/clam-$tag.list" PATH="$STUBBIN:$PATH" \ php "$REPO/scripts/scan-files.php" --extract "$ex" --quarantine "$WORK/q-$tag" \ - --report "$WORK/scan-$tag.json" --import-id "t-$tag" "$@" 2>"$WORK/scan-$tag.log" + --report "$WORK/scan-$tag.json" --attestation "$WORK/attest-$tag.json" --scope-bin "$WHP_SCAN_SCOPE_BIN" \ + --import-id "t-$tag" "$@" 2>"$WORK/scan-$tag.log" } jq_php() { php -r '$r = json_decode(file_get_contents($argv[1]), true); echo json_encode($r[$argv[2]] ?? null);' "$1" "$2"; } echo "scan-files.php --skip-mail (mail tree extracted)" cp -a "$WORK/ex-mail" "$WORK/scan-skip" run_scan "$WORK/scan-skip" skip --skip-mail -# Expected argv entry: the extract dir with ERE metacharacters escaped -# (the only one mktemp's path can hold is "."), then the mail-tree pattern. -SKIPDIR="$WORK/scan-skip" -EXCL="--exclude-dir=^${SKIPDIR//./\\.}/[^/]+/homedir/mail(/.*)?\$" -if grep -qxF -- "$EXCL" "$WORK/clam-skip.args"; then - pass "--skip-mail: clamscan gets --exclude-dir for the mail tree" -else - fail "--skip-mail: clamscan gets --exclude-dir for the mail tree (want $EXCL; got: $(tr '\n' ' ' < "$WORK/clam-skip.args"))" -fi +check "--skip-mail: the clamscan file list holds no path of the mail tree" "! grep -q '/homedir/mail/' '$WORK/clam-skip.list'" +check "--skip-mail: clamscan is given --file-list (no recursive walk of the extract)" "grep -q -- '^--file-list=' '$WORK/clam-skip.args' && ! grep -qx -- '--recursive' '$WORK/clam-skip.args'" check "--skip-mail: a hit inside the mail tree is NOT quarantined (message stays in the Maildir)" \ "[[ -f '$WORK/scan-skip/$U/homedir/mail/$D/alice/cur/1700000000.M1P1.host,S=40:2,S' ]]" check "--skip-mail: a hit outside the mail tree is still quarantined" \ "[[ ! -e '$WORK/scan-skip/$U/homedir/public_html/index.php' && -f '$WORK/q-skip/$U/homedir/public_html/index.php' ]]" check "--skip-mail: report files_quarantined = 1" "[[ \$(jq_php '$WORK/scan-skip.json' files_quarantined) == 1 ]]" check "--skip-mail: report mail_scan_skipped = true" "[[ \$(jq_php '$WORK/scan-skip.json' mail_scan_skipped) == true ]]" -NONMAIL=$(cd "$WORK/scan-skip" && find . -type f ! -path "./$U/homedir/mail/*" | wc -l) -check "--skip-mail: files_scanned counts only non-mail files ($NONMAIL, after the quarantine move)" \ - "[[ \$(jq_php '$WORK/scan-skip.json' files_scanned) == $((NONMAIL + 1)) ]]" +check "--skip-mail: report files_scanned = the length of the clamscan list" \ + "[[ \$(jq_php '$WORK/scan-skip.json' files_scanned) == \$(wc -l < '$WORK/clam-skip.list') ]]" +check "--skip-mail: the scope stats record the mail tree as skipped" "[[ \$(php -r '\$a=json_decode(file_get_contents(\$argv[1]),true); echo \$a[\"skipped_by_class\"][\"mail\"] ?? 0;' '$WORK/attest-skip.json') -ge 1 ]]" check "--skip-mail: the skip is logged with its reason" "grep -q 'NOT scanning the mail tree' '$WORK/scan-skip.log'" echo "I-1: top-level dirs other than cpmove-* (acct/, backup-_/)" @@ -284,9 +295,10 @@ for fx in acct:acct backupdir:backup-10.20.2026_10-00-00_testuser; do check "$name: in-tree Dovecot hard link kept" "[[ -f '$M/cur/1700000002.M3P1.host,S=41:2,S' ]]" check "$name: strips recorded as stripped_mail_link" "grep -q '$top/homedir/mail/$D/alice/.evil-rel' '$WORK/ex-$name.actions.json'" rm -rf "$WORK/q-$name" - CLAM_TOP="$top" CLAMSCAN_ARGS_OUT="$WORK/clam-$name.args" PATH="$STUBBIN:$PATH" \ + CLAM_EXTRACT="$OUT" CLAM_TOP="$top" CLAMSCAN_ARGS_OUT="$WORK/clam-$name.args" CLAMSCAN_LIST_OUT="$WORK/clam-$name.list" PATH="$STUBBIN:$PATH" \ php "$REPO/scripts/scan-files.php" --extract "$OUT" --quarantine "$WORK/q-$name" \ - --report "$WORK/scan-$name.json" --import-id "t-$name" --skip-mail 2>/dev/null + --report "$WORK/scan-$name.json" --attestation "$WORK/attest-$name.json" --scope-bin "$WHP_SCAN_SCOPE_BIN" \ + --import-id "t-$name" --skip-mail 2>/dev/null check "$name: --skip-mail keeps a hit inside $top/homedir/mail in the Maildir" "[[ -f '$M/cur/1700000000.M1P1.host,S=40:2,S' ]]" check "$name: --skip-mail still quarantines public_html" "[[ ! -e '$OUT/$top/homedir/public_html/index.php' ]]" done @@ -307,10 +319,52 @@ fi echo "scan-files.php without --skip-mail (unchanged behaviour)" cp -a "$WORK/ex-mail" "$WORK/scan-noskip" run_scan "$WORK/scan-noskip" noskip -check "no flag: no --exclude-dir passed" "! grep -q -- '--exclude-dir' '$WORK/clam-noskip.args'" check "no flag: report mail_scan_skipped = false" "[[ \$(jq_php '$WORK/scan-noskip.json' mail_scan_skipped) == false ]]" check "no flag: both hits quarantined" "[[ \$(jq_php '$WORK/scan-noskip.json' files_quarantined) == 2 ]]" +# ---- scan scope: the synthetic tree (polyglot, symlink, docroot under tmp, handler dir, oversize) ---- +echo "scan scope: synthetic extract (tests/build-scope-tree.sh)" +ST="$WORK/scope-tree" +bash "$REPO/tests/build-scope-tree.sh" "$ST" --big +run_scan "$ST" scope --skip-mail +check "scope: scan-files.php exits 0" "run_scan '$ST' scope2 --skip-mail" +while read -r f; do + check "scope: listed for clamscan: $f" "grep -qxF '$ST/$f' '$WORK/clam-scope.list'" +done < "$ST/EXPECT_LISTED" +while read -r f; do + check "scope: NOT listed: $f" "! grep -qxF '$ST/$f' '$WORK/clam-scope.list'" +done < "$ST/EXPECT_NOT_LISTED" +check "scope: the mail message is not listed with --skip-mail" "! grep -qxF \"$ST/\$(cat '$ST/EXPECT_MAIL')\" '$WORK/clam-scope.list'" +check "scope: the sparse 2001 MiB mp4 is NOT on the list (clamscan cannot be given it)" "! grep -q 'huge.mp4' '$WORK/clam-scope.list'" +check "scope: ...it is named in oversize_unscanned_files" "grep -q 'huge.mp4' '$WORK/attest-scope.json' && [[ \$(php -r '\$a=json_decode(file_get_contents(\$argv[1]),true); echo \$a[\"oversize_unscanned\"];' '$WORK/attest-scope.json') == 1 ]]" +check "scope: the stub's hit on the listed index.php is quarantined" "[[ -f '$WORK/q-scope/cpmove-scope/homedir/public_html/index.php' ]]" +ATT="$WORK/attest-scope.json" +chk_att() { php -r ' +$a = json_decode(file_get_contents($argv[1])); +$ok = $a->policy === "code-risky-v1" && $a->scope_version === 1 + && $a->files_total === $a->files_scanned + $a->files_skipped_by_policy + $a->in_scope_unscanned + $a->oversize_unscanned + && is_object($a->skipped_by_class) && is_array($a->in_scope_unscanned_files) && is_array($a->oversize_unscanned_files) + && $a->engine_version === "1.4.6" && $a->signature_db_version === "28191" && $a->signatures_loaded === 3632214 && ($a->clamscan_exit === 1) + && $a->in_scope_unscanned === 0; +echo $ok ? "ok" : "bad";' "$ATT"; } +check "scope: attestation = the CLI stats (invariant holds) + engine_version, signature_db_version, signatures_loaded, clamscan_exit" "[[ \$(chk_att) == ok ]]" +check "scope: clamscan limits (2000M file, 4000M scan, scantime 0, alert-exceeds-max, tempdir only when asked)" \ + "grep -qx -- '--max-filesize=2000M' '$WORK/clam-scope.args' && grep -qx -- '--max-scansize=4000M' '$WORK/clam-scope.args' && grep -qx -- '--max-scantime=0' '$WORK/clam-scope.args' && grep -qx -- '--alert-exceeds-max=yes' '$WORK/clam-scope.args' && grep -qx -- '--max-recursion=8' '$WORK/clam-scope.args' && grep -qx -- '--max-files=10000' '$WORK/clam-scope.args'" +run_scan "$ST" scratch --skip-mail --scratch "$WORK/clam-scratch" +check "scope: --scratch becomes clamscan's --tempdir (disk scratch, not the RAM /tmp)" "grep -qx -- '--tempdir=$WORK/clam-scratch' '$WORK/clam-scratch.args'" + +echo "scan scope: fail closed (no fall back to an unscoped or partial scan)" +frc() { local rc=0; "$@" >/dev/null 2>&1 || rc=$?; echo "$rc"; } +cp -a "$WORK/ex-mail" "$WORK/scan-fc" +check "tool missing => exit 1, no report" "[[ \$(frc env CLAM_EXTRACT=x PATH='$STUBBIN:$PATH' php '$REPO/scripts/scan-files.php' --extract '$WORK/scan-fc' --quarantine '$WORK/q-fc' --report '$WORK/fc.json' --attestation '$WORK/fc-att.json' --scope-bin '$WORK/no-such-tool' --import-id t) == 1 && ! -e '$WORK/fc-att.json' ]]" +printf '#!/bin/sh\nexit 3\n' > "$WORK/bad-scope"; chmod +x "$WORK/bad-scope" +check "tool exits non-zero => exit 1, no report" "[[ \$(frc env CLAM_EXTRACT=x PATH='$STUBBIN:$PATH' php '$REPO/scripts/scan-files.php' --extract '$WORK/scan-fc' --quarantine '$WORK/q-fc' --report '$WORK/fc.json' --attestation '$WORK/fc-att.json' --scope-bin '$WORK/bad-scope' --import-id t) == 1 && ! -e '$WORK/fc-att.json' ]]" +printf '#!/bin/sh\necho garbage > "$6"; : > "$4"; exit 0\n' > "$WORK/junk-scope"; chmod +x "$WORK/junk-scope" +check "tool writes unusable stats => exit 1" "[[ \$(frc env CLAM_EXTRACT=x PATH='$STUBBIN:$PATH' php '$REPO/scripts/scan-files.php' --extract '$WORK/scan-fc' --quarantine '$WORK/q-fc' --report '$WORK/fc.json' --attestation '$WORK/fc-att.json' --scope-bin '$WORK/junk-scope' --import-id t) == 1 ]]" +check "clamscan exit 2 => exit 1" "[[ \$(frc env STUB_EXIT=2 CLAM_EXTRACT=x CLAMSCAN_ARGS_OUT='$WORK/x.args' CLAMSCAN_LIST_OUT='$WORK/x.list' PATH='$STUBBIN:$PATH' php '$REPO/scripts/scan-files.php' --extract '$WORK/scan-fc' --quarantine '$WORK/q-fc' --report '$WORK/fc.json' --attestation '$WORK/fc-att.json' --scope-bin '$WHP_SCAN_SCOPE_BIN' --import-id t) == 1 && ! -e '$WORK/fc-att.json' ]]" +check "clamscan loaded 0 signatures => exit 1" "[[ \$(frc env STUB_SIGS=0 CLAM_EXTRACT=x CLAMSCAN_ARGS_OUT='$WORK/x.args' CLAMSCAN_LIST_OUT='$WORK/x.list' PATH='$STUBBIN:$PATH' php '$REPO/scripts/scan-files.php' --extract '$WORK/scan-fc' --quarantine '$WORK/q-fc' --report '$WORK/fc.json' --attestation '$WORK/fc-att.json' --scope-bin '$WHP_SCAN_SCOPE_BIN' --import-id t) == 1 ]]" +check "no clamscan on PATH => exit 1" "[[ \$(frc env CLAM_EXTRACT=x PATH='/usr/bin:/bin' php '$REPO/scripts/scan-files.php' --extract '$WORK/scan-fc' --quarantine '$WORK/q-fc' --report '$WORK/fc.json' --attestation '$WORK/fc-att.json' --scope-bin '$WHP_SCAN_SCOPE_BIN' --import-id t) == 1 ]]" + echo if [[ $FAILS -eq 0 ]]; then echo "ALL PASS"; else echo "$FAILS FAILURE(S)"; fi exit $(( FAILS == 0 ? 0 : 1 )) From 2ebb05a6d62b734f5c6729830f12dc1ace0b1fbb Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Sun, 22 Nov 2026 07:30:19 -0800 Subject: [PATCH 2/5] scan-files: fail closed on scan errors masked by hits, unmapped hits and quarantine failures Review of the scan-scope change (measured on ClamAV 1.4.6 in this image): - clamscan exits 1, not 2, when one listed file is infected and another cannot be read: only the summary says "Total errors: 1". A mode-000 webshell next to any detected file went unscanned and the run passed (privd accepted the attestation, require_scan_scope=true included). Now: a summary with Total errors > 0, or no summary at all, fails the run. - Every hit line must name an EXACT entry of the scan list (the last ": " ends the path; signature names never contain one); anything else fails the run instead of being skipped. - The list itself is checked before clamscan sees it: each entry a plain absolute path below the extract, <= 1022 bytes, no control character, and exactly files_scanned entries. - A hit that cannot be moved to quarantine fails the run (it used to log a WARN and leave the infected file in the tree to be imported). Duplicate hits (a link target listed twice) are one action. - Tests: names with ': ' + ' FOUND', leading '-', \n, \r, >= 1023 bytes; rogue hit, Total errors, no summary, unquarantinable hit, list longer than files_scanned, entry outside the extract (red on the old script); image-scope-test.sh runs a mode-000 file next to EICAR end to end. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6 --- scripts/scan-files.php | 94 ++++++++++++++++++++++++++++++++------- tests/image-scope-test.sh | 22 +++++++++ tests/run-tests.sh | 46 +++++++++++++++++-- 3 files changed, 141 insertions(+), 21 deletions(-) diff --git a/scripts/scan-files.php b/scripts/scan-files.php index f97c94c..b569e23 100755 --- a/scripts/scan-files.php +++ b/scripts/scan-files.php @@ -163,6 +163,33 @@ fwrite(STDERR, sprintf( $stats->files_skipped_by_policy, $stats->in_scope_unscanned, $stats->oversize_unscanned )); +// The list is what clamscan is told to scan: check it before trusting it. Every entry must be an +// absolute path below the extract, at most MAX_LIST_PATH bytes (clamscan reads --file-list lines with +// fgets(buf, 1024): a longer line is split into bogus entries), free of control characters (a \n or \r +// would split or alter an entry), and there must be exactly files_scanned of them. whp-scan-scope +// already refuses such names (in_scope_unscanned); this is the belt, and it fails the run. +const MAX_LIST_PATH = 1022; +$listRaw = @file_get_contents($listPath); +if (!is_string($listRaw)) { + fwrite(STDERR, "scan-files: FATAL: cannot read the scan list $listPath\n"); + exit(1); +} +$listed = []; +$nEntries = 0; +foreach ($listRaw === '' ? [] : explode("\n", rtrim($listRaw, "\n")) as $entry) { + $nEntries++; + if ($entry === '' || strlen($entry) > MAX_LIST_PATH || preg_match('/[\x00-\x1f\x7f]/', $entry) + || !str_starts_with($entry, $extractDir . '/') || str_contains($entry, '/../') || str_ends_with($entry, '/..')) { + fwrite(STDERR, "scan-files: FATAL: unusable entry #$nEntries in the scan list (empty, too long, control character or outside the extract): the scan cannot cover it\n"); + exit(1); + } + $listed[$entry] = true; +} +if ($nEntries !== $filesScanned || ($listRaw !== '' && !str_ends_with($listRaw, "\n"))) { + fwrite(STDERR, "scan-files: FATAL: the scan list holds $nEntries entries, whp-scan-scope reported $filesScanned\n"); + exit(1); +} + // -- clamscan over the file list --------------------------------------------- // Engine and database version: "ClamAV 1.4.3/28191/Sun Nov 22 08:25:05 2026". @@ -201,30 +228,56 @@ if ($clamRc < 0 || $clamRc > 1) { fwrite(STDERR, (string) @file_get_contents($clamErr)); exit(1); } -$known = 0; +// stdout holds hit lines (": FOUND") and the summary, nothing else we trust. +// clamscan's exit status is 1 as soon as ONE file is infected, even when other files could not be read +// (measured, ClamAV 1.4.6: a mode-000 file next to an EICAR file gives exit 1 and "Total errors: 1"), +// so the summary's error count is checked too: any file clamscan could not scan fails the run. +$known = -1; +$errors = 0; +$summary = false; $hits = []; -foreach (preg_split('/\r?\n/', $clamOut) as $line) { +foreach (explode("\n", $clamOut) as $line) { + $line = rtrim($line, "\r"); if (preg_match('/^Known viruses: (\d+)$/', $line, $m)) { $known = (int) $m[1]; continue; } - if ($line === '' || !str_ends_with($line, ' FOUND')) continue; - // Strip trailing ' FOUND'. - $body = substr($line, 0, -6); - $colon = strrpos($body, ': '); - if ($colon === false) continue; - $path = substr($body, 0, $colon); - $sig = substr($body, $colon + 2); - if (!str_starts_with($path, $extractDir)) { - // Defensive: the list only holds paths below the extract dir. + if (preg_match('/^Total errors: (\d+)$/', $line, $m)) { + $errors = (int) $m[1]; continue; } + if (preg_match('/^Scanned files: \d+$/', $line)) { + $summary = true; + continue; + } + if (!str_ends_with($line, ' FOUND')) continue; + // Signature names never contain ": ", so the LAST ": " ends the path (a path may contain ": "). + $body = substr($line, 0, -6); + $colon = strrpos($body, ': '); + $path = $colon === false ? '' : substr($body, 0, $colon); + $sig = $colon === false ? '' : substr($body, $colon + 2); + if (!isset($listed[$path]) || !preg_match('/^[A-Za-z0-9][A-Za-z0-9._:\/+-]*$/', $sig)) { + // Not an exact entry of the list: the output is not what this script asked for. Never guess. + fwrite(STDERR, "scan-files: FATAL: clamscan reported a hit this script cannot map to a listed file: " . json_encode($line) . "\n"); + exit(1); + } if ($skipMail && preg_match($mailDirPcre, $path)) { - // Belt: the scope never lists the mail tree; never move a message out of a Maildir regardless. - fwrite(STDERR, "scan-files: WARN ignoring a hit inside the mail tree: $path\n"); + // Only reachable through a web-root symlink whose target is a message (the scope lists link + // targets): the message is copied verbatim into the mailbox, never served. Never move it out. + fwrite(STDERR, "scan-files: WARN ignoring a hit inside the mail tree: " . json_encode($path) . "\n"); continue; } - $hits[] = ['path' => $path, 'signature' => $sig]; + $hits[$path] = ['path' => $path, 'signature' => $sig]; // a path listed twice (link target + file) is one hit +} +$hits = array_values($hits); +if (!$summary) { + fwrite(STDERR, "scan-files: FATAL: clamscan printed no scan summary: the scan did not complete\n"); + exit(1); +} +if ($errors !== 0) { + fwrite(STDERR, "scan-files: FATAL: clamscan could not scan $errors listed file(s) (Total errors: $errors): the scan is incomplete\n"); + fwrite(STDERR, (string) @file_get_contents($clamErr)); + exit(1); } if ($known <= 0) { fwrite(STDERR, "scan-files: FATAL: clamscan loaded no signatures (Known viruses: $known): nothing was scanned\n"); @@ -280,11 +333,18 @@ foreach ($hits as $h) { // sometimes EXDEVs even though /tmp and /host are both ours). if (@copy($path, $qPath)) { @unlink($path); - } else { - fwrite(STDERR, "scan-files: WARN failed to quarantine $path -> $qPath\n"); - continue; } } + clearstatcache(); + if (file_exists($path) || is_link($path)) { + // An infected file that stays in the tree would be imported: fail the run instead. + fwrite(STDERR, "scan-files: FATAL: failed to quarantine " . json_encode($path) . " -> " . json_encode($qPath) . "\n"); + exit(1); + } + if (!file_exists($qPath)) { + fwrite(STDERR, "scan-files: FATAL: quarantine copy missing for " . json_encode($path) . "\n"); + exit(1); + } $quarantined++; $actions[] = [ 'path' => $relPath, diff --git a/tests/image-scope-test.sh b/tests/image-scope-test.sh index 561af07..adefc1e 100755 --- a/tests/image-scope-test.sh +++ b/tests/image-scope-test.sh @@ -67,6 +67,28 @@ out="$(docker run --rm --user 0 -v "isc-s-$SUF:/s" -v "isc-q-$SUF:/q" --entrypoi if [[ "$out" == "OK" ]]; then pass "report.json scan object: schema, invariants, hits, oversize, scratch"; else fail "report.json scan object: $out"; fi grep -q 'scan-files: scope code-risky-v1' "$WORK/run.log" && pass "log shows the scope line" || fail "log shows the scope line" +# Review of 2026-11-22: clamscan exits 1, not 2, when one listed file is infected and another cannot be read, so a +# mode-000 webshell next to any hit went unscanned with in_scope_unscanned 0. The tarball is made inside the image +# as root (GNU tar keeps mode 000; root can read the file to pack it). +echo "entrypoint run: mode-000 file next to an EICAR hit" +docker run --rm --user 0 -v "isc-bk-$SUF:/b" --entrypoint sh "$IMAGE" -c ' + set -e; d=/tmp/m/cpmove-mask/homedir/public_html; mkdir -p "$d" /tmp/m/cpmove-mask/userdata + printf "documentroot: /home/mask/public_html\n" > /tmp/m/cpmove-mask/userdata/mask.test + printf "%s" "X5O!P%@AP[4\\PZX54(P^)7CC)7}\$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!\$H+H*" > "$d/eicar.php" + cp "$d/eicar.php" "$d/hidden.php"; chmod 000 "$d/hidden.php" + tar czf /b/cpmove-mask.tar.gz -C /tmp/m cpmove-mask' +docker run --rm --user 0 -v "isc-q-$SUF:/q" -v "isc-s-$SUF:/s" --entrypoint sh "$IMAGE" -c 'rm -rf /q/m /s/m' +rc=0 +docker run --rm --user 999:999 --cap-drop=ALL --security-opt=no-new-privileges --read-only \ + --tmpfs /tmp:rw,nosuid,nodev,exec,size=1g --memory=2g --memory-swap=2g --cpus=2 \ + -v "isc-bk-$SUF:/host/backup:ro" -v "isc-q-$SUF:/host/quarantine" -v "isc-s-$SUF:/host/sanitized" \ + -e IMPORT_ID=m -e IMPORT_USERNAME=mask -e IMPORT_BACKUP_FILE=/host/backup/cpmove-mask.tar.gz \ + -e CLAMAV_REFRESH=false "$IMAGE" >"$WORK/run-mask.log" 2>&1 || rc=$? +out="$(docker run --rm --user 0 -v "isc-s-$SUF:/s" --entrypoint php "$IMAGE" -r ' +$s = json_decode(file_get_contents("/s/m/report.json"))->scan ?? null; +echo (is_object($s) && $s->in_scope_unscanned === 1 && $s->in_scope_unscanned_files === ["cpmove-mask/homedir/public_html/hidden.php"]) ? "OK" : json_encode($s);' 2>&1 || true)" +if [[ $rc -eq 0 && "$out" == "OK" ]]; then pass "mode-000 file is in_scope_unscanned by name (privd refuses the run)"; else fail "mode-000 file (rc=$rc): $out"; fi + echo if [[ $FAILS -eq 0 ]]; then echo "ALL PASS"; else echo "$FAILS FAILURE(S)"; fi exit $(( FAILS == 0 ? 0 : 1 )) diff --git a/tests/run-tests.sh b/tests/run-tests.sh index 62411e9..b093391 100755 --- a/tests/run-tests.sh +++ b/tests/run-tests.sh @@ -244,12 +244,19 @@ cat > "$STUBBIN/clamscan" <<'STUB' if [[ "${1:-}" == "--version" ]]; then echo "ClamAV 1.4.6/28191/Sun Nov 22 06:27:13 2026"; exit 0; fi printf '%s\n' "$@" > "$CLAMSCAN_ARGS_OUT" for a in "$@"; do case "$a" in --file-list=*) cp "${a#--file-list=}" "$CLAMSCAN_LIST_OUT";; esac; done -echo "Known viruses: ${STUB_SIGS:-3632214}" [[ -n "${STUB_EXIT:-}" && "$STUB_EXIT" -ge 2 ]] && { echo "ERROR: stub failure" >&2; exit "$STUB_EXIT"; } top="${CLAM_TOP:-cpmove-testuser}" dir="$CLAM_EXTRACT" -echo "$dir/$top/homedir/mail/example.com/alice/cur/1700000000.M1P1.host,S=40:2,S: Test.Mail.Sig FOUND" -grep -F '/index.php' "$CLAMSCAN_LIST_OUT" | while read -r f; do echo "$f: Test.Php.Sig FOUND"; done +# like clamscan: only listed files are reported (the mail message only when the list holds it) +grep -F '/homedir/mail/example.com/alice/cur/1700000000.M1P1.host,S=40:2,S' "$CLAMSCAN_LIST_OUT" | while IFS= read -r f; do echo "$f: Test.Mail.Sig FOUND"; done +grep -F -e '/index.php' -e 'EVIL' "$CLAMSCAN_LIST_OUT" | while IFS= read -r f; do echo "$f: Test.Php.Sig FOUND"; done +[[ -n "${STUB_ROGUE:-}" ]] && echo "$STUB_ROGUE: Test.Rogue.Sig FOUND" +echo +echo "----------- SCAN SUMMARY -----------" +echo "Known viruses: ${STUB_SIGS:-3632214}" +echo "Engine version: 1.4.6" +[[ -z "${STUB_NO_SUMMARY:-}" ]] && echo "Scanned files: $(wc -l < "$CLAMSCAN_LIST_OUT")" +[[ -n "${STUB_ERRORS:-}" ]] && echo "Total errors: $STUB_ERRORS" exit 1 STUB chmod +x "$STUBBIN/clamscan" @@ -320,7 +327,7 @@ echo "scan-files.php without --skip-mail (unchanged behaviour)" cp -a "$WORK/ex-mail" "$WORK/scan-noskip" run_scan "$WORK/scan-noskip" noskip check "no flag: report mail_scan_skipped = false" "[[ \$(jq_php '$WORK/scan-noskip.json' mail_scan_skipped) == false ]]" -check "no flag: both hits quarantined" "[[ \$(jq_php '$WORK/scan-noskip.json' files_quarantined) == 2 ]]" +check "no flag: the listed hit is quarantined (the plain-data mail message is not in scope, so clamscan never reports it)" "[[ \$(jq_php '$WORK/scan-noskip.json' files_quarantined) == 1 ]]" # ---- scan scope: the synthetic tree (polyglot, symlink, docroot under tmp, handler dir, oversize) ---- echo "scan scope: synthetic extract (tests/build-scope-tree.sh)" @@ -365,6 +372,37 @@ check "clamscan exit 2 => exit 1" "[[ \$(frc env STUB_EXIT=2 CLAM_EXTRACT=x CLAM check "clamscan loaded 0 signatures => exit 1" "[[ \$(frc env STUB_SIGS=0 CLAM_EXTRACT=x CLAMSCAN_ARGS_OUT='$WORK/x.args' CLAMSCAN_LIST_OUT='$WORK/x.list' PATH='$STUBBIN:$PATH' php '$REPO/scripts/scan-files.php' --extract '$WORK/scan-fc' --quarantine '$WORK/q-fc' --report '$WORK/fc.json' --attestation '$WORK/fc-att.json' --scope-bin '$WHP_SCAN_SCOPE_BIN' --import-id t) == 1 ]]" check "no clamscan on PATH => exit 1" "[[ \$(frc env CLAM_EXTRACT=x PATH='/usr/bin:/bin' php '$REPO/scripts/scan-files.php' --extract '$WORK/scan-fc' --quarantine '$WORK/q-fc' --report '$WORK/fc.json' --attestation '$WORK/fc-att.json' --scope-bin '$WHP_SCAN_SCOPE_BIN' --import-id t) == 1 ]]" +echo "scan-files: hostile names, clamscan output and quarantine (red on the pre-review scan-files.php)" +HT="$WORK/hostile"; HP="$HT/cpmove-h/homedir/public_html" +mkdir -p "$HP" "$WORK/q-hostile" +printf 'x' > "$HP/EVIL: Test.Fake.Sig FOUND.php" # ': ' and ' FOUND' inside the name: listed, hit, quarantined by exact path +printf 'x' > "$HP/-EVIL-dash.php" # leading dash: a list entry, never an option +printf 'x' > "$HP/nl"$'\n'"EVIL.php" # newline: refused by the scope tool (in_scope_unscanned), never listed +printf 'x' > "$HP/cr"$'\r'"EVIL.php" # carriage return: refused too +LONGD="$HP/$(printf 'd%.0s' $(seq 1 200))/$(printf 'e%.0s' $(seq 1 200))/$(printf 'f%.0s' $(seq 1 200))/$(printf 'g%.0s' $(seq 1 200))" +mkdir -p "$LONGD"; printf 'x' > "$LONGD/$(printf 'h%.0s' $(seq 1 200))EVIL.php" # path >= 1023 bytes: refused +hrun() { local rc=0; CLAM_EXTRACT="$HT" CLAMSCAN_ARGS_OUT="$WORK/clam-h.args" CLAMSCAN_LIST_OUT="$WORK/clam-h.list" PATH="$STUBBIN:$PATH" "$@" \ + php "$REPO/scripts/scan-files.php" --extract "$HT" --quarantine "$WORK/q-hostile" --report "$WORK/scan-h.json" \ + --attestation "$WORK/attest-h.json" --scope-bin "$WHP_SCAN_SCOPE_BIN" --import-id t-h >"$WORK/scan-h.log" 2>&1 || rc=$?; echo "$rc"; } +check "hostile: scan-files exits 0" "[[ \$(hrun env) == 0 ]]" +check "hostile: names with ': ' and a leading '-' are quarantined by their exact path" \ + "[[ -f '$WORK/q-hostile/cpmove-h/homedir/public_html/EVIL: Test.Fake.Sig FOUND.php' && -f '$WORK/q-hostile/cpmove-h/homedir/public_html/-EVIL-dash.php' && ! -e '$HP/-EVIL-dash.php' ]]" +check "hostile: \\n, \\r and >= 1023-byte paths are never listed and are counted in_scope_unscanned (privd refuses the run)" \ + "[[ \$(php -r '\$a=json_decode(file_get_contents(\$argv[1])); echo \$a->in_scope_unscanned;' '$WORK/attest-h.json') == 3 && \$(grep -c EVIL '$WORK/clam-h.list') == 2 ]]" +mkdir -p "$WORK/q-hostile" +check "a hit on a path that is not an exact list entry => exit 1" "[[ \$(hrun env STUB_ROGUE='$HP/index.php') == 1 ]]" +check "clamscan exit 1 but 'Total errors: 1' (an unreadable file next to a hit) => exit 1" "[[ \$(hrun env STUB_ERRORS=1) == 1 ]]" +check "no scan summary => exit 1" "[[ \$(hrun env STUB_NO_SUMMARY=1) == 1 ]]" +if [[ $(id -u) -ne 0 ]]; then + printf 'x' > "$HP/EVIL2.php"; rm -rf "$WORK/q-hostile"; mkdir -p "$WORK/q-hostile"; chmod 500 "$WORK/q-hostile" + check "a hit that cannot be quarantined => exit 1 (never left in the tree silently)" "[[ \$(hrun env) == 1 && -f '$HP/EVIL2.php' ]]" + chmod 700 "$WORK/q-hostile" +fi +printf '#!/bin/sh\n"%s" "$@" || exit $?\nprintf "%%s/x\\n" "$2" >> "$4"\n' "$WHP_SCAN_SCOPE_BIN" > "$WORK/extra-scope"; chmod +x "$WORK/extra-scope" +check "the list holds more entries than files_scanned => exit 1" "[[ \$(frc env CLAM_EXTRACT='$HT' CLAMSCAN_ARGS_OUT='$WORK/x.args' CLAMSCAN_LIST_OUT='$WORK/x.list' PATH='$STUBBIN:$PATH' php '$REPO/scripts/scan-files.php' --extract '$HT' --quarantine '$WORK/q-x' --report '$WORK/fc.json' --attestation '$WORK/fc-att.json' --scope-bin '$WORK/extra-scope' --import-id t) == 1 ]]" +printf '#!/bin/sh\n"%s" "$@" || exit $?\nprintf "/etc/passwd\\n" > "$4"\nphp -r "\\$s=json_decode(file_get_contents(\\$argv[1]));\\$s->files_total+=1-\\$s->files_scanned;\\$s->files_scanned=1;file_put_contents(\\$argv[1],json_encode(\\$s));" "$6"\n' "$WHP_SCAN_SCOPE_BIN" > "$WORK/out-scope"; chmod +x "$WORK/out-scope" +check "a list entry outside the extract => exit 1" "[[ \$(frc env CLAM_EXTRACT='$HT' CLAMSCAN_ARGS_OUT='$WORK/x.args' CLAMSCAN_LIST_OUT='$WORK/x.list' PATH='$STUBBIN:$PATH' php '$REPO/scripts/scan-files.php' --extract '$HT' --quarantine '$WORK/q-x' --report '$WORK/fc.json' --attestation '$WORK/fc-att.json' --scope-bin '$WORK/out-scope' --import-id t) == 1 ]]" + echo if [[ $FAILS -eq 0 ]]; then echo "ALL PASS"; else echo "$FAILS FAILURE(S)"; fi exit $(( FAILS == 0 ? 0 : 1 )) From 3321176b4dff644b43cf8ee69f443e520c682222 Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Sun, 22 Nov 2026 07:30:19 -0800 Subject: [PATCH 3/5] build: pin the Go image by digest; WHP source token via a read-only secret and a credential helper - GO_IMAGE was the floating tag golang:1.27-alpine: now pinned to the index digest sha256:70bd7dde... (resolved 2026-11-22). - The WHP fetch passed the token on git's command line (-c http.extraHeader=...$(cat secret)): now a credential helper reads the BuildKit secret file at fetch time (GIT_TERMINAL_PROMPT=0). Verified on a local build: the token is in no layer blob, not in docker history, not in docker inspect, not in /whp/.git/config, not in the build log. - CI passed CI_TOKEN (registry push rights) as whp_token: now the repo secret WHP_READ_TOKEN (a read-only token for cloud-hosting-platform/whp, to be created by an admin); the workflow fails at its first step with a clear error while it is not set. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6 --- .gitea/workflows/build-push.yaml | 16 ++++++++++++++-- Dockerfile | 18 +++++++++++++----- README.md | 10 ++++++++-- 3 files changed, 35 insertions(+), 9 deletions(-) diff --git a/.gitea/workflows/build-push.yaml b/.gitea/workflows/build-push.yaml index 099ef2b..03f4f17 100644 --- a/.gitea/workflows/build-push.yaml +++ b/.gitea/workflows/build-push.yaml @@ -14,6 +14,18 @@ jobs: - name: Checkout uses: actions/checkout@v4 + # The image builds whp-scan-scope from the private WHP repo at the pinned WHP_COMMIT. It needs a + # READ-ONLY token scoped to cloud-hosting-platform/whp (repo secret WHP_READ_TOKEN), never the + # registry-push CI_TOKEN. Fail here, clearly, instead of half-way through the build. + - name: Require WHP_READ_TOKEN + env: + WHP_READ_TOKEN: ${{ secrets.WHP_READ_TOKEN }} + run: | + if [ -z "${WHP_READ_TOKEN:-}" ]; then + echo "::error::repo secret WHP_READ_TOKEN is not set: create a read-only token for cloud-hosting-platform/whp and add it as WHP_READ_TOKEN (see README.md)" + exit 1 + fi + # Base image pinned by DIGEST, looked up directly at Docker Hub (never via # the pkg-cache mirror), so the mirror can only serve content-addressed # blobs that BuildKit verifies. If the lookup fails this job does NOT use @@ -116,7 +128,7 @@ jobs: BASE_IMAGE=${{ steps.base.outputs.image }} PKG_CACHE=${{ steps.pkgcache.outputs.url }} secrets: | - whp_token=${{ secrets.CI_TOKEN }} + whp_token=${{ secrets.WHP_READ_TOKEN }} tags: cpanel-importer:smoke no-cache: true @@ -170,7 +182,7 @@ jobs: BASE_IMAGE=${{ steps.base.outputs.image }} PKG_CACHE=${{ steps.pkgcache.outputs.url }} secrets: | - whp_token=${{ secrets.CI_TOKEN }} + whp_token=${{ secrets.WHP_READ_TOKEN }} tags: ${{ steps.tags.outputs.tags }} cache-from: type=registry,ref=repo.anhonesthost.net/cloud-hosting-platform/cpanel-importer:latest cache-to: type=inline diff --git a/Dockerfile b/Dockerfile index 2b9565f..faaa26d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -23,11 +23,17 @@ ARG BASE_IMAGE=almalinux:10-minimal # scan policy changes. It is currently the merge of WHP PR #331 (limit 256 MiB); # bump it to the merge commit of the WHP PR that raises the limit to 2000 MiB # (feat/scan-scope-2gib) BEFORE publishing an image that is meant to enforce it. -# CI passes the repo token as the BuildKit secret `whp_token` (read access to -# cloud-hosting-platform/whp). For a local build without network access to the +# CI passes a READ-ONLY token for cloud-hosting-platform/whp as the BuildKit +# secret `whp_token` (repo secret WHP_READ_TOKEN: never the registry-push +# CI_TOKEN). The token is handed to git by a credential helper that reads the +# secret file at fetch time: it is never on a command line, in an ENV/ARG, in +# .git/config or in a layer. For a local build without network access to the # repo, override the whole source stage with a checkout: # docker buildx build --build-context whp-src=/path/to/whp-checkout ... -ARG GO_IMAGE=golang:1.27-alpine +# +# GO_IMAGE is pinned by DIGEST (the multi-arch index of golang:1.27-alpine, +# resolved 2026-11-22 from registry-1.docker.io). Bump tag and digest together. +ARG GO_IMAGE=golang:1.27-alpine@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 ARG WHP_REPO=https://repo.anhonesthost.net/cloud-hosting-platform/whp.git ARG WHP_COMMIT=e668e25dcdc1938d9d9399ea904daba71c0f0778 @@ -36,12 +42,14 @@ ARG WHP_REPO ARG WHP_COMMIT RUN apk add --no-cache git RUN --mount=type=secret,id=whp_token,required=false \ - set -eu; \ + set -eu; export GIT_TERMINAL_PROMPT=0; \ case "${WHP_COMMIT}" in *[!0-9a-f]*|"") echo "WHP_COMMIT must be a full lowercase hex sha" >&2; exit 1;; esac; \ [ "${#WHP_COMMIT}" -eq 40 ] || { echo "WHP_COMMIT must be 40 hex chars" >&2; exit 1; }; \ git init -q /whp && cd /whp; \ if [ -s /run/secrets/whp_token ]; then \ - git -c "http.extraHeader=Authorization: token $(cat /run/secrets/whp_token)" fetch -q --depth 1 "${WHP_REPO}" "${WHP_COMMIT}"; \ + git -c credential.helper= \ + -c 'credential.helper=!f() { [ "$1" = get ] || exit 0; echo username=whp-read; printf "password=%s\n" "$(cat /run/secrets/whp_token)"; }; f' \ + fetch -q --depth 1 "${WHP_REPO}" "${WHP_COMMIT}"; \ else \ git fetch -q --depth 1 "${WHP_REPO}" "${WHP_COMMIT}"; \ fi; \ diff --git a/README.md b/README.md index b66d8e9..63db790 100644 --- a/README.md +++ b/README.md @@ -79,13 +79,19 @@ named by `userdata`; NOT the mail tree, logs, clean bulk media or plain data out (`oversize_unscanned_files` for clean media/archives: a staff-review warning; `in_scope_unscanned_files` for anything else: the panel refuses the import). `report.json` carries the tool's whole stats object plus the engine fields as its `scan` object; the panel's privd validates it. **No tool, no scan:** a missing or failing -`whp-scan-scope`, or clamscan exit >= 2, fails the run (`status: failed`), there is no fall back to an unscoped scan. +`whp-scan-scope`, clamscan exit >= 2, a summary with `Total errors` > 0 (clamscan exits 1, not 2, when one file is +infected and another could not be read), a hit line that is not an exact entry of the list, a list entry that is not +a plain path below the extract, or a hit that cannot be moved to quarantine fails the run (`status: failed`); there +is no fall back to an unscoped or partial scan. `--tempdir` of clamscan is the disk scratch `/host/sanitized//work/clamtmp` (removed after the scan), never the RAM `/tmp`. Bump `WHP_COMMIT` whenever the WHP scan policy or limits change (it must be a full 40-hex sha). Local build without access to the private repo: `docker buildx build --build-context whp-src=/path/to/whp-checkout -t cpanel-importer:dev .`. -In CI the repo token is the BuildKit secret `whp_token`. +In CI the BuildKit secret `whp_token` comes from the repo secret **`WHP_READ_TOKEN`**: a READ-ONLY token for +`cloud-hosting-platform/whp` (never the registry-push `CI_TOKEN`); the workflow fails at its first step when it is +not set. It reaches git through a credential helper that reads the secret file, so it is never on a command line or +in a layer. The Go build image is pinned by digest (`GO_IMAGE`). Container exits with status `0` on success, non-zero on any failure (missing/unreadable backup, dangerous symlink found, scanner error). From 63286329e326c04ab31eafea7135c21648560968 Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Sun, 22 Nov 2026 07:34:12 -0800 Subject: [PATCH 4/5] scan-files: a hit inside the skipped mail tree fails the run It was logged as a WARN and dropped from the report: a web-root link into a Maildir (x.php -> ../mail///cur/) got the message listed as the link's target, and an infected message vanished from what privd sees. Now fatal (the message is still never moved out of the Maildir). whp-scan-scope (WHP #334) refuses such links by name as well. Tests: relative, absolute and chained web-root links to an EICAR message (red on the pre-review script with the pre-review tool), and a listed mail-tree hit (red on the pre-review script). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6 --- scripts/scan-files.php | 9 +++++---- tests/run-tests.sh | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/scripts/scan-files.php b/scripts/scan-files.php index b569e23..e2f1e25 100755 --- a/scripts/scan-files.php +++ b/scripts/scan-files.php @@ -262,10 +262,11 @@ foreach (explode("\n", $clamOut) as $line) { exit(1); } if ($skipMail && preg_match($mailDirPcre, $path)) { - // Only reachable through a web-root symlink whose target is a message (the scope lists link - // targets): the message is copied verbatim into the mailbox, never served. Never move it out. - fwrite(STDERR, "scan-files: WARN ignoring a hit inside the mail tree: " . json_encode($path) . "\n"); - continue; + // Only reachable through a web-root symlink whose target is a message (whp-scan-scope refuses + // those itself since the 2026-11-22 review). Never move a message out of a Maildir, and never + // drop the hit either: fail the run. + fwrite(STDERR, "scan-files: FATAL: infected file inside the skipped mail tree reached through the scan list (a web-root link into a Maildir?): " . json_encode($path) . "\n"); + exit(1); } $hits[$path] = ['path' => $path, 'signature' => $sig]; // a path listed twice (link target + file) is one hit } diff --git a/tests/run-tests.sh b/tests/run-tests.sh index b093391..b8d45d7 100755 --- a/tests/run-tests.sh +++ b/tests/run-tests.sh @@ -398,6 +398,20 @@ if [[ $(id -u) -ne 0 ]]; then check "a hit that cannot be quarantined => exit 1 (never left in the tree silently)" "[[ \$(hrun env) == 1 && -f '$HP/EVIL2.php' ]]" chmod 700 "$WORK/q-hostile" fi +printf '#!/bin/sh\n"%s" "$@" || exit $?\nm=$(find "$2" -path "*/homedir/mail/*" -type f | head -1)\nprintf "%%s\\n" "$m" > "$4"\nphp -r "\\$s=json_decode(file_get_contents(\\$argv[1]));\\$s->files_total+=1-\\$s->files_scanned-\\$s->in_scope_unscanned;\\$s->files_scanned=1;\\$s->in_scope_unscanned=0;\\$s->in_scope_unscanned_files=[];file_put_contents(\\$argv[1],json_encode(\\$s));" "$6"\n' "$WHP_SCAN_SCOPE_BIN" > "$WORK/mail-scope"; chmod +x "$WORK/mail-scope" +# web-root links into the skipped mail tree (relative, absolute, chain) -> the message holds the EICAR string +MT="$WORK/maillink"; MM="$MT/cpmove-m/homedir/mail/example.com/alice/cur"; MP="$MT/cpmove-m/homedir/public_html" +mkdir -p "$MM" "$MP" "$WORK/q-ml" +printf 'X5O!P%%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*' > "$MM/1700000000.M1P1.host,S=40:2,S" +ln -s ../mail/example.com/alice/cur/1700000000.M1P1.host,S=40:2,S "$MP/rel.php" +ln -s "$MM/1700000000.M1P1.host,S=40:2,S" "$MP/abs.php"; ln -s rel.php "$MP/chain.php" +mlrc=0; CLAM_EXTRACT="$MT" CLAM_TOP=cpmove-m CLAMSCAN_ARGS_OUT="$WORK/clam-ml.args" CLAMSCAN_LIST_OUT="$WORK/clam-ml.list" PATH="$STUBBIN:$PATH" \ + php "$REPO/scripts/scan-files.php" --extract "$MT" --quarantine "$WORK/q-ml" --report "$WORK/scan-ml.json" --attestation "$WORK/attest-ml.json" \ + --scope-bin "$WHP_SCAN_SCOPE_BIN" --import-id t-ml --skip-mail >"$WORK/scan-ml.log" 2>&1 || mlrc=$? +check "web-root links into the mail tree: never silently accepted (scope refuses them by name, or the run fails)" \ + "[[ $mlrc -ne 0 || \$(php -r '\$a=json_decode(file_get_contents(\$argv[1])); echo \$a->in_scope_unscanned;' '$WORK/attest-ml.json') == 3 ]]" +check "a listed mail-tree path that clamscan flags => exit 1 (old: WARN and ignored)" \ + "[[ \$(frc env CLAM_EXTRACT='$MT' CLAM_TOP=cpmove-m CLAMSCAN_ARGS_OUT='$WORK/x.args' CLAMSCAN_LIST_OUT='$WORK/x.list' PATH='$STUBBIN:$PATH' php '$REPO/scripts/scan-files.php' --extract '$MT' --quarantine '$WORK/q-x' --report '$WORK/fc.json' --attestation '$WORK/fc-att.json' --scope-bin '$WORK/mail-scope' --import-id t --skip-mail) == 1 && -f '$MM/1700000000.M1P1.host,S=40:2,S' ]]" printf '#!/bin/sh\n"%s" "$@" || exit $?\nprintf "%%s/x\\n" "$2" >> "$4"\n' "$WHP_SCAN_SCOPE_BIN" > "$WORK/extra-scope"; chmod +x "$WORK/extra-scope" check "the list holds more entries than files_scanned => exit 1" "[[ \$(frc env CLAM_EXTRACT='$HT' CLAMSCAN_ARGS_OUT='$WORK/x.args' CLAMSCAN_LIST_OUT='$WORK/x.list' PATH='$STUBBIN:$PATH' php '$REPO/scripts/scan-files.php' --extract '$HT' --quarantine '$WORK/q-x' --report '$WORK/fc.json' --attestation '$WORK/fc-att.json' --scope-bin '$WORK/extra-scope' --import-id t) == 1 ]]" printf '#!/bin/sh\n"%s" "$@" || exit $?\nprintf "/etc/passwd\\n" > "$4"\nphp -r "\\$s=json_decode(file_get_contents(\\$argv[1]));\\$s->files_total+=1-\\$s->files_scanned;\\$s->files_scanned=1;file_put_contents(\\$argv[1],json_encode(\\$s));" "$6"\n' "$WHP_SCAN_SCOPE_BIN" > "$WORK/out-scope"; chmod +x "$WORK/out-scope" From bfe233094596a177d3ee3b9c090677ac49317e4c Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Sun, 22 Nov 2026 07:37:54 -0800 Subject: [PATCH 5/5] build: pin WHP_COMMIT to the merge of WHP #334 (8a350449e5e8) whp-scan-scope with the 2000 MiB limit and the review fixes (unreadable files, control characters, >= 1023-byte paths and web-root links into the skipped mail tree refused by name). Verified: full build through the fetch path with a token secret (token in no layer, history, inspect or build log), tests/run-tests.sh and tests/image-scope-test.sh ALL PASS on the built image. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6 --- Dockerfile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Dockerfile b/Dockerfile index faaa26d..7b31ac1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -20,9 +20,9 @@ ARG BASE_IMAGE=almalinux:10-minimal # in that repo. # # WHP_COMMIT MUST be a full 40-hex commit sha and MUST be bumped when the -# scan policy changes. It is currently the merge of WHP PR #331 (limit 256 MiB); -# bump it to the merge commit of the WHP PR that raises the limit to 2000 MiB -# (feat/scan-scope-2gib) BEFORE publishing an image that is meant to enforce it. +# scan policy changes. It is the merge of WHP PR #334 (limit 2000 MiB; refuses +# unreadable, control-character, >= 1023-byte paths and web-root links into the +# skipped mail tree). # CI passes a READ-ONLY token for cloud-hosting-platform/whp as the BuildKit # secret `whp_token` (repo secret WHP_READ_TOKEN: never the registry-push # CI_TOKEN). The token is handed to git by a credential helper that reads the @@ -35,7 +35,7 @@ ARG BASE_IMAGE=almalinux:10-minimal # resolved 2026-11-22 from registry-1.docker.io). Bump tag and digest together. ARG GO_IMAGE=golang:1.27-alpine@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 ARG WHP_REPO=https://repo.anhonesthost.net/cloud-hosting-platform/whp.git -ARG WHP_COMMIT=e668e25dcdc1938d9d9399ea904daba71c0f0778 +ARG WHP_COMMIT=8a350449e5e89703ad1b0ad1c1a446f001d178b5 FROM ${GO_IMAGE} AS whp-fetch ARG WHP_REPO