I'm having issues with CWE-73 regarding parentDir reaching the unzip method.
This class is responsible for unzipping the file and returning the address/name of the file in a temporary folder. I've researched a lot about validations, but no version is accepted in the Veracode Scan. Could you help me?
The vulnerability CWE-73 is pointed out in the line
Path entryPath = parentDir.resolve(entryName).toAbsolutePath().normalize();
Method that calls the class that will unzip the file:
private String criaEdescompactaArquivo(String fileName, byte[] report) throws IOException {
String extractedFileName;
var decodedFile = new DecodedMultipartFile(report, fileName);
var file = Files.createTempFile(fileName, ".zip");
decodedFile.transferTo(file);
extractedFileName = UnzipFileHelper.unzip(file.toFile());
return extractedFileName;
}
Class that will unzip the file and return the address/name of the file in the temporary folder:
import java.io.*;
import java.nio.file.*;
import java.util.Objects;
import java.util.zip.;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class UnzipFileHelper {
private UnzipFileHelper() {
throw new IllegalStateException("Utility class");
}
public static String unzip(File file) throws IOException {
return unzip(file, file.getParentFile().toPath());
}
private static String unzip(File file, Path parentDir) throws IOException {
if (!Files.isDirectory(parentDir)) {
throw new SecurityException("Parent directory is not valid");
}
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(file))) {
ZipEntry zipEntry = zis.getNextEntry();
if (Objects.isNull(zipEntry)) {
return null;
}
String entryName = zipEntry.getName();
if (entryName.contains("..") || entryName.contains(File.separator)) {
throw new SecurityException("Invalid file name");
}
Path entryPath = parentDir.resolve(entryName).toAbsolutePath().normalize();
log.info("Unzip: entryPath = {}", entryPath);
if (!entryPath.startsWith(parentDir)) {
throw new SecurityException("Invalid file path");
}
final long MAX_FILE_SIZE = (long) 100 * 1_024 * 1_024;
if (zipEntry.getSize() > MAX_FILE_SIZE) {
throw new SecurityException("File size exceeds maximum allowed");
}
Files.createDirectories(entryPath.getParent());
try (OutputStream fos = Files.newOutputStream(entryPath)) {
final byte[] buf = new byte[1024];
int length;
while ((length = zis.read(buf, 0, buf.length)) >= 0) {
fos.write(buf, 0, length);
}
}
zis.closeEntry();
return entryPath.toString();
}
}
}
Changes needed to mitigate this vulnerability.