dotscope 0.7.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
//! Call indirection detection via SSA analysis.
//!
//! Detects two categories of call indirection:
//!
//! ## Delegate Proxies
//!
//! Delegate-based call indirection where every method call is hidden behind a
//! delegate proxy class. Each proxy class:
//!
//! 1. Inherits from `System.MulticastDelegate`
//! 2. Has a static singleton field of its own type
//! 3. Has a static wrapper method that takes `N+1` args (last is the delegate)
//!    and internally `callvirt`s the delegate's `Invoke()`
//!
//! Creates a [`DelegateProxyResolutionPass`] with pre-computed findings from
//! detection, which emulates delegate `.cctor`s and resolves target methods.
//!
//! ## Reflection Call Indirection
//!
//! Reflection-based call indirection where direct calls are hidden behind
//! `Module.ResolveMethod`, `Type.GetMethod`, `MethodInfo.Invoke`,
//! `Activator.CreateInstance`, or `FieldInfo.GetValue/SetValue`.
//!
//! Produces [`ReflectionFindings`] consumed by the engine-owned
//! [`ReflectionDevirtualizationPass`](crate::deobfuscation::passes::ReflectionDevirtualizationPass).
//!
//! ## Detection
//!
//! Detection uses `detect_ssa()` to:
//! 1. Pre-scan assembly types for delegate types with static fields
//! 2. Verify wrapper methods via their SSA structure
//! 3. Scan SSA functions for delegate proxy and reflection call patterns

use std::{
    any::Any,
    collections::{HashMap, HashSet},
    sync::Arc,
};

use log::debug;

use crate::{
    analysis::{SsaFunction, SsaOp, SsaVarId},
    cilassembly::CleanupRequest,
    compiler::{PassPhase, SsaPass},
    deobfuscation::{
        context::AnalysisContext,
        passes::{
            count_resolve_method_calli_sites, DelegateProxyResolutionPass, DelegateTypeInfo,
            ReflectionDevirtualizationPass,
        },
        techniques::{Detection, Evidence, Technique, TechniqueCategory},
        utils::is_method_named,
    },
    metadata::token::Token,
    CilObject,
};

/// Findings from delegate proxy detection.
#[derive(Debug)]
pub struct DelegateProxyFindings {
    /// delegate_type_token → singleton field + wrapper method info.
    pub delegate_types: HashMap<Token, DelegateTypeInfo>,
    /// Method tokens containing at least one delegate proxy call.
    pub affected_methods: HashSet<Token>,
}

/// Findings from reflection call indirection detection.
#[derive(Debug, Default)]
pub struct ReflectionFindings {
    /// Method tokens containing reflection call sites.
    pub affected_methods: HashSet<Token>,
    /// Total number of reflection sites detected.
    pub site_count: usize,
}

/// Combined findings from delegate proxy AND reflection detection.
///
/// `GenericDelegateProxy::detect_ssa()` produces this because both analyses
/// share the same SSA scanning pass. The engine extracts [`ReflectionFindings`]
/// to create [`ReflectionDevirtualizationPass`](crate::deobfuscation::passes::ReflectionDevirtualizationPass);
/// the technique uses [`DelegateProxyFindings`] for [`DelegateProxyResolutionPass`].
#[derive(Debug)]
pub struct CallIndirectionFindings {
    /// Delegate proxy detection results.
    pub delegate: DelegateProxyFindings,
    /// Reflection call indirection results.
    pub reflection: ReflectionFindings,
}

/// Traces a variable backwards through def-use chains to check if it
/// originates from a method argument.
///
/// Checks the variable's `VariableOrigin` directly (O(1) for argument vars),
/// and follows `Copy` and single-input `Phi` nodes for indirect references.
/// Limits traversal depth to prevent infinite loops.
fn traces_to_argument(ssa: &SsaFunction, var: SsaVarId) -> bool {
    let mut current = var;
    for _ in 0..20 {
        // Check the variable's origin — if it's an argument, we're done
        if let Some(variable) = ssa.variable(current) {
            if variable.origin().is_argument() {
                return true;
            }
        }

        // Check if defined by an instruction (Copy, LoadArg, etc.)
        if let Some(op) = ssa.get_definition(current) {
            match op {
                SsaOp::LoadArg { .. } => return true,
                SsaOp::Copy { src, .. } => {
                    current = *src;
                    continue;
                }
                _ => return false,
            }
        }

        // Check if defined by a phi node
        if let Some((_block_idx, phi)) = ssa.find_phi_defining(current) {
            let operands = phi.operands();
            if operands.len() == 1 {
                current = operands[0].value();
                continue;
            }
            return false;
        }

        return false;
    }
    false
}

/// Checks if a method's SSA matches the delegate wrapper pattern.
///
/// A wrapper method contains a `CallVirt` to an `Invoke` method where the
/// object (first arg) traces back to a `LoadArg`, meaning it receives the
/// delegate as a parameter and calls its `Invoke`. This is checked purely
/// via SSA def-use chains, making it immune to junk code insertions.
fn is_delegate_wrapper_ssa(ssa: &SsaFunction, assembly: &CilObject) -> bool {
    for block in ssa.blocks() {
        for instr in block.instructions() {
            let SsaOp::CallVirt { method, args, .. } = instr.op() else {
                continue;
            };

            // Check if the target method is "Invoke" on a delegate type
            let Some(method_name) = assembly.resolve_method_name(method.token()) else {
                continue;
            };
            if method_name != "Invoke" {
                continue;
            }

            // The first arg of CallVirt is the object (delegate instance).
            // It must trace back to a method argument — meaning the wrapper
            // receives the delegate as a parameter and calls its Invoke.
            let Some(&obj_var) = args.first() else {
                continue;
            };
            if traces_to_argument(ssa, obj_var) {
                return true;
            }
        }
    }
    false
}

/// Scans an SSA function for calls to known delegate wrapper methods.
///
/// Returns `true` if at least one `Call` instruction references a wrapper
/// method from the pre-computed set.
fn has_delegate_proxy_calls(ssa: &SsaFunction, wrapper_methods: &HashMap<Token, Token>) -> bool {
    for block in ssa.blocks() {
        for instr in block.instructions() {
            if let SsaOp::Call { method, .. } = instr.op() {
                if wrapper_methods.contains_key(&method.token()) {
                    return true;
                }
            }
        }
    }
    false
}

/// Detects delegate proxy call indirection via SSA analysis.
///
/// Identifies delegate types used as call proxies and the methods affected
/// by this pattern. Creates a [`DelegateProxyResolutionPass`] to resolve
/// indirect calls to their actual targets via emulation.
pub struct GenericDelegateProxy;

impl Technique for GenericDelegateProxy {
    fn id(&self) -> &'static str {
        "generic.delegates"
    }

    fn name(&self) -> &'static str {
        "Delegate Proxy Resolution"
    }

    fn category(&self) -> TechniqueCategory {
        TechniqueCategory::Call
    }

    fn detect(&self, _assembly: &CilObject) -> Detection {
        // IL-level detection is not used — all detection happens in detect_ssa()
        // where we can follow exact def-use chains and verify wrapper patterns.
        Detection::new_empty()
    }

    fn detect_ssa(&self, ctx: &AnalysisContext, assembly: &CilObject) -> Detection {
        // Phase 1: Find delegate proxy types by scanning all types.
        //
        // A delegate proxy type:
        // - Inherits from System.MulticastDelegate (is_delegate())
        // - Has at least one static field (the singleton instance)
        // - Has a static wrapper method whose SSA contains CallVirt(Invoke)
        //   where the delegate object comes from a LoadArg parameter
        let mut delegate_types: HashMap<Token, DelegateTypeInfo> = HashMap::new();
        let mut wrapper_to_delegate: HashMap<Token, Token> = HashMap::new();

        let mut delegate_count = 0usize;
        let mut has_static_field = 0usize;
        let mut has_static_method = 0usize;
        let mut has_ssa = 0usize;
        let mut is_wrapper = 0usize;

        for type_entry in assembly.types().iter() {
            let ty = type_entry.value();
            if !ty.is_delegate() {
                continue;
            }
            delegate_count += 1;

            // Find the singleton static field. Delegate types normally have no
            // static fields, so any static field is the singleton instance.
            let Some(singleton_field_token) = ty
                .fields
                .iter()
                .find(|(_, f)| f.flags.is_static())
                .map(|(_, f)| f.token)
            else {
                continue;
            };
            has_static_field += 1;

            // Find the wrapper method: static (not .cctor/.ctor), whose SSA
            // shows a CallVirt(Invoke) pattern with the delegate from a parameter.
            let wrapper_method_token = ty.methods.iter().find_map(|(_, method_ref)| {
                let method = method_ref.upgrade()?;
                if !method.is_static() || method.is_cctor() || method.is_ctor() {
                    return None;
                }
                has_static_method += 1;

                // Look up this method's SSA function from the analysis context
                let ssa_ref = ctx.ssa_functions.get(&method.token);
                if ssa_ref.is_none() {
                    debug!(
                        "Delegate detect: type {}.{} method 0x{:08X} ({}) has no SSA",
                        ty.namespace, ty.name, method.token.value(), method.name
                    );
                    return None;
                }
                has_ssa += 1;

                let ssa = ssa_ref.unwrap();
                if is_delegate_wrapper_ssa(ssa.value(), assembly) {
                    is_wrapper += 1;
                    Some(method.token)
                } else {
                    debug!(
                        "Delegate detect: type {}.{} method 0x{:08X} ({}) SSA did not match wrapper pattern",
                        ty.namespace, ty.name, method.token.value(), method.name
                    );
                    None
                }
            });

            let Some(wrapper_method_token) = wrapper_method_token else {
                continue;
            };

            delegate_types.insert(
                ty.token,
                DelegateTypeInfo {
                    singleton_field_token,
                    wrapper_method_token,
                },
            );
            wrapper_to_delegate.insert(wrapper_method_token, ty.token);
        }

        debug!(
            "Delegate detect: {} delegate types, {} with static fields, {} with static methods, {} with SSA, {} matched wrapper pattern",
            delegate_count, has_static_field, has_static_method, has_ssa, is_wrapper
        );

        // Phase 2: Scan SSA functions for delegate proxy calls AND reflection patterns.
        let mut delegate_affected: HashSet<Token> = HashSet::new();
        let mut reflection_affected: HashSet<Token> = HashSet::new();
        let mut reflection_site_count = 0usize;

        for entry in ctx.ssa_functions.iter() {
            let method_token = *entry.key();
            let ssa = entry.value();

            // Delegate proxy calls
            if !delegate_types.is_empty() && has_delegate_proxy_calls(ssa, &wrapper_to_delegate) {
                delegate_affected.insert(method_token);
            }

            // Reflection patterns: CallIndirect with ResolveMethod chain (P1)
            let calli_count = count_resolve_method_calli_sites(ssa, assembly);
            if calli_count > 0 {
                reflection_affected.insert(method_token);
                reflection_site_count += calli_count;
            }

            // Reflection patterns: Call/CallVirt to reflection APIs (P2, P3, P5, P6)
            let api_count = count_reflection_api_calls(ssa, assembly);
            if api_count > 0 {
                reflection_affected.insert(method_token);
                reflection_site_count += api_count;
            }
        }

        let has_delegates = !delegate_types.is_empty() && !delegate_affected.is_empty();
        let has_reflection = !reflection_affected.is_empty();

        if !has_delegates && !has_reflection {
            return Detection::new_empty();
        }

        let mut evidence = Vec::new();
        if has_delegates {
            let type_count = delegate_types.len();
            let method_count = delegate_affected.len();
            evidence.push(Evidence::Structural(format!(
                "{type_count} delegate proxy types affecting {method_count} methods"
            )));
        }
        if has_reflection {
            let method_count = reflection_affected.len();
            evidence.push(Evidence::Structural(format!(
                "{reflection_site_count} reflection call indirection sites in {method_count} methods"
            )));
        }

        let findings = CallIndirectionFindings {
            delegate: DelegateProxyFindings {
                delegate_types,
                affected_methods: delegate_affected,
            },
            reflection: ReflectionFindings {
                affected_methods: reflection_affected,
                site_count: reflection_site_count,
            },
        };

        Detection::new_detected(
            evidence,
            Some(Box::new(findings) as Box<dyn Any + Send + Sync>),
        )
    }

    fn ssa_phase(&self) -> Option<PassPhase> {
        Some(PassPhase::Inline)
    }

    fn create_pass(
        &self,
        ctx: &AnalysisContext,
        detection: &Detection,
        _assembly: &Arc<CilObject>,
    ) -> Vec<Box<dyn SsaPass>> {
        let Some(combined) = detection.findings::<CallIndirectionFindings>() else {
            return Vec::new();
        };

        let mut passes: Vec<Box<dyn SsaPass>> = Vec::new();

        // Delegate proxy resolution pass (emulation-based)
        let delegate = &combined.delegate;
        if !delegate.delegate_types.is_empty() {
            if let Some(pool) = ctx.template_pool.get().cloned() {
                passes.push(Box::new(DelegateProxyResolutionPass::new(
                    pool,
                    delegate.delegate_types.clone(),
                    delegate.affected_methods.clone(),
                )));
            }
        }

        // Reflection devirtualization pass (SSA chain tracing)
        let reflection = &combined.reflection;
        if !reflection.affected_methods.is_empty() {
            passes.push(Box::new(ReflectionDevirtualizationPass::with_methods(
                reflection.affected_methods.clone(),
            )));
        }

        passes
    }

    fn cleanup(&self, detection: &Detection) -> Option<CleanupRequest> {
        let combined = detection.findings::<CallIndirectionFindings>()?;
        let delegate = &combined.delegate;
        if delegate.delegate_types.is_empty() {
            return None;
        }

        let mut request = CleanupRequest::new();
        for &type_token in delegate.delegate_types.keys() {
            request.add_type(type_token);
        }
        Some(request)
    }
}

/// Counts reflection API call sites in an SSA function (P2, P3, P5, P6).
///
/// Matches `Call`/`CallVirt` to `MethodInfo.Invoke`, `Activator.CreateInstance`,
/// `FieldInfo.GetValue`, and `FieldInfo.SetValue` where the target comes from
/// a traceable reflection chain.
fn count_reflection_api_calls(ssa: &SsaFunction, assembly: &CilObject) -> usize {
    let mut count = 0;
    for block in ssa.blocks() {
        for instr in block.instructions() {
            let (method_token, arg_count) = match instr.op() {
                SsaOp::Call { method, args, .. } | SsaOp::CallVirt { method, args, .. } => {
                    (method.token(), args.len())
                }
                _ => continue,
            };

            let Some(name) = assembly.resolve_method_name(method_token) else {
                continue;
            };

            // P2/P3: MethodInfo.Invoke with 3 args (this, obj, params[])
            if name == "Invoke" && arg_count == 3 {
                // Verify this is MethodBase/MethodInfo.Invoke, not Delegate.Invoke
                if is_method_named(assembly, method_token, "MethodBase")
                    || is_method_named(assembly, method_token, "MethodInfo")
                {
                    count += 1;
                    continue;
                }
            }

            // P5: Activator.CreateInstance
            if name.contains("CreateInstance")
                && is_method_named(assembly, method_token, "Activator")
            {
                count += 1;
                continue;
            }

            // P6: FieldInfo.GetValue / SetValue
            if (name == "GetValue" || name == "SetValue")
                && is_method_named(assembly, method_token, "FieldInfo")
            {
                count += 1;
            }
        }
    }
    count
}

#[cfg(test)]
mod tests {
    use crate::{
        compiler::PassPhase,
        deobfuscation::techniques::{
            generic::delegates::{CallIndirectionFindings, GenericDelegateProxy},
            Technique, TechniqueCategory,
        },
        test::helpers::load_sample,
    };

    #[test]
    fn test_detect_negative_confuserex_original() {
        let asm = load_sample("tests/samples/packers/confuserex/1.6.0/original.exe");

        let technique = GenericDelegateProxy;
        let detection = technique.detect(&asm);

        assert!(
            !detection.is_detected(),
            "GenericDelegateProxy should not detect anything in a ConfuserEx original sample"
        );
        assert!(
            detection.evidence().is_empty(),
            "No evidence should be present for a non-obfuscated sample"
        );
        assert!(
            detection.findings::<CallIndirectionFindings>().is_none(),
            "No findings should be present for a non-obfuscated sample"
        );
    }

    #[test]
    fn test_detect_negative_obfuscar_sample() {
        let asm = load_sample("tests/samples/packers/obfuscar/2.2.50/obfuscar_strings_only.exe");

        let technique = GenericDelegateProxy;
        let detection = technique.detect(&asm);

        assert!(
            !detection.is_detected(),
            "GenericDelegateProxy should not detect anything in an Obfuscar sample"
        );
    }

    #[test]
    fn test_technique_metadata() {
        let technique = GenericDelegateProxy;
        assert_eq!(technique.id(), "generic.delegates");
        assert_eq!(technique.name(), "Delegate Proxy Resolution");
        assert_eq!(technique.category(), TechniqueCategory::Call);
        assert!(technique.supersedes().is_empty());
    }

    #[test]
    fn test_technique_ssa_phase() {
        let technique = GenericDelegateProxy;
        assert_eq!(
            technique.ssa_phase(),
            Some(PassPhase::Inline),
            "GenericDelegateProxy should run in the Inline SSA phase"
        );
    }
}