dotscope 0.6.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
Documentation
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
//! ConfuserEx Anti-Tamper Protection Detection and Decryption
//!
//! This module provides detection and decryption for ConfuserEx's anti-tamper protection,
//! which encrypts method bodies to prevent tampering and static analysis.
//!
//! # Source Code Analysis
//!
//! Based on analysis of the ConfuserEx source code at:
//! - `Confuser.Protections/AntiTamper/AntiTamperProtection.cs` - Main protection entry point
//! - `Confuser.Runtime/AntiTamper.Normal.cs` - Normal mode runtime
//! - `Confuser.Runtime/AntiTamper.Anti.cs` - Anti mode runtime (with anti-debug)
//! - `Confuser.Runtime/AntiTamper.JIT.cs` - JIT mode runtime (hooks the JIT compiler)
//!
//! # Protection Modes
//!
//! ConfuserEx anti-tamper has three modes, selectable via the `mode` parameter:
//!
//! ## 1. Normal Mode (`Mode.Normal`)
//!
//! **Source:** `Confuser.Runtime/AntiTamper.Normal.cs` and `Confuser.Protections/AntiTamper/NormalMode.cs`
//!
//! **How it works:**
//! 1. Creates a custom PE section with obfuscated name (random `name1 * name2`)
//! 2. Moves **both** method bodies AND the Constants chunk to this section during compilation
//! 3. Encrypts the **entire** section contents using XOR with a derived key
//! 4. At runtime, decrypts the section in-place using `VirtualProtect` to make it writable
//!
//! **What gets encrypted (from NormalMode.cs `CreateSections()`):**
//! ```csharp
//! // Move Constants to encrypted section - includes FieldRVA data!
//! alignment = writer.TextSection.Remove(writer.Constants).Value;
//! newSection.Add(writer.Constants, alignment);
//!
//! // Move encrypted methods
//! var encryptedChunk = new MethodBodyChunks(writer.TheOptions.ShareMethodBodies);
//! newSection.Add(encryptedChunk, 4);
//! foreach (MethodDef method in methods) {
//!     if (!method.HasBody) continue;
//!     MethodBody body = writer.Metadata.GetMethodBody(method);
//!     writer.MethodBodies.Remove(body);
//!     encryptedChunk.Add(body);
//! }
//! ```
//!
//! **IMPORTANT:** The Constants section contains FieldRVA initialization data. When combined
//! with Constants protection (which stores encrypted data in a static field), the LZMA-compressed
//! constants data is also encrypted by anti-tamper. This requires decrypting **both** method
//! bodies AND FieldRVA data during deobfuscation.
//!
//! **Runtime signature:**
//! ```csharp
//! [DllImport("kernel32.dll")]
//! static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
//!
//! static unsafe void Initialize() {
//!     Module m = typeof(AntiTamperNormal).Module;
//!     var b = (byte*)Marshal.GetHINSTANCE(m);
//!     // ... PE parsing to find encrypted section ...
//!     VirtualProtect((IntPtr)e, l << 2, 0x40, out w);  // PAGE_EXECUTE_READWRITE
//!     // ... XOR decryption loop ...
//! }
//! ```
//!
//! **Detection criteria:**
//! - P/Invoke declaration for `VirtualProtect` from `kernel32.dll`
//! - Call to `Marshal.GetHINSTANCE(Module)`
//! - Call to `typeof(...).Module` or `get_Module` property
//! - Methods with encrypted bodies (RVA set but body unparseable)
//!
//! ## 2. Anti Mode (`Mode.Anti`)
//!
//! **Source:** `Confuser.Runtime/AntiTamper.Anti.cs`
//!
//! **How it works:**
//! Same as Normal mode, but with integrated anti-debug checks. The decryption
//! code is interleaved with debugger detection that calls `Environment.FailFast`
//! if a debugger is detected.
//!
//! **Runtime signature:**
//! ```csharp
//! [DllImport("kernel32.dll")]
//! static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
//!
//! [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
//! static extern bool CheckRemoteDebuggerPresent(IntPtr hProcess, ref bool isDebuggerPresent);
//!
//! static unsafe void Initialize() {
//!     // ... same PE parsing ...
//!     CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref isDebuggerPresent);
//!     if (isDebuggerPresent) Environment.FailFast(null);
//!     // ... more checks interspersed with decryption ...
//! }
//! ```
//!
//! **Detection criteria (in addition to Normal mode):**
//! - P/Invoke declaration for `CheckRemoteDebuggerPresent`
//! - Calls to `Process.GetCurrentProcess()`
//! - Calls to `Environment.FailFast`
//!
//! ## 3. JIT Mode (`Mode.JIT`)
//!
//! **Source:** `Confuser.Runtime/AntiTamper.JIT.cs`
//!
//! **How it works:**
//! Instead of decrypting at startup, this mode hooks the CLR's JIT compiler.
//! Method bodies remain encrypted until the moment they are JIT-compiled,
//! at which point they are decrypted on-demand.
//!
//! **Runtime signature:**
//! ```csharp
//! [DllImport("kernel32.dll")]
//! static extern IntPtr LoadLibrary(string lib);
//!
//! [DllImport("kernel32.dll")]
//! static extern IntPtr GetProcAddress(IntPtr lib, string proc);
//!
//! [DllImport("kernel32.dll")]
//! static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
//!
//! static void Hook() {
//!     IntPtr jit = LoadLibrary("clrjit.dll");  // or mscorjit.dll for older .NET
//!     var get = Marshal.GetDelegateForFunctionPointer(GetProcAddress(jit, "getJit"), typeof(getJit));
//!     // ... hooks the JIT compiler's compileMethod function ...
//! }
//! ```
//!
//! **Detection criteria:**
//! - P/Invoke declarations for `LoadLibrary` and `GetProcAddress`
//! - References to JIT-related strings ("clrjit.dll", "mscorjit.dll", "getJit")
//! - Complex hooking structures (delegate types, unsafe code patterns)
//!
//! # Injection Point
//!
//! For all modes, the anti-tamper initialization is injected at the **very beginning**
//! of `<Module>::.cctor` (the module's static constructor):
//!
//! ```csharp
//! // From NormalMode.cs line 92:
//! MethodDef cctor = context.CurrentModule.GlobalType.FindStaticConstructor();
//! cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, initMethod));
//! ```
//!
//! # Protection Preset
//!
//! Anti-tamper is part of the **Maximum** preset only:
//! ```csharp
//! // From AntiTamperProtection.cs line 37:
//! public override ProtectionPreset Preset {
//!     get { return ProtectionPreset.Maximum; }
//! }
//! ```
//!
//! # Decryption Strategy
//!
//! This module provides generic anti-tamper decryption by:
//! 1. Loading the PE file into emulator memory at `ImageBase`
//! 2. Leveraging BCL stubs (GetHINSTANCE, VirtualProtect, etc.) from the emulation runtime
//! 3. Emulating the anti-tamper initialization code which decrypts the section in-place
//! 4. Extracting decrypted method bodies from the virtual image
//! 5. Extracting decrypted FieldRVA data from the virtual image (Constants section)
//! 6. Rebuilding the assembly with decrypted data in the standard .text section
//!
//! This approach is fully generic - we don't hardcode encryption keys or algorithms.
//! Instead, we let the obfuscator's own decryption code do the work.
//!
//! **Why FieldRVA extraction is critical:**
//! When Constants protection is combined with Anti-Tamper, the LZMA-compressed
//! constant data (stored at a FieldRVA) is encrypted. Without extracting the
//! decrypted FieldRVA data, the Constants warmup phase receives encrypted data
//! instead of LZMA data, causing the LZMA hook to fail and the deobfuscation
//! to produce incorrect results or crash.
//!
//! # Test Samples
//!
//! | Sample | Has Anti-Tamper | Mode | Notes |
//! |--------|-----------------|------|-------|
//! | `original.exe` | No | N/A | Unprotected baseline |
//! | `mkaring_minimal.exe` | No | N/A | Minimal preset |
//! | `mkaring_normal.exe` | No | N/A | Normal preset (no anti-tamper) |
//! | `mkaring_maximum.exe` | Yes | Unknown | Maximum preset |

use std::sync::Arc;

use crate::{
    assembly::{opcodes, Operand},
    cilassembly::{CilAssembly, GeneratorConfig},
    compiler::{EventKind, EventLog},
    deobfuscation::{
        detection::{DetectionEvidence, DetectionScore},
        findings::DeobfuscationFindings,
        obfuscators::confuserex::{
            candidates::{find_candidates, ProtectionType},
            utils,
        },
    },
    emulation::{EmulationOutcome, ProcessBuilder, TracingConfig},
    error::Error,
    metadata::{
        tables::{FieldRvaRaw, MethodDefRaw, TableDataOwned, TableId},
        token::Token,
        validation::ValidationConfig,
    },
    CilObject, Result,
};

/// Detected anti-tamper mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AntiTamperMode {
    /// Normal mode: VirtualProtect-based decryption at startup.
    /// P/Invoke: VirtualProtect
    /// Signature: GetHINSTANCE + get_Module + VirtualProtect
    Normal,

    /// Anti mode: Normal + integrated anti-debug checks.
    /// P/Invoke: VirtualProtect, CheckRemoteDebuggerPresent
    /// Signature: Normal + CheckRemoteDebuggerPresent + FailFast
    Anti,

    /// JIT mode: Hooks the JIT compiler for on-demand decryption.
    /// P/Invoke: LoadLibrary, GetProcAddress, VirtualProtect
    /// Signature: LoadLibrary("clrjit.dll") + GetProcAddress("getJit")
    Jit,

    /// Unknown mode: Has encrypted methods but mode couldn't be determined.
    Unknown,
}

/// Result of anti-tamper detection for a single method.
#[derive(Debug, Clone)]
pub struct AntiTamperMethodInfo {
    /// The method token.
    pub token: Token,
    /// Detected anti-tamper mode (if determinable).
    pub mode: AntiTamperMode,
    /// Whether this method calls VirtualProtect.
    pub calls_virtualprotect: bool,
    /// Whether this method calls GetHINSTANCE.
    pub calls_gethinstance: bool,
    /// Whether this method calls get_Module.
    pub calls_get_module: bool,
    /// Whether this method calls CheckRemoteDebuggerPresent.
    pub calls_check_debugger: bool,
    /// Whether this method calls LoadLibrary.
    pub calls_loadlibrary: bool,
    /// Whether this method calls GetProcAddress.
    pub calls_getprocaddress: bool,
    /// Whether this method calls Environment.FailFast.
    pub calls_failfast: bool,
}

/// Result of anti-tamper detection.
#[derive(Debug, Default)]
pub struct AntiTamperDetectionResult {
    /// Methods detected as anti-tamper initialization.
    pub methods: Vec<AntiTamperMethodInfo>,
    /// Count of methods with encrypted bodies.
    pub encrypted_method_count: usize,
    /// Detected anti-tamper mode (most confident).
    pub detected_mode: Option<AntiTamperMode>,
    /// P/Invoke methods found (VirtualProtect, LoadLibrary, etc.)
    pub pinvoke_methods: Vec<Token>,
}

impl AntiTamperDetectionResult {
    /// Returns true if any anti-tamper protection was detected.
    pub fn is_detected(&self) -> bool {
        !self.methods.is_empty() || self.encrypted_method_count > 0
    }

    /// Returns the token of the best anti-tamper initialization method.
    ///
    /// Prefers methods that are NOT the module .cctor, as the .cctor just
    /// calls the actual initialization method.
    pub fn best_init_method(&self) -> Option<Token> {
        // First, try to find a non-.cctor method with strong indicators
        self.methods
            .iter()
            .filter(|m| {
                // Strong indicators: has at least 2 of the key calls
                let indicators = [
                    m.calls_virtualprotect,
                    m.calls_gethinstance,
                    m.calls_get_module,
                    m.calls_loadlibrary && m.calls_getprocaddress,
                ]
                .iter()
                .filter(|&&x| x)
                .count();
                indicators >= 2
            })
            .map(|m| m.token)
            .next()
            .or_else(|| self.methods.first().map(|m| m.token))
    }
}

/// Detects anti-tamper protection and populates findings.
///
/// This is the main detection entry point called by the orchestrator.
/// It detects:
/// - Anti-tamper initialization methods (VirtualProtect + GetHINSTANCE calls)
/// - Encrypted method bodies (methods with RVA but no parseable body)
/// - The specific anti-tamper mode being used
pub fn detect(assembly: &CilObject, score: &DetectionScore, findings: &mut DeobfuscationFindings) {
    let result = detect_antitamper(assembly);

    // Populate findings
    for method_info in &result.methods {
        findings.anti_tamper_methods.push(method_info.token);
    }
    findings.encrypted_method_count = result.encrypted_method_count;

    // Add detection evidence
    add_evidence(&result, score);
}

/// Detects anti-tamper protection in an assembly and returns detailed results.
///
/// This function scans for all three anti-tamper modes and identifies:
/// - Anti-tamper initialization methods
/// - The specific mode being used
/// - Encrypted method bodies
pub fn detect_antitamper(assembly: &CilObject) -> AntiTamperDetectionResult {
    let mut result = AntiTamperDetectionResult::default();

    // Detect encrypted method bodies
    result.encrypted_method_count = utils::find_encrypted_methods(assembly).len();

    // Detect P/Invoke methods for anti-tamper APIs
    result.pinvoke_methods = find_antitamper_pinvokes(assembly);

    // Detect anti-tamper initialization methods
    result.methods = find_antitamper_methods(assembly);

    // Determine the mode based on findings
    result.detected_mode = determine_mode(&result);

    result
}

/// Adds detection evidence to the score based on anti-tamper findings.
fn add_evidence(result: &AntiTamperDetectionResult, score: &DetectionScore) {
    // Add evidence for anti-tamper methods
    if !result.methods.is_empty() {
        let locations: boxcar::Vec<Token> = boxcar::Vec::new();
        for m in &result.methods {
            locations.push(m.token);
        }

        let mode_name = match result.detected_mode {
            Some(AntiTamperMode::Normal) => "Normal",
            Some(AntiTamperMode::Anti) => "Anti",
            Some(AntiTamperMode::Jit) => "JIT",
            Some(AntiTamperMode::Unknown) | None => "Unknown",
        };

        let confidence = (result.methods.len() * 25).min(50);
        score.add(DetectionEvidence::BytecodePattern {
            name: format!(
                "ConfuserEx anti-tamper ({} mode, {} methods)",
                mode_name,
                result.methods.len()
            ),
            locations,
            confidence,
        });
    }

    // Add evidence for encrypted method bodies
    if result.encrypted_method_count > 0 {
        let confidence = result.encrypted_method_count.min(50);
        score.add(DetectionEvidence::EncryptedMethodBodies {
            count: result.encrypted_method_count,
            confidence,
        });
    }

    // Add evidence for P/Invoke methods
    if !result.pinvoke_methods.is_empty() {
        let locations: boxcar::Vec<Token> = boxcar::Vec::new();
        for t in &result.pinvoke_methods {
            locations.push(*t);
        }

        score.add(DetectionEvidence::BytecodePattern {
            name: format!(
                "Anti-tamper P/Invoke methods ({} native calls)",
                result.pinvoke_methods.len()
            ),
            locations,
            confidence: 20,
        });
    }
}

/// Finds P/Invoke methods that are characteristic of anti-tamper protection.
///
/// Looks for:
/// - VirtualProtect (all modes)
/// - CheckRemoteDebuggerPresent (Anti mode)
/// - LoadLibrary, GetProcAddress (JIT mode)
///
/// Uses the actual import names from the ImplMap table, not the potentially
/// obfuscated method names.
fn find_antitamper_pinvokes(assembly: &CilObject) -> Vec<Token> {
    let mut pinvokes = Vec::new();

    let antitamper_apis = [
        "VirtualProtect",
        "CheckRemoteDebuggerPresent",
        "LoadLibrary",
        "LoadLibraryA",
        "LoadLibraryW",
        "GetProcAddress",
    ];

    // Build a map from MethodDef token to import name
    let import_map = utils::build_pinvoke_import_map(assembly);

    for method in &assembly.query_methods().native() {
        // Look up the actual import name (not the potentially obfuscated method name)
        let import_name = import_map.get(&method.token).map(String::as_str);

        // Check if the import name matches any anti-tamper API
        if let Some(name) = import_name {
            if antitamper_apis.contains(&name) {
                pinvokes.push(method.token);
            }
        }
    }

    pinvokes
}

/// Finds methods that appear to be anti-tamper initialization methods.
///
/// Detection is based on call patterns characteristic of each mode.
/// Uses the actual import names from ImplMap for P/Invoke methods,
/// not the potentially obfuscated method names.
fn find_antitamper_methods(assembly: &CilObject) -> Vec<AntiTamperMethodInfo> {
    let mut found = Vec::new();

    // Build import map once for all method analysis
    let import_map = utils::build_pinvoke_import_map(assembly);

    for method in &assembly.query_methods().has_body() {
        let Some(cfg) = method.cfg() else {
            continue;
        };

        // Track what this method calls
        let mut calls_virtualprotect = false;
        let mut calls_gethinstance = false;
        let mut calls_get_module = false;
        let mut calls_check_debugger = false;
        let mut calls_loadlibrary = false;
        let mut calls_getprocaddress = false;
        let mut calls_failfast = false;

        for node_id in cfg.node_ids() {
            let Some(block) = cfg.block(node_id) else {
                continue;
            };

            for instr in &block.instructions {
                if instr.opcode == opcodes::CALL || instr.opcode == opcodes::CALLVIRT {
                    if let Operand::Token(token) = &instr.operand {
                        if let Some(name) =
                            utils::resolve_call_target(assembly, *token, &import_map)
                        {
                            match name.as_str() {
                                "VirtualProtect" => calls_virtualprotect = true,
                                "GetHINSTANCE" => calls_gethinstance = true,
                                "get_Module" => calls_get_module = true,
                                "CheckRemoteDebuggerPresent" => calls_check_debugger = true,
                                "LoadLibrary" | "LoadLibraryA" | "LoadLibraryW" => {
                                    calls_loadlibrary = true;
                                }
                                "GetProcAddress" => calls_getprocaddress = true,
                                "FailFast" => calls_failfast = true,
                                _ => {}
                            }
                        }
                    }
                }
            }
        }

        // Determine if this looks like an anti-tamper method
        // Normal mode: GetHINSTANCE + get_Module + VirtualProtect
        // Anti mode: Normal + CheckRemoteDebuggerPresent
        // JIT mode: LoadLibrary + GetProcAddress (+ VirtualProtect typically)
        //
        // IMPORTANT: Constants protection also uses GetHINSTANCE + get_Module to read
        // encrypted data from the PE, but it does NOT call VirtualProtect (no need to
        // modify memory protection for reading). The key differentiator is VirtualProtect.

        let is_normal_mode = calls_gethinstance && calls_get_module && calls_virtualprotect;
        let is_anti_mode = is_normal_mode && calls_check_debugger;
        let is_jit_mode = calls_loadlibrary && calls_getprocaddress && calls_virtualprotect;

        if is_normal_mode || is_anti_mode || is_jit_mode {
            // All modes require VirtualProtect, so we can determine mode precisely
            let mode = if is_jit_mode {
                AntiTamperMode::Jit
            } else if is_anti_mode {
                AntiTamperMode::Anti
            } else {
                AntiTamperMode::Normal
            };

            found.push(AntiTamperMethodInfo {
                token: method.token,
                mode,
                calls_virtualprotect,
                calls_gethinstance,
                calls_get_module,
                calls_check_debugger,
                calls_loadlibrary,
                calls_getprocaddress,
                calls_failfast,
            });
        }
    }

    found
}

/// Determines the most likely anti-tamper mode based on detection results.
fn determine_mode(result: &AntiTamperDetectionResult) -> Option<AntiTamperMode> {
    if result.methods.is_empty() {
        return None;
    }

    // Count votes for each mode
    let mut normal_votes = 0;
    let mut anti_votes = 0;
    let mut jit_votes = 0;

    for method in &result.methods {
        match method.mode {
            AntiTamperMode::Normal => normal_votes += 1,
            AntiTamperMode::Anti => anti_votes += 1,
            AntiTamperMode::Jit => jit_votes += 1,
            AntiTamperMode::Unknown => {}
        }
    }

    // JIT mode is mutually exclusive with Normal/Anti
    if jit_votes > 0 {
        return Some(AntiTamperMode::Jit);
    }

    // Anti mode implies Normal mode detection too
    if anti_votes > 0 {
        return Some(AntiTamperMode::Anti);
    }

    if normal_votes > 0 {
        return Some(AntiTamperMode::Normal);
    }

    // If we have encrypted methods but couldn't determine mode
    if result.encrypted_method_count > 0 {
        return Some(AntiTamperMode::Unknown);
    }

    None
}

/// Finds all methods with non-zero RVAs.
///
/// This includes both methods with valid bodies and encrypted methods.
/// Used when we need to re-extract all method bodies to handle section layout changes.
fn find_all_methods_with_rva(assembly: &CilObject) -> Vec<Token> {
    assembly
        .methods()
        .iter()
        .filter_map(|entry| {
            let method = entry.value();
            if method.rva.is_some_and(|rva| rva > 0) {
                Some(method.token)
            } else {
                None
            }
        })
        .collect()
}

/// Result of extracting decrypted method bodies.
#[derive(Debug)]
struct ExtractedMethodBodies {
    /// Map of method token to decrypted body bytes.
    bodies: Vec<(Token, Vec<u8>)>,
    /// Number of methods that couldn't be extracted.
    failed_count: usize,
}

/// Extracts all decrypted method bodies from emulator memory.
///
/// For each encrypted method, reads and parses its body from the
/// decrypted virtual image.
fn extract_decrypted_bodies(
    assembly: &CilObject,
    virtual_image: &[u8],
    encrypted_methods: &[Token],
) -> ExtractedMethodBodies {
    let mut bodies = Vec::new();
    let mut failed_count = 0;

    for &token in encrypted_methods {
        let Some(rva) = utils::get_method_rva(assembly, token) else {
            failed_count += 1;
            continue;
        };

        if rva == 0 || rva as usize >= virtual_image.len() {
            failed_count += 1;
            continue;
        }

        match utils::extract_method_body_at_rva(virtual_image, rva) {
            Some(body_bytes) => {
                bodies.push((token, body_bytes));
            }
            None => {
                failed_count += 1;
            }
        }
    }

    ExtractedMethodBodies {
        bodies,
        failed_count,
    }
}

/// Result of extracting decrypted field data.
#[derive(Debug)]
struct ExtractedFieldData {
    /// Map of field RID to (original_rva, decrypted_data).
    fields: Vec<(u32, u32, Vec<u8>)>,
    /// Number of fields that couldn't be extracted.
    failed_count: usize,
}

/// Extracts decrypted FieldRVA data from emulator memory.
///
/// Anti-tamper encrypts not just method bodies but also the Constants section,
/// which includes FieldRVA data. This function extracts the decrypted field
/// initialization data from the virtual image.
fn extract_decrypted_field_data(assembly: &CilObject, virtual_image: &[u8]) -> ExtractedFieldData {
    let mut fields = Vec::new();
    let mut failed_count = 0;

    // Get FieldRVA table
    let Some(tables) = assembly.tables() else {
        return ExtractedFieldData {
            fields,
            failed_count,
        };
    };

    let Some(fieldrva_table) = tables.table::<FieldRvaRaw>() else {
        return ExtractedFieldData {
            fields,
            failed_count,
        };
    };

    for row in fieldrva_table {
        let rva = row.rva;
        if rva == 0 {
            continue;
        }

        // Get field size from ClassLayout table
        let Some(field_size) = utils::get_field_data_size(assembly, row.field) else {
            failed_count += 1;
            continue;
        };

        // Extract data from virtual image at the RVA
        let rva_usize = rva as usize;
        if rva_usize + field_size > virtual_image.len() {
            failed_count += 1;
            continue;
        }

        let data = virtual_image[rva_usize..rva_usize + field_size].to_vec();
        fields.push((row.rid, rva, data));
    }

    ExtractedFieldData {
        fields,
        failed_count,
    }
}

/// Result of anti-tamper emulation.
///
/// Contains the decrypted virtual image and metadata about the emulation.
#[derive(Debug)]
struct EmulationResult {
    /// The decrypted virtual image (PE loaded at ImageBase).
    virtual_image: Vec<u8>,
    /// Number of methods that were encrypted before decryption.
    encrypted_methods: Vec<Token>,
    /// The method token that performed decryption.
    decryptor_method: Token,
    /// Number of instructions executed during emulation.
    instructions_executed: u64,
}

/// Decrypts anti-tamper protected method bodies and returns a new assembly.
///
/// This function uses the CilAssembly modification API to rebuild method bodies
/// in the normal .text section rather than keeping them in the encrypted section.
/// This results in a cleaner output that can be further analyzed or executed.
///
/// # Process
///
/// 1. Emulates the anti-tamper initialization to decrypt method bodies in memory
/// 2. Extracts decrypted method bodies from the virtual image
/// 3. Creates a CilAssembly and stores each body via the modification API
/// 4. Updates MethodDef RVAs to point to the new locations
/// 5. Writes the assembly with bodies in the standard .text section
///
/// # Arguments
///
/// * `assembly` - The anti-tamper protected assembly.
/// * `events` - Event log for recording deobfuscation activity.
/// * `tracing` - Optional tracing configuration for emulation debugging.
///
/// # Returns
///
/// A new [`CilObject`] with decrypted method bodies in the .text section.
///
/// # Errors
///
/// Returns an error if emulation, extraction, or assembly writing fails.
pub fn decrypt_bodies(
    assembly: CilObject,
    events: &mut EventLog,
    tracing: Option<TracingConfig>,
) -> Result<CilObject> {
    let assembly_arc = Arc::new(assembly);

    // Step 1: Emulate anti-tamper to get decrypted virtual image
    let emulation_result = emulate_antitamper(&assembly_arc, tracing)?;

    // Log emulation completion
    events.info(format!(
        "Anti-tamper emulation completed: {} instructions executed via method 0x{:08x}",
        emulation_result.instructions_executed,
        emulation_result.decryptor_method.value()
    ));

    // Step 2: Find ALL methods with RVAs (not just encrypted ones)
    // This is necessary because the assembly writer may change section layout,
    // which would invalidate existing RVAs. By extracting ALL method bodies
    // from the decrypted virtual image, we ensure all RVAs get updated correctly.
    let all_methods_with_rva = find_all_methods_with_rva(&assembly_arc);

    // Step 3: Extract ALL method bodies from virtual image
    let extracted = extract_decrypted_bodies(
        &assembly_arc,
        &emulation_result.virtual_image,
        &all_methods_with_rva,
    );

    if extracted.bodies.is_empty() {
        return Err(Error::Deobfuscation(
            "No method bodies could be extracted from decrypted image".to_string(),
        ));
    }

    // Log warning if some extractions failed
    if extracted.failed_count > 0 {
        events.warn(format!(
            "Failed to extract {} method bodies from decrypted image",
            extracted.failed_count
        ));
    }

    // Log each decrypted method body
    let encrypted_count = emulation_result.encrypted_methods.len();
    for &token in &emulation_result.encrypted_methods {
        events
            .record(EventKind::MethodBodyDecrypted)
            .method(token)
            .message(format!("Decrypted method body 0x{:08x}", token.value()));
    }

    // Step 4: Create CilAssembly from original PE bytes
    let mut cil_assembly = CilAssembly::from_bytes_with_validation(
        assembly_arc.file().data().to_vec(),
        ValidationConfig::analysis(),
    )?;

    // Step 5: Store each body and update MethodDef RVAs
    for (method_token, body_bytes) in extracted.bodies {
        // Store the method body - returns a placeholder RVA
        let placeholder_rva = cil_assembly.store_method_body(body_bytes);

        // Get the existing MethodDef row
        let rid = method_token.row();
        #[allow(clippy::redundant_closure_for_method_calls)]
        // Note: closure needed here — method reference with turbofish breaks downstream type inference
        let existing_row = cil_assembly
            .view()
            .tables()
            .and_then(|t| t.table::<MethodDefRaw>())
            .and_then(|table| table.get(rid))
            .ok_or_else(|| Error::Deobfuscation(format!("MethodDef row {rid} not found")))?;

        // Create updated row with new RVA
        let updated_row = MethodDefRaw {
            rid: existing_row.rid,
            token: existing_row.token,
            offset: existing_row.offset,
            rva: placeholder_rva,
            impl_flags: existing_row.impl_flags,
            flags: existing_row.flags,
            name: existing_row.name,
            signature: existing_row.signature,
            param_list: existing_row.param_list,
        };

        // Update the MethodDef row
        cil_assembly.table_row_update(
            TableId::MethodDef,
            rid,
            TableDataOwned::MethodDef(updated_row),
        )?;
    }

    // Step 5b: Extract and store decrypted FieldRVA data
    // Anti-tamper also encrypts the Constants section which contains FieldRVA data
    let extracted_fields =
        extract_decrypted_field_data(&assembly_arc, &emulation_result.virtual_image);

    let field_count = extracted_fields.fields.len();
    if extracted_fields.failed_count > 0 {
        events.warn(format!(
            "Failed to extract {} field data entries from decrypted image",
            extracted_fields.failed_count
        ));
    }

    // Store decrypted field data and update FieldRVA rows
    for (rid, _original_rva, data) in extracted_fields.fields {
        // Store the field data - returns a placeholder RVA
        let placeholder_rva = cil_assembly.store_field_data(data);

        // Get the existing FieldRVA row
        #[allow(clippy::redundant_closure_for_method_calls)]
        // Note: closure needed here — method reference with turbofish breaks downstream type inference
        let existing_row = cil_assembly
            .view()
            .tables()
            .and_then(|t| t.table::<FieldRvaRaw>())
            .and_then(|table| table.get(rid))
            .ok_or_else(|| Error::Deobfuscation(format!("FieldRVA row {rid} not found")))?;

        // Create updated row with new RVA
        let updated_row = FieldRvaRaw {
            rid: existing_row.rid,
            token: existing_row.token,
            offset: existing_row.offset,
            rva: placeholder_rva,
            field: existing_row.field,
        };

        // Update the FieldRVA row
        cil_assembly.table_row_update(
            TableId::FieldRVA,
            rid,
            TableDataOwned::FieldRVA(updated_row),
        )?;
    }

    // Log anti-tamper removal summary
    events.record(EventKind::AntiTamperRemoved).message(
        format!("Anti-tamper protection removed: {encrypted_count} method bodies, {field_count} field data entries decrypted")
    );

    // Step 6: Write the modified assembly and reload
    // Use skip_original_method_bodies because we've decrypted and stored ALL method bodies
    // from the virtual image - the original encrypted bodies are no longer needed
    let config = GeneratorConfig::default().with_skip_original_method_bodies(true);
    cil_assembly.into_cilobject_with(ValidationConfig::analysis(), config)
}

/// Emulates anti-tamper decryption and returns the decrypted virtual image.
///
/// This function:
/// 1. Loads the PE into emulator memory at ImageBase
/// 2. Finds the anti-tamper initialization method
/// 3. Emulates it with stubbed GetHINSTANCE/VirtualProtect
/// 4. Returns the decrypted virtual image from memory
///
/// The virtual image is the PE loaded at ImageBase with sections at their
/// virtual addresses - this is where the decrypted method bodies reside.
///
/// # Arguments
///
/// * `assembly` - The anti-tamper protected assembly.
/// * `pe_bytes` - The raw PE file bytes.
///
/// # Returns
///
/// An [`EmulationResult`] containing the decrypted virtual image and metadata.
///
/// # Errors
///
/// Returns an error if:
/// - No anti-tamper method is found
/// - Emulation fails
/// - Memory extraction fails
fn emulate_antitamper(
    assembly: &Arc<CilObject>,
    tracing: Option<TracingConfig>,
) -> Result<EmulationResult> {
    // Use scored candidate detection to find the best anti-tamper initialization method
    let candidates = find_candidates(assembly, ProtectionType::AntiTamper);
    let decryptor_method = candidates.best().map(|c| c.token).ok_or_else(|| {
        Error::Deobfuscation("No anti-tamper initialization method found".to_string())
    })?;

    // Find encrypted methods before decryption
    let encrypted_methods = utils::find_encrypted_methods(assembly);

    // Build the emulation process using ProcessBuilder.
    // ProcessBuilder automatically maps the assembly's PE image when .assembly_arc() is used.
    // All required stubs (GetHINSTANCE, VirtualProtect, VirtualAlloc, reflection, IntPtr, etc.)
    // are automatically registered by the emulation runtime.
    let mut builder = ProcessBuilder::new()
        .assembly_arc(Arc::clone(assembly))
        .name("anti-tamper-emulation")
        .with_max_instructions(10_000_000)
        .with_max_call_depth(200)
        .with_timeout_ms(120_000); // 2 minutes - anti-tamper can be slow

    // Add tracing if configured, with anti-tamper context prefix
    if let Some(mut tracing_config) = tracing {
        tracing_config.context_prefix = Some("anti-tamper".to_string());
        builder = builder.with_tracing(tracing_config);
    }

    let process = builder.build()?;

    // Get the loaded image info for extracting decrypted data later
    let loaded_image = process
        .primary_image()
        .ok_or_else(|| Error::Deobfuscation("Failed to get loaded PE image info".to_string()))?;
    let pe_base = loaded_image.base_address;
    #[allow(clippy::cast_possible_truncation)]
    let virtual_size = loaded_image.size_of_image as usize;

    let outcome = process.execute_method(decryptor_method, vec![])?;
    let instructions_executed = match outcome {
        EmulationOutcome::Completed { instructions, .. }
        | EmulationOutcome::Breakpoint { instructions, .. } => instructions,
        EmulationOutcome::LimitReached { limit, .. } => {
            return Err(Error::Deobfuscation(format!(
                "Anti-tamper emulation exceeded limit: {limit:?}"
            )));
        }
        EmulationOutcome::Stopped { reason, .. } => {
            return Err(Error::Deobfuscation(format!(
                "Anti-tamper emulation stopped: {reason}"
            )));
        }
        EmulationOutcome::UnhandledException { exception, .. } => {
            return Err(Error::Deobfuscation(format!(
                "Anti-tamper emulation threw exception: {exception:?}"
            )));
        }
        EmulationOutcome::RequiresSymbolic { reason, .. } => {
            return Err(Error::Deobfuscation(format!(
                "Anti-tamper emulation requires symbolic execution: {reason}"
            )));
        }
    };

    // Extract the decrypted virtual image from memory
    let virtual_image = process.read_memory(pe_base, virtual_size)?;

    Ok(EmulationResult {
        virtual_image,
        encrypted_methods,
        decryptor_method,
        instructions_executed,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::deobfuscation::obfuscators::confuserex::utils::find_encrypted_methods;

    const SAMPLES_DIR: &str = "tests/samples/packers/confuserex";

    /// Test that the original (unprotected) sample has no anti-tamper.
    #[test]
    fn test_original_no_antitamper() -> crate::Result<()> {
        let path = format!("{}/original.exe", SAMPLES_DIR);
        let assembly = CilObject::from_path_with_validation(&path, ValidationConfig::analysis())?;

        let result = detect_antitamper(&assembly);

        assert!(
            result.methods.is_empty(),
            "Original should have no anti-tamper methods"
        );
        assert_eq!(
            result.encrypted_method_count, 0,
            "Original should have no encrypted methods"
        );
        assert!(
            result.pinvoke_methods.is_empty(),
            "Original should have no anti-tamper P/Invoke"
        );
        assert!(!result.is_detected());

        Ok(())
    }

    /// Test that the normal preset sample has no anti-tamper.
    #[test]
    fn test_normal_no_antitamper() -> crate::Result<()> {
        let path = format!("{}/mkaring_normal.exe", SAMPLES_DIR);
        let assembly = CilObject::from_path_with_validation(&path, ValidationConfig::analysis())?;

        let result = detect_antitamper(&assembly);

        // Normal preset should NOT have anti-tamper (it's Maximum only)
        assert_eq!(
            result.encrypted_method_count, 0,
            "Normal preset should have no encrypted methods"
        );

        Ok(())
    }

    /// Test that the standalone antitamper sample has anti-tamper protection.
    #[test]
    fn test_antitamper_sample_detection() -> crate::Result<()> {
        let path = format!("{}/mkaring_antitamper.exe", SAMPLES_DIR);
        let assembly = CilObject::from_path_with_validation(&path, ValidationConfig::analysis())?;

        let result = detect_antitamper(&assembly);

        assert!(
            result.encrypted_method_count > 0,
            "Antitamper sample should have encrypted methods, found {}",
            result.encrypted_method_count
        );
        assert!(result.is_detected(), "Anti-tamper should be detected");
        assert!(
            result.best_init_method().is_some(),
            "Should identify an anti-tamper initialization method"
        );

        Ok(())
    }

    /// Test that the standalone antitamper sample can be decrypted.
    #[test]
    fn test_antitamper_sample_decryption() -> crate::Result<()> {
        let path = format!("{}/mkaring_antitamper.exe", SAMPLES_DIR);
        let assembly = CilObject::from_path_with_validation(&path, ValidationConfig::analysis())?;

        // Get encrypted methods before decryption
        let encrypted_before = find_encrypted_methods(&assembly);
        assert!(
            !encrypted_before.is_empty(),
            "Should have encrypted methods before decryption"
        );

        // Decrypt the assembly
        let mut events = EventLog::new();
        let decrypted = decrypt_bodies(assembly, &mut events, None)?;

        // Verify no encrypted methods remain
        let encrypted_after = find_encrypted_methods(&decrypted);
        assert!(
            encrypted_after.is_empty(),
            "Should have no encrypted methods after decryption, found {}",
            encrypted_after.len()
        );

        // Verify decrypted methods have valid IL bodies
        for token in &encrypted_before {
            let method = decrypted.method(token);
            assert!(
                method.is_some(),
                "Method 0x{:08X} should exist",
                token.value()
            );
            let method = method.unwrap();
            let body = method.body.get();
            assert!(
                body.is_some(),
                "Decrypted method 0x{:08X} should have a body",
                token.value()
            );
        }

        Ok(())
    }

    /// Test that the maximum preset sample has anti-tamper protection.
    #[test]
    fn test_maximum_detection() -> crate::Result<()> {
        let path = format!("{}/mkaring_maximum.exe", SAMPLES_DIR);
        let assembly = CilObject::from_path_with_validation(&path, ValidationConfig::analysis())?;

        let result = detect_antitamper(&assembly);

        assert!(
            result.encrypted_method_count > 0,
            "Maximum should have encrypted methods, found {}",
            result.encrypted_method_count
        );
        assert!(result.is_detected(), "Anti-tamper should be detected");
        assert!(
            result.best_init_method().is_some(),
            "Should identify an anti-tamper initialization method"
        );

        Ok(())
    }

    /// Test that the maximum preset sample can be decrypted.
    #[test]
    #[cfg(not(feature = "skip-expensive-tests"))]
    fn test_maximum_decryption() -> crate::Result<()> {
        let path = format!("{}/mkaring_maximum.exe", SAMPLES_DIR);
        let assembly = CilObject::from_path_with_validation(&path, ValidationConfig::analysis())?;

        // Get encrypted methods before decryption
        let encrypted_before = find_encrypted_methods(&assembly);
        assert!(
            !encrypted_before.is_empty(),
            "Should have encrypted methods before decryption"
        );

        // Decrypt the assembly
        let mut events = EventLog::new();
        let decrypted = decrypt_bodies(assembly, &mut events, None)?;

        // Verify no encrypted methods remain
        let encrypted_after = find_encrypted_methods(&decrypted);
        assert!(
            encrypted_after.is_empty(),
            "Should have no encrypted methods after decryption, found {}",
            encrypted_after.len()
        );

        // Verify decrypted methods have valid IL bodies
        for token in &encrypted_before {
            let method = decrypted.method(token);
            assert!(
                method.is_some(),
                "Method 0x{:08X} should exist",
                token.value()
            );
            let method = method.unwrap();
            let body = method.body.get();
            assert!(
                body.is_some(),
                "Decrypted method 0x{:08X} should have a body",
                token.value()
            );
        }

        Ok(())
    }
}