← Back to Baseline

Why it Matters

File uploads are a common target for attackers. If an upload form accepts any file type without checks, attackers may upload a PHP shell disguised as an image. Once uploaded, they can execute commands, steal data, or take over the entire server.

Secure upload handling means validating MIME type, checking extensions, limiting file size, and storing files outside the webroot. Randomizing file names and re-encoding images add more protection. With these controls, uploaded files cannot be used as an entry point for attacks.

Verification Steps

Manual

# Review custom upload handlers
grep -R "move_uploaded_file" app/code

# Check if:
# - MIME type is validated
# - File extension is validated
# - File size is limited
# - Storage is outside pub/ when possible

Remediation / Fix Guidance

  1. Validate both MIME type and file extension against a whitelist (e.g., jpg, png, pdf).
  2. Set file size limits to avoid DoS via large uploads.
  3. Store uploads outside pub/ or use generated random names to prevent direct access.
  4. For images, re-encode with a safe library (e.g., GD or Imagick) before saving.
  5. Disable execution permission on upload folders.

Examples

Fail Example
// Unsafe: saves file with original name in pub/
move_uploaded_file($_FILES['file']['tmp_name'], 'pub/uploads/' . $_FILES['file']['name']);
Pass Example
// Safe: validates type and renames
$allowed = ['image/jpeg','image/png'];
$type = mime_content_type($_FILES['file']['tmp_name']);

if (in_array($type, $allowed, true)) {
    $newName = bin2hex(random_bytes(8)) . '.jpg';
    move_uploaded_file($_FILES['file']['tmp_name'], '/var/uploads/' . $newName);
} else {
    throw new Exception("Invalid file type");
}

References