// InjectDll.cpp// i686-w64-mingw32-gcc .\InjectDll.cpp -o InjectDll#include"windows.h"#include"tchar.h"#include"stdio.h"boolInjectDll(DWORDdwPID,LPCTSTRszDllPath){HANDLEhProcess=NULL,hThread=NULL;HMODULEhMod=NULL;LPVOIDpRemoteBuf=NULL;DWORDdwBufSize=(DWORD)(_tcslen(szDllPath)+1)*sizeof(TCHAR);LPTHREAD_START_ROUTINEpThreadProc=NULL;// Open the target process with all access rightsif(!(hProcess=OpenProcess(PROCESS_ALL_ACCESS,FALSE,dwPID))){_tprintf(_T("OpenProcess(%d) failed. GetLastError = %d\n"),dwPID,GetLastError());returnfalse;}// Allocate memory in the target process for the DLL pathpRemoteBuf=VirtualAllocEx(hProcess,NULL,dwBufSize,MEM_COMMIT,PAGE_READWRITE);// Write the DLL path to the allocated memory in the target processWriteProcessMemory(hProcess,pRemoteBuf,(LPVOID)szDllPath,dwBufSize,NULL);// Get the address of LoadLibraryW in Kernel32.dllhMod=GetModuleHandle(_T("Kernel32"));pThreadProc=(LPTHREAD_START_ROUTINE)GetProcAddress(hMod,"LoadLibraryA");// LoadLibraryA for ANSI, LoadLibraryW for Unicode// 教本中用的是 LoadLibraryW,但我只能使用 LoadLibraryA// 此处获取到 Kernel32.dll 被加载到 InjectDll.exe 进程中的地址,不是被注入进程中的地址// 但是由于 Kernel32.dll 在所有进程中的基地址都是一样的,所以这个地址在被注入进程中也是正确的// Create a remote thread in the target process to load the DLLhThread=CreateRemoteThread(hProcess,// hProcessNULL,// lpThreadAttributes0,// dwStackSizepThreadProc,// lpStartAddresspRemoteBuf,// lpParameter0,// dwCreationFlagsNULL);// lpThreadIdWaitForSingleObject(hThread,INFINITE);CloseHandle(hThread);CloseHandle(hProcess);returntrue;}int_tmain(intargc,_TCHAR*argv[]){if(argc!=3){_tprintf(_T("Usage: %s <PID> <DLL Path>\n"),argv[0]);return1;}DWORDdwPID=_tstol(argv[1]);LPCTSTRszDllPath=argv[2];if(InjectDll(dwPID,szDllPath)){_tprintf(_T("Successfully injected DLL into process %d with dll path %s\n"),dwPID,szDllPath);}else{_tprintf(_T("Failed to inject DLL into process %d\n"),dwPID);}return0;}