예제 #1
0
        public void OptionalHeader_NonEmptyDataDirectories()
        {
            var oh = new OptionalHeader();

            oh.PEMagic             = PEMagic.NT32;
            oh.Subsystem           = Subsystem.WindowsCUI;
            oh.DllCharacteristics  = DllCharacteristics.TerminalServerAware;
            oh.NumberOfRvaAndSizes = 4;

            oh.DataDirectories = new DataDirectory[4];

            oh.DataDirectories[0] = new DataDirectory {
                Size = 5
            };
            oh.DataDirectories[1] = new DataDirectory {
                Size = 6
            };
            oh.DataDirectories[2] = new DataDirectory {
                Size = 100
            };
            oh.DataDirectories[3] = new DataDirectory {
                VirtualAddress = 10, Size = 20
            };

            Assert.AreEqual("NT32 WindowsCUI TerminalServerAware DataDirectories[ExportSymbols,ImportSymbols,Resources,Exception]", oh.ToString());
        }
예제 #2
0
        /// <summary>
        /// Writes the PE file to the provided output stream.
        /// </summary>
        /// <param name="writer">The output stream to write to.</param>
        public void Write(IBinaryStreamWriter writer)
        {
            UpdateHeaders();

            // Dos header.
            DosHeader.Write(writer);

            // NT headers
            writer.FileOffset = DosHeader.NextHeaderOffset;

            writer.WriteUInt32(ValidPESignature);
            FileHeader.Write(writer);
            OptionalHeader.Write(writer);

            // Section headers.
            writer.FileOffset = OptionalHeader.FileOffset + FileHeader.SizeOfOptionalHeader;
            foreach (var section in Sections)
            {
                section.CreateHeader().Write(writer);
            }

            // Data between section headers and sections.
            ExtraSectionData?.Write(writer);

            // Sections.

            writer.FileOffset = OptionalHeader.SizeOfHeaders;
            foreach (var section in Sections)
            {
                writer.FileOffset = section.FileOffset;
                section.Contents.Write(writer);
                writer.Align(OptionalHeader.FileAlignment);
            }
        }
예제 #3
0
        internal void Read(PeReader rdr)
        {
            rdr.SetPosition(0);
            if (t == PeFileType.Image)
            {
                dos = new DOSHeader(this);
                dos.Read(rdr);

                rdr.SetPosition(dos.PEHeaderOffset);
                sign = rdr.ReadBytes(4);

                pe = new PEHeader(this);
                pe.Read(rdr);

                op = new OptionalHeader(this);
                op.Read(rdr);

                sects = new SectionHeaders(this);
                sects.Read(rdr);

                certs = new CertificateDirectory(op.DataDirectories[DataDirectoryType.Certificate]);
                certs.Load(rdr, op.DataDirectories[DataDirectoryType.Certificate].Address.Value);
            }
            else if (t == PeFileType.Object)
            {
                pe = new PEHeader(this);
                pe.Read(rdr);

                sects = new SectionHeaders(this);
                sects.Read(rdr);
            }
        }
예제 #4
0
        public PE(MemoryStream input, long maxMetadataUsages) : base(input)
        {
            raw = input.GetBuffer();
            Console.Write("Reading PE File Header...");
            var start = DateTime.Now;

            this.maxMetadataUsages = maxMetadataUsages;
            if (ReadUInt16() != 0x5A4D) //Magic number
            {
                throw new Exception("ERROR: Magic number mismatch.");
            }
            Position = 0x3C;                //Signature position position (lol)
            Position = ReadUInt32();        //Signature position
            if (ReadUInt32() != 0x00004550) //Signature
            {
                throw new Exception("ERROR: Invalid PE file signature");
            }

            var fileHeader = ReadClass <FileHeader>(-1);

            if (fileHeader.Machine == 0x014c) //Intel 386
            {
                is32Bit        = true;
                optionalHeader = ReadClass <OptionalHeader>(-1);
                optionalHeader.DataDirectory = ReadClassArray <DataDirectory>(-1, optionalHeader.NumberOfRvaAndSizes);
                imageBase = optionalHeader.ImageBase;
            }
            else if (fileHeader.Machine == 0x8664) //AMD64
            {
                optionalHeader64 = ReadClass <OptionalHeader64>(-1);
                optionalHeader64.DataDirectory = ReadClassArray <DataDirectory>(-1, optionalHeader64.NumberOfRvaAndSizes);
                imageBase = optionalHeader64.ImageBase;
            }
            else
            {
                throw new Exception("ERROR: Unsupported machine.");
            }

            sections = new SectionHeader[fileHeader.NumberOfSections];
            for (var i = 0; i < fileHeader.NumberOfSections; i++)
            {
                sections[i] = new SectionHeader
                {
                    Name                 = Encoding.UTF8.GetString(ReadBytes(8)).Trim('\0'),
                    VirtualSize          = ReadUInt32(),
                    VirtualAddress       = ReadUInt32(),
                    SizeOfRawData        = ReadUInt32(),
                    PointerToRawData     = ReadUInt32(),
                    PointerToRelocations = ReadUInt32(),
                    PointerToLinenumbers = ReadUInt32(),
                    NumberOfRelocations  = ReadUInt16(),
                    NumberOfLinenumbers  = ReadUInt16(),
                    Characteristics      = ReadUInt32()
                };
            }

            Console.WriteLine($"OK ({(DateTime.Now - start).TotalMilliseconds} ms)");
            Console.WriteLine($"\tImage Base at 0x{imageBase:X}");
            Console.WriteLine($"\tDLL is {(is32Bit ? "32" : "64")}-bit");
        }
예제 #5
0
        /// <summary>
        /// Recomputes file offsets and sizes in the file, optional and section headers.
        /// </summary>
        /// <remarks>
        /// Affected fields in the file header include:
        /// <list type="bullet">
        ///     <item>
        ///         <term>SizeOfOptionalHeader</term>
        ///     </item>
        /// </list>
        /// Affected fields in the optional header include:
        /// <list type="bullet">
        ///     <item>
        ///         <term>SizeOfHeaders</term>
        ///     </item>
        /// </list>
        /// Affected fields in the section header include:
        /// <list type="bullet">
        ///     <item>
        ///         <term>VirtualAddress</term>
        ///         <term>VirtualSize</term>
        ///         <term>PointerToRawData</term>
        ///         <term>SizeOfRawData</term>
        ///     </item>
        /// </list>
        /// </remarks>
        public void UpdateHeaders()
        {
            var oldSections = Sections.Select(_ => _.CreateHeader()).ToList();

            FileHeader.NumberOfSections = (ushort)Sections.Count;

            FileHeader.UpdateOffsets(
                DosHeader.NextHeaderOffset + 4,
                DosHeader.NextHeaderOffset + 4);
            OptionalHeader.UpdateOffsets(
                FileHeader.FileOffset + FileHeader.GetPhysicalSize(),
                FileHeader.FileOffset + FileHeader.GetVirtualSize());

            FileHeader.SizeOfOptionalHeader = (ushort)OptionalHeader.GetPhysicalSize();
            OptionalHeader.SizeOfHeaders    = (OptionalHeader.FileOffset
                                               + FileHeader.SizeOfOptionalHeader
                                               + SectionHeader.SectionHeaderSize * (uint)Sections.Count)
                                              .Align(OptionalHeader.FileAlignment);

            AlignSections();
            AlignDataDirectoryEntries(oldSections);

            var lastSection = Sections[Sections.Count - 1];

            OptionalHeader.SizeOfImage = lastSection.Rva
                                         + lastSection.GetVirtualSize().Align(OptionalHeader.SectionAlignment);
        }
예제 #6
0
 public PEFile(DosHeader dosHeader, FileHeader fileHeader, OptionalHeader optionalHeader)
 {
     DosHeader      = dosHeader ?? throw new ArgumentNullException(nameof(dosHeader));
     FileHeader     = fileHeader ?? throw new ArgumentNullException(nameof(fileHeader));
     OptionalHeader = optionalHeader ?? throw new ArgumentNullException(nameof(optionalHeader));
     Sections       = new PESectionCollection(this);
 }
예제 #7
0
 /// <summary>
 /// Creates a new portable executable file.
 /// </summary>
 /// <param name="dosHeader">The DOS header to add.</param>
 /// <param name="fileHeader">The COFF header to add.</param>
 /// <param name="optionalHeader">The optional header to add.</param>
 public PEFile(DosHeader dosHeader, FileHeader fileHeader, OptionalHeader optionalHeader)
 {
     DosHeader         = dosHeader ?? throw new ArgumentNullException(nameof(dosHeader));
     FileHeader        = fileHeader ?? throw new ArgumentNullException(nameof(fileHeader));
     OptionalHeader    = optionalHeader ?? throw new ArgumentNullException(nameof(optionalHeader));
     _extraSectionData = new LazyVariable <ISegment>(GetExtraSectionData);
     MappingMode       = PEMappingMode.Unmapped;
 }
예제 #8
0
        public void OptionalHeader()
        {
            var oh = new OptionalHeader();

            oh.PEMagic            = PEMagic.NT32;
            oh.Subsystem          = Subsystem.WindowsCUI;
            oh.DllCharacteristics = DllCharacteristics.TerminalServerAware;

            Assert.AreEqual("NT32 WindowsCUI TerminalServerAware", oh.ToString());
        }
예제 #9
0
        public void OptionalHeader_EmptyDataDirectories()
        {
            var oh = new OptionalHeader();

            oh.PEMagic             = PEMagic.NT32;
            oh.Subsystem           = Subsystem.WindowsCUI;
            oh.DllCharacteristics  = DllCharacteristics.TerminalServerAware;
            oh.NumberOfRvaAndSizes = 4;

            Assert.AreEqual("NT32 WindowsCUI TerminalServerAware", oh.ToString());
        }
        private void ConstructHeaders(ExceptionCollector collector)
        {
            MsDosHeader = new MsDosHeader(collector, Window.GetSlice(0, 128));
            FileHeader  = new FileHeader(collector, Window.GetSlice(MsDosHeader.LongFileAddressOfNewExeHeader, 24));

            if (FileHeader.OptionalHeaderSize > 0)
            {
                OptionalHeader = new OptionalHeader(collector,
                                                    Window.GetSlice(MsDosHeader.LongFileAddressOfNewExeHeader + 24,
                                                                    FileHeader.OptionalHeaderSize));
            }
        }
예제 #11
0
        public XPeParser(String path)
        {
            f = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            BinaryReader br = new BinaryReader(f);

            /* Check the main signature */
            ushort dosSig = br.ReadUInt16();

            if (dosSig != IMAGE_DOS_SIGNATURE)
            {
                throw new Exception("Invalid DOS Signature for the executable!");
            }

            /* Seek to the PE header */
            br.BaseStream.Seek(0x3C, SeekOrigin.Begin);
            uint peOffset = br.ReadUInt32();

            /* Check the PE signature */
            br.BaseStream.Seek(peOffset, SeekOrigin.Begin);

            uint peSign = br.ReadUInt32();

            if (peSign != IMAGE_NT_SIGNATURE)
            {
                throw new Exception("Invalid PE Signature for the executable!");
            }

            /* Read the rest of PE header, then check some fields */
            imHdr = new ImageFileHeader(br);

            /* Specific machine value to indicate Xbox 360 */
            if (imHdr.Machine != 0x1F2)
            {
                throw new Exception("The PE is valid but it's not an Xbox 360 executable.");
            }

            /*
             * The strange thing is that imHdr.Characteristics is set to 0x102
             * (usually), indicating a 32bit architecture, while the Xenon is 64-bit.
             * Microsoft likes to mess with their own specifications...
             */
            optHdr = new OptionalHeader(br);

            sectHdrs = new SectionHeader[imHdr.NumberOfSections];
            for (int i = 0; i < imHdr.NumberOfSections; i++)
            {
                sectHdrs[i] = new SectionHeader(br);
            }

            FileName = path;
        }
            private void _read()
            {
                _peSignature      = m_io.EnsureFixedContents(new byte[] { 80, 69, 0, 0 });
                _coffHdr          = new CoffHeader(m_io, this, m_root);
                __raw_optionalHdr = m_io.ReadBytes(CoffHdr.SizeOfOptionalHeader);
                var io___raw_optionalHdr = new KaitaiStream(__raw_optionalHdr);

                _optionalHdr = new OptionalHeader(io___raw_optionalHdr, this, m_root);
                _sections    = new List <Section>((int)(CoffHdr.NumberOfSections));
                for (var i = 0; i < CoffHdr.NumberOfSections; i++)
                {
                    _sections.Add(new Section(m_io, this, m_root));
                }
            }
        internal OptionalHeader ReadOptionalHeader()
        {
            Format format;

            var magic = ReadMagic(out format);

            if (format == Format.UNKNOWN)
            {
                return(null);
            }

            var header = new OptionalHeader()
            {
                Magic = magic,
                MajorLinkerVersion      = ReadByte(),
                MinorLinkerVersion      = ReadByte(),
                SizeOfCode              = ReadUInt32(),
                SizeOfInitializedData   = ReadUInt32(),
                SizeOfUninitializedData = ReadUInt32(),
                AddressOfEntryPoint     = ReadUInt32(),
                BaseOfCode              = ReadUInt32(),
                BaseOfData              = (format == Format.PE32_PLUS) ? ReadUInt32() : 0
            };

            header.ImageBase             = (format == Format.PE32_PLUS) ? ReadUInt64() : ReadUInt32();
            header.SectionAlignment      = ReadUInt32();
            header.FileAlignment         = ReadUInt32();
            header.MajorOsVersion        = ReadUInt16();
            header.MinorOsVersion        = ReadUInt16();
            header.MajorImageVersion     = ReadUInt16();
            header.MinorImageVersion     = ReadUInt16();
            header.MajorSubsystemVersion = ReadUInt16();
            header.MinorSubsystemVersion = ReadUInt16();
            header.Win32VersionValue     = ReadUInt32();
            header.SizeOfImage           = ReadUInt32();
            header.SizeOfHeaders         = ReadUInt32();
            header.Checksum            = ReadUInt32();
            header.Subsystem           = ReadUInt16();
            header.DllCharacteristics  = ReadUInt16();
            header.SizeOfStackReserve  = (format == Format.PE32_PLUS) ? ReadUInt64() : ReadUInt32();
            header.SizeOfStackCommit   = (format == Format.PE32_PLUS) ? ReadUInt64() : ReadUInt32();
            header.SizeOfHeapReserve   = (format == Format.PE32_PLUS) ? ReadUInt64() : ReadUInt32();
            header.SizeOfHeapCommit    = (format == Format.PE32_PLUS) ? ReadUInt64() : ReadUInt32();
            header.LoaderFlags         = ReadUInt32();
            header.NumberOfRvaAndSizes = ReadUInt32();

            return(header);
        }
예제 #14
0
        public CopiedProcessModule(Process process, IntPtr baseAddress, int size)
        {
            BaseAddress = baseAddress;
            using (var memoryReader = new MemoryReader(process))
            {
                var copiedBytes = memoryReader.ReadMemory(baseAddress, size, out var bytesRead);
                if (bytesRead != size)
                {
                    throw new AccessViolationException("Could not copy entire module into memory.");
                }
                var reader = new ByteArrayReader(copiedBytes);

                // DOS header.
                var dosHeader = DosHeader.FromReader(reader);
                reader.FileOffset = dosHeader.NextHeaderOffset;

                uint signature = reader.ReadUInt32();
                if (signature != 0x4550) //PE\0\0
                {
                    throw new BadImageFormatException();
                }

                // Read NT headers.
                var peFile = new PEFile(
                    dosHeader,
                    FileHeader.FromReader(reader),
                    OptionalHeader.FromReader(reader));
                ImageFile = peFile;

                // Section headers.
                reader.FileOffset = peFile.OptionalHeader.FileOffset + peFile.FileHeader.SizeOfOptionalHeader;
                for (int i = 0; i < peFile.FileHeader.NumberOfSections; i++)
                {
                    var header = SectionHeader.FromReader(reader);
                    header.PointerToRawData = header.VirtualAddress;
                    header.SizeOfRawData    = header.VirtualSize;

                    var contentsReader = reader.Fork(header.PointerToRawData, header.VirtualSize);
                    var contents       = DataSegment.FromReader(contentsReader);
                    contents.UpdateOffsets(header.PointerToRawData, header.VirtualAddress);

                    peFile.Sections.Add(new PESection(header, new VirtualSegment(contents, header.VirtualSize)));
                }

                Image = PEImage.FromFile(peFile);
            }
        }
예제 #15
0
        public OptionalHeaderModel(OptionalHeader optionalHeader, PEHeaderModel peHeader)
            : base("Optional header")
        {
            this.optionalHeader = optionalHeader;

            BindAddressToPEHeader(peHeader);

            this.Address = peHeader.Address + peHeader.Length;

            UpdateLength();

            UpdateDataFromPEMagic();

            this.m_DataDirectories = new ReadOnlyObservableCollection <DataDirectoryModel>(coreDataDirectories);

            UpdateDataDirectories();
        }
예제 #16
0
        public CLRHeader(AssemblyBuffer buffer, OptionalHeader header, SectionsHeaders sectionsHeaders)
        {
            this.cb = buffer.ReadDWord();
            this.MajorRuntimeVersion = buffer.ReadWord();
            this.MinorRuntimeVersion = buffer.ReadWord();
            this.MetaData            = new DataDirectory(buffer);
            this.Flags = buffer.ReadDWord();

            this.EntryPointTokenOrEntryPointRVA = buffer.ReadDWord();

            this.Resources               = new DataDirectory(buffer);
            this.StrongNameSignature     = new DataDirectory(buffer);
            this.CodeManagerTable        = new DataDirectory(buffer);
            this.VTableFixups            = new DataDirectory(buffer);
            this.ExportAddressTableJumps = new DataDirectory(buffer);
            this.ManagedNativeHeader     = new DataDirectory(buffer);
        }
예제 #17
0
            private void _read()
            {
                _peSignature = m_io.ReadBytes(4);
                if (!((KaitaiStream.ByteArrayCompare(PeSignature, new byte[] { 80, 69, 0, 0 }) == 0)))
                {
                    throw new ValidationNotEqualError(new byte[] { 80, 69, 0, 0 }, PeSignature, M_Io, "/types/pe_header/seq/0");
                }
                _coffHdr          = new CoffHeader(m_io, this, m_root);
                __raw_optionalHdr = m_io.ReadBytes(CoffHdr.SizeOfOptionalHeader);
                var io___raw_optionalHdr = new KaitaiStream(__raw_optionalHdr);

                _optionalHdr = new OptionalHeader(io___raw_optionalHdr, this, m_root);
                _sections    = new List <Section>();
                for (var i = 0; i < CoffHdr.NumberOfSections; i++)
                {
                    _sections.Add(new Section(m_io, this, m_root));
                }
            }
예제 #18
0
        /// <summary>
        /// Reads a PE file from the provided input stream.
        /// </summary>
        /// <param name="reader">The input stream to read from.</param>
        /// <returns>The PE file that was read.</returns>
        /// <exception cref="BadImageFormatException">Occurs when the file does not follow the PE file format.</exception>
        public static PEFile FromReader(IBinaryStreamReader reader)
        {
            // DOS header.
            var dosHeader = DosHeader.FromReader(reader);

            reader.FileOffset = dosHeader.NextHeaderOffset;

            uint signature = reader.ReadUInt32();

            if (signature != ValidPESignature)
            {
                throw new BadImageFormatException();
            }

            // Read NT headers.
            var peFile = new PEFile(
                dosHeader,
                FileHeader.FromReader(reader),
                OptionalHeader.FromReader(reader));

            // Section headers.
            reader.FileOffset = peFile.OptionalHeader.FileOffset + peFile.FileHeader.SizeOfOptionalHeader;
            for (int i = 0; i < peFile.FileHeader.NumberOfSections; i++)
            {
                var header = SectionHeader.FromReader(reader);

                var contentsReader = reader.Fork(header.PointerToRawData, header.SizeOfRawData);
                var contents       = DataSegment.FromReader(contentsReader);
                contents.UpdateOffsets(header.PointerToRawData, header.VirtualAddress);

                peFile.Sections.Add(new PESection(header, new VirtualSegment(contents, header.VirtualSize)));
            }

            // Data between section headers and sections.
            int extraSectionDataLength = (int)(peFile.OptionalHeader.SizeOfHeaders - reader.FileOffset);

            if (extraSectionDataLength != 0)
            {
                peFile.ExtraSectionData = DataSegment.FromReader(reader, extraSectionDataLength);
            }

            return(peFile);
        }
예제 #19
0
        public XPeParser(String path)
        {
            f = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            BinaryReader br = new BinaryReader(f);

            /* Check the main signature */
            ushort dosSig = br.ReadUInt16();
            if (dosSig != IMAGE_DOS_SIGNATURE)
                throw new Exception("Invalid DOS Signature for the executable!");

            /* Seek to the PE header */
            br.BaseStream.Seek(0x3C, SeekOrigin.Begin);
            uint peOffset = br.ReadUInt32();

            /* Check the PE signature */
            br.BaseStream.Seek(peOffset, SeekOrigin.Begin);

            uint peSign = br.ReadUInt32();
            if (peSign != IMAGE_NT_SIGNATURE)
                throw new Exception("Invalid PE Signature for the executable!");

            /* Read the rest of PE header, then check some fields */
            imHdr = new ImageFileHeader(br);

            /* Specific machine value to indicate Xbox 360 */
            if (imHdr.Machine != 0x1F2)
                throw new Exception("The PE is valid but it's not an Xbox 360 executable.");

            /*
             * The strange thing is that imHdr.Characteristics is set to 0x102
             * (usually), indicating a 32bit architecture, while the Xenon is 64-bit.
             * Microsoft likes to mess with their own specifications...
             */
            optHdr = new OptionalHeader(br);

            sectHdrs = new SectionHeader[imHdr.NumberOfSections];
            for (int i = 0; i < imHdr.NumberOfSections; i++)
                sectHdrs[i] = new SectionHeader(br);

            FileName = path;
        }
예제 #20
0
        /// <summary>
        /// Reads a PE file from an input stream.
        /// </summary>
        /// <param name="reader">The input stream.</param>
        /// <param name="mode">Indicates how the input PE file is mapped.</param>
        /// <exception cref="BadImageFormatException">Occurs when the input stream is malformed.</exception>
        public SerializedPEFile(IBinaryStreamReader reader, PEMappingMode mode)
        {
            _reader     = reader ?? throw new ArgumentNullException(nameof(reader));
            MappingMode = mode;

            // DOS header.
            DosHeader     = DosHeader.FromReader(reader);
            reader.Offset = DosHeader.Offset + DosHeader.NextHeaderOffset;

            uint signature = reader.ReadUInt32();

            if (signature != ValidPESignature)
            {
                throw new BadImageFormatException();
            }

            // Read NT headers.
            FileHeader     = FileHeader.FromReader(reader);
            OptionalHeader = OptionalHeader.FromReader(reader);

            // Read section headers.
            reader.Offset   = OptionalHeader.Offset + FileHeader.SizeOfOptionalHeader;
            _sectionHeaders = new List <SectionHeader>(FileHeader.NumberOfSections);
            for (int i = 0; i < FileHeader.NumberOfSections; i++)
            {
                _sectionHeaders.Add(SectionHeader.FromReader(reader));
            }

            // Data between section headers and sections.
            int extraSectionDataLength = (int)(DosHeader.Offset + OptionalHeader.SizeOfHeaders - reader.Offset);

            if (extraSectionDataLength != 0)
            {
                ExtraSectionData = DataSegment.FromReader(reader, extraSectionDataLength);
            }
        }
예제 #21
0
 static void AssertOptionalHeader(OptionalHeader optionalHeader)
 {
     Assert.AreEqual((byte)8, optionalHeader.MajorLinkerVersion);
     Assert.AreEqual((byte)0, optionalHeader.MinorLinkerVersion);
     Assert.AreEqual((uint)0, optionalHeader.SizeOfUninitializedData);
     Assert.AreEqual((uint)8192, optionalHeader.BaseOfCode);
     Assert.AreEqual((uint)0x400000, optionalHeader.ImageBase);
     Assert.AreEqual((uint)8192, optionalHeader.SectionAlignment);
     Assert.AreEqual((uint)512, optionalHeader.FileAlignment);
     Assert.AreEqual((ushort)4, optionalHeader.MajorOperatingSystemVersion);
     Assert.AreEqual((ushort)0, optionalHeader.MinorOperatingSystemVersion);
     Assert.AreEqual((ushort)0, optionalHeader.MajorImageVersion);
     Assert.AreEqual((ushort)0, optionalHeader.MinorImageVersion);
     Assert.AreEqual((ushort)4, optionalHeader.MajorSubsystemVersion);
     Assert.AreEqual((ushort)0, optionalHeader.MinorSubsystemVersion);
     Assert.AreEqual((uint)0, optionalHeader.Win32VersionValue);
     Assert.AreEqual((uint)512, optionalHeader.SizeOfHeaders);
     Assert.AreEqual((uint)0, optionalHeader.CheckSum);
     Assert.AreEqual(Subsystem.WindowsCUI, optionalHeader.Subsystem);
     Assert.AreEqual(DllCharacteristics.DynamicBase | DllCharacteristics.NxCompatible | DllCharacteristics.NoSEH | DllCharacteristics.TerminalServerAware, optionalHeader.DllCharacteristics);
     Assert.AreEqual((uint)0x100000, optionalHeader.SizeOfHeapReserve);
     Assert.AreEqual((uint)0, optionalHeader.LoaderFlags);
     Assert.AreEqual((uint)16, optionalHeader.NumberOfRvaAndSizes);
 }
예제 #22
0
        static void WriteOptionalHeader(OptionalHeader optionalHeader, BinaryStreamWriter writer)
        {
            writer.WriteUInt16((ushort)optionalHeader.PEMagic);

            writer.WriteByte(optionalHeader.MajorLinkerVersion);
            writer.WriteByte(optionalHeader.MinorLinkerVersion);
            writer.WriteUInt32(optionalHeader.SizeOfCode);
            writer.WriteUInt32(optionalHeader.SizeOfInitializedData);
            writer.WriteUInt32(optionalHeader.SizeOfUninitializedData);
            writer.WriteUInt32(optionalHeader.AddressOfEntryPoint);
            writer.WriteUInt32(optionalHeader.BaseOfCode);

            if (optionalHeader.PEMagic == PEMagic.NT32)
            {
                writer.WriteUInt32(optionalHeader.BaseOfData);
                writer.WriteUInt32(checked ((uint)optionalHeader.ImageBase));
            }
            else
            {
                writer.WriteUInt64(optionalHeader.ImageBase);
            }

            writer.WriteUInt32(optionalHeader.SectionAlignment);
            writer.WriteUInt32(optionalHeader.FileAlignment);
            writer.WriteUInt16(optionalHeader.MajorOperatingSystemVersion);
            writer.WriteUInt16(optionalHeader.MinorOperatingSystemVersion);
            writer.WriteUInt16(optionalHeader.MajorImageVersion);
            writer.WriteUInt16(optionalHeader.MinorImageVersion);
            writer.WriteUInt16(optionalHeader.MajorSubsystemVersion);
            writer.WriteUInt16(optionalHeader.MinorSubsystemVersion);
            writer.WriteUInt32(optionalHeader.Win32VersionValue);
            writer.WriteUInt32(optionalHeader.SizeOfImage);
            writer.WriteUInt32(optionalHeader.SizeOfHeaders);
            writer.WriteUInt32(optionalHeader.CheckSum);
            writer.WriteUInt16((ushort)optionalHeader.Subsystem);
            writer.WriteUInt16((ushort)optionalHeader.DllCharacteristics);

            if (optionalHeader.PEMagic == PEMagic.NT32)
            {
                writer.WriteUInt32(checked ((uint)optionalHeader.SizeOfStackReserve));
                writer.WriteUInt32(checked ((uint)optionalHeader.SizeOfStackCommit));
                writer.WriteUInt32(checked ((uint)optionalHeader.SizeOfHeapReserve));
                writer.WriteUInt32(checked ((uint)optionalHeader.SizeOfHeapCommit));
            }
            else
            {
                writer.WriteUInt64(optionalHeader.SizeOfStackReserve);
                writer.WriteUInt64(optionalHeader.SizeOfStackCommit);
                writer.WriteUInt64(optionalHeader.SizeOfHeapReserve);
                writer.WriteUInt64(optionalHeader.SizeOfHeapCommit);
            }

            writer.WriteUInt32(optionalHeader.LoaderFlags);
            writer.WriteUInt32(optionalHeader.NumberOfRvaAndSizes);

            for (int i = 0; i < optionalHeader.DataDirectories.Length; i++)
            {
                writer.WriteUInt32(optionalHeader.DataDirectories[i].VirtualAddress);
                writer.WriteUInt32(optionalHeader.DataDirectories[i].Size);
            }
        }
예제 #23
0
        private void FileOpen(string file)
        {
            // Set status bar location for the file.
            tbStatusBarLocation.Text = file;

            // Parse the PE file
            if (!PeFile.IsPEFile(file))
            {
                ShowInvalidPeFileMsgBox();
                return;
            }

            _peFile = new PeFile(file);

            // Set all FileInfo fields.
            FileInfo.SetFileInfo(_peFile);

            // Set the DOS header fields
            DosNtHeader.SetDosHeader(_peFile);

            // Set the PE File fields
            DosNtHeader.SetNtHeader(_peFile);

            // Set the File header
            FileHeaderDebug.SetFileHeader(_peFile);

            // Set the Debug directory.
            FileHeaderDebug.SetDebug(_peFile);

            // Set the Optional header
            OptionalHeader.SetOptionalHeader(_peFile);

            // Set the imports.
            Imports.SetImports(_peFile);

            // Set the exports.
            Exports.SetExports(_peFile);

            // Set the resources.
            Resource.SetResources(_peFile);

            // Set the sections.
            SectionHeaders.SetSections(_peFile);

            // Set the Exception (only for x64)
            Exceptions.SetException(_peFile);

            // Set the Relocations.
            Relocation.SetRelocations(_peFile);

            // Set the Digital Signature information.
            Signature.SetDigSignature(_peFile);

            // Set the Bound Import directory.
            DebugBoundImport.SetBoundImport(_peFile);

            // Set the Delay Import descriptor.
            DebugBoundImport.SetDelayImport(_peFile);

            // Set the TLS directory.
            TlsDirectory.SetTlsDirectory(_peFile);

            // Set the Load Config Directory
            LoadConfig.SetLoadConfig(_peFile);

            // Set the Data Directory View
            DirectoryView.SetDirectoryView(_peFile);
        }
예제 #24
0
        /// <summary>
        /// 获得OPTIONAL PE扩展属性
        /// </summary>
        /// <param name="Fileindex"></param>
        /// <returns></returns>
        private void LoadOptionalHeader()
        {
            _OptionalHeader = new OptionalHeader();

            _OptionalHeader.FileStarIndex = PEFileIndex;

            Loadbyte(ref _OptionalHeader.Magic);
            Loadbyte(ref _OptionalHeader.MajorLinkerVersion);
            Loadbyte(ref _OptionalHeader.MinorLinkerVersion);
            Loadbyte(ref _OptionalHeader.SizeOfCode);
            Loadbyte(ref _OptionalHeader.SizeOfInitializedData);
            Loadbyte(ref _OptionalHeader.SizeOfUninitializedData);
            Loadbyte(ref _OptionalHeader.AddressOfEntryPoint);
            Loadbyte(ref _OptionalHeader.BaseOfCode);
            Loadbyte(ref _OptionalHeader.ImageBase);
            Loadbyte(ref _OptionalHeader.ImageFileCode);
            Loadbyte(ref _OptionalHeader.SectionAlign);
            Loadbyte(ref _OptionalHeader.FileAlign);

            Loadbyte(ref _OptionalHeader.MajorOSV);
            Loadbyte(ref _OptionalHeader.MinorOSV);
            Loadbyte(ref _OptionalHeader.MajorImageVer);
            Loadbyte(ref _OptionalHeader.MinorImageVer);
            Loadbyte(ref _OptionalHeader.MajorSV);
            Loadbyte(ref _OptionalHeader.MinorSV);
            Loadbyte(ref _OptionalHeader.UNKNOW);
            Loadbyte(ref _OptionalHeader.SizeOfImage);
            Loadbyte(ref _OptionalHeader.SizeOfHeards);
            Loadbyte(ref _OptionalHeader.CheckSum);
            Loadbyte(ref _OptionalHeader.Subsystem);
            Loadbyte(ref _OptionalHeader.DLL_Characteristics);
            Loadbyte(ref _OptionalHeader.Bsize);
            Loadbyte(ref _OptionalHeader.TimeBsize);
            Loadbyte(ref _OptionalHeader.AucBsize);
            Loadbyte(ref _OptionalHeader.SizeOfBsize);
            Loadbyte(ref _OptionalHeader.FuckBsize);
            Loadbyte(ref _OptionalHeader.DirectCount);

            _OptionalHeader.FileEndIndex = PEFileIndex;
        }
예제 #25
0
 public OptionalHeaderData64(OptionalHeader optionalHeader)
     : base(optionalHeader)
 {
 }
예제 #26
0
 public DataDirectoryModel(OptionalHeader optionalHeader, DataDirectoryKind dataDirectoryKind)
 {
     this.optionalHeader = optionalHeader;
     this.m_Kind         = dataDirectoryKind;
 }
예제 #27
0
 public OptionalHeaderData(OptionalHeader optionalHeader)
 {
     this.optionalHeader = optionalHeader;
 }
        protected void ConstructPEImage(FileStream file, bool partialConstruct)
        {
            this._partialConstruct = partialConstruct;
            this._dosHeader        = new DosHeader(file);
            long size = this._dosHeader.NtHeaderPosition - (this._dosHeader.Address + this._dosHeader.Size);

            if (size < 0L)
            {
                throw new Win32Exception(11, Resources.GetString("Ex_InvalidPEFormat"));
            }
            this._dosStub        = new DosStub(file, this._dosHeader.Address + this._dosHeader.Size, size);
            this._ntSignature    = new NtSignature(file, (long)this._dosHeader.NtHeaderPosition);
            this._fileHeader     = new FileHeader(file, this._ntSignature.Address + this._ntSignature.Size);
            this._optionalHeader = new OptionalHeader(file, this._fileHeader.Address + this._fileHeader.Size);
            long address = this._optionalHeader.Address + this._optionalHeader.Size;
            int  num3    = 0;

            for (num3 = 0; num3 < this._optionalHeader.NumberOfRvaAndSizes; num3++)
            {
                DataDirectory directory = new DataDirectory(file, address);
                address += directory.Size;
                this._dataDirectories.Add(directory);
            }
            if (this._fileHeader.SizeOfOptionalHeader < (((ulong)this._optionalHeader.Size) + (this._optionalHeader.NumberOfRvaAndSizes * Marshal.SizeOf(typeof(IMAGE_DATA_DIRECTORY)))))
            {
                throw new Win32Exception(11, Resources.GetString("Ex_InvalidPEFormat"));
            }
            bool flag           = false;
            uint virtualAddress = 0;

            if (this._optionalHeader.NumberOfRvaAndSizes > 2)
            {
                virtualAddress = ((DataDirectory)this._dataDirectories[2]).VirtualAddress;
                flag           = true;
            }
            long num5 = this._optionalHeader.Address + this._fileHeader.SizeOfOptionalHeader;

            for (num3 = 0; num3 < this._fileHeader.NumberOfSections; num3++)
            {
                SectionHeader sectionHeader = new SectionHeader(file, num5);
                Section       section       = null;
                if (flag && (sectionHeader.VirtualAddress == virtualAddress))
                {
                    section = this._resourceSection = new ResourceSection(file, sectionHeader, partialConstruct);
                }
                else
                {
                    section = new Section(file, sectionHeader);
                }
                sectionHeader.Section = section;
                this._sectionHeaders.Add(sectionHeader);
                this._sections.Add(section);
                num5 += sectionHeader.Size;
            }
            this.ConstructStream();
            ArrayList c    = new ArrayList();
            long      num6 = 0L;

            foreach (PEComponent component in this._streamComponents)
            {
                if (component.Address < num6)
                {
                    throw new Win32Exception(11, Resources.GetString("Ex_InvalidPEFormat"));
                }
                if (component.Address > num6)
                {
                    PEComponent component2 = new PEComponent(file, num6, component.Address - num6);
                    c.Add(component2);
                }
                num6 = component.Address + component.Size;
            }
            if (num6 < file.Length)
            {
                PEComponent component3 = new PEComponent(file, num6, file.Length - num6);
                c.Add(component3);
            }
            this._streamComponents.AddRange(c);
            this._streamComponents.Sort(new PEComponentComparer());
            this._canRead  = true;
            this._canSeek  = true;
            this._length   = file.Length;
            this._position = 0L;
        }
 protected void ConstructPEImage(FileStream file, bool partialConstruct)
 {
     this._partialConstruct = partialConstruct;
     this._dosHeader = new DosHeader(file);
     long size = this._dosHeader.NtHeaderPosition - (this._dosHeader.Address + this._dosHeader.Size);
     if (size < 0L)
     {
         throw new Win32Exception(11, Resources.GetString("Ex_InvalidPEFormat"));
     }
     this._dosStub = new DosStub(file, this._dosHeader.Address + this._dosHeader.Size, size);
     this._ntSignature = new NtSignature(file, (long) this._dosHeader.NtHeaderPosition);
     this._fileHeader = new FileHeader(file, this._ntSignature.Address + this._ntSignature.Size);
     this._optionalHeader = new OptionalHeader(file, this._fileHeader.Address + this._fileHeader.Size);
     long address = this._optionalHeader.Address + this._optionalHeader.Size;
     int num3 = 0;
     for (num3 = 0; num3 < this._optionalHeader.NumberOfRvaAndSizes; num3++)
     {
         DataDirectory directory = new DataDirectory(file, address);
         address += directory.Size;
         this._dataDirectories.Add(directory);
     }
     if (this._fileHeader.SizeOfOptionalHeader < (((ulong) this._optionalHeader.Size) + (this._optionalHeader.NumberOfRvaAndSizes * Marshal.SizeOf(typeof(IMAGE_DATA_DIRECTORY)))))
     {
         throw new Win32Exception(11, Resources.GetString("Ex_InvalidPEFormat"));
     }
     bool flag = false;
     uint virtualAddress = 0;
     if (this._optionalHeader.NumberOfRvaAndSizes > 2)
     {
         virtualAddress = ((DataDirectory) this._dataDirectories[2]).VirtualAddress;
         flag = true;
     }
     long num5 = this._optionalHeader.Address + this._fileHeader.SizeOfOptionalHeader;
     for (num3 = 0; num3 < this._fileHeader.NumberOfSections; num3++)
     {
         SectionHeader sectionHeader = new SectionHeader(file, num5);
         Section section = null;
         if (flag && (sectionHeader.VirtualAddress == virtualAddress))
         {
             section = this._resourceSection = new ResourceSection(file, sectionHeader, partialConstruct);
         }
         else
         {
             section = new Section(file, sectionHeader);
         }
         sectionHeader.Section = section;
         this._sectionHeaders.Add(sectionHeader);
         this._sections.Add(section);
         num5 += sectionHeader.Size;
     }
     this.ConstructStream();
     ArrayList c = new ArrayList();
     long num6 = 0L;
     foreach (PEComponent component in this._streamComponents)
     {
         if (component.Address < num6)
         {
             throw new Win32Exception(11, Resources.GetString("Ex_InvalidPEFormat"));
         }
         if (component.Address > num6)
         {
             PEComponent component2 = new PEComponent(file, num6, component.Address - num6);
             c.Add(component2);
         }
         num6 = component.Address + component.Size;
     }
     if (num6 < file.Length)
     {
         PEComponent component3 = new PEComponent(file, num6, file.Length - num6);
         c.Add(component3);
     }
     this._streamComponents.AddRange(c);
     this._streamComponents.Sort(new PEComponentComparer());
     this._canRead = true;
     this._canSeek = true;
     this._length = file.Length;
     this._position = 0L;
 }