From 2ebb05a6d62b734f5c6729830f12dc1ace0b1fbb Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Sun, 22 Nov 2026 07:30:19 -0800 Subject: [PATCH] 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 ))