public static ModuleDefMD UnAntiTamper(ModuleDefMD module, byte[] rawbytes) { dynInstr = new List <Instruction>(); initialKeys = new uint[4]; cctor = module.GlobalType.FindStaticConstructor(); antitamp = cctor.Body.Instructions[0].Operand as MethodDef; if (antitamp == null) { return(null); } IList <ImageSectionHeader> imageSectionHeaders = module.MetaData.PEImage.ImageSectionHeaders; ImageSectionHeader confSec = imageSectionHeaders[0]; FindInitialKeys(antitamp); if (initialKeys == null) { return(null); } input = new MemoryStream(rawbytes); reader = new BinaryReader(input); Hash1(input, reader, imageSectionHeaders, confSec); arrayKeys = GetArrayKeys(); DecryptMethods(reader, confSec, input); ModuleDefMD fmd2 = ModuleDefMD.Load(input); fmd2.GlobalType.FindStaticConstructor().Body.Instructions.RemoveAt(0); return(fmd2); }
public PEHeaderReader(string filePath) { // Read in the DLL or EXE and get the timestamp using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read); var reader = new BinaryReader(stream); DOSHeader = Mem.ReadFromBinaryReader <ImageDOSHeader>(reader); // Add 4 bytes to the offset stream.Seek(DOSHeader.ELfanew, SeekOrigin.Begin); uint ntHeadersSignature = reader.ReadUInt32(); FileHeader = Mem.ReadFromBinaryReader <ImageFileHeader>(reader); if (Is32BitHeader) { OptionalHeader32 = Mem.ReadFromBinaryReader <ImageOptionalHeader32>(reader); } else { OptionalHeader64 = Mem.ReadFromBinaryReader <ImageOptionalHeader64>(reader); } ImageSectionHeaders = new ImageSectionHeader[FileHeader.NumberOfSections]; for (int headerNo = 0; headerNo < ImageSectionHeaders.Length; ++headerNo) { ImageSectionHeaders[headerNo] = Mem.ReadFromBinaryReader <ImageSectionHeader>(reader); } }
private ImageSectionHeader WriteSectionHeader(WindowsAssembly pE) { int newSectionHeaderOffset = (int)pE.SectionHeaders.Last().StartOffset + 0x28; if (newSectionHeaderOffset + 0x28 > pE.SectionHeaders.First().PointerToRawData) { throw new Exception("Not ehought space in header to add a new section"); } byte[] stubSectionHeader; ImageSectionHeader section = PrepareNewSection(pE, out stubSectionHeader); pE.SectionHeaders.Add(section); dataStream.Seek(newSectionHeaderOffset, SeekOrigin.Begin); if (stubSectionHeader != null) { dataStream.Write(stubSectionHeader, 0, stubSectionHeader.Length); } else { throw new Exception("Can't generate IMAGE_SECTION_HEADER"); } return(section); }
public SectionBuilder(NetAssemblyBuilder builder, string name) { _builder = builder; Header = new ImageSectionHeader() { Name = name }; }
internal ImageSectionInfo(ImageSectionHeader struc, int number, IntPtr address) { Number = number; Name = struc.Name; Address = address; Size = (int)struc.VirtualSize; Characteristics = struc.Characteristics; }
public void Dispose() { if (chunk != null) { chunk.Data.Dispose(); } chunk = null; peSection = null; }
/// <inheritdoc/> public void Dispose() { if (Chunk != null) { Chunk.Data.Dispose(); } Chunk = null; PESection = null; }
static uint GetSectionNameHash(ImageSectionHeader section) { uint hash = 0; foreach (var c in section.Name) { hash += c; } return(hash); }
public Section( ImageSectionHeader section ) : this( section.Name, section.VirtualSize, section.VirtualAddress, section.SizeOfRawData, section.PointerToRawData, section.CharacteristicsResolved ) { }
private void CreateTextSection() { _textContents = new CompactNetTextContents(Assembly); _textSectionHeader = new ImageSectionHeader { Name = ".text", Attributes = ImageSectionAttributes.MemoryExecute | ImageSectionAttributes.MemoryRead | ImageSectionAttributes.ContentCode, Section = { Segments = { _textContents } } }; }
protected override ImageSectionHeader[] ParseTarget() { var sh = new ImageSectionHeader[_numOfSections]; const uint secSize = 0x28; // Every section header is 40 bytes in size. for (uint i = 0; i < _numOfSections; i++) { sh[i] = new ImageSectionHeader(PeFile, Offset + i * secSize, _imageBaseAddress); } return(sh); }
private void WriteNtHeaders(WindowsAssembly pE, ImageSectionHeader section, bool movEP) { if (movEP) { pE.NtHeaders.OptionalHeader.AddressOfEntrypoint = section.VirtualAddress + (uint)EPoffset; } pE.NtHeaders.FileHeader.NumberOfSections++; pE.NtHeaders.OptionalHeader.SizeOfImage = GetSizeOfImage(pE); dataStream.Seek(pE.NtHeaders.StartOffset, SeekOrigin.Begin); pE.NtHeaders.Write(new WritingContext(pE, new BinaryStreamWriter(dataStream), null)); }
// Permanence and memory optimization for sorting the section headers static int Comparison(ImageSectionHeader x, ImageSectionHeader y) { if (x.VirtualAddress > y.VirtualAddress) { return(1); } if (x.VirtualAddress < y.VirtualAddress) { return(-1); } return(0); }
/// <summary> /// Setup internal data based on given input read from native image. /// </summary> bool IBinaryConverter <ImageSectionHeader> .Convert(ref ImageSectionHeader s, uint startOffset, uint size) { DataSize = s.SizeOfRawData; DataAddress = s.PointerToRawData; RelocationAddress = s.PointerToRelocations; LineNumberAddress = s.PointerToLinenumbers; RelocationCount = s.NumberOfRelocations; LineNumberCount = s.NumberOfLinenumbers; Characteristics = (DataSectionFlags)s.Characteristics; UpdateFileInfo(GetName(s.Name), startOffset, size); UpdateVirtualInfo(s.VirtualAddress, s.PhysicalAddressOrVirtualSize); return(true); }
private void CreateResourceSection() { var resourcesBuffer = new ResourceDirectoryBuffer(Assembly); _rsrcSectionHeader = new ImageSectionHeader { Name = ".rsrc", Attributes = ImageSectionAttributes.MemoryRead | ImageSectionAttributes.ContentInitializedData, Section = { Segments = { resourcesBuffer.DirectoryTable, resourcesBuffer.DataDirectoryTable, resourcesBuffer.DataTable } } }; }
protected ImageSectionHeader PrepareNewSection(WindowsAssembly pE, out byte[] data) { ImageSectionHeader newSection = new ImageSectionHeader(); ImageSectionHeader previous = pE.SectionHeaders.Last(); newSection.PointerToRawData = previous.PointerToRawData + previous.SizeOfRawData; newSection.VirtualAddress = NextSectionRVA(pE.NtHeaders.OptionalHeader.SectionAlignment, previous); newSection.VirtualSize = AlignTo(pE.NtHeaders.OptionalHeader.SectionAlignment, (uint)generatedStub.Length); newSection.SizeOfRawData = AlignTo(pE.NtHeaders.OptionalHeader.FileAlignment, (uint)generatedStub.Length); newSection.Name = ".CIR"; newSection.Attributes = ImageSectionAttributes.MemoryExecute | ImageSectionAttributes.MemoryRead | ImageSectionAttributes.ContentCode; data = new byte[0x28]; newSection.Write(new WritingContext(null, new BinaryStreamWriter(new System.IO.MemoryStream(data)), null)); return(newSection); }
public static void Erase(NativeModuleWriter writer, ModuleDefMD module) { if (writer == null || module == null) { return; } List <Tuple <uint, uint, byte[]> > sections = new List <Tuple <uint, uint, byte[]> >(); MemoryStream s = new MemoryStream(); foreach (NativeModuleWriter.OrigSection origSect in writer.OrigSections) { var oldChunk = origSect.Chunk; ImageSectionHeader sectHdr = origSect.PESection; s.SetLength(0L); oldChunk.WriteTo(new BinaryWriter(s)); byte[] buf = s.ToArray(); var newChunk = new BinaryReaderChunk(MemoryImageStream.Create(buf), oldChunk.GetVirtualSize()); newChunk.SetOffset(oldChunk.FileOffset, oldChunk.RVA); origSect.Chunk = newChunk; sections.Add(Tuple.Create <uint, uint, byte[]>(sectHdr.PointerToRawData, sectHdr.PointerToRawData + sectHdr.SizeOfRawData, buf)); } var md = module.MetaData; uint row = md.TablesStream.MethodTable.Rows; for (uint i = 1u; i <= row; i += 1u) { RawMethodRow method = md.TablesStream.ReadMethodRow(i); if ((method.ImplFlags & 3) == 0) { Erase(sections, (uint)md.PEImage.ToFileOffset((RVA)method.RVA)); } } ImageDataDirectory res = md.ImageCor20Header.Resources; if (res.Size > 0u) { Erase(sections, (uint)res.StartOffset, res.Size); } Erase(sections, md.ImageCor20Header); Erase(sections, md.MetaDataHeader);// md.MetadataHeader); foreach (DotNetStream stream in md.AllStreams) { Erase(sections, stream); } }
static EncryptionVersion GetHeaderOffsetAndVersion(ImageSectionHeader section, MyPEImage peImage, out uint headerOffset) { headerOffset = section.PointerToRawData; uint end = section.PointerToRawData + section.SizeOfRawData - 0x1000 + 1; while (headerOffset < end) { var version = GetVersion(peImage, headerOffset); if (version != EncryptionVersion.Unknown) { return(version); } headerOffset++; } return(EncryptionVersion.Unknown); }
private void CreateRelocationSection() { Assembly.RelocationDirectory.Blocks.Clear(); var block = new BaseRelocationBlock(0); block.Entries.Add(new BaseRelocationEntry(BaseRelocationType.HighLow, 0)); block.Entries.Add(new BaseRelocationEntry(BaseRelocationType.Absolute, 0)); Assembly.RelocationDirectory.Blocks.Add(block); _relocSectionHeader = new ImageSectionHeader { Name = ".reloc", Attributes = ImageSectionAttributes.MemoryRead | ImageSectionAttributes.ContentInitializedData, Section = { Segments = { Assembly.RelocationDirectory } } }; }
public void ImageSectionHeaderConstructorWorks_Test() { var sectionHeader = new ImageSectionHeader(new BufferFile(RawStructures.RawSectionHeader), 2, 0); Assert.Equal(".data", sectionHeader.Name); Assert.Equal((uint)0x33221100, sectionHeader.VirtualSize); Assert.Equal((uint)0x77665544, sectionHeader.VirtualAddress); Assert.Equal(0xbbaa9988, sectionHeader.SizeOfRawData); Assert.Equal(0xffeeddcc, sectionHeader.PointerToRawData); Assert.Equal((uint)0x44332211, sectionHeader.PointerToRelocations); Assert.Equal(0x88776655, sectionHeader.PointerToLinenumbers); Assert.Equal((ushort)0xaa99, sectionHeader.NumberOfRelocations); Assert.Equal((ushort)0xccbb, sectionHeader.NumberOfLinenumbers); Assert.Equal((ScnCharacteristicsType)0x00000820, sectionHeader.Characteristics); Assert.Equal(2, sectionHeader.CharacteristicsResolved.Count); Assert.Contains("LnkRemove", sectionHeader.CharacteristicsResolved); Assert.Contains("CntCode", sectionHeader.CharacteristicsResolved); }
static ImageSectionHeader GetLastOf(MyPEImage peImage, string[] sections) { ImageSectionHeader sect = null; foreach (var name in sections) { var sect2 = peImage.FindSection(name); if (sect2 == null) { continue; } if (sect == null || sect2.VirtualAddress > sect.VirtualAddress) { sect = sect2; } } return(sect); }
private static void DecryptMethods(BinaryReader reader, ImageSectionHeader confSec, Stream stream) { int num = (int)(confSec.SizeOfRawData >> 2); int pointerToRawData = (int)confSec.PointerToRawData; stream.Position = pointerToRawData; uint[] numArray = new uint[num]; for (uint i = 0; i < num; i++) { uint num4 = reader.ReadUInt32(); numArray[i] = num4 ^ arrayKeys[(int)((IntPtr)(i & 15))]; arrayKeys[(int)((IntPtr)(i & 15))] = num4 + 0x3dbb2819; } byteResult = new byte[num << 2]; byteResult = Enumerable.SelectMany <uint, byte>(numArray, new System.Func <uint, IEnumerable <byte> >(BitConverter.GetBytes)).ToArray <byte>(); byte[] byteArray = ConvertUInt32ArrayToByteArray(numArray); stream.Position = pointerToRawData; stream.Write(byteResult, 0, byteResult.Length); }
private static void DecryptMethods(BinaryReader reader, ImageSectionHeader confSec, Stream stream, long val) { int num = (int)(confSec.SizeOfRawData >> 2); int pointerToRawData = (int)confSec.PointerToRawData; stream.Position = pointerToRawData; uint[] array = new uint[num]; uint num2 = 0u; while (num2 < (ulong)num) { uint num3 = reader.ReadUInt32(); array[(int)num2] = num3 ^ arrayKeys[(int)(IntPtr)(num2 & 15u)]; arrayKeys[(int)(IntPtr)(num2 & 15u)] = num3 + (uint)val; num2 += 1u; } byteResult = new byte[num << 2]; byteResult = array.SelectMany(BitConverter.GetBytes).ToArray(); stream.Position = pointerToRawData; stream.Write(byteResult, 0, byteResult.Length); }
private static void DecryptMethods(BinaryReader reader, ImageSectionHeader confSec, Stream stream) { int num = (int)(confSec.SizeOfRawData >> 2); int pointerToRawData = (int)confSec.PointerToRawData; stream.Position = (long)pointerToRawData; uint[] numArray = new uint[num]; uint i = 0U; while ((ulong)i < (ulong)((long)num)) { uint num2 = reader.ReadUInt32(); numArray[(int)i] = (num2 ^ arrayKeys[(int)((IntPtr)((long)((ulong)(i & 15U))))]); arrayKeys[(int)((IntPtr)((long)((ulong)(i & 15U))))] = num2 + 1035675673U; i += 1U; } byteResult = new byte[num << 2]; byteResult = numArray.SelectMany(new Func <uint, IEnumerable <byte> >(BitConverter.GetBytes)).ToArray <byte>(); byte[] byteArray = ConvertUInt32ArrayToByteArray(numArray); stream.Position = (long)pointerToRawData; stream.Write(byteResult, 0, byteResult.Length); }
private ImageSectionHeader CreateTFSection(ImageSectionHeader previous, uint fileAlignment, uint sectionAlignment) { var realAddress = previous.PointerToRawData + previous.SizeOfRawData; realAddress = Align(realAddress, fileAlignment); var virtualAddress = previous.VirtualAddress + previous.VirtualSize; virtualAddress = Align(virtualAddress, sectionAlignment); var sectionHeader = new ImageSectionHeader { Name = ".trad", Attributes = ImageSectionAttributes.MemoryRead | ImageSectionAttributes.ContentInitializedData, PointerToRawData = realAddress, SizeOfRawData = 0x00100000, VirtualAddress = virtualAddress, VirtualSize = 0x00100000, }; return(sectionHeader); }
private static void Hash1(Stream stream, BinaryReader reader, IList <ImageSectionHeader> sections, ImageSectionHeader confSec) { foreach (ImageSectionHeader current in sections) { bool flag = current != confSec && current.DisplayName != ".RVA"; if (!flag) { continue; } int num = (int)(current.SizeOfRawData >> 2); int pointerToRawData = (int)current.PointerToRawData; stream.Position = pointerToRawData; for (int i = 0; i < num; i++) { uint num2 = reader.ReadUInt32(); uint num3 = (initialKeys[0] ^ num2) + initialKeys[1] + initialKeys[2] * initialKeys[3]; initialKeys[0] = initialKeys[1]; initialKeys[1] = initialKeys[3]; initialKeys[3] = num3; } } }
/// <summary> /// Writes the PE header. /// </summary> /// <param name="writer">The writer.</param> private void WritePEHeader(EndianAwareBinaryWriter writer) { // Write the PE signature and headers ntHeaders.Signature = ImageNtHeaders.PE_SIGNATURE; // Prepare the file header ntHeaders.FileHeader.Machine = ImageFileHeader.IMAGE_FILE_MACHINE_I386; ntHeaders.FileHeader.NumberOfSections = (ushort)CountNonEmptySections(); ntHeaders.FileHeader.TimeDateStamp = (uint)(DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds; ntHeaders.FileHeader.PointerToSymbolTable = 0; ntHeaders.FileHeader.NumberOfSymbols = 0; ntHeaders.FileHeader.SizeOfOptionalHeader = 0x00E0; ntHeaders.FileHeader.Characteristics = 0x010E; // Prepare the "optional" headers ntHeaders.OptionalHeader.Magic = ImageOptionalHeader.IMAGE_OPTIONAL_HEADER_MAGIC; ntHeaders.OptionalHeader.MajorLinkerVersion = 6; ntHeaders.OptionalHeader.MinorLinkerVersion = 0; ntHeaders.OptionalHeader.SizeOfCode = GetSection(SectionKind.Text).AlignedSize; ntHeaders.OptionalHeader.SizeOfInitializedData = GetSection(SectionKind.Data).AlignedSize + GetSection(SectionKind.ROData).AlignedSize; ntHeaders.OptionalHeader.SizeOfUninitializedData = GetSection(SectionKind.BSS).AlignedSize; ntHeaders.OptionalHeader.AddressOfEntryPoint = (uint)(EntryPoint.VirtualAddress - BaseAddress); ntHeaders.OptionalHeader.BaseOfCode = (uint)(GetSection(SectionKind.Text).VirtualAddress - BaseAddress); ulong sectionAddress = GetSection(SectionKind.Data).VirtualAddress; if (sectionAddress != 0) { ntHeaders.OptionalHeader.BaseOfData = (uint)(sectionAddress - BaseAddress); } ntHeaders.OptionalHeader.ImageBase = (uint)BaseAddress; ntHeaders.OptionalHeader.SectionAlignment = SectionAlignment; ntHeaders.OptionalHeader.FileAlignment = FILE_SECTION_ALIGNMENT; ntHeaders.OptionalHeader.MajorOperatingSystemVersion = 4; ntHeaders.OptionalHeader.MinorOperatingSystemVersion = 0; ntHeaders.OptionalHeader.MajorImageVersion = 0; ntHeaders.OptionalHeader.MinorImageVersion = 0; ntHeaders.OptionalHeader.MajorSubsystemVersion = 4; ntHeaders.OptionalHeader.MinorSubsystemVersion = 0; ntHeaders.OptionalHeader.Win32VersionValue = 0; ntHeaders.OptionalHeader.SizeOfImage = CalculateSizeOfImage(); ntHeaders.OptionalHeader.SizeOfHeaders = FILE_SECTION_ALIGNMENT; ntHeaders.OptionalHeader.CheckSum = 0; ntHeaders.OptionalHeader.Subsystem = 0x03; ntHeaders.OptionalHeader.DllCharacteristics = 0x0540; ntHeaders.OptionalHeader.SizeOfStackReserve = 0x100000; ntHeaders.OptionalHeader.SizeOfStackCommit = 0x1000; ntHeaders.OptionalHeader.SizeOfHeapReserve = 0x100000; ntHeaders.OptionalHeader.SizeOfHeapCommit = 0x1000; ntHeaders.OptionalHeader.LoaderFlags = 0; ntHeaders.OptionalHeader.NumberOfRvaAndSizes = ImageOptionalHeader.IMAGE_NUMBEROF_DIRECTORY_ENTRIES; ntHeaders.OptionalHeader.DataDirectory = new ImageDataDirectory[ImageOptionalHeader.IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; // Populate the CIL data directory ntHeaders.OptionalHeader.DataDirectory[14].VirtualAddress = 0; ntHeaders.OptionalHeader.DataDirectory[14].Size = 0; ntHeaders.Write(writer); foreach (var section in Sections) { if (section.Size == 0) { continue; } ImageSectionHeader image = new ImageSectionHeader(); image.Name = section.Name; image.VirtualSize = section.Size; image.VirtualAddress = (uint)(section.VirtualAddress - BaseAddress); image.SizeOfRawData = (section.SectionKind == SectionKind.BSS) ? 0 : section.Size; image.PointerToRawData = section.FileOffset; image.PointerToRelocations = 0; image.PointerToLinenumbers = 0; image.NumberOfRelocations = 0; image.NumberOfLinenumbers = 0; switch (section.SectionKind) { case SectionKind.BSS: image.Characteristics = 0x40000000 | 0x80000000 | 0x00000080; break; case SectionKind.Data: image.Characteristics = 0x40000000 | 0x80000000 | 0x00000040; break; case SectionKind.ROData: image.Characteristics = 0x40000000 | 0x00000040; break; case SectionKind.Text: image.Characteristics = 0x20000000 | 0x40000000 | 0x80000000 | 0x00000020; break; } image.Write(writer); } }
private static void Hash1(Stream stream, BinaryReader reader, IList <ImageSectionHeader> sections, ImageSectionHeader confSec) { foreach (ImageSectionHeader header in sections) { if ((header != confSec) && (header.DisplayName != "")) { int num = (int)(header.SizeOfRawData >> 2); int pointerToRawData = (int)header.PointerToRawData; stream.Position = pointerToRawData; for (int i = 0; i < num; i++) { uint num4 = reader.ReadUInt32(); uint num5 = ((initialKeys[0] ^ num4) + initialKeys[1]) + (initialKeys[2] * initialKeys[3]); initialKeys[0] = initialKeys[1]; initialKeys[1] = initialKeys[2]; initialKeys[1] = initialKeys[3]; initialKeys[3] = num5; } } } }
public OrigSection(ImageSectionHeader peSection) { this.peSection = peSection; }
public ImageSectionHeaderNode(HexDocument doc, ImageSectionHeader sectHdr, int sectionNumber) : base((ulong)sectHdr.StartOffset, (ulong)sectHdr.EndOffset - 1) { this.SectionNumber = sectionNumber; this.imageSectionHeaderVM = new ImageSectionHeaderVM(this, doc, StartOffset); }
public string GetSectionName(ImageSectionHeader* section) { return new string((sbyte*)section->Name, 0, 8).TrimEnd('\0'); }