forensic-rs 0.13.1

A Rust-based framework to build tools that analyze forensic artifacts and can be reused as libraries across multiple projects without changing anything.
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
use crate::{
    err::ForensicError,
    traits::registry::{RegHiveKey, RegValue, RegistryKeyInfo, RegistryReader},
};
use std::{cell::RefCell, collections::BTreeMap};

use super::time::Filetime;

/// Basic Registry for testing. Includes the user profile "S-1-5-21-1366093794-4292800403-1155380978-513"
#[derive(Clone, Debug)]
pub struct TestingRegistry {
    pub cell: BTreeMap<String, MountedCell>,
    pub cached: RefCell<BTreeMap<RegHiveKey, String>>,
    pub counter: RefCell<isize>,
}

impl Default for TestingRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl TestingRegistry {
    pub fn empty() -> Self {
        Self {
            cell: BTreeMap::new(),
            cached: RefCell::new(basic_cache()),
            counter: RefCell::default(),
        }
    }
    pub fn new() -> Self {
        Self {
            cell: basic_registry(),
            cached: RefCell::new(basic_cache()),
            counter: RefCell::new(0),
        }
    }
    pub fn increase_counter(&self) -> isize {
        let mut borrowed = self.counter.borrow_mut();
        let ret = *borrowed;
        *borrowed += 1;
        ret
    }
    pub fn add_value(&mut self, path: &str, value: &str, data: RegValue) {
        let (hkey, rest) = match path.split_once(|v| v == '/' || v == '\\') {
            Some(v) => v,
            None => {
                return self
                    .cell
                    .entry(path.to_string())
                    .or_insert(MountedCell::new(path))
                    .add_value("", value, data)
            }
        };
        self.cell
            .entry(hkey.to_string())
            .or_insert(MountedCell::new(hkey))
            .add_value(rest, value, data);
    }
    pub fn contains(&self, path: &str) -> bool {
        let (hkey, rest) = match path.split_once(|v| v == '/' || v == '\\') {
            Some(v) => v,
            None => return self.cell.contains_key(path),
        };
        let hive = match self.cell.get(hkey) {
            Some(v) => v,
            None => return false,
        };
        hive.contains_key(rest)
    }
    pub fn get_value(&self, path: &str, value: &str) -> Option<RegValue> {
        let (hkey, rest) = match path.split_once(|v| v == '/' || v == '\\') {
            Some(v) => v,
            None => (path, ""),
        };
        let hive = match self.cell.get(hkey) {
            Some(v) => v,
            None => return None,
        };
        hive.get_value(rest, value)
    }
    pub fn get_values(&self, path: &str) -> Option<Vec<String>> {
        let (hkey, rest) = match path.split_once(|v| v == '/' || v == '\\') {
            Some(v) => v,
            None => (path, ""),
        };
        let hive = match self.cell.get(hkey) {
            Some(v) => v,
            None => return None,
        };
        Some(hive.get_values(rest))
    }
    pub fn get_keys(&self, path: &str) -> Option<Vec<String>> {
        let (hkey, rest) = match path.split_once(|v| v == '/' || v == '\\') {
            Some(v) => v,
            None => (path, ""),
        };
        let hive = match self.cell.get(hkey) {
            Some(v) => v,
            None => return None,
        };
        Some(hive.get_keys(rest))
    }
}

#[derive(Clone, Debug, Default)]
pub struct MountedCell {
    pub name: String,
    pub keys: BTreeMap<String, MountedCell>,
    pub values: BTreeMap<String, RegValue>,
}
impl MountedCell {
    pub fn new(name: &str) -> Self {
        Self {
            name: name.into(),
            keys: BTreeMap::new(),
            values: BTreeMap::new(),
        }
    }
    pub fn add_key(&mut self, path: &str) {
        if path.is_empty() {
            return;
        }
        let (first, rest) = match path.split_once(|v| v == '/' || v == '\\') {
            Some(v) => v,
            None => {
                self.keys
                    .entry(path.to_string())
                    .or_insert(MountedCell::new(path))
                    .add_key(path);
                return;
            }
        };
        self.keys
            .entry(first.to_string())
            .or_insert(MountedCell::new(first))
            .add_key(rest);
    }
    pub fn contains_key(&self, path: &str) -> bool {
        let (first, rest) = match path.split_once(|v| v == '/' || v == '\\') {
            Some(v) => v,
            None => return self.keys.contains_key(path),
        };
        let hive = match self.keys.get(first) {
            Some(v) => v,
            None => return false,
        };
        hive.contains_key(rest)
    }
    pub fn add_value(&mut self, path: &str, value: &str, data: RegValue) {
        if path.is_empty() {
            self.values.insert(value.into(), data);
            return;
        }
        let (first, rest) = match path.split_once(|v| v == '/' || v == '\\') {
            Some(v) => v,
            None => {
                self.keys
                    .entry(path.to_string())
                    .or_insert(MountedCell::new(path))
                    .add_value("", value, data);
                return;
            }
        };
        self.keys
            .entry(first.to_string())
            .or_insert(MountedCell::new(first))
            .add_value(rest, value, data);
    }
    pub fn get_value(&self, path: &str, value: &str) -> Option<RegValue> {
        if path.is_empty() {
            return self.values.get(value).cloned();
        }
        let (first, rest) = match path.split_once(|v| v == '/' || v == '\\') {
            Some(v) => v,
            None => return self.keys.get(path)?.get_value("", value),
        };
        self.keys.get(first)?.get_value(rest, value)
    }
    pub fn get_values(&self, path: &str) -> Vec<String> {
        if path.is_empty() {
            return self
                .values
                .keys()
                .map(|v| v.to_string())
                .collect();
        }
        let (first, rest) = match path.split_once(|v| v == '/' || v == '\\') {
            Some(v) => v,
            None => {
                return match self.keys.get(path) {
                    Some(v) => v.get_values(""),
                    None => Vec::new(),
                }
            }
        };
        match self.keys.get(first) {
            Some(v) => v.get_values(rest),
            None => Vec::new(),
        }
    }
    pub fn get_keys(&self, path: &str) -> Vec<String> {
        if path.is_empty() {
            return self
                .keys
                .keys()
                .map(|v| v.to_string())
                .collect();
        }
        let (first, rest) = match path.split_once(|v| v == '/' || v == '\\') {
            Some(v) => v,
            None => {
                return match self.keys.get(path) {
                    Some(v) => v.get_keys(""),
                    None => Vec::new(),
                }
            }
        };
        match self.keys.get(first) {
            Some(v) => v.get_keys(rest),
            None => Vec::new(),
        }
    }
}

impl RegistryReader for TestingRegistry {
    fn from_file(
        &self,
        _file: Box<dyn crate::traits::vfs::VirtualFile>,
    ) -> crate::err::ForensicResult<Box<dyn RegistryReader>> {
        Ok(Box::new(TestingRegistry::new()))
    }

    fn from_fs(
        &self,
        _fs: Box<dyn crate::traits::vfs::VirtualFileSystem>,
    ) -> crate::err::ForensicResult<Box<dyn RegistryReader>> {
        Ok(Box::new(TestingRegistry::new()))
    }

    fn open_key(
        &self,
        hkey: crate::traits::registry::RegHiveKey,
        key_name: &str,
    ) -> crate::err::ForensicResult<crate::traits::registry::RegHiveKey> {
        let mut borrowed = self.cached.borrow_mut();
        let (hkey, path) = match borrowed.get(&hkey) {
            Some(v) => {
                let full_path = format!("{}\\{}", v, key_name);
                if !self.contains(&full_path) {
                    return Err(ForensicError::missing_string(format!(
                        "Key path {} not found",
                        full_path
                    )));
                }
                let handle = self.increase_counter();
                (handle, full_path)
            }
            None => return Err(ForensicError::missing_str("Hkey not found")),
        };
        borrowed.insert(RegHiveKey::Hkey(hkey), path);
        Ok(RegHiveKey::Hkey(hkey))
    }

    fn read_value(
        &self,
        hkey: crate::traits::registry::RegHiveKey,
        value_name: &str,
    ) -> crate::err::ForensicResult<RegValue> {
        let borrowed = self.cached.borrow();
        let key_path = borrowed
            .get(&hkey)
            .ok_or_else(|| ForensicError::missing_str("HKey not found"))?;
        let value = self.get_value(key_path, value_name).ok_or_else(|| {
            ForensicError::missing_string(format!("Value {}\\{} not found", key_path, value_name))
        })?;
        Ok(value)
    }

    fn enumerate_values(
        &self,
        hkey: crate::traits::registry::RegHiveKey,
    ) -> crate::err::ForensicResult<Vec<String>> {
        let borrowed = self.cached.borrow();
        let key_path = borrowed
            .get(&hkey)
            .ok_or_else(|| ForensicError::missing_str("HKey not found"))?;
        let value = self.get_values(key_path).ok_or_else(|| {
            ForensicError::missing_string(format!("Values for {} not found", key_path))
        })?;
        Ok(value)
    }

    fn enumerate_keys(
        &self,
        hkey: crate::traits::registry::RegHiveKey,
    ) -> crate::err::ForensicResult<Vec<String>> {
        let borrowed = self.cached.borrow();
        let key_path = borrowed
            .get(&hkey)
            .ok_or_else(|| ForensicError::missing_str("HKey not found"))?;
        let value = self.get_keys(key_path).ok_or_else(|| {
            ForensicError::missing_string(format!("Keys for {} not found", key_path))
        })?;
        Ok(value)
    }

    fn key_at(
        &self,
        hkey: crate::traits::registry::RegHiveKey,
        pos: u32,
    ) -> crate::err::ForensicResult<String> {
        let borrowed = self.cached.borrow();
        let key_path = borrowed
            .get(&hkey)
            .ok_or_else(|| ForensicError::missing_str("HKey not found"))?;
        let mut value = self.get_keys(key_path).ok_or_else(|| {
            ForensicError::missing_string(format!("Keys for {} not found", key_path))
        })?;
        let pos = pos as usize;
        if pos > value.len() {
            return Err(ForensicError::NoMoreData);
        }
        Ok(value.remove(pos))
    }

    fn value_at(
        &self,
        hkey: crate::traits::registry::RegHiveKey,
        pos: u32,
    ) -> crate::err::ForensicResult<String> {
        let borrowed = self.cached.borrow();
        let key_path = borrowed
            .get(&hkey)
            .ok_or_else(|| ForensicError::missing_str("HKey not found"))?;
        let mut value = self.get_values(key_path).ok_or_else(|| {
            ForensicError::missing_string(format!("Values for {} not found", key_path))
        })?;
        let pos = pos as usize;
        if pos > value.len() {
            return Err(ForensicError::NoMoreData);
        }
        Ok(value.remove(pos))
    }

    fn key_info(&self, hkey: RegHiveKey) -> crate::err::ForensicResult<crate::traits::registry::RegistryKeyInfo> {
        let borrowed = self.cached.borrow();
        let key_path = borrowed
            .get(&hkey)
            .ok_or_else(|| ForensicError::missing_str("HKey not found"))?;
        let value = self.get_values(key_path).ok_or_else(|| {
            ForensicError::missing_string(format!("Values for {} not found", key_path))
        })?;
        let keys = self.get_keys(key_path).ok_or_else(|| {
            ForensicError::missing_string(format!("Values for {} not found", key_path))
        })?;
        Ok(RegistryKeyInfo {
            last_write_time : Filetime::new(0),
            subkeys : keys.len() as u32,
            values : value.len() as u32,
            max_subkey_name_length : keys.iter().map(|v| v.len()).fold(0, |acc, e| e.max(acc)) as u32,
            max_value_name_length: value.iter().map(|v| v.len()).fold(0, |acc, e| e.max(acc)) as u32,
            max_value_length: 0,
        })
    }
}
fn basic_cache() -> BTreeMap<RegHiveKey, String> {
    {
        let mut map = BTreeMap::new();
        for (k, p) in [
            (RegHiveKey::HkeyLocalMachine, "HKLM"),
            (RegHiveKey::HkeyCurrentUser, "HKCU"),
            (RegHiveKey::HkeyUsers, "HKU"),
            (RegHiveKey::HkeyClassesRoot, "HKCR"),
        ] {
            map.insert(k, p.to_string());
        }
        map
    }
}

fn basic_registry() -> BTreeMap<String, MountedCell> {
    let mut map = BTreeMap::new();
    for k in ["HKLM", "HKCU", "HKCR"] {
        map.insert(k.to_string(), MountedCell::new(k));
    }
    let mut hkcu_cell = MountedCell::new("HKU");
    hkcu_cell.add_value(
        "S-1-5-21-1366093794-4292800403-1155380978-513\\Volatile Environment",
        "USERPROFILE",
        RegValue::from_str(r"C:\Users\Tester"),
    );
    hkcu_cell.add_value(
        "S-1-5-21-1366093794-4292800403-1155380978-513\\Volatile Environment",
        "APPDATA",
        RegValue::from_str(r"C:\Users\Tester\AppData\Roaming"),
    );
    hkcu_cell.add_value(
        "S-1-5-21-1366093794-4292800403-1155380978-513\\Volatile Environment",
        "LOCALAPPDATA",
        RegValue::from_str(r"C:\Users\Tester\AppData\Local"),
    );
    hkcu_cell.add_value(
        "S-1-5-21-1366093794-4292800403-1155380978-513\\Volatile Environment",
        "USERDOMAIN",
        RegValue::from_str(r"TestMachine"),
    );
    hkcu_cell.add_value(
        "S-1-5-21-1366093794-4292800403-1155380978-513\\Volatile Environment",
        "USERNAME",
        RegValue::from_str(r"Tester"),
    );
    map.insert("HKU".into(), hkcu_cell);
    map
}

pub fn init_testing_logger() {
    let rcv = crate::notifications::testing_notifier_dummy();
    std::thread::spawn(move || loop {
        let msg = match rcv.recv() {
            Ok(v) => v,
            Err(_) => return,
        };
        println!(
            "{:?} - {} - {}:{} - {}",
            msg.r#type, msg.module, msg.file, msg.line, msg.data
        );
    });
    let rcv = crate::logging::testing_logger_dummy();
    std::thread::spawn(move || loop {
        let msg = match rcv.recv() {
            Ok(v) => v,
            Err(_) => return,
        };
        println!(
            "{:?} - {} - {}:{} - {}",
            msg.level, msg.module, msg.file, msg.line, msg.data
        );
    });
}