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=<checkout> 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXi4YX5FxJGqhi6qab6
This commit is contained in:
shadowdaoandClaude Sonnet 5.5 committed 2026-11-22 07:05:11 -08:00
1 parent 228eb94ad5
commit 7da863cfd1
9 files changed
+469 -137

No files matched your search

+18 -2
View File
@@ -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"
+146 -113
View File
@@ -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 <dir> --quarantine <dir> --report <out.json> --import-id <id> [--skip-mail]
* scan-files.php --extract <dir> --quarantine <dir> --report <out.json> --attestation <out.json>
* --import-id <id> [--scratch <dir>] [--skip-mail] [--scope-bin <path>]
*
* --skip-mail: do not scan (or count, or quarantine anything in) the
* <top dir>/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 <dir> --quarantine <dir> --report <out.json> --import-id <id> [--skip-mail]\n");
fwrite(STDERR, "usage: scan-files.php --extract <dir> --quarantine <dir> --report <out.json> --attestation <out.json> --import-id <id> [--scratch <dir>] [--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/<user>/...)
// 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/<user>/<addon>/wp-content/db.php, access-logs ->
// /usr/local/apache/domlogs/<user>, 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 --------------------------------------------