From 3680f438d0491ba01f884382d814ba6ca238353d Mon Sep 17 00:00:00 2001 From: Jonathan Leitschuh Date: Mon, 12 Sep 2022 16:10:50 -0400 Subject: [PATCH] vuln-fix: Zip Slip Vulnerability (#4144) 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 Co-authored-by: Moderne --- .../web/filter/initialization/TestInstallUtil.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/web/src/main/java/org/openmrs/web/filter/initialization/TestInstallUtil.java b/web/src/main/java/org/openmrs/web/filter/initialization/TestInstallUtil.java index 318fd8246658..7d7547f12f04 100755 --- a/web/src/main/java/org/openmrs/web/filter/initialization/TestInstallUtil.java +++ b/web/src/main/java/org/openmrs/web/filter/initialization/TestInstallUtil.java @@ -184,9 +184,14 @@ protected static boolean addZippedTestModules(InputStream in) { //delete all previously added modules in case of prior test installations FileUtils.cleanDirectory(moduleRepository); + + final File zipEntryFile = new File(moduleRepository, fileName); + + if (!zipEntryFile.toPath().normalize().startsWith(moduleRepository.toPath().normalize())) { + throw new IOException("Bad zip entry"); + } - OpenmrsUtil.copyFile(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream( - new File(moduleRepository, fileName)))); + OpenmrsUtil.copyFile(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(zipEntryFile))); } else { log.debug("Ignoring file that is not a .omod '{}'", fileName); }