Exemplo n.º 1
0
        internal PeImage(Memory <byte> imageBytes)
        {
            using var peReader = new PEReader(new MemoryStream(imageBytes.ToArray()));

            BaseRelocationDirectory = new BaseRelocationDirectory(peReader.PEHeaders, imageBytes);

            DelayImportDirectory = new DelayImportDirectory(peReader.PEHeaders, imageBytes);

            ExportDirectory = new ExportDirectory(peReader.PEHeaders, imageBytes);

            Headers = peReader.PEHeaders;

            ImportDirectory = new ImportDirectory(peReader.PEHeaders, imageBytes);

            LoadConfigDirectory = new LoadConfigDirectory(peReader.PEHeaders, imageBytes);

            var debugDirectoryEntries = peReader.ReadDebugDirectory();

            if (debugDirectoryEntries.Any(entry => entry.Type == DebugDirectoryEntryType.CodeView))
            {
                var codeViewEntry = debugDirectoryEntries.First(entry => entry.Type == DebugDirectoryEntryType.CodeView);

                PdbData = peReader.ReadCodeViewDebugDirectoryData(codeViewEntry);
            }

            TlsDirectory = new TlsDirectory(peReader.PEHeaders, imageBytes);

            ValidatePeImage();
        }
Exemplo n.º 2
0
        public PEFile(string file)
        {
            if (String.IsNullOrWhiteSpace(file))
            {
                throw new ArgumentException("PE file cannot be null or empty.");
            }

            exdir    = new ExportDirectory(file);
            FileName = file;
        }
Exemplo n.º 3
0
        internal PeImage(Memory <byte> imageBytes)
        {
            using var peReader = new PEReader(imageBytes.ToArray().ToImmutableArray());

            if (peReader.PEHeaders.PEHeader is null || !peReader.PEHeaders.IsDll)
            {
                throw new BadImageFormatException("The provided file was not a valid DLL");
            }

            ExportDirectory = new ExportDirectory(peReader.PEHeaders, imageBytes);
        }
Exemplo n.º 4
0
        public async Task <DataContent> GetContentAsync()
        {
            if (VirtualAddress == 0 || Size == 0)
            {
                return(null);
            }

            switch (DirectoryType)
            {
            case DataDirectoryType.LoadConfigTable:
                return(await LoadConfigurationDirectory.GetAsync(_image).ConfigureAwait(false));

            case DataDirectoryType.TLSTable:
                return(await TLSDirectory.GetAsync(_image).ConfigureAwait(false));

            case DataDirectoryType.CertificateTable:
                return(await Certificate.GetAsync(_image).ConfigureAwait(false));

            case DataDirectoryType.CLRRuntimeHeader:
                return(await CLR.GetAsync(_image).ConfigureAwait(false));

            case DataDirectoryType.Debug:
                return(await DebugDirectory.GetAsync(_image).ConfigureAwait(false));

            case DataDirectoryType.BaseRelocationTable:
                return(await RelocationTable.GetAsync(_image).ConfigureAwait(false));

            case DataDirectoryType.ExportTable:
                return(await ExportDirectory.GetAsync(_image).ConfigureAwait(false));

            case DataDirectoryType.ImportTable:
                return(await ImportDirectory.GetAsync(_image).ConfigureAwait(false));

            case DataDirectoryType.DelayImportDescriptor:
                return(await DelayedImportDirectory.GetAsync(_image).ConfigureAwait(false));

            case DataDirectoryType.ExceptionTable:
                return(await ExceptionTable.GetAsync(_image).ConfigureAwait(false));

            case DataDirectoryType.ResourceTable:
                return(await ResourceDirectory.GetAsync(_image).ConfigureAwait(false));

            default:
            {
                var calc       = _image.GetCalculator();
                var fileOffset = calc.RVAToOffset(VirtualAddress);
                var va         = _imageBase + VirtualAddress;
                var location   = new Location(_image, fileOffset, VirtualAddress, va, Size, Size);

                return(new DataContent(_image, this, location));
            }
            }
        }
Exemplo n.º 5
0
        internal PeImage(Memory <byte> imageBytes)
        {
            using var peReader = new PEReader(imageBytes.ToArray().ToImmutableArray());

            if (peReader.PEHeaders.PEHeader is null || !peReader.PEHeaders.IsDll)
            {
                throw new BadImageFormatException("The provided file was not a valid DLL");
            }

            ExportDirectory     = new ExportDirectory(peReader.PEHeaders, imageBytes);
            Headers             = peReader.PEHeaders;
            ImportDirectory     = new ImportDirectory(peReader.PEHeaders, imageBytes);
            LoadConfigDirectory = new LoadConfigDirectory(peReader.PEHeaders, imageBytes);
            RelocationDirectory = new RelocationDirectory(peReader.PEHeaders, imageBytes);
            ResourceDirectory   = new ResourceDirectory(peReader.PEHeaders, imageBytes);
            TlsDirectory        = new TlsDirectory(peReader.PEHeaders, imageBytes);
        }
Exemplo n.º 6
0
        private static IntPtr GetFunctionAddressFromExportDirectory(byte[] exportDirectoryBuffer, uint exportTableRva, string functionName)
        {
            uint RvaToDirectoryPosition(uint address) => address - exportTableRva;

            using (var reader = new BinaryReader(new MemoryStream(exportDirectoryBuffer)))
            {
                var exportDirectory = new ExportDirectory(reader);

                var functionAddress      = IntPtr.Zero;
                var exportFunctionOffset = RvaToDirectoryPosition(exportDirectory.AddressOfFunctions);
                var ordinalOffset        = RvaToDirectoryPosition(exportDirectory.AddressOfNameOrdinals);
                var exportNameOffset     = RvaToDirectoryPosition(exportDirectory.AddressOfNames);

                reader.BaseStream.Position = exportNameOffset;
                for (var i = 0; i < exportDirectory.NumberOfNames; ++i)
                {
                    reader.BaseStream.Position = exportNameOffset + (i * sizeof(uint));

                    var nameOffset = reader.ReadUInt32();
                    if (nameOffset == 0)
                    {
                        continue;
                    }

                    reader.BaseStream.Position = RvaToDirectoryPosition(nameOffset);
                    if (functionName == ReadAsciiString(reader))
                    {
                        reader.BaseStream.Position = ordinalOffset + (i * sizeof(ushort));
                        var ordinalIndex = reader.ReadUInt16();
                        if (ordinalIndex >= exportDirectory.NumberOfFunctions)
                        {
                            throw new Win32Exception(
                                      $"Function ordinal out of range {ordinalIndex} >= {exportDirectory.NumberOfFunctions}");
                        }

                        reader.BaseStream.Position = exportFunctionOffset + (ordinalIndex * sizeof(uint));
                        functionAddress            = new IntPtr(reader.ReadUInt32());
                    }
                }
                return(functionAddress);
            }
        }
Exemplo n.º 7
0
        internal PeImage(Memory <byte> imageBuffer)
        {
            using var peReader = new PEReader(new MemoryStream(imageBuffer.ToArray()));

            BaseRelocationDirectory = new BaseRelocationDirectory(peReader.PEHeaders, imageBuffer);

            DelayImportDirectory = new DelayImportDirectory(peReader.PEHeaders, imageBuffer);

            ExportDirectory = new ExportDirectory(peReader.PEHeaders, imageBuffer);

            Headers = peReader.PEHeaders;

            ImportDirectory = new ImportDirectory(peReader.PEHeaders, imageBuffer);

            LoadConfigDirectory = new LoadConfigDirectory(peReader.PEHeaders, imageBuffer);

            TlsDirectory = new TlsDirectory(peReader.PEHeaders, imageBuffer);

            ValidatePeImage();
        }
Exemplo n.º 8
0
        public void ExportDataTable(DataTable dtDataTable)
        {
            string FilePath = ExportDirectory.TrimEnd('\\') + "\\" + dtDataTable.TableName + Extension;

            StringBuilder sb = new StringBuilder();

            IEnumerable <string> columnNames = dtDataTable.Columns.Cast <DataColumn>().
                                               Select(column => column.ColumnName);

            sb.AppendLine(string.Join(",", columnNames));

            foreach (DataRow row in dtDataTable.Rows)
            {
                IEnumerable <string> fields = row.ItemArray.Select(field =>
                                                                   string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
                sb.AppendLine(string.Join(",", fields));
            }

            File.WriteAllText(FilePath, sb.ToString());
        }
Exemplo n.º 9
0
        public void PersistentExportedSymbol()
        {
            var image = PEImage.FromBytes(Properties.Resources.HelloWorld);

            // Prepare mock.
            var exportDirectory = new ExportDirectory("HelloWorld.dll");
            var exportedSymbol  = new ExportedSymbol(new VirtualAddress(0x12345678), "TestExport");

            exportDirectory.Entries.Add(exportedSymbol);
            image.Exports = exportDirectory;

            // Rebuild.
            var newImage = RebuildAndReloadManagedPE(image);

            // Verify.
            Assert.Equal(1, newImage.Exports.Entries.Count);
            var newExportedSymbol = newImage.Exports.Entries[0];

            Assert.Equal(exportedSymbol.Name, newExportedSymbol.Name);
            Assert.Equal(exportedSymbol.Ordinal, newExportedSymbol.Ordinal);
            Assert.Equal(exportedSymbol.Address.Rva, newExportedSymbol.Address.Rva);
        }
Exemplo n.º 10
0
        internal ExportTable(IoMemory mem, UIntPtr imageBase, DirectoryEntry entry)
        {
            this.mem   = mem;
            this.entry = entry;

            try {
                exports = new ExportDirectory(mem, (int)entry.virtualAddress);

                if (exports.NumberOfFunctions > 0)
                {
                    addresses = new UIntPtr[exports.NumberOfFunctions];
                    for (uint i = 0; i < exports.NumberOfFunctions; i++)
                    {
                        addresses[i] = imageBase
                                       + mem.Read32Unchecked((int)(exports.AddressOfFunctions + 4 * i));
                    }
                }

                if (exports.NumberOfNames > 0)
                {
                    names    = new string[exports.NumberOfNames];
                    ordinals = new ushort[exports.NumberOfNames];
                    for (uint i = 0; i < exports.NumberOfNames; i++)
                    {
                        ordinals[i]
                            = mem.Read16Unchecked((int)(exports.AddressOfOrdinals + 2 * i));
                        uint addrOfName
                                 = mem.Read32Unchecked((int)(exports.AddressOfNames + 4 * i));
                        names[i] = mem.ReadAsciiZeroString((int)addrOfName);
                    }
                }
            }
            catch (Exception e) {
                DebugStub.Print("Caught exception: {0}\n",
                                __arglist(e.ToString()));
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 读取基本信息
        /// </summary>
        public void ReadInfo(BinaryReader reader)
        {
            //Seek(reader, 0x3c);
            //PEoffset = reader.ReadInt32();

            //Seek(reader, PEoffset + 0x34);
            //ImageBase = reader.ReadUInt32();

            //Seek(reader, PEoffset + 0x28);
            //PEEntry = reader.ReadUInt32() + ImageBase;
            //KernelWin.WriteLine("PEEntry:0x{0:X}", PEEntry);

            //PEEntry = Entry.GetEntryPoint(Entry.GetEntryOrdinal(0));
            //KernelWin.WriteLine("EntryOrdinal:0x{0:X}", Entry.GetEntryOrdinal(0));
            //KernelWin.WriteLine("PEEntry:0x{0:X}", PEEntry);

            DosHeader dosHeader = new DosHeader();

            dosHeader.Read(reader);

            PEoffset  = dosHeader.NewExeHeader;
            ImageBase = (UInt32)dosHeader.OptionalHeader.ImageBase;

            ExportDirectory export  = dosHeader.OptionalHeader.Export;
            Int32           address = 0;

            if (export != null)
            {
                Seek(reader, export.AddressOfFunctions);
                address = reader.ReadInt32();
            }
            else
            {
                address = dosHeader.OptionalHeader.AddressOfEntryPoint;
            }
            PEEntry = (UInt32)address + ImageBase;

            Seek(reader, PEEntry - ImageBase);
            long temp = reader.ReadByte();

            if (temp == 0x68)
            {
                temp = PEEntry + 1 - ImageBase;
            }
            else if (temp == 0x58)
            {
                temp = PEEntry + 2 - ImageBase;
            }
            Seek(reader, temp);

            Header = reader.ReadUInt32();
            //VBSig = IDCFunction.EvalAndReturnLong("Dword(" + VBHeader + ")");
            //VBSig = Bytes.Dword(Header);
            if (Header - ImageBase > reader.BaseStream.Length)
            {
                throw new Exception("非VB文件格式!");
            }

            Seek(reader, Header - ImageBase);
            VBSig = reader.ReadUInt32();

            if (VBSig != 0x21354256)    //VB5
            {
                throw new Exception(String.Format("错误VB签名:0x{0:X}", VBSig));
            }

            //temp = IDCFunction.EvalAndReturnLong("Word(" + VBHeader + "+0x22)");
            //temp = Bytes.Word((UInt32)Header + 0x22);
            Seek(reader, Header + 0x22 - ImageBase);
            temp = reader.ReadInt16();
            if (temp < 0x0a)
            {
                throw new Exception("不是VB6程序!");
            }

            Seek(reader, Header - ImageBase);
            VBHeader header = new VBHeader();

            header.Info = this;
            header.Read(reader);

            HeaderInfo = header;
        }
Exemplo n.º 12
0
        /// <summary>
        /// 读取输出表
        /// </summary>
        private void LoadExportDirectory()
        {

            if (_OptionalDirAttrib.DirByte.Count == 0) return;
            OptionalDirAttrib.DirAttrib ExporRVA = (OptionalDirAttrib.DirAttrib)_OptionalDirAttrib.DirByte[0];
            if (GetLong(ExporRVA.DirRva) == 0) return;


            long ExporAddress = GetLong(ExporRVA.DirRva);  //获取的位置

            _ExportDirectory = new ExportDirectory();
            for (int i = 0; i != _SectionTable.Section.Count; i++) //循环节表
            {
                SectionTable.SectionData Sect = (SectionTable.SectionData)_SectionTable.Section[i];

                long StarRva = GetLong(Sect.SizeOfRawDataRVA);
                long EndRva = GetLong(Sect.SizeOfRawDataSize);

                if (ExporAddress >= StarRva && ExporAddress < StarRva + EndRva)
                {
                    PEFileIndex = ExporAddress - GetLong(Sect.SizeOfRawDataRVA) + GetLong(Sect.PointerToRawData);

                    _ExportDirectory.FileStarIndex = PEFileIndex;
                    _ExportDirectory.FileEndIndex = PEFileIndex + GetLong(ExporRVA.DirSize);

                    Loadbyte(ref _ExportDirectory.Characteristics);
                    Loadbyte(ref _ExportDirectory.TimeDateStamp);
                    Loadbyte(ref _ExportDirectory.MajorVersion);
                    Loadbyte(ref _ExportDirectory.MinorVersion);
                    Loadbyte(ref _ExportDirectory.Name);
                    Loadbyte(ref _ExportDirectory.Base);
                    Loadbyte(ref _ExportDirectory.NumberOfFunctions);
                    Loadbyte(ref _ExportDirectory.NumberOfNames);
                    Loadbyte(ref _ExportDirectory.AddressOfFunctions);
                    Loadbyte(ref _ExportDirectory.AddressOfNames);
                    Loadbyte(ref _ExportDirectory.AddressOfNameOrdinals);

                    PEFileIndex = GetLong(_ExportDirectory.AddressOfFunctions) - GetLong(Sect.SizeOfRawDataRVA) + GetLong(Sect.PointerToRawData);
                    long EndIndex = GetLong(_ExportDirectory.AddressOfNames) - GetLong(Sect.SizeOfRawDataRVA) + GetLong(Sect.PointerToRawData);
                    long Numb = (EndIndex - PEFileIndex) / 4;
                    for (long z = 0; z != Numb; z++)
                    {
                        byte[] Data = new byte[4];
                        Loadbyte(ref Data);
                        _ExportDirectory.AddressOfFunctionsList.Add(Data);
                    }

                    Numb = 0;
                    PEFileIndex = EndIndex;
                    EndIndex = GetLong(_ExportDirectory.AddressOfNameOrdinals) - GetLong(Sect.SizeOfRawDataRVA) + GetLong(Sect.PointerToRawData);
                    Numb = (EndIndex - PEFileIndex) / 4;
                    for (long z = 0; z != Numb; z++)
                    {
                        byte[] Data = new byte[4];
                        Loadbyte(ref Data);
                        _ExportDirectory.AddressOfNamesList.Add(Data);
                    }

                    Numb = 0;
                    PEFileIndex = EndIndex;
                    EndIndex = GetLong(_ExportDirectory.Name) - GetLong(Sect.SizeOfRawDataRVA) + GetLong(Sect.PointerToRawData);
                    Numb = (EndIndex - PEFileIndex) / 2;
                    for (long z = 0; z != Numb; z++)
                    {
                        byte[] Data = new byte[2];
                        Loadbyte(ref Data);
                        _ExportDirectory.AddressOfNameOrdinalsList.Add(Data);
                    }


                    PEFileIndex = EndIndex;

                    long ReadIndex = 0;
                    while (true)
                    {
                        if (PEFileByte[PEFileIndex + ReadIndex] == 0)
                        {
                            if (PEFileByte[PEFileIndex + ReadIndex + 1] == 0) break;

                            byte[] Date = new byte[ReadIndex];
                            Loadbyte(ref Date);
                            _ExportDirectory.NameList.Add(Date);

                            PEFileIndex++;
                            ReadIndex = 0;
                        }
                        ReadIndex++;
                    }
                    break;
                }

            }

        }