示例#1
0
 private static extern bool ReadProcessMemory(
     IntPtr hProcess,
     IntPtr lpBaseAddress,
     out IMAGE_NT_HEADERS64 lpBuffer,
     int nSize,
     IntPtr lpNumberOfBytesRead
     );
示例#2
0
        /// <summary>
        /// Initializes a new instance of <see cref="Pe64Headers"/>.
        /// </summary>
        /// <param name="peStream">
        /// The stream to the PE file, positioned at the <see cref="IMAGE_NT_HEADERS64"/> structure.
        /// </param>
        public Pe64Headers(Stream peStream)
        {
            _ntHeader = peStream.Read <IMAGE_NT_HEADERS64>();

            // read the data directories
            int nDirectories = checked ((int)_ntHeader.OptionalHeader.NumberOfRvaAndSizes);

            _dataDirectories = new IMAGE_DATA_DIRECTORY[nDirectories];

            for (int i = 0; i < nDirectories; i++)
            {
                _dataDirectories[i] = peStream.Read <IMAGE_DATA_DIRECTORY>();
            }


            // read the section headers
            int nSections = NumberOfSections;

            _sectionHeaders     = new IMAGE_SECTION_HEADER[nSections];
            _sectionNameToIndex = new Dictionary <string, int>(capacity: nSections);

            for (int i = 0; i < nSections; i++)
            {
                _sectionHeaders[i] = peStream.Read <IMAGE_SECTION_HEADER>();

                string name = _sectionHeaders[i].NameStr;
                _sectionNameToIndex[name] = i;
            }
        }
示例#3
0
 public void insert_NT64(IMAGE_NT_HEADERS64 INH)
 {
     foreach (var field in typeof(IMAGE_DOS_HEADER).GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
     {
         //global.Dos_Header.Add(new Binder())
     }
 }
示例#4
0
 public PE64File(IMAGE_DOS_HEADER dosHeader, IMAGE_NT_HEADERS64 peHeader, byte[] dosStub)
 {
     Type      = PEType.PE64;
     DOSHeader = DOSHeader.FromNativeStruct(dosHeader);
     PEHeader  = PE64Header.FromNativeStruct(peHeader);
     Sections  = new PESection[peHeader.FileHeader.NumberOfSections];
     DOS_Stub  = dosStub;
 }
示例#5
0
 public static PE64Header FromNativeStruct(IMAGE_NT_HEADERS64 nativeStruct)
 {
     return(new PE64Header
     {
         Signature = new string(nativeStruct.Signature),
         FileHeader = PE64FileHeader.FromNativeStruct(nativeStruct.FileHeader),
         OptionalHeader = PE64OptionalHeader.FromNativeStruct(nativeStruct.OptionalHeader)
     });
 }
示例#6
0
        private PEFile Dump64BitPE(IntPtr processId, IMAGE_DOS_HEADER dosHeader, byte[] dosStub, IntPtr peHeaderPointer)
        {
            IMAGE_NT_HEADERS64 peHeader = ReadProcessStruct <IMAGE_NT_HEADERS64>(processId, peHeaderPointer);

            if (peHeader.IsValid)
            {
                return(new PE64File(dosHeader, peHeader, dosStub));
            }
            return(default);
示例#7
0
        public Pe64Accessor(Stream peStream)
        {
            _ntHeader = peStream.Read <IMAGE_NT_HEADERS64>();

            uint nSections = _ntHeader.OptionalHeader.NumberOfRvaAndSizes;

            _sectionHeaders = new IMAGE_SECTION_HEADER[nSections];

            for (uint i = 0; i < nSections; i++)
            {
                _sectionHeaders[i] = peStream.Read <IMAGE_SECTION_HEADER>();
            }
        }
示例#8
0
        static void Main()
        {
            IntPtr curProc = GetCurrentProcess();

            MODULEINFO modInfo;
            IntPtr     handle = GetModuleHandle("ntdll.dll");

            GetModuleInformation(curProc, handle, out modInfo, 0x18);
            IntPtr dllBase    = modInfo.lpBaseOfDll;
            string fileName   = "C:\\Windows\\System32\\ntdll.dll";
            IntPtr file       = CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
            IntPtr mapping    = CreateFileMapping(file, IntPtr.Zero, FileMapProtection.PageReadonly | FileMapProtection.SectionImage, 0, 0, null);
            IntPtr mappedFile = MapViewOfFile(mapping, FileMapAccess.FileMapRead, 0, 0, IntPtr.Zero);

            IMAGE_DOS_HEADER   dosHeader = (IMAGE_DOS_HEADER)Marshal.PtrToStructure(dllBase, typeof(IMAGE_DOS_HEADER));
            IntPtr             ptrToNt   = (dllBase + dosHeader.e_lfanew);
            IMAGE_NT_HEADERS64 ntHeaders = (IMAGE_NT_HEADERS64)Marshal.PtrToStructure(ptrToNt, typeof(IMAGE_NT_HEADERS64));

            for (int i = 0; i < ntHeaders.FileHeader.NumberOfSections; i++)
            {
                IntPtr ptrSectionHeader            = (ptrToNt + Marshal.SizeOf(typeof(IMAGE_NT_HEADERS64)));
                IMAGE_SECTION_HEADER sectionHeader = (IMAGE_SECTION_HEADER)Marshal.PtrToStructure((ptrSectionHeader + (i * Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)))), typeof(IMAGE_SECTION_HEADER));
                string sectionName = new string(sectionHeader.Name);

                if (sectionName.Contains("text"))
                {
                    uint   oldProtect = 0;
                    IntPtr lpAddress  = IntPtr.Add(dllBase, (int)sectionHeader.VirtualAddress);
                    IntPtr srcAddress = IntPtr.Add(mappedFile, (int)sectionHeader.VirtualAddress);
                    int    vProtect   = VirtualProtect(lpAddress, sectionHeader.VirtualSize, 0x40, out oldProtect);
                    memcpy(lpAddress, srcAddress, sectionHeader.VirtualSize);
                    vProtect = VirtualProtect(lpAddress, sectionHeader.VirtualSize, oldProtect, out oldProtect);
                }
            }

            Console.Read();

            CloseHandle(curProc);
            CloseHandle(file);
            CloseHandle(mapping);
            FreeLibrary(handle);
        }
示例#9
0
        /// <summary>
        /// Parses the specified data.
        /// </summary>
        /// <param name="data">The PE image data.</param>
        private void ParseData(byte[] data)
        {
            using (DwarfMemoryReader reader = new DwarfMemoryReader(data))
            {
                dosHeader = reader.ReadStructure <IMAGE_DOS_HEADER>();
                if (dosHeader.e_magic != IMAGE_DOS_SIGNATURE)
                {
                    throw new ArgumentException($"Invalid IMAGE_DOS_HEADER magic constant. Expected: 0x{IMAGE_DOS_SIGNATURE:X}, Got: 0x{dosHeader.e_magic:X}");
                }

                reader.Position = (int)dosHeader.e_lfanew;
                ntHeaders32     = reader.ReadStructure <IMAGE_NT_HEADERS32>();
                if (ntHeaders32.Signature != IMAGE_NT_SIGNATURE)
                {
                    throw new ArgumentException($"Invalid optional header signature. Expected: 0x{IMAGE_NT_SIGNATURE:X}, Got: 0x{ntHeaders32.Signature:X}");
                }
                if (ntHeaders32.FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64 ||
                    ntHeaders32.FileHeader.Machine == IMAGE_FILE_MACHINE_IA64)
                {
                    reader.Position   = (int)dosHeader.e_lfanew;
                    ntHeaders64       = reader.ReadStructure <IMAGE_NT_HEADERS64>();
                    Is64bit           = true;
                    fileHeader        = ntHeaders64.FileHeader;
                    reader.Position  += ntHeaders64.FileHeader.SizeOfOptionalHeader - Marshal.SizeOf <IMAGE_OPTIONAL_HEADER64>();
                    CodeSegmentOffset = ntHeaders64.OptionalHeader.ImageBase;
                }
                else
                {
                    Is64bit           = false;
                    fileHeader        = ntHeaders32.FileHeader;
                    reader.Position  += ntHeaders32.FileHeader.SizeOfOptionalHeader - Marshal.SizeOf <IMAGE_OPTIONAL_HEADER32>();
                    CodeSegmentOffset = ntHeaders32.OptionalHeader.ImageBase;
                }

                // Load image section headers
                uint stringTablePosition = fileHeader.PointerToSymbolTable + fileHeader.NumberOfSymbols * IMAGE_SIZEOF_SYMBOL;

                imageSectionHeaders = new IMAGE_SECTION_HEADER[fileHeader.NumberOfSections];
                for (int section = 0; section < imageSectionHeaders.Length; section++)
                {
                    IMAGE_SECTION_HEADER imageSectionHeader = reader.ReadStructure <IMAGE_SECTION_HEADER>();
                    imageSectionHeaders[section] = imageSectionHeader;
                    string name = imageSectionHeader.Section;
                    if (imageSectionHeader.Name[0] == '/')
                    {
                        uint position = stringTablePosition + uint.Parse(imageSectionHeader.Section.Substring(1));

                        name = reader.ReadString((int)position);
                    }

                    switch (name)
                    {
                    case ".debug_info":
                        DebugData = reader.ReadBlock(imageSectionHeader.SizeInImage, (int)imageSectionHeader.PointerToRawData);
                        break;

                    case ".debug_abbrev":
                        DebugDataDescription = reader.ReadBlock(imageSectionHeader.SizeInImage, (int)imageSectionHeader.PointerToRawData);
                        break;

                    case ".debug_line":
                        DebugLine = reader.ReadBlock(imageSectionHeader.SizeInImage, (int)imageSectionHeader.PointerToRawData);
                        break;

                    case ".debug_frame":
                        DebugFrame = reader.ReadBlock(imageSectionHeader.SizeInImage, (int)imageSectionHeader.PointerToRawData);
                        break;

                    case ".debug_str":
                        DebugDataStrings = reader.ReadBlock(imageSectionHeader.SizeInImage, (int)imageSectionHeader.PointerToRawData);
                        break;

                    case ".eh_frame":
                        EhFrame        = reader.ReadBlock(imageSectionHeader.SizeInImage, (int)imageSectionHeader.PointerToRawData);
                        EhFrameAddress = imageSectionHeader.PointerToRawData + CodeSegmentOffset;
                        break;

                    case ".data":
                        DataSectionAddress = imageSectionHeader.PointerToRawData + CodeSegmentOffset;
                        break;

                    case ".text":
                        TextSectionAddress = imageSectionHeader.PointerToRawData + CodeSegmentOffset;
                        break;
                    }
                }

                // Load image symbols
                List <PublicSymbol> publicSymbols = new List <PublicSymbol>();
                byte toSkip = 0;

                reader.Position = (int)fileHeader.PointerToSymbolTable;
                for (uint i = 0; i < fileHeader.NumberOfSymbols; i++)
                {
                    int          position = reader.Position;
                    IMAGE_SYMBOL symbol   = reader.ReadStructure <IMAGE_SYMBOL>();

                    if (toSkip == 0)
                    {
                        string name = symbol.SymbolName;

                        if (string.IsNullOrEmpty(name))
                        {
                            int stringPosition = (int)reader.ReadUint(position);
                            stringPosition = (int)reader.ReadUint(position + 4);

                            name = reader.ReadString((int)stringTablePosition + stringPosition);
                        }


                        if (symbol.SectionNumber > 0 && symbol.SectionNumber <= imageSectionHeaders.Length)
                        {
                            uint sectionAddress = imageSectionHeaders[symbol.SectionNumber - 1].VirtualAddress;
                            sectionAddress += symbol.Value;

                            publicSymbols.Add(new PublicSymbol(name, sectionAddress));
                        }

                        toSkip = symbol.NumberOfAuxSymbols;
                    }
                    else
                    {
                        toSkip--;
                    }
                }
                PublicSymbols = publicSymbols;
            }
        }
示例#10
0
        private unsafe void PopulateHeaderStructs(FileStream fin)
        {
            byte[] Data  = new byte[4096];
            int    iRead = fin.Read(Data, 0, 4096);

            fin.Flush();
            fin.Close();

            fixed(byte *p_Data = Data)
            {
                IMAGE_DOS_HEADER *  idh  = (IMAGE_DOS_HEADER *)p_Data;
                IMAGE_NT_HEADERS32 *inhs = (IMAGE_NT_HEADERS32 *)(idh->nt_head_ptr + p_Data);

                ModuleMachineType = (MachineType)inhs->FileHeader.Machine;

                if (ModuleMachineType == MachineType.I386)
                {
                    IMAGE_NT_HEADERS32 *inhs32 = (IMAGE_NT_HEADERS32 *)(idh->nt_head_ptr + p_Data);
                    ImageFileHeader       = inhs32->FileHeader;
                    ModuleMachineType     = (MachineType)inhs32->FileHeader.Machine;
                    ImageOptionalHeader32 = inhs32->OptionalHeader;
                    ModuleImageBase       = (IntPtr)inhs32->OptionalHeader.ImageBase;

                    ImageNTHeaders32 = new IMAGE_NT_HEADERS32
                    {
                        Signature      = inhs32->Signature,
                        FileHeader     = inhs32->FileHeader,
                        OptionalHeader = inhs32->OptionalHeader
                    };

                    byte[] bytes = new byte[256];
                    var    ret   = ErcCore.ReadProcessMemory(ModuleProcess.Handle,
                                                             (IntPtr)((uint)ModuleBase + ImageOptionalHeader32.LoadConfigTable.VirtualAddress), bytes, 256, out int BytesRead);
                    if (BitConverter.ToUInt32(bytes, 58) > 0 || BitConverter.ToUInt32(bytes, 62) > 0)
                    {
                        ModuleSafeSEH = true;
                    }
                }
                else if (ModuleMachineType == MachineType.x64)
                {
                    IMAGE_NT_HEADERS64 *inhs64 = (IMAGE_NT_HEADERS64 *)(idh->nt_head_ptr + p_Data);
                    ImageFileHeader       = inhs64->FileHeader;
                    ImageOptionalHeader64 = inhs64->OptionalHeader;
                    ModuleImageBase       = (IntPtr)inhs64->OptionalHeader.ImageBase;

                    ImageNTHeaders64 = new IMAGE_NT_HEADERS64
                    {
                        Signature      = inhs64->Signature,
                        FileHeader     = inhs64->FileHeader,
                        OptionalHeader = inhs64->OptionalHeader
                    };

                    byte[] bytes = new byte[256];
                    var    ret   = ErcCore.ReadProcessMemory(ModuleProcess.Handle,
                                                             (IntPtr)((long)ModuleBase + (long)ImageOptionalHeader64.LoadConfigTable.VirtualAddress), bytes, 256, out int BytesRead);
                    if (BitConverter.ToUInt64(bytes, 88) > 0 || BitConverter.ToUInt64(bytes, 96) > 0)
                    {
                        ModuleSafeSEH = true;
                    }
                }
                else
                {
                    ModuleFailed = true;
                }
            }
        }
示例#11
0
        private static IntPtr Hollow(byte[] payload)
        {
            uint SECTION_MAP_WRITE   = 0x0002;
            uint SECTION_MAP_READ    = 0x0004;
            uint SECTION_MAP_EXECUTE = 0x0008;
            uint SECTION_ALL_ACCESS  = SECTION_MAP_WRITE | SECTION_MAP_READ | SECTION_MAP_EXECUTE;
            uint PAGE_READ_ONLY      = 0x02;
            uint SEC_IMAGE           = 0x1000000;
            uint PAGE_READWRITE      = 0x04;

            String SystemDirectory = System.Environment.SystemDirectory;

            String[] files        = Directory.GetFiles(SystemDirectory, "*.dll");
            IntPtr   file         = IntPtr.Zero;
            uint     numBytesRead = 0;
            int      payload_size = payload.Length;
            uint     viewSize     = 0;

            for (int i = 0; i < files.Length; i++)
            {
                string module = files[i];
                if (GetModuleHandle(module) == IntPtr.Zero)
                {
                    file = CreateFile(module, FileAccess.GenericRead, FileShare.Read, IntPtr.Zero, FileMode.OpenExisting, 0, IntPtr.Zero);
                    uint   lpFileSize = GetFileSize(file, IntPtr.Zero);
                    byte[] fileBuffer = new byte[lpFileSize];
                    bool   fileRead   = ReadFile(file, fileBuffer, lpFileSize, out numBytesRead, IntPtr.Zero);
                    IntPtr fileBufPtr = Marshal.AllocHGlobal(fileBuffer.Length);
                    Marshal.Copy(fileBuffer, 0, fileBufPtr, fileBuffer.Length);
                    if (fileRead == true)
                    {
                        SetFilePointer(file, 0, IntPtr.Zero, 0);
                        IMAGE_DOS_HEADER     dosHeader          = (IMAGE_DOS_HEADER)Marshal.PtrToStructure(fileBufPtr, typeof(IMAGE_DOS_HEADER));
                        IntPtr               ptrToNtHeaders     = (fileBufPtr + dosHeader.e_lfanew);
                        IMAGE_NT_HEADERS64   ntHeaders          = (IMAGE_NT_HEADERS64)Marshal.PtrToStructure(ptrToNtHeaders, typeof(IMAGE_NT_HEADERS64));
                        IntPtr               ptrToSectionHeader = (ptrToNtHeaders + Marshal.SizeOf(typeof(IMAGE_NT_HEADERS64)));
                        IMAGE_SECTION_HEADER sectionHeader      = (IMAGE_SECTION_HEADER)Marshal.PtrToStructure(ptrToSectionHeader, typeof(IMAGE_SECTION_HEADER));

                        string sectionName = new string(sectionHeader.Name);
                        if (sectionName.Contains("text") && ntHeaders.OptionalHeader.SizeOfImage > payload_size && payload_size < sectionHeader.VirtualSize)
                        {
                            Console.WriteLine("Found usable DLL: " + files[i]);
                            IntPtr baseAddr = IntPtr.Zero;
                            IntPtr hSection = IntPtr.Zero;

                            NtCreateSection(out hSection, SECTION_ALL_ACCESS, IntPtr.Zero, IntPtr.Zero, PAGE_READ_ONLY, SEC_IMAGE, file);
                            NtMapViewOfSection(hSection, GetCurrentProcess(), out baseAddr, UIntPtr.Zero, UIntPtr.Zero, 0, out viewSize, 1, 0, PAGE_READ_ONLY);
                            if (viewSize >= ntHeaders.OptionalHeader.SizeOfImage)
                            {
                                uint   oldProtect  = 0;
                                IntPtr textAddress = IntPtr.Add(baseAddr, sectionHeader.VirtualAddress);
                                bool   a           = VirtualProtect(textAddress, payload_size, PAGE_READWRITE, out oldProtect);
                                Marshal.Copy(payload, 0, textAddress, payload_size);
                                bool b = VirtualProtect(textAddress, payload_size, oldProtect, out oldProtect);
                                if (b == true)
                                {
                                    return(textAddress);
                                }
                            }
                        }
                    }
                }
            }
            return(IntPtr.Zero);
        }