Browse Source

Add security checks to prevent directory traversal when decompressing

pull/537/head
afeng2016-s 9 months ago
parent
commit
ed9392069f

+ 0
- 12
pf4j/src/main/java/org/pf4j/util/FileUtils.java View File

@@ -185,11 +185,6 @@ public final class FileUtils {
String directoryName = fileName.substring(0, fileName.lastIndexOf("."));
Path pluginDirectory = filePath.resolveSibling(directoryName);

// Check whether directory traversal risks exist in the path
if (!isInvalidPath(pluginDirectory)) {
throw new SecurityException("Invalid destination directory");
}

if (!Files.exists(pluginDirectory) || pluginZipDate.compareTo(Files.getLastModifiedTime(pluginDirectory)) > 0) {
// expand '.zip' file
Unzip unzip = new Unzip();
@@ -202,13 +197,6 @@ public final class FileUtils {
return pluginDirectory;
}

/**
* Use regular expressions to check whether the path contains a path traversal attempt
*/
private static boolean isInvalidPath(Path path) {
String pathStr = path.toString();
return pathStr.matches(".*\\.\\.(\\\\|/).*");
}

/**
* Return true only if path is a zip file.

+ 10
- 0
pf4j/src/main/java/org/pf4j/util/Unzip.java View File

@@ -20,7 +20,10 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;

import org.slf4j.Logger;
@@ -80,6 +83,11 @@ public class Unzip {
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
File file = new File(destination, zipEntry.getName());

// add check
if (zipEntry.getName().indexOf("..") != -1 && !file.getCanonicalPath().startsWith(destination.getCanonicalPath())) {
throw new ZipException("The file "+zipEntry.getName()+" is trying to leave the target output directory of "+destination+". Ignoring this file.");
}

// create intermediary directories - sometimes zip don't add them
File dir = new File(file.getParent());

@@ -100,6 +108,8 @@ public class Unzip {
}
}



private static void mkdirsOrThrow(File dir) throws IOException {
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Failed to create directory " + dir);

Loading…
Cancel
Save