-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.cs
More file actions
611 lines (535 loc) · 24.7 KB
/
Utils.cs
File metadata and controls
611 lines (535 loc) · 24.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
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
using System;
using System.Reflection;
using AsmResolver;
using AsmResolver.DotNet;
using AsmResolver.DotNet.Code.Cil;
using AsmResolver.PE.DotNet.Cil;
public class DeGremlin
{
private readonly ModuleDefinition module;
private readonly int token;
private readonly Assembly assembly;
private static readonly CilOpCode[] ConvOvfOpCodes = new[]
{
CilOpCodes.Conv_Ovf_I1,
CilOpCodes.Conv_Ovf_I2,
CilOpCodes.Conv_Ovf_I4,
CilOpCodes.Conv_Ovf_I8,
CilOpCodes.Conv_Ovf_U1,
CilOpCodes.Conv_Ovf_U2,
CilOpCodes.Conv_Ovf_U4,
CilOpCodes.Conv_Ovf_U8,
CilOpCodes.Conv_Ovf_I,
CilOpCodes.Conv_Ovf_U
};
public DeGremlin(Assembly _assembly, ModuleDefinition _module, int _token)
{
module = _module;
token = _token;
assembly = _assembly;
}
public void Process()
{
for (int i = 0; i < 10; i++)
{
removeSizeof();
removeEmptyType();
removeChecked();
//transformStoI4();
removeAdd();
removeMul();
removeSub();
removeXOR();
decryptStrings();
}
}
// method to get previous non-NOP instruction
private CilInstruction GetPrevNonNop(CilInstructionCollection instructions, int startIndex, out int foundIndex)
{
foundIndex = -1;
for (int i = startIndex - 1; i >= 0; i--)
{
if (instructions[i].OpCode != CilOpCodes.Nop)
{
foundIndex = i;
return instructions[i];
}
}
return null;
}
private bool getIntegerOperand(CilInstruction inst, out int value)
{
value = 0;
// Handle ldc.i4 variants
if (inst.OpCode == CilOpCodes.Ldc_I4)
value = (int)inst.Operand;
else if (inst.OpCode == CilOpCodes.Ldc_I4_S)
value = (int)(sbyte)inst.Operand;
else if (inst.OpCode == CilOpCodes.Ldc_I4_0)
value = 0;
else if (inst.OpCode == CilOpCodes.Ldc_I4_1)
value = 1;
else if (inst.OpCode == CilOpCodes.Ldc_I4_2)
value = 2;
else if (inst.OpCode == CilOpCodes.Ldc_I4_3)
value = 3;
else if (inst.OpCode == CilOpCodes.Ldc_I4_4)
value = 4;
else if (inst.OpCode == CilOpCodes.Ldc_I4_5)
value = 5;
else if (inst.OpCode == CilOpCodes.Ldc_I4_6)
value = 6;
else if (inst.OpCode == CilOpCodes.Ldc_I4_7)
value = 7;
else if (inst.OpCode == CilOpCodes.Ldc_I4_8)
value = 8;
else if (inst.OpCode == CilOpCodes.Ldc_I4_M1)
value = -1;
// Handle ldc.i8 (int64) - may truncate
else if (inst.OpCode == CilOpCodes.Ldc_I8)
{
long longValue = (long)inst.Operand;
value = (int)longValue; // Truncates if value is outside int32 range
}
// Handle ldc.r4 (float) - converts to int
else if (inst.OpCode == CilOpCodes.Ldc_R4)
{
float floatValue = (float)inst.Operand;
value = (int)floatValue; // Truncates decimal part
}
// Handle ldc.r8 (double) - converts to int
else if (inst.OpCode == CilOpCodes.Ldc_R8)
{
double doubleValue = (double)inst.Operand;
value = (int)doubleValue; // Truncates decimal part
}
else
return false;
return true;
}
private void decryptStrings()
{
foreach (var type in module.GetAllTypes())
{
foreach (var method in type.Methods)
{
if (method.HasMethodBody && method.CilMethodBody is { } body)
{
var instructions = body.Instructions;
for (int i = instructions.Count - 1; i > 0; i--)
{
var instruction = instructions[i];
if (instruction.OpCode == CilOpCodes.Call)
{
if (instruction.Operand is IMethodDescriptor calledMethod && token == calledMethod.MetadataToken)
{
var index = body.Instructions.IndexOf(instruction);
List<int> arguments = new List<int>();
List<int> indices = new List<int>();
int argsFound = 0;
int pointer = index - 1;
while (pointer >= 0 && argsFound < 3)
{
var current_inst = body.Instructions[pointer];
if (current_inst.OpCode == CilOpCodes.Nop)
{
pointer--;
continue;
}
if (current_inst.OpCode.Mnemonic.StartsWith("conv."))
{
pointer--;
current_inst.ReplaceWithNop();
continue;
}
if (!current_inst.OpCode.Mnemonic.StartsWith("ldc."))
{
break;
}
arguments.Insert(0, Convert.ToInt32(current_inst.Operand));
indices.Insert(0, pointer);
argsFound++;
pointer--;
}
while (pointer >= 0 && body.Instructions[pointer].OpCode == CilOpCodes.Nop)
{
pointer--;
}
if (arguments.Count == 3)
{
var originalInstructions = indices.ToDictionary(
idx => idx,
idx => new {
OpCode = body.Instructions[idx].OpCode,
Operand = body.Instructions[idx].Operand
});
var originalCallOpCode = instruction.OpCode;
var originalCallOperand = instruction.Operand;
try
{
object[] argsArray = arguments.Select(x => (object)x).ToArray();
string decryptedString = MethodInvoker.InvokeMethod(assembly, token, argsArray);
//Console.WriteLine(decryptedString);
try
{
body.Instructions[indices[0]].ReplaceWithNop();
body.Instructions[indices[1]].ReplaceWithNop();
body.Instructions[indices[2]].ReplaceWithNop();
instruction.OpCode = CilOpCodes.Ldstr;
instruction.Operand = decryptedString;
body.ComputeMaxStack();
//Console.WriteLine($"->{body.Instructions[pointer].OpCode}");
}
catch (Exception ex)
{
//Console.WriteLine("Exception during instruction modification");
foreach (var idx in indices)
{
if (originalInstructions.TryGetValue(idx, out var original))
{
body.Instructions[idx].OpCode = original.OpCode;
body.Instructions[idx].Operand = original.Operand;
}
}
instruction.OpCode = originalCallOpCode;
instruction.Operand = originalCallOperand;
continue;
}
}
catch (Exception ex)
{
//Console.WriteLine("Exception during decryption");
continue;
}
}
}
}
}
}
}
}
}
private void removeXOR()
{
foreach (var type in module.GetAllTypes())
{
foreach (var method in type.Methods)
{
//Console.WriteLine($"{method.Name} : {method.MetadataToken}");
if (method.HasMethodBody)
{
if (method.CilMethodBody is { } body)
{
foreach (var instruction in body.Instructions)
{
if (instruction.OpCode == CilOpCodes.Xor)
{
try
{
var index = body.Instructions.IndexOf(instruction);
int idx1, idx2;
var prev_inst = GetPrevNonNop(body.Instructions, index, out idx1);
var prev_inst2 = GetPrevNonNop(body.Instructions, idx1, out idx2);
if (prev_inst == null || prev_inst2 == null)
continue;
int val1, val2;
if (!getIntegerOperand(prev_inst, out val1) || !getIntegerOperand(prev_inst2, out val2))
continue;
int xor = val1 ^ val2;
body.Instructions[idx1].ReplaceWithNop();
body.Instructions[idx2].ReplaceWithNop();
instruction.ReplaceWith(CilOpCodes.Ldc_I4, (int)xor);
//Console.WriteLine(prev_inst);
}
catch (Exception ex) { continue; }
}
//Console.WriteLine($"0x{Convert.ToString(instruction.Offset, 16)}");
}
}
}
}
}
}
private void removeAdd()
{
foreach (var type in module.GetAllTypes())
{
foreach (var method in type.Methods)
{
//Console.WriteLine($"{method.Name} : {method.MetadataToken}");
if (method.HasMethodBody)
{
if (method.CilMethodBody is { } body)
{
foreach (var instruction in body.Instructions)
{
// current_inst.OpCode.Mnemonic.StartsWith("ldc.")
if (instruction.OpCode == CilOpCodes.Add ||
instruction.OpCode == CilOpCodes.Add_Ovf ||
instruction.OpCode == CilOpCodes.Add_Ovf_Un)
{
try
{
var index = body.Instructions.IndexOf(instruction);
int idx1, idx2;
var prev_inst = GetPrevNonNop(body.Instructions, index, out idx1);
var prev_inst2 = GetPrevNonNop(body.Instructions, idx1, out idx2);
if (prev_inst == null || prev_inst2 == null)
continue;
int val1, val2;
if (!getIntegerOperand(prev_inst, out val1) || !getIntegerOperand(prev_inst2, out val2))
continue;
int sum = val1 + val2;
body.Instructions[idx1].ReplaceWithNop();
body.Instructions[idx2].ReplaceWithNop();
instruction.ReplaceWith(CilOpCodes.Ldc_I4, (int)sum);
//Console.WriteLine(prev_inst);
}
catch (Exception ex) { continue; }
}
//Console.WriteLine($"0x{Convert.ToString(instruction.Offset, 16)}");
}
}
}
}
}
}
private void removeMul()
{
foreach (var type in module.GetAllTypes())
{
foreach (var method in type.Methods)
{
//Console.WriteLine($"{method.Name} : {method.MetadataToken}");
if (method.HasMethodBody)
{
if (method.CilMethodBody is { } body)
{
foreach (var instruction in body.Instructions)
{
// current_inst.OpCode.Mnemonic.StartsWith("ldc.")
if (instruction.OpCode == CilOpCodes.Mul ||
instruction.OpCode == CilOpCodes.Mul_Ovf ||
instruction.OpCode == CilOpCodes.Mul_Ovf_Un)
{
try
{
var index = body.Instructions.IndexOf(instruction);
int idx1, idx2;
var prev_inst = GetPrevNonNop(body.Instructions, index, out idx1);
var prev_inst2 = GetPrevNonNop(body.Instructions, idx1, out idx2);
if (prev_inst == null || prev_inst2 == null)
continue;
int val1, val2;
if (!getIntegerOperand(prev_inst, out val1) || !getIntegerOperand(prev_inst2, out val2))
continue;
int mul = val1 * val2;
body.Instructions[idx1].ReplaceWithNop();
body.Instructions[idx2].ReplaceWithNop();
instruction.ReplaceWith(CilOpCodes.Ldc_I4, (int)mul);
//Console.WriteLine(prev_inst);
}
catch (Exception ex) { continue; }
}
//Console.WriteLine($"0x{Convert.ToString(instruction.Offset, 16)}");
}
}
}
}
}
}
private void removeSub()
{
foreach (var type in module.GetAllTypes())
{
foreach (var method in type.Methods)
{
//Console.WriteLine($"{method.Name} : {method.MetadataToken}");
if (method.HasMethodBody)
{
if (method.CilMethodBody is { } body)
{
foreach (var instruction in body.Instructions)
{
// current_inst.OpCode.Mnemonic.StartsWith("ldc.")
if (instruction.OpCode == CilOpCodes.Sub ||
instruction.OpCode == CilOpCodes.Sub_Ovf ||
instruction.OpCode == CilOpCodes.Sub_Ovf_Un)
{
try
{
var index = body.Instructions.IndexOf(instruction);
int idx1, idx2;
var prev_inst = GetPrevNonNop(body.Instructions, index, out idx1);
var prev_inst2 = GetPrevNonNop(body.Instructions, idx1, out idx2);
if (prev_inst == null || prev_inst2 == null)
continue;
int val1, val2;
if (!getIntegerOperand(prev_inst, out val1) || !getIntegerOperand(prev_inst2, out val2))
continue;
int diff = val2 - val1;
body.Instructions[idx1].ReplaceWithNop();
body.Instructions[idx2].ReplaceWithNop();
instruction.ReplaceWith(CilOpCodes.Ldc_I4, (int)diff);
//Console.WriteLine(prev_inst);
}
catch (Exception ex) { continue; }
}
//Console.WriteLine($"0x{Convert.ToString(instruction.Offset, 16)}");
}
}
}
}
}
}
private void removeChecked()
{
foreach (var type in module.GetAllTypes())
{
foreach (var method in type.Methods)
{
//Console.WriteLine($"{method.Name} : {method.MetadataToken}");
if (method.HasMethodBody)
{
if (method.CilMethodBody is { } body)
{
foreach (var instruction in body.Instructions)
{
if (Array.Exists(ConvOvfOpCodes, op => op == instruction.OpCode))
{
instruction.ReplaceWithNop();
// not needed to check previous instruction for this operation
}
//Console.WriteLine($"0x{Convert.ToString(instruction.Offset, 16)}");
}
}
}
}
}
}
private void removeEmptyType()
{
foreach (var type in module.GetAllTypes())
{
foreach (var method in type.Methods)
{
//Console.WriteLine($"{method.Name} : {method.MetadataToken}");
if (method.HasMethodBody)
{
if (method.CilMethodBody is { } body)
{
foreach (var instruction in body.Instructions)
{
// Deobfuscating System.Type::EmptyTypes
if (instruction.OpCode == CilOpCodes.Ldlen)
{
var index = body.Instructions.IndexOf(instruction);
int prevIdx;
var previous_inst = GetPrevNonNop(body.Instructions, index, out prevIdx);
if (previous_inst == null)
continue;
if (previous_inst.Operand is AsmResolver.DotNet.IFieldDescriptor field
&& field.Name == "EmptyTypes"
&& field.DeclaringType?.FullName == "System.Type")
{
//Console.WriteLine(previous_inst);
instruction.ReplaceWith(CilOpCodes.Ldc_I4, 0);
body.Instructions[prevIdx].ReplaceWithNop();
body.ComputeMaxStack(true);
}
}
}
}
}
}
}
}
private void removeSizeof()
{
foreach (var type in module.GetAllTypes())
{
foreach (var method in type.Methods)
{
//Console.WriteLine($"{method.Name} : {method.MetadataToken}");
if (method.HasMethodBody)
{
if (method.CilMethodBody is { } body)
{
foreach (var instruction in body.Instructions)
{
if (instruction.OpCode == CilOpCodes.Sizeof)
{
// Deobfuscating sizeof()
if (instruction.Operand is AsmResolver.DotNet.TypeReference typeRef && typeRef.Namespace == "System")
{
instruction.OpCode = CilOpCodes.Ldc_I4;
int size = -1;
switch (typeRef.Name)
{
case "Guid":
size = 16;
break;
case "Int64":
size = 8;
break;
case "Int32":
size = 4;
break;
case "UInt64":
size = 8;
break;
case "UInt32":
size = 4;
break;
case "Byte":
size = 1;
break;
case "Double":
size = 8;
break;
case "Single":
size = 4;
break;
case "Int16":
size = 2;
break;
case "UInt16":
size = 2;
break;
default:
//Console.WriteLine(instruction.Operand);
break;
}
if (size > 0)
{
instruction.ReplaceWith(CilOpCodes.Ldc_I4, (int)size);
}
}
}
}
}
}
}
}
}
}
public static class MethodInvoker
{
public static string InvokeMethod(Assembly assembly, int token, params object[] args)
{
var method_ = assembly.ManifestModule.ResolveMethod(token) as MethodInfo;
if (method_ == null)
throw new InvalidOperationException("Method not found");
// Verify the signature matches what we expect
if (!method_.IsStatic ||
method_.ReturnType != typeof(string) ||
method_.GetParameters().Length != 3 ||
method_.GetParameters().All(p => p.ParameterType != typeof(int)))
{
throw new InvalidOperationException("Method signature mismatch");
}
// Invoke with the specified parameters
string result = (string)method_.Invoke(null, args);
return result;
}
}