Skip to content

Security Fix: Prevent Zip Slip Vulnerability in unzip() Method #1441

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions src/main/java/org/myrobotlab/io/Zip.java
Original file line number Diff line number Diff line change
Expand Up @@ -226,15 +226,34 @@ static public void unzip(String zipFile, String newPath) throws ZipException, IO
ZipFile zip = new ZipFile(file);
// String newPath = zipFile.substring(0, zipFile.length() - 4);

new File(newPath).mkdir();
File destDir = new File(newPath);
destDir.mkdir();

// Get canonical path of destination directory for security validation
String canonicalDestDir = destDir.getCanonicalPath();

Enumeration<?> zipFileEntries = zip.entries();

// Process each entry
while (zipFileEntries.hasMoreElements()) {
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(newPath, currentEntry);

// Security: Validate entry name to prevent Zip Slip attacks
if (currentEntry.contains("..") || currentEntry.startsWith("/") || currentEntry.startsWith("\\")) {
throw new IOException("Unsafe zip entry detected: " + currentEntry);
}

File destFile = new File(destDir, currentEntry);

// Security: Verify the resolved file path is within the destination directory
String canonicalFilePath = destFile.getCanonicalPath();
if (!canonicalFilePath.startsWith(canonicalDestDir + File.separator) &&
!canonicalFilePath.equals(canonicalDestDir)) {
throw new IOException("Zip Slip attack detected: " + currentEntry);
}

// destFile = new File(newPath, destFile.getName());
File destinationParent = destFile.getParentFile();

Expand Down