vmi_utils/injector/
recipe.rs

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
use std::collections::HashMap;

use vmi_core::{os::VmiOs, Architecture, Hex, Registers, Va, VmiContext, VmiDriver, VmiError};

/// The control flow of a recipe step.
pub enum RecipeControlFlow {
    /// Continue to the next step.
    Continue,

    /// Stop executing the recipe.
    Break,

    /// Repeat the current step.
    Repeat,

    /// Skip the next step.
    Skip,

    /// Jump to a specific step.
    Goto(usize),
}

/// A function that executes a single step in an injection recipe.
pub type RecipeStepFn<Driver, Os, T> = Box<
    dyn Fn(&mut RecipeContext<'_, Driver, Os, T>) -> Result<RecipeControlFlow, VmiError>
        + Send
        + Sync
        + 'static,
>;

/// A cache of symbols for a single image.
/// The key is the symbol name and the value is the virtual address.
pub type SymbolCache = HashMap<String, Va>;

/// A cache of symbols for multiple images.
/// The key is the image filename and the value is the symbol cache.
pub type ImageSymbolCache = HashMap<String, SymbolCache>;

/// A sequence of injection steps to be executed in order.
pub struct Recipe<Driver, Os, T>
where
    Driver: VmiDriver,
    Os: VmiOs<Driver>,
{
    /// The ordered list of steps to execute.
    pub(super) steps: Vec<RecipeStepFn<Driver, Os, T>>,

    /// User-provided data shared between steps.
    pub(super) data: T,

    /// Whether the bridge support is enabled.
    pub(super) bridge: bool,
}

impl<Driver, Os, T> Recipe<Driver, Os, T>
where
    Driver: VmiDriver,
    Os: VmiOs<Driver>,
{
    /// Creates a new recipe with the given data.
    pub fn new(data: T) -> Self {
        Self {
            steps: Vec::new(),
            data,
            bridge: false,
        }
    }

    /// Creates a new recipe with the given data and bridge support.
    pub fn new_with_bridge(data: T) -> Self {
        Self {
            steps: Vec::new(),
            data,
            bridge: true,
        }
    }

    /// Adds a new step to the recipe.
    pub fn step<F>(mut self, f: F) -> Self
    where
        F: Fn(&mut RecipeContext<'_, Driver, Os, T>) -> Result<RecipeControlFlow, VmiError>
            + Send
            + Sync
            + 'static,
    {
        self.steps.push(Box::new(f));
        self
    }
}

/// Context provided to each recipe step during execution.
pub struct RecipeContext<'a, Driver, Os, T>
where
    Driver: VmiDriver,
    Os: VmiOs<Driver>,
{
    /// The VMI context.
    pub vmi: &'a VmiContext<'a, Driver, Os>,

    /// The CPU registers.
    pub registers: &'a mut <<Driver as VmiDriver>::Architecture as Architecture>::Registers,

    /// User-provided data shared between steps.
    pub data: &'a mut T,

    /// Cache of resolved symbols for each module.
    pub cache: &'a mut ImageSymbolCache,
}

/// Manages the execution of a recipe's steps.
pub struct RecipeExecutor<Driver, Os, T>
where
    Driver: VmiDriver,
    Os: VmiOs<Driver>,
{
    /// The recipe being executed.
    recipe: Recipe<Driver, Os, T>,

    /// Cache of resolved symbols per module.
    cache: ImageSymbolCache,

    /// Original state of CPU registers to restore after completion.
    original_registers: Option<<Driver::Architecture as Architecture>::Registers>,

    /// Index of the current step being executed.
    index: Option<usize>,
}

impl<Driver, Os, T> RecipeExecutor<Driver, Os, T>
where
    Driver: VmiDriver,
    Os: VmiOs<Driver>,
{
    /// Creates a new recipe executor with the given recipe.
    pub fn new(recipe: Recipe<Driver, Os, T>) -> Self {
        Self {
            recipe,
            cache: ImageSymbolCache::new(),
            original_registers: None,
            index: None,
        }
    }

    /// Executes the next step in the recipe.
    pub fn execute(
        &mut self,
        vmi: &VmiContext<Driver, Os>,
    ) -> Result<<<Driver as VmiDriver>::Architecture as Architecture>::Registers, VmiError> {
        let index = match &mut self.index {
            Some(index) => index,
            None => {
                self.original_registers = Some(*vmi.registers());
                self.index.insert(0)
            }
        };

        if let Some(step) = self.recipe.steps.get(*index) {
            tracing::debug!(index, "recipe step");

            let mut registers = *vmi.registers();

            let next = step(&mut RecipeContext {
                vmi,
                registers: &mut registers,
                data: &mut self.recipe.data,
                cache: &mut self.cache,
            })?;

            match next {
                RecipeControlFlow::Continue => {
                    *index += 1;
                    return Ok(registers);
                }
                RecipeControlFlow::Break => {}
                RecipeControlFlow::Repeat => {
                    return Ok(registers);
                }
                RecipeControlFlow::Skip => {
                    *index += 2;
                    return Ok(registers);
                }
                RecipeControlFlow::Goto(i) => {
                    *index = i;
                    return Ok(registers);
                }
            }
        }

        tracing::debug!(
            result = %Hex(vmi.registers().result()),
            "recipe finished"
        );

        self.index = None;
        let original_registers = self.original_registers.expect("original_registers");
        Ok(original_registers)
    }

    /// Resets the executor to the initial state.
    pub fn reset(&mut self) {
        self.index = None;
    }

    /// Returns whether the recipe has finished executing.
    pub fn done(&self) -> bool {
        self.index.is_none() && self.original_registers.is_some()
    }
}