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 <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:30:19 -08:00
1 parent 7da863cfd1
commit 2ebb05a6d6
3 files changed
+141 -21

No files matched your search

+77 -17
View File
@@ -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 ("<listed path>: <signature> 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,