//卸載掉指定進程中的指定模塊,一般用來清除DLL木馬
//
//注:
//1,對於多次調用了LoadLibrary的進程,需要多次調用該函數才能夠保證從該進程完全卸載
//2,只有進程創建後動態載入的DLL調用該函數才能夠達到效果(如果指定進程的引入表中包含了欲卸載的模塊,調用雖然能夠成功,但是該模塊的函數資源等仍然有效。)。
//
//參數:
//Pid: 進程ID
//Module: 模塊名
//
//返回值;成功 TRUE,失敗 FALSE
BOOL FreeRemoteModule(DWord Pid, LPCSTR Module)
{
//打開目標進程,需要的3種權限
HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD|PROCESS_VM_OperaTION|PROCESS_VM_WRITE, FALSE, Pid);
if(hProcess==0)
return FALSE;
//在目標進程分配內存並將欲卸載的模塊名寫入
DWORD len=(DWord)strlen(Module)+1,wlen=0;
void* lpBuf=VirtualAllocEx(hProcess, NULL, len, MEM_COMMIT, PAGE_READWRITE);
if(lpBuf==NULL)
{
CloseHandle(hProcess);
return FALSE;
}
if((!WriteProcessMemory(hProcess,lpBuf,(LPVOID)Module,len,&wlen)) || (wlen!=len))
{
VirtualFreeEx(hProcess, lpBuf, len, MEM_DECOMMIT);
CloseHandle(hProcess);
return FALSE;
}
DWord dwHandle,ret;
HANDLE hThread;
LPVOID pFunc;
///////////////////////////////////
///dwHandle=GetModuleHandle(Module)
///////////////////////////////////
pFunc= GetModuleHandleA;
hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pFunc, lpBuf, 0, NULL);
// 等待GetModuleHandle運行完畢
ret=WaitForSingleObject(hThread, INFINITE);
// 獲得GetModuleHandle的返回值
ret=GetExitCodeThread(hThread, &dwHandle);
// 釋放目標進程中申請的空間
ret=VirtualFreeEx(hProcess, lpBuf, len, MEM_DECOMMIT);
ret=CloseHandle(hThread);
///////////////////////////////////////
//FreeLibrary(dwHandle);
///////////////////////////////////////
pFunc = FreeLibrary;
hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pFunc, (LPVOID)dwHandle, 0, NULL);
// 等待FreeLibrary卸載完畢
ret=WaitForSingleObject(hThread, INFINITE);
ret=CloseHandle(hThread);
ret=CloseHandle(hProcess);
return TRUE;
}