Beginner LevelWeb Security & Cyber Defense
What security checks are mandatory when accepting User File Uploads?
❓ Interview Prompt: Explain file upload security, magic byte validation, storage outside web root (S3), random filenames, and non-executable directories.
Allowing users to upload files without strict validation exposes servers to Remote Code Execution (RCE):
Mandatory Security Checklist:
1
Magic Byte Validation: Validate true file types using file magic headers ('FF D8 FF' for JPEG), never relying on client 'Content-Type' headers or file extensions.
2
Store Outside Web Root: Store uploaded files in an S3 bucket or non-executable server directory.
3
Randomize Filenames: Generate a UUID filename ('uuid.v4() + '.jpg'') to prevent path traversal.
4
Re-encode Media: Re-process images using Sharp/ImageMagick to strip malicious embedded polyglot scripts.
Code Implementation Example
typescript
import fileType from 'file-type';
import { v4 as uuidv4 } from 'uuid';
export async function validateAndSaveUpload(buffer: Buffer) {
const type = await fileType.fromBuffer(buffer);
// 1. Verify true magic bytes (Must be allowed image type)
if (!type || !['image/jpeg', 'image/png'].includes(type.mime)) {
throw new Error('Invalid file format');
}
// 2. Generate safe randomized UUID filename
const safeFilename = '${uuidv4()}.${type.ext}';
await s3.upload({ Bucket: 'uploads', Key: safeFilename, Body: buffer });
}💡Validating file magic bytes and saving to S3 with a randomized UUID filename.
🎯 Interview Key Takeaway
Validate file magic bytes, generate randomized UUID filenames, and store uploads outside the web root to prevent RCE.
#File Uploads#Magic Bytes#RCE#Beginner
Back to all Web Security & Cyber Defense Questions→