Ghidra is a software reverse engineering (SRE) framework
GP-1697 fall back to built-in zip file support when 7zip fails to init
dev747368dd12434a4144
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/FileSystemService.java b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/FileSystemService.javaindex a7b3ed51d8..920a703380 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/FileSystemService.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/FileSystemService.java@@ -15,9 +15,10 @@*/package ghidra.formats.gfilesystem;-import java.io.*;import java.util.List;+import java.io.*;+import ghidra.app.util.bin.*;import ghidra.formats.gfilesystem.FileCache.FileCacheEntry;import ghidra.formats.gfilesystem.FileCache.FileCacheEntryBuilder;@@ -538,6 +539,57 @@ public class FileSystemService {return tempFileCacheEntry.asByteProvider(resultFSRL);}+ /**+ * Converts a {@link ByteProvider} to the underlying File that contains the contents of+ * the ByteProvider.+ * <p>+ * Returns {@code null} if the underlying file is not available.+ *+ * @param provider {@link ByteProvider}+ * @return a java {@link File} that is providing the bytes of the specified ByteProvider,+ * or null if there is no available file+ */+ public File getFileIfAvailable(ByteProvider provider) {+ // reach into the inner details of the ByteProviders that we know about and+ // know could contain a real File+ if (provider instanceof RefdByteProvider) {+ provider = ((RefdByteProvider) provider).getWrappedByteProvider();+ }+ if (provider instanceof FileByteProvider || provider instanceof RandomAccessByteProvider) {+ return provider.getFile();+ }++ return null;+ }++ /**+ * Exports the bytes in a {@link ByteProvider} into normal {@link File} that can be+ * used as the caller wishes.+ * <p>+ * This method is labeled as 'plaintext' to differentiate it from the standard obfuscated+ * temp files that are produced by this service.+ *+ * @param provider {@link ByteProvider} that will be written to a temp file+ * @param filenamePrefix filename prefix of the newly created File+ * @param monitor {@link TaskMonitor}+ * @return temporary {@link File}+ * @throws IOException if error copying data or if cancelled+ */+ public File createPlaintextTempFile(ByteProvider provider, String filenamePrefix,+ TaskMonitor monitor) throws IOException {+ File tmpFile =+ File.createTempFile(filenamePrefix, Long.toString(System.currentTimeMillis()));+ monitor.setMessage("Copying " + provider.getName() + " to temp file");+ monitor.initialize(provider.length());+ try {+ FSUtilities.copyByteProviderToFile(provider, tmpFile, monitor);+ }+ catch (CancelledException e) {+ throw new IOException("Copy was cancelled: " + provider.getName());+ }+ return tmpFile;+ }+/*** Allows the resources used by caching the specified file to be released.*diff --git a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/RefdByteProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/RefdByteProvider.javaindex bb481b2cc8..c772692b23 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/RefdByteProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/RefdByteProvider.java@@ -45,6 +45,10 @@ public class RefdByteProvider implements ByteProvider {this.fsrl = fsrl;}+ /* package */ ByteProvider getWrappedByteProvider() {+ return provider;+ }+@Overridepublic void close() throws IOException {provider.close();diff --git a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/factory/GFileSystemFactoryByteProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/factory/GFileSystemFactoryByteProvider.javaindex 61a0dfaa97..4eb4d5b0c6 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/factory/GFileSystemFactoryByteProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/formats/gfilesystem/factory/GFileSystemFactoryByteProvider.java@@ -44,7 +44,7 @@ public interface GFileSystemFactoryByteProvider<FSTYPE extends GFileSystem>* @throws IOException if there is an error reading files.* @throws CancelledException if the user cancels*/- public FSTYPE create(FSRLRoot targetFSRL, ByteProvider byteProvider,+ public GFileSystem create(FSRLRoot targetFSRL, ByteProvider byteProvider,FileSystemService fsService, TaskMonitor monitor)throws IOException, CancelledException;}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ios/dmg/DmgClientFileSystemFactory.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ios/dmg/DmgClientFileSystemFactory.javaindex 6496650c61..920674dd0a 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ios/dmg/DmgClientFileSystemFactory.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/ios/dmg/DmgClientFileSystemFactory.java@@ -114,11 +114,8 @@ public class DmgClientFileSystemFactory implementsdecryptedProvider = provider;}- File decryptedDmgFile = File.createTempFile("ghidra_decrypted_dmg_file",- Long.toString(System.currentTimeMillis()));- monitor.setMessage("Copying DMG container to temp file");- monitor.initialize(decryptedProvider.length());- FSUtilities.copyByteProviderToFile(decryptedProvider, decryptedDmgFile, monitor);+ File decryptedDmgFile = fsService.createPlaintextTempFile(decryptedProvider,+ "ghidra_decrypted_dmg_file", monitor);DmgClientFileSystem fs =new DmgClientFileSystem(decryptedDmgFile, true, targetFSRL, fsService);diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/sevenzip/SevenZipFileSystemFactory.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/sevenzip/SevenZipFileSystemFactory.javaindex 6b7a241816..9a8b950fc0 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/sevenzip/SevenZipFileSystemFactory.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/sevenzip/SevenZipFileSystemFactory.java@@ -15,16 +15,20 @@*/package ghidra.file.formats.sevenzip;-import java.io.IOException;import java.util.List;+import java.io.IOException;+import ghidra.app.util.bin.ByteProvider;import ghidra.app.util.recognizer.*;import ghidra.formats.gfilesystem.*;import ghidra.formats.gfilesystem.factory.GFileSystemFactoryByteProvider;import ghidra.formats.gfilesystem.factory.GFileSystemProbeBytesOnly;+import ghidra.util.Msg;import ghidra.util.exception.CancelledException;import ghidra.util.task.TaskMonitor;+import net.sf.sevenzipjbinding.SevenZip;+import net.sf.sevenzipjbinding.SevenZipNativeInitializationException;public class SevenZipFileSystemFactoryimplements GFileSystemFactoryByteProvider<SevenZipFileSystem>, GFileSystemProbeBytesOnly {@@ -35,6 +39,7 @@ public class SevenZipFileSystemFactorynew RarRecognizer(), new RPMRecognizer(), new VHDRecognizer(), new XarRecognizer(),new UnixCompressRecognizer());+ private static boolean initFailed;private final int recognizerBytesRequired;public SevenZipFileSystemFactory() {@@ -77,4 +82,26 @@ public class SevenZipFileSystemFactory}}+ /**+ * Returns true if the native libraries for 7zip were initialized.+ * <p>+ *+ * @return boolean true if 7zip dlls/libs/etc were successfully initialized+ */+ public static boolean initNativeLibraries() {+ try {+ SevenZip.initSevenZipFromPlatformJAR(); // calling this multiple times is ok+ return true;+ }+ catch (SevenZipNativeInitializationException e) {+ if (!initFailed) {+ Msg.warn(SevenZipFileSystemFactory.class,+ "Sevenzip native libraries failed to initialize: " + e.getMessage());+ initFailed = true;+ }+ return false;+ }++ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/zip/ZipFileSystemBuiltin.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/zip/ZipFileSystemBuiltin.javanew file mode 100644index 0000000000..e70bd191b1--- /dev/null+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/zip/ZipFileSystemBuiltin.java@@ -0,0 +1,177 @@+/* ###+ * IP: GHIDRA+ *+ * 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.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package ghidra.file.formats.zip;++import java.util.Enumeration;+import java.util.List;+import java.util.zip.ZipEntry;+import java.util.zip.ZipFile;++import java.io.*;+import java.sql.Date;++import ghidra.app.util.bin.ByteProvider;+import ghidra.formats.gfilesystem.*;+import ghidra.formats.gfilesystem.annotations.FileSystemInfo;+import ghidra.formats.gfilesystem.fileinfo.FileAttributeType;+import ghidra.formats.gfilesystem.fileinfo.FileAttributes;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * An alternative implementation of the zip file system, using java's built-in support+ * for zip files.+ * <p>+ * This class is used when the 7zip libraries fail to load, typically on a non-supported+ * platform.+ * <p>+ * The user will lose the ability to open password protected zip files when operating in this+ * mode, as well as the ability to use obfuscated temp files, which may allow a virusscanner+ * to mangle our temp files.+ * <p>+ * This class's name does not end in "FileSystem", so that it will not be found by the class searcher.+ * <p>+ * It also needs to duplicate the FileSystemInfo annotation to allow {@link GFileSystem#getType()}+ * and {@link GFileSystem#getDescription()} to operate in the default manner.+ */+@FileSystemInfo(type = "zip", description = "ZIP", factory = ZipFileSystemFactory.class, priority = FileSystemInfo.PRIORITY_HIGH)+public class ZipFileSystemBuiltin implements GFileSystem {+ static final String TEMPFILE_PREFIX = "ghidra_tmp_zipfile";++ private FileSystemIndexHelper<ZipEntry> fsIndexHelper;+ private FSRLRoot fsFSRL;+ private ZipFile zipFile;+ private FileSystemRefManager refManager = new FileSystemRefManager(this);+ private FileSystemService fsService;++ public ZipFileSystemBuiltin(FSRLRoot fsFSRL, FileSystemService fsService) {+ this.fsFSRL = fsFSRL;+ this.fsService = fsService;+ this.fsIndexHelper = new FileSystemIndexHelper<>(this, fsFSRL);+ }++ @Override+ public String getName() {+ return fsFSRL.getContainer().getName();+ }++ @Override+ public void close() throws IOException {+ refManager.onClose();+ if (zipFile != null) {+ zipFile.close();+ zipFile = null;+ }+ fsIndexHelper.clear();+ }++ @Override+ public boolean isClosed() {+ return zipFile == null;+ }++ @Override+ public FSRLRoot getFSRL() {+ return fsFSRL;+ }++ @Override+ public int getFileCount() {+ return fsIndexHelper.getFileCount();+ }++ public void mount(File f, boolean deleteFileWhenDone, TaskMonitor monitor)+ throws CancelledException, IOException {++ // Just a little paranoia to ensure we don't delete a user's file.+ // The ZipFileSystemFactory knows to create temp files with this prefix.+ deleteFileWhenDone = deleteFileWhenDone && f.getName().startsWith(TEMPFILE_PREFIX);++ int openMode = deleteFileWhenDone+ ? ZipFile.OPEN_READ | ZipFile.OPEN_DELETE+ : ZipFile.OPEN_READ;+ this.zipFile = new ZipFile(f, openMode);++ Enumeration<? extends ZipEntry> entries = zipFile.entries();+ while (entries.hasMoreElements()) {+ monitor.checkCanceled();+ ZipEntry currentEntry = entries.nextElement();+ fsIndexHelper.storeFile(currentEntry.getName(), -1, currentEntry.isDirectory(),+ currentEntry.getSize(), currentEntry);+ }+ }++ @Override+ public FileAttributes getFileAttributes(GFile file, TaskMonitor monitor) {+ ZipEntry zipEntry = fsIndexHelper.getMetadata(file);+ if (zipEntry == null) {+ return null;+ }+ FileAttributes result = new FileAttributes();++ result.add(FileAttributeType.COMMENT_ATTR, zipEntry.getComment());+ result.add(FileAttributeType.SIZE_ATTR, zipEntry.getSize());+ Date date = new Date(zipEntry.getLastModifiedTime().toMillis());+ result.add(FileAttributeType.MODIFIED_DATE_ATTR, date);+ result.add(FileAttributeType.COMPRESSED_SIZE_ATTR, zipEntry.getCompressedSize());+ result.add("CRC", Long.toHexString(zipEntry.getCrc()));+ result.add("Compression Method", "0x" + Integer.toHexString(zipEntry.getMethod()));+ return result;+ }++ @Override+ public String toString() {+ return "ZipFilesystemBuiltin [ fsrl=" + fsFSRL + ", filename=" + zipFile.getName() + " ]";+ }++ @Override+ public GFile lookup(String path) throws IOException {+ return fsIndexHelper.lookup(path);+ }++ @Override+ public InputStream getInputStream(GFile file, TaskMonitor monitor)+ throws IOException, CancelledException {+ ZipEntry zipEntry = fsIndexHelper.getMetadata(file);+ return (zipEntry != null) ? zipFile.getInputStream(zipEntry) : null;+ }++ @Override+ public ByteProvider getByteProvider(GFile file, TaskMonitor monitor)+ throws IOException, CancelledException {+ ZipEntry zipEntry = fsIndexHelper.getMetadata(file);+ if (zipEntry == null) {+ return null;+ }+ return fsService.getDerivedByteProvider(+ fsFSRL.getContainer(),+ file.getFSRL(),+ zipEntry.getName(),+ zipEntry.getSize(),+ () -> zipFile.getInputStream(zipEntry),+ monitor);+ }++ @Override+ public List<GFile> getListing(GFile directory) throws IOException {+ return fsIndexHelper.getListing(directory);+ }++ @Override+ public FileSystemRefManager getRefManager() {+ return refManager;+ }+}diff --git a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/zip/ZipFileSystemFactory.java b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/zip/ZipFileSystemFactory.javaindex 6ba38cce49..fa24c18cdd 100644--- a/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/zip/ZipFileSystemFactory.java+++ b/Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/zip/ZipFileSystemFactory.java@@ -15,9 +15,11 @@*/package ghidra.file.formats.zip;+import java.io.File;import java.io.IOException;import ghidra.app.util.bin.ByteProvider;+import ghidra.file.formats.sevenzip.SevenZipFileSystemFactory;import ghidra.formats.gfilesystem.*;import ghidra.formats.gfilesystem.factory.GFileSystemFactoryByteProvider;import ghidra.formats.gfilesystem.factory.GFileSystemProbeBytesOnly;@@ -26,8 +28,26 @@ import ghidra.util.task.TaskMonitor;public class ZipFileSystemFactoryimplements GFileSystemFactoryByteProvider<ZipFileSystem>, GFileSystemProbeBytesOnly {+ /**+ * Use "-Dghidra.file.formats.zip.ZipFileSystemFactory.USE_BUILTIN_ZIP_SUPPORT=true" jvm+ * startup option to disable use of 7zip libraries when opening zip filesystems.+ */+ private static boolean USE_BUILTIN_ZIP_SUPPORT = Boolean+ .getBoolean("ghidra.file.formats.zip.ZipFileSystemFactory.USE_BUILTIN_ZIP_SUPPORT");+private static final int START_BYTES_REQUIRED = 2;+ /**+ * Sets the static flag controlling which zip file implementation will used when opening+ * a zip file system.+ *+ * @param b boolean true forces use of the built-in java zip library (in other words, disables+ * use of 7zip), false will allow the 7zip libraries to be attempted to be used+ */+ public static void setUseBuiltinZipSupport(boolean b) {+ USE_BUILTIN_ZIP_SUPPORT = b;+ }+@Overridepublic int getBytesRequired() {return START_BYTES_REQUIRED;@@ -39,17 +59,40 @@ public class ZipFileSystemFactory}@Override- public ZipFileSystem create(FSRLRoot targetFSRL, ByteProvider byteProvider,+ public GFileSystem create(FSRLRoot targetFSRL, ByteProvider byteProvider,FileSystemService fsService, TaskMonitor monitor)throws IOException, CancelledException {- ZipFileSystem fs = new ZipFileSystem(targetFSRL, fsService);- try {- fs.mount(byteProvider, monitor);- return fs;++ // Try to use 7zip to handle .zip files, or fall back to using the less feature rich+ // built-in java zip file support.+ if (!USE_BUILTIN_ZIP_SUPPORT && SevenZipFileSystemFactory.initNativeLibraries()) {+ ZipFileSystem fs = new ZipFileSystem(targetFSRL, fsService);+ try {+ fs.mount(byteProvider, monitor);+ return fs;+ }+ catch (IOException ioe) {+ fs.close();+ throw ioe;+ }}- catch (IOException ioe) {- fs.close();- throw ioe;+ else {+ File zipFile = fsService.getFileIfAvailable(byteProvider);+ boolean deleteZipFileWhenDone = false;+ if (zipFile == null) {+ zipFile = fsService.createPlaintextTempFile(byteProvider,+ ZipFileSystemBuiltin.TEMPFILE_PREFIX, monitor);+ deleteZipFileWhenDone = true;+ }+ ZipFileSystemBuiltin fs = new ZipFileSystemBuiltin(targetFSRL, fsService);+ try {+ fs.mount(zipFile, deleteZipFileWhenDone, monitor);+ return fs;+ }+ catch (IOException ioe) {+ fs.close();+ throw ioe;+ }}}