12, the remote thread injection

Remote thread injection

// use the last article of edr.dll copied to Debug following MFC project inside
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description

#include <strsafe.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#ifdef UNICODE
#define InjectLib InjectLibW
#else
#define InjectLib InjectLibA
#endif

BOOL WINAPI InjectLibW(DWORD dwProcessId,PCWSTR pszLibFile)
{
	BOOL bOK = FALSE;
	HANDLE hProcess = NULL,hThread = NULL;
	PWSTR pszLibFileRemote = NULL;
	__try
	{
		hProcess = OpenProcess(
			PROCESS_QUERY_INFORMATION	|
			PROCESS_CREATE_THREAD		|
			PROCESS_VM_OPERATION		|
			PROCESS_VM_WRITE,
			FALSE,dwProcessId);
		if(hProcess == NULL) __leave;

		int cch = lstrlenW(pszLibFile) + 1;
		int cb = cch * sizeof(wchar_t);

		pszLibFileRemote = (PWSTR)VirtualAllocEx(hProcess,NULL,cb,MEM_COMMIT,PAGE_READWRITE);
		if(pszLibFileRemote == NULL) __leave;

		if(!WriteProcessMemory(hProcess,pszLibFileRemote,(PVOID)pszLibFile,cb,NULL)) __leave;

		PTHREAD_START_ROUTINE pfnThreadRtn = (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(TEXT("Kernel32")),"LoadLibraryW");

		if(pfnThreadRtn == NULL) __leave;



		hThread = CreateRemoteThread(hProcess,NULL,0,pfnThreadRtn,pszLibFileRemote,0,NULL);
		if(hThread == NULL) __leave;

		WaitForSingleObject(hThread,INFINITE);

		bOK = TRUE;
	}
	__finally
	{
		if(pszLibFileRemote != NULL)
			VirtualFreeEx(hProcess,pszLibFileRemote,0,MEM_RELEASE);
		if(hThread != NULL)
			CloseHandle(hThread);

		if(hProcess != NULL)
			CloseHandle(hProcess);
	}
	return bOK;
}

BOOL WINAPI InjectLibA(DWORD dwProcessId,PCSTR pszLibFile)
{

	SIZE_T cchSize = lstrlenA(pszLibFile) + 1;
	PWSTR pszLibFileW = (PWSTR)_alloca(cchSize * sizeof(wchar_t));

	StringCchPrintfW(pszLibFileW,cchSize,L"%s",pszLibFile);

	return InjectLibW(dwProcessId,pszLibFileW);
}

......

void CdemoDlg::OnBnClickedButton1()
{
	// TODO: 在此添加控件通知处理程序代码
	UpdateData(TRUE);
	DWORD dwProcessId = m_npid;



	TCHAR szLibFile[MAX_PATH];
	GetModuleFileName(NULL,szLibFile,_countof(szLibFile));


	PTSTR pFileName = _tcschr(szLibFile,TEXT('\\')) + 1;
	_tcscpy_s(pFileName,_countof(szLibFile)-(pFileName - szLibFile),TEXT("edr.dll"));

	TRACE("%d\n",dwProcessId);
	TRACE(L"%s",pFileName);
	if(InjectLib(dwProcessId,szLibFile))
	{
		AfxMessageBox(_T("DLL Injection successful"));
		
		
	}
	else
	{
		AfxMessageBox(_T("DLL Injection failed"));
	}



}


Here Insert Picture Description

Published 32 original articles · won praise 53 · views 240 000 +

Guess you like

Origin blog.csdn.net/qq_42250189/article/details/105212067