DLL injection using remote threads

/*Principle: Create a thread in the target process and let the created thread load its own DLL*/
void CInjectDLLDlg::OnBnClickedBtnThread()
{
	/* Get a handle to the running process */
	HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD |
		                         PROCESS_VM_OPERATION | PROCESS_VM_WRITE, FALSE, m_dwId);
	if ( !hProcess ) {
		return ;
	}

	/*The local process applies for memory in the address space of the remote process and stores the path string of the dll in the remote address space*/
	TCHAR szDllPath[MAX_PATH] = _T("D:\\DrawingProgram\\InjectDLL\\Debug\\MyDll.dll");
	int cByte  = (_tcslen(szDllPath)+1) * sizeof(TCHAR);
	LPVOID pAddr = VirtualAllocEx(hProcess, NULL, cByte, MEM_COMMIT, PAGE_READWRITE);
	if ( !pAddr || !WriteProcessMemory(hProcess, pAddr, szDllPath, cByte, NULL)) {
		return ;
	}

	/* Get the address of the LoadLibrary function */
#ifdef _UNICODE
	PTHREAD_START_ROUTINE pfnStartAddr = (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(_T("Kernel32")), "LoadLibraryW");
#else
	PTHREAD_START_ROUTINE pfnStartAddr = (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(_T("Kernel32")), "LoadLibraryA");
#endif
	if ( !pfnStartAddr ) {
		return ;
	}

	/*Create a new thread in the target process. When the new thread is created, the LoadLibrary function will be called immediately, and the address of the DLL path name will be passed in */
	DWORD dwThreadID = 0;
	HANDLE hRemoteThread = CreateRemoteThread(hProcess, NULL, 0, pfnStartAddr, pAddr, 0, &dwThreadID);
	if ( !hRemoteThread ) {
		return ;
	}
	CloseHandle(hRemoteThread);
	CloseHandle(hProcess);
	return ;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326315221&siteId=291194637