Skip to main content

vmi_os_linux/
lib.rs

1//! Linux OS-specific VMI operations.
2
3use std::cell::RefCell;
4
5use isr_core::Profile;
6use vmi_core::{
7    Architecture, Pa, Va, VmiCore, VmiDriver, VmiError, VmiOs, VmiState, VmiVa as _,
8    driver::VmiRead,
9    os::{ProcessObject, ThreadObject},
10};
11
12mod arch;
13use self::arch::ArchAdapter;
14
15mod comps;
16pub use self::comps::{
17    LinuxDEntry, LinuxFile, LinuxFsStruct, LinuxImage, LinuxMapped, LinuxMmStruct, LinuxModule,
18    LinuxPath, LinuxQStr, LinuxTaskStruct, LinuxThread, LinuxUserModule, LinuxVFSMount,
19    LinuxVmAreaStruct,
20};
21
22mod error;
23pub use self::error::LinuxError;
24
25mod iter;
26pub use self::iter::{ListEntryIterator, MapleTree, MapleTreeIteratorNew};
27
28mod offsets;
29pub use self::offsets::{Offsets, Symbols};
30
31macro_rules! offset {
32    ($vmi:expr, $field:ident) => {
33        &__self(&$vmi).offsets.$field
34    };
35}
36
37macro_rules! symbol {
38    ($vmi:expr, $field:ident) => {
39        __self(&$vmi).symbols.$field
40    };
41}
42
43fn __self<'a, Driver>(vmi: &VmiState<'a, LinuxOs<Driver>>) -> &'a LinuxOs<Driver>
44where
45    Driver: VmiRead,
46    Driver::Architecture: ArchAdapter<Driver>,
47{
48    vmi.underlying_os()
49}
50
51/// VMI operations for the Linux operating system.
52///
53/// `LinuxOs` provides methods and utilities for introspecting a Linux-based
54/// virtual machine. It encapsulates Linux-specific knowledge and operations,
55/// allowing for high-level interactions with the guest OS structures and processes.
56pub struct LinuxOs<Driver>
57where
58    Driver: VmiDriver,
59{
60    offsets: Offsets,
61    symbols: Symbols,
62    kernel_image_base: RefCell<Option<Va>>,
63    kaslr_offset: RefCell<Option<u64>>,
64
65    _marker: std::marker::PhantomData<Driver>,
66}
67
68//#[expect(non_snake_case, unused_variables)]
69impl<Driver> LinuxOs<Driver>
70where
71    Driver: VmiRead,
72    Driver::Architecture: ArchAdapter<Driver>,
73{
74    /// Creates a new `LinuxOs` instance.
75    pub fn new(profile: &Profile) -> Result<Self, VmiError> {
76        Ok(Self {
77            offsets: Offsets::new(profile)?,
78            symbols: Symbols::new(profile)?,
79            kernel_image_base: RefCell::new(None),
80            kaslr_offset: RefCell::new(None),
81            _marker: std::marker::PhantomData,
82        })
83    }
84
85    /// Locates and retrieves the Linux banner string from kernel memory.
86    ///
87    /// The banner string typically contains kernel version information and build details.
88    pub fn find_banner(
89        vmi: &VmiCore<Driver>,
90        registers: &<Driver::Architecture as Architecture>::Registers,
91    ) -> Result<Option<String>, VmiError> {
92        Driver::Architecture::find_banner(vmi, registers)
93    }
94
95    /// Returns the KASLR (Kernel Address Space Layout Randomization) offset.
96    ///
97    /// This value represents the randomized offset applied to the kernel's base address
98    /// when KASLR is enabled.
99    pub fn kaslr_offset(vmi: VmiState<Self>) -> Result<u64, VmiError> {
100        Driver::Architecture::kaslr_offset(vmi)
101    }
102
103    /// Retrieves the per-CPU base address for the current CPU.
104    ///
105    /// Linux maintains per-CPU data structures, and this method returns the base
106    /// address for accessing such data on the current processor.
107    pub fn per_cpu(vmi: VmiState<Self>) -> Va {
108        Driver::Architecture::per_cpu(vmi)
109    }
110
111    /// Returns an iterator over a doubly-linked list of `LIST_ENTRY` structures.
112    ///
113    /// This method is used to iterate over a doubly-linked list of `LIST_ENTRY`
114    /// structures in memory. It returns an iterator that yields the virtual
115    /// addresses of each `LIST_ENTRY` structure in the list.
116    pub fn linked_list<'a>(
117        vmi: VmiState<'a, Self>,
118        list_head: Va,
119        offset: u64,
120    ) -> Result<impl Iterator<Item = Result<Va, VmiError>> + use<'a, Driver>, VmiError> {
121        Ok(ListEntryIterator::new(vmi, list_head, offset))
122    }
123
124    /// Constructs a file path string from path components in the kernel.
125    ///
126    /// This method walks the dentry chain to build a complete path, handling
127    /// mount points and filesystem boundaries appropriately. Both the `path`
128    /// and `root` arguments should be pointers to `struct path` objects.
129    pub fn construct_path(
130        _vmi: VmiState<Self>,
131        path: &LinuxPath<Driver>,
132        root: &LinuxPath<Driver>,
133    ) -> Result<String, VmiError> {
134        let mut dentry = path.dentry()?;
135        let mnt = path.mnt()?;
136        let root_dentry = root.dentry()?;
137        let root_mnt = root.mnt()?;
138        let mnt_mnt_root = mnt.mnt_root()?;
139
140        let mut result = String::new();
141
142        while dentry.va() != root_dentry.va() || mnt.va() != root_mnt.va() {
143            let dentry_parent = match dentry.parent()? {
144                Some(dentry) => dentry,
145                None => break,
146            };
147
148            if dentry.va() == mnt_mnt_root.va() || dentry.va() == dentry_parent.va() {
149                break;
150            }
151
152            let name = dentry.name()?.unwrap_or_else(|| String::from("<unknown>"));
153
154            result.insert_str(0, &name);
155            result.insert(0, '/');
156
157            dentry = dentry_parent;
158        }
159
160        Ok(result)
161    }
162}
163
164//#[expect(non_snake_case, unused_variables)]
165impl<Driver> VmiOs for LinuxOs<Driver>
166where
167    Driver: VmiRead,
168    Driver::Architecture: ArchAdapter<Driver>,
169{
170    type Architecture = Driver::Architecture;
171    type Driver = Driver;
172
173    type Process<'a> = LinuxTaskStruct<'a, Driver>;
174    type Thread<'a> = LinuxThread;
175    type Image<'a> = LinuxImage;
176    type Module<'a> = LinuxModule;
177    type UserModule<'a> = LinuxUserModule;
178    type Region<'a> = LinuxVmAreaStruct<'a, Driver>;
179    type Mapped<'a> = LinuxMapped;
180
181    fn kernel_image_base(_vmi: VmiState<Self>) -> Result<Va, VmiError> {
182        unimplemented!()
183    }
184
185    fn kernel_information_string(_vmi: VmiState<Self>) -> Result<String, VmiError> {
186        unimplemented!()
187    }
188
189    fn kpti_enabled(_vmi: VmiState<Self>) -> Result<bool, VmiError> {
190        unimplemented!()
191    }
192
193    fn modules<'a>(
194        _vmi: VmiState<'a, Self>,
195    ) -> Result<impl Iterator<Item = Result<Self::Module<'a>, VmiError>> + use<'a, Driver>, VmiError>
196    {
197        #[allow(unreachable_code)]
198        {
199            unimplemented!() as Result<std::iter::Empty<_>, VmiError>
200        }
201    }
202
203    fn processes<'a>(
204        vmi: VmiState<'a, Self>,
205    ) -> Result<impl Iterator<Item = Result<Self::Process<'a>, VmiError>> + use<'a, Driver>, VmiError>
206    {
207        let __init_task = symbol!(vmi, init_task);
208        let __task_struct = &offset!(vmi, task_struct);
209
210        let init_task = Va(__init_task) + Self::kaslr_offset(vmi)?;
211        let tasks = init_task + __task_struct.tasks.offset();
212
213        Ok(Self::linked_list(vmi, tasks, __task_struct.tasks.offset())?
214            .map(move |result| result.map(|entry| LinuxTaskStruct::new(vmi, ProcessObject(entry)))))
215    }
216
217    fn process(
218        vmi: VmiState<'_, Self>,
219        process: ProcessObject,
220    ) -> Result<Self::Process<'_>, VmiError> {
221        Ok(LinuxTaskStruct::new(vmi, process))
222    }
223
224    fn current_process(vmi: VmiState<'_, Self>) -> Result<Self::Process<'_>, VmiError> {
225        let pcpu_hot = symbol!(vmi, pcpu_hot);
226        let __pcpu_hot = offset!(vmi, pcpu_hot);
227
228        let per_cpu = Self::per_cpu(vmi);
229        if per_cpu.is_null() {
230            return Err(LinuxError::CorruptedStruct("per_cpu").into());
231        }
232
233        let addr = per_cpu + pcpu_hot + __pcpu_hot.current_task.offset();
234        let result = vmi.read_va_native(addr)?;
235
236        Ok(LinuxTaskStruct::new(vmi, ProcessObject(result)))
237    }
238
239    fn system_process(vmi: VmiState<'_, Self>) -> Result<Self::Process<'_>, VmiError> {
240        let __init_task = symbol!(vmi, init_task);
241        let __task_struct = &offset!(vmi, task_struct);
242
243        let init_task = Va(__init_task) + Self::kaslr_offset(vmi)?;
244        Ok(LinuxTaskStruct::new(vmi, ProcessObject(init_task)))
245    }
246
247    fn thread(
248        _vmi: VmiState<'_, Self>,
249        _thread: ThreadObject,
250    ) -> Result<Self::Thread<'_>, VmiError> {
251        unimplemented!()
252    }
253
254    fn current_thread(_vmi: VmiState<'_, Self>) -> Result<Self::Thread<'_>, VmiError> {
255        unimplemented!()
256    }
257
258    fn image(_vmi: VmiState<'_, Self>, _image_base: Va) -> Result<Self::Image<'_>, VmiError> {
259        unimplemented!()
260    }
261
262    fn module(_vmi: VmiState<'_, Self>, _module: Va) -> Result<Self::Module<'_>, VmiError> {
263        unimplemented!()
264    }
265
266    fn user_module(
267        _vmi: VmiState<'_, Self>,
268        _module: Va,
269        _root: Pa,
270    ) -> Result<Self::UserModule<'_>, VmiError> {
271        unimplemented!()
272    }
273
274    fn region(vmi: VmiState<'_, Self>, region: Va) -> Result<Self::Region<'_>, VmiError> {
275        Ok(LinuxVmAreaStruct::new(vmi, region))
276    }
277
278    fn syscall_argument(vmi: VmiState<Self>, index: u64) -> Result<u64, VmiError> {
279        Driver::Architecture::syscall_argument(vmi, index)
280    }
281
282    fn function_argument(vmi: VmiState<Self>, index: u64) -> Result<u64, VmiError> {
283        Driver::Architecture::function_argument(vmi, index)
284    }
285
286    fn function_return_value(vmi: VmiState<Self>) -> Result<u64, VmiError> {
287        Driver::Architecture::function_return_value(vmi)
288    }
289
290    fn last_error(_vmi: VmiState<Self>) -> Result<Option<u32>, VmiError> {
291        unimplemented!()
292    }
293}