From 72beec83d32e3e75cc29dc0efb3c1344ec238400 Mon Sep 17 00:00:00 2001 From: Jonathan Leitschuh Date: Fri, 29 Jul 2022 19:17:15 +0000 Subject: [PATCH] vuln-fix: Zip Slip Vulnerability This fixes a Zip-Slip vulnerability. This change does one of two things. This change either 1. Inserts a guard to protect against Zip Slip. OR 2. Replaces `dir.getCanonicalPath().startsWith(parent.getCanonicalPath())`, which is vulnerable to partial path traversal attacks, with the more secure `dir.getCanonicalFile().toPath().startsWith(parent.getCanonicalFile().toPath())`. For number 2, consider `"/usr/outnot".startsWith("/usr/out")`. The check is bypassed although `/outnot` is not under the `/out` directory. It's important to understand that the terminating slash may be removed when using various `String` representations of the `File` object. For example, on Linux, `println(new File("/var"))` will print `/var`, but `println(new File("/var", "/")` will print `/var/`; however, `println(new File("/var", "/").getCanonicalPath())` will print `/var`. Weakness: CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') Severity: High CVSSS: 7.4 Detection: CodeQL (https://codeql.github.com/codeql-query-help/java/java-zipslip/) & OpenRewrite (https://public.moderne.io/recipes/org.openrewrite.java.security.ZipSlip) Reported-by: Jonathan Leitschuh Signed-off-by: Jonathan Leitschuh Bug-tracker: https://github.com/JLLeitschuh/security-research/issues/16 Co-authored-by: Moderne --- .../java/cn/springmvc/mybatis/common/utils/ZipUtil.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/cn/springmvc/mybatis/common/utils/ZipUtil.java b/src/main/java/cn/springmvc/mybatis/common/utils/ZipUtil.java index 3bf47a3..78fbe43 100644 --- a/src/main/java/cn/springmvc/mybatis/common/utils/ZipUtil.java +++ b/src/main/java/cn/springmvc/mybatis/common/utils/ZipUtil.java @@ -33,7 +33,7 @@ public static boolean compress(List files, String zipPath, boolean isDel) } try { // ----压缩文件: - FileOutputStream stream = new FileOutputStream(zipPath); + FileOutputStream stream = new FileOutputStream(new File(zipPath)); CheckedOutputStream checkedStream = new CheckedOutputStream(stream, new CRC32());// 使用指定校验和创建输出流 ZipOutputStream zipStream = new ZipOutputStream(checkedStream); BufferedOutputStream out = new BufferedOutputStream(zipStream); @@ -98,7 +98,11 @@ public static void unZipFiles(File zipfile, String descDir) { entry = ((ZipEntry) entries.nextElement()); zipEntryName = entry.getName(); in = zf.getInputStream(entry); - out = new FileOutputStream(descDir + zipEntryName); + final File zipEntryFile = new File(descDir, zipEntryName); + if (!zipEntryFile.toPath().normalize().startsWith(descDir)) { + throw new RuntimeException("Bad zip entry"); + } + out = new FileOutputStream(zipEntryFile); buf1 = new byte[1024]; len = 0; while ((len = in.read(buf1)) > 0) {