From bfb3d42396727614aef625143b4381e64142f9bb Mon Sep 17 00:00:00 2001 From: Mark Saroufim Date: Fri, 29 Sep 2023 16:46:40 -0700 Subject: [PATCH] fix zip slip error (#2634) --- .../pytorch/serve/archive/utils/ZipUtils.java | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/frontend/archive/src/main/java/org/pytorch/serve/archive/utils/ZipUtils.java b/frontend/archive/src/main/java/org/pytorch/serve/archive/utils/ZipUtils.java index c27eae64b1..62e625f73c 100644 --- a/frontend/archive/src/main/java/org/pytorch/serve/archive/utils/ZipUtils.java +++ b/frontend/archive/src/main/java/org/pytorch/serve/archive/utils/ZipUtils.java @@ -28,8 +28,15 @@ public static void unzip(InputStream is, File dest) throws IOException { try (ZipInputStream zis = new ZipInputStream(is)) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { - String name = entry.getName(); - File file = new File(dest, name); + File file = new File(dest, entry.getName()); + File canonicalDestDir = dest.getCanonicalFile(); + File canonicalFile = file.getCanonicalFile(); + + // Check for Zip Slip vulnerability + if (!canonicalFile.getPath().startsWith(canonicalDestDir.getPath())) { + throw new IOException("Detected Zip Slip vulnerability: " + entry.getName()); + } + if (entry.isDirectory()) { FileUtils.forceMkdir(file); } else { @@ -108,6 +115,14 @@ public static void decompressTarGzipFile(InputStream is, File dest) throws IOExc while ((entry = tis.getNextEntry()) != null) { String name = entry.getName().substring(entry.getName().indexOf('/') + 1); File file = new File(dest, name); + File canonicalDestDir = dest.getCanonicalFile(); + File canonicalFile = file.getCanonicalFile(); + + // Check for Zip Slip vulnerability + if (!canonicalFile.getPath().startsWith(canonicalDestDir.getPath())) { + throw new IOException("Detected Zip Slip vulnerability: " + entry.getName()); + } + if (entry.isDirectory()) { FileUtils.forceMkdir(file); } else {