Link Search Menu Expand Document

Unrestricted File Upload in Java

Vulnerable example

In the example below, the filename is user controlled. It could be possible to store the file in a different location from the one intended by the application. The logic does not perform checks on the file type, thus allowing any type of file to be uploaded.

public class UploadAction extends ActionSupport {
    private File uploadedFile;
    // setter and getter for uploadedFile

    public String execute() {
        try {
            File fileToCreate = new File(filepath + File.separator +filename);
            // Copy temporary file content to this file
            FileUtils.copyFile(uploadedFile, fileToCreate);
            return "SUCCESS";
        } catch (Throwable e) {
            addActionError(e.getMessage());
            return "ERROR";
        }
    }
}

Prevention

Restrict the upload to specific file types by implementing an allow list on the file extension.

if (!validExtensions.contains(getFileExtension(fileName))) {
    writer.println("Invalid Extension");
    writer.close();
    return;
}

private String getFileExtension(String fileName) {
    String extension = "";
    int i = fileName.lastIndexOf('.');
    if (i > 0) {
        extension = fileName.substring(i + 1);
    }
    return extension;
}

Ensure the user cannot manipulate the upload path, for example use java.io.File.getName() to obtain the file name, i.e., without additional path elements, and use this value to build the path. For example new File("../../../../file.ext").getName() yields file.ext.

Implement a check based on the file contents, and also ensure all uploaded files are scanned with an antivirus solution.

References

SEI CERT - Oracle Coding Standard for Java OWASP - FileUpload