ClamAV S3 Upload Scanning Without Exposing Unapproved Files

Storage & Media

Design ClamAV scanning for S3 uploads with bounded streaming, private quarantine, and version-locked promotion. Keep unapproved files out of download paths.

TL;DR

  • Make a successful scan a prerequisite for download, rendering, indexing, or forwarding. In a direct upload flow, write to an isolated S3 quarantine bucket and publish only the scanned object version.
  • For small files that already pass through the API, spool the upload within a byte limit and scan that same stream with ClamAV before writing to the serving bucket.
  • Keep scanner timeouts, unavailable engines, unsupported files, and incomplete results outside the serving path. Record the outcome separately from the upload state.
  • Test the download boundary and recovery path with harmless fixtures, duplicate events, and simulated scanner outages.

The security boundary is the first read

A customer uploads an invoice from a browser. The same application immediately creates a thumbnail, adds the filename to a shared workspace, and sends a link to finance. A scanner subscribed to storage notifications starts a few seconds later. Even if its eventual detection is correct, the preview service and email recipient have already received unreviewed data. The architecture allowed reads before a verdict.

“Before S3 write” works when the API owns the entire body path and the size is bounded. It becomes awkward for large uploads and mobile clients on slow networks. An isolated S3 bucket can accept bytes earlier without offering a path to downloads or previews. The invariant becomes: no unapproved object version is readable by the serving system. This can hold during partial uploads, duplicate messages, and scanner outages.

Draw every read path before selecting an engine. Include CDN origins, presigned downloads, preview workers, extractors, export jobs, support tools, and any direct access granted to client credentials. For each principal, identify the bucket it can access and the condition under which it gets an object key. A private bucket alone does not enforce workflow if the application serving role can issue a presigned URL for anything in that bucket. Amazon S3 presigned requests

Model upload and publication distinctly in the UI. After transfer, return “Received, scanning” and a status route or event subscription. The path presented after upload should be a logical document ID, with the download action enabled only after approval. Make rejections actionable where possible, and retain a separate operator reason for configuration failures or unsupported formats.

Choose inline scanning or isolated quarantine

Inline ClamAV scanning for small API uploads

Inline scanning has two serial phases: receive and scan the original bytes, then write them to private storage when the scanner accepts them. It fits a route already receiving low-volume attachments with a clear maximum size and enough application time to handle both phases. Set corresponding request limits upstream, since many frameworks process multipart forms before entering the route. Apply format policy and authorization before reading or forwarding the content wherever the framework permits.

A spool keeps small documents in memory and moves larger bodies to temporary storage. Set the rollover threshold and the absolute byte cap separately. Keep the spool outside any served directory and remove it on success, rejection, timeout, or disconnect. Under concurrency, budget both API memory and temporary disk capacity. The maximum permitted per-file size alone does not bound aggregate resource consumption. Python spooled temporary files

Private S3 quarantine for direct browser uploads

Issue an upload capability for a generated key under a private quarantine bucket. Associate it with the authenticated tenant and the upload record. Treat the user-supplied filename as display metadata. Give the upload role scoped write privileges and give the scanner version-specific quarantine read access. The download signer should read only the approved destination. Keep browser requests away from destination keys even when the user knows the destination naming scheme.

Enable S3 Versioning before accepting uploads and capture the exact VersionId from each relevant object creation event. A presigned URL can be reused while it remains valid, and a later request to the same key can produce a new version. A decision about version A must only authorize A. Store per-version evidence, then choose whether an upload record accepts its first valid version or explicitly supersedes it. Never switch the mapping merely because an event arrived last. S3 Versioning · Presigned URL behavior

S3 notifications can be delivered more than once and out of order. Build a durable job key from bucket, object key, and version ID. The event key for native S3 notifications is URL-encoded. Decode it for SDK calls before putting it in the chosen internal identity representation. Only use the S3 sequencer to compare events for the same key. Avoid letting notification order define what a user can access. S3 event delivery · S3 event message structure

Implement a bounded scanner and explicit promotion

Send a bounded stream to the ClamAV Unix socket

The following Python helper expects a blocking binary stream and a reachable local clamd socket. Use a synchronous worker or a dedicated thread for the scanner connection. The protocol uses a command, network-order chunk lengths, a zero-length final frame, and a NUL-terminated reply. Returning normally represents the one accepted daemon reply for this operation. All other outcomes leave publishing blocked. ClamAV clamd protocol

# Python 3.11+. The caller owns and closes the upload stream and spool.
import socket
import struct
from typing import BinaryIO

class BlockedUpload(Exception):
    pass

class ScanUnavailable(Exception):
    pass

def inspect_upload(source: BinaryIO, spool: BinaryIO, limit: int) -> int:
    size = 0
    reply = bytearray()
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as daemon:
            daemon.settimeout(15)
            daemon.connect("/run/clamav/clamd.sock")
            daemon.sendall(b"zINSTREAM\0")
            while chunk := source.read(64 * 1024):
                size += len(chunk)
                if size > limit:
                    raise BlockedUpload("upload_too_large")
                spool.write(chunk)
                daemon.sendall(struct.pack("!I", len(chunk)) + chunk)
            daemon.sendall(struct.pack("!I", 0))

            while b"\0" not in reply and len(reply) < 4096:
                block = daemon.recv(min(512, 4096 - len(reply)))
                if not block:
                    break
                reply.extend(block)
    except OSError as exc:
        raise ScanUnavailable("upload_stream_or_scanner_error") from exc

    if b"\0" not in reply:
        raise ScanUnavailable("incomplete_scan_reply")
    line = bytes(reply.partition(b"\0")[0])
    if line.startswith(b"stream: ") and line.endswith(b" FOUND"):
        raise BlockedUpload("scanner_blocked_file")
    if line != b"stream: OK":
        raise ScanUnavailable("scan_did_not_complete")

    spool.seek(0)
    return size

Give the function a fresh, owned spool for one request and pass that spool directly to the approved write after success. Keeping a single byte stream prevents a filename lookup or another open call from swapping the bytes between scan and write. Use structured reasons for the operator. A scanner policy limit can present as FOUND under a heuristic signature, so a blocked result does not necessarily mean confirmed malware. Inspect only appropriate diagnostic fields in restricted logs.

The socket timeout bounds an individual I/O call. Give the entire upload and inspection their own bounded time through the API server and task supervisor. Cancel an interrupted request without publishing even if a late verdict appears. Return an appropriate size, policy, or temporary service error. Use client retries for clearly retryable failures only, with a new upload session where the product contract requires one.

Configure the daemon limits and signature updates

# clamd.conf excerpt for an API with a 16 MiB upload cap.
# Configure ownership of /run/clamav for the shared local socket.
LocalSocket /run/clamav/clamd.sock
LocalSocketMode 660
StreamMaxLength 16M
MaxFileSize 16M
MaxScanSize 64M
MaxRecursion 12
MaxThreads 4
AlertExceedsMax yes

The daemon's streamed-input limit and internal inspection limits address different resources. Expanded content can exceed limits while the upload fits its wire-size budget. Test allowed file types with the deployed engine and configuration. For workflows that must inspect every member, explicitly reject unsupported formats or formats whose contents cannot be reviewed under the policy. A multi-format scanner is not a substitute for application-specific parsing restrictions. Keep signatures current with FreshClam and validate that the running daemon has loaded the intended signature data. ClamAV's TCP socket has no application authentication. Use a local socket or an isolated private network. ClamAV sample configuration · ClamAV and FreshClam configuration · ClamAV scanning documentation

Promote only the object version that was scanned

In the quarantine flow, the scanner reads with GetObject(VersionId=...) and stores the outcome under a unique upload-version record. The version string should come from the job identity. A promoter verifies that the record allows publication and uses an exact-version copy. This sample assumes both buckets are versioned, destination keys are worker-generated under tenant scope, and documents are delivered as attachments.

# Boto3. Call only after validating the durable accepted verdict.
def copy_approved_version(s3, source_bucket: str, source_key: str,
                          source_version: str, approved_bucket: str,
                          destination_key: str) -> str:
    if not source_version or source_version == "null":
        raise ValueError("a versioned quarantine object is required")

    copy = s3.copy_object(
        Bucket=approved_bucket,
        Key=destination_key,
        CopySource={
            "Bucket": source_bucket,
            "Key": source_key,
            "VersionId": source_version,
        },
        MetadataDirective="REPLACE",
        ContentType="application/octet-stream",
        ContentDisposition="attachment",
    )
    destination_version = copy.get("VersionId")
    if not destination_version or destination_version == "null":
        raise RuntimeError("approved bucket must return a version ID")
    return destination_version

The destination copy and database state update are separate operations. Acknowledge the job only after durably recording the approved destination key and version. A repeat copy can create an orphan destination version. Retry reconciliation and lifecycle rules should clean those without deleting versions in use. Guard the final database update with the upload record's active version and job attempt so a stale worker cannot repoint a replacement or resurrect a deleted upload. Keep the serving role's authorization tied to the committed record. S3 CopyObject API

Failure modes to test at the publication boundary

Scanner outage or stale signatures

Stop the scanner and simulate signature refresh failure. Confirm that downloads and previews remain inaccessible, including from a second member of the same organization. Track the age of the oldest pending upload and deployed signature age. Retry with capped exponential backoff, stop dispatching when capacity is unavailable, and alert operators before workflows silently accumulate a backlog.

Duplicate and out-of-order events

Deliver two notifications for version A, a notification for B, then an approval for A. Verify that only the accepted record changes and that a request for B cannot read A under B's identity. Kill a worker after the copy succeeds, before it commits the destination mapping. Check that a retry eventually records one authoritative destination version.

Resource exhaustion and incomplete results

Test legal near-limit files concurrently, plus too-large and unsupported inputs. Assert that spool files disappear after cancellation and that scanner pool saturation does not consume every request worker. Put a per-tenant byte or job budget on queue admission when one workspace can otherwise occupy the entire scanner pool. Label failure reasons for operators without copying file content, access URLs, or credentials into logs.

Unexpected delivery paths

Use a benign scanner test fixture to assert that a blocked path stays unreadable via the App API, CDN, and previews. Test the read-role policies directly. A passing status-screen test says little about a worker that still treats raw S3 events as permission to index a file. Gate each consumer on the release decision or have it subscribe to an event emitted only after publication.

When to choose GuardDuty, ClamAV, or a review workflow

Inline ClamAV fits small files that already cross application servers and need an immediate upload outcome. The operating cost is scanner capacity, signature maintenance, and longer request lifetimes. Quarantine with ClamAV fits direct uploads and teams that need engine control or specific verdict handling. It introduces a queue, retry state, and an explicit publication step.

GuardDuty Malware Protection for S3 fits teams that want a managed scan service and can work within its supported file coverage. AWS publishes scan status events and supports optional object tags. Treat only the approved success result as eligible, and keep UNSUPPORTED, ACCESS_DENIED, and FAILED out of the serving path. Managed scanning changes who operates the engine. The application still defines access to pending versions. How GuardDuty Malware Protection for S3 works · GuardDuty scan results

Manual review or format restrictions fit exceptional files the application cannot reliably inspect or safely render. Make those a visible product state, separate from operational retries. An unattended retry of an unsupported format does not improve coverage.

Size the system using bytes and queue age

In an illustrative benchmark scenario, four scanners process 12 MiB files in three seconds each, including transfer and scanning. At continuous utilization, that corresponds to about 16 MiB/s and 80 files per minute. This calculation uses hypothetical planning inputs. If arrivals average 120 files per minute for ten minutes during a peak, the queue grows by about 400 files during that window in the simplified model. Mixed file sizes, retries, and signature reloads can widen the spread.

Measure time from upload completion to approved publication by size band and file type. Separately record queue age, daemon wait, scan runtime, and promotion time. Decide when to tell users a scan is delayed and how long quarantine retains objects after review completes. The retention policy should account for privacy, investigations, retries, and abandoned uploads.

Frequently asked questions

Should I scan before uploading a file to S3?

Scan before the S3 write when files already pass through your application and fit a bounded synchronous flow. For direct uploads, write to a private quarantine bucket, scan the exact object version, then promote or explicitly release that version. The controlling requirement is to prevent unapproved content from reaching any serving or processing path.

Can ClamAV scan a file without storing the entire upload in memory?

Yes. The daemon's INSTREAM protocol accepts bounded chunks over a socket. A spool can retain the same bytes for the subsequent storage step, spilling to a private temporary file beyond a configured threshold. Set a hard upload limit and a concurrency budget. The scanner also has its own limits for inspecting content.

What should happen when ClamAV is unavailable?

Keep the file inaccessible until a completed scan permits publication. Inline requests can show a retryable error. Quarantined uploads can remain in a pending or delayed state while workers retry with backoff. Track signature age and oldest pending job age separately so operators can distinguish a stale scanner from a growing queue.

Does a clean ClamAV scan make a file safe to preview?

A clean verdict means the configured engine found no matching threat under its scan policy. Keep separate controls for accepted file types, parser isolation, safe download headers, and content rendering. If your application cannot safely interpret a format, offer an attachment download only after approval or disallow that format.

Further reading

Reviewing a document upload flow? Talk to Dumb Potato about designing the scan, quarantine, and download boundary.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with cloud and devops

Discuss your project