From 311bb39d65260690eac691cd1dcc37a0f66ee030 Mon Sep 17 00:00:00 2001 From: Jonathan Leitschuh Date: Fri, 29 Jul 2022 19:15:39 +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 --- .../apktool/apkinfo/manifestextractor/Extract.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/ninjaflip/androidrevenge/core/apktool/apkinfo/manifestextractor/Extract.java b/src/main/java/com/ninjaflip/androidrevenge/core/apktool/apkinfo/manifestextractor/Extract.java index d718e38..fd63179 100644 --- a/src/main/java/com/ninjaflip/androidrevenge/core/apktool/apkinfo/manifestextractor/Extract.java +++ b/src/main/java/com/ninjaflip/androidrevenge/core/apktool/apkinfo/manifestextractor/Extract.java @@ -87,7 +87,7 @@ public void unZip(String apkFile) throws Exception { // Create Zip Entry Folder File zeFile = extractFolder; if (zeFolder != null) { - zeFile = new File(extractFolder.getPath() + File.separator + zeFolder); + zeFile = new File(extractFolder.getPath(), zeFolder); if (!zeFile.exists()) zeFile.mkdirs(); } @@ -112,7 +112,13 @@ public void unZip(String apkFile) throws Exception { int count; byte data[] = new byte[BUFFER]; - FileOutputStream fos = new FileOutputStream(zeFile.getPath() + File.separator + zeName); + final File zipEntryFile = new File(zeFile.getPath(), zeName); + + if (!zipEntryFile.toPath().normalize().startsWith(zeFile.getPath())) { + throw new RuntimeException("Bad zip entry"); + } + + FileOutputStream fos = new FileOutputStream(zipEntryFile); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zin.read(data, 0, BUFFER)) != -1) {