dll的注入 (远程线程方式)

DWORD MyGetProcessHand(LPCSTR lpProcessName)

{
DWORD dwPid = 0;
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(hSnapShot == INVALID_HANDLE_VALUE)
{
printf("CreateToolhelp32Snapshot error: %d\r\n", GetLastError());
return dwPid;
}


PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
Process32First(hSnapShot, &pe32);
do 
{
if(!strcmp(pe32.szExeFile, lpProcessName))
{
dwPid = pe32.th32ProcessID;
break;
}
} while (Process32Next(hSnapShot, &pe32));


CloseHandle(hSnapShot);
return dwPid;
}


void MyEnableDebugPrivilege(HANDLE hProcess)
{
HANDLE hToken;
LUID luid;
TOKEN_PRIVILEGES tps;


if(!OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken))
{
printf("OpenProcessToken error: %d\r\n", GetLastError());
return;
}


if(!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid))
{
printf("luid error: %d\r\n", GetLastError());
CloseHandle(hToken);
return;
}


tps.PrivilegeCount = 1;
tps.Privileges[0].Luid = luid;
tps.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;


if(!AdjustTokenPrivileges(hToken, false, &tps, sizeof(tps), NULL, NULL))
{
printf("AdjustTokenPrivileges error: %d\r\n", GetLastError());
CloseHandle(hToken);
}
}


int main(int argc, char* argv[])
{
// 查询并获取指定进程ID 
DWORD dwPid = MyGetProcessHand((LPCSTR)"pe.exe");
LPCSTR lpDllName = "HookDll.dll";

// 设置本进程权限为debug权限(调试权限),这样可打开其他进程
MyEnableDebugPrivilege(GetCurrentProcess());


// 获取目标进程的句柄
HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_ALL_ACCESS, NULL, dwPid);
if(NULL == hProcess)
{
printf("OpenProcess error: %d\r\n", GetLastError());
return -1;
}



DWORD dwSize = strlen(lpDllName) + 1;
DWORD dwWriteByte;

// 在远程进程中申请内存空间,用来储存注入的dll的路径
LPVOID lpRemoteBuf = VirtualAllocEx(hProcess, NULL, dwSize, MEM_COMMIT, PAGE_READWRITE);


// 写入目标dll路径
if(WriteProcessMemory(hProcess, lpRemoteBuf, (LPVOID)lpDllName, dwSize, &dwWriteByte))
{
if(dwWriteByte != dwSize)
{
VirtualFree(hProcess, dwSize, MEM_COMMIT);
CloseHandle(hProcess);
return -1;
}
}
else
{
printf("WriteProcessMemory error %d\r\n", GetLastError());
CloseHandle(hProcess);
return -1;
}


DWORD dwNewThreadId;
LPVOID lpLoadDll = LoadLibraryA;


// 创建远程线程 (这里的lpLoadDll存放LoadLibraryA, 相当于把LoadLibraryA当做线程处理函数, 而参数就是目标dll的地址)
HANDLE hNewRemoteThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)lpLoadDll, lpRemoteBuf, 0, &dwNewThreadId);
if(NULL == hNewRemoteThread)
{
printf("CreateRemoteThread error %d\r\n", GetLastError());
CloseHandle(hProcess);
return -1;
}

printf("%d\r\n", hNewRemoteThread);
WaitForSingleObject(hNewRemoteThread, INFINITE);
CloseHandle(hNewRemoteThread);

system("pause");


return 0;
}

你可能感兴趣的:(C语言(仅供复习))