Skip to content

Commit 2d4608d

Browse files
committed
update security fix for unzip process
1 parent edb628a commit 2d4608d

2 files changed

Lines changed: 23 additions & 2 deletions

File tree

rlib-io/src/main/java/javasabr/rlib/io/util/FileUtils.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -407,20 +407,22 @@ public static int unzip(Path destination, Path zipFile) {
407407
if (!Files.exists(destination)) {
408408
throw new IllegalArgumentException("The folder " + destination + " doesn't exist.");
409409
}
410+
Path normalizedDestination = destination.normalize();
410411
int count = 0;
411412
try (var zin = new ZipInputStream(Files.newInputStream(zipFile))) {
412413
for (var entry = zin.getNextEntry(); entry != null; entry = zin.getNextEntry()) {
413414
String entryName = entry.getName();
414415
Path targetFile = destination
415416
.resolve(entryName)
416417
.normalize();
417-
if (!targetFile.startsWith(destination)) {
418+
if (!targetFile.startsWith(normalizedDestination)) {
418419
LOGGER.warning(entryName, "Unexpected entry name:[%s] which is outside"::formatted);
419420
continue;
420421
}
421422
if (entry.isDirectory()) {
422423
Files.createDirectories(targetFile);
423424
} else {
425+
Files.createDirectories(targetFile.getParent());
424426
Files.copy(zin, targetFile, StandardCopyOption.REPLACE_EXISTING);
425427
count++;
426428
}

rlib-io/src/test/java/javasabr/rlib/io/FileUtilsTest.java

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,12 +111,31 @@ void shouldUnzipFileCorrectly() throws IOException {
111111
zout.write("test text 5".getBytes(StandardCharsets.UTF_8));
112112
}
113113

114-
Path outputDir = Files.createTempDirectory("test-unzip");
114+
Path tempDirectory = Files.createTempDirectory("test-unzip");
115+
Path outputDir = tempDirectory
116+
.resolve("output")
117+
.resolve("folder");
118+
119+
Files.createDirectories(outputDir);
115120

116121
// when:
117122
int unpackedFiles = FileUtils.unzip(outputDir, zipFile);
118123

119124
// then:
120125
assertThat(unpackedFiles).isEqualTo(3);
126+
assertThat(outputDir
127+
.resolve("fileA.txt"))
128+
.exists();
129+
assertThat(outputDir
130+
.resolve("dir_a")
131+
.resolve("fileC.txt"))
132+
.exists();
133+
assertThat(tempDirectory
134+
.resolve("output")
135+
.resolve("fileB.txt"))
136+
.doesNotExist();
137+
assertThat(tempDirectory
138+
.resolve("fileE.txt"))
139+
.doesNotExist();
121140
}
122141
}

0 commit comments

Comments
 (0)