MFC 函数注入

2019-11-22 C++

问题:

USB 通信DLL代码找不到,无法知道通信协议

解决思路:

注入windows相关接口,查看通信过程中发送的协议

实现代码:比如注入CreateFile

typedef HANDLE(WINAPI * Real_CreateFile) (
LPCWSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile);

1. 保存函数调用地址

BYTE g_oldJmp[6] = { 0 };
BYTE g_jmp[6] = { 0 };

2. 实现注入函数 执行函数前先恢复原接口函数地址,执行完再设置为更改后的地址

HANDLE WINAPI Routed_CreateFile(
LPCWSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile)
{
CStringW strTmp(lpFileName);
HANDLE handle = NULL;
VirtualProtect((LPVOID)g_pOrigCreateFile, 6, g_myProtect, NULL); //ReadWrite again
memcpy(g_pOrigCreateFile, g_oldJmp, 6); //Unhook API
handle = CreateFileW(strTmp.GetString(), dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
memcpy(g_pOrigCreateFile, g_jmp, 6); //Rehook API
VirtualProtect((LPVOID)g_pOrigCreateFile, 6, g_oldProtect, NULL); //Normal setts
CStringW strMsg(_T(""));
strMsg.Format(L"%s %x %x %x %x %x\r\n", strTmp.GetString(), dwDesiredAccess, dwShareMode, handle, dwCreationDisposition, dwFlagsAndAttributes);
::OutputDebugStringW(strMsg);
return handle;
}


//注入接口
void BeginRedirect(LPVOID newFunction, LPVOID oldFunction, BYTE *jmp, BYTE *oldJmp)
{
BYTE tempJMP[6] = {0xE9, 0x90, 0x90, 0x90, 0x90, 0xC3}; 
memcpy(jmp, tempJMP, 6);
DWORD dwJMPSize = (reinterpret_cast<DWORD>(newFunction) - reinterpret_cast<DWORD>(oldFunction) - 5);
VirtualProtect(oldFunction, 6, PAGE_EXECUTE_READWRITE, &g_oldProtect);
//Change memory settings to make sure we can write the JMP in
memcpy(oldJmp, oldFunction, 6); //Copy old bytes before writing JMP
memcpy(&jmp[1], &dwJMPSize, 4); //Write the address to JMP to
memcpy(oldFunction, jmp, 6); //Write it in process memory
VirtualProtect((LPVOID)oldFunction, 6, g_oldProtect, NULL); //Change 
}

//初始化

g_pOrigCreateFile = reinterpret_cast<Real_CreateFile>(GetProcAddress(GetModuleHandle("Kernel32.dll"), "CreateFileW")); 
if (g_pOrigCreateFile != NULL)
{
BeginRedirect(Routed_CreateFile, g_pOrigCreateFile, g_jmp, g_oldJmp);
}

标签: c++ 函数hook

评论(0) 浏览(484)

Powered by EMLOG Copyright @ 狼酒 版权所有. 闽ICP备14012694号-2