Ghidra is a software reverse engineering (SRE) framework
GP-3565: More Mach-O markup improvements
Ryan Kurtz5e66a127eaa2
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/CodeSignatureCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/CodeSignatureCommand.javanew file mode 100644index 0000000000..7481c6c29c--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/CodeSignatureCommand.java@@ -0,0 +1,75 @@+/* ###+ * 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.app.util.bin.format.macho.commands;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.format.macho.MachHeader;+import ghidra.app.util.bin.format.macho.commands.codesignature.CodeSignatureBlobParser;+import ghidra.app.util.bin.format.macho.commands.codesignature.CodeSignatureGenericBlob;+import ghidra.app.util.importer.MessageLog;+import ghidra.program.model.address.Address;+import ghidra.program.model.data.DataUtilities;+import ghidra.program.model.listing.Data;+import ghidra.program.model.listing.Program;+import ghidra.util.exception.CancelledException;+import ghidra.util.task.TaskMonitor;++/**+ * Represents a LC_CODE_SIGNATURE command.+ */+public class CodeSignatureCommand extends LinkEditDataCommand {++ private CodeSignatureGenericBlob blob;++ /**+ * Creates and parses a new {@link CodeSignatureCommand}+ *+ * @param loadCommandReader A {@link BinaryReader reader} that points to the start of the load+ * command+ * @param dataReader A {@link BinaryReader reader} that can read the data that the load command+ * references. Note that this might be in a different underlying provider.+ * @throws IOException if an IO-related error occurs while parsing+ */+ CodeSignatureCommand(BinaryReader loadCommandReader, BinaryReader dataReader)+ throws IOException {+ super(loadCommandReader, dataReader);+ dataReader.setLittleEndian(false); // Everything that follows is always big-endian+ blob = CodeSignatureBlobParser.parse(dataReader);+ }++ @Override+ public void markup(Program program, MachHeader header, String source, TaskMonitor monitor,+ MessageLog log) throws CancelledException {+ Address addr = fileOffsetToAddress(program, header, dataoff, datasize);+ if (addr == null) {+ return;+ }+ super.markup(program, header, source, monitor, log);++ try {+ Data d = DataUtilities.createData(program, addr, blob.toDataType(), -1,+ DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ LoadCommand.setEndian(d, true);+ blob.markup(program, addr, header, monitor, log);+ }+ catch (Exception e) {+ log.appendMsg(CodeSignatureCommand.class.getSimpleName(),+ "Failed to markup: " + getContextualName(source, null));+ }+ }+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedFixupsCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedFixupsCommand.javaindex e3c0628759..11b4534cfe 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedFixupsCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/DyldChainedFixupsCommand.java@@ -75,29 +75,7 @@ public class DyldChainedFixupsCommand extends LinkEditDataCommand {try {DataUtilities.createData(program, addr, chainHeader.toDataType(), -1,DataUtilities.ClearDataMode.CHECK_FOR_SPACE);-- Address segsAddr = addr.add(chainHeader.getStartsOffset());- DyldChainedStartsInImage chainedStartsInImage = chainHeader.getChainedStartsInImage();- DataUtilities.createData(program, segsAddr, chainedStartsInImage.toDataType(), -1,- DataUtilities.ClearDataMode.CHECK_FOR_SPACE);-- int[] segInfoOffset = chainedStartsInImage.getSegInfoOffset();- List<DyldChainedStartsInSegment> chainedStarts =- chainedStartsInImage.getChainedStarts();- int skipCount = 0;- for (int i = 0; i < segInfoOffset.length; i++) {- if (segInfoOffset[i] == 0) {- // The chainStarts list doesn't have entries for 0 offsets, so we must keep- // track of the index differences between the 2 entities- skipCount++;- continue;- }- DyldChainedStartsInSegment startsInSeg = chainedStarts.get(i - skipCount);- if (startsInSeg != null) {- DataUtilities.createData(program, segsAddr.add(segInfoOffset[i]),- startsInSeg.toDataType(), -1, DataUtilities.ClearDataMode.CHECK_FOR_SPACE);- }- }+ chainHeader.markup(program, addr, header, monitor, log);}catch (Exception e) {log.appendMsg(DyldChainedFixupsCommand.class.getSimpleName(),diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommand.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommand.javaindex 46fd65296e..e4973474d9 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommand.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommand.java@@ -22,9 +22,11 @@ import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;import ghidra.app.util.bin.format.macho.MachHeader;import ghidra.app.util.importer.MessageLog;+import ghidra.docking.settings.SettingsDefinition;import ghidra.program.flatapi.FlatProgramAPI;import ghidra.program.model.address.Address;import ghidra.program.model.address.AddressSpace;+import ghidra.program.model.data.EndianSettingsDefinition;import ghidra.program.model.listing.*;import ghidra.util.exception.CancelledException;import ghidra.util.task.TaskMonitor;@@ -201,6 +203,28 @@ public abstract class LoadCommand implements StructConverter {return null;}+ /**+ * Recursively sets the given {@link Data} and its components to big/little endian+ *+ * @param data The {@link Data}+ * @param bigEndian True to set to big endian; false to set to little endian+ * @throws Exception if there was a problem setting the endianness+ */+ public static void setEndian(Data data, boolean bigEndian) throws Exception {+ for (int i = 0; i < data.getNumComponents(); i++) {+ Data component = data.getComponent(i);+ SettingsDefinition[] settings = component.getDataType().getSettingsDefinitions();+ for (int j = 0; j < settings.length; j++) {+ if (settings[j] instanceof EndianSettingsDefinition endianSetting) {+ endianSetting.setBigEndian(component, true);+ }+ }+ for (int j = 0; j < component.getNumComponents(); j++) {+ setEndian(component.getComponent(j), bigEndian);+ }+ }+ }+//-------------------Legacy code to support Raw Binary markup----------------------------------/*** Marks-up this {@link LoadCommand} with data structures and comments. Assumes the programdiff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommandFactory.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommandFactory.javaindex 409390d17b..f5c27f486f 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommandFactory.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/LoadCommandFactory.java@@ -109,6 +109,8 @@ public class LoadCommandFactory {case LC_RPATH:return new RunPathCommand(reader);case LC_CODE_SIGNATURE:+ return new CodeSignatureCommand(reader,+ getLinkerLoadCommandReader(reader, header, splitDyldCache));case LC_SEGMENT_SPLIT_INFO:case LC_OPTIMIZATION_HINT:case LC_DYLIB_CODE_SIGN_DRS:diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedFixupHeader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedFixupHeader.javaindex be0df54c78..db0286bd85 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedFixupHeader.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedFixupHeader.java@@ -20,8 +20,16 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;import ghidra.app.util.bin.format.macho.MachConstants;+import ghidra.app.util.bin.format.macho.MachHeader;+import ghidra.app.util.importer.MessageLog;+import ghidra.program.model.address.Address;import ghidra.program.model.data.*;+import ghidra.program.model.listing.Data;+import ghidra.program.model.listing.Program;+import ghidra.program.model.symbol.*;+import ghidra.util.exception.CancelledException;import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;/*** Represents a dyld_chained_fixups_header structure.@@ -68,6 +76,50 @@ public class DyldChainedFixupHeader implements StructConverter {chainedImports.initSymbols(reader, this);}+ /**+ * Marks up this data structure with data structures and comments+ *+ * @param program The {@link Program} to mark up+ * @param address The {@link Address} of this data structure+ * @param header The Mach-O header+ * @param monitor A cancellable task monitor+ * @param log The log+ * @throws CancelledException if the user cancelled the operation+ */+ public void markup(Program program, Address address, MachHeader header, TaskMonitor monitor,+ MessageLog log) throws CancelledException {+ try {+ if (startsOffset != 0) {+ Address startsAddr = address.add(startsOffset);+ DataUtilities.createData(program, startsAddr, chainedStartsInImage.toDataType(), -1,+ DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ chainedStartsInImage.markup(program, startsAddr, header, monitor, log);+ }+ if (importsOffset != 0 && symbolsOffset != 0) {+ ReferenceManager referenceManager = program.getReferenceManager();+ Address importsAddr = address.add(importsOffset);+ Address symbolsAddr = address.add(symbolsOffset);+ DyldChainedImport[] chainedImportArray = chainedImports.getChainedImports();+ for (int i = 0; i < importsCount; i++) {+ DyldChainedImport chainedImport = chainedImportArray[i];+ DataType dt = chainedImport.toDataType();+ Data d = DataUtilities.createData(program, importsAddr.add(i * dt.getLength()),+ dt, -1, DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ Address strAddr = symbolsAddr.add(chainedImport.getNameOffset());+ DataUtilities.createData(program,+ symbolsAddr.add(chainedImport.getNameOffset()), STRING, -1,+ DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ referenceManager.addMemoryReference(d.getMinAddress(), strAddr, RefType.DATA,+ SourceType.IMPORTED, 0);+ }+ }+ }+ catch (Exception e) {+ log.appendMsg(DyldChainedFixupHeader.class.getSimpleName(),+ "Failed to markup dyld_chained_fixups_header");+ }+ }+@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {StructureDataType struct = new StructureDataType("dyld_chained_fixups_header", 0);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedImport.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedImport.javaindex 3b6b5da7a9..d981d502bc 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedImport.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedImport.java@@ -85,22 +85,22 @@ public class DyldChainedImport implements StructConverter {@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {StructureDataType dt = new StructureDataType("dyld_chained_import", 0);-+ dt.setPackingEnabled(true);try {switch (imports_format) {case DYLD_CHAINED_IMPORT:- dt.addBitField(DWORD, 8, "lib_ordinal", "ordinal in imports");+ dt.addBitField(DWORD, 8, "lib_ordinal", null);dt.addBitField(DWORD, 1, "weak_import", null);dt.addBitField(DWORD, 23, "name_offset", null);break;case DYLD_CHAINED_IMPORT_ADDEND:- dt.addBitField(DWORD, 8, "lib_ordinal", "ordinal in imports");+ dt.addBitField(DWORD, 8, "lib_ordinal", null);dt.addBitField(DWORD, 1, "weak_import", null);dt.addBitField(DWORD, 23, "name_offset", null);dt.add(DWORD, "addend", null);break;case DYLD_CHAINED_IMPORT_ADDEND64:- dt.addBitField(QWORD, 16, "lib_ordinal", "ordinal in imports");+ dt.addBitField(QWORD, 16, "lib_ordinal", null);dt.addBitField(QWORD, 1, "weak_import", null);dt.addBitField(QWORD, 15, "reserved", null);dt.addBitField(QWORD, 32, "name_offset", null);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedImports.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedImports.javaindex bacb7b1cdf..93d253e2c7 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedImports.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedImports.java@@ -20,18 +20,14 @@ import java.util.ArrayList;import java.util.List;import ghidra.app.util.bin.BinaryReader;-import ghidra.app.util.bin.StructConverter;import ghidra.app.util.bin.format.macho.commands.dyld.BindingTable.Binding;-import ghidra.program.model.data.ArrayDataType;-import ghidra.program.model.data.DataType;-import ghidra.util.exception.DuplicateNameException;/*** Represents a dyld_chained_import array.** @see <a href="https://github.com/apple-oss-distributions/dyld/blob/main/include/mach-o/fixup-chains.h">mach-o/fixup-chains.h</a>*/-public class DyldChainedImports implements StructConverter {+public class DyldChainedImports {private int importsCount;private int importsFormat;@@ -61,15 +57,6 @@ public class DyldChainedImports implements StructConverter {}}- @Override- public DataType toDataType() throws DuplicateNameException, IOException {- DataType chainedImportDt = chainedImports[0].toDataType();- DataType dt =- new ArrayDataType(chainedImportDt, importsCount, chainedImportDt.getLength());-- return dt;- }-public int getImportsCount() {return importsCount;}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedStartsInImage.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedStartsInImage.javaindex 8177c7152e..274011276a 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedStartsInImage.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedStartsInImage.java@@ -22,8 +22,14 @@ import java.util.List;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;import ghidra.app.util.bin.format.macho.MachConstants;+import ghidra.app.util.bin.format.macho.MachHeader;+import ghidra.app.util.importer.MessageLog;+import ghidra.program.model.address.Address;import ghidra.program.model.data.*;+import ghidra.program.model.listing.Program;+import ghidra.util.exception.CancelledException;import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;/*** Represents a dyld_chained_starts_in_image structure.@@ -59,6 +65,40 @@ public class DyldChainedStartsInImage implements StructConverter {}}+ /**+ * Marks up this data structure with data structures and comments+ *+ * @param program The {@link Program} to mark up+ * @param address The {@link Address} of this data structure+ * @param header The Mach-O header+ * @param monitor A cancellable task monitor+ * @param log The log+ * @throws CancelledException if the user cancelled the operation+ */+ public void markup(Program program, Address address, MachHeader header, TaskMonitor monitor,+ MessageLog log) throws CancelledException {+ try {+ int skipCount = 0;+ for (int i = 0; i < segInfoOffset.length; i++) {+ if (segInfoOffset[i] == 0) {+ // The chainStarts list doesn't have entries for 0 offsets, so we must keep+ // track of the index differences between the 2 entities+ skipCount++;+ continue;+ }+ DyldChainedStartsInSegment startsInSeg = chainedStarts.get(i - skipCount);+ if (startsInSeg != null) {+ DataUtilities.createData(program, address.add(segInfoOffset[i]),+ startsInSeg.toDataType(), -1, DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ }+ }+ }+ catch (Exception e) {+ log.appendMsg(DyldChainedStartsInImage.class.getSimpleName(),+ "Failed to markup dyld_chained_starts_in_image");+ }+ }+@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {StructureDataType struct = new StructureDataType("dyld_chained_starts_in_image", 0);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedStartsInSegment.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedStartsInSegment.javaindex 7034f60a61..8bfd1b91dc 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedStartsInSegment.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/chained/DyldChainedStartsInSegment.java@@ -20,8 +20,14 @@ import java.io.IOException;import ghidra.app.util.bin.BinaryReader;import ghidra.app.util.bin.StructConverter;import ghidra.app.util.bin.format.macho.MachConstants;+import ghidra.app.util.bin.format.macho.MachHeader;+import ghidra.app.util.importer.MessageLog;+import ghidra.program.model.address.Address;import ghidra.program.model.data.*;+import ghidra.program.model.listing.Program;+import ghidra.util.exception.CancelledException;import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;/*** Represents a dyld_chained_starts_in_segment structure.@@ -56,6 +62,27 @@ public class DyldChainedStartsInSegment implements StructConverter {pageStarts = reader.readNextShortArray(pageCount);}+ /**+ * Marks up this data structure with data structures and comments+ *+ * @param program The {@link Program} to mark up+ * @param address The {@link Address} of this data structure+ * @param header The Mach-O header+ * @param monitor A cancellable task monitor+ * @param log The log+ * @throws CancelledException if the user cancelled the operation+ */+ public void markup(Program program, Address address, MachHeader header, TaskMonitor monitor,+ MessageLog log) throws CancelledException {+ try {++ }+ catch (Exception e) {+ log.appendMsg(DyldChainedStartsInSegment.class.getSimpleName(),+ "Failed to markup dyld_chained_starts_in_segment");+ }+ }+@Overridepublic DataType toDataType() throws DuplicateNameException, IOException {StructureDataType struct = new StructureDataType("dyld_chained_starts_in_segment", 0);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureBlobIndex.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureBlobIndex.javanew file mode 100644index 0000000000..a0f3ce580b--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureBlobIndex.java@@ -0,0 +1,70 @@+/* ###+ * 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.app.util.bin.format.macho.commands.codesignature;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;+import ghidra.app.util.bin.format.macho.MachConstants;+import ghidra.program.model.data.*;+import ghidra.util.exception.DuplicateNameException;++/**+ * Represents a CS_BlobIndex structure+ *+ * @see <a href="https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/cs_blobs.h">osfmk/kern/cs_blobs.h</a>+ */+public class CodeSignatureBlobIndex implements StructConverter {++ private int type;+ private long offset;++ /**+ * Creates a new {@link CodeSignatureBlobIndex}+ *+ * @param reader A {@link BinaryReader} positioned at the start of the structure+ * @throws IOException if there was an IO-related problem creating the structure+ */+ public CodeSignatureBlobIndex(BinaryReader reader) throws IOException {+ type = reader.readNextInt();+ offset = reader.readNextUnsignedInt();+ }++ /**+ * {@return the type}+ */+ public int getType() {+ return type;+ }++ /**+ * {@return the offset}+ */+ public long getOffset() {+ return offset;+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ StructureDataType struct = new StructureDataType("CS_BlobIndex", 0);+ struct.add(DWORD, "type", "type of entry");+ struct.add(DWORD, "offset", "offset of entry");+ struct.setCategoryPath(new CategoryPath(MachConstants.DATA_TYPE_CATEGORY));+ return struct;+ }++}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureBlobParser.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureBlobParser.javanew file mode 100644index 0000000000..aa3676f909--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureBlobParser.java@@ -0,0 +1,45 @@+/* ###+ * 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.app.util.bin.format.macho.commands.codesignature;++import static ghidra.app.util.bin.format.macho.commands.codesignature.CodeSignatureConstants.*;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;++/**+ * Class to parse Code Signature blobs+ */+public class CodeSignatureBlobParser {++ /**+ * Parses a new Code Signature blob+ *+ * @param reader A {@link BinaryReader} positioned at the start of a Code Signature blob+ * @return A new Code Signature blob+ * @throws IOException if there was an IO-related error parsing the blob+ */+ public static CodeSignatureGenericBlob parse(BinaryReader reader) throws IOException {+ int magic = reader.peekNextInt();+ return switch (magic) {+ case CSMAGIC_EMBEDDED_SIGNATURE -> new CodeSignatureSuperBlob(reader);+ case CSMAGIC_CODEDIRECTORY -> new CodeSignatureCodeDirectory(reader);+ // TODO: Handle more blob types+ default -> new CodeSignatureGenericBlob(reader);+ };+ }+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureCodeDirectory.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureCodeDirectory.javanew file mode 100644index 0000000000..ee520794aa--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureCodeDirectory.java@@ -0,0 +1,199 @@+/* ###+ * 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.app.util.bin.format.macho.commands.codesignature;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.format.macho.MachConstants;+import ghidra.app.util.bin.format.macho.MachHeader;+import ghidra.app.util.importer.MessageLog;+import ghidra.program.model.address.Address;+import ghidra.program.model.data.*;+import ghidra.program.model.listing.CodeUnit;+import ghidra.program.model.listing.Program;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * Represents a CS_BlobIndex structure+ *+ * @see <a href="https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/cs_blobs.h">osfmk/kern/cs_blobs.h</a>+ */+@SuppressWarnings("unused")+public class CodeSignatureCodeDirectory extends CodeSignatureGenericBlob {++ private int version;+ private int flags;+ private int hashOffset;+ private int identOffset;+ private int nSpecialSlots;+ private int nCodeSlots;+ private int codeLimit;+ private int hashSize;+ private int hashType;+ private int platform;+ private int pageSize;+ private int spare2;+ private int scatterOffset;+ private int teamOffset;+ private int spare3;+ private long codeLimit64;+ private long execSegBase;+ private long execSegLimit;+ private long execSegFlags;+ private int runtime;+ private int preEncryptOffset;+ private int linkageHashType;+ private int linkageHashApplicationType;+ private int linkageApplicationSubType;+ private int linkageOffset;+ private int linkageSize;++ /**+ * Creates a new {@link CodeSignatureCodeDirectory}+ *+ * @param reader A {@link BinaryReader} positioned at the start of the structure+ * @throws IOException if there was an IO-related problem creating the structure+ */+ public CodeSignatureCodeDirectory(BinaryReader reader) throws IOException {+ super(reader);++ version = reader.readNextInt();+ flags = reader.readNextInt();+ hashOffset = reader.readNextInt();+ identOffset = reader.readNextInt();+ nSpecialSlots = reader.readNextInt();+ nCodeSlots = reader.readNextInt();+ codeLimit = reader.readNextInt();+ hashSize = reader.readNextUnsignedByte();+ hashType = reader.readNextUnsignedByte();+ platform = reader.readNextUnsignedByte();+ pageSize = reader.readNextUnsignedByte();+ spare2 = reader.readNextInt();+ if (version >= 0x20100) {+ scatterOffset = reader.readNextInt();+ }+ if (version >= 0x20200) {+ teamOffset = reader.readNextInt();+ }+ if (version >= 0x20300) {+ spare3 = reader.readNextInt();+ codeLimit64 = reader.readNextLong();+ }+ if (version >= 0x20400) {+ execSegBase = reader.readNextLong();+ execSegLimit = reader.readNextLong();+ execSegFlags = reader.readNextLong();+ }+ if (version >= 0x20500) {+ runtime = reader.readNextInt();+ preEncryptOffset = reader.readNextInt();+ }+ if (version >= 0x20600) {+ linkageHashType = reader.readNextUnsignedByte();+ linkageHashApplicationType = reader.readNextUnsignedByte();+ linkageApplicationSubType = reader.readNextUnsignedShort();+ linkageOffset = reader.readNextInt();+ linkageSize = reader.readNextInt();+ }+ }++ @Override+ public void markup(Program program, Address addr, MachHeader header, TaskMonitor monitor,+ MessageLog log) throws CancelledException {++ try {+ if (identOffset != 0) {+ Address identAddr = addr.add(identOffset);+ DataUtilities.createData(program, identAddr, STRING, -1,+ DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ program.getListing()+ .setComment(identAddr, CodeUnit.PRE_COMMENT, "CS_CodeDirectory identifer");+ }+ if (teamOffset != 0) {+ Address teamAddr = addr.add(teamOffset);+ DataUtilities.createData(program, teamAddr, STRING, -1,+ DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ program.getListing()+ .setComment(teamAddr, CodeUnit.PRE_COMMENT,+ "CS_CodeDirectory team identifier");+ }+ if (hashOffset != 0 && hashSize != 0) {+ Address hashAddr = addr.add(hashOffset);+ DataType hashArrayDt = new ArrayDataType(BYTE, hashSize, 1);+ DataType hasheArrayArrayDt = new ArrayDataType(hashArrayDt, nCodeSlots, 1);+ DataUtilities.createData(program, hashAddr, hasheArrayArrayDt, -1,+ DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ program.getListing()+ .setComment(hashAddr, CodeUnit.PRE_COMMENT, "CS_CodeDirectory hashes");+ }+ }+ catch (Exception e) {+ log.appendMsg(CodeSignatureCodeDirectory.class.getSimpleName(),+ "Failed to markup CS_CodeDirectory");+ }+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ StructureDataType struct = new StructureDataType("CS_CodeDirectory", 0);+ struct.add(DWORD, "magic", "magic number (CSMAGIC_CODEDIRECTORY)");+ struct.add(DWORD, "length", "total length of CodeDirectory blob");+ struct.add(DWORD, "version", "compatibility version");+ struct.add(DWORD, "flags", "setup and mode flags");+ struct.add(DWORD, "hashOffset", "offset of hash slot element at index zero");+ struct.add(DWORD, "identOffset", "offset of identifier string");+ struct.add(DWORD, "nSpecialSlots", "number of special hash slots");+ struct.add(DWORD, "nCodeSlots", "number of ordinary (code) hash slots");+ struct.add(DWORD, "codeLimit", "limit to main image signature range");+ struct.add(BYTE, "hashSize", "size of each hash in bytes");+ struct.add(BYTE, "hashType", "type of hash (cdHashType* constants)");+ struct.add(BYTE, "platform", "platform identifier; zero if not platform binary");+ struct.add(BYTE, "pageSize", "log2(page size in bytes); 0 => infinite");+ struct.add(DWORD, "spare2", "unused (must be zero)");+ if (version >= 0x20100) {+ struct.add(DWORD, "scatterOffset", "offset of optional scatter vector");+ }+ if (version >= 0x20200) {+ struct.add(DWORD, "teamOffset", "offset of optional team identifier");+ }+ if (version >= 0x20300) {+ struct.add(DWORD, "spare3", "unused (must be zero)");+ struct.add(QWORD, "codeLimit64", "limit to main image signature range, 64 bits");+ }+ if (version >= 0x20400) {+ struct.add(QWORD, "execSegBase", "offset of executable segment");+ struct.add(QWORD, "execSegLimit", "limit of executable segment");+ struct.add(QWORD, "execSegFlags", "executable segment flags");+ }+ if (version >= 0x20500) {+ struct.add(DWORD, "runtime", "");+ struct.add(DWORD, "preEncryptOffset", "");+ }+ if (version >= 0x20600) {+ struct.add(BYTE, "linkageHashType", "");+ struct.add(BYTE, "linkageHashApplicationType", "");+ struct.add(WORD, "linkageApplicationSubType", "");+ struct.add(DWORD, "linkageOffset", "");+ struct.add(DWORD, "linkageSize", "");+ }+ struct.setCategoryPath(new CategoryPath(MachConstants.DATA_TYPE_CATEGORY));+ return struct;+ }++}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureConstants.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureConstants.javanew file mode 100644index 0000000000..39169a8d7c--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureConstants.java@@ -0,0 +1,35 @@+/* ###+ * 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.app.util.bin.format.macho.commands.codesignature;++/**+ * Code Signature constants+ *+ * @see <a href="https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/cs_blobs.h">osfmk/kern/cs_blobs.h</a>+ */+public class CodeSignatureConstants {++ public static final int CSMAGIC_REQUIREMENT = 0xfade0c00;+ public static final int CSMAGIC_REQUIREMENTS = 0xfade0c01;+ public static final int CSMAGIC_CODEDIRECTORY = 0xfade0c02;+ public static final int CSMAGIC_EMBEDDED_SIGNATURE = 0xfade0cc0;+ public static final int CSMAGIC_EMBEDDED_SIGNATURE_OLD = 0xfade0b02;+ public static final int CSMAGIC_EMBEDDED_ENTITLEMENTS = 0xfade7171;+ public static final int CSMAGIC_EMBEDDED_DER_ENTITLEMENTS = 0xfade7172;+ public static final int CSMAGIC_DETACHED_SIGNATURE = 0xfade0cc1;+ public static final int CSMAGIC_BLOBWRAPPER = 0xfade0b01;+ public static final int CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT = 0xfade8181;+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureGenericBlob.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureGenericBlob.javanew file mode 100644index 0000000000..fcef8a137f--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureGenericBlob.java@@ -0,0 +1,107 @@+/* ###+ * 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.app.util.bin.format.macho.commands.codesignature;++import java.io.IOException;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.StructConverter;+import ghidra.app.util.bin.format.macho.MachConstants;+import ghidra.app.util.bin.format.macho.MachHeader;+import ghidra.app.util.importer.MessageLog;+import ghidra.program.model.address.Address;+import ghidra.program.model.data.*;+import ghidra.program.model.listing.CodeUnit;+import ghidra.program.model.listing.Program;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * Represents a CS_GenericBlob structure+ *+ * @see <a href="https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/cs_blobs.h">osfmk/kern/cs_blobs.h</a>+ */+public class CodeSignatureGenericBlob implements StructConverter {++ protected int magic;+ protected int length;++ protected long base;++ /**+ * Creates a new {@link CodeSignatureGenericBlob}+ *+ * @param reader A {@link BinaryReader} positioned at the start of the structure+ * @throws IOException if there was an IO-related problem creating the structure+ */+ public CodeSignatureGenericBlob(BinaryReader reader) throws IOException {+ base = reader.getPointerIndex();+ magic = reader.readNextInt();+ length = reader.readNextInt();+ }++ /**+ * {@return the magic}+ */+ public int getMagic() {+ return magic;+ }++ /**+ * {@return the length}+ */+ public int getLength() {+ return length;+ }++ /**+ * Marks up this {@link CodeSignatureGenericBlob} data with data structures and comments+ *+ * @param program The {@link Program} to mark up+ * @param address The {@link Address} of the blob+ * @param header The Mach-O header+ * @param monitor A cancellable task monitor+ * @param log The log+ * @throws CancelledException if the user cancelled the operation+ */+ public void markup(Program program, Address address, MachHeader header, TaskMonitor monitor,+ MessageLog log) throws CancelledException {+ if (length - 8 == 0) {+ return;+ }+ try {+ DataType dt = new ArrayDataType(BYTE, length - 8, 1);+ Address hashAddr = address.add(toDataType().getLength());+ DataUtilities.createData(program, hashAddr, dt, -1,+ DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ program.getListing().setComment(hashAddr, CodeUnit.PRE_COMMENT, "CS_GenericBlob hash");+ }+ catch (Exception e) {+ log.appendMsg(CodeSignatureGenericBlob.class.getSimpleName(),+ "Failed to markup CS_GenericBlob");+ }+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ StructureDataType struct = new StructureDataType("CS_GenericBlob", 0);+ struct.add(DWORD, "magic", "magic number");+ struct.add(DWORD, "length", "total length of blob");+ struct.setCategoryPath(new CategoryPath(MachConstants.DATA_TYPE_CATEGORY));+ return struct;+ }+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureSuperBlob.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureSuperBlob.javanew file mode 100644index 0000000000..d6fbb5854b--- /dev/null+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/macho/commands/codesignature/CodeSignatureSuperBlob.java@@ -0,0 +1,124 @@+/* ###+ * 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.app.util.bin.format.macho.commands.codesignature;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;++import ghidra.app.util.bin.BinaryReader;+import ghidra.app.util.bin.format.macho.MachConstants;+import ghidra.app.util.bin.format.macho.MachHeader;+import ghidra.app.util.bin.format.macho.commands.LoadCommand;+import ghidra.app.util.importer.MessageLog;+import ghidra.program.model.address.Address;+import ghidra.program.model.data.*;+import ghidra.program.model.listing.Data;+import ghidra.program.model.listing.Program;+import ghidra.util.exception.CancelledException;+import ghidra.util.exception.DuplicateNameException;+import ghidra.util.task.TaskMonitor;++/**+ * Represents a CS_SuperBlob structure+ *+ * @see <a href="https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/cs_blobs.h">osfmk/kern/cs_blobs.h</a>+ */+public class CodeSignatureSuperBlob extends CodeSignatureGenericBlob {++ private int count;++ private List<CodeSignatureBlobIndex> indexList;+ private List<CodeSignatureGenericBlob> indexBlobs;++ /**+ * Creates a new {@link CodeSignatureSuperBlob}+ *+ * @param reader A {@link BinaryReader} positioned at the start of the structure+ * @throws IOException if there was an IO-related problem creating the structure+ */+ public CodeSignatureSuperBlob(BinaryReader reader) throws IOException {+ super(reader);+ count = reader.readNextInt();++ indexList = new ArrayList<>(count);+ for (int i = 0; i < count; i++) {+ indexList.add(new CodeSignatureBlobIndex(reader));+ }++ indexBlobs = new ArrayList<>(count);+ for (CodeSignatureBlobIndex blobIndex : indexList) {+ reader.setPointerIndex(base + blobIndex.getOffset());+ indexBlobs.add(CodeSignatureBlobParser.parse(reader));+ }+ }++ /**+ * {@return the number of index entries}+ */+ public int getCount() {+ return count;+ }++ /**+ * {@return the index entries}+ */+ public List<CodeSignatureBlobIndex> getIndexEntries() {+ return indexList;+ }++ /**+ * {@return the index blobs}+ */+ public List<CodeSignatureGenericBlob> getIndexBlobs() {+ return indexBlobs;+ }++ @Override+ public void markup(Program program, Address addr, MachHeader header, TaskMonitor monitor,+ MessageLog log) throws CancelledException {++ try {+ for (int i = 0; i < count; i++) {+ CodeSignatureBlobIndex blobIndex = indexList.get(i);+ CodeSignatureGenericBlob blob = indexBlobs.get(i);+ Data d = DataUtilities.createData(program, addr.add(blobIndex.getOffset()),+ blob.toDataType(), -1, DataUtilities.ClearDataMode.CHECK_FOR_SPACE);+ LoadCommand.setEndian(d, true);+ blob.markup(program, addr.add(blobIndex.getOffset()), header, monitor, log);+ }+ }+ catch (Exception e) {+ log.appendMsg(CodeSignatureSuperBlob.class.getSimpleName(),+ "Failed to markup CS_SuperBlob");+ }+ }++ @Override+ public DataType toDataType() throws DuplicateNameException, IOException {+ StructureDataType struct = new StructureDataType("CS_SuperBlob", 0);+ struct.add(DWORD, "magic", "magic number");+ struct.add(DWORD, "length", "total length of SuperBlob");+ struct.add(DWORD, "count", "number of index entries following");+ if (!indexList.isEmpty()) {+ DataType dt = indexList.get(0).toDataType();+ struct.add(new ArrayDataType(dt, count, dt.getLength()), "index", "(count) entries");+ }+ struct.setCategoryPath(new CategoryPath(MachConstants.DATA_TYPE_CATEGORY));+ return struct;+ }++}