代码注入进程代码实现

#include"windows.h"
#include"tchar.h"
typedef struct _THREAD_PARAM
{
	FARPROC pFunc[2]; //LoadLibraryA(),GetProcessAddress()
}THREAD_PARAM,*PTHREAD_PARAM;
BYTE g_InjectionCode[] =
{

};

BOOL InjectCode(DWORD dwPID)
{
	HMODULE hMod = NULL;
	THREAD_PARAM param = { 0, };
	HANDLE hProcess = NULL;
	LPVOID pRemoteBuf[2] = { 0, };

	hMod = GetModuleHandleA("kernek32.dll");
	//set THREAD_PRAM
	param.pFunc[0] = GetProcAddress(hMod, "LoadLibraryA");
	param.pFunc[1] = GetProcAddress(hMod, "GetProcessAddress");
	//Open Process
	hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID);
	//Alloction for THREAD_PARAM
	pRemoteBuf[0] = VirtualAllocEx(hProcess, NULL, sizeof(THREAD_PARAM), MEM_COMMIT, PAGE_READWRITE);
	WriteProcessMemory(hProcess, pRemoteBuf[0], (LPVOID)¶m, sizeof(THREAD_PARAM), NULL);
	//Alloction for g_injectionCode
	pRemoteBuf[1] = VirtualAllocEx(hProcess, NULL, sizeof(g_InjectionCode), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
	WriteProcessMemory(hProcess, pRemoteBuf[1], (LPVOID)&g_InjectionCode, sizeof(g_InjectionCode), NULL);
	HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pRemoteBuf[1], pRemoteBuf[0], 0, NULL);
	WaitForSingleObject(hThread, INFINITE);
	CloseHandle(hThread);
	CloseHandle(hProcess);
	return TRUE;
}

//获取库的地址,获取库中函数的地址,分别把2个地址写入到注入线程的内存空间,创建远程线程
int _tmain(int argc,TCHAR *argv[])
{
	InjectCode((DWORD)_tstol(argv[1]));
	return 0;
}

过程分析:

  1. 用GetModuleHandleA函数获取kernel32.dll的加载句柄。
  2. 用GetProcessAddress函数 和刚才获取到的句柄获取到LoadLibraryA函数和GetProcessAddress函数的加载地址。
  3. 利用OpenProcess函数和要注入进程的pid来获取到进程句柄(PROCESS_ALL_ACCESS权限)
  4. 把数据和代码写入到进程的空间中去
    1、需要向3获取到的句柄中写入2获取到的地址(为了能够执行这2个函数)。(利用VirtualAlloc函数和WriteProcessMemory函数)
    2、需要向3获取到的句柄中写入要注入的代码。
  5. 利用CreateRemoteThread来让写入的代码和数据执行。(4步写入的2个内容注入代码作为函数,地址作为参数)

整个过程其实就是写入到远程进程然后执行,写入需要被写入线程的句柄,执行需要执行的代码的地址。

你可能感兴趣的:(逆向,逆向工程核心原理)