bool TryGetModuleHandle(string moduleName, out IntPtr moduleHandle) { moduleHandle = IntPtr.Zero; IntPtr h = Win32Functions.GetModuleHandle(moduleName); if (h != IntPtr.Zero) { moduleHandle = h; } return(moduleHandle != IntPtr.Zero); }
bool TryOpenProcess(int pid, out IntPtr handle) { handle = IntPtr.Zero; IntPtr i = Win32Functions.OpenProcess(ProcessAccessFlags.All, false, pid); if (i != IntPtr.Zero) { handle = i; } return(handle != IntPtr.Zero); }
bool TryGetProcAddress(IntPtr hModule, string funcName, out IntPtr funcPtr) { funcPtr = IntPtr.Zero; if (hModule != IntPtr.Zero) { IntPtr p = Win32Functions.GetProcAddress(hModule, funcName); if (p != IntPtr.Zero) { funcPtr = p; } return(funcPtr != IntPtr.Zero); } return(false); }
void ReadyForProcess() { if (!TryOpenProcess(_pid, out _hProcess)) { _readiedForInject = false; return; } _remoteMemory = Win32Functions.VirtualAllocEx(_hProcess, IntPtr.Zero, (uint)_dllName.ToBytes(Encoding.ASCII).Length + 5, AllocationType.Commit, MemoryProtection.ReadWrite); if (_remoteMemory == IntPtr.Zero) { _readiedForInject = false; return; } byte[] toWriteBytes = _dllName.ToBytes(Encoding.ASCII); IntPtr pBuffer = Marshal.AllocHGlobal(toWriteBytes.Length + 5); Marshal.Copy(toWriteBytes, 0, pBuffer, toWriteBytes.Length); int wroteSize = 0; bool suc = Win32Functions.WriteProcessMemory(_hProcess, _remoteMemory, pBuffer, toWriteBytes.Length, ref wroteSize); if (suc && wroteSize != toWriteBytes.Length) { _readiedForInject = false; return; } if (!TryGetModuleHandle("kernel32", out _k32Handle)) { _readiedForInject = false; return; } if (!TryGetProcAddress(_k32Handle, "LoadLibraryA", out _loadDllPtr)) { _readiedForInject = false; return; } _readiedForInject = true; }
public bool Inject() { ReadyForProcess(); if (_readiedForInject) { IntPtr hThread = Win32Functions.CreateRemoteThread(_hProcess, IntPtr.Zero, 0, _loadDllPtr, _remoteMemory, 0, IntPtr.Zero); if (hThread != IntPtr.Zero) { Win32Functions.WaitForSingleObject(hThread, 0xffffffff); Clean(); Win32Functions.CloseHandle(hThread); return(true); } Clean(); return(false); } return(false); }
void Clean() { Win32Functions.VirtualFreeEx(_hProcess, _remoteMemory, _dllName.ToBytes(Encoding.ASCII).Length + 5, AllocationType.Decommit); }