第27章:代码注入(略)
实现代码注入不仅需要将需要执行的代码写入对应的进程,还需要将对应的数据也写入其中.
代码注入是一个可执行程序对另一个程序的注入,main函数通过调用InjectCode函数实现注入
BOOL InjectCode(DWORD dwPID) { HMODULE hMod = NULL; THREAD_PARAM param = {0,}; HANDLE hProcess = NULL; HANDLE hThread = NULL; LPVOID pRemoteBuf[2] = {0,}; DWORD dwSize = 0; hMod = GetModuleHandleA("kernel32.dll"); // set THREAD_PARAM 前面定义了一系列的结构体变量 param.pFunc[0] = GetProcAddress(hMod, "LoadLibraryA"); param.pFunc[1] = GetProcAddress(hMod, "GetProcAddress"); strcpy_s(param.szBuf[0], "user32.dll"); strcpy_s(param.szBuf[1], "MessageBoxA"); strcpy_s(param.szBuf[2], "www.reversecore.com"); strcpy_s(param.szBuf[3], "ReverseCore"); // Open Process if ( !(hProcess = OpenProcess(PROCESS_ALL_ACCESS, // dwDesiredAccess FALSE, // bInheritHandle dwPID)) ) // dwProcessId { printf("OpenProcess() fail : err_code = %d\n", GetLastError()); return FALSE; } // Allocation for THREAD_PARAM 将自定义的结构体数据写入目标进程内 dwSize = sizeof(THREAD_PARAM); if( !(pRemoteBuf[0] = VirtualAllocEx(hProcess, // hProcess NULL, // lpAddress dwSize, // dwSize MEM_COMMIT, // flAllocationType PAGE_READWRITE)) ) // flProtect { printf("VirtualAllocEx() fail : err_code = %d\n", GetLastError()); return FALSE; } if( !WriteProcessMemory(hProcess, // hProcess pRemoteBuf[0], // lpBaseAddress (LPVOID)¶m, // lpBuffer dwSize, // nSize NULL) ) // [out] lpNumberOfBytesWritten { printf("WriteProcessMemory() fail : err_code = %d\n", GetLastError()); return FALSE; }
// Allocation for ThreadProc() 将代码写入目标进程中 dwSize = (DWORD)InjectCode - (DWORD)ThreadProc; //地址相减,函数写的时候是ThreadProc前面,InjectCode在后面. if( !(pRemoteBuf[1] = VirtualAllocEx(hProcess, // hProcess NULL, // lpAddress dwSize, // dwSize MEM_COMMIT, // flAllocationType PAGE_EXECUTE_READWRITE)) ) // flProtect { printf("VirtualAllocEx() fail : err_code = %d\n", GetLastError()); return FALSE; } if( !WriteProcessMemory(hProcess, // hProcess pRemoteBuf[1], // lpBaseAddress (LPVOID)ThreadProc, // lpBuffer dwSize, // nSize NULL) ) // [out] lpNumberOfBytesWritten { printf("WriteProcessMemory() fail : err_code = %d\n", GetLastError()); return FALSE; } if( !(hThread = CreateRemoteThread(hProcess, // hProcess NULL, // lpThreadAttributes 0, // dwStackSize (LPTHREAD_START_ROUTINE)pRemoteBuf[1], // dwStackSize pRemoteBuf[0], // lpParameter 0, // dwCreationFlags NULL)) ) // lpThreadId { printf("CreateRemoteThread() fail : err_code = %d\n", GetLastError()); return FALSE; } WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); CloseHandle(hProcess); return TRUE; }
现在暂时用不上,留作以后参考