/// <summary> /// Generate a text file with all info from the executable. /// </summary> /// <param name="elfPath">executable path.</param> public ShowInfo(string elfPath) { // Check if the file exists. if (!File.Exists(elfPath)) { throw new FileNotFoundException("The executable file is not found.", elfPath); } var pe = PEFile.FromFile(elfPath); var sb = new StringBuilder(); sb.AppendLine($"Header info from executable {Path.GetFileName(elfPath)}\n\n"); foreach (var section in pe.Sections) { sb.AppendLine($"SECTION NAME: {section.Name}"); sb.AppendLine($"OFFSET: 0x{section.Offset:X}"); sb.AppendLine($"RVA: 0x{section.Rva:X}"); sb.AppendLine($"PHYSICAL SIZE: 0x{section.GetPhysicalSize():X}"); sb.AppendLine($"VIRTUAL SIZE: 0x{section.GetVirtualSize():X}"); var translationSectionBase = (int)(pe.OptionalHeader.ImageBase + (section.Rva - section.Offset)); sb.AppendLine($"TRANSLATION SECTION BASE: 0x{translationSectionBase:X}"); sb.AppendLine($"IS READABLE: {section.IsReadable}"); sb.AppendLine($"\n\n"); } File.WriteAllText(elfPath + ".txt", sb.ToString()); }
public void Read() { try { foreach (ProcessModule module in _process.Modules) { try { var fileOnDisk = PEFile.FromFile(module.FileName); var imageOnDisk = PEImage.FromFile(fileOnDisk); if (!imageOnDisk.Characteristics.HasFlag(Characteristics.Image)) { continue; } ModuleList.Add(new CopiedProcessModule(_process, module.BaseAddress, module.ModuleMemorySize) { ModuleName = module.ModuleName, ImageFileOnDisk = fileOnDisk, ImageOnDisk = imageOnDisk }); } catch (AccessViolationException) { //do nothing, could be something malicious } } } catch (Win32Exception) { //do nothing again, we probably just don't have access. TODO: log this somehow! } }
public void RebuildNetPEAddSection() { const string fileName = "HelloWorld"; const string sectionName = ".test"; var sectionData = new byte[] { 1, 3, 3, 7 }; var peFile = PEFile.FromBytes(Properties.Resources.HelloWorld); // Add a new section. peFile.Sections.Add(new PESection(sectionName, SectionFlags.MemoryRead | SectionFlags.ContentInitializedData) { Contents = new DataSegment(sectionData) }); // Rebuild and check if file is still runnable. _fixture .GetRunner <FrameworkPERunner>() .RebuildAndRun(peFile, fileName, "Hello World!" + Environment.NewLine); // Read the new file. var newPEFile = PEFile.FromFile(_fixture .GetRunner <FrameworkPERunner>() .GetTestExecutablePath(nameof(PEFileTest), nameof(RebuildNetPEAddSection), fileName)); // Verify the section and its data is present: var newSection = newPEFile.Sections.First(s => s.Name == sectionName); var newData = new byte[sectionData.Length]; Assert.Equal(sectionData.Length, newSection .CreateReader() .ReadBytes(newData, 0, newData.Length)); Assert.Equal(sectionData, newData); }
private DevirtualisationContext CreateDevirtualisationContext(DevirtualisationOptions options) { string workingDirectory = Path.GetDirectoryName(options.InputFile); // Open target PE. Logger.Log(Tag, $"Opening target file {options.InputFile}..."); var peFile = PEFile.FromFile(options.InputFile); // Create #Koi stream aware metadata reader. var streamReader = options.OverrideKoiStreamData ? new DefaultMetadataStreamReader() : (IMetadataStreamReader) new KoiVmAwareStreamReader(options.KoiStreamName, Logger); var peImage = PEImage.FromFile(peFile, new PEReaderParameters { MetadataStreamReader = streamReader }); var metadata = peImage.DotNetDirectory?.Metadata; if (metadata is null) { throw new BadImageFormatException("Assembly does not contain a valid .NET header."); } // If custom koi stream data was provided, inject it. KoiStream koiStream; if (!options.OverrideKoiStreamData) { koiStream = metadata.GetStream <KoiStream>() ?? throw new DevirtualisationException( "Koi stream was not found in the target PE. This could be because the input file is " + "not protected with KoiVM, or the metadata stream uses a name that is different " + "from the one specified in the input parameters."); } else { string path = Path.IsPathRooted(options.KoiStreamDataFile) ? options.KoiStreamDataFile : Path.Combine(workingDirectory, options.KoiStreamDataFile); Logger.Log(Tag, $"Opening external Koi stream data file {path}..."); var contents = File.ReadAllBytes(path); // Replace original koi stream if it existed. koiStream = new KoiStream(options.KoiStreamName, new DataSegment(contents), Logger); } // Ignore invalid / encrypted method bodies when specified. var moduleReadParameters = new ModuleReaderParameters(workingDirectory, options.IgnoreInvalidMD ? (IErrorListener)ThrowErrorListener.Instance : EmptyErrorListener.Instance); var module = ModuleDefinition.FromImage(peImage, moduleReadParameters); var runtimeModule = ResolveRuntimeModule(options, module); koiStream.ResolutionContext = module; return(new DevirtualisationContext(options, module, runtimeModule, koiStream, Logger)); }
public DeoxysContext(DeoxysOptions options, ILogger logger) { Options = options; Module = ModuleDefinition.FromFile(options.FilePath); PeFile = PEFile.FromFile(options.FilePath); Logger = logger; VirtualizedMethods = new List <NashaMethodInfo>(); DeoxysOpCodes = new Dictionary <int, NashaOpCode>(); DisassembledVirtualizedMethods = new List <NashaMethod>(); }
/// <summary> /// Opens a PE image from a specific file on the disk. /// </summary> /// <param name="filePath">The </param> /// <param name="readParameters">The parameters to use while reading the PE image.</param> /// <returns>The PE image that was opened.</returns> /// <exception cref="BadImageFormatException">Occurs when the file does not follow the PE file format.</exception> public static IPEImage FromFile(string filePath, PEReadParameters readParameters) => FromFile(PEFile.FromFile(filePath), readParameters);
/// <summary> /// Opens a PE image from a specific file on the disk. /// </summary> /// <param name="filePath">The </param> /// <returns>The PE image that was opened.</returns> /// <exception cref="BadImageFormatException">Occurs when the file does not follow the PE file format.</exception> public static IPEImage FromFile(string filePath) => FromFile(PEFile.FromFile(filePath));
static void Main(string[] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); shiftJisEncoding = Encoding.GetEncoding(932); if (args.Length != 4) { Console.WriteLine("Usage: DgfTextInject <exeSrcPath> <exeDestPath> <lectSrcPath> <lsSrcPath>"); Environment.Exit(2); } string exeSrcPath = args[0]; string exeDestPath = args[1]; string lectSrcPath = args[2]; string lsSrcPath = args[3]; try { int numLectEntries = 151; uint lectdatRva = 0x15FE10; int lectStringsSize = 0; int numLsEntries = 24; uint lsmenuRva = 0x1D9488; int lsStringsSize = 0; var pe = PEFile.FromFile(exeSrcPath); // This dumps text files //using (StreamWriter sw = File.CreateText(lectSrcPath)) // DumpStrings(pe, lectdatRva, numLectEntries, 0x2c, 0x50, sw); //using (StreamWriter sw = File.CreateText(lsSrcPath)) // DumpStrings(pe, lsmenuRva, numLsEntries, 0x04, 0x0c, sw); //return; string[] newLectStrings = File.ReadAllLines(lectSrcPath); if (newLectStrings.Length != numLectEntries) { throw new InvalidDataException("Lectures source file does not contain same number of lines as number of lecture definitions."); } uint newLectSpace = CalcSpaceRequired(newLectStrings); string[] newLsStrings = File.ReadAllLines(lsSrcPath); if (newLsStrings.Length != numLsEntries) { throw new InvalidDataException("LS source file does not contain same number of lines as number of LS definitions."); } uint newLsSpace = CalcSpaceRequired(newLsStrings); bool lectInNewSection = true; // newLectSpace > lectStringsSize; bool lsInNewSection = true; // newLsSpace > lsStringsSize; Dictionary <string, uint> writtenLectStrings = new Dictionary <string, uint>(); Dictionary <string, uint> writtenLsStrings = new Dictionary <string, uint>(); List <uint> lectOffsets = new List <uint>(); List <uint> lsOffsets = new List <uint>(); using MemoryStream newSectionMs = new MemoryStream(); using MemoryStream newLectMs = new MemoryStream(); using MemoryStream newLsMs = new MemoryStream(); WriteStrings(lectInNewSection ? newSectionMs : newLectMs, newLectStrings, writtenLectStrings, lectOffsets); WriteStrings(lsInNewSection ? newSectionMs : newLsMs, newLsStrings, writtenLsStrings, lsOffsets); PESection newSection = null; if (lectInNewSection || lsInNewSection) { newSection = new PESection(".trans", SectionFlags.MemoryRead | SectionFlags.ContentInitializedData); newSection.Contents = new DataSegment(newSectionMs.ToArray()); pe.Sections.Add(newSection); pe.UpdateHeaders(); } uint additionalNewSectOffset = 0; uint stringsRva = UpdateTable(pe, lectdatRva, 0x2c, 0x50, lectOffsets, lectInNewSection ? (uint?)(newSection.Rva + additionalNewSectOffset) : null); if (lectInNewSection) { additionalNewSectOffset += newLectSpace; } else { var dataSect = pe.GetSectionContainingRva(stringsRva); using (MemoryStream ms = new MemoryStream((dataSect.Contents as DataSegment).Data)) { ms.Seek(stringsRva - dataSect.Rva, SeekOrigin.Begin); ms.Write(newLectMs.ToArray()); } } stringsRva = UpdateTable(pe, lsmenuRva, 0x04, 0x0c, lsOffsets, lsInNewSection ? (uint?)(newSection.Rva + additionalNewSectOffset) : null); if (lsInNewSection) { additionalNewSectOffset += newLsSpace; } else { var dataSect = pe.GetSectionContainingRva(stringsRva); using (MemoryStream ms = new MemoryStream((dataSect.Contents as DataSegment).Data)) { ms.Seek(stringsRva - dataSect.Rva, SeekOrigin.Begin); ms.Write(newLsMs.ToArray()); } } pe.Write(exeDestPath); } catch (Exception ex) { Console.WriteLine("Something went wrong: " + ex.ToString()); Environment.Exit(1); } }
/// <summary> /// Opens a PE image from a specific file on the disk. /// </summary> /// <param name="filePath">The </param> /// <param name="readerParameters">The parameters to use while reading the PE image.</param> /// <returns>The PE image that was opened.</returns> /// <exception cref="BadImageFormatException">Occurs when the file does not follow the PE file format.</exception> public static IPEImage FromFile(string filePath, PEReaderParameters readerParameters) => FromFile(PEFile.FromFile(readerParameters.FileService.OpenFile(filePath)), readerParameters);
public void Read() { var moduleList = new List <ProcessModule>(); try { moduleList = _process.Modules.Cast <ProcessModule>().ToList(); } catch (Win32Exception) { } if (moduleList.Count == 0) //no modules or access { return; } Parallel.ForEach(moduleList, (m) => { try { var fileOnDisk = PEFile.FromFile(m.FileName); var imageOnDisk = PEImage.FromFile(fileOnDisk); if (!imageOnDisk.Characteristics.HasFlag(Characteristics.Image)) { return; } ModuleList.Add(new CopiedProcessModule(_process, m.BaseAddress, m.ModuleMemorySize, m.ModuleName) { ModuleName = m.ModuleName, ImageFileOnDisk = fileOnDisk, ImageOnDisk = imageOnDisk }); } catch (AccessViolationException) { //do nothing, could be something malicious } }); /* * try * { * foreach (ProcessModule module in _process.Modules) * { * try * { * var fileOnDisk = PEFile.FromFile(module.FileName); * var imageOnDisk = PEImage.FromFile(fileOnDisk); * if (!imageOnDisk.Characteristics.HasFlag(Characteristics.Image)) * continue; * * ModuleList.Add(new CopiedProcessModule(_process, module.BaseAddress, module.ModuleMemorySize) * { * ModuleName = module.ModuleName, * ImageFileOnDisk = fileOnDisk, * ImageOnDisk = imageOnDisk * }); * } * catch (AccessViolationException) * { * //do nothing, could be something malicious * } * } * } * catch (Win32Exception) * { * //do nothing again, we probably just don't have access. TODO: log this somehow! * }*/ }
/// <summary> /// Expand the current executable for write the new content. /// </summary> /// <param name="path">Path of the executable.</param> /// <param name="size">Size of the new partition.</param> public Expand(string path, uint size) { newSize = size; peFile = PEFile.FromFile(path); }