めいくりぷとのブログ

技術的なことをまったりと。

xigncode copy dll bypass

VOID Detour_o_o()
	{
		typedef LPVOID(WINAPI *VirtualAlloc_t)(
			_In_opt_ LPVOID lpAddress,
			_In_	 SIZE_T dwSize,
			_In_	 DWORD  flAllocationType,
			_In_	 DWORD  flProtect
			);

		typedef BOOL(WINAPI *VirtualProtect_t)(
			_In_  LPVOID lpAddress,
			_In_  SIZE_T dwSize,
			_In_  DWORD  flNewProtect,
			_Out_ PDWORD lpflOldProtect
			);

		static HMODULE hNTDLL = NULL;
		static HMODULE hKERNELBASE = NULL;

		static VirtualAlloc_t _VirtualAlloc =
			reinterpret_cast<VirtualAlloc_t>(GetProcAddress(GetModuleHandle(L"KERNELBASE.dll"), "VirtualAlloc"));
		VirtualAlloc_t VirtualAlloc_Hook = [](
			_In_opt_ LPVOID lpAddress,
			_In_     SIZE_T dwSize,
			_In_     DWORD  flAllocationType,
			_In_     DWORD  flProtect) -> LPVOID
		{
			HMODULE	hModule;
			LPVOID lpBuffer;
			
			lpBuffer = _VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect);
			if (lpBuffer)
			{
				GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast<LPCWSTR>(_ReturnAddress()), &hModule);
				if (hModule == GetModuleHandle(L"x3.xem") ||
					hModule == NULL)
				{
					if (dwSize == xigncode_manager::get_file_size("ntdll") && !hNTDLL)
						hNTDLL = reinterpret_cast<HMODULE>(lpBuffer);

					if (dwSize == xigncode_manager::get_file_size("kernelbase") && !hKERNELBASE)
						hKERNELBASE = reinterpret_cast<HMODULE>(lpBuffer);
				}
			}

			return lpBuffer;
		};

		static VirtualProtect_t _VirtualProtect =
			reinterpret_cast<VirtualProtect_t>(GetProcAddress(GetModuleHandle(L"KERNELBASE.dll"), "VirtualProtect"));
		VirtualProtect_t VirtualProtect_Hook = [](
			_In_  LPVOID lpAddress,
			_In_  SIZE_T dwSize,
			_In_  DWORD  flNewProtect,
			_Out_ PDWORD lpflOldProtect) -> BOOL
		{
			LPVOID lpBaseAddress;
			HMODULE	hModule;
	
			GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast<LPCWSTR>(_ReturnAddress()), &hModule);
			if (hModule == GetModuleHandle(L"x3.xem") ||
				hModule == NULL)
			{
				if (dwSize > 0x00010000)
				{
					lpBaseAddress = reinterpret_cast<LPVOID>(PBYTE(lpAddress) - 0x1000);
					if (lpBaseAddress != NULL)
					{
						if (lpBaseAddress == (LPVOID)hNTDLL)
						{
							Detour_NtQueryVirtualMemory(lpBaseAddress);
							Detour_NtOpenProcess(lpBaseAddress);
							Detour_NtQuerySystemInformation(lpBaseAddress);
						}
						else if (lpBaseAddress == (LPVOID)hKERNELBASE)
						{
							Detour_VirtualAlloc(lpBaseAddress);
							Detour_VirtualProtect(lpBaseAddress);
						}
					}
				}	
			}

			return _VirtualProtect(lpAddress, dwSize, flNewProtect, lpflOldProtect);
		};

		DetourFunction(TRUE, reinterpret_cast<LPVOID*>(&_VirtualAlloc), VirtualAlloc_Hook);
		DetourFunction(TRUE, reinterpret_cast<LPVOID*>(&_VirtualProtect), VirtualProtect_Hook);
	}