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 ))