~ruther/csharp-dll-injector

ref: f606b7433c934d799b2c94bf8caf1a6f3bd38c13 csharp-dll-injector/DllUtils/Process/RemoteProcessHandle.cs -rw-r--r-- 1.6 KiB
f606b743 — František Boháček chore: add license 4 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using DllUtils.Exceptions;
using DllUtils.Interop;
using DllUtils.Modules;

namespace DllUtils.Process
{
    public class RemoteProcessHandle : ProcessHandle
    {
        public RemoteProcessHandle(System.Diagnostics.Process process) : base(process)
        {
        }

        public InjectedModule Inject(string dllPath)
        {
            Open();

            RemoteModule kernel32 = GetRemoteKernel32();
            string fullPath = Path.GetFullPath(dllPath);
            IntPtr loadedLibrary = kernel32.ExecuteFunction("LoadLibraryA", Encoding.ASCII.GetBytes(fullPath)).Address;

            if (loadedLibrary == IntPtr.Zero)
            {
                int error = Marshal.GetLastWin32Error();
                ;
                throw new ModuleException($"Failed to inject {dllPath} library.");
            }

            IntPtr localHandle = Kernel32.LoadLibraryA(fullPath);
            if (localHandle == IntPtr.Zero)
            {
                throw new ModuleException($"Failed to load {fullPath} to local process.");
            }

            return new InjectedModule(loadedLibrary, localHandle, this, dllPath);
        }

        public RemoteModule GetRemoteKernel32()
        {
            IntPtr kernel32 = Kernel32.GetModuleHandle("kernel32.dll");
            if (kernel32 == IntPtr.Zero)
            {
                throw new ModuleException("Failed to load kernel32.dll.");
            }

            return new RemoteModule(kernel32, kernel32, this);
        }
    }
}
Do not follow this link