Unrestricted upload of dangerous file types

Restrict uploaded file types, storage and processing

Description

What happens to an upload depends on where it is stored and how the server or browser processes it. A file accepted as data may later be interpreted as code.

Potential impact

A server that handles an upload as a JSP, ASP or PHP script may run its code. An interpreter can read and run a file even when the file has no execute permission.

Remediation

  1. Generate the storage name on the server. Check the size and actual format independently of the submitted filename and MIME type.
  2. Store uploads outside the web root and restrict writes. Configure the web server and later handlers to treat uploads as data. Keep the directory search permissions needed to access files.
  3. Compare normalized path components to confirm the destination is inside the upload root. Create new files atomically.
  4. Scan for malware and use an isolated environment for further processing.

Examples

Before

java
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
    // Save using the client-supplied filename
    String fileName = file.getOriginalFilename();
    File destinationFile = new File("/uploads/" + fileName);
    file.transferTo(destinationFile);
    return "uploadSuccess";
}

After

This excerpt requires Java 11 or later. Create the upload directory and let the application write files there. Prevent untrusted users from changing the directory or its parents to redirect writes. Set a multipart request limit in Spring. Keep stored text out of code execution and direct HTML rendering.

java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.UUID;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public final class SafeUploadController {
    private static final Path UPLOAD_ROOT =
            Path.of("/var/lib/myapp/uploads").toAbsolutePath().normalize();
    private static final long MAX_TEXT_SIZE = 1024 * 1024;

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty() || file.getSize() > MAX_TEXT_SIZE) {
            throw new IOException("Invalid file size");
        }

        byte[] content = file.getBytes();
        String text;
        try {
            text = StandardCharsets.UTF_8.newDecoder()
                    .onMalformedInput(CodingErrorAction.REPORT)
                    .onUnmappableCharacter(CodingErrorAction.REPORT)
                    .decode(ByteBuffer.wrap(content))
                    .toString();
        } catch (CharacterCodingException e) {
            throw new IOException("The upload is not valid UTF-8 text", e);
        }
        if (text.codePoints().anyMatch(c -> c == 0
                || (Character.isISOControl(c) && c != '\n' && c != '\r' && c != '\t'))) {
            throw new IOException("Invalid text content");
        }

        String storedName = UUID.randomUUID() + ".txt";
        Path target = UPLOAD_ROOT.resolve(storedName).normalize();
        if (!target.startsWith(UPLOAD_ROOT)) {
            throw new IOException("Invalid upload destination");
        }

        // Precreate UPLOAD_ROOT outside the web root and prevent execution of uploaded code.
        Files.write(target, content, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
        return "uploadSuccess";
    }
}

The revised handler accepts nonempty UTF-8 text up to 1 MiB and rejects disallowed control characters. It checks the destination and uses CREATE_NEW to create a UUID-based .txt file. Malware scanning is a separate step.

Related CVEs

References