安全读取 java 中的文件

Securely read a file in java

我正在使用 IBM AppScan 扫描我的代码,在一种方法中,我正在传递由 UploadedFile 类型的用户上传的文件,并使用以下代码将其读取到字节数组。但是扫描给出了 "Vulnerability Type - Validation.Required" 错误。在 运行 这段代码之前,我正在验证文件扩展名并 null 检查文件。

验证检查:

if (file != null && !file.getFileName().isEmpty()) {
     // Checking file extension here. Like jpg,png etc.
}

如果有帮助,它属于 CWE 20 类别。 https://cwe.mitre.org/data/definitions/20.html

private int fileUpload(UploadedFile file) { // import org.primefaces.model.UploadedFile;
        try {
            String fileName = file.getFileName();
            int fileSize = (int) file.getSize();
            String fileType = new Validator().fetchFileExtension(fileName);
            byte[] filebytea = new byte[fileSize];
            try {
                FileInputStream fileStream = (FileInputStream) file.getInputstream();
                fileStream.read(filebytea); // Error: Vulnerability Type Validation.Required
            } catch (Exception e) {
                //System.out.println("error in file stream" + e.getMessage());
            }

不要使用 FileInputStream 或 FileOutputStream。它们被认为是有害的。在某些情况下,rhey 会导致您在生产中不希望出现的 GC 问题。

参见this解释。 SonarQube 通常也会显示此问题。

你应该使用:

Files.newInputStream(..)
Files.newOutputStream(..) 

您拨打 read 的电话就是问题所在。它可以但不必完全读取数据。因此,您必须检查 read 的 return 值并多次调用它。如果你不想自己实现这个,你可以使用 DataInputStream.readFully() 或者 fileStream.readAllBytes() (后者需要 Java 9+)。

以下代码应该不会引起任何问题,并且适用于 Java 7+:

    try (DataInputStream in = new DataInputStream(file.getInputstream())) {
        in.readFully(filebytea); 
    } catch (Exception e) {
        //System.out.println("error in file stream" + e.getMessage());
    }