Skip to main content

cmtraceopen_parser/parser/
registry.rs

1//! Windows Registry export file (.reg) parser.
2//!
3//! Parses files exported by `regedit.exe` (format version 5.00 and REGEDIT4).
4//! Handles UTF-16LE encoded files via the shared `read_file_content` decoder.
5
6use serde::{Deserialize, Serialize};
7
8/// Registry value type tag, matching Windows registry value kinds.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
10#[serde(rename_all = "camelCase")]
11pub enum RegistryValueKind {
12    String,
13    Dword,
14    Qword,
15    Binary,
16    ExpandString,
17    MultiString,
18    None,
19    DeleteMarker,
20}
21
22/// A single registry value within a key.
23#[derive(Debug, Clone, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub struct RegistryValue {
26    pub name: String,
27    pub kind: RegistryValueKind,
28    pub data: String,
29    pub line_number: u32,
30}
31
32/// A registry key with its path and values.
33#[derive(Debug, Clone, Serialize, Deserialize)]
34#[serde(rename_all = "camelCase")]
35pub struct RegistryKey {
36    pub path: String,
37    pub values: Vec<RegistryValue>,
38    pub line_number: u32,
39    pub is_delete: bool,
40}
41
42/// Result of parsing a .reg file.
43#[derive(Debug, Clone, Serialize, Deserialize)]
44#[serde(rename_all = "camelCase")]
45pub struct RegistryParseResult {
46    pub keys: Vec<RegistryKey>,
47    pub file_path: String,
48    pub file_size: u64,
49    pub total_keys: u32,
50    pub total_values: u32,
51    pub parse_errors: u32,
52}
53
54/// Parse a decoded .reg file content into structured registry data.
55pub fn parse_registry_content(
56    content: &str,
57    file_path: &str,
58    file_size: u64,
59) -> RegistryParseResult {
60    let lines: Vec<&str> = content.lines().collect();
61    let mut keys: Vec<RegistryKey> = Vec::new();
62    let mut current_key: Option<RegistryKey> = None;
63    let mut parse_errors: u32 = 0;
64    let mut total_values: u32 = 0;
65
66    let mut i = 0;
67    // Skip header line(s)
68    while i < lines.len() {
69        let trimmed = lines[i].trim();
70        if trimmed.starts_with("Windows Registry Editor Version")
71            || trimmed.starts_with("REGEDIT4")
72            || trimmed.is_empty()
73        {
74            i += 1;
75        } else {
76            break;
77        }
78    }
79
80    while i < lines.len() {
81        let line = lines[i];
82        let trimmed = line.trim();
83
84        if trimmed.is_empty() {
85            i += 1;
86            continue;
87        }
88
89        // Key line: [HKEY_...] or [-HKEY_...]
90        if trimmed.starts_with('[') && trimmed.ends_with(']') {
91            // Flush previous key
92            if let Some(key) = current_key.take() {
93                keys.push(key);
94            }
95
96            let inner = &trimmed[1..trimmed.len() - 1];
97            let (path, is_delete) = if let Some(stripped) = inner.strip_prefix('-') {
98                (stripped.to_string(), true)
99            } else {
100                (inner.to_string(), false)
101            };
102
103            current_key = Some(RegistryKey {
104                path,
105                values: Vec::new(),
106                line_number: (i + 1) as u32,
107                is_delete,
108            });
109            i += 1;
110            continue;
111        }
112
113        // Value line — only valid inside a key
114        if let Some(ref mut key) = current_key {
115            if let Some(value) = parse_value_line(trimmed, (i + 1) as u32, &lines, &mut i) {
116                total_values += 1;
117                key.values.push(value);
118            } else {
119                parse_errors += 1;
120                i += 1;
121            }
122        } else {
123            parse_errors += 1;
124            i += 1;
125        }
126    }
127
128    // Flush last key
129    if let Some(key) = current_key.take() {
130        keys.push(key);
131    }
132
133    let total_keys = keys.len() as u32;
134
135    RegistryParseResult {
136        keys,
137        file_path: file_path.to_string(),
138        file_size,
139        total_keys,
140        total_values,
141        parse_errors,
142    }
143}
144
145/// Parse a value line, consuming continuation lines for hex data.
146/// Advances `line_idx` past any consumed continuation lines.
147fn parse_value_line(
148    first_line: &str,
149    line_number: u32,
150    all_lines: &[&str],
151    line_idx: &mut usize,
152) -> Option<RegistryValue> {
153    // Default value: @=<data>
154    let (name, data_str) = if let Some(stripped) = first_line.strip_prefix("@=") {
155        ("(Default)".to_string(), stripped)
156    } else if first_line.starts_with('"') {
157        // "name"=<data> or "name"=-
158        let closing_quote = find_closing_quote(first_line, 1)?;
159        let name = unescape_reg_string(&first_line[1..closing_quote]);
160        let after = first_line[closing_quote + 1..].trim_start();
161        if !after.starts_with('=') {
162            return None;
163        }
164        let data_str = after[1..].trim_start();
165        (name, data_str)
166    } else {
167        return None;
168    };
169
170    // Collect full data string, joining continuation lines
171    let mut full_data = data_str.to_string();
172    *line_idx += 1;
173
174    // Handle backslash continuation for hex values
175    while full_data.ends_with('\\') {
176        full_data.pop(); // remove trailing backslash
177        if *line_idx < all_lines.len() {
178            let cont = all_lines[*line_idx].trim();
179            full_data.push_str(cont);
180            *line_idx += 1;
181        } else {
182            break;
183        }
184    }
185
186    let full_data = full_data.trim();
187
188    // Delete marker
189    if full_data == "-" {
190        return Some(RegistryValue {
191            name,
192            kind: RegistryValueKind::DeleteMarker,
193            data: "(value deleted)".to_string(),
194            line_number,
195        });
196    }
197
198    // String value: "..."
199    if full_data.starts_with('"') && full_data.len() >= 2 {
200        let inner = if let Some(close) = find_closing_quote(full_data, 1) {
201            unescape_reg_string(&full_data[1..close])
202        } else {
203            full_data[1..].to_string()
204        };
205        return Some(RegistryValue {
206            name,
207            kind: RegistryValueKind::String,
208            data: inner,
209            line_number,
210        });
211    }
212
213    // DWORD: dword:XXXXXXXX
214    if let Some(hex_str) = full_data.strip_prefix("dword:") {
215        let value = u32::from_str_radix(hex_str.trim(), 16).unwrap_or(0);
216        return Some(RegistryValue {
217            name,
218            kind: RegistryValueKind::Dword,
219            data: format!("0x{:08x} ({})", value, value),
220            line_number,
221        });
222    }
223
224    // hex(b): QWORD
225    if let Some(hex_bytes_str) = full_data.strip_prefix("hex(b):") {
226        let bytes = parse_hex_bytes(hex_bytes_str);
227        let value = bytes_to_qword(&bytes);
228        return Some(RegistryValue {
229            name,
230            kind: RegistryValueKind::Qword,
231            data: format!("0x{:016x} ({})", value, value),
232            line_number,
233        });
234    }
235
236    // hex(2): REG_EXPAND_SZ (UTF-16LE encoded)
237    if let Some(hex_bytes_str) = full_data.strip_prefix("hex(2):") {
238        let bytes = parse_hex_bytes(hex_bytes_str);
239        let decoded = decode_utf16le_bytes(&bytes);
240        return Some(RegistryValue {
241            name,
242            kind: RegistryValueKind::ExpandString,
243            data: decoded,
244            line_number,
245        });
246    }
247
248    // hex(7): REG_MULTI_SZ (UTF-16LE encoded, null-separated)
249    if let Some(hex_bytes_str) = full_data.strip_prefix("hex(7):") {
250        let bytes = parse_hex_bytes(hex_bytes_str);
251        let decoded = decode_utf16le_multi_string(&bytes);
252        return Some(RegistryValue {
253            name,
254            kind: RegistryValueKind::MultiString,
255            data: decoded,
256            line_number,
257        });
258    }
259
260    // hex(0): REG_NONE
261    if let Some(hex_bytes_str) = full_data.strip_prefix("hex(0):") {
262        let bytes = parse_hex_bytes(hex_bytes_str);
263        return Some(RegistryValue {
264            name,
265            kind: RegistryValueKind::None,
266            data: format_hex_display(&bytes),
267            line_number,
268        });
269    }
270
271    // hex: REG_BINARY
272    if let Some(hex_bytes_str) = full_data.strip_prefix("hex:") {
273        let bytes = parse_hex_bytes(hex_bytes_str);
274        return Some(RegistryValue {
275            name,
276            kind: RegistryValueKind::Binary,
277            data: format_hex_display(&bytes),
278            line_number,
279        });
280    }
281
282    // Other hex(N): types — treat as binary
283    if full_data.starts_with("hex(") {
284        if let Some(colon_pos) = full_data.find("):") {
285            let hex_bytes_str = &full_data[colon_pos + 2..];
286            let bytes = parse_hex_bytes(hex_bytes_str);
287            return Some(RegistryValue {
288                name,
289                kind: RegistryValueKind::Binary,
290                data: format_hex_display(&bytes),
291                line_number,
292            });
293        }
294    }
295
296    // Unrecognized format
297    Some(RegistryValue {
298        name,
299        kind: RegistryValueKind::String,
300        data: full_data.to_string(),
301        line_number,
302    })
303}
304
305/// Find closing quote position, handling escaped quotes (\\").
306fn find_closing_quote(s: &str, start: usize) -> Option<usize> {
307    let bytes = s.as_bytes();
308    let mut i = start;
309    while i < bytes.len() {
310        if bytes[i] == b'\\' {
311            i += 2; // skip escaped char
312        } else if bytes[i] == b'"' {
313            return Some(i);
314        } else {
315            i += 1;
316        }
317    }
318    None
319}
320
321/// Unescape a registry string value (handles \\, \").
322fn unescape_reg_string(s: &str) -> String {
323    let mut result = String::with_capacity(s.len());
324    let mut chars = s.chars();
325    while let Some(c) = chars.next() {
326        if c == '\\' {
327            if let Some(next) = chars.next() {
328                match next {
329                    '\\' => result.push('\\'),
330                    '"' => result.push('"'),
331                    'n' => result.push('\n'),
332                    _ => {
333                        result.push('\\');
334                        result.push(next);
335                    }
336                }
337            }
338        } else {
339            result.push(c);
340        }
341    }
342    result
343}
344
345/// Parse comma-separated hex bytes like "01,00,04,80".
346fn parse_hex_bytes(s: &str) -> Vec<u8> {
347    s.split(',')
348        .filter_map(|b| {
349            let trimmed = b.trim();
350            if trimmed.is_empty() {
351                None
352            } else {
353                u8::from_str_radix(trimmed, 16).ok()
354            }
355        })
356        .collect()
357}
358
359/// Convert up to 8 bytes (little-endian) to a u64.
360fn bytes_to_qword(bytes: &[u8]) -> u64 {
361    let mut value: u64 = 0;
362    for (i, &byte) in bytes.iter().take(8).enumerate() {
363        value |= (byte as u64) << (i * 8);
364    }
365    value
366}
367
368/// Decode UTF-16LE bytes to a String, stripping trailing null.
369fn decode_utf16le_bytes(bytes: &[u8]) -> String {
370    if bytes.len() < 2 {
371        return String::new();
372    }
373    let u16_iter = bytes
374        .chunks_exact(2)
375        .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]));
376    let decoded: String = char::decode_utf16(u16_iter)
377        .map(|r| r.unwrap_or('\u{FFFD}'))
378        .collect();
379    decoded.trim_end_matches('\0').to_string()
380}
381
382/// Decode UTF-16LE multi-string (null-separated, double-null terminated).
383fn decode_utf16le_multi_string(bytes: &[u8]) -> String {
384    if bytes.len() < 2 {
385        return String::new();
386    }
387    let u16_iter: Vec<u16> = bytes
388        .chunks_exact(2)
389        .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
390        .collect();
391
392    // Split on null characters, filter empties
393    let strings: Vec<String> = u16_iter
394        .split(|&c| c == 0)
395        .filter(|s| !s.is_empty())
396        .map(|s| {
397            char::decode_utf16(s.iter().copied())
398                .map(|r| r.unwrap_or('\u{FFFD}'))
399                .collect()
400        })
401        .collect();
402
403    strings.join(" | ")
404}
405
406/// Format bytes as hex display string, truncated if long.
407fn format_hex_display(bytes: &[u8]) -> String {
408    if bytes.is_empty() {
409        return "(zero-length binary value)".to_string();
410    }
411    let display_len = bytes.len().min(128);
412    let hex: String = bytes[..display_len]
413        .iter()
414        .map(|b| format!("{:02x}", b))
415        .collect::<Vec<_>>()
416        .join(" ");
417    if bytes.len() > 128 {
418        format!("{} ... ({} bytes total)", hex, bytes.len())
419    } else {
420        hex
421    }
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427
428    #[test]
429    fn test_parse_simple_reg_file() {
430        let content = r#"Windows Registry Editor Version 5.00
431
432[HKEY_LOCAL_MACHINE\SOFTWARE\Test]
433"StringValue"="Hello World"
434"DwordValue"=dword:0000002a
435@="Default Value"
436
437[HKEY_LOCAL_MACHINE\SOFTWARE\Test\SubKey]
438"AnotherValue"="Test"
439"#;
440
441        let result = parse_registry_content(content, "test.reg", 200);
442        assert_eq!(result.total_keys, 2);
443        assert_eq!(result.total_values, 4);
444        assert_eq!(result.parse_errors, 0);
445
446        let key0 = &result.keys[0];
447        assert_eq!(key0.path, r"HKEY_LOCAL_MACHINE\SOFTWARE\Test");
448        assert_eq!(key0.values.len(), 3);
449        assert!(!key0.is_delete);
450
451        assert_eq!(key0.values[0].name, "StringValue");
452        assert_eq!(key0.values[0].kind, RegistryValueKind::String);
453        assert_eq!(key0.values[0].data, "Hello World");
454
455        assert_eq!(key0.values[1].name, "DwordValue");
456        assert_eq!(key0.values[1].kind, RegistryValueKind::Dword);
457        assert_eq!(key0.values[1].data, "0x0000002a (42)");
458
459        assert_eq!(key0.values[2].name, "(Default)");
460        assert_eq!(key0.values[2].data, "Default Value");
461    }
462
463    #[test]
464    fn test_parse_hex_continuation() {
465        let content = r#"Windows Registry Editor Version 5.00
466
467[HKEY_LOCAL_MACHINE\SOFTWARE\Test]
468"BinValue"=hex:01,02,03,\
469  04,05,06
470"#;
471
472        let result = parse_registry_content(content, "test.reg", 100);
473        assert_eq!(result.total_values, 1);
474        assert_eq!(result.keys[0].values[0].kind, RegistryValueKind::Binary);
475        assert_eq!(result.keys[0].values[0].data, "01 02 03 04 05 06");
476    }
477
478    #[test]
479    fn test_parse_expand_string() {
480        // "system32\drivers\HTTP.sys" encoded as UTF-16LE hex
481        let content = "Windows Registry Editor Version 5.00\n\n\
482            [HKEY_LOCAL_MACHINE\\SOFTWARE\\Test]\n\
483            \"Path\"=hex(2):73,00,79,00,73,00,00,00\n";
484
485        let result = parse_registry_content(content, "test.reg", 100);
486        assert_eq!(
487            result.keys[0].values[0].kind,
488            RegistryValueKind::ExpandString
489        );
490        assert_eq!(result.keys[0].values[0].data, "sys");
491    }
492
493    #[test]
494    fn test_parse_delete_key_and_value() {
495        let content = r#"Windows Registry Editor Version 5.00
496
497[-HKEY_LOCAL_MACHINE\SOFTWARE\OldKey]
498
499[HKEY_LOCAL_MACHINE\SOFTWARE\Test]
500"Removed"=-
501"#;
502
503        let result = parse_registry_content(content, "test.reg", 100);
504        assert_eq!(result.total_keys, 2);
505        assert!(result.keys[0].is_delete);
506        assert_eq!(
507            result.keys[1].values[0].kind,
508            RegistryValueKind::DeleteMarker
509        );
510    }
511
512    #[test]
513    fn test_parse_qword() {
514        let content = "Windows Registry Editor Version 5.00\n\n\
515            [HKEY_LOCAL_MACHINE\\SOFTWARE\\Test]\n\
516            \"Big\"=hex(b):ff,ff,00,00,00,00,00,00\n";
517
518        let result = parse_registry_content(content, "test.reg", 100);
519        assert_eq!(result.keys[0].values[0].kind, RegistryValueKind::Qword);
520        assert!(result.keys[0].values[0].data.contains("65535"));
521    }
522
523    #[test]
524    fn test_parse_multi_string() {
525        // "AB\0CD\0\0" encoded as UTF-16LE
526        let content = "Windows Registry Editor Version 5.00\n\n\
527            [HKEY_LOCAL_MACHINE\\SOFTWARE\\Test]\n\
528            \"Multi\"=hex(7):41,00,42,00,00,00,43,00,44,00,00,00,00,00\n";
529
530        let result = parse_registry_content(content, "test.reg", 100);
531        assert_eq!(
532            result.keys[0].values[0].kind,
533            RegistryValueKind::MultiString
534        );
535        assert_eq!(result.keys[0].values[0].data, "AB | CD");
536    }
537
538    #[test]
539    fn test_escaped_string_value() {
540        let content = "Windows Registry Editor Version 5.00\n\n\
541            [HKEY_LOCAL_MACHINE\\SOFTWARE\\Test]\n\
542            \"Path\"=\"C:\\\\Windows\\\\System32\"\n";
543
544        let result = parse_registry_content(content, "test.reg", 100);
545        assert_eq!(result.keys[0].values[0].data, "C:\\Windows\\System32");
546    }
547
548    #[test]
549    fn test_empty_key() {
550        let content = r#"Windows Registry Editor Version 5.00
551
552[HKEY_LOCAL_MACHINE\SOFTWARE\EmptyKey]
553
554[HKEY_LOCAL_MACHINE\SOFTWARE\NextKey]
555"Value"="test"
556"#;
557
558        let result = parse_registry_content(content, "test.reg", 100);
559        assert_eq!(result.total_keys, 2);
560        assert_eq!(result.keys[0].values.len(), 0);
561        assert_eq!(result.keys[1].values.len(), 1);
562    }
563
564    #[test]
565    fn test_parse_empty_file() {
566        let content = "Windows Registry Editor Version 5.00\n\n";
567        let result = parse_registry_content(content, "empty.reg", 40);
568        assert_eq!(result.total_keys, 0);
569        assert_eq!(result.total_values, 0);
570        assert_eq!(result.parse_errors, 0);
571    }
572}