/// <summary> /// Executes code at a given address and returns the thread's exit code. /// </summary> /// <param name="dwStartAddress">Address to be executed.</param> /// <param name="dwParameter">Parameter to be passed to the code being executed.</param> /// <returns>Returns the exit code of the thread.</returns> public uint Execute(uint dwStartAddress, uint dwParameter) { IntPtr hThread; UIntPtr lpExitCode = UIntPtr.Zero; bool bSuccess = false; hThread = CreateRemoteThread(dwStartAddress, dwParameter); if (hThread == IntPtr.Zero) { throw new Exception("Thread could not be remotely created."); } bSuccess = (SThread.WaitForSingleObject(hThread, 10000) == WaitValues.WAIT_OBJECT_0); if (bSuccess) { bSuccess = Imports.GetExitCodeThread(hThread, out lpExitCode); } Imports.CloseHandle(hThread); if (!bSuccess) { throw new Exception("Error waiting for thread to exit or getting exit code."); } return((uint)lpExitCode); }
/// <summary> /// Injects a dll into a process by creating a remote thread on LoadLibrary. /// </summary> /// <param name="hProcess">Handle to the process into which dll will be injected.</param> /// <param name="szDllPath">Full path of the dll that will be injected.</param> /// <returns>Returns the base address of the injected dll on success, zero on failure.</returns> public static uint InjectDllCreateThread(IntPtr hProcess, string szDllPath) { if (hProcess == IntPtr.Zero) { throw new ArgumentNullException("hProcess"); } if (szDllPath.Length == 0) { throw new ArgumentNullException("szDllPath"); } if (!szDllPath.Contains("\\")) { szDllPath = System.IO.Path.GetFullPath(szDllPath); } if (!System.IO.File.Exists(szDllPath)) { throw new ArgumentException("DLL not found.", "szDllPath"); } uint dwBaseAddress = RETURN_ERROR; uint lpLoadLibrary; uint lpDll; IntPtr hThread; lpLoadLibrary = (uint)Imports.GetProcAddress(Imports.GetModuleHandle("kernel32.dll"), "LoadLibraryA"); if (lpLoadLibrary > 0) { lpDll = SMemory.AllocateMemory(hProcess); if (lpDll > 0) { if (SMemory.WriteASCIIString(hProcess, lpDll, szDllPath)) { hThread = SThread.CreateRemoteThread(hProcess, lpLoadLibrary, lpDll); //wait for thread handle to have signaled state //exit code will be equal to the base address of the dll if (SThread.WaitForSingleObject(hThread, 5000) == WaitValues.WAIT_OBJECT_0) { dwBaseAddress = SThread.GetExitCodeThread(hThread); } Imports.CloseHandle(hThread); } SMemory.FreeMemory(hProcess, lpDll); } } return(dwBaseAddress); }