How can you validate whether a file is safe before uploading or reading it?
How can you validate whether a file is safe before uploading or reading it?
Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
Anubhav Kumar
22-May-2025Validating whether a file is safe before uploading or reading is essential to prevent security risks such as malware, viruses, or malicious code injection. Below are best practices and techniques for validating file safety:
1. Validate File Type (MIME Type and Extension)
Check File Extension
Ensure only allowed extensions (e.g.,
.jpg
,.pdf
,.docx
, etc.):Check MIME Type (Content-Type)
Don't trust
file.ContentType
from the browser. Instead, inspect the file's content (see below).2. Inspect File Content (Magic Bytes/Signature)
Use magic numbers to verify the file type:
Refer to file signature databases like Gary Kessler's File Signatures Table.
3. Limit File Size
Set a max file size limit (e.g., 5MB):
Also configure server-side limits in settings (e.g., in ASP.NET Core:
RequestSizeLimit
orMaxRequestBodySize
).4. Scan for Malware
Use antivirus APIs or malware scanners before accepting the file:
MpCmdRun.exe -Scan
)Example (with VirusTotal API):
5. Rename Files to Avoid Path Injection
Never trust client filenames. Sanitize and/or replace with GUID:
6. Store Outside Web Root
Never store uploaded files in a public web directory. This prevents accidental execution or download.
Store files in a secured directory like
/app_data/uploads
.7. Avoid Inline Execution
Do not allow direct rendering of uploaded files (e.g., don't return HTML/JS from user-uploaded files).
Set the correct content-disposition headers:
Summary Checklist