Example #1
0
        private IntPtr LoadDll(string dllPath, int id)
        {
            try
            {
                IntPtr hProcess = PInvoke.OpenProcess(ExtendedTypes.ProcessAccessFlags.All, false, id);

                IntPtr hModule;

                IntPtr fnLoadLibraryW = PInvoke.GetProcAddress(PInvoke.GetModuleHandleA("kernel32.dll"), "LoadLibraryW");

                if (fnLoadLibraryW == IntPtr.Zero)
                {
                    throw new Exception("Unable to locate the LoadLibraryW entry point");
                }

                // Create a wchar_t * in the remote process which points to the unicode version of the dll path.
                IntPtr pLib = Utils.CreateRemotePointer(hProcess, Encoding.Unicode.GetBytes(dllPath + "\0"), 0x04);

                if (pLib == IntPtr.Zero)
                {
                    throw new InvalidOperationException("Failed to allocate memory in the remote process");
                }

                try
                {
                    // Call LoadLibraryW in the remote process by using CreateRemoteThread.
                    uint hMod = Utils.RunThread(hProcess, fnLoadLibraryW, pLib, 10000);

                    if (hMod == uint.MaxValue)
                    {
                        throw new Exception("Error occurred when calling function in the remote process");
                    }
                    else if (hMod == 0)
                    {
                        throw new Exception("Failed to load module into remote process. Error code: " + Utils.GetLastErrorEx(hProcess).ToString());
                    }
                    else
                    {
                        hModule = new IntPtr(hMod);
                    }
                }
                finally
                {
                    // Cleanup in all cases.
                    PInvoke.VirtualFreeEx(hProcess, pLib, 0, 0x8000);
                }
                return(hModule);
            }
            catch (Exception e)
            {
                logBox.AppendText("\n" + e.Message);
                return(IntPtr.Zero);
            }
        }
Example #2
0
        public static IntPtr CreateRemotePointer(IntPtr hProcess, byte[] pData, int flProtect)
        {
            if (pData == null || hProcess == IntPtr.Zero)
            {
                return(IntPtr.Zero);
            }

            IntPtr lpAddress = PInvoke.VirtualAllocEx(hProcess, IntPtr.Zero, (uint)pData.Length, 12288, flProtect);

            if (lpAddress != IntPtr.Zero && PInvoke.WriteProcessMemory(hProcess, lpAddress, pData, pData.Length, out uint lpNumberOfBytesRead) && lpNumberOfBytesRead == pData.Length || lpAddress == IntPtr.Zero)
            {
                return(lpAddress);
            }

            PInvoke.VirtualFreeEx(hProcess, lpAddress, 0, 32768);
            lpAddress = IntPtr.Zero;

            return(lpAddress);
        }