Ghidra is a software reverse engineering (SRE) framework
GP-7250 Improved ElfHeader parse hardening for program headers and section headers.
Ryan Kurtz6c50a66e8a93
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfHeader.javaindex 8e23f00d9f..dad7d26230 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfHeader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfHeader.java@@ -37,6 +37,8 @@ public class ElfHeader implements StructConverter {private static final int MAX_HEADERS_TO_CHECK_FOR_IMAGEBASE = 20;private static final int PAD_LENGTH = 7;++ static final long FILE_OFFSET_HARD_LIMIT = 0x00007FFFFFFFFFFFL;private HashMap<Integer, ElfProgramHeaderType> programHeaderTypeMap;private HashMap<Integer, ElfSectionHeaderType> sectionHeaderTypeMap;@@ -65,11 +67,14 @@ public class ElfHeader implements StructConverter {private final int e_flags; //processor-specific flagsprivate final short e_ehsize; //elf header sizeprivate final short e_phentsize; //size of entries in the program header table- private final int e_phnum; //number of enties in the program header table (may be extended and may not be preserved)+ private final int e_phnum; //number of entries in the program header table (may be extended and may not be preserved)private final short e_shentsize; //size of entries in the section header table- private final int e_shnum; //number of enties in the section header table (may be extended and may not be preserved)+ private final int e_shnum; //number of entries in the section header table (may be extended and may not be preserved)private final int e_shstrndx; //section index of the section name string table (may be extended and may not be preserved)+ private boolean phnumTruncated = false;+ private boolean shnumTruncated = false;+private Structure headerStructure;private boolean parsed = false;@@ -104,8 +109,12 @@ public class ElfHeader implements StructConverter {* @throws ElfException if header parse failed*/public ElfHeader(ByteProvider provider, Consumer<String> errorConsumer) throws ElfException {+ if (provider.length() < 0) {+ throw new IllegalArgumentException(+ "Unsupport byte provider length: 0x" + Long.toHexString(provider.length()));+ }this.provider = provider;- this.errorConsumer = errorConsumer != null ? errorConsumer : msg -> {+ this.errorConsumer = errorConsumer != null ? errorConsumer : _ -> {/* no logging if errorConsumer was null */};try {@@ -134,15 +143,17 @@ public class ElfHeader implements StructConverter {e_machine = reader.readNextShort();e_version = reader.readNextInt();+ long phoff;+ long shoff;if (is32Bit()) {e_entry = reader.readNextUnsignedInt();- e_phoff = reader.readNextUnsignedInt();- e_shoff = reader.readNextUnsignedInt();+ phoff = reader.readNextUnsignedInt();+ shoff = reader.readNextUnsignedInt();}else if (is64Bit()) {e_entry = reader.readNextLong();- e_phoff = reader.readNextLong();- e_shoff = reader.readNextLong();+ phoff = reader.readNextLong();+ shoff = reader.readNextLong();}else {throw new ElfException(@@ -150,24 +161,112 @@ public class ElfHeader implements StructConverter {Integer.toHexString(e_ident_class) + ")");}+ if (phoff < 0 || phoff > FILE_OFFSET_HARD_LIMIT || phoff >= provider.length()) {+ logError("Invalid ELF e_phoff value (program header table offset): 0x" ++ Long.toHexString(phoff));+ phoff = 0;+ }+ if (shoff < 0 || shoff > FILE_OFFSET_HARD_LIMIT || shoff >= provider.length()) {+ logError("Invalid ELF e_shoff value (section header table offset): 0x" ++ Long.toHexString(shoff));+ shoff = 0;+ }+ e_phoff = phoff;+ e_shoff = shoff;+e_flags = reader.readNextInt();e_ehsize = reader.readNextShort();e_phentsize = reader.readNextShort();+ long u_phentsize = Short.toUnsignedLong(e_phentsize);int phnum = reader.readNextUnsignedShort();- if (phnum == Short.toUnsignedInt(ElfConstants.PN_XNUM)) {- phnum = readExtendedProgramHeaderCount(); // use extended stored program header count+ if (e_phoff == 0) {+ phnum = 0; // disable program header use}- e_phnum = phnum;+ else if (phnum == Short.toUnsignedInt(ElfConstants.PN_XNUM)) {+ phnum = readExtendedProgramHeaderCount(); // use extended stored program header count (uses e_shoff)+ }+ long u_phnum = Integer.toUnsignedLong(phnum);e_shentsize = reader.readNextShort();+ long u_shentsize = Short.toUnsignedLong(e_shentsize);int shnum = reader.readNextUnsignedShort();- if (shnum == 0 ||- shnum >= Short.toUnsignedInt(ElfSectionHeaderConstants.SHN_LORESERVE)) {- shnum = readExtendedSectionHeaderCount(); // use extended stored section header count+ if (shnum >= Short.toUnsignedInt(ElfSectionHeaderConstants.SHN_LORESERVE)) {+ logError("Invalid ELF e_shnum value (section header count): 0x" ++ Long.toHexString(shnum));+ shnum = 0;+ }+ if (e_shoff == 0) {+ shnum = 0; // disable section header use+ }+ else if (shnum == 0) {+ // NOTE: Only e_shnum==0 is a valid trigger for extended value but we will check regardless when bad value is read+ shnum = readExtendedSectionHeaderCount(); // use extended stored section header count (uses e_shoff)+ }+ long u_shnum = Integer.toUnsignedLong(shnum);++ if (phnum > 0) {+ // validate e_phentsize value+ long supportedPHSize =+ is64Bit() ? ElfProgramHeader.ELF64_PHDR_SIZE : ElfProgramHeader.ELF32_PHDR_SIZE;+ if (u_phentsize != supportedPHSize) {+ if (shnum != 0) {+ logError(+ "Unsupported e_phentsize value (program header size): " + u_phentsize ++ " (expected " + supportedPHSize + "), using section headers only");+ phnum = 0; // disable parse of program headers+ }+ else {+ throw new ElfException(+ "Unsupported e_phentsize value (program header size): " + u_phentsize ++ " (expected " + supportedPHSize + ")");+ }+ }+ else {+ long hardLimit = Integer.toUnsignedLong(Integer.MAX_VALUE) / u_phentsize;+ int count = (int) constrainHeaderCount(u_phnum, e_phoff, u_phentsize, hardLimit,+ "Program Header");+ // flag as truncated if only a partial header set can be read or marked-up+ phnumTruncated = hasHeaderFragment(u_phnum, e_phoff, u_phentsize, hardLimit,+ "Program Header") ||+ (count != phnum);+ phnum = count;+ }+ }++ if (shnum > 0) {+ // validate e_shentsize value+ long supportedSHSize =+ is64Bit() ? ElfSectionHeader.ELF64_SHDR_SIZE : ElfSectionHeader.ELF32_SHDR_SIZE;+ if (u_shentsize != supportedSHSize) {+ if (phnum != 0) {+ logError(+ "Unsupported e_shentsize value (section header size): " + u_shentsize ++ " (expected " + supportedSHSize + "), using program headers only");+ shnum = 0; // disable parse of section headers+ }+ // TODO: add ability to handle short headers with limited markup+ else {+ throw new ElfException(+ "Unsupported e_shentsize value (section header size): " + u_shentsize ++ " (expected " + supportedSHSize + ")");+ }+ }+ else {+ long hardLimit = Integer.toUnsignedLong(Integer.MAX_VALUE) / u_shentsize;+ int count = (int) constrainHeaderCount(u_shnum, e_shoff, u_shentsize, hardLimit,+ "Section Header");+ shnumTruncated = hasHeaderFragment(u_shnum, e_shoff, u_shentsize, hardLimit,+ "Section Header") ||+ (count != shnum);+ shnum = count;+ }}++ // commit final program and section header counts+ e_phnum = phnum;e_shnum = shnum;int shstrndx = reader.readNextUnsignedShort();@@ -184,6 +283,70 @@ public class ElfHeader implements StructConverter {}}+ /**+ * Constrain number of header elements based upon file bounds and hard limits.+ *+ * @param headerCount header count as specified by another header field (unsigned)+ * @param headerTableOffset starting offset of header table+ * @param headerSize size of each header element+ * @param hardLimit hard limit for maximum number of headers in table (-1 no limit imposed)+ * @param headerType type of header (used for logging)+ * @return allowed header count+ */+ long constrainHeaderCount(long headerCount, long headerTableOffset, long headerSize,+ long hardLimit, String headerType) {+ // maxPossible allows one extra which may be truncated+ long availableSpace = provider.length() - headerTableOffset;+ long maxPossible = availableSpace / headerSize;+ String limitType = "file capacity";+ if (hardLimit >= 0 && maxPossible >= hardLimit) {+ maxPossible = hardLimit;+ limitType = "hard limit";+ }+ else if ((availableSpace % headerSize) != 0) {+ // NOTE: If using an array for markup last partial element must be omitted+ // (see hasHeaderFragment)+ ++maxPossible; // allow for last header to be truncated+ }+ if (headerCount > maxPossible) {+ logError(headerType + " count " + headerCount ++ " exceeds " + limitType + " " + maxPossible + "; truncating");+ return maxPossible;+ }+ return headerCount;+ }++ /**+ * Used in conjunction with {@link #constrainHeaderCount(long, long, long, long, String)} to+ * determine if the last table entry to be loaded is a partial-entry.+ * <p>+ * NOTE: If a markup array datatype is applied to memory it may not fit in the memory+ * block and may need to be reduced by one element.+ *+ * @param headerCount header count as specified by another header field (unsigned)+ * @param headerTableOffset starting offset of header table+ * @param headerSize size of each header element+ * @param hardLimit hard limit for maximum number of headers in table (-1 no limit imposed)+ * @param headerType type of header (used for logging)+ * @return allowed header count+ */+ boolean hasHeaderFragment(long headerCount, long headerTableOffset, long headerSize,+ long hardLimit, String headerType) {++ long availableSpace = provider.length() - headerTableOffset;+ long completeEntryCount = availableSpace / headerSize;+ long permittedCount = headerCount;+ if (hardLimit >= 0) {+ permittedCount = Math.min(headerCount, hardLimit);+ }++ if (permittedCount > completeEntryCount && (availableSpace % headerSize) != 0) {+ logError(headerType + " has partial entry");+ return true;+ }+ return false;+ }+/*** Returns the unconstrained binary reader (i.e., reads beyond EOF* will return 0-bytes).@@ -207,7 +370,8 @@ public class ElfHeader implements StructConverter {private ElfSectionHeader getSection0() throws IOException {if (section0 == null && e_shoff != 0) {- if (!providerContainsRegion(e_shoff, e_shentsize)) {+ if (!providerContainsRegion(e_shoff,+ is64Bit() ? ElfSectionHeader.ELF64_SHDR_SIZE : ElfSectionHeader.ELF32_SHDR_SIZE)) {return null;}section0 = new ElfSectionHeader(reader.clone(e_shoff), this);@@ -218,33 +382,43 @@ public class ElfHeader implements StructConverter {/*** Read extended program header count (e_phnum) stored in first section header (ST_NULL)* sh_info field value. This is done to overcome the short value limitation of the- * e_phnum header field. Returned value is restricted to the range 0..0x7fffffff.- * @return extended program header count or 0 if not found or out of range+ * e_phnum header field.+ * @return extended program header count or 0 if not found or invalid* @throws IOException if file IO error occurs*/private int readExtendedProgramHeaderCount() throws IOException {ElfSectionHeader s = getSection0();- if (s != null && s.getType() == ElfSectionHeaderConstants.SHT_NULL) {- int val = s.getInfo();- return val < 0 ? 0 : val;+ if (s == null || s.getType() != ElfSectionHeaderConstants.SHT_NULL) {+ logError("Failed to load Section-0 required for extended program header count");+ return 0;}- return 0;+ int val = s.getInfo();+ if (val < 0) {+ logError("Invalid extended program header count: " + val);+ return 0;+ }+ return val;}/*** Read extended section header count (e_shnum) stored in first section header (ST_NULL)* sh_size field value. This is done to overcome the short value limitation of the- * e_shnum header field. Returned value is restricted to the range 0..0x7fffffff.- * @return extended section header count or 0 if not found or out of range+ * e_shnum header field.+ * @return extended section header count or 0 if not found or invalid* @throws IOException if file IO error occurs*/private int readExtendedSectionHeaderCount() throws IOException {ElfSectionHeader s = getSection0();- if (s != null && s.getType() == ElfSectionHeaderConstants.SHT_NULL) {- long val = s.getSize();- return (val < 0 || val > Integer.MAX_VALUE) ? 0 : (int) val;+ if (s == null || s.getType() != ElfSectionHeaderConstants.SHT_NULL) {+ logError("Failed to load Section-0 required for extended section header count");+ return 0;}- return 0;+ long val = s.getSize();+ if (val < 0 || val > Integer.MAX_VALUE) {+ logError("Invalid extended section header count: " + val);+ return 0;+ }+ return (int) val;}/**@@ -499,6 +673,15 @@ public class ElfHeader implements StructConverter {return;}+ long tableSize = section.getSize();+ if (tableSize <= 0) {+ logError("Relocation table section header '" ++ section.getNameAsString() ++ "' has invalid sh_size value (table size): 0x" ++ Long.toHexString(tableSize));+ return;+ }+int link = section.getLink(); // section index of associated symbol tableint info = section.getInfo(); // section index of section to which relocations apply (relocation offset base)@@ -541,16 +724,18 @@ public class ElfHeader implements StructConverter {format = TableFormat.RELR;}+ // Avoid use of unlimited reader for relocation tables to enforce EOFElfRelocationTable relocTable =- new ElfRelocationTable(reader, this, section, section.getOffset(),- section.getAddress(), section.getSize(), section.getEntrySize(),- addendTypeReloc, symbolTable, sectionToBeRelocated, format);+ new ElfRelocationTable(new BinaryReader(provider, hasLittleEndianHeaders), this,+ section, section.getOffset(), section.getAddress(), tableSize,+ section.getEntrySize(), addendTypeReloc, symbolTable, sectionToBeRelocated,+ format);relocationTableList.add(relocTable);}}- catch (NotFoundException e) {- errorConsumer.accept("Failed to process relocation section " ++ catch (NotFoundException | ElfException e) {+ logError("Failed to process relocation table " +section.getNameAsString() + ": " + e.getMessage());}}@@ -603,7 +788,7 @@ public class ElfHeader implements StructConverter {ElfProgramHeader relocTableLoadHeader = getProgramLoadHeaderContaining(relocTableAddr);if (relocTableLoadHeader == null) {- errorConsumer.accept("Failed to locate " + relocTableAddrType.name ++ logError("Failed to locate " + relocTableAddrType.name +" in memory at 0x" + Long.toHexString(relocTableAddr));return;}@@ -617,10 +802,26 @@ public class ElfHeader implements StructConverter {return; // skip reloc table previously parsed}}++ if (relocTableOffset < 0 || relocTableOffset > FILE_OFFSET_HARD_LIMIT ||+ relocTableOffset >= provider.length()) {+ logError("Invalid derived dynamic relocation table file offset: 0x" ++ Long.toHexString(relocTableOffset) + "; " + relocTableAddrType + ": 0x" ++ Long.toHexString(relocTableAddr));+ return;+ }+long tableEntrySize =relocEntrySizeType != null ? dynamicTable.getDynamicValue(relocEntrySizeType) : -1;long tableSize = dynamicTable.getDynamicValue(relocTableSizeType);+ if (tableSize <= 0) {+ logError("Dynamic relocation table has invalid " + relocTableSizeType ++ " (table size): 0x" ++ Long.toHexString(tableSize));+ return;+ }+ElfRelocationTable.TableFormat format = TableFormat.DEFAULT;if (relocTableAddrType == ElfDynamicType.DT_ANDROID_REL ||relocTableAddrType == ElfDynamicType.DT_ANDROID_RELA) {@@ -631,11 +832,16 @@ public class ElfHeader implements StructConverter {format = TableFormat.RELR;}+ // Avoid use of unlimited reader for relocation tables to enforce EOFElfRelocationTable relocTable =- new ElfRelocationTable(reader, this, null, relocTableOffset, relocTableAddr,- tableSize, tableEntrySize, addendTypeReloc, dynamicSymbolTable, null, format);+ new ElfRelocationTable(new BinaryReader(provider, hasLittleEndianHeaders), this,+ null, relocTableOffset, relocTableAddr, tableSize, tableEntrySize,+ addendTypeReloc, dynamicSymbolTable, null, format);relocationTableList.add(relocTable);}+ catch (ElfException e) {+ logError("Failed to process relocation table: " + e.getMessage());+ }catch (NotFoundException e) {// ignore - skip (required dynamic table value is missing)}@@ -713,7 +919,7 @@ public class ElfHeader implements StructConverter {return;}if (dynamicHeaders.length > 1) {- errorConsumer.accept("Multiple ELF Dynamic table program headers found");+ logError("Multiple ELF Dynamic table program headers found");}ElfSectionHeader[] dynamicSections = getSections(ElfSectionHeaderConstants.SHT_DYNAMIC);@@ -742,7 +948,7 @@ public class ElfHeader implements StructConverter {adjustAddressForPrelink(dynamicTable.getDynamicValue(ElfDynamicType.DT_STRTAB));}catch (NotFoundException e) {- errorConsumer.accept("ELF does not contain a dynamic string table (DT_STRTAB)");+ logError("ELF does not contain a dynamic string table (DT_STRTAB)");}}@@ -773,7 +979,7 @@ public class ElfHeader implements StructConverter {private ElfStringTable parseDynamicStringTable(long dynamicStringTableAddr) {if (!dynamicTable.containsDynamicValue(ElfDynamicType.DT_STRSZ)) {- errorConsumer.accept("Failed to parse DT_STRTAB, missing dynamic dependency");+ logError("Failed to parse DT_STRTAB, missing dynamic dependency");return null;}@@ -781,7 +987,7 @@ public class ElfHeader implements StructConverter {long stringTableSize = dynamicTable.getDynamicValue(ElfDynamicType.DT_STRSZ);if (dynamicStringTableAddr == 0) {- errorConsumer.accept("ELF Dynamic String Table of size " + stringTableSize ++ logError("ELF Dynamic String Table of size " + stringTableSize +" appears to have been stripped from binary");return null;}@@ -789,7 +995,7 @@ public class ElfHeader implements StructConverter {ElfProgramHeader stringTableLoadHeader =getProgramLoadHeaderContaining(dynamicStringTableAddr);if (stringTableLoadHeader == null) {- errorConsumer.accept("Failed to locate DT_STRTAB in memory at 0x" ++ logError("Failed to locate DT_STRTAB in memory at 0x" +Long.toHexString(dynamicStringTableAddr));return null;}@@ -803,7 +1009,8 @@ public class ElfHeader implements StructConverter {}}- private int[] getExtendedSymbolSectionIndexTable(ElfSectionHeader symbolTableSectionHeader) {+ private int[] getExtendedSymbolSectionIndexTable(ElfSectionHeader symbolTableSectionHeader,+ int symbolCount) {if (!hasExtendedSymbolSectionIndexTable) {return null;@@ -829,7 +1036,28 @@ public class ElfHeader implements StructConverter {}// determine number of 32-bit index elements for int[]- int count = (int) (symbolSectionIndexHeader.getSize() / 4);+ long size = symbolSectionIndexHeader.getSize();+ if (size <= 0 || size > Integer.MAX_VALUE) {+ logError(+ "Symbol table section index header '" + symbolSectionIndexHeader.getNameAsString() ++ "' has invalid size: 0x" + Long.toHexString(size));+ return null;+ }++ long indexTableOffset = symbolSectionIndexHeader.getOffset();+ if (symbolSectionIndexHeader.isInvalidOffset()) {+ logError(+ "Symbol table section index header '" + symbolSectionIndexHeader.getNameAsString() ++ "' has invalid offset value: 0x" ++ Long.toHexString(indexTableOffset));+ return null;+ }++ // Get constrained index entry count - limited by the number of symbol entries+ int count = (int) constrainHeaderCount(size / 4, indexTableOffset, 4, symbolCount,+ "Symbol section index");+ hasHeaderFragment(size / 4, indexTableOffset, 4, symbolCount, "Symbol section index"); // performs logging only+int[] indexTable = new int[count];try {@@ -839,7 +1067,7 @@ public class ElfHeader implements StructConverter {}}catch (IOException e) {- errorConsumer.accept("Failed to read symbol section index table at 0x" ++ logError("Failed to read symbol section index table at 0x" +Long.toHexString(symbolSectionIndexHeader.getOffset()) + ": " +symbolSectionIndexHeader.getNameAsString());}@@ -857,7 +1085,7 @@ public class ElfHeader implements StructConverter {adjustAddressForPrelink(dynamicTable.getDynamicValue(ElfDynamicType.DT_SYMTAB));}catch (NotFoundException e) {- errorConsumer.accept("ELF does not contain a dynamic symbol table (DT_SYMTAB)");+ logError("ELF does not contain a dynamic symbol table (DT_SYMTAB)");}}@@ -867,30 +1095,79 @@ public class ElfHeader implements StructConverter {if (symbolTableSectionHeader.getType() == ElfSectionHeaderConstants.SHT_SYMTAB ||symbolTableSectionHeader.getType() == ElfSectionHeaderConstants.SHT_DYNSYM) {// || symbolTableSectionHeader.getType() == ElfSectionHeaderConstants.SHT_SUNW_LDYNSYM) {++ long tableOffset = symbolTableSectionHeader.getOffset();if (symbolTableSectionHeader.isInvalidOffset()) {+ logError(+ "Symbol table section header '" ++ symbolTableSectionHeader.getNameAsString() ++ "' has invalid offset value: 0x" ++ Long.toHexString(tableOffset));continue;}- ElfSectionHeader stringTableSectionHeader =- sectionHeaders[symbolTableSectionHeader.getLink()];- ElfStringTable stringTable = getStringTable(stringTableSectionHeader);+ long tableSize = symbolTableSectionHeader.getSize();+ if (tableSize <= 0) {+ logError("Symbol table section header '" ++ symbolTableSectionHeader.getNameAsString() ++ "' has invalid sh_size value (table size): 0x" ++ Long.toHexString(tableSize));+ continue;+ }++ long entrySize = symbolTableSectionHeader.getEntrySize();+ if (!ElfSymbolTable.isValidEntrySize(is32Bit(), entrySize)) {+ logError("Symbol table section header '" ++ symbolTableSectionHeader.getNameAsString() ++ "' has unsupported sh_entsize value (table entry size): 0x" ++ Long.toHexString(entrySize));+ continue;+ }+ if ((tableSize % entrySize) != 0) {+ logError("Symbol table section header '" ++ symbolTableSectionHeader.getNameAsString() ++ "' has sh_size which is not a multiple of sh_entsize value");+ }- Msg.debug(this,- "Elf symbol table section " + symbolTableSectionHeader.getNameAsString() +- " linked to string table section " +- stringTableSectionHeader.getNameAsString());+ // Get constrained symbol count for table+ long expectedSymbolCount = tableSize / entrySize;+ long hardLimit = Integer.toUnsignedLong(Integer.MAX_VALUE) / entrySize;+ int symbolCount =+ (int) constrainHeaderCount(expectedSymbolCount, tableOffset, entrySize,+ hardLimit, "Symbol");+ boolean hasTruncatedSymbolTable =+ hasHeaderFragment(expectedSymbolCount, tableOffset, entrySize,+ hardLimit, "Symbol") || (symbolCount != expectedSymbolCount);++ ElfStringTable stringTable = null;+ int stringSectionIndex = symbolTableSectionHeader.getLink();+ if (stringSectionIndex >= 0 && stringSectionIndex < sectionHeaders.length) {+ ElfSectionHeader stringTableSectionHeader = sectionHeaders[stringSectionIndex];+ stringTable = getStringTable(stringTableSectionHeader);+ if (stringTable != null) {+ Msg.debug(this,+ "Elf symbol table section " ++ symbolTableSectionHeader.getNameAsString() ++ " linked to string table section " ++ stringTableSectionHeader.getNameAsString());+ }+ }+ if (stringTable == null) {+ logError("String table not found for symbol table: " ++ symbolTableSectionHeader.getNameAsString());+ }boolean isDyanmic = ElfSectionHeaderConstants.dot_dynsym.equals(symbolTableSectionHeader.getNameAsString());// get extended symbol section index table if presentint[] symbolSectionIndexTable =- getExtendedSymbolSectionIndexTable(symbolTableSectionHeader);+ getExtendedSymbolSectionIndexTable(symbolTableSectionHeader, symbolCount);ElfSymbolTable symbolTable =new ElfSymbolTable(reader, this, symbolTableSectionHeader,- symbolTableSectionHeader.getOffset(), symbolTableSectionHeader.getAddress(),- symbolTableSectionHeader.getSize(), symbolTableSectionHeader.getEntrySize(),+ tableOffset, symbolTableSectionHeader.getAddress(),+ (int) entrySize, symbolCount, hasTruncatedSymbolTable,stringTable, symbolSectionIndexTable, isDyanmic);symbolTableList.add(symbolTable);if (symbolTable.getAddressOffset() == dynamicSymbolTableAddr) {@@ -940,67 +1217,89 @@ public class ElfHeader implements StructConverter {long tableAddr = dynamicTable.getDynamicValue(ElfDynamicType.DT_SYMTAB);if (tableAddr == 0) {- errorConsumer.accept(- "ELF Dynamic String Table of size appears to have been stripped from binary");+ logError("Failed to process DT_SYMTAB with 0 value");+ return null;}- if (dynamicStringTable == null) {- errorConsumer.accept("Failed to process DT_SYMTAB, missing dynamic string table");+ tableAddr = adjustAddressForPrelink(tableAddr);+ long tableEntrySize = dynamicTable.getDynamicValue(ElfDynamicType.DT_SYMENT);++ ElfProgramHeader symbolTableLoadHeader = getProgramLoadHeaderContaining(tableAddr);+ if (symbolTableLoadHeader == null) {+ logError(+ "Failed to locate DT_SYMTAB in memory at 0x" + Long.toHexString(tableAddr));return null;}- if (tableAddr == 0) {+ // Create dynamic symbol table if not defined as a section+ long symbolTableOffset = symbolTableLoadHeader.getOffset(tableAddr);+ if (symbolTableOffset <= 0 || symbolTableOffset > FILE_OFFSET_HARD_LIMIT ||+ symbolTableOffset >= provider.length()) {+ logError("Dynamic symbol table has invalid DT_SYMTAB value (table offset): 0x" ++ Long.toHexString(symbolTableOffset));return null;}- tableAddr = adjustAddressForPrelink(tableAddr);- long tableEntrySize = dynamicTable.getDynamicValue(ElfDynamicType.DT_SYMENT);-// Use dynamic symbol hash table DT_HASH, DT_GNU_HASH, or DT_GNU_XHASH to// determine symbol table count/lengthlong hashTableAddr = dynamicTable.getDynamicValue(dynamicHashType);hashTableAddr = adjustAddressForPrelink(hashTableAddr);- ElfProgramHeader symbolTableLoadHeader = getProgramLoadHeaderContaining(tableAddr);- if (symbolTableLoadHeader == null) {- errorConsumer.accept(- "Failed to locate DT_SYMTAB in memory at 0x" + Long.toHexString(tableAddr));- return null;- }ElfProgramHeader hashTableLoadHeader = getProgramLoadHeaderContaining(hashTableAddr);if (hashTableLoadHeader == null) {- errorConsumer.accept(+ logError("Failed to locate DT_HASH, DT_GNU_HASH, or DT_GNU_XHASH in memory at 0x" +Long.toHexString(hashTableAddr));return null;}- // Create dynamic symbol table if not defined as a section- long symbolTableOffset = symbolTableLoadHeader.getOffset(tableAddr);+ if (!ElfSymbolTable.isValidEntrySize(is32Bit(), tableEntrySize)) {+ logError(+ "Dynamic symbol table has unsupported DT_SYMENT value (table entry size): 0x" ++ Long.toHexString(tableEntrySize));+ return null;+ }// determine symbol count from dynamic symbol hash table- int symCount;+ long expectedSymbolCount;long symbolHashTableOffset = hashTableLoadHeader.getOffset(hashTableAddr);if (dynamicHashType == ElfDynamicType.DT_GNU_HASH) {- symCount = deriveGnuHashDynamicSymbolCount(symbolHashTableOffset);+ expectedSymbolCount = deriveGnuHashDynamicSymbolCount(symbolHashTableOffset);}else if (dynamicHashType == ElfDynamicType.DT_GNU_XHASH) {- symCount = deriveGnuXHashDynamicSymbolCount(symbolHashTableOffset);+ expectedSymbolCount = deriveGnuXHashDynamicSymbolCount(symbolHashTableOffset);}else {// DT_HASH table, nchain corresponds is same as symbol count- symCount = reader.readInt(symbolHashTableOffset + 4); // nchain from DT_HASH+ expectedSymbolCount = reader.readUnsignedInt(symbolHashTableOffset + 4); // nchain from DT_HASH}- if (symCount == 0) {+ if (expectedSymbolCount <= 0) {+ logError("Unable to determine symbol count for dynamic symbol table at address 0x" ++ Long.toHexString(tableAddr));return null;}+ // Get constrained symbol count for table+ long hardLimit = Integer.toUnsignedLong(Integer.MAX_VALUE) / tableEntrySize;+ int symbolCount =+ (int) constrainHeaderCount(expectedSymbolCount, symbolTableOffset, tableEntrySize,+ hardLimit, "Symbol");+ boolean hasTruncatedSymbolTable =+ hasHeaderFragment(expectedSymbolCount, symbolTableOffset, tableEntrySize,+ hardLimit, "Symbol") || (symbolCount != expectedSymbolCount);++ if (dynamicStringTable == null) {+ logError("String table not found for dynamic symbol table at address 0x" ++ Long.toHexString(tableAddr));+ }+// NOTE: When parsed from dynamic table and not found via section header parse// it is assumed that the extended symbol section table is not used.return new ElfSymbolTable(reader, this, null, symbolTableOffset, tableAddr,- tableEntrySize * symCount, tableEntrySize, dynamicStringTable, null, true);+ (int) tableEntrySize, symbolCount, hasTruncatedSymbolTable, dynamicStringTable,+ null, true);}catch (NotFoundException e) {throw new AssertException(e);@@ -1013,15 +1312,15 @@ public class ElfHeader implements StructConverter {* @return dynamic symbol count (0 may be returned when processing error occurs)* @throws IOException file read error*/- private int deriveGnuHashDynamicSymbolCount(long gnuHashTableOffset) throws IOException {- int numBuckets = reader.readInt(gnuHashTableOffset);- int symbolBase = reader.readInt(gnuHashTableOffset + 4);+ private long deriveGnuHashDynamicSymbolCount(long gnuHashTableOffset) throws IOException {++ long numBuckets = reader.readUnsignedInt(gnuHashTableOffset);+ long symbolBase = reader.readUnsignedInt(gnuHashTableOffset + 4);long bloomSize = reader.readUnsignedInt(gnuHashTableOffset + 8);// int bloomShift = reader.readInt(gnuHashTableOffset + 12);long bloomWordSize = is64Bit() ? 8 : 4;long bucketsOffset = gnuHashTableOffset + 16 + (bloomWordSize * bloomSize);-// Identify restricted region which contains GNU hash table (arbitrary min-length)long maxOffset = getMaxOffsetForLoadedRegionContaining(gnuHashTableOffset, 12);if (maxOffset <= 0) {@@ -1030,8 +1329,8 @@ public class ElfHeader implements StructConverter {}long bucketOffset = bucketsOffset;- int maxSymbolIndex = 0;- for (int i = 0; i < numBuckets; i++) {+ long maxSymbolIndex = 0;+ for (long i = 0; i < numBuckets; i++) {if (bucketOffset < gnuHashTableOffset || bucketOffset > maxOffset) {logError("Error occured while inspecting GNU Hash table");return 0;@@ -1043,7 +1342,7 @@ public class ElfHeader implements StructConverter {bucketOffset += 4;}- int chainIndex = maxSymbolIndex - symbolBase;+ long chainIndex = maxSymbolIndex - symbolBase;++maxSymbolIndex;long chainOffset = bucketOffset + (4 * chainIndex); // chains immediately follow buckets@@ -1086,12 +1385,12 @@ public class ElfHeader implements StructConverter {* @return dynamic symbol count* @throws IOException file read error*/- private int deriveGnuXHashDynamicSymbolCount(long gnuHashTableOffset) throws IOException {+ private long deriveGnuXHashDynamicSymbolCount(long gnuHashTableOffset) throws IOException {// Elf32_Word ngnusyms; // number of entries in chains (and xlat); dynsymcount=symndx+ngnusyms// Elf32_Word nbuckets; // number of hash table buckets// Elf32_Word symndx; // number of initial .dynsym entires skipped in chains[] (and xlat[])- int ngnusyms = reader.readInt(gnuHashTableOffset);- int symndx = reader.readInt(gnuHashTableOffset + 8);+ long ngnusyms = reader.readUnsignedInt(gnuHashTableOffset);+ long symndx = reader.readUnsignedInt(gnuHashTableOffset + 8);return symndx + ngnusyms;}@@ -1117,16 +1416,9 @@ public class ElfHeader implements StructConverter {}parsedSectionHeaders = true;- boolean missing = false;sectionHeaders = new ElfSectionHeader[e_shnum];for (int i = 0; i < e_shnum; ++i) {- long index = e_shoff + (i * e_shentsize);- if (!missing && !providerContainsRegion(index, e_shentsize)) {- int unreadCnt = e_shnum - i;- errorConsumer.accept(unreadCnt + " of " + e_shnum +- " section headers are truncated/missing from file");- missing = true;- }+ long index = e_shoff + (i * (long) e_shentsize);sectionHeaders[i] = new ElfSectionHeader(reader.clone(index), this);if (sectionHeaders[i].getType() == ElfSectionHeaderConstants.SHT_SYMTAB_SHNDX) {hasExtendedSymbolSectionIndexTable = true;@@ -1147,16 +1439,9 @@ public class ElfHeader implements StructConverter {}private void parseProgramHeaders() throws IOException {- boolean missing = false;programHeaders = new ElfProgramHeader[e_phnum];for (int i = 0; i < e_phnum; ++i) {- long index = e_phoff + (i * e_phentsize);- if (!missing && !providerContainsRegion(index, e_phentsize)) {- int unreadCnt = e_phnum - i;- errorConsumer.accept(unreadCnt + " of " + e_phnum +- " program headers are truncated/missing from file");- missing = true;- }+ long index = e_phoff + (i * (long) e_phentsize);programHeaders[i] = new ElfProgramHeader(reader.clone(index), this);}@@ -1374,7 +1659,7 @@ public class ElfHeader implements StructConverter {hasLittleEndianHeaders = false;}else if (bytes[ElfConstants.EI_DATA] != ElfConstants.ELF_DATA_LE) {- errorConsumer.accept("Invalid EI_DATA, assuming little-endian headers (EI_DATA=0x" ++ logError("Invalid EI_DATA, assuming little-endian headers (EI_DATA=0x" +Integer.toHexString(bytes[ElfConstants.EI_DATA]) + ")");}if (!hasLittleEndianHeaders && bytes[ElfConstants.EI_NIDENT] != 0) {@@ -1468,6 +1753,14 @@ public class ElfHeader implements StructConverter {return e_phnum;}+ /**+ * {@return true if {@link #getProgramHeaderCount()} was reduced or table entries were+ * truncated during parse due to constraints}+ */+ public boolean hasTruncatedProgramHeaders() {+ return phnumTruncated;+ }+/*** This member holds the program header table's file offset in bytes. If the file has no* program header table, this member holds zero.@@ -1496,6 +1789,14 @@ public class ElfHeader implements StructConverter {return e_shnum;}+ /**+ * {@return true if {@link #getSectionHeaderCount()} was reduced or table entries were truncated+ * during parse due to constraints}+ */+ public boolean hasTruncatedSectionHeaders() {+ return shnumTruncated;+ }+/*** This member holds the section header table's file offset in bytes. If the file has no section* header table, this member holds zero.diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfProgramHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfProgramHeader.javaindex 400852cf08..45efe9ecfa 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfProgramHeader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfProgramHeader.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.@@ -67,6 +67,9 @@ import ghidra.util.StringUtilities;public class ElfProgramHeaderimplements StructConverter, Comparable<ElfProgramHeader>, MemoryLoadable {+ static final int ELF64_PHDR_SIZE = 56;+ static final int ELF32_PHDR_SIZE = 32;+protected final ElfHeader header;private final int p_type;@@ -78,6 +81,8 @@ public class ElfProgramHeaderprivate final long p_memsz;private final long p_align;+ private boolean hasValidOffset; // may be revised with p_offset change+private final BinaryReader reader;/**@@ -120,6 +125,14 @@ public class ElfProgramHeader//and ".bss".//TODO Err.warn(this, "Program Header: extra bytes");}++ checkValidOffset();+ }++ private void checkValidOffset() {+ hasValidOffset = p_offset >= 0 && p_offset < ElfHeader.FILE_OFFSET_HARD_LIMIT &&+ (header.is64Bit() || p_offset != ElfConstants.ELF32_INVALID_OFFSET) &&+ p_offset < reader.getByteProvider().length();}/**@@ -308,7 +321,7 @@ public class ElfProgramHeader* @return true if this program header's offset is invalid*/public boolean isInvalidOffset() {- return p_offset < 0 || (header.is32Bit() && p_offset == ElfConstants.ELF32_INVALID_OFFSET);+ return !hasValidOffset;}/**@@ -340,6 +353,7 @@ public class ElfProgramHeader*/void setOffset(long offset) {this.p_offset = offset;+ checkValidOffset();}/**diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfRelocation.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfRelocation.javaindex 1d758042e1..b8da5807fb 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfRelocation.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfRelocation.java@@ -15,14 +15,15 @@*/package ghidra.app.util.bin.format.elf;+import java.io.EOFException;import java.io.IOException;import java.lang.reflect.Constructor;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;import ghidra.app.util.bin.format.elf.extend.ElfLoadAdapter;-import ghidra.app.util.bin.format.elf.relocation.ElfRelocationContext;import ghidra.app.util.bin.format.elf.relocation.AbstractElfRelocationHandler;+import ghidra.app.util.bin.format.elf.relocation.ElfRelocationContext;import ghidra.program.model.data.*;/**@@ -98,10 +99,11 @@ public class ElfRelocation implements StructConverter {* @param relocationIndex index of entry in relocation table* @param withAddend true if it's a RELA entry with addend, else false* @return ELF relocation object+ * @throws EOFException if file has insufficient data (out-of-bounds read error)* @throws IOException if an IO or parse error occurs*/static ElfRelocation createElfRelocation(BinaryReader reader, ElfHeader elfHeader,- int relocationIndex, boolean withAddend) throws IOException {+ int relocationIndex, boolean withAddend) throws EOFException, IOException {Class<? extends ElfRelocation> elfRelocationClazz = getElfRelocationClass(elfHeader);ElfRelocation elfRelocation = getInstance(elfRelocationClazz);elfRelocation.initElfRelocation(reader, elfHeader, relocationIndex, withAddend);@@ -173,10 +175,11 @@ public class ElfRelocation implements StructConverter {* @param elfHeader ELF header* @param relocationTableIndex index of relocation within relocation table* @param withAddend true if it's a RELA entry with addend, else false+ * @throws EOFException if file has insufficient data (out-of-bounds read error)* @throws IOException if an IO or parse error occurs*/protected void initElfRelocation(BinaryReader reader, ElfHeader elfHeader,- int relocationTableIndex, boolean withAddend) throws IOException {+ int relocationTableIndex, boolean withAddend) throws EOFException, IOException {this.is32bit = elfHeader.is32Bit();this.relocationIndex = relocationTableIndex;this.hasAddend = withAddend;@@ -215,8 +218,11 @@ public class ElfRelocation implements StructConverter {}}- private void readEntryData(BinaryReader reader) throws IOException {+ private void readEntryData(BinaryReader reader) throws EOFException, IOException {if (is32bit) {+ if (!ElfRelocationTable.isValidNextFileOffset(reader, hasAddend ? 12 : 8)) {+ throw new EOFException("Insufficient data");+ }this.r_offset = reader.readNextUnsignedInt();this.r_info = reader.readNextUnsignedInt();if (hasAddend) {@@ -224,6 +230,9 @@ public class ElfRelocation implements StructConverter {}}else {+ if (!ElfRelocationTable.isValidNextFileOffset(reader, hasAddend ? 24 : 16)) {+ throw new EOFException("Insufficient data");+ }this.r_offset = reader.readNextLong();this.r_info = reader.readNextLong();if (hasAddend) {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfRelocationTable.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfRelocationTable.javaindex 39bb77ffd7..b5ab7fd005 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfRelocationTable.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfRelocationTable.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.@@ -15,10 +15,13 @@*/package ghidra.app.util.bin.format.elf;+import java.io.EOFException;import java.io.IOException;import java.util.ArrayList;import java.util.List;+import javax.help.UnsupportedOperationException;+import ghidra.app.util.bin.BinaryReader;import ghidra.program.model.data.*;import ghidra.util.Msg;@@ -44,6 +47,8 @@ public class ElfRelocationTable implements ElfFileSection {private final long length;private final long entrySize;+ private boolean relocTableTruncated = false;+private final boolean addendTypeReloc;private final ElfHeader elfHeader;@@ -57,18 +62,20 @@ public class ElfRelocationTable implements ElfFileSection {* @param relocTableSection relocation table section header or null if associated with a dynamic table entry* @param fileOffset relocation table file offset* @param addrOffset memory address of relocation table (should already be adjusted for prelink)- * @param length length of relocation table in bytes+ * @param length length of relocation table in bytes (must be greater than 0)* @param entrySize size of each relocation entry in bytes* @param addendTypeReloc true if addend type relocation table* @param symbolTable associated symbol table (may be null if not applicable)* @param sectionToBeRelocated or null for dynamic relocation table* @param format table format+ * @throws ElfException if an invalid relocation entry size is specified* @throws IOException if an IO or parse error occurs*/public ElfRelocationTable(BinaryReader reader, ElfHeader header,ElfSectionHeader relocTableSection, long fileOffset, long addrOffset, long length,long entrySize, boolean addendTypeReloc, ElfSymbolTable symbolTable,- ElfSectionHeader sectionToBeRelocated, TableFormat format) throws IOException {+ ElfSectionHeader sectionToBeRelocated, TableFormat format)+ throws ElfException, IOException {this.elfHeader = header;this.relocTableSection = relocTableSection;@@ -83,6 +90,12 @@ public class ElfRelocationTable implements ElfFileSection {this.sectionToBeRelocated = sectionToBeRelocated;this.symbolTable = symbolTable;+ if (format != TableFormat.ANDROID && this.entrySize != getSupportedRelocationEntrySize()) {+ throw new ElfException(+ "Relocation table has unsupported entry size: 0x" ++ Long.toHexString(this.entrySize));+ }+BinaryReader relocReader = reader.clone(fileOffset);List<ElfRelocation> relocList;if (format == TableFormat.RELR) {@@ -98,6 +111,20 @@ public class ElfRelocationTable implements ElfFileSection {relocList.toArray(relocs);}+ private int getSupportedRelocationEntrySize() {+ if (format == TableFormat.RELR) {+ return elfHeader.is32Bit() ? 4 : 8;+ }+ if (format == TableFormat.DEFAULT) {+ if (elfHeader.is32Bit()) {+ return addendTypeReloc ? 12 : 8;+ }+ return addendTypeReloc ? 24 : 16;+ }+ throw new UnsupportedOperationException(+ "Unsupported format for entry size check: " + format);+ }+/*** Determine if required symbol table is missing. If so, relocations may not be processed.* @return true if required symbol table is missing, else false@@ -114,19 +141,30 @@ public class ElfRelocationTable implements ElfFileSection {}private List<ElfRelocation> parseStandardRelocations(BinaryReader reader) throws IOException {+List<ElfRelocation> relocations = new ArrayList<>();- int nRelocs = (int) (length / entrySize);- for (int relocationIndex = 0; relocationIndex < nRelocs; ++relocationIndex) {- relocations.add(ElfRelocation.createElfRelocation(reader, elfHeader, relocationIndex,- addendTypeReloc));+ long expectedCount = length / entrySize;++ long hardLimit = Integer.toUnsignedLong(Integer.MAX_VALUE) / entrySize;+ int count = (int) elfHeader.constrainHeaderCount(expectedCount, fileOffset, entrySize,+ hardLimit, "Relocation Table");+ relocTableTruncated = elfHeader.hasHeaderFragment(expectedCount, fileOffset, entrySize,+ hardLimit, "Relocation Table") || count != expectedCount;++ try {+ for (int relocationIndex = 0; relocationIndex < count; ++relocationIndex) {+ relocations.add(ElfRelocation.createElfRelocation(reader, elfHeader, relocationIndex,+ addendTypeReloc));+ }+ }+ catch (EOFException e) {+ // return truncated list+ relocTableTruncated = true;+ elfHeader.logError("Truncated ELF Relocation table due to unexpected EOF");}return relocations;}- private long readNextRelrEntry(BinaryReader reader) throws IOException {- return entrySize == 8 ? reader.readNextLong() : reader.readNextUnsignedInt();- }-private long addRelrEntry(long offset, List<ElfRelocation> relocList) throws IOException {relocList.add(ElfRelocation.createElfRelocation(elfHeader, relocList.size(),addendTypeReloc, offset, 0, 0));@@ -151,30 +189,63 @@ public class ElfRelocationTable implements ElfFileSection {private List<ElfRelocation> parseRelrRelocations(BinaryReader reader) throws IOException {// NOTE: Current implementation supports an entrySize of 8 or 4. This could be- // made more flexable if needed (applies to ElfRelrRelocationTableDataType as well)+ // made more flexible if needed (applies to ElfRelrRelocationTableDataType as well)List<ElfRelocation> relocList = new ArrayList<>();+ if (length == 0) {+ return relocList;+ }long remaining = length; // limit to number of bytes specified for RELR table- long offset = readNextRelrEntry(reader);- offset = addRelrEntry(offset, relocList);- remaining -= entrySize;+ try {+ long offset = readNextRelrEntry(reader);+ offset = addRelrEntry(offset, relocList);+ remaining -= entrySize;- while (remaining > 0) {- long nextValue = readNextRelrEntry(reader);- if ((nextValue & 1) == 1) {- offset = addRelrEntries(offset, nextValue, relocList);- }- else {- offset = addRelrEntry(nextValue, relocList);+ while (remaining > 0) {+ long nextValue = readNextRelrEntry(reader);+ if ((nextValue & 1) == 1) {+ offset = addRelrEntries(offset, nextValue, relocList);+ }+ else {+ offset = addRelrEntry(nextValue, relocList);+ }+ remaining -= entrySize;}- remaining -= entrySize;+ }+ catch (EOFException e) {+ // return truncated/incomplete relocation list+ relocTableTruncated = true;+ elfHeader.logError("Truncated ELF RELR Relocation table due to unexpected EOF");}return relocList;}+ private long readNextRelrEntry(BinaryReader reader) throws EOFException, IOException {+ if (!isValidNextFileOffset(reader, entrySize == 8 ? 8 : 4)) {+ throw new EOFException("Insufficient data");+ }+ return entrySize == 8 ? reader.readNextLong() : reader.readNextUnsignedInt();+ }++ static boolean isValidFileOffset(BinaryReader reader, long offset, long len) {+ if (len <= 0) {+ throw new IllegalArgumentException();+ }+ long endOffset = offset + len - 1;+ return offset >= 0 && endOffset >= offset && endOffset < reader.length();+ }++ static boolean isValidNextFileOffset(BinaryReader reader, long len) {+ return isValidFileOffset(reader, reader.getPointerIndex(), len);+ }+private List<ElfRelocation> parseAndroidRelocations(BinaryReader reader) throws IOException {+ if (!isValidNextFileOffset(reader, 4)) {+ throw new IOException(+ "Android relocation table not found at file offset " + reader.getPointerIndex());+ }String identifier = reader.readNextAsciiString(4);if (!"APS2".equals(identifier)) {throw new IOException("Unsupported Android relocation table format");@@ -185,6 +256,11 @@ public class ElfRelocationTable implements ElfFileSection {try {int relocationIndex = 0;long remainingRelocations = reader.readNext(LEB128::signed); // reloc_count+ if (remainingRelocations <= 0) {+ elfHeader.logError(+ "Unexpected ELF Android APS2 relocation count " + remainingRelocations);+ return relocations;+ }long offset = reader.readNext(LEB128::signed); // reloc_baseOffsetlong addend = 0;@@ -194,8 +270,13 @@ public class ElfRelocationTable implements ElfFileSection {// group_sizelong groupSize = reader.readNext(LEB128::signed);+ if (groupSize <= 0) {+ elfHeader.logError(+ "Unexpected ELF Android APS2 Group relocation count " + groupSize);+ break;+ }if (groupSize > remainingRelocations) {- elfHeader.logError("Group relocation count " + groupSize ++ elfHeader.logError("ELF Android APS2 Group relocation count " + groupSize +" exceeded total count " + remainingRelocations);break;}@@ -220,7 +301,7 @@ public class ElfRelocationTable implements ElfFileSection {if (groupHasAddend && groupedByAddend) {if (!addendTypeReloc) {elfHeader.logError(- "ELF Android Relocation processing failed. Unexpected r_addend in android.rel section");+ "ELF Android APS2 Relocation processing failed. Unexpected r_addend in android.rel section");return List.of();}// group_addend (optional)@@ -253,7 +334,13 @@ public class ElfRelocationTable implements ElfFileSection {remainingRelocations -= groupSize;}}+ catch (EOFException e) {+ // return truncated/incomplete relocation list+ relocTableTruncated = true;+ elfHeader.logError("Truncated Android relocation table due to unexpected EOF");+ }catch (IOException e) {+ elfHeader.logError("Error reading Android relocation table: " + e.getMessage());Msg.error(this, "Error reading relocations.", e);}@@ -295,6 +382,14 @@ public class ElfRelocationTable implements ElfFileSection {return relocs.length;}+ /**+ * {@return true if {@link #getRelocationCount()} was reduced or table entries were truncated+ * during parse due to constraints}+ */+ public boolean isParsedRelocationCountReduced() {+ return relocTableTruncated;+ }+/*** Returns the associated symbol table.* A relocation object contains a symbol index.@@ -340,6 +435,9 @@ public class ElfRelocationTable implements ElfFileSection {@Overridepublic DataType toDataType() throws IOException {+ if (length > Integer.MAX_VALUE) {+ return null;+ }if (format == TableFormat.RELR) {String relrStructureName = "Elf_RelrRelocationTable_" + Long.toHexString(addrOffset);return new ElfRelrRelocationTableDataType(relrStructureName, (int) length,@@ -352,7 +450,7 @@ public class ElfRelocationTable implements ElfFileSection {ElfRelocation relocationRepresentative =ElfRelocation.createElfRelocation(elfHeader, -1, addendTypeReloc, 0, 0, 0);DataType relocEntryDataType = relocationRepresentative.toDataType();- return new ArrayDataType(relocEntryDataType, (int) (length / entrySize), (int) entrySize);+ return new ArrayDataType(relocEntryDataType, relocs.length, -1);}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfSectionHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfSectionHeader.javaindex c58226bdbe..6a58ac2c01 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfSectionHeader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfSectionHeader.java@@ -72,6 +72,9 @@ import ghidra.util.StringUtilities;public class ElfSectionHeader implements StructConverter, MemoryLoadable {+ static final int ELF64_SHDR_SIZE = 64;+ static final int ELF32_SHDR_SIZE = 40;+private final BinaryReader reader;private final ElfHeader header;@@ -86,6 +89,8 @@ public class ElfSectionHeader implements StructConverter, MemoryLoadable {private final long sh_addralign;private final long sh_entsize;+ private final boolean hasValidOffset;+private String name; // delayed initializationprivate ElfCompressedSectionHeader compressedHeader;@@ -133,7 +138,10 @@ public class ElfSectionHeader implements StructConverter, MemoryLoadable {if ((sh_flags & ElfSectionHeaderConstants.SHF_COMPRESSED) != 0) {compressedHeader = readCompressedSectionHeader();}- //checkSize();++ hasValidOffset = sh_offset >= 0 && sh_offset < ElfHeader.FILE_OFFSET_HARD_LIMIT &&+ (header.is64Bit() || sh_offset != ElfConstants.ELF32_INVALID_OFFSET) &&+ sh_offset < reader.getByteProvider().length();}private ElfCompressedSectionHeader readCompressedSectionHeader() {@@ -377,8 +385,7 @@ public class ElfSectionHeader implements StructConverter, MemoryLoadable {* @return true if this section header's offset is invalid*/public boolean isInvalidOffset() {- return sh_offset < 0 ||- (header.is32Bit() && sh_offset == ElfConstants.ELF32_INVALID_OFFSET);+ return !hasValidOffset;}/**diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfSymbol.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfSymbol.javaindex 2b09a65ce4..af59699b73 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfSymbol.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfSymbol.java@@ -162,7 +162,7 @@ public class ElfSymbol {// FIXME: handle extended section indexingint uSectionIndex = Short.toUnsignedInt(st_shndx);if (Short.compareUnsigned(st_shndx, ElfSectionHeaderConstants.SHN_LORESERVE) < 0 &&- uSectionIndex < sections.length) {+ uSectionIndex >= 0 && uSectionIndex < sections.length) {ElfSectionHeader section = sections[uSectionIndex];nameAsString = section.getNameAsString();}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfSymbolTable.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfSymbolTable.javaindex ca19b41915..03d8c318a1 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfSymbolTable.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/elf/ElfSymbolTable.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.@@ -29,15 +29,20 @@ import ghidra.util.exception.DuplicateNameException;*/public class ElfSymbolTable implements ElfFileSection {- private final ElfStringTable stringTable;+ static final int ELF64_SYMENT_SIZE = 24;+ static final int ELF32_SYMENT_SIZE = 16;++ private final ElfStringTable stringTable; // may be nullprivate final ElfSectionHeader symbolTableSection; // may be nullprivate final int[] symbolSectionIndexTable;private final long fileOffset;private final long addrOffset;private final long length;- private final long entrySize;+ private final int entrySize;private final int symbolCount;+ private boolean symbolTableTruncated;+private final boolean is32bit;private final boolean isDynamic;@@ -48,10 +53,12 @@ public class ElfSymbolTable implements ElfFileSection {* @param reader byte reader (reader is not retained and position is unaffected)* @param header elf header* @param symbolTableSection string table section header or null if associated with a dynamic table entry- * @param fileOffset symbol table file offset+ * or unable to locate string table.+ * @param fileOffset symbol table file offset (must be pre-validated)* @param addrOffset memory address of symbol table (should already be adjusted for prelink)- * @param length length of symbol table in bytes of -1 if unknown* @param entrySize size of each symbol entry in bytes+ * @param symbolCount number of symbol entries within symbol table+ * @param symbolTableTruncated true if symbol count was reduced during parse due to constraints* @param stringTable associated string table* @param symbolSectionIndexTable extended symbol section index table (may be null, used when* symbol <code>st_shndx == SHN_XINDEX</code>). See@@ -60,24 +67,28 @@ public class ElfSymbolTable implements ElfFileSection {* @throws IOException if an IO or parse error occurs*/public ElfSymbolTable(BinaryReader reader, ElfHeader header,- ElfSectionHeader symbolTableSection, long fileOffset, long addrOffset, long length,- long entrySize, ElfStringTable stringTable, int[] symbolSectionIndexTable,+ ElfSectionHeader symbolTableSection, long fileOffset, long addrOffset,+ int entrySize, int symbolCount, boolean symbolTableTruncated,+ ElfStringTable stringTable,+ int[] symbolSectionIndexTable,boolean isDynamic) throws IOException {+ this.is32bit = header.is32Bit();+this.symbolTableSection = symbolTableSection;this.fileOffset = fileOffset;this.addrOffset = addrOffset;- this.length = length;this.entrySize = entrySize;+ this.symbolCount = symbolCount;+ this.length = (long) entrySize * (long) symbolCount;+ this.symbolTableTruncated = symbolTableTruncated;this.stringTable = stringTable;- this.is32bit = header.is32Bit();this.symbolSectionIndexTable = symbolSectionIndexTable;this.isDynamic = isDynamic;BinaryReader symTableReader = reader.clone(fileOffset);List<ElfSymbol> symbolList = new ArrayList<>();- symbolCount = (int) (length / entrySize);// load the all the symbol entries first, don't initialize the string name// that will be done later to help localize memory access@@ -97,14 +108,27 @@ public class ElfSymbolTable implements ElfFileSection {.collect(Collectors.toList());// initialize the Symbol string names from string table- for (ElfSymbol sym : sortedList) {- sym.initSymbolName(symTableReader, stringTable);+ if (stringTable != null) {+ for (ElfSymbol sym : sortedList) {+ sym.initSymbolName(symTableReader, stringTable);+ }}symbols = new ElfSymbol[symbolList.size()];symbolList.toArray(symbols);}+ /**+ * Check if specified symbol entry size is valid and may be cast to a 32-bit integer+ * @param is32bit true if 32-bit ELF, false of 64-bit Elf+ * @param entrySize symbol entry size+ * @return true if entry size is valid+ */+ static boolean isValidEntrySize(boolean is32bit, long entrySize) {+ int minEntrySize = is32bit ? ELF32_SYMENT_SIZE : ELF64_SYMENT_SIZE;+ return entrySize >= minEntrySize && entrySize <= Integer.MAX_VALUE;+ }+/*** Returns true if this is the dynamic symbol table* @return true if this is the dynamic symbol table@@ -114,8 +138,7 @@ public class ElfSymbolTable implements ElfFileSection {}/**- * Returns the associated string table section.- * @return the associated string table section+ * {@return associated string table section or null if string table not found}*/public ElfStringTable getStringTable() {return stringTable;@@ -128,6 +151,14 @@ public class ElfSymbolTable implements ElfFileSection {return symbolCount;}+ /**+ * {@return true if {@link #getSymbolCount()} was reduced or table entries were truncated+ * during parse due to constraints}+ */+ public boolean hasTruncatedSymbolTable() {+ return symbolTableTruncated;+ }+/*** Returns all of the symbols defined in this symbol table.* @return all of the symbols defined in this symbol table@@ -294,6 +325,9 @@ public class ElfSymbolTable implements ElfFileSection {@Overridepublic DataType toDataType() throws DuplicateNameException {+ if (length > Integer.MAX_VALUE) {+ return null;+ }String dtName = is32bit ? "Elf32_Sym" : "Elf64_Sym";Structure struct = new StructureDataType(new CategoryPath("/ELF"), dtName, 0);struct.add(DWORD, "st_name", null);@@ -316,6 +350,6 @@ public class ElfSymbolTable implements ElfFileSection {struct.add(new ArrayDataType(ByteDataType.dataType, sizeRemaining, 1), "st_unknown",null);}- return new ArrayDataType(struct, (int) (length / entrySize), (int) entrySize);+ return new ArrayDataType(struct, symbolCount, -1);}}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.javaindex 4c39fe862e..448c24182c 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/opinion/ElfProgramBuilder.java@@ -1180,7 +1180,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {private void markupProgramHeaders(TaskMonitor monitor) {int headerCount = elf.getProgramHeaderCount();- int size = elf.e_phentsize() * headerCount;+ long size = (long) elf.e_phentsize() * headerCount;if (size == 0) {return;}@@ -1190,7 +1190,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {Structure phStructDt = (Structure) elf.getProgramHeaders()[0].toDataType();phStructDt = phStructDt.clone(program.getDataTypeManager());- Array arrayDt = new ArrayDataType(phStructDt, headerCount, size);+ Array arrayDt = new ArrayDataType(phStructDt, headerCount, -1);Address headerAddr = findLoadAddress(elf.e_phoff(), size);@@ -1209,8 +1209,17 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {addElfHeaderReferenceMarkup(elf.getPhoffComponentOrdinal(), headerAddr);- Data array =- createData(headerAddr, program.getDataTypeManager().resolve(arrayDt, null));+ if (elf.e_phentsize() != phStructDt.getAlignedLength()) {+ String msg =+ "Unable to markup ELF Program Header table due to irregular 'e_phentsize' value: " ++ elf.e_phentsize();+ listing.setComment(headerAddr, CommentType.PRE, msg);+ log(msg);+ return;+ }++ Data array = applyMarkupData(headerAddr, arrayDt, "Program Headers",+ elf.hasTruncatedProgramHeaders());if (array == null) {return;}@@ -1223,6 +1232,9 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {monitor.incrementProgress(1);Data d = array.getComponent(i);+ if (d == null) {+ break; // assume truncated markup+ }d.setComment(CommentType.EOL, programHeaders[i].getComment());if (programHeaders[i].getType() == ElfProgramHeaderConstants.PT_NULL) {continue;@@ -1247,7 +1259,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {private void markupSectionHeaders(TaskMonitor monitor) {int headerCount = elf.getSectionHeaderCount();- int size = elf.e_shentsize() * headerCount;+ long size = (long) elf.e_shentsize() * headerCount;if (size == 0) {return;}@@ -1257,7 +1269,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {Structure shStructDt = (Structure) elf.getSections()[0].toDataType();shStructDt = shStructDt.clone(program.getDataTypeManager());- Array arrayDt = new ArrayDataType(shStructDt, headerCount, elf.e_shentsize());+ Array arrayDt = new ArrayDataType(shStructDt, headerCount, -1);Address headerAddr = findLoadAddress(elf.e_shoff(), size);@@ -1276,8 +1288,17 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {addElfHeaderReferenceMarkup(elf.getShoffComponentOrdinal(), headerAddr);- Data array =- createData(headerAddr, program.getDataTypeManager().resolve(arrayDt, null));+ if (elf.e_shentsize() != shStructDt.getAlignedLength()) {+ String msg =+ "Unable to markup ELF Section Header table due to irregular 'e_shentsize' value: " ++ elf.e_shentsize();+ listing.setComment(headerAddr, CommentType.PRE, msg);+ log(msg);+ return;+ }++ Data array = applyMarkupData(headerAddr, arrayDt, "Section Headers",+ elf.hasTruncatedSectionHeaders());if (array == null) {return;}@@ -1289,6 +1310,9 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {monitor.incrementProgress(1);Data d = array.getComponent(i);+ if (d == null) {+ break; // assume truncated markup+ }String comment = sections[i].getNameAsString();String type = sections[i].getTypeAsString();if (type != null) {@@ -1328,14 +1352,8 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {private void markupRelocationTable(Address relocTableAddr, ElfRelocationTable relocTable,TaskMonitor monitor) {try {- DataType dataType = relocTable.toDataType();- if (dataType != null) {- listing.createData(relocTableAddr, dataType);- }- else {- listing.setComment(relocTableAddr, CommentType.PRE,- "ELF Relocation Table (markup not yet supported)");- }+ applyMarkupData(relocTableAddr, relocTable.toDataType(), "Relocation Table",+ relocTable.isParsedRelocationCountReduced());}catch (Exception e) {log("Failed to properly markup relocation table: " + getMessage(e));@@ -1577,8 +1595,7 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {symbolTableAddr = findLoadAddress(symbolTableSection, 0);}else {- symbolTableAddr =- findLoadAddress(elfSymbolTable.getFileOffset(), elfSymbolTable.getLength());+ symbolTableAddr = findLoadAddress(elfSymbolTable.getFileOffset(), 1);}ElfSymbol[] symbols = elfSymbolTable.getSymbols();@@ -2608,16 +2625,75 @@ class ElfProgramBuilder extends MemorySectionResolver implements ElfLoadHelper {}}+ /**+ * Create listing markup data with possible array truncation.+ * @param addr listing address+ * @param dt datatype to be applied+ * @param description brief markup type description for errors and applied comment(s)+ * @param truncated true if parsed data had been truncated (as reflected by dt length)+ * @return applied data or null+ */+ private Data applyMarkupData(Address addr, DataType dt, String description, boolean truncated) {+ AddressRange rangeContainingStart =+ program.getMemory().getAllInitializedAddressSet().getRangeContaining(addr);+ if (rangeContainingStart == null) {+ log("Failed to markup " + description + " at " + addr ++ " (initialized memory not found)");+ return null;+ }++ if (dt == null) {+ listing.setComment(addr, CommentType.PRE,+ "ELF " + description + " markup not supported or table is too large)");+ return null;+ }++ dt = dt.clone(program.getDataTypeManager()); // ensure we have proper data organization++ // Check array markup case which may require truncation+ if (dt instanceof Array arrayDt) {+ Address endAddr;+ try {+ endAddr = addr.addNoWrap(dt.getLength() - 1);+ truncated |= !rangeContainingStart.contains(endAddr);+ }+ catch (AddressOverflowException e) {+ endAddr = addr.getAddressSpace().getMaxAddress();+ truncated = true;+ }+ rangeContainingStart = rangeContainingStart.intersectRange(addr, endAddr);++ long availSpace = rangeContainingStart.getMaxAddress().subtract(addr) + 1;+ DataType elementDt = arrayDt.getDataType();+ int reducedElementCount = (int) (availSpace / elementDt.getAlignedLength());+ if (reducedElementCount == 0) {+ return null;+ }+ dt = new ArrayDataType(elementDt, reducedElementCount, -1,+ program.getDataTypeManager());+ }++ Data data = createData(addr, dt);+ if (data != null && truncated) {+ listing.setComment(addr, CommentType.PRE,+ "WARNING: Incomplete markup! " + description + " has been truncated");+ }+ return data;+ }+private void markupSymbolTable(Address symbolTableAddr, ElfSymbolTable symbolTable,TaskMonitor monitor) {Data array = null;try {- array = listing.createData(symbolTableAddr, symbolTable.toDataType());+ array = applyMarkupData(symbolTableAddr, symbolTable.toDataType(), "Symbol Table",+ symbolTable.hasTruncatedSymbolTable());}catch (Exception e) {- log("Failed to properly markup symbol table at " + symbolTableAddr + ": " +- getMessage(e));+ // ignore+ }++ if (array == null) {return;}diff --git a/Ghidra/Processors/MIPS/src/main/java/ghidra/app/util/bin/format/elf/relocation/MIPS_Elf64Relocation.java b/Ghidra/Processors/MIPS/src/main/java/ghidra/app/util/bin/format/elf/relocation/MIPS_Elf64Relocation.javaindex ea2864d2dc..4311e949b3 100644--- a/Ghidra/Processors/MIPS/src/main/java/ghidra/app/util/bin/format/elf/relocation/MIPS_Elf64Relocation.java+++ b/Ghidra/Processors/MIPS/src/main/java/ghidra/app/util/bin/format/elf/relocation/MIPS_Elf64Relocation.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.@@ -15,6 +15,7 @@*/package ghidra.app.util.bin.format.elf.relocation;+import java.io.EOFException;import java.io.IOException;import ghidra.app.util.bin.BinaryReader;@@ -42,7 +43,7 @@ public class MIPS_Elf64Relocation extends ElfRelocation {@Overrideprotected void initElfRelocation(BinaryReader reader, ElfHeader elfHeader,- int relocationTableIndex, boolean withAddend) throws IOException {+ int relocationTableIndex, boolean withAddend) throws EOFException, IOException {super.initElfRelocation(reader, elfHeader, relocationTableIndex, withAddend);long info = getRelocationInfo();if (elfHeader.isLittleEndian()) {