Ghidra is a software reverse engineering (SRE) framework
GP-7286 Added size safeguards for packed DB deserializer
ghidra1dc8e3ad4fe0d
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/plugin/importer/ImporterPlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/plugin/importer/ImporterPlugin.javaindex e016a4793d..ec10b4977c 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/plugin/importer/ImporterPlugin.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/plugin/importer/ImporterPlugin.java@@ -266,30 +266,24 @@ public class ImporterPlugin extends Pluginreturn failedFiles; // return files not yet imported}- private boolean doUnpackFile(DomainFolder folder, TaskMonitor monitor, File f)+ private boolean doUnpackFile(DomainFolder folder, TaskMonitor monitor, File packedFile)throws CancelledException {// Test for Packed DB file using ItemDeserializer- ItemDeserializer deserializer = null;- try {- deserializer = new ItemDeserializer(f); // fails for non-packed file+ try (ItemDeserializer _ = new ItemDeserializer(packedFile)) {+ // fails for non-packed file}catch (IOException e) {return false;}- finally {- if (deserializer != null) {- deserializer.dispose();- }- }- monitor.setMessage("Unpacking " + f.getName() + " ...");+ monitor.setMessage("Unpacking " + packedFile.getName() + " ...");// Perform direct unpack of Packed DB file- String filename = makeValidUniqueFilename(f.getName(), folder);+ String filename = makeValidUniqueFilename(packedFile.getName(), folder);try {- DomainFile df = folder.createFile(filename, f, monitor);- Msg.info(this, "Imported " + f.getName() + " to " + df.getPathname());+ DomainFile df = folder.createFile(filename, packedFile, monitor);+ Msg.info(this, "Imported " + packedFile.getName() + " to " + df.getPathname());return true;}catch (InvalidNameException e) {@@ -297,7 +291,7 @@ public class ImporterPlugin extends Plugin}catch (IOException e) {Msg.showError(JavaFileListHandler.class, tool.getToolFrame(),- "Packed DB Import Failed", "Failed to import " + f.getName(), e);+ "Packed DB Import Failed", "Failed to import " + packedFile.getName(), e);}return false;}diff --git a/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/db/PackedDatabase.java b/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/db/PackedDatabase.javaindex 8731c57840..cf66740b19 100644--- a/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/db/PackedDatabase.java+++ b/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/db/PackedDatabase.java@@ -477,22 +477,18 @@ public class PackedDatabase extends Database {*/private void readContentTypeAndName() throws IOException {- ItemDeserializer itemDeserializer = null;if (packedDbLock != null) {lock(packedDbLock, true, true);}- try {- itemDeserializer = new ItemDeserializer(packedDbFile);- if (itemDeserializer.getFileType() != FolderItem.DATABASE_FILE_TYPE) {+ try (ItemDeserializer itemDeserializer = new ItemDeserializer(packedDbFile)) {+ contentType = itemDeserializer.getContentType();+ if (itemDeserializer.getFileType() != FolderItem.DATABASE_FILE_TYPE ||+ contentType == null) {throw new IOException("Incorrect file type");}- contentType = itemDeserializer.getContentType();itemName = itemDeserializer.getItemName();}finally {- if (itemDeserializer != null) {- itemDeserializer.dispose();- }if (packedDbLock != null) {packedDbLock.removeLock();}@@ -523,30 +519,43 @@ public class PackedDatabase extends Database {}int version = bfMgr.getCurrentVersion() + 1; // should be 1 in most situationsFile file = bfMgr.getBufferFile(version);- OutputStream out = new BufferedOutputStream(new FileOutputStream(file));- ItemDeserializer itemDeserializer = null;- try {+ boolean success = false;+ try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file));+ ItemDeserializer itemDeserializer = new ItemDeserializer(packedFile)) {Msg.debug(PackedDatabase.class, "Unpacking database " + packedFile + " -> " + file);- itemDeserializer = new ItemDeserializer(packedFile);+ checkFreeSpace(file, itemDeserializer.getLength());itemDeserializer.saveItem(out, monitor);bfMgr.versionCreated(version, "Unpacked " + packedFile, checkinId);+ success = true;}catch (IOCancelledException e) {throw new CancelledException();}finally {- if (itemDeserializer != null) {- itemDeserializer.dispose();- }- try {- out.close();- }- catch (IOException e) {- // ignore+ if (!success) {+ file.delete();}}}+ private static void checkFreeSpace(File destFile, long requiredSpace) throws IOException {++ File canonicalFile = destFile.getCanonicalFile();++ long freeSpace = canonicalFile.getFreeSpace();+ if (freeSpace <= 0) {+ return; // unable to check free space+ }++ // We need room to grow database after unpacking - use factor of 10+ long spaceNeeded = 10 * requiredSpace;+ if (spaceNeeded < 0 || spaceNeeded > freeSpace) {+ throw new IOException(+ "Insufficient disc space for unpacking database (" + requiredSpace + "): " ++ canonicalFile.getParent());+ }+ }+/*** Refresh the temporary database from the packed file if it has been updated* since the previous refresh.@@ -579,14 +588,6 @@ public class PackedDatabase extends Database {return true;}-// File[] files = dbDir.listFiles();-// for (int i = 0; i < files.length; i++) {-// if (!files[i].delete()) {-// return false;-// }-// }-// currentVersion = 0;-monitor.setMessage("Unpacking file...");refreshDatabase(bfMgr, -1, packedDbFile, monitor);@@ -594,8 +595,6 @@ public class PackedDatabase extends Database {if (isCached) {PackedDatabaseCache.getCache().updateLastModified(packedDbFile, modTime);}-// currentVersion = 1;-}finally {if (packedDbLock != null) {diff --git a/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/db/PackedDatabaseCache.java b/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/db/PackedDatabaseCache.javaindex 0f3eb847ea..e33c42edec 100644--- a/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/db/PackedDatabaseCache.java+++ b/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/db/PackedDatabaseCache.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.@@ -212,27 +212,23 @@ public class PackedDatabaseCache {}private CachedDB createCachedDb(ResourceFile packedDbFile) throws IOException {+ if (!packedDbFile.isFile()) {+ throw new FileNotFoundException("File not found: " + packedDbFile);+ }File dbDir = createCachedDir();- ItemDeserializer itemDeserializer = null;boolean success = false;- try {- if (!packedDbFile.isFile()) {- throw new FileNotFoundException("File not found: " + packedDbFile);- }- itemDeserializer = new ItemDeserializer(packedDbFile);- if (itemDeserializer.getFileType() != FolderItem.DATABASE_FILE_TYPE) {+ try (ItemDeserializer itemDeserializer = new ItemDeserializer(packedDbFile)) {+ String contentType = itemDeserializer.getContentType();+ if (itemDeserializer.getFileType() != FolderItem.DATABASE_FILE_TYPE ||+ contentType == null) {throw new IOException("Incorrect file type");}- String contentType = itemDeserializer.getContentType();String itemName = itemDeserializer.getItemName();CachedDB cachedDb = new CachedDB(packedDbFile, dbDir, contentType, itemName, 0, true);success = true;return cachedDb;}finally {- if (itemDeserializer != null) {- itemDeserializer.dispose();- }if (!success) {FileUtilities.deleteDir(dbDir);}diff --git a/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/local/ItemDeserializer.java b/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/local/ItemDeserializer.javaindex 1499711f93..3c1664a8fc 100644--- a/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/local/ItemDeserializer.java+++ b/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/local/ItemDeserializer.java@@ -19,6 +19,8 @@ import java.io.*;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;+import org.apache.commons.lang3.StringUtils;+import generic.jar.ResourceFile;import ghidra.util.MonitoredInputStream;import ghidra.util.exception.IOCancelledException;@@ -35,7 +37,7 @@ import ghidra.util.task.TaskMonitor;* <li>Data length</li>* </ul>*/-public class ItemDeserializer {+public class ItemDeserializer implements Closeable {private static final long MAGIC_NUMBER = ItemSerializer.MAGIC_NUMBER;private static final int FORMAT_VERSION = ItemSerializer.FORMAT_VERSION;@@ -43,6 +45,9 @@ public class ItemDeserializer {private final static int IO_BUFFER_SIZE = ItemSerializer.IO_BUFFER_SIZE;+ // Maximum compression ratio allowed+ private final static int MAX_EXPECTED_COMPRESSION_RATIO = 20;+private InputStream in;private String itemName;private String contentType;@@ -54,7 +59,7 @@ public class ItemDeserializer {/*** Constructor.* @param packedFile item to deserialize.- * @throws IOException+ * @throws IOException if an IO error occurs opening packed file*/public ItemDeserializer(File packedFile) throws IOException {this(new ResourceFile(packedFile));@@ -62,6 +67,8 @@ public class ItemDeserializer {public ItemDeserializer(ResourceFile packedFile) throws IOException {+ long fileLen = packedFile.length();+in = new BufferedInputStream(packedFile.getInputStream());// Read header containing: original item name and content type@@ -77,11 +84,22 @@ public class ItemDeserializer {itemName = objIn.readUTF();contentType = objIn.readUTF();- if (contentType.length() == 0) {+ if (StringUtils.isBlank(contentType)) {contentType = null;}fileType = objIn.readInt();length = objIn.readLong();++ if (StringUtils.isBlank(itemName) || length <= 0) {+ throw new IOException("Invalid packed data file");+ }++ long compressionRatio = length / fileLen;+ if (compressionRatio > MAX_EXPECTED_COMPRESSION_RATIO) {+ throw new IOException(+ "Suspicious packed data file compression ratio: " + compressionRatio);+ }+success = true;}catch (UTFDataFormatException e) {@@ -93,56 +111,57 @@ public class ItemDeserializer {in.close();}catch (IOException e) {+ // ignore}}}}- @Override- protected void finalize() throws Throwable {- dispose();- super.finalize();- }-/*** Close packed-file input stream and free resources.+ * @deprecated {@link #close()} should be used.*/+ @Deprecatedpublic void dispose() {+ try {+ close();+ }+ catch (IOException e) {+ // ignore+ }+ }++ @Override+ public void close() throws IOException {if (in != null) {- try {- in.close();- }- catch (IOException e) {- }- finally {- in = null;- }+ in.close();+ in = null;}}/**- * Returns packed item name+ * {@return packed item name}*/public String getItemName() {return itemName;}/**- * Returns packed content type+ * {@return packed content type}*/public String getContentType() {return contentType;}/**- * Returns packed file type.+ * {@return packed file type}*/public int getFileType() {return fileType;}/**- * Returns unpacked data length+ * {@return unpacked data length}*/public long getLength() {return length;@@ -151,9 +170,13 @@ public class ItemDeserializer {/*** Save the item to the specified output stream.* This method may only be invoked once.- * @param out- * @param monitor- * @throws IOException+ * The caller may want to check target file-system for sufficient storage+ * based upon uncompressed {@link #length}.+ *+ * @param out destination output stream+ * @param monitor task monitor+ * @throws IOCancelledException if stream cancelled by monitor+ * @throws IOException if an IO error occurs*/public void saveItem(OutputStream out, TaskMonitor monitor) throws IOCancelledException,IOException {@@ -168,9 +191,6 @@ public class ItemDeserializer {if (entry == null || !ZIP_ENTRY_NAME.equals(entry.getName())) {throw new IOException("Data error");}-// if (length != entry.getSize()) {-// throw new IOException("Content length is " + entry.getSize() + ", expected " + length);-// }InputStream itemIn = zipIn;if (monitor != null) {@@ -188,6 +208,9 @@ public class ItemDeserializer {cnt = (int) (len < IO_BUFFER_SIZE ? len : IO_BUFFER_SIZE);}+ if (itemIn.read() > 0) {+ throw new IOException("Data error: expected end of data");+ }}}diff --git a/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/local/LocalFileSystem.java b/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/local/LocalFileSystem.javaindex cf85aac96d..57deee7730 100644--- a/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/local/LocalFileSystem.java+++ b/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/store/local/LocalFileSystem.java@@ -610,20 +610,16 @@ public abstract class LocalFileSystem implements FileSystem {testValidName(parentPath, true);testValidName(name, false);- ItemDeserializer itemDeserializer = new ItemDeserializer(packedFile);String contentType;- try {+ try (ItemDeserializer itemDeserializer = new ItemDeserializer(packedFile)) {int fileType = itemDeserializer.getFileType();- if (fileType != FolderItem.DATABASE_FILE_TYPE) {+ contentType = itemDeserializer.getContentType();+ if (fileType != FolderItem.DATABASE_FILE_TYPE || contentType == null) {throw new UnsupportedOperationException("Only packed database files are supported");}if (name == null) {name = itemDeserializer.getItemName();}- contentType = itemDeserializer.getContentType();- }- finally {- itemDeserializer.dispose();}ItemStorage itemStorage = allocateItemStorage(parentPath, name);