--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 (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, // = length of the clamscan file list * "files_clean": N, * "files_cleaned": 0, // always 0 in v1.0 — no cleaners yet * "files_quarantined": N, * "actions": [ { path, signature, action, cleaner, backup } ] * } */ require __DIR__ . '/lib/safety-net.php'; const SCANNER_VERSION = '1.1.0'; // 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 --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); // /homedir/mail: WHP accepts any top-level dir name // (cpmove-, backup-_, ...), so the skip covers all of them. // The mail tree is copied verbatim into the customer's own mailbox, and // WHP verifies the copy message-by-message against what it packaged. So it // is NOT scanned: quarantining a message would silently drop mail, and // ClamAV over a multi-GB maildir would dominate the run. PCRE form for the // PHP walk, POSIX ERE form for clamscan --exclude-dir. $mailDirPcre = '#\A' . preg_quote($extractDir, '#') . '/[^/]+/homedir/mail(?:/|\z)#'; $mailDirEre = '^' . preg_replace('/[.\[\]()*+?{}|^$\\\\]/', '\\\\$0', $extractDir) . '/[^/]+/homedir/mail(/.*)?$'; if (!is_dir($extractDir)) { fwrite(STDERR, "scan-files: extract dir does not exist: $extractDir\n"); exit(2); } @mkdir($quarantineDir, 0750, true); fwrite(STDERR, "scan-files: starting (extract=$extractDir, quarantine=$quarantineDir)\n"); if ($skipMail) { fwrite(STDERR, "scan-files: NOT scanning the mail tree (/homedir/mail): it is copied verbatim into the customer's own mailbox and verified against the source; scanning would quarantine messages out of it and multi-GB maildirs would dominate the run\n"); } // -- v1.0 cleaner registry (intentionally empty) ---------------------------- // // Each entry maps a ClamAV signature substring -> classification + // cleaner callable. v1.0 ships empty so EVERY hit is classified as // QUARANTINE_ONLY. See CONTRIBUTING.md "Adding an auto-cleaner pattern" // for how to add a tested entry. // // Shape (v1.1+): // $cleaners = [ // 'php-eval-base64-prefix' => [ // 'class' => 'KNOWN_REMOVABLE', // 'match' => fn(string $sig): bool => str_contains($sig, 'PHP.Trojan.EvalB64'), // 'clean' => fn(string $path): bool => /* rewrite file in place; return ok */, // ], // ]; $cleaners = []; // -- scope: decide which files clamscan sees -------------------------------- /** * 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 )); // 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". [$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); } // 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 (explode("\n", $clamOut) as $line) { $line = rtrim($line, "\r"); if (preg_match('/^Known viruses: (\d+)$/', $line, $m)) { $known = (int) $m[1]; continue; } 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)) { // 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 } $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"); exit(1); } // 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 -------------------------------------------- $actions = []; $cleaned = 0; $quarantined = 0; foreach ($hits as $h) { $path = $h['path']; $sig = $h['signature']; // v1.0 — every hit is QUARANTINE_ONLY because the cleaner registry // is empty. Future work in v1.1 will iterate $cleaners and pick a // matching cleaner. $classification = 'QUARANTINE_ONLY'; foreach ($cleaners as $name => $entry) { if (($entry['match'])($sig)) { $classification = $entry['class']; $cleanerName = $name; break; } } $relPath = ltrim(substr($path, strlen($extractDir)), '/'); $qPath = $quarantineDir . '/' . $relPath; if ($classification === 'QUARANTINE_ONLY') { // Move the whole file to quarantine; remove from extract dir so // the rsync to /host/sanitized/ does not include it. @mkdir(dirname($qPath), 0750, true); if (!@rename($path, $qPath)) { // Fall back to copy + unlink (rename across mount boundaries // sometimes EXDEVs even though /tmp and /host are both ours). if (@copy($path, $qPath)) { @unlink($path); } } 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, 'signature' => $sig, 'action' => 'quarantined', 'cleaner' => null, 'backup' => $qPath, ]; continue; } // v1.1+ paths: if ($classification === 'KNOWN_REMOVABLE' || $classification === 'REMOVABLE_WITH_BACKUP') { // Backup first, then run the cleaner. @mkdir(dirname($qPath), 0750, true); $backup = $qPath . '.original'; if (!@copy($path, $backup)) { fwrite(STDERR, "scan-files: backup before clean failed: $path; quarantining instead\n"); @rename($path, $qPath); $quarantined++; $actions[] = [ 'path' => $relPath, 'signature' => $sig, 'action' => 'quarantined', 'cleaner' => null, 'backup' => $qPath, ]; continue; } $cleanerOk = ($cleaners[$cleanerName]['clean'])($path); if (!$cleanerOk) { // Cleaner refused; fall back to quarantine. @rename($path, $qPath); $quarantined++; $actions[] = [ 'path' => $relPath, 'signature' => $sig, 'action' => 'quarantined', 'cleaner' => $cleanerName, 'backup' => $qPath, ]; continue; } $cleaned++; $actions[] = [ 'path' => $relPath, 'signature' => $sig, 'action' => 'cleaned', 'cleaner' => $cleanerName, 'backup' => $backup, ]; } } $report = [ 'scanner_version' => SCANNER_VERSION, 'import_id' => $importId, 'files_scanned' => $filesScanned, 'files_clean' => max(0, $filesScanned - count($hits)), 'files_cleaned' => $cleaned, 'files_quarantined' => $quarantined, 'mail_scan_skipped' => $skipMail, 'actions' => $actions, ]; @file_put_contents($reportPath, json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n"); fwrite(STDERR, sprintf( "scan-files: done — scanned=%d clean=%d cleaned=%d quarantined=%d\n", $filesScanned, $report['files_clean'], $cleaned, $quarantined )); exit(0);