-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMonoInjector.cs
More file actions
383 lines (313 loc) · 14.8 KB
/
MonoInjector.cs
File metadata and controls
383 lines (313 loc) · 14.8 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Trinity
{
/// <summary>
/// SharpMonoInjector-style injector for Unity Mono games
/// Properly injects managed DLLs into running Unity processes
/// </summary>
public class MonoInjector : IDisposable
{
#region Native Methods
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, IntPtr dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr lpAddress, IntPtr dwSize, uint dwFreeType);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, IntPtr nSize, out IntPtr lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, IntPtr nSize, out IntPtr lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, IntPtr dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, out IntPtr lpThreadId);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetExitCodeThread(IntPtr hThread, out IntPtr lpExitCode);
[DllImport("psapi.dll", SetLastError = true)]
private static extern bool EnumProcessModulesEx(IntPtr hProcess, [Out] IntPtr[] lphModule, uint cb, out uint lpcbNeeded, uint dwFilterFlag);
[DllImport("psapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern uint GetModuleBaseName(IntPtr hProcess, IntPtr hModule, StringBuilder lpBaseName, uint nSize);
private const uint PROCESS_ALL_ACCESS = 0x1F0FFF;
private const uint MEM_COMMIT = 0x1000;
private const uint MEM_RESERVE = 0x2000;
private const uint MEM_RELEASE = 0x8000;
private const uint PAGE_EXECUTE_READWRITE = 0x40;
private const uint INFINITE = 0xFFFFFFFF;
private const uint LIST_MODULES_ALL = 0x03;
#endregion
private IntPtr _handle;
private IntPtr _monoModule;
private Dictionary<string, IntPtr> _exports = new Dictionary<string, IntPtr>();
private List<IntPtr> _allocations = new List<IntPtr>();
private bool _attached;
private bool _is64Bit;
public bool Attach(Process process)
{
_handle = OpenProcess(PROCESS_ALL_ACCESS, false, process.Id);
if (_handle == IntPtr.Zero)
return false;
_monoModule = FindMonoModule();
if (_monoModule == IntPtr.Zero)
{
CloseHandle(_handle);
return false;
}
_is64Bit = Is64BitProcess();
_attached = true;
return true;
}
private bool Is64BitProcess()
{
// Read DOS header to get PE offset
byte[] dosHeader = new byte[64];
ReadProcessMemory(_handle, _monoModule, dosHeader, (IntPtr)64, out _);
int peOffset = BitConverter.ToInt32(dosHeader, 60);
// Read PE signature + file header (machine type is at offset 4 from PE sig)
byte[] peHeader = new byte[6];
ReadProcessMemory(_handle, _monoModule + peOffset, peHeader, (IntPtr)6, out _);
// Machine type: 0x8664 = AMD64, 0x014c = i386
ushort machine = BitConverter.ToUInt16(peHeader, 4);
return machine == 0x8664;
}
private IntPtr FindMonoModule()
{
IntPtr[] modules = new IntPtr[1024];
if (!EnumProcessModulesEx(_handle, modules, (uint)(modules.Length * IntPtr.Size), out uint cbNeeded, LIST_MODULES_ALL))
return IntPtr.Zero;
int count = (int)(cbNeeded / IntPtr.Size);
StringBuilder name = new StringBuilder(260);
for (int i = 0; i < count; i++)
{
if (modules[i] == IntPtr.Zero) continue;
name.Clear();
if (GetModuleBaseName(_handle, modules[i], name, 260) > 0)
{
string n = name.ToString().ToLower();
if (n.Contains("mono") && n.EndsWith(".dll"))
return modules[i];
}
}
return IntPtr.Zero;
}
public IntPtr GetExport(string name)
{
if (_exports.TryGetValue(name, out IntPtr addr))
return addr;
addr = GetExportAddress(name);
if (addr != IntPtr.Zero)
_exports[name] = addr;
return addr;
}
private IntPtr GetExportAddress(string exportName)
{
byte[] dosHeader = ReadBytes(_monoModule, 64);
int peOffset = BitConverter.ToInt32(dosHeader, 60);
byte[] peHeader = ReadBytes(_monoModule + peOffset, 24);
bool is64 = BitConverter.ToUInt16(peHeader, 4) == 0x8664;
int optSize = BitConverter.ToUInt16(peHeader, 20);
byte[] optHeader = ReadBytes(_monoModule + peOffset + 24, optSize);
int exportRva = BitConverter.ToInt32(optHeader, is64 ? 112 : 96);
if (exportRva == 0) return IntPtr.Zero;
byte[] exportDir = ReadBytes(_monoModule + exportRva, 40);
int numFuncs = BitConverter.ToInt32(exportDir, 20);
int numNames = BitConverter.ToInt32(exportDir, 24);
int funcsRva = BitConverter.ToInt32(exportDir, 28);
int namesRva = BitConverter.ToInt32(exportDir, 32);
int ordsRva = BitConverter.ToInt32(exportDir, 36);
byte[] namePtrs = ReadBytes(_monoModule + namesRva, numNames * 4);
byte[] ords = ReadBytes(_monoModule + ordsRva, numNames * 2);
byte[] funcs = ReadBytes(_monoModule + funcsRva, numFuncs * 4);
for (int i = 0; i < numNames; i++)
{
int nameRva = BitConverter.ToInt32(namePtrs, i * 4);
string n = ReadString(_monoModule + nameRva);
if (n == exportName)
{
int ord = BitConverter.ToUInt16(ords, i * 2);
int funcRva = BitConverter.ToInt32(funcs, ord * 4);
return _monoModule + funcRva;
}
}
return IntPtr.Zero;
}
private byte[] ReadBytes(IntPtr addr, int size)
{
byte[] buffer = new byte[size];
ReadProcessMemory(_handle, addr, buffer, (IntPtr)size, out _);
return buffer;
}
private string ReadString(IntPtr addr)
{
byte[] buffer = new byte[256];
ReadProcessMemory(_handle, addr, buffer, (IntPtr)256, out _);
int len = Array.IndexOf(buffer, (byte)0);
return Encoding.ASCII.GetString(buffer, 0, len >= 0 ? len : 256);
}
public IntPtr AllocateMemory(int size)
{
IntPtr addr = VirtualAllocEx(_handle, IntPtr.Zero, (IntPtr)size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (addr != IntPtr.Zero)
_allocations.Add(addr);
return addr;
}
public bool WriteMemory(IntPtr addr, byte[] data)
{
return WriteProcessMemory(_handle, addr, data, (IntPtr)data.Length, out _);
}
public IntPtr WriteString(string str)
{
byte[] data = Encoding.UTF8.GetBytes(str + "\0");
IntPtr addr = AllocateMemory(data.Length);
if (addr == IntPtr.Zero) return IntPtr.Zero;
WriteMemory(addr, data);
return addr;
}
public IntPtr Execute(IntPtr funcAddr, IntPtr arg = default)
{
IntPtr thread = CreateRemoteThread(_handle, IntPtr.Zero, IntPtr.Zero, funcAddr, arg, 0, out _);
if (thread == IntPtr.Zero) return IntPtr.Zero;
WaitForSingleObject(thread, INFINITE);
GetExitCodeThread(thread, out IntPtr result);
CloseHandle(thread);
return result;
}
public IntPtr ExecuteWithArgs(IntPtr funcAddr, params IntPtr[] args)
{
// Build shellcode to call function with multiple arguments
List<byte> shellcode = new List<byte>();
if (_is64Bit)
{
// x64 calling convention: RCX, RDX, R8, R9, then stack
// sub rsp, 0x28 (shadow space + alignment)
shellcode.AddRange(new byte[] { 0x48, 0x83, 0xEC, 0x28 });
// mov rcx, arg0
if (args.Length > 0)
{
shellcode.AddRange(new byte[] { 0x48, 0xB9 });
shellcode.AddRange(BitConverter.GetBytes(args[0].ToInt64()));
}
// mov rdx, arg1
if (args.Length > 1)
{
shellcode.AddRange(new byte[] { 0x48, 0xBA });
shellcode.AddRange(BitConverter.GetBytes(args[1].ToInt64()));
}
// mov r8, arg2
if (args.Length > 2)
{
shellcode.AddRange(new byte[] { 0x49, 0xB8 });
shellcode.AddRange(BitConverter.GetBytes(args[2].ToInt64()));
}
// mov r9, arg3
if (args.Length > 3)
{
shellcode.AddRange(new byte[] { 0x49, 0xB9 });
shellcode.AddRange(BitConverter.GetBytes(args[3].ToInt64()));
}
// mov rax, funcAddr
shellcode.AddRange(new byte[] { 0x48, 0xB8 });
shellcode.AddRange(BitConverter.GetBytes(funcAddr.ToInt64()));
// call rax
shellcode.AddRange(new byte[] { 0xFF, 0xD0 });
// add rsp, 0x28
shellcode.AddRange(new byte[] { 0x48, 0x83, 0xC4, 0x28 });
// ret
shellcode.Add(0xC3);
}
else
{
// x86: push args in reverse order
for (int i = args.Length - 1; i >= 0; i--)
{
shellcode.Add(0x68); // push imm32
shellcode.AddRange(BitConverter.GetBytes(args[i].ToInt32()));
}
// mov eax, funcAddr
shellcode.Add(0xB8);
shellcode.AddRange(BitConverter.GetBytes(funcAddr.ToInt32()));
// call eax
shellcode.AddRange(new byte[] { 0xFF, 0xD0 });
// ret
shellcode.Add(0xC3);
}
byte[] code = shellcode.ToArray();
IntPtr codeAddr = AllocateMemory(code.Length);
if (codeAddr == IntPtr.Zero) return IntPtr.Zero;
WriteMemory(codeAddr, code);
return Execute(codeAddr);
}
public bool Inject(string assemblyPath, string namespaceName, string className, string methodName)
{
if (!_attached) return false;
// Get mono functions
IntPtr mono_get_root_domain = GetExport("mono_get_root_domain");
IntPtr mono_thread_attach = GetExport("mono_thread_attach");
IntPtr mono_assembly_open = GetExport("mono_assembly_open");
IntPtr mono_assembly_get_image = GetExport("mono_assembly_get_image");
IntPtr mono_class_from_name = GetExport("mono_class_from_name");
IntPtr mono_class_get_method_from_name = GetExport("mono_class_get_method_from_name");
IntPtr mono_runtime_invoke = GetExport("mono_runtime_invoke");
if (mono_get_root_domain == IntPtr.Zero || mono_thread_attach == IntPtr.Zero ||
mono_assembly_open == IntPtr.Zero || mono_assembly_get_image == IntPtr.Zero ||
mono_class_from_name == IntPtr.Zero || mono_class_get_method_from_name == IntPtr.Zero ||
mono_runtime_invoke == IntPtr.Zero)
{
return false;
}
// Get root domain
IntPtr rootDomain = Execute(mono_get_root_domain);
if (rootDomain == IntPtr.Zero) return false;
// Attach thread
ExecuteWithArgs(mono_thread_attach, rootDomain);
// Write assembly path
IntPtr pathPtr = WriteString(assemblyPath);
if (pathPtr == IntPtr.Zero) return false;
// Allocate status variable
IntPtr statusPtr = AllocateMemory(4);
if (statusPtr == IntPtr.Zero) return false;
// Open assembly
IntPtr assembly = ExecuteWithArgs(mono_assembly_open, pathPtr, statusPtr);
if (assembly == IntPtr.Zero) return false;
// Get image
IntPtr image = ExecuteWithArgs(mono_assembly_get_image, assembly);
if (image == IntPtr.Zero) return false;
// Write namespace and class names
IntPtr nsPtr = WriteString(namespaceName);
IntPtr classPtr = WriteString(className);
if (nsPtr == IntPtr.Zero || classPtr == IntPtr.Zero) return false;
// Get class
IntPtr klass = ExecuteWithArgs(mono_class_from_name, image, nsPtr, classPtr);
if (klass == IntPtr.Zero) return false;
// Write method name
IntPtr methodPtr = WriteString(methodName);
if (methodPtr == IntPtr.Zero) return false;
// Get method (0 args)
IntPtr method = ExecuteWithArgs(mono_class_get_method_from_name, klass, methodPtr, IntPtr.Zero);
if (method == IntPtr.Zero) return false;
// Invoke method
ExecuteWithArgs(mono_runtime_invoke, method, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
return true;
}
public void Dispose()
{
foreach (var addr in _allocations)
{
VirtualFreeEx(_handle, addr, IntPtr.Zero, MEM_RELEASE);
}
_allocations.Clear();
if (_handle != IntPtr.Zero)
{
CloseHandle(_handle);
_handle = IntPtr.Zero;
}
}
}
}