1. 远程线程注入原理

远程线程注入就是用我们自己的进程在另一个进程中创建一个线程,调用另一个进程中的函数。比如我们在另一个进程中调用LoadLibrarayW函数,就可以在目标进程中注入Dll

注入原理图如下:

0.png

2. 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
HANDLE processHandle = NULL;
LPVOID remoteMemoryAddress = 0;
HMODULE kernal32ModuleHandle = NULL;
LPVOID loadLibraryAddress = NULL;

bool injectRemote(DWORD PID) {
processHandle = OpenProcess(PROCESS_ALL_ACCESS, NULL, PID);
if (processHandle == NULL)
{
// Fail to open the process
printf("Fail To Open Process: %d\n", GetLastError());
return EXIT_FAILURE;
}

TCHAR dllPath[MAX_PATH] = TEXT("D:\\Inject.dll");

// Create a physical and virtual memory in the remote process:
remoteMemoryAddress = VirtualAllocEx(processHandle, NULL, MAX_PATH, MEM_COMMIT, PAGE_READWRITE);
// Write dll path to remote memory
if (WriteProcessMemory(processHandle, remoteMemoryAddress, (LPCVOID)dllPath, MAX_PATH, NULL) == 0) {
printf("Fail to write process memory: %d\n", GetLastError());
VirtualFreeEx(processHandle, remoteMemoryAddress, REMOTE_MEMORY_SIZE, MEM_RELEASE);
CloseHandle(processHandle);
return EXIT_FAILURE;
}

kernal32ModuleHandle = GetModuleHandle(TEXT("kernel32.dll"));
if (kernal32ModuleHandle == NULL)
{
printf("Fail to find kernal32.dll: %d\n", GetLastError());
VirtualFreeEx(processHandle, remoteMemoryAddress, REMOTE_MEMORY_SIZE, MEM_RELEASE);
CloseHandle(processHandle);
return EXIT_FAILURE;
}

loadLibraryAddress = (LPVOID)GetProcAddress(kernal32ModuleHandle, "LoadLibraryW");
if (loadLibraryAddress == NULL)
{
printf("find LoadLibraryW failed: %d\n", GetLastError());
VirtualFreeEx(processHandle, remoteMemoryAddress, REMOTE_MEMORY_SIZE, MEM_RELEASE);
CloseHandle(kernal32ModuleHandle);
CloseHandle(processHandle);
return EXIT_FAILURE;
}


if (CreateRemoteThread(processHandle, NULL, 0, (LPTHREAD_START_ROUTINE)loadLibraryAddress, remoteMemoryAddress, 0, NULL) == NULL)
{
printf("Create Remote Threads Error: %d\n", GetLastError());
VirtualFreeEx(processHandle, remoteMemoryAddress, REMOTE_MEMORY_SIZE, MEM_RELEASE);
CloseHandle(kernal32ModuleHandle);
CloseHandle(processHandle);
return EXIT_FAILURE;
}


VirtualFreeEx(processHandle, remoteMemoryAddress, REMOTE_MEMORY_SIZE, MEM_RELEASE);
CloseHandle(processHandle);
}