How do you validate an uploaded file's actual content type (not just its client-supplied extension or Content-Type header) to prevent malicious file uploads?
Short answer
Since a client can freely lie about a file's Content-Type header or rename a file's extension, robust validation inspects the file's actual binary signature (magic bytes/file header) rather than trusting client-supplied metadata -- libraries like FileSignatures or manual…
Advertisement
AModel answer
Since a client can freely lie about a file's Content-Type header or rename a file's extension, robust validation inspects the file's actual binary signature (magic bytes/file header) rather than trusting client-supplied metadata -- libraries like FileSignatures or manual magic-byte checking verify a file genuinely is what it claims to be before accepting it, an important defense against uploading disguised executable or script content.
public bool IsValidImageFile(Stream stream) {
var buffer = new byte[8];
stream.Read(buffer, 0, 8);
stream.Position = 0; // reset for later reading
// PNG magic bytes: 89 50 4E 47 0D 0A 1A 0A
return buffer[0] == 0x89 && buffer[1] == 0x50 && buffer[2] == 0x4E && buffer[3] == 0x47;
}Real-world example
A user profile picture upload feature rejects a malicious file disguised with a .jpg extension and image/jpeg Content-Type header but actually containing executable script content, caught by inspecting the file's genuine magic bytes rather than trusting client-supplied metadata.
Likely follow-ups
- What other security risks exist for file uploads beyond content type spoofing (path traversal, oversized files)?
- How would you scan uploaded files for malware as an additional layer of defense?
Related topics