Web Security & OWASP (50 Qs)•Part 5: API Security, DevSecOps & Enterprise Incident Handling (43 - 50)
Secure File Upload Architecture: Extension spoofing, MIME validation, magic bytes, and S3 sandboxing.
Why File Uploads are High Risk
Allowing users to upload files is one of the most hazardous capabilities in web applications. Attackers upload Web Shells (e.g., shell.php, backdoor.jsp) and execute them directly on the web server.
sql
+-------------------------------------------------------------------------------+
| Defensive File Upload Pipeline Blueprint |
| |
| 1. File Name Sanitization -> Discard user filename! Generate random UUIDv4|
| 2. Double Extension Defense -> Strip "avatar.php.jpg" tricks |
| 3. Magic Byte Inspection -> Check initial bytes (e.g., ÿØÿ for JPEG) |
| 4. Anti-Virus Scanning -> Stream through ClamAV scanner container |
| 5. Isolated Object Storage -> Upload to S3 with private ACL |
| 6. Safe Content Serving -> Serve via CloudFront with Content-Disposition|
| `attachment` and nosniff headers! |
+-------------------------------------------------------------------------------+
Magic Byte Validation (Never Trust File Extensions!)
Attackers easily rename a PHP script to image.jpg. Validate the file signature (magic bytes):
typescript
import { fileTypeFromBuffer } from 'file-type';
async function validateUploadedImage(buffer: Buffer) {
// Reads the actual binary signature from file header
const type = await fileTypeFromBuffer(buffer);
const ALLOWED_MIMES = ['image/jpeg', 'image/png', 'image/webp'];
if (!type || !ALLOWED_MIMES.includes(type.mime)) {
throw new BadRequestException('Invalid file type! Fake image detected.');
}
return type;
}