DEV Community

丁久
丁久

Posted on • Originally published at dingjiu1989-hue.github.io

Secure File Upload Implementation

This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.

Secure File Upload Implementation

Secure File Upload Implementation

Secure File Upload Implementation

Secure File Upload Implementation

Secure File Upload Implementation

Secure File Upload Implementation

Secure File Upload Implementation

Secure File Upload Implementation

Secure File Upload Implementation

Secure File Upload Implementation

The Risk of File Uploads

File upload functionality is one of the most dangerous features an application can expose. An unrestricted file upload can lead to remote code execution, malware distribution, data breaches, and server compromise. Every file upload endpoint must be treated as a critical attack surface.

Threat Model

| Attack | Description | |--------|-------------| | Malicious file upload | Attacker uploads a PHP shell or executable | | File size DoS | Huge files exhaust disk space or memory | | Path traversal | Filename manipulates directory traversal | | MIME type spoofing | File extension does not match content | | Malware distribution | Legitimate-looking files containing malware | | Zip bombs | Compressed archive that expands to enormous size | | SSRF via file processing | Server-side parsing of attacker-controlled files |

Validation Strategy

1\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\. Validate File Extension

Allowlist-based validation is essential. Blocklisting (e.g., rejecting .exe files) will always miss edge cases.

ALLOWED_EXTENSIONS = {

Images

'.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg',

Documents

'.pdf', '.doc', '.docx', '.xls', '.xlsx',

Other

'.txt', '.csv'

}

def validate_extension(filename):

ext = os.path.splitext(filename)[1].lower()

if ext not in ALLOWED_EXTENSIONS:

raise ValueError(f"Extension {ext} not allowed")

2\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\. Validate MIME Type

Never trust the Content-Type header from the client. Inspect the actual file content:

import magic

def validate_mime(file_stream):

mime = magic.from_buffer(file_stream.read(2048), mime=True)

file_stream.seek(0)


Read the full article on AI Study Room for complete code examples, comparison tables, and related resources.

Found this useful? Check out more developer guides and tool comparisons on AI Study Room.

Top comments (0)