forked from mkaring/ConfuserEx
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathReferenceReplacer.cs
More file actions
450 lines (388 loc) · 15.7 KB
/
Copy pathReferenceReplacer.cs
File metadata and controls
450 lines (388 loc) · 15.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Confuser.Core;
using Confuser.Core.Helpers;
using Confuser.Core.Services;
using dnlib.DotNet;
using dnlib.DotNet.Emit;
namespace Confuser.Protections.Constants {
internal class ReferenceReplacer {
public static void ReplaceReference(CEContext ctx, ProtectionParameters parameters) {
foreach (var entry in ctx.ReferenceRepl) {
EnsureNoInlining(entry.Key);
if (parameters.GetParameter<bool>(ctx.Context, entry.Key, "cfg"))
ReplaceCFG(entry.Key, entry.Value, ctx);
else
ReplaceNormal(entry.Key, entry.Value);
}
}
static void ReplaceNormal(MethodDef method, List<Tuple<Instruction, uint, IMethod>> instrs) {
foreach (var instr in instrs) {
int i = method.Body.Instructions.IndexOf(instr.Item1);
instr.Item1.OpCode = OpCodes.Ldc_I4;
instr.Item1.Operand = (int)instr.Item2;
method.Body.Instructions.Insert(i + 1, Instruction.Create(OpCodes.Call, instr.Item3));
Instruction instr1 = method.Body.Instructions[i + 1];
method.Body.Instructions.Insert(i + 1, Instruction.Create(OpCodes.Br_S, instr1));
}
}
static void EnsureNoInlining(MethodDef method) {
method.ImplAttributes &= ~MethodImplAttributes.AggressiveInlining;
method.ImplAttributes |= MethodImplAttributes.NoInlining;
}
struct CFGContext {
public CEContext Ctx;
public ControlFlowGraph Graph;
public BlockKey[] Keys;
public RandomGenerator Random;
public Dictionary<uint, CFGState> StatesMap;
public Local StateVariable;
}
struct CFGState {
public uint A;
public uint B;
public uint C;
public uint D;
public CFGState(uint seed, uint mult) {
A = seed *= mult;
B = seed *= mult;
C = seed *= mult;
D = seed *= mult;
}
public void UpdateExplicit(int id, uint value) {
switch (id) {
case 0:
A = value;
break;
case 1:
B = value;
break;
case 2:
C = value;
break;
case 3:
D = value;
break;
}
}
public void UpdateIncremental(int id, uint value) {
switch (id) {
case 0:
A *= value;
break;
case 1:
B += value;
break;
case 2:
C ^= value;
break;
case 3:
D -= value;
break;
}
}
public uint GetIncrementalUpdate(int id, uint target) {
switch (id) {
case 0:
return A ^ target;
case 1:
return target - B;
case 2:
return C ^ target;
case 3:
return D - target;
}
throw new UnreachableException();
}
public uint Get(int id) {
switch (id) {
case 0:
return A;
case 1:
return B;
case 2:
return C;
case 3:
return D;
}
throw new UnreachableException();
}
public static byte EncodeFlag(bool exp, int updateId, int getId) {
byte fl = (byte)(exp ? 0x80 : 0);
fl |= (byte)updateId;
fl |= (byte)(getId << 2);
return fl;
}
}
static void InjectStateType(CEContext ctx) {
if (ctx.CfgCtxType == null) {
var type = ctx.Context.Registry.GetService<IRuntimeService>().GetRuntimeType("Confuser.Runtime.CFGCtx");
ctx.CfgCtxType = InjectHelper.Inject(type, ctx.Module);
ctx.Module.Types.Add(ctx.CfgCtxType);
ctx.CfgCtxCtor = ctx.CfgCtxType.FindMethod(".ctor");
ctx.CfgCtxNext = ctx.CfgCtxType.FindMethod("Next");
// Randomize the CFG state multiplier so the baked-in 0x21412321 literal
// no longer fingerprints the output. Must stay odd (invertible mod 2^32) and
// match the obfuscator-side CFGState computation (see CFGState.ctor).
ctx.CfgCtxMultiplier = ctx.Random.NextUInt32() | 1;
foreach (var instr in ctx.CfgCtxCtor.Body.Instructions) {
if (instr.OpCode == OpCodes.Ldc_I4 && (int)instr.Operand == 0x21412321)
instr.Operand = (int)ctx.CfgCtxMultiplier;
}
ctx.Name.MarkHelper(ctx.CfgCtxType, ctx.Marker, ctx.Protection);
foreach (var def in ctx.CfgCtxType.Fields)
ctx.Name.MarkHelper(def, ctx.Marker, ctx.Protection);
foreach (var def in ctx.CfgCtxType.Methods)
ctx.Name.MarkHelper(def, ctx.Marker, ctx.Protection);
}
}
static void InsertEmptyStateUpdate(CFGContext ctx, ControlFlowBlock block) {
var body = ctx.Graph.Body;
var key = ctx.Keys[block.Id];
if (key.EntryState == key.ExitState)
return;
Instruction first = null;
// Cannot use graph.IndexOf because instructions has been modified.
int targetIndex = body.Instructions.IndexOf(block.Header);
CFGState entry;
if (!ctx.StatesMap.TryGetValue(key.EntryState, out entry)) {
key.Type = BlockKeyType.Explicit;
}
if (key.Type == BlockKeyType.Incremental) {
// Incremental
CFGState exit;
if (!ctx.StatesMap.TryGetValue(key.ExitState, out exit)) {
// Create new exit state
// Update one of the entry states to be exit state
exit = entry;
int updateId = ctx.Random.NextInt32(3);
uint targetValue = ctx.Random.NextUInt32();
exit.UpdateExplicit(updateId, targetValue);
int getId = ctx.Random.NextInt32(3);
var fl = CFGState.EncodeFlag(false, updateId, getId);
var incr = entry.GetIncrementalUpdate(updateId, targetValue);
body.Instructions.Insert(targetIndex++, first = Instruction.Create(OpCodes.Ldloca, ctx.StateVariable));
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Ldc_I4_S, (sbyte)fl));
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Ldc_I4, (int)incr));
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Call, ctx.Ctx.CfgCtxNext));
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Pop));
ctx.StatesMap[key.ExitState] = exit;
}
else {
// Scan for updated state
var headerIndex = targetIndex;
for (int stateId = 0; stateId < 4; stateId++) {
if (entry.Get(stateId) == exit.Get(stateId))
continue;
uint targetValue = exit.Get(stateId);
int getId = ctx.Random.NextInt32(3);
var fl = CFGState.EncodeFlag(false, stateId, getId);
var incr = entry.GetIncrementalUpdate(stateId, targetValue);
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Ldloca, ctx.StateVariable));
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Ldc_I4_S, (sbyte)fl));
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Ldc_I4, (int)incr));
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Call, ctx.Ctx.CfgCtxNext));
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Pop));
}
first = body.Instructions[headerIndex];
}
}
else {
// Explicit
CFGState exit;
if (!ctx.StatesMap.TryGetValue(key.ExitState, out exit)) {
// Create new exit state from random seed
var seed = ctx.Random.NextUInt32();
exit = new CFGState(seed, ctx.Ctx.CfgCtxMultiplier);
body.Instructions.Insert(targetIndex++, first = Instruction.Create(OpCodes.Ldloca, ctx.StateVariable));
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Ldc_I4, (int)seed));
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Call, ctx.Ctx.CfgCtxCtor));
ctx.StatesMap[key.ExitState] = exit;
}
else {
// Scan for updated state
var headerIndex = targetIndex;
for (int stateId = 0; stateId < 4; stateId++) {
uint targetValue = exit.Get(stateId);
int getId = ctx.Random.NextInt32(3);
var fl = CFGState.EncodeFlag(true, stateId, getId);
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Ldloca, ctx.StateVariable));
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Ldc_I4_S, (sbyte)fl));
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Ldc_I4, (int)targetValue));
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Call, ctx.Ctx.CfgCtxNext));
body.Instructions.Insert(targetIndex++, Instruction.Create(OpCodes.Pop));
}
first = body.Instructions[headerIndex];
}
}
ctx.Graph.Body.ReplaceReference(block.Header, first);
}
static uint InsertStateGetAndUpdate(CFGContext ctx, ref int index, BlockKeyType type, ref CFGState currentState, CFGState? targetState) {
var body = ctx.Graph.Body;
if (type == BlockKeyType.Incremental) {
// Incremental
if (targetState == null) {
// Randomly update and get state
int updateId = ctx.Random.NextInt32(3);
uint targetValue = ctx.Random.NextUInt32();
int getId = ctx.Random.NextInt32(3);
var fl = CFGState.EncodeFlag(false, updateId, getId);
var incr = currentState.GetIncrementalUpdate(updateId, targetValue);
currentState.UpdateExplicit(updateId, targetValue);
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Ldloca, ctx.StateVariable));
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Ldc_I4_S, (sbyte)fl));
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Ldc_I4, (int)incr));
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Call, ctx.Ctx.CfgCtxNext));
return currentState.Get(getId);
}
// Scan for updated state
int[] stateIds = { 0, 1, 2, 3 };
ctx.Random.Shuffle(stateIds);
int i = 0;
uint getValue = 0;
foreach (var stateId in stateIds) {
// There must be at least one update&get
if (currentState.Get(stateId) == targetState.Value.Get(stateId) &&
i != stateIds.Length - 1) {
i++;
continue;
}
uint targetValue = targetState.Value.Get(stateId);
int getId = ctx.Random.NextInt32(3);
var fl = CFGState.EncodeFlag(false, stateId, getId);
var incr = currentState.GetIncrementalUpdate(stateId, targetValue);
currentState.UpdateExplicit(stateId, targetValue);
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Ldloca, ctx.StateVariable));
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Ldc_I4_S, (sbyte)fl));
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Ldc_I4, (int)incr));
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Call, ctx.Ctx.CfgCtxNext));
i++;
if (i == stateIds.Length)
getValue = currentState.Get(getId);
else
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Pop));
}
return getValue;
}
else {
// Explicit
if (targetState == null) {
// Create new exit state from random seed
var seed = ctx.Random.NextUInt32();
currentState = new CFGState(seed, ctx.Ctx.CfgCtxMultiplier);
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Ldloca, ctx.StateVariable));
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Dup));
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Ldc_I4, (int)seed));
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Call, ctx.Ctx.CfgCtxCtor));
// Randomly get state
int updateId = ctx.Random.NextInt32(3);
uint targetValue = ctx.Random.NextUInt32();
int getId = ctx.Random.NextInt32(3);
var fl = CFGState.EncodeFlag(false, updateId, getId);
var incr = currentState.GetIncrementalUpdate(updateId, targetValue);
currentState.UpdateExplicit(updateId, targetValue);
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Ldc_I4_S, (sbyte)fl));
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Ldc_I4, (int)incr));
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Call, ctx.Ctx.CfgCtxNext));
return currentState.Get(getId);
}
else {
// Scan for updated state
int[] stateIds = { 0, 1, 2, 3 };
ctx.Random.Shuffle(stateIds);
int i = 0;
uint getValue = 0;
foreach (var stateId in stateIds) {
uint targetValue = targetState.Value.Get(stateId);
int getId = ctx.Random.NextInt32(3);
var fl = CFGState.EncodeFlag(true, stateId, getId);
currentState.UpdateExplicit(stateId, targetValue);
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Ldloca, ctx.StateVariable));
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Ldc_I4_S, (sbyte)fl));
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Ldc_I4, (int)targetValue));
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Call, ctx.Ctx.CfgCtxNext));
i++;
if (i == stateIds.Length)
getValue = targetState.Value.Get(getId);
else
body.Instructions.Insert(index++, Instruction.Create(OpCodes.Pop));
}
return getValue;
}
}
}
static void ReplaceCFG(MethodDef method, List<Tuple<Instruction, uint, IMethod>> instrs, CEContext ctx) {
InjectStateType(ctx);
var graph = ControlFlowGraph.Construct(method.Body);
var sequence = KeySequence.ComputeKeys(graph, null);
var cfgCtx = new CFGContext {
Ctx = ctx,
Graph = graph,
Keys = sequence,
StatesMap = new Dictionary<uint, CFGState>(),
Random = ctx.Random
};
cfgCtx.StateVariable = new Local(ctx.CfgCtxType.ToTypeSig());
method.Body.Variables.Add(cfgCtx.StateVariable);
method.Body.InitLocals = true;
var blockReferences = new Dictionary<int, SortedList<int, Tuple<Instruction, uint, IMethod>>>();
foreach (var instr in instrs) {
var index = graph.IndexOf(instr.Item1);
var block = graph.GetContainingBlock(index);
SortedList<int, Tuple<Instruction, uint, IMethod>> list;
if (!blockReferences.TryGetValue(block.Id, out list))
list = blockReferences[block.Id] = new SortedList<int, Tuple<Instruction, uint, IMethod>>();
list.Add(index, instr);
}
// Update state for blocks not in use
for (int i = 0; i < graph.Count; i++) {
var block = graph[i];
if (blockReferences.ContainsKey(block.Id))
continue;
InsertEmptyStateUpdate(cfgCtx, block);
}
// Update references
foreach (var blockRef in blockReferences) {
var key = sequence[blockRef.Key];
CFGState currentState;
if (!cfgCtx.StatesMap.TryGetValue(key.EntryState, out currentState)) {
Debug.Assert((graph[blockRef.Key].Type & ControlFlowBlockType.Entry) != 0);
Debug.Assert(key.Type == BlockKeyType.Explicit);
// Create new entry state
uint blockSeed = ctx.Random.NextUInt32();
currentState = new CFGState(blockSeed, ctx.CfgCtxMultiplier);
cfgCtx.StatesMap[key.EntryState] = currentState;
var index = graph.Body.Instructions.IndexOf(graph[blockRef.Key].Header);
Instruction newHeader;
method.Body.Instructions.Insert(index++, newHeader = Instruction.Create(OpCodes.Ldloca, cfgCtx.StateVariable));
method.Body.Instructions.Insert(index++, Instruction.Create(OpCodes.Ldc_I4, (int)blockSeed));
method.Body.Instructions.Insert(index++, Instruction.Create(OpCodes.Call, ctx.CfgCtxCtor));
method.Body.ReplaceReference(graph[blockRef.Key].Header, newHeader);
key.Type = BlockKeyType.Incremental;
}
var type = key.Type;
for (int i = 0; i < blockRef.Value.Count; i++) {
var refEntry = blockRef.Value.Values[i];
CFGState? targetState = null;
if (i == blockRef.Value.Count - 1) {
CFGState exitState;
if (cfgCtx.StatesMap.TryGetValue(key.ExitState, out exitState))
targetState = exitState;
}
var index = graph.Body.Instructions.IndexOf(refEntry.Item1) + 1;
var value = InsertStateGetAndUpdate(cfgCtx, ref index, type, ref currentState, targetState);
refEntry.Item1.OpCode = OpCodes.Ldc_I4;
refEntry.Item1.Operand = (int)(refEntry.Item2 ^ value);
method.Body.Instructions.Insert(index++, Instruction.Create(OpCodes.Xor));
method.Body.Instructions.Insert(index, Instruction.Create(OpCodes.Call, refEntry.Item3));
if (i == blockRef.Value.Count - 1 && targetState == null) {
cfgCtx.StatesMap[key.ExitState] = currentState;
}
type = BlockKeyType.Incremental;
}
}
}
}
}