Skip to content

Commit

Permalink
Fixes tarslip issue (#3075)
Browse files Browse the repository at this point in the history
  • Loading branch information
tosterberg committed May 8, 2024
1 parent 32859b7 commit 76598f9
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 2 deletions.
2 changes: 1 addition & 1 deletion api/src/main/java/ai/djl/util/TarUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public static void untar(InputStream is, Path dir, boolean gzip) throws IOExcept
try (TarArchiveInputStream tis = new TarArchiveInputStream(bis)) {
TarArchiveEntry entry;
while ((entry = tis.getNextEntry()) != null) {
String entryName = entry.getName();
String entryName = ZipUtils.removeLeadingFileSeparator(entry.getName());
if (entryName.contains("..")) {
throw new IOException("Malicious zip entry: " + entryName);
}
Expand Down
12 changes: 11 additions & 1 deletion api/src/main/java/ai/djl/util/ZipUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public static void unzip(InputStream is, Path dest) throws IOException {
ZipEntry entry;
Set<String> set = new HashSet<>();
while ((entry = zis.getNextEntry()) != null) {
String name = entry.getName();
String name = removeLeadingFileSeparator(entry.getName());
if (name.contains("..")) {
throw new IOException("Malicious zip entry: " + name);
}
Expand Down Expand Up @@ -121,6 +121,16 @@ private static void addToZip(Path root, Path file, ZipOutputStream zos) throws I
}
}

static String removeLeadingFileSeparator(String name) {
int index = 0;
for (; index < name.length(); index++) {
if (name.charAt(index) != File.separatorChar) {
break;
}
}
return name.substring(index);
}

private static final class ValidationInputStream extends FilterInputStream {

private static final int ZIP64_LOCSIG = 0x07064b50; // "PK\006\007"
Expand Down
13 changes: 13 additions & 0 deletions api/src/test/java/ai/djl/util/ZipUtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,19 @@ public void testEmptyZipFile() throws IOException {
}
}

@Test
public void testOffendingTar() throws IOException {
Path path = Paths.get("src/test/resources/offending.tar");
Path output = Paths.get("build/output");
Path file = output.resolve("tmp/empty.txt");
Utils.deleteQuietly(file);
Files.createDirectories(output);
try (InputStream is = Files.newInputStream(path)) {
TarUtils.untar(is, output, false);
}
Assert.assertTrue(Files.exists(file));
}

@Test
public void testInvalidZipFile() throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Expand Down
Binary file added api/src/test/resources/offending.tar
Binary file not shown.

0 comments on commit 76598f9

Please sign in to comment.