Make sure to read this post before raising a thread here:
Then tell us:
- What language is this for?
- Java
- Which rule?
- javasecurity:S6096
- Why do you believe it’s a false-positive?
- It is prevented by checking normalized path with targetDirectory path as described here
- Are you using
- SonarQube - Enterprise Edition Version 10.2 (build 77647)
- How can we reproduce the problem?
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Example {
private static final String targetDirectory = "/example/directory/";
public void extractEntry(ZipFile zipFile) throws IOException {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String name = entry.getName();
String dest = targetDirectory + name;
if (!Path.of(dest).normalize().startsWith(Path.of(targetDirectory).normalize())) {
throw new IOException("Entry is outside of the target dir.");
}
try (InputStream zis = zipFile.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(dest)) {
byte[] readBuffer = new byte[4096];
int bytesIn;
while ((bytesIn = zis.read(readBuffer)) != -1) {
fos.write(readBuffer, 0, bytesIn);
}
fos.flush();
}
}
}
}