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>
This commit is contained in:
Anthony Stirling 2025-05-08 17:04:09 +01:00 committed by GitHub
parent 512e9d7236
commit 96b3a4b2b8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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;
}
}