← Java / Spring · Contents

JAVA-033 / Beginner

File uploads: checking only extension and Content-Type

A04:2021 Insecure Design · CWE-434 Unrestricted Upload of File with Dangerous Type

Why is this a problem?

Headers can be forged, and .jsp.jpg can bypass checks.

How to fix it

java
String ext = allowedExt(file);          // Allowlisted extension
Path target = dir.resolve(UUID.randomUUID() + "." + ext).normalize();
// Check magic bytes and disable execution in the storage directory

Further reading