From 96b3a4b2b86c8b2243b677d6702a540ff824c8a0 Mon Sep 17 00:00:00 2001 From: Anthony Stirling <77850077+Frooodle@users.noreply.github.com> Date: Thu, 8 May 2025 17:04:09 +0100 Subject: [PATCH] Potential fix for code scanning alert no. 46: Arbitrary file access during archive extraction ("Zip Slip") Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- .../software/SPDF/utils/FileToPdf.java | 20 +++++++------------ 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/src/main/java/stirling/software/SPDF/utils/FileToPdf.java b/src/main/java/stirling/software/SPDF/utils/FileToPdf.java index da4aeab3c..81a307917 100644 --- a/src/main/java/stirling/software/SPDF/utils/FileToPdf.java +++ b/src/main/java/stirling/software/SPDF/utils/FileToPdf.java @@ -86,7 +86,7 @@ public class FileToPdf { new ByteArrayInputStream(Files.readAllBytes(zipFilePath)))) { ZipEntry entry = zipIn.getNextEntry(); while (entry != null) { - Path filePath = tempUnzippedDir.resolve(sanitizeZipFilename(entry.getName())); + Path filePath = sanitizeZipFilename(tempUnzippedDir, entry.getName()); if (!entry.isDirectory()) { Files.createDirectories(filePath.getParent()); if (entry.getName().toLowerCase().endsWith(".html") @@ -188,20 +188,14 @@ public class FileToPdf { } } - static String sanitizeZipFilename(String entryName) { + static Path sanitizeZipFilename(Path baseDir, String entryName) throws IOException { if (entryName == null || entryName.trim().isEmpty()) { - return ""; + throw new IOException("Invalid zip entry name"); } - // Remove any drive letters (e.g., "C:\") and leading forward/backslashes - entryName = entryName.replaceAll("^[a-zA-Z]:[\\\\/]+", ""); - entryName = entryName.replaceAll("^[\\\\/]+", ""); - - // Recursively remove path traversal sequences - while (entryName.contains("../") || entryName.contains("..\\")) { - entryName = entryName.replace("../", "").replace("..\\", ""); + Path resolvedPath = baseDir.resolve(entryName).normalize(); + if (!resolvedPath.startsWith(baseDir)) { + throw new IOException("Zip entry is outside of the target directory: " + entryName); } - // Normalize all backslashes to forward slashes - entryName = entryName.replaceAll("\\\\", "/"); - return entryName; + return resolvedPath; } }