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
//! Matcher trait and implementations for hook matching.
//!
//! This module defines the [`HookMatcher`] trait and several implementations for
//! determining whether a hook should be applied to a given method call.
//!
//! # Available Matchers
//!
//! | Matcher | Description |
//! |---------|-------------|
//! | [`NameMatcher`] | Match by namespace, type, and/or method name |
//! | [`InternalMethodMatcher`] | Match only internal methods (MethodDef) |
//! | [`SignatureMatcher`] | Match by parameter and return types |
//! | [`RuntimeMatcher`] | Match by inspecting runtime argument values |
//!
//! # Combining Matchers
//!
//! Multiple matchers can be added to a single hook. All matchers must match for
//! the hook to be applied (AND semantics).
//!
//! ```rust,ignore
//! use dotscope::emulation::{Hook, HookPriority};
//! use dotscope::metadata::typesystem::CilFlavor;
//!
//! // This hook requires ALL conditions to be true:
//! // 1. Internal method
//! // 2. Parameter is byte[]
//! // 3. Returns byte[]
//! // 4. First argument looks like LZMA header
//! let hook = Hook::new("lzma-decompressor")
//!     .match_internal_method()
//!     .match_signature(vec![CilFlavor::Array { .. }], Some(CilFlavor::Array { .. }))
//!     .match_runtime("lzma-header", |ctx, thread| {
//!         // Custom runtime check
//!         is_lzma_header(ctx, thread)
//!     });
//! ```

use std::sync::Arc;

use crate::{
    emulation::{runtime::hook::types::HookContext, EmulationThread},
    metadata::typesystem::CilFlavor,
};

/// Type alias for runtime matcher predicates.
pub type RuntimePredicate = dyn Fn(&HookContext<'_>, &EmulationThread) -> bool + Send + Sync;

/// Trait for implementing hook matchers.
///
/// Matchers determine whether a hook should be applied to a given method call.
/// Each matcher implements a single matching criterion. Multiple matchers can
/// be combined on a hook (all must match).
///
/// # Implementing Custom Matchers
///
/// ```rust,no_run
/// use dotscope::emulation::{HookMatcher, HookContext, EmulationThread};
///
/// struct ModuleNameMatcher {
///     module_name: String,
/// }
///
/// impl HookMatcher for ModuleNameMatcher {
///     fn matches(&self, context: &HookContext<'_>, _thread: &EmulationThread) -> bool {
///         // Custom matching logic based on module name
///         context.method_token.table() == 0x06 // Check if MethodDef
///     }
///
///     fn description(&self) -> String {
///         format!("module={}", self.module_name)
///     }
/// }
/// ```
///
/// # Thread Safety
///
/// Matchers must be `Send + Sync` to allow hook registration from any thread.
pub trait HookMatcher: Send + Sync {
    /// Checks if this matcher matches the given context.
    ///
    /// # Arguments
    ///
    /// * `context` - The hook context containing method call information
    /// * `thread` - The emulation thread (for runtime data inspection)
    ///
    /// # Returns
    ///
    /// `true` if the matcher matches, `false` otherwise.
    fn matches(&self, context: &HookContext<'_>, thread: &EmulationThread) -> bool;

    /// Returns a description of this matcher for debugging.
    ///
    /// This should be a concise description of what the matcher checks for,
    /// such as "namespace=System, type=String" or "internal method only".
    fn description(&self) -> String;
}

/// Matches methods by namespace, type name, and/or method name.
///
/// Each component is optional. Unset components match anything. When multiple
/// components are set, all must match.
///
/// # Examples
///
/// ```rust,no_run
/// use dotscope::emulation::NameMatcher;
///
/// // Match all methods named "Decrypt" in any namespace/type
/// let matcher = NameMatcher::new().method_name("Decrypt");
///
/// // Match String.Concat specifically
/// let matcher = NameMatcher::full("System", "String", "Concat");
///
/// // Match all methods in the System namespace
/// let matcher = NameMatcher::new().namespace("System");
/// ```
#[derive(Clone, Debug, Default)]
pub struct NameMatcher {
    namespace: Option<String>,
    type_name: Option<String>,
    method_name: Option<String>,
}

impl NameMatcher {
    /// Creates a new name matcher with all components optional.
    ///
    /// Use the builder methods to specify which components to match.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the namespace to match.
    ///
    /// # Arguments
    ///
    /// * `ns` - The namespace to match exactly
    #[must_use]
    pub fn namespace(mut self, ns: impl Into<String>) -> Self {
        self.namespace = Some(ns.into());
        self
    }

    /// Sets the type name to match.
    ///
    /// # Arguments
    ///
    /// * `name` - The type name to match exactly
    #[must_use]
    pub fn type_name(mut self, name: impl Into<String>) -> Self {
        self.type_name = Some(name.into());
        self
    }

    /// Sets the method name to match.
    ///
    /// # Arguments
    ///
    /// * `name` - The method name to match exactly
    #[must_use]
    pub fn method_name(mut self, name: impl Into<String>) -> Self {
        self.method_name = Some(name.into());
        self
    }

    /// Creates a matcher from all three components.
    ///
    /// This is a convenience method for matching a specific method.
    ///
    /// # Arguments
    ///
    /// * `namespace` - The namespace to match
    /// * `type_name` - The type name to match
    /// * `method_name` - The method name to match
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::emulation::NameMatcher;
    ///
    /// let matcher = NameMatcher::full("System", "String", "Concat");
    /// ```
    #[must_use]
    pub fn full(
        namespace: impl Into<String>,
        type_name: impl Into<String>,
        method_name: impl Into<String>,
    ) -> Self {
        Self {
            namespace: Some(namespace.into()),
            type_name: Some(type_name.into()),
            method_name: Some(method_name.into()),
        }
    }
}

impl HookMatcher for NameMatcher {
    fn matches(&self, context: &HookContext<'_>, _thread: &EmulationThread) -> bool {
        let ns_matches = self
            .namespace
            .as_ref()
            .is_none_or(|ns| ns == context.namespace);

        let type_matches = self
            .type_name
            .as_ref()
            .is_none_or(|t| t == context.type_name);

        let method_matches = self
            .method_name
            .as_ref()
            .is_none_or(|m| m == context.method_name);

        ns_matches && type_matches && method_matches
    }

    fn description(&self) -> String {
        let mut parts = Vec::new();
        if let Some(ns) = &self.namespace {
            parts.push(format!("namespace={ns}"));
        }
        if let Some(t) = &self.type_name {
            parts.push(format!("type={t}"));
        }
        if let Some(m) = &self.method_name {
            parts.push(format!("method={m}"));
        }
        if parts.is_empty() {
            "any".to_string()
        } else {
            parts.join(", ")
        }
    }
}

/// Matches only internal methods (MethodDef, not MemberRef).
///
/// Internal methods are defined in the assembly being analyzed. External methods
/// are from referenced assemblies (typically BCL or third-party libraries).
///
/// This is useful for matching obfuscator-generated methods that wouldn't be
/// in the BCL.
///
/// # Examples
///
/// ```rust,no_run
/// use dotscope::emulation::{Hook, InternalMethodMatcher};
///
/// let hook = Hook::new("internal-only")
///     .add_matcher(InternalMethodMatcher);
/// ```
#[derive(Clone, Debug, Default)]
pub struct InternalMethodMatcher;

impl HookMatcher for InternalMethodMatcher {
    fn matches(&self, context: &HookContext<'_>, _thread: &EmulationThread) -> bool {
        context.is_internal
    }

    fn description(&self) -> String {
        "internal method only".to_string()
    }
}

/// Matches methods by their parameter and return types.
///
/// Uses CIL type flavors to match the method signature. Both parameter types
/// and return type can be specified independently.
///
/// # Examples
///
/// ```rust,no_run
/// use dotscope::emulation::SignatureMatcher;
/// use dotscope::metadata::typesystem::CilFlavor;
///
/// // Match methods that take (int32, int32) and return int32
/// let matcher = SignatureMatcher::new()
///     .params(vec![CilFlavor::I4, CilFlavor::I4])
///     .returns(CilFlavor::I4);
///
/// // Match methods that return int32
/// let matcher = SignatureMatcher::new()
///     .returns(CilFlavor::I4);
/// ```
#[derive(Clone, Debug, Default)]
pub struct SignatureMatcher {
    param_types: Option<Vec<CilFlavor>>,
    return_type: Option<CilFlavor>,
}

impl SignatureMatcher {
    /// Creates a new signature matcher.
    ///
    /// By default, no type constraints are applied.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the expected parameter types.
    ///
    /// All parameter types must match exactly in order.
    ///
    /// # Arguments
    ///
    /// * `types` - The expected parameter types
    #[must_use]
    pub fn params(mut self, types: Vec<CilFlavor>) -> Self {
        self.param_types = Some(types);
        self
    }

    /// Sets the expected return type.
    ///
    /// # Arguments
    ///
    /// * `return_type` - The expected return type
    #[must_use]
    pub fn returns(mut self, return_type: CilFlavor) -> Self {
        self.return_type = Some(return_type);
        self
    }
}

impl HookMatcher for SignatureMatcher {
    fn matches(&self, context: &HookContext<'_>, _thread: &EmulationThread) -> bool {
        // Check parameter types if specified
        if let Some(expected_params) = &self.param_types {
            match context.param_types {
                Some(actual_params) => {
                    if expected_params.len() != actual_params.len() {
                        return false;
                    }
                    for (expected, actual) in expected_params.iter().zip(actual_params.iter()) {
                        if expected != actual {
                            return false;
                        }
                    }
                }
                None => return false, // Can't verify, fail conservatively
            }
        }

        // Check return type if specified
        if let Some(expected_ret) = &self.return_type {
            match &context.return_type {
                Some(actual_ret) => {
                    if expected_ret != actual_ret {
                        return false;
                    }
                }
                None => return false,
            }
        }

        true
    }

    fn description(&self) -> String {
        let mut parts = Vec::new();
        if let Some(params) = &self.param_types {
            parts.push(format!("params={params:?}"));
        }
        if let Some(ret) = &self.return_type {
            parts.push(format!("returns={ret:?}"));
        }
        if parts.is_empty() {
            "any signature".to_string()
        } else {
            parts.join(", ")
        }
    }
}

/// Matches methods based on runtime argument inspection.
///
/// This matcher uses a closure to inspect actual argument values at runtime.
/// This enables pattern matching like "input looks like LZMA data" that cannot
/// be determined from metadata alone.
///
/// # Performance
///
/// Runtime matchers are evaluated for every method call that passes other
/// matchers. Keep the predicate efficient to avoid performance impact.
///
/// # Examples
///
/// ```rust,ignore
/// use dotscope::emulation::RuntimeMatcher;
///
/// // Match methods where first argument is a byte[] starting with LZMA header
/// let matcher = RuntimeMatcher::new("lzma-header", |ctx, thread| {
///     if let Some(EmValue::Reference(r)) = ctx.args.first() {
///         if let Some(bytes) = thread.heap().get_array_as_bytes(*r) {
///             return bytes.len() >= 5 && bytes[0] == 0x5D;
///         }
///     }
///     false
/// });
/// ```
pub struct RuntimeMatcher {
    predicate: Arc<RuntimePredicate>,
    description: String,
}

impl RuntimeMatcher {
    /// Creates a new runtime matcher with the given predicate.
    ///
    /// # Arguments
    ///
    /// * `description` - Human-readable description of what this matches
    /// * `predicate` - Function that inspects context and returns `true` if matched
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use dotscope::emulation::RuntimeMatcher;
    ///
    /// let matcher = RuntimeMatcher::new("has-three-args", |ctx, _thread| {
    ///     ctx.args.len() == 3
    /// });
    /// ```
    pub fn new<F>(description: impl Into<String>, predicate: F) -> Self
    where
        F: Fn(&HookContext<'_>, &EmulationThread) -> bool + Send + Sync + 'static,
    {
        Self {
            predicate: Arc::new(predicate),
            description: description.into(),
        }
    }
}

impl HookMatcher for RuntimeMatcher {
    fn matches(&self, context: &HookContext<'_>, thread: &EmulationThread) -> bool {
        (self.predicate)(context, thread)
    }

    fn description(&self) -> String {
        self.description.clone()
    }
}

/// Matches P/Invoke (native) method calls by DLL name and/or function name.
///
/// This matcher identifies calls to unmanaged code through the P/Invoke
/// mechanism. It can match by DLL name, function name, or both.
///
/// # Normalization
///
/// DLL names are normalized to lowercase and the `.dll` extension is removed
/// for consistent matching. Function names are compared case-sensitively.
///
/// # Examples
///
/// ```rust,no_run
/// use dotscope::emulation::NativeMethodMatcher;
///
/// // Match all calls to kernel32.dll
/// let matcher = NativeMethodMatcher::new().dll("kernel32");
///
/// // Match VirtualProtect specifically
/// let matcher = NativeMethodMatcher::full("kernel32", "VirtualProtect");
///
/// // Match any function named GetModuleHandle (any DLL)
/// let matcher = NativeMethodMatcher::new().function("GetModuleHandle");
/// ```
#[derive(Clone, Debug, Default)]
pub struct NativeMethodMatcher {
    dll_name: Option<String>,
    function_name: Option<String>,
}

impl NativeMethodMatcher {
    /// Creates a new native method matcher with no constraints.
    ///
    /// Use the builder methods to specify which components to match.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the DLL name to match.
    ///
    /// The DLL name is normalized: converted to lowercase with `.dll` extension removed.
    ///
    /// # Arguments
    ///
    /// * `dll` - The DLL name to match (e.g., "kernel32" or "kernel32.dll")
    #[must_use]
    pub fn dll(mut self, dll: impl Into<String>) -> Self {
        let dll = dll.into().to_lowercase();
        let normalized = dll
            .trim_end_matches(".dll")
            .trim_end_matches(".DLL")
            .to_string();
        self.dll_name = Some(normalized);
        self
    }

    /// Sets the function name to match.
    ///
    /// Function names are matched case-sensitively.
    ///
    /// # Arguments
    ///
    /// * `function` - The function name to match (e.g., "VirtualProtect")
    #[must_use]
    pub fn function(mut self, function: impl Into<String>) -> Self {
        self.function_name = Some(function.into());
        self
    }

    /// Creates a matcher for a specific DLL and function combination.
    ///
    /// # Arguments
    ///
    /// * `dll` - The DLL name (normalized automatically)
    /// * `function` - The function name
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::emulation::NativeMethodMatcher;
    ///
    /// let matcher = NativeMethodMatcher::full("kernel32", "VirtualProtect");
    /// ```
    #[must_use]
    pub fn full(dll: impl Into<String>, function: impl Into<String>) -> Self {
        Self::new().dll(dll).function(function)
    }
}

impl HookMatcher for NativeMethodMatcher {
    fn matches(&self, context: &HookContext<'_>, _thread: &EmulationThread) -> bool {
        // Must be a native call
        if !context.is_native {
            return false;
        }

        // Check DLL name if specified
        if let Some(expected_dll) = &self.dll_name {
            let actual_dll = context
                .dll_name
                .map(|d| {
                    d.to_lowercase()
                        .trim_end_matches(".dll")
                        .trim_end_matches(".DLL")
                        .to_string()
                })
                .unwrap_or_default();
            if expected_dll != &actual_dll {
                return false;
            }
        }

        // Check function name if specified
        if let Some(expected_fn) = &self.function_name {
            if expected_fn != context.method_name {
                return false;
            }
        }

        true
    }

    fn description(&self) -> String {
        let mut parts = Vec::new();
        parts.push("native".to_string());
        if let Some(dll) = &self.dll_name {
            parts.push(format!("dll={dll}"));
        }
        if let Some(func) = &self.function_name {
            parts.push(format!("function={func}"));
        }
        parts.join(", ")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::metadata::{token::Token, typesystem::PointerSize};

    fn create_test_context<'a>() -> HookContext<'a> {
        HookContext::new(
            Token::new(0x06000001),
            "System",
            "String",
            "Concat",
            PointerSize::Bit64,
        )
    }

    #[test]
    fn test_name_matcher_full() {
        let matcher = NameMatcher::full("System", "String", "Concat");
        assert_eq!(
            matcher.description(),
            "namespace=System, type=String, method=Concat"
        );
    }

    #[test]
    fn test_name_matcher_partial() {
        let matcher = NameMatcher::new().method_name("Decrypt");
        assert_eq!(matcher.description(), "method=Decrypt");
    }

    #[test]
    fn test_name_matcher_empty() {
        let matcher = NameMatcher::new();
        assert_eq!(matcher.description(), "any");
    }

    #[test]
    fn test_internal_method_matcher_description() {
        let matcher = InternalMethodMatcher;
        assert_eq!(matcher.description(), "internal method only");
    }

    #[test]
    fn test_signature_matcher_description() {
        let matcher = SignatureMatcher::new()
            .params(vec![CilFlavor::I4, CilFlavor::I4])
            .returns(CilFlavor::I4);

        let desc = matcher.description();
        assert!(desc.contains("params="));
        assert!(desc.contains("returns="));
    }
}