-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
68 lines (55 loc) · 2.03 KB
/
Copy pathProgram.cs
File metadata and controls
68 lines (55 loc) · 2.03 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
using MemoryModule;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
var suffix = Environment.Is64BitProcess ? "64" : "";
using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream($"MemoryModulePP{suffix}.dll");
using var memoryModulePP = NativeAssembly.Load(stream);
var LdrLoadDllMemoryExW = memoryModulePP.GetDelegate<LdrLoadDllMemoryExWDelegate>("LdrLoadDllMemoryExW");
var LdrUnloadDllMemory = memoryModulePP.GetDelegate<LdrUnloadDllMemoryDelegate>("LdrUnloadDllMemory");
using var secretStream = Assembly.GetExecutingAssembly().GetManifestResourceStream($"Secret{suffix}.dll")!;
using var secretMs = new MemoryStream();
secretStream.CopyTo(secretMs);
var secretBytes = secretMs.ToArray();
const uint LOAD_FLAGS_PASS_IMAGE_CHECK = 0x40000000;
LdrLoadDllMemoryExW(
out IntPtr secretHandle,
out _,
// MemoryModulePP has a weird check that will somehow fail for our binaries.
LOAD_FLAGS_PASS_IMAGE_CHECK,
secretBytes,
// This misleading parameter must always be 0.
0,
"secret",
null
);
NativeLibrary.SetDllImportResolver(Assembly.GetExecutingAssembly(),
(name, asm, path) =>
{
if (name == "secret")
{
return secretHandle;
}
return IntPtr.Zero;
});
for (int i = 0; i < 10; ++i)
{
[DllImport("secret")]
static extern int GetSecret();
int result = GetSecret();
Console.WriteLine(result);
Debug.Assert(Math.Clamp(result, 0, 100) == result);
}
LdrUnloadDllMemory(secretHandle);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate int LdrLoadDllMemoryExWDelegate(
[Out] out IntPtr BaseAddress,
[Out] out IntPtr LdrEntry,
[In] uint dwFlags,
[In][MarshalAs(UnmanagedType.LPArray)] byte[] BufferAddress,
[In] UIntPtr BufferSize,
[In][MarshalAs(UnmanagedType.LPWStr)] string? DllName,
[In][MarshalAs(UnmanagedType.LPWStr)] string? DllFullName
);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate bool LdrUnloadDllMemoryDelegate([In] IntPtr BaseAddress);