Video in progress
In Spring, what security mistakes can you make when saving a user-uploaded file to disk?
The most dangerous is path traversal: getOriginalFilename() can be ../../etc/cron.d/x. You need to generate the file name yourself, normalize() the path and check that it is inside the base directory, and limit the size and type.
📖 Answer
The buggy code:
Path target = Path.of("/data/uploads", file.getOriginalFilename());
file.transferTo(target);
The client sends the name itself. If it sends ../../app/config/application.yml, you overwrite your configuration for it.
Safer:
Path base = Path.of("/data/uploads").toAbsolutePath().normalize();
String ext = extensionOf(file.getOriginalFilename()); // allowlist: png, jpg, pdf
Path target = base.resolve(UUID.randomUUID() + "." + ext).normalize();
if (!target.startsWith(base)) {
throw new SecurityException("Noto'g'ri yo'l");
}
try (InputStream in = file.getInputStream()) {
Files.copy(in, target);
}
Other things:
- set
spring.servlet.multipart.max-file-sizeandmax-request-size, otherwise someone will fill your disk; - don't trust the
Content-Typeheader: it comes from the client too. If needed, check the first bytes (the magic number) or use Apache Tika; - don't serve the upload directory as static resources, otherwise you get XSS through
.htmlor.svg; - keep the original name in the DB, and use a UUID name on disk.
Sign up to mark studied questions and save your progress.