Ghidra is a software reverse engineering (SRE) framework
GP-7132: Improved path traversal checks
Ryan Kurtzca002c5904b5
diff --git a/Ghidra/Features/Base/ghidra_scripts/ExtractELFDebugFilesScript.java b/Ghidra/Features/Base/ghidra_scripts/ExtractELFDebugFilesScript.javaindex 41c4dc5c3c..6bda5ce9d6 100644--- a/Ghidra/Features/Base/ghidra_scripts/ExtractELFDebugFilesScript.java+++ b/Ghidra/Features/Base/ghidra_scripts/ExtractELFDebugFilesScript.java@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -98,10 +98,7 @@ public class ExtractELFDebugFilesScript extends GhidraScript {private void extractDebugFileToDestDir(GFile file, File destDir)throws CancelledException, IOException {- File destFile = new File(destDir, file.getPath()).getCanonicalFile();- if (!FileUtilities.isPathContainedWithin(destDir, destFile)) {- throw new IOException("Bad path / filename: " + file);- }+ File destFile = FileUtilities.getSecureFile(destDir, file.getPath());if (destFile.exists()) {printerr("Duplicate debug file: " + file.getFSRL() + ", " + destFile);return;diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.javaindex 4c5b90b774..42d60a08f1 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.java@@ -441,10 +441,7 @@ class GhidraScriptActionManager {ZipEntry entry = entries.nextElement();String name = entry.getName();- File destination = new File(versionedExtractDir, name);- if (!FileUtilities.isPathContainedWithin(versionedExtractDir, destination)) {- throw new IOException("Zip entry escapes target directory: " + name);- }+ FileUtilities.getSecureFile(versionedExtractDir, name);monitor.setMessage("Extracting " + name + "...");writeZipEntry(versionedExtractDir, entry, zipFileObject.getInputStream(entry));monitor.incrementProgress(1);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf/external/LocalDirDebugLinkProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf/external/LocalDirDebugLinkProvider.javaindex d30bbdedc8..f0ce100bd1 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf/external/LocalDirDebugLinkProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf/external/LocalDirDebugLinkProvider.java@@ -21,6 +21,7 @@ import java.util.zip.CRC32;import ghidra.util.Msg;import ghidra.util.exception.CancelledException;import ghidra.util.task.TaskMonitor;+import utilities.util.FileUtilities;/*** Searches for DWARF external debug files specified via a debug-link filename / crc in a directory.@@ -96,7 +97,7 @@ public class LocalDirDebugLinkProvider implements DebugFileProvider {}private void ensureSafeFilename(String filename) throws IOException {- File testFile = new File(searchDir, filename);+ File testFile = FileUtilities.getSecureFile(searchDir, filename);if (!searchDir.equals(testFile.getParentFile())) {throw new IOException("Unsupported path specified in debug file: " + filename);}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf/external/SameDirDebugInfoProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf/external/SameDirDebugInfoProvider.javaindex d7eddb8141..9f80be847b 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf/external/SameDirDebugInfoProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf/external/SameDirDebugInfoProvider.java@@ -23,6 +23,7 @@ import org.apache.commons.io.FilenameUtils;import ghidra.util.Msg;import ghidra.util.exception.CancelledException;import ghidra.util.task.TaskMonitor;+import utilities.util.FileUtilities;/*** A {@link DebugFileProvider} that only looks in the program's original import directory for@@ -119,7 +120,7 @@ public class SameDirDebugInfoProvider implements DebugFileProvider {}private File ensureSafeFilename(String filename) throws IOException {- File testFile = new File(progDir, filename);+ File testFile = FileUtilities.getSecureFile(progDir, filename);if (!progDir.equals(testFile.getParentFile())) {throw new IOException("Unsupported path specified in debug file: " + filename);}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/xml/MemoryMapXmlMgr.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/xml/MemoryMapXmlMgr.javaindex dad67fc21d..2de48f255f 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/xml/MemoryMapXmlMgr.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/xml/MemoryMapXmlMgr.java@@ -192,11 +192,7 @@ class MemoryMapXmlMgr {private void setData(byte[] bytes, int offset, String directory, String fileName,int fileOffset, int length, MessageLog log) throws IOException {File dir = new File(directory);- File f = new File(dir, fileName);- if (!FileUtilities.isPathContainedWithin(dir, f)) {- throw new FileNotFoundException(- "FILE_NAME entry escapes target directory: " + fileName);- }+ File f = FileUtilities.getSecureFile(dir, fileName);RandomAccessFile binfile = new RandomAccessFile(f, "r");//binfile.seek(fileOffset);try {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/AbstractFileExtractorTask.java b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/AbstractFileExtractorTask.javaindex d4f13d29f1..d07e1c74d4 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/AbstractFileExtractorTask.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/AbstractFileExtractorTask.java@@ -89,13 +89,6 @@ public abstract class AbstractFileExtractorTask extends Task {return;}- if (!FileUtilities.isPathContainedWithin(rootOutputDirectory, destDirectory)) {- // This can happen with hostile relative paths supplied by the data in the src filesystem.- String srcPath = (srcGFileDirectory != null) ? srcGFileDirectory.getPath() : "/";- throw new IOException("Extracted directory " + srcPath + " [" + destDirectory +- "] would be outside of root destination directory: " + rootOutputDirectory);- }-if (!destDirectory.isDirectory() && !destDirectory.mkdirs()) {throw new IOException("Failed to create destination directory " + destDirectory);}@@ -106,7 +99,7 @@ public abstract class AbstractFileExtractorTask extends Task {String destFname = mapSourceFilenameToDest(srcFile);- File destFSFile = new File(destDirectory, destFname);+ File destFSFile = FileUtilities.getSecureFile(destDirectory, destFname);if (srcFile.isDirectory()) {processDirectory(srcFile, destFSFile, monitor);}@@ -119,11 +112,6 @@ public abstract class AbstractFileExtractorTask extends Task {protected void processFile(GFile srcFile, File destFSFile, TaskMonitor monitor)throws IOException, CancelledException {try {- if (!FileUtilities.isPathContainedWithin(this.rootOutputDirectory, destFSFile)) {- throw new IOException("Extracted file " + srcFile.getPath() + " [" + destFSFile +- "] would be outside of root destination directory: " +- this.rootOutputDirectory);- }extractFile(srcFile, destFSFile.getCanonicalFile(), monitor);}catch (CancelledException | IOCancelledException e) {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/tasks/GFileSystemExtractAllTask.java b/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/tasks/GFileSystemExtractAllTask.javaindex e7a64f94e8..88e3f6b4c9 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/tasks/GFileSystemExtractAllTask.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/plugins/fsbrowser/tasks/GFileSystemExtractAllTask.java@@ -103,10 +103,10 @@ public class GFileSystemExtractAllTask extends AbstractFileExtractorTask {}}- private boolean verifyRootOutputDir(String destDirName) {+ private boolean verifyRootOutputDir(String destDirName) throws IOException {boolean isSameName = destDirName.equals(rootOutputDirectory.getName());- File newRootOutputDir =- isSameName ? rootOutputDirectory : new File(rootOutputDirectory, destDirName);+ File newRootOutputDir = isSameName ? rootOutputDirectory+ : FileUtilities.getSecureFile(rootOutputDirectory, destDirName);if (newRootOutputDir.isFile()) {Msg.showError(this, parentComponent, "Export Destination Error","Unable to export to " + newRootOutputDir + " as it is a file");diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/eclipse/AndroidProjectCreator.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/eclipse/AndroidProjectCreator.javaindex b0b34315b0..a3501290e2 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/eclipse/AndroidProjectCreator.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/eclipse/AndroidProjectCreator.java@@ -129,11 +129,7 @@ public class AndroidProjectCreator {if (childName.equals("META-INF")) {continue;}- File subDir = new File(outputDirectory, childName);- if (!FileUtilities.isPathContainedWithin(outputDirectory, subDir)) {- Msg.error(this, "Skipping directory with path traversal: " + childName);- continue;- }+ File subDir = FileUtilities.getSecureFile(outputDirectory, childName);FileUtilities.checkedMkdir(subDir);processListing(subDir, fs, child.getListing(), monitor);continue;@@ -222,11 +218,7 @@ public class AndroidProjectCreator {try (InputStream is = inputFile.getInputStream()) {FileUtilities.checkedMkdirs(outputDirectory);- File destFile = new File(outputDirectory, outputName);- if (!FileUtilities.isPathContainedWithin(outputDirectory, destFile)) {- throw new IOException("Path traversal detected in entry name: " + outputName);- }-+ File destFile = FileUtilities.getSecureFile(outputDirectory, outputName);monitor.setMessage("Copying [" + inputFile.getName() + "] to Eclipse project...");FileUtilities.copyStreamToFile(is, destFile, false, monitor);diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/jad/JarDecompiler.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/jad/JarDecompiler.javaindex 7b14bfcd32..5144939b43 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/jad/JarDecompiler.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/jad/JarDecompiler.java@@ -99,11 +99,7 @@ public class JarDecompiler {if (monitor.isCancelled()) {break;}- File outputFile = new File(outputDirectory.getAbsolutePath(), file.getPath());- if (!FileUtilities.isPathContainedWithin(outputDirectory, outputFile)) {- throw new IOException("Extracted file " + outputFile.getPath() +- " would be outside of root destination directory: " + outputDirectory);- }+ File outputFile = FileUtilities.getSecureFile(outputDirectory, file.getPath());FileUtilities.checkedMkdirs(outputFile.getParentFile());if (!file.isDirectory()) {monitor.setMessage("Unzipping jar file... ");diff --git a/Ghidra/Features/Sarif/src/main/java/sarif/managers/MemoryMapSarifMgr.java b/Ghidra/Features/Sarif/src/main/java/sarif/managers/MemoryMapSarifMgr.javaindex 3012dd838a..a688f7cf4f 100644--- a/Ghidra/Features/Sarif/src/main/java/sarif/managers/MemoryMapSarifMgr.java+++ b/Ghidra/Features/Sarif/src/main/java/sarif/managers/MemoryMapSarifMgr.java@@ -50,9 +50,9 @@ public class MemoryMapSarifMgr extends SarifMgr {this.programMgr = programMgr;}- ////////////////////////////+ //--------------------------// SARIF READ CURRENT DTD //- ////////////////////////////+ //--------------------------@Overridepublic boolean read(Map<String, Object> result, SarifProgramOptions options,@@ -143,10 +143,7 @@ public class MemoryMapSarifMgr extends SarifMgr {byte[] bytes = new byte[length];Arrays.fill(bytes, (byte) 0xff);File dir = new File(directory);- File f = new File(directory, fileName);- if (!FileUtilities.isPathContainedWithin(dir, f)) {- throw new RuntimeException(fileName + " not found within " + directory);- }+ File f = FileUtilities.getSecureFile(dir, fileName);try (RandomAccessFile binfile = new RandomAccessFile(f, "r")) {int pos = 0;while (pos < length) {@@ -168,9 +165,9 @@ public class MemoryMapSarifMgr extends SarifMgr {return bytes;}- /////////////////////////////+ //---------------------------// SARIF WRITE CURRENT DTD //- /////////////////////////////+ //---------------------------void write(JsonArray results, AddressSetView addrs, TaskMonitor monitor,boolean isWriteContents, String filePath) throws IOException, CancelledException {diff --git a/Ghidra/Framework/Generic/src/main/java/ghidra/util/extensions/ExtensionUtils.java b/Ghidra/Framework/Generic/src/main/java/ghidra/util/extensions/ExtensionUtils.javaindex a4e4355f3e..08ff753fb0 100644--- a/Ghidra/Framework/Generic/src/main/java/ghidra/util/extensions/ExtensionUtils.java+++ b/Ghidra/Framework/Generic/src/main/java/ghidra/util/extensions/ExtensionUtils.java@@ -585,11 +585,7 @@ public class ExtensionUtils {monitor.checkCancelled();ZipArchiveEntry entry = entries.nextElement();- String filePath = installDir + File.separator + entry.getName();- File destination = new File(filePath);- if (!FileUtilities.isPathContainedWithin(installDirRoot, destination)) {- throw new IOException("Zip entry escapes target directory: " + entry.getName());- }+ File destination = FileUtilities.getSecureFile(installDirRoot, entry.getName());if (entry.isDirectory()) {destination.mkdirs();}diff --git a/Ghidra/Framework/Gui/src/main/java/generic/theme/ThemeReader.java b/Ghidra/Framework/Gui/src/main/java/generic/theme/ThemeReader.javaindex e6db3bd083..7bd2072a40 100644--- a/Ghidra/Framework/Gui/src/main/java/generic/theme/ThemeReader.java+++ b/Ghidra/Framework/Gui/src/main/java/generic/theme/ThemeReader.java@@ -146,10 +146,7 @@ class ThemeReader extends AbstractThemeReader {String relativePath = path.substring(indexOf, path.length());File dir = Application.getUserSettingsDirectory();- File iconFile = new File(dir, relativePath);- if (!FileUtilities.isPathContainedWithin(dir, iconFile)) {- throw new IOException("Zip entry escapes target directory: " + relativePath);- }+ File iconFile = FileUtilities.getSecureFile(dir, relativePath);FileUtils.copyInputStreamToFile(is, iconFile);}diff --git a/Ghidra/Framework/Utility/src/main/java/utilities/util/FileUtilities.java b/Ghidra/Framework/Utility/src/main/java/utilities/util/FileUtilities.javaindex 96e483b8dc..9c55440d7b 100644--- a/Ghidra/Framework/Utility/src/main/java/utilities/util/FileUtilities.java+++ b/Ghidra/Framework/Utility/src/main/java/utilities/util/FileUtilities.java@@ -875,12 +875,37 @@ public final class FileUtilities {return potentialParents.stream().anyMatch(p -> startsWith(p.getAbsolutePath(), otherPath));}+ /**+ * {@return a new {@link File} object from the given {@code secureBaseDir} and+ * {@code untrustedPathname} that is safe from+ * <a href="https://en.wikipedia.org/wiki/Directory_traversal_attack"> path traversal+ * attacks</a>}+ *+ * @param secureBaseDir The trusted base directory from which to create the {@link File}+ * @param untrustedPathname A pathname relative to the {@code baseDir} used to form the new {@link File},+ * possibly supplied or controlled by an attacker+ * @throws IOException if a path traversal attack is detected+ */+ public static File getSecureFile(File secureBaseDir, String untrustedPathname)+ throws IOException {+ File f = new File(secureBaseDir, untrustedPathname);+ if (!startsWith(secureBaseDir.getPath(), f.getPath())) {+ throw new IOException("Path traversal detected! '%s' escapes '%s'"+ .formatted(untrustedPathname, secureBaseDir));+ }+ return f;+ }+/*** Returns true if the given {@code potentialParentFile} is the parent path of* the given {@code otherFile}, or if the two file paths point to the same path.* <p>* NOTE: Both files are converted to their {@link File#getCanonicalPath() canonical form} prior* to comparing their paths, which may have performance implications, particularly on Windows.+ * <p>+ * WARNING: The canonical form of a pathname may change depending on whether or not+ * the file or directory exists (particularly on Windows). If any of the given {@link File}+ * parameters do not exist, this method may not behave as expected.** @param potentialParentFile The file that may be the parent* @param otherFile The file that may be the child@@ -912,7 +937,11 @@ public final class FileUtilities {* <p>* NOTE: All files are converted to their {@link File#getCanonicalPath() canonical form} prior* to comparing their paths, which may have performance implications, particularly on Windows.- *+ * <p>+ * WARNING: The canonical form of a pathname may change depending on whether or not+ * the file or directory exists (particularly on Windows). If any of the given {@link File}+ * parameters do not exist, this method may not behave as expected.+ ** @param potentialParents The files that may be the parent* @param otherFile The file that may be the child* @return boolean true if {@code otherFile}'s canonical path is within any of the