-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
524 lines (430 loc) · 20.6 KB
/
Program.cs
File metadata and controls
524 lines (430 loc) · 20.6 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using System;
using System.IO;
using System.Linq;
using System.Text;
using CommandLine;
namespace NetFuscator
{
public class Options
{
[Option('f', "file", Required = true, HelpText = "Path to the assembly you want to obfuscate.")]
public string file { get; set; }
[Option('r', "resources", Required = false, HelpText = "(OPTIONAL) Path to a directory containing text files you want to use to adjust the assembly's entropy.")]
public string resources { get; set; }
[Option('n', "names", Required = false, HelpText = "(OPTIONAL) What you want the assembly's name to be. Defaults to a random eight-character string.")]
public string assemblyName { get; set; }
}
public class Program
{
// --------------------------------------------------------------------------
// Helpers
// --------------------------------------------------------------------------
private static readonly Random Rng = new Random();
private static string RandomName(int length = 8)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var sb = new StringBuilder(length);
// Always start with a letter so the identifier is always valid IL
for (int i = 0; i < length; i++)
sb.Append(chars[Rng.Next(chars.Length)]);
return sb.ToString();
}
// --------------------------------------------------------------------------
// Namespace / class renaming
// --------------------------------------------------------------------------
// Maps each distinct original namespace to a single randomly-generated
// replacement so every type that used to live in the same namespace still
// does after renaming. Without this, each type would get its own unique
// random namespace and dnSpy would show one namespace per type.
private static readonly System.Collections.Generic.Dictionary<string, string> _namespaceMap
= new System.Collections.Generic.Dictionary<string, string>(StringComparer.Ordinal);
private static void ObfuscateNamespace(TypeDefinition type)
{
var original = type.Namespace ?? string.Empty;
if (original.Length == 0) return; // global namespace — leave alone
if (!_namespaceMap.TryGetValue(original, out var replacement))
{
replacement = RandomName();
_namespaceMap[original] = replacement;
}
type.Namespace = replacement;
}
private static void ObfuscateClass(TypeDefinition type)
{
if (!type.IsClass) return;
// Generic type names need to preserve the `N arity suffix (e.g., MyClass`1 for one type parameter). Without it, the metadata is malformed.
if (type.HasGenericParameters)
{
type.Name = RandomName() + "`" + type.GenericParameters.Count;
return;
}
type.Name = RandomName();
}
// --------------------------------------------------------------------------
// Method renaming
// --------------------------------------------------------------------------
private static void ObfuscateMethods(TypeDefinition type, string entrypoint_namespace)
{
foreach (var method in type.Methods)
{
// Constructors must keep their names (.ctor / .cctor)
if (method.IsConstructor) continue;
// Skip special-named methods (get_X, set_X, add_X, op_X …)
if (method.IsSpecialName || method.IsRuntimeSpecialName) continue;
// Entry point must stay named Main
if (method.Name == "Main") continue;
// Virtual methods override a slot defined by a base class or interface.
// Renaming them breaks the vtable contract.
if (method.IsVirtual) continue;
// Explicit interface implementations are also linked by name+signature
// even when not marked virtual in the usual sense.
if (method.Overrides.Count > 0) continue;
// P/Invoke: the method name IS the native entry point unless
// EntryPoint was set explicitly in [DllImport]
if (method.IsPInvokeImpl) continue;
// TODO: figure out how to handle renames of methods with generic paramaters (references aren't being updated properly)
if (method.HasGenericParameters || method.DeclaringType.HasGenericParameters) continue;
method.Name = RandomName();
}
}
// --------------------------------------------------------------------------
// Field / parameter renaming
// --------------------------------------------------------------------------
private static void ObfuscateVariables(TypeDefinition type)
{
// Enum value names are used by reflection — don't touch them
if (type.IsEnum) return;
// Fields (aka variables)
foreach (var field in type.Fields)
{
if (field.IsSpecialName) continue;
if (field.Name == "value__") continue; // enum backing field
field.Name = RandomName();
}
// Method parameters
foreach (var method in type.Methods)
{
if (!method.HasBody) continue;
foreach (var param in method.Parameters)
param.Name = RandomName();
}
// Note: local variables have no names in IL (only in PDB debug info), so there's nothing to rename here.
// Note: nested types are NOT renamed here. ProcessType recurses into them
}
// --------------------------------------------------------------------------
// String literal obfuscation
// --------------------------------------------------------------------------
// The injected decoder method — created once per module before processing starts.
private static MethodDefinition _stringDecoderMethod;
private static void CreateStringDecoderMethod(ModuleDefinition module)
{
// Insert into dedicated non-generic type — can never collide with anonymous/generic types
var decoderType = new TypeDefinition(
"",
RandomName(),
TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Abstract,
module.ImportReference(typeof(object)));
module.Types.Add(decoderType);
var method = new MethodDefinition(
RandomName(),
MethodAttributes.Assembly | MethodAttributes.Static,
module.TypeSystem.String);
method.Parameters.Add(
new ParameterDefinition("s", ParameterAttributes.None, module.TypeSystem.String));
var il = method.Body.GetILProcessor();
// Build: new string(s.ToCharArray().Reverse())
// Using ImportReference so Cecil emits correct assembly refs
var toCharArray = module.ImportReference(typeof(string).GetMethod("ToCharArray", Type.EmptyTypes));
var arrayReverse = module.ImportReference(typeof(Array).GetMethod("Reverse", new[] { typeof(Array) }));
var stringCtorArr = module.ImportReference(typeof(string).GetConstructor(new[] { typeof(char[]) }));
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, toCharArray);
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Call, arrayReverse);
il.Emit(OpCodes.Newobj, stringCtorArr);
il.Emit(OpCodes.Ret);
decoderType.Methods.Add(method);
_stringDecoderMethod = method;
}
private static void ObfuscateStrings(TypeDefinition type)
{
foreach (var method in type.Methods)
{
if (!method.HasBody) continue;
method.Body.SimplifyMacros();
var il = method.Body.GetILProcessor();
foreach (var instr in method.Body.Instructions.ToList())
{
if (instr.OpCode != OpCodes.Ldstr) continue;
var original = (string)instr.Operand;
if (string.IsNullOrEmpty(original)) continue;
instr.Operand = new string(original.Reverse().ToArray());
var call = il.Create(OpCodes.Call, _stringDecoderMethod);
il.InsertAfter(instr, call);
}
method.Body.OptimizeMacros();
}
}
// --------------------------------------------------------------------------
// Per-type entry point
// --------------------------------------------------------------------------
private static void ProcessType(TypeDefinition type, string entrypoint_namespace)
{
// Recurse into nested types first
foreach (TypeDefinition nested in type.NestedTypes)
{
ProcessType(nested, entrypoint_namespace);
}
// Skip compiler-generated types
if (type.IsSpecialName || type.Name.StartsWith("<"))
{
return;
}
var root = type;
while (root.DeclaringType != null)
{
root = root.DeclaringType;
}
if (root.Namespace == null || !root.Namespace.StartsWith(entrypoint_namespace))
{
return;
}
Console.WriteLine($"Obfuscating: {type.FullName}");
ObfuscateMethods(type, entrypoint_namespace);
ObfuscateVariables(type);
ObfuscateNamespace(type);
ObfuscateClass(type);
ObfuscateStrings(type);
}
private static void RenameNamespacePrefix(ModuleDefinition module, string oldPrefix, string newPrefix)
{
// 1. Embedded resource streams
foreach (var r in module.Resources)
{
if (r.Name.StartsWith(oldPrefix + "."))
r.Name = newPrefix + r.Name.Substring(oldPrefix.Length);
}
// 2. ldstr literals in EVERY method, including [CompilerGenerated] types
// (this is where the Resources.ResourceManager ctor string lives)
foreach (var type in module.GetTypes())
{
foreach (var method in type.Methods)
{
if (!method.HasBody) continue;
foreach (var instr in method.Body.Instructions)
{
if (instr.OpCode == OpCodes.Ldstr
&& instr.Operand is string s
&& s.StartsWith(oldPrefix + "."))
{
instr.Operand = newPrefix + s.Substring(oldPrefix.Length);
}
}
}
}
// 3. Namespace field on the types themselves (cosmetic, but keeps things tidy)
foreach (var type in module.GetTypes())
{
if (type.Namespace == oldPrefix || type.Namespace.StartsWith(oldPrefix + "."))
type.Namespace = newPrefix + type.Namespace.Substring(oldPrefix.Length);
}
}
// --------------------------------------------------------------------------
// Entropy measurement and adjustment
// --------------------------------------------------------------------------
private const double EntropyMin = 4.5;
private const double EntropyMax = 5.5;
private const int MaxEmbedAttempts = 500; // safety cap
private static double ComputeShannonEntropy(byte[] data)
{
if (data == null || data.Length == 0) return 0.0;
var counts = new long[256];
foreach (var b in data) counts[b]++;
double entropy = 0.0;
double length = data.Length;
for (int i = 0; i < 256; i++)
{
if (counts[i] == 0) continue;
double p = counts[i] / length;
entropy -= p * Math.Log(p, 2);
}
return entropy;
}
private static double MeasureAssemblyEntropy(AssemblyDefinition assembly)
{
using (var ms = new System.IO.MemoryStream())
{
assembly.Write(ms);
return ComputeShannonEntropy(ms.ToArray());
}
}
private static void AdjustEntropyWithResources(AssemblyDefinition assembly, string resourceDir)
{
var module = assembly.MainModule;
// Queue of candidate text files. Shuffle so repeated runs don't produce
// identical embedded resource sets.
var candidates = System.IO.Directory
.EnumerateFiles(resourceDir, "*.txt", System.IO.SearchOption.AllDirectories)
.OrderBy(_ => Rng.Next())
.ToList();
if (candidates.Count == 0)
{
Console.Error.WriteLine($"Warning: no .txt files in '{resourceDir}' — skipping entropy adjustment.");
return;
}
int attempts = 0;
int candidateIndex = 0;
while (attempts < MaxEmbedAttempts)
{
double entropy = MeasureAssemblyEntropy(assembly);
Console.WriteLine($" entropy = {entropy:F4} (target {EntropyMin}–{EntropyMax})");
if (entropy >= EntropyMin && entropy <= EntropyMax)
{
Console.WriteLine(" entropy in target range.");
return;
}
if (candidateIndex >= candidates.Count)
{
Console.Error.WriteLine(" ran out of candidate files before reaching target entropy.");
return;
}
string file = candidates[candidateIndex++];
byte[] bytes;
try
{
bytes = System.IO.File.ReadAllBytes(file);
}
catch (Exception ex)
{
Console.Error.WriteLine($" could not read {file}: {ex.Message}");
continue;
}
string resourceName;
do
{
resourceName = Guid.NewGuid().ToString("N");
} while (module.Resources.Any(r => r.Name == resourceName));
var embedded = new EmbeddedResource(resourceName, ManifestResourceAttributes.Private, bytes);
module.Resources.Add(embedded);
Console.WriteLine($" embedded {System.IO.Path.GetFileName(file)} as '{resourceName}' ({bytes.Length} bytes)");
attempts++;
}
Console.Error.WriteLine(" hit MaxEmbedAttempts cap without converging.");
}
// --------------------------------------------------------------------------
// Assembly-level metadata scrubbing
// --------------------------------------------------------------------------
private static readonly string[] IdentityAttributesToStrip =
{
"AssemblyTitleAttribute",
"AssemblyDescriptionAttribute",
"AssemblyConfigurationAttribute",
"AssemblyCompanyAttribute",
"AssemblyProductAttribute",
"AssemblyCopyrightAttribute",
"AssemblyTrademarkAttribute",
"AssemblyCultureAttribute",
"AssemblyInformationalVersionAttribute",
};
private static void ScrubAssemblyMetadata(AssemblyDefinition assembly, string newName)
{
var module = assembly.MainModule;
// Logical identity in the manifest
assembly.Name.Name = newName;
// PE-level module filename (what ildasm/dnSpy show as the module entry)
module.Name = newName + (module.Kind == ModuleKind.Dll ? ".dll" : ".exe");
// Module Version ID — a fresh GUID baked into the PE header
module.Mvid = Guid.NewGuid();
// Replace the [assembly: Guid("...")] typelib GUID blob with a new one.
// Leaving the attribute present (rather than stripping it) preserves COM
// interop surface area when the original assembly exposed types to COM.
foreach (var attr in assembly.CustomAttributes)
{
if (attr.AttributeType.Name == "GuidAttribute" &&
attr.ConstructorArguments.Count == 1 &&
attr.ConstructorArguments[0].Type.FullName == "System.String")
{
attr.ConstructorArguments[0] = new CustomAttributeArgument(
module.TypeSystem.String, Guid.NewGuid().ToString());
}
}
// Strip identity-leaking attributes (title, company, copyright, etc.).
// Version attributes are kept so the manifest version stays coherent.
for (int i = assembly.CustomAttributes.Count - 1; i >= 0; i--)
{
if (IdentityAttributesToStrip.Contains(assembly.CustomAttributes[i].AttributeType.Name))
assembly.CustomAttributes.RemoveAt(i);
}
}
// --------------------------------------------------------------------------
// Entry point
// --------------------------------------------------------------------------
public static void Main(string[] args)
{
string inputPath = null;
string resourcesPath = null;
string newAssemblyName = null;
Parser.Default.ParseArguments<Options>(args)
.WithParsed(o =>
{
inputPath = o.file;
resourcesPath = o.resources;
newAssemblyName = o.assemblyName;
})
.WithNotParsed(o =>
{
Environment.Exit(1);
});
if (!File.Exists(inputPath))
{
Console.Error.WriteLine($"Error: file '{inputPath}' not found.");
Environment.Exit(1);
}
if (resourcesPath != null && !Directory.Exists(resourcesPath))
{
Console.Error.WriteLine($"Error: directory '{inputPath}' not found.");
Environment.Exit(1);
}
try
{
var readerParams = new ReaderParameters { ReadWrite = false, InMemory = true };
var assembly = AssemblyDefinition.ReadAssembly(inputPath, readerParams);
var module = assembly.MainModule;
// Scrub assembly-level metadata (name, Mvid, GUID, identity attrs).
if (newAssemblyName == null)
{
newAssemblyName = RandomName();
}
ScrubAssemblyMetadata(assembly, newAssemblyName);
string outputPath = newAssemblyName +
(module.Kind == ModuleKind.Dll ? ".dll" : ".exe");
// Create the decoder helper once, before any type processing
CreateStringDecoderMethod(module);
string newPropertiesPrefix = RandomName() + ".Properties";
string existingPropertiesPrefix = module.EntryPoint.DeclaringType.Namespace.Split('.')[0];
RenameNamespacePrefix(module, $"{existingPropertiesPrefix}.Properties", newPropertiesPrefix);
string entrypoint_namespace = module.EntryPoint.DeclaringType.Namespace;
CustomAttributeHelper.BuildTypeMap(module);
foreach (TypeDefinition type in module.Types)
{
ProcessType(type, entrypoint_namespace);
}
CustomAttributeHelper.FixCustomAttributeTypeReferences(module);
if (resourcesPath != null)
{
AdjustEntropyWithResources(assembly, resourcesPath);
}
assembly.Write(Path.Combine(Directory.GetCurrentDirectory(), outputPath));
Console.WriteLine($"Obfuscated: {inputPath} -> {outputPath}");
Console.WriteLine("Done.");
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
}
}
}