Skip to content

Commit 2ac03eb

Browse files
authored
Merge pull request eugenp#5524 from eugenp/Issue-5497
UnzipFile is vulnerable to Zip Slip eugenp#5497
2 parents 9289bf8 + 917c643 commit 2ac03eb

2 files changed

Lines changed: 19 additions & 3 deletions

File tree

‎core-java-io/src/main/java/com/baeldung/unzip/UnzipFile.java‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@
99

1010
public class UnzipFile {
1111
public static void main(final String[] args) throws IOException {
12-
final String fileZip = "src/main/resources/compressed.zip";
12+
final String fileZip = "src/main/resources/unzipTest/compressed.zip";
13+
final File destDir = new File("src/main/resources/unzipTest");
1314
final byte[] buffer = new byte[1024];
1415
final ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
1516
ZipEntry zipEntry = zis.getNextEntry();
1617
while (zipEntry != null) {
17-
final String fileName = zipEntry.getName();
18-
final File newFile = new File("src/main/resources/unzipTest/" + fileName);
18+
final File newFile = newFile(destDir, zipEntry);
1919
final FileOutputStream fos = new FileOutputStream(newFile);
2020
int len;
2121
while ((len = zis.read(buffer)) > 0) {
@@ -27,4 +27,20 @@ public static void main(final String[] args) throws IOException {
2727
zis.closeEntry();
2828
zis.close();
2929
}
30+
31+
/**
32+
* @see https://snyk.io/research/zip-slip-vulnerability
33+
*/
34+
public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
35+
File destFile = new File(destinationDir, zipEntry.getName());
36+
37+
String destDirPath = destinationDir.getCanonicalPath();
38+
String destFilePath = destFile.getCanonicalPath();
39+
40+
if (!destFilePath.startsWith(destDirPath + File.separator)) {
41+
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
42+
}
43+
44+
return destFile;
45+
}
3046
}
256 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)