regf 0.1.0

A Rust library for parsing, manipulating, and writing Windows Registry hive files (regf format)
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
//! Subkeys list structures (li, lf, lh, ri).
//!
//! These structures store lists of subkeys for key nodes.

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::io::{self, Cursor, Read, Write};

use crate::error::{Error, Result};
use crate::structures::signatures;

/// Index leaf element (li).
#[derive(Debug, Clone, Copy)]
pub struct IndexLeafElement {
    /// Offset of key node.
    pub key_node_offset: u32,
}

/// Fast leaf element (lf).
///
/// The name hint contains the first 4 ASCII characters of the key name.
/// Per the spec:
/// - If a key name is less than 4 characters, unused bytes are null-padded
/// - UTF-16LE characters are converted to ASCII (extended ASCII if code < 256)
/// - If any character cannot be converted to ASCII, the first byte is null
#[derive(Debug, Clone, Copy)]
pub struct FastLeafElement {
    /// Offset of key node.
    pub key_node_offset: u32,
    /// First 4 characters of key name as ASCII (hint for lookups).
    pub name_hint: [u8; 4],
}

impl FastLeafElement {
    /// Create a name hint from a key name string.
    ///
    /// The hint contains the first 4 ASCII characters of the name.
    /// If any character is not ASCII-compatible (code >= 256), the first byte
    /// is set to null as per the specification.
    pub fn create_name_hint(name: &str) -> [u8; 4] {
        let mut hint = [0u8; 4];
        for (i, c) in name.chars().take(4).enumerate() {
            let code = c as u32;
            if code <= 255 {
                hint[i] = code as u8;
            } else {
                // If any char is not ASCII-compatible, null the first byte per spec
                hint[0] = 0;
                break;
            }
        }
        hint
    }

    /// Get the name hint as a string (for display/debugging).
    pub fn hint_as_string(&self) -> String {
        self.name_hint
            .iter()
            .take_while(|&&b| b != 0)
            .map(|&b| b as char)
            .collect()
    }

    /// Check if the name hint potentially matches a key name.
    /// This is used for quick lookups - a mismatch means definite no match,
    /// but a match requires full name comparison.
    pub fn hint_matches(&self, name: &str) -> bool {
        let target_hint = Self::create_name_hint(name);

        // If either hint has null first byte, can't use for matching
        if self.name_hint[0] == 0 || target_hint[0] == 0 {
            return true; // Must do full comparison
        }

        self.name_hint == target_hint
    }
}

/// Hash leaf element (lh).
#[derive(Debug, Clone, Copy)]
pub struct HashLeafElement {
    /// Offset of key node.
    pub key_node_offset: u32,
    /// Hash of key name.
    pub name_hash: u32,
}

/// Index root element (ri).
#[derive(Debug, Clone, Copy)]
pub struct IndexRootElement {
    /// Offset of subkeys list.
    pub subkeys_list_offset: u32,
}

/// Index leaf list (li).
#[derive(Debug, Clone)]
pub struct IndexLeaf {
    /// Signature: "li"
    pub signature: [u8; 2],
    /// Number of elements.
    pub num_elements: u16,
    /// List elements.
    pub elements: Vec<IndexLeafElement>,
}

impl IndexLeaf {
    /// Fixed header size.
    pub const HEADER_SIZE: usize = 4;

    /// Parse an index leaf from a byte slice.
    pub fn parse(data: &[u8]) -> Result<Self> {
        if data.len() < Self::HEADER_SIZE {
            return Err(Error::BufferTooSmall {
                needed: Self::HEADER_SIZE,
                available: data.len(),
            });
        }

        let mut cursor = Cursor::new(data);

        let mut signature = [0u8; 2];
        cursor.read_exact(&mut signature)?;

        if &signature != signatures::INDEX_LEAF {
            return Err(Error::InvalidSignature {
                expected: "li".to_string(),
                found: String::from_utf8_lossy(&signature).to_string(),
            });
        }

        let num_elements = cursor.read_u16::<LittleEndian>()?;

        let needed = Self::HEADER_SIZE + (num_elements as usize * 4);
        if data.len() < needed {
            return Err(Error::BufferTooSmall {
                needed,
                available: data.len(),
            });
        }

        let mut elements = Vec::with_capacity(num_elements as usize);
        for _ in 0..num_elements {
            let key_node_offset = cursor.read_u32::<LittleEndian>()?;
            elements.push(IndexLeafElement { key_node_offset });
        }

        Ok(Self {
            signature,
            num_elements,
            elements,
        })
    }

    /// Write the index leaf to a writer.
    pub fn write<W: Write>(&self, writer: &mut W) -> io::Result<()> {
        writer.write_all(&self.signature)?;
        writer.write_u16::<LittleEndian>(self.num_elements)?;
        for elem in &self.elements {
            writer.write_u32::<LittleEndian>(elem.key_node_offset)?;
        }
        Ok(())
    }

    /// Create a new index leaf.
    pub fn new() -> Self {
        Self {
            signature: *signatures::INDEX_LEAF,
            num_elements: 0,
            elements: Vec::new(),
        }
    }

    /// Get the total size.
    pub fn total_size(&self) -> usize {
        Self::HEADER_SIZE + (self.elements.len() * 4)
    }

    /// Serialize to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buffer = Vec::new();
        self.write(&mut buffer).unwrap();
        buffer
    }
}

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

/// Fast leaf list (lf).
#[derive(Debug, Clone)]
pub struct FastLeaf {
    /// Signature: "lf"
    pub signature: [u8; 2],
    /// Number of elements.
    pub num_elements: u16,
    /// List elements.
    pub elements: Vec<FastLeafElement>,
}

impl FastLeaf {
    /// Fixed header size.
    pub const HEADER_SIZE: usize = 4;

    /// Parse a fast leaf from a byte slice.
    pub fn parse(data: &[u8]) -> Result<Self> {
        if data.len() < Self::HEADER_SIZE {
            return Err(Error::BufferTooSmall {
                needed: Self::HEADER_SIZE,
                available: data.len(),
            });
        }

        let mut cursor = Cursor::new(data);

        let mut signature = [0u8; 2];
        cursor.read_exact(&mut signature)?;

        if &signature != signatures::FAST_LEAF {
            return Err(Error::InvalidSignature {
                expected: "lf".to_string(),
                found: String::from_utf8_lossy(&signature).to_string(),
            });
        }

        let num_elements = cursor.read_u16::<LittleEndian>()?;

        let needed = Self::HEADER_SIZE + (num_elements as usize * 8);
        if data.len() < needed {
            return Err(Error::BufferTooSmall {
                needed,
                available: data.len(),
            });
        }

        let mut elements = Vec::with_capacity(num_elements as usize);
        for _ in 0..num_elements {
            let key_node_offset = cursor.read_u32::<LittleEndian>()?;
            let mut name_hint = [0u8; 4];
            cursor.read_exact(&mut name_hint)?;
            elements.push(FastLeafElement {
                key_node_offset,
                name_hint,
            });
        }

        Ok(Self {
            signature,
            num_elements,
            elements,
        })
    }

    /// Write the fast leaf to a writer.
    pub fn write<W: Write>(&self, writer: &mut W) -> io::Result<()> {
        writer.write_all(&self.signature)?;
        writer.write_u16::<LittleEndian>(self.num_elements)?;
        for elem in &self.elements {
            writer.write_u32::<LittleEndian>(elem.key_node_offset)?;
            writer.write_all(&elem.name_hint)?;
        }
        Ok(())
    }

    /// Create a new fast leaf.
    pub fn new() -> Self {
        Self {
            signature: *signatures::FAST_LEAF,
            num_elements: 0,
            elements: Vec::new(),
        }
    }

    /// Get the total size.
    pub fn total_size(&self) -> usize {
        Self::HEADER_SIZE + (self.elements.len() * 8)
    }

    /// Serialize to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buffer = Vec::new();
        self.write(&mut buffer).unwrap();
        buffer
    }
}

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

/// Hash leaf list (lh).
#[derive(Debug, Clone)]
pub struct HashLeaf {
    /// Signature: "lh"
    pub signature: [u8; 2],
    /// Number of elements.
    pub num_elements: u16,
    /// List elements.
    pub elements: Vec<HashLeafElement>,
}

impl HashLeaf {
    /// Fixed header size.
    pub const HEADER_SIZE: usize = 4;

    /// Parse a hash leaf from a byte slice.
    pub fn parse(data: &[u8]) -> Result<Self> {
        if data.len() < Self::HEADER_SIZE {
            return Err(Error::BufferTooSmall {
                needed: Self::HEADER_SIZE,
                available: data.len(),
            });
        }

        let mut cursor = Cursor::new(data);

        let mut signature = [0u8; 2];
        cursor.read_exact(&mut signature)?;

        if &signature != signatures::HASH_LEAF {
            return Err(Error::InvalidSignature {
                expected: "lh".to_string(),
                found: String::from_utf8_lossy(&signature).to_string(),
            });
        }

        let num_elements = cursor.read_u16::<LittleEndian>()?;

        let needed = Self::HEADER_SIZE + (num_elements as usize * 8);
        if data.len() < needed {
            return Err(Error::BufferTooSmall {
                needed,
                available: data.len(),
            });
        }

        let mut elements = Vec::with_capacity(num_elements as usize);
        for _ in 0..num_elements {
            let key_node_offset = cursor.read_u32::<LittleEndian>()?;
            let name_hash = cursor.read_u32::<LittleEndian>()?;
            elements.push(HashLeafElement {
                key_node_offset,
                name_hash,
            });
        }

        Ok(Self {
            signature,
            num_elements,
            elements,
        })
    }

    /// Write the hash leaf to a writer.
    pub fn write<W: Write>(&self, writer: &mut W) -> io::Result<()> {
        writer.write_all(&self.signature)?;
        writer.write_u16::<LittleEndian>(self.num_elements)?;
        for elem in &self.elements {
            writer.write_u32::<LittleEndian>(elem.key_node_offset)?;
            writer.write_u32::<LittleEndian>(elem.name_hash)?;
        }
        Ok(())
    }

    /// Create a new hash leaf.
    pub fn new() -> Self {
        Self {
            signature: *signatures::HASH_LEAF,
            num_elements: 0,
            elements: Vec::new(),
        }
    }

    /// Get the total size.
    pub fn total_size(&self) -> usize {
        Self::HEADER_SIZE + (self.elements.len() * 8)
    }

    /// Serialize to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buffer = Vec::new();
        self.write(&mut buffer).unwrap();
        buffer
    }
}

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

/// Index root list (ri).
#[derive(Debug, Clone)]
pub struct IndexRoot {
    /// Signature: "ri"
    pub signature: [u8; 2],
    /// Number of elements.
    pub num_elements: u16,
    /// List elements.
    pub elements: Vec<IndexRootElement>,
}

impl IndexRoot {
    /// Fixed header size.
    pub const HEADER_SIZE: usize = 4;

    /// Parse an index root from a byte slice.
    pub fn parse(data: &[u8]) -> Result<Self> {
        if data.len() < Self::HEADER_SIZE {
            return Err(Error::BufferTooSmall {
                needed: Self::HEADER_SIZE,
                available: data.len(),
            });
        }

        let mut cursor = Cursor::new(data);

        let mut signature = [0u8; 2];
        cursor.read_exact(&mut signature)?;

        if &signature != signatures::INDEX_ROOT {
            return Err(Error::InvalidSignature {
                expected: "ri".to_string(),
                found: String::from_utf8_lossy(&signature).to_string(),
            });
        }

        let num_elements = cursor.read_u16::<LittleEndian>()?;

        let needed = Self::HEADER_SIZE + (num_elements as usize * 4);
        if data.len() < needed {
            return Err(Error::BufferTooSmall {
                needed,
                available: data.len(),
            });
        }

        let mut elements = Vec::with_capacity(num_elements as usize);
        for _ in 0..num_elements {
            let subkeys_list_offset = cursor.read_u32::<LittleEndian>()?;
            elements.push(IndexRootElement { subkeys_list_offset });
        }

        Ok(Self {
            signature,
            num_elements,
            elements,
        })
    }

    /// Write the index root to a writer.
    pub fn write<W: Write>(&self, writer: &mut W) -> io::Result<()> {
        writer.write_all(&self.signature)?;
        writer.write_u16::<LittleEndian>(self.num_elements)?;
        for elem in &self.elements {
            writer.write_u32::<LittleEndian>(elem.subkeys_list_offset)?;
        }
        Ok(())
    }

    /// Create a new index root.
    pub fn new() -> Self {
        Self {
            signature: *signatures::INDEX_ROOT,
            num_elements: 0,
            elements: Vec::new(),
        }
    }

    /// Get the total size.
    pub fn total_size(&self) -> usize {
        Self::HEADER_SIZE + (self.elements.len() * 4)
    }

    /// Serialize to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buffer = Vec::new();
        self.write(&mut buffer).unwrap();
        buffer
    }
}

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

/// Enumeration of all subkeys list types.
#[derive(Debug, Clone)]
pub enum SubkeysList {
    /// Index leaf (li).
    IndexLeaf(IndexLeaf),
    /// Fast leaf (lf).
    FastLeaf(FastLeaf),
    /// Hash leaf (lh).
    HashLeaf(HashLeaf),
    /// Index root (ri).
    IndexRoot(IndexRoot),
}

impl SubkeysList {
    /// Parse a subkeys list from a byte slice.
    pub fn parse(data: &[u8]) -> Result<Self> {
        if data.len() < 2 {
            return Err(Error::BufferTooSmall {
                needed: 2,
                available: data.len(),
            });
        }

        let sig: [u8; 2] = [data[0], data[1]];

        match &sig {
            b"li" => Ok(SubkeysList::IndexLeaf(IndexLeaf::parse(data)?)),
            b"lf" => Ok(SubkeysList::FastLeaf(FastLeaf::parse(data)?)),
            b"lh" => Ok(SubkeysList::HashLeaf(HashLeaf::parse(data)?)),
            b"ri" => Ok(SubkeysList::IndexRoot(IndexRoot::parse(data)?)),
            _ => Err(Error::UnknownCellType(sig)),
        }
    }

    /// Get all key node offsets from this list.
    pub fn get_offsets(&self) -> Vec<u32> {
        match self {
            SubkeysList::IndexLeaf(il) => il.elements.iter().map(|e| e.key_node_offset).collect(),
            SubkeysList::FastLeaf(fl) => fl.elements.iter().map(|e| e.key_node_offset).collect(),
            SubkeysList::HashLeaf(hl) => hl.elements.iter().map(|e| e.key_node_offset).collect(),
            SubkeysList::IndexRoot(ir) => ir.elements.iter().map(|e| e.subkeys_list_offset).collect(),
        }
    }

    /// Check if this is an index root.
    pub fn is_index_root(&self) -> bool {
        matches!(self, SubkeysList::IndexRoot(_))
    }

    /// Serialize to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        match self {
            SubkeysList::IndexLeaf(il) => il.to_bytes(),
            SubkeysList::FastLeaf(fl) => fl.to_bytes(),
            SubkeysList::HashLeaf(hl) => hl.to_bytes(),
            SubkeysList::IndexRoot(ir) => ir.to_bytes(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_index_leaf() {
        let mut il = IndexLeaf::new();
        il.elements.push(IndexLeafElement { key_node_offset: 100 });
        il.elements.push(IndexLeafElement { key_node_offset: 200 });
        il.num_elements = il.elements.len() as u16;

        let bytes = il.to_bytes();
        let parsed = IndexLeaf::parse(&bytes).unwrap();

        assert_eq!(parsed.num_elements, 2);
        assert_eq!(parsed.elements[0].key_node_offset, 100);
        assert_eq!(parsed.elements[1].key_node_offset, 200);
    }

    #[test]
    fn test_hash_leaf() {
        let mut hl = HashLeaf::new();
        hl.elements.push(HashLeafElement {
            key_node_offset: 100,
            name_hash: 12345,
        });
        hl.num_elements = hl.elements.len() as u16;

        let bytes = hl.to_bytes();
        let parsed = HashLeaf::parse(&bytes).unwrap();

        assert_eq!(parsed.num_elements, 1);
        assert_eq!(parsed.elements[0].key_node_offset, 100);
        assert_eq!(parsed.elements[0].name_hash, 12345);
    }
}