-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
106 lines (78 loc) · 3.02 KB
/
Program.cs
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
using AsmResolver.DotNet;
using AsmResolver.PE.DotNet.Cil;
using FractalAST.FASTBuilders.CIL;
using FractalAST.FASTBuilders.Expression;
using FractalAST.Nodes;
using FractalAST.Visitors;
using System.Diagnostics;
namespace FractalAST
{
internal class Program
{
static void Main(string[] args)
{
CreateASTFromCil();
CreateASTFromString();
}
private static void CreateASTFromString()
{
var root = "z / (y + y) - -(y + 1)".ToAST();
root.Validate();
var rootEval = root.Evaluate();
var clone = root.Clone();
var cloneEval = clone.Evaluate();
Debug.Assert(rootEval == cloneEval);
clone.Validate();
var vTest = new BasicLinearMBAVisitor();
clone.Accept(vTest);
var obfEval = clone.Evaluate();
// MUST be the same.
Debug.Assert(cloneEval == obfEval);
clone.Validate();
Console.WriteLine(clone);
}
private static void CreateASTFromCil()
{
ModuleDefinition mod = ModuleDefinition.FromModule(typeof(Program).Module);
var method = mod.GetAllTypes().First(x => x.Name == "Program").Methods.First(x => x.Name == "MathTest1");
method.CilMethodBody!.Instructions.ExpandMacros();
var instList = method.CilMethodBody!.Instructions.ToList();
var (root, unused, used) = instList.ToAST();
root.Validate();
var rootEval = root.Evaluate();
var clone = root.Clone();
var cloneEval = clone.Evaluate();
Debug.Assert(rootEval == cloneEval);
clone.Validate();
var vTest = new BasicLinearMBAVisitor();
clone.Accept(vTest);
var obfEval = clone.Evaluate();
// MUST be the same.
Debug.Assert(cloneEval == obfEval);
clone.Validate();
ReplaceInstructionsWithObfuscated(method, used, clone);
mod.Write("Example.dll");
Console.WriteLine(clone);
}
private static void ReplaceInstructionsWithObfuscated(MethodDefinition method, IEnumerable<CilInstruction> used, FASTNode clone)
{
var export = new CILExportVisitor();
clone.Accept(export);
var newInsts = export.OutputInstructions;
foreach (var usedInst in used)
{
usedInst.ReplaceWithNop();
}
var firstIndexOfNops = method.CilMethodBody!.Instructions.GetIndexByOffset(used.First().Offset);
method.CilMethodBody!.Instructions.InsertRange(firstIndexOfNops, newInsts);
method.CilMethodBody!.Instructions.CalculateOffsets();
method.CilMethodBody!.Instructions.OptimizeMacros();
}
public static int MathTest1(int x, int y, int z)
{
return z / (y + y) - -(y + 1);
//int i = 0;
//return i + 33 + (x * y) + z << 1;
}
}
}