@param array $config avMode (clamd|clamscan|skip; skip only with env UPLOAD_GUARD_ENV=test|dev),
clamd (socket|host,port,timeoutMs), clamscan (binary, dbDir, lockFile, timeoutMs, lockWaitMs,
maxDbAgeHours), auditLog, policyDir, tmpDir, onScannerDown, maxDbAgeHours (72, clamd only),
maxEntryBytes (5 MiB)
@throws InvalidArgumentException on an invalid avMode (the only thing the constructor validates)
Remove temporary directories created by this instance (sanitized files not yet finalized).
Neutralise a spreadsheet cell for CSV/XLSX export (formula injection).
Text that would be sent to a model for an inspected file (name + metadata + body), capped.
Move/write an accepted file into $destDir under a random name; returns the stored path.
$originalPath is only needed for an 'accept' verdict of a different guard instance.
Inspect a file that is already stored temporarily outside the webroot.
Never throws; any internal failure produces a reject verdict (fail closed).
Batch API: items = array(array('path' =>, 'claimed' =>, 'profile' =>, 'context' =>), ...); returns the verdicts in the
same order. S0-S4 run per item, then ALL pending files go through ONE AV phase (avMode clamscan: one clamscan run,
one database load), then S6/S7 per item; one audit line per item. Never throws.
Heuristic scan of untrusted text. Returns array(score, findings, cleaned, level ok|flag|high).
Wrap untrusted text for a prompt in a block with a random nonce (spec 6.3).
avMode clamscan: all files of all pending jobs (main files and unpacked zip entries) in ONE clamscan run.
S5 for every job that survived S1-S4: known-bad list, then clamd per item or ONE clamscan run for the batch.
heic / heif / avif box tree (spec 5, mirrors bmff.py): top-level boxes add up exactly to the file size, ftyp first and
well-formed (size >= 16, (size-16) % 4 == 0), exactly one meta; meta (full box) and iprp/ipco/dinf are walked with the
same rule. Caps: 64 top-level boxes, 4096 in total, depth 6. Reads headers only.
ISO BMFF top-level box chain (mp4 / mov) must tile the whole file; ftyp first; moov, mdat or moof present.
------------------------------------------------------------------ // policy / config helpers // ------------------------------------------------------------------
------------------------------------------------------------------ // S4: executability // ------------------------------------------------------------------
------------------------------------------------------------------ // S3: images // ------------------------------------------------------------------
------------------------------------------------------------------ // S3: binary containers (audio, video, fonts) // ------------------------------------------------------------------
Returns the lowercase extension (last part) or null; appends reason codes to $reasons.
------------------------------------------------------------------ // S3: PDF // ------------------------------------------------------------------
RTF (spec 5, mirrors structure.check_rtf): embedded objects (\\object, \\objdata ...), DDE/INCLUDE fields -> ACTIVE_CONTENT,
external templates -> EXTERNAL_REF, raw \\binN data (cannot be inspected) -> PARSE_FAIL. Plain text for S6 goes to $st['texts'].
------------------------------------------------------------------ // S3 dispatcher // ------------------------------------------------------------------
------------------------------------------------------------------ // SVG: strict re-serialising sanitizer (own tokenizer, no DOM, no network) // ------------------------------------------------------------------
Returns the text decoded to UTF-8; appends XML_DTD / EXTERNAL_REF / PARSE_FAIL to $r.
Health check (PING + VERSION), cached 5 minutes. Returns array('age' => hours|null) or null if clamd is down.
Returns array('found' => bool, 'sig' => string|null) or null when clamd misbehaved (= DOWN).
Exclusive host-wide lock (shared protocol, identical in all ports): the lock file is created with fopen(..., 'x')
(O_EXCL) and holds "
unlinked; retries every 200 ms up to $waitMs. Returns true when the lock is held (release with clamscanUnlock) or false
(= scanner down).
Returns array('res' => path => signature|null, 'age' => hours, 'maxAge' => hours) or null when the scanner is down.
ISO-BMFF with ftyp at offset 4: avif | heic | heif | mov | mp4 | null (spec 4.1). Major brand qt = mov; a compatible
brand is only considered when the major brand is not an mp4 brand; the ftyp size must be sane (>= 16, (size-16) % 4 == 0).
Decode XML bytes in any UTF flavour into UTF-8 for textual scans (never throws).
Magic-at-offset-0 types. Returns type, 'zip' for a zip container, or null.
Content based detection. Returns array('type' => string|null, 'zip' => directory|null).
$ext is the claimed lowercase extension (used only to enable csv/json, which are plain text).
------------------------------------------------------------------ // S6: text extraction // ------------------------------------------------------------------
Minimal NFKC substitute (fullwidth ASCII, mathematical alphanumerics, exotic spaces) when intl is missing.
Walks the GIF block structure. Returns array(end, frames, headEnd, keep[]) or false.
Regex helper: a match OR a regex failure counts as a hit (fail closed).
------------------------------------------------------------------ // injection helpers // ------------------------------------------------------------------
Set of names (decoded) used in a PDF fragment: array(name => true).
Splits a PDF into the skeleton (stream bodies removed) and the list of streams.
Scans every file in $files. Returns array(name, result OK|FOUND|DOWN, signature, dbAgeHours, stale).
Marker scan (spec 4.3). $text: whole text type; otherwise a binary view where short markers need context.
AV unavailable: reject (AV_DOWN) or, with onScannerDown=hold, quarantine.
S0..S4 (profile, input, name, type identity, structure, executability). Sets $j['done'] on a reject.
S6 (LLM text) and S7 (result).
Rejects the job and ends its pipeline.
Parses a restricted XML subset and re-serialises only allow-listed elements/attributes.
Returns the sanitized document or null (with $err = ACTIVE_CONTENT | PARSE_FAIL).
Handles a text segment (or CDATA). Returns false on failure ($err set).
Valid UTF-8 text without NUL/control characters (BOM stripped) or null.
Drop a leading UTF-8 BOM and leading whitespace.
Unsigned 32-bit big endian (float on 32-bit PHP when >= 2^31).
------------------------------------------------------------------ // S7: sanitized output // ------------------------------------------------------------------
Weak fallback when ext/xml is missing: balanced tags, single root, only predefined entities.
Name of the first element after the prolog (xml decl, comments, PIs, DOCTYPE), or null.
Resolve the 5 predefined entities and numeric references; null if anything else appears.
------------------------------------------------------------------ // zip: own central directory parser (no ZipArchive needed), limits, containers // ------------------------------------------------------------------
One entry of a plain zip: runs through name + type + structure + executability checks as a separate file.
Reads and verifies one entry (stored or deflate). Returns data or false with $err set.
Chameleon Framework © 2012 - 2026