Sub topic 8
Scanning and quarantining untrusted files
This chapter assumes you know how presigned uploads work, how to validate size and type, and the basics of an event-driven pipeline. It covers what happens between "the bytes landed in storage" and "the file is allowed to be used by anyone else."
Why validation is not enough
Earlier validation checks the size, the declared type, and the first bytes of a file. Those checks are cheap and worth doing. They do not tell you whether the file is safe.
A file can have a correct PNG signature and still contain a malicious payload after the header. A PDF can contain scripts. An Office document can contain macros. An archive can expand to thousands of times its size. A malware scanner looks for known bad patterns inside the whole file, which signature checks never do.
Treat every uploaded file as untrusted until a scan marks it clean. The word for this state is quarantine: the file exists in storage, but nothing is allowed to read it except the scanner.
The quarantine pattern
The idea is to separate where files arrive from where files are served. You use two locations, typically two buckets, and a file moves from the first to the second only after it passes the scan.
| Location | Who can write | Who can read | Purpose |
|---|---|---|---|
| Quarantine bucket | Clients (through presigned URLs) | The scanner only | Holds files that have not been checked |
| Clean bucket | The pipeline only | The CDN and your application | Holds files that passed the scan |
| Rejected prefix or bucket | The pipeline only | Security staff only | Holds infected files for review, then deletes them |
Using separate buckets is safer than using a flag on one object, because the access policy enforces the rule. If the CDN has no permission on the quarantine bucket, a bug in your application cannot accidentally serve an unscanned file.
The upload flow changes in one place. The presigned POST policy from the earlier chapters points at the quarantine bucket, not the public one.
import boto3
s3 = boto3.client("s3")
post = s3.generate_presigned_post(
Bucket="example-quarantine",
Key="incoming/3f2a9c/avatar.jpg",
Fields={"Content-Type": "image/jpeg"},
Conditions=[
{"Content-Type": "image/jpeg"},
["content-length-range", 1, 5 * 1024 * 1024],
],
ExpiresIn=300,
)The scan workflow
The scan runs asynchronously, driven by the storage event that announces a new object. The client never waits for it inside the upload request.
- The client uploads to the quarantine bucket.
- Storage emits an "object created" event.
- A worker receives the event and downloads the object (or streams it) to a scanner.
- The scanner returns a verdict: clean, infected, or error.
- On clean, the worker copies the object to the clean bucket and updates the database record.
- On infected, the worker moves the object to the rejected location, updates the record, and notifies the user or your logs.
- On error, the worker retries, and eventually sends the message to a dead-letter queue.
Tracking state in the database
The database record for the upload needs an explicit state, so the rest of your application knows what it may do with the file. A small state machine is enough.
Your API should refuse to return a delivery URL for any record that is not in the available state. This check is the second line of defense after the bucket permissions.
A scan worker example
The example below uses ClamAV, a widely used open-source scanner, through its clamd daemon. It streams the object to the daemon instead of loading it fully into memory. The worker assumes a running clamd reachable at the host and port shown, and the clamd Python package installed.
import boto3
import clamd
s3 = boto3.client("s3")
scanner = clamd.ClamdNetworkSocket(host="clamav.internal", port=3310)
QUARANTINE = "example-quarantine"
CLEAN = "example-clean"
REJECTED = "example-rejected"
def scan_object(key: str) -> str:
body = s3.get_object(Bucket=QUARANTINE, Key=key)["Body"]
result = scanner.instream(body)
status, detail = result["stream"]
if status == "OK":
s3.copy_object(
Bucket=CLEAN,
Key=key,
CopySource={"Bucket": QUARANTINE, "Key": key},
)
s3.delete_object(Bucket=QUARANTINE, Key=key)
return "available"
if status == "FOUND":
s3.copy_object(
Bucket=REJECTED,
Key=key,
CopySource={"Bucket": QUARANTINE, "Key": key},
)
s3.delete_object(Bucket=QUARANTINE, Key=key)
print(f"infected: {key} ({detail})")
return "rejected"
raise RuntimeError(f"scan error for {key}: {detail}")Raising on an error status matters. If the worker returned "available" on a failed scan, an outage in the scanner would let unscanned files through. The rule is to fail closed: when the verdict is unknown, the file stays in quarantine.
Edge cases and failure modes
- Duplicate events. Storage events are delivered at least once. Make the worker idempotent. If the object is already gone from quarantine, check the record state and exit without error.
- Large files. Scanners have size limits, often set by the daemon's
StreamMaxLengthoption. A file larger than the limit may be partly scanned or rejected. Decide in advance what happens: reject the upload, or use a scanner that supports larger objects. - Archives. A zip bomb is a small archive that expands to an enormous size. Configure the scanner with limits on recursion depth, total extracted size, and file count, and treat a limit hit as a failure, not a pass.
- Stale signatures. Scanners rely on a database of known threats. Update it regularly, and alert when the database is older than a day or two. A scanner with old definitions gives false confidence.
- Time-of-check to time-of-use. If the same key can be overwritten after the scan, the clean copy may differ from what was scanned. Copy the scanned version by its version ID, or use unique keys per upload and never allow overwrites.
- Scanner cost and throughput. Scanning is CPU-heavy. Put events on a queue and scale workers with queue depth, so a burst of uploads delays scans instead of dropping them.
- User experience. Scanning adds seconds or minutes. Show the user an "processing" state, and do not display the file until the record is
available.
Managed options
You do not have to run your own scanner. Cloud providers and vendors offer services that watch a bucket and tag objects with a verdict, for example Amazon GuardDuty Malware Protection for S3. These reduce operations work. The trade-offs are cost per gigabyte, less control over archive limits, and a verdict that arrives as a tag or event that your pipeline must still act on. The quarantine and state-tracking design in this chapter is the same either way.
Exercise
Your team keeps uploads in a single bucket and sets a database flag scanned = false until the scanner finishes. A teammate points out that a bug in the image-serving code could still expose unscanned files. What change removes that risk, and what should the API do for records that are not yet scanned?
Show answer
Move incoming files to a separate quarantine bucket that the CDN and the serving code have no permission to read, and let only the scan worker copy clean files into the bucket that the CDN serves. The permissions then enforce the rule even if the application code has a bug. The API should also return no delivery URL for any record whose state is not available, and the UI should show a "processing" state.
Exercise
The scan worker catches an exception when the scanner daemon is unreachable and marks the file available so users are not blocked. Why is this a mistake, and what should happen instead?
Show answer
It fails open, so any outage of the scanner lets unscanned files through, and an attacker could time an upload for such a moment. The worker should fail closed: leave the file in quarantine, retry with backoff, and send the message to a dead-letter queue after repeated failures so someone can investigate.