- Command Line: inject.exe <Target Process> <DLL to be injected>
- For example: inject.exe notepad.exe Agent.dll
- Source Code (inject.exe):
#include "windows.h"
#include "tchar.h"
#include "TLHELP32.H"
#include "stddef.h"
#include "stdio.h"
#include "Shlwapi.h"
#pragma comment(lib, "shlwapi.lib")
DWORD FindTarget(LPCTSTR lpszProcess);
void Inject(DWORD dProcessId, LPCTSTR lpszDllName);
DWORD hLibModule = 0;
int _tmain(int argc, _TCHAR* argv[])
{
if (argc != 3)
{
printf("Usage: Envedit.exe <process id> <dll to be injected>\n");
return -1;
}
DWORD dProcessId = 0;
dProcessId = FindTarget((LPCTSTR)argv[1]);
if (dProcessId == 0)
{
printf("Cannot find process specified as the command line option.\n");
return -1;
}
TCHAR szLibPath[MAX_PATH];
GetCurrentDirectory(MAX_PATH, szLibPath);
_tcscat(szLibPath, _T("\\"));
_tcscat(szLibPath, (LPCTSTR)argv[2]);
if (!PathFileExists(szLibPath))
{
printf("Cannot find .dll file specified as the command line option.\n");
return -1;
}
Inject(dProcessId, szLibPath);
return 0;
}
DWORD FindTarget(LPCTSTR lpszProcess)
{
DWORD dwRet = 0;
PROCESSENTRY32 pe32 = { sizeof( PROCESSENTRY32 ) };
HANDLE hSnapshot = NULL;
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
Process32First(hSnapshot, &pe32);
do
{
if (0 == lstrcmpi(pe32.szExeFile, lpszProcess))
{
dwRet = pe32.th32ProcessID;
break;
}
} while (Process32Next(hSnapshot, &pe32));
CloseHandle(hSnapshot);
return dwRet;
}
void Inject(DWORD dProcessId, LPCTSTR lpszDllName)
{
HANDLE hProcess = NULL;
HANDLE hThread = NULL;
LPVOID lpRemoteAddress = NULL;
BOOL bResult = FALSE;
do
{
hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE,
FALSE, dProcessId);
if (hProcess == NULL)
{
break;
}
lpRemoteAddress = VirtualAllocEx(hProcess, NULL, _tcslen(lpszDllName) * sizeof(TCHAR),
MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (lpRemoteAddress == NULL)
{
break;
}
bResult = WriteProcessMemory(hProcess, lpRemoteAddress, (LPVOID)lpszDllName, _tcslen(lpszDllName) * sizeof(TCHAR), NULL);
if (bResult == FALSE)
{
break;
}
LPTHREAD_START_ROUTINE pFun =
(LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(_T("Kernel32.dll")), "LoadLibraryW");
hThread = CreateRemoteThread(hProcess, NULL, 0, pFun, lpRemoteAddress, 0, NULL);
if (hThread == NULL)
{
break;
}
if (WAIT_FAILED == WaitForSingleObject(hThread, INFINITE))
{
break;
}
if (0 == GetExitCodeThread(hThread, &hLibModule))
{
break;
}
CloseHandle(hThread);
pFun = (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(_T("Kernel32.dll")), "FreeLibrary" );
hThread = CreateRemoteThread(hProcess, NULL, 0, pFun, lpRemoteAddress, 0, NULL);
if (hThread == FALSE)
{
break;
}
if (WAIT_FAILED == WaitForSingleObject(hThread, INFINITE))
{
break;
}
} while (0);
if (hThread != NULL)
{
CloseHandle(hThread);
}
if (hProcess != NULL)
{
CloseHandle(hProcess);
}
if (lpRemoteAddress != NULL)
{
VirtualFreeEx( hProcess, lpRemoteAddress, _tcslen(lpszDllName) * sizeof(TCHAR), MEM_RELEASE);
}
}
Hope this can help…