rusthound-ce 2.5.8

Active Directory data collector for Bloodhound Community Edition written in rust.
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
590
591
592
593
594
use crate::modules::gpo::types::{
    GpoError, GptTmplPolicy, PrivilegeAssignment, RestrictedGroupDirective,
    RestrictedGroupOperation,
};

/// Decodes raw bytes of a GptTmpl.inf security template into a UTF-8 `String`.
///
/// # Encodings
/// - **Canonical protocol encoding**: UTF-16LE with BOM (`0xFF 0xFE`) per Microsoft MS-GPSB section 2.2.
/// - **Additional tolerated encodings**: Defensively accepts UTF-8, UTF-8 with BOM, UTF-16BE with BOM,
///   and UTF-16LE without BOM for collector resilience.
///
/// Rejects incompatible UTF-32 BOMs and truncated/malformed byte sequences with [`GpoError::InvalidEncoding`].
pub fn decode_gpttmpl_bytes(raw: &[u8]) -> Result<String, GpoError> {
    if raw.is_empty() {
        return Ok(String::new());
    }

    // Check for UTF-32 BOMs first to prevent UTF-32LE (0xFF 0xFE 0x00 0x00)
    // from being misidentified as UTF-16LE (0xFF 0xFE).
    if raw.starts_with(&[0x00, 0x00, 0xFE, 0xFF]) {
        return Err(GpoError::InvalidEncoding(
            "Unsupported UTF-32BE encoding".to_string(),
        ));
    }
    if raw.starts_with(&[0xFF, 0xFE, 0x00, 0x00]) {
        return Err(GpoError::InvalidEncoding(
            "Unsupported UTF-32LE encoding".to_string(),
        ));
    }

    // UTF-8 BOM: 0xEF, 0xBB, 0xBF
    if raw.starts_with(&[0xEF, 0xBB, 0xBF]) {
        return std::str::from_utf8(&raw[3..])
            .map(|s| s.to_string())
            .map_err(|e| GpoError::InvalidEncoding(format!("Invalid UTF-8 after BOM: {e}")));
    }

    // UTF-16LE BOM: 0xFF, 0xFE (Canonical per MS-GPSB)
    if raw.starts_with(&[0xFF, 0xFE]) {
        return decode_utf16le(&raw[2..]);
    }

    // UTF-16BE BOM: 0xFE, 0xFF
    if raw.starts_with(&[0xFE, 0xFF]) {
        return decode_utf16be(&raw[2..]);
    }

    // Attempt standard UTF-8 first (valid ASCII is also valid UTF-8)
    if let Ok(s) = std::str::from_utf8(raw) {
        return Ok(s.to_string());
    }

    // If UTF-8 fails and byte length is even, check for UTF-16LE heuristic (common in Windows INF files)
    if raw.len() >= 2 && raw.len() % 2 == 0 && raw[1] == 0 {
        if let Ok(s) = decode_utf16le(raw) {
            return Ok(s);
        }
    }

    Err(GpoError::InvalidEncoding(
        "Unable to decode policy bytes: unrecognized or corrupted character encoding".to_string(),
    ))
}

/// Decodes UTF-16LE byte slice into a String.
fn decode_utf16le(bytes: &[u8]) -> Result<String, GpoError> {
    if bytes.len() % 2 != 0 {
        return Err(GpoError::InvalidEncoding(
            "Truncated UTF-16LE sequence (odd byte count)".to_string(),
        ));
    }

    let u16_units: Vec<u16> = bytes
        .chunks_exact(2)
        .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
        .collect();

    char::decode_utf16(u16_units)
        .collect::<Result<String, _>>()
        .map_err(|e| GpoError::InvalidEncoding(format!("Invalid UTF-16LE code point: {e}")))
}

/// Decodes UTF-16BE byte slice into a String.
fn decode_utf16be(bytes: &[u8]) -> Result<String, GpoError> {
    if bytes.len() % 2 != 0 {
        return Err(GpoError::InvalidEncoding(
            "Truncated UTF-16BE sequence (odd byte count)".to_string(),
        ));
    }

    let u16_units: Vec<u16> = bytes
        .chunks_exact(2)
        .map(|chunk| u16::from_be_bytes([chunk[0], chunk[1]]))
        .collect();

    char::decode_utf16(u16_units)
        .collect::<Result<String, _>>()
        .map_err(|e| GpoError::InvalidEncoding(format!("Invalid UTF-16BE code point: {e}")))
}

/// Parses a decoded `GptTmpl.inf` content string into a structured `GptTmplPolicy`.
/// Returns `Err(GpoError::MalformedContent)` for malformed assignments in
/// `[Privilege Rights]` or `[Group Membership]`.
///
/// # Comments and Syntax
/// Per Microsoft Windows INF specifications and MS-GPSB section 2.2.6:
/// - Semicolon (`;`) is the comment delimiter.
/// - Character `#` is valid in principal names (e.g. `svc#backup`) and is NOT treated as a comment delimiter.
/// - Empty assignments (e.g. `SeTcbPrivilege = `) represent privileges with zero assigned principals.
pub fn parse_gpttmpl(content: &str) -> Result<GptTmplPolicy, GpoError> {
    let mut current_section: Option<String> = None;
    let mut privilege_rights: Vec<PrivilegeAssignment> = Vec::new();
    let mut restricted_groups: Vec<RestrictedGroupDirective> = Vec::new();

    for (line_idx, line) in content.lines().enumerate() {
        let line_no = line_idx + 1;
        let trimmed = line.trim();

        // Skip empty lines and full-line comments starting with ';'
        if trimmed.is_empty() || trimmed.starts_with(';') {
            continue;
        }

        // Section header: [Section Name]
        if trimmed.starts_with('[') && trimmed.ends_with(']') {
            let section_name = trimmed[1..trimmed.len() - 1].trim();
            current_section = Some(section_name.to_ascii_lowercase());
            continue;
        }

        // Parse section entries
        if let Some(ref section) = current_section {
            if section == "privilege rights" {
                let (raw_key, raw_val) = trimmed.split_once('=').ok_or_else(|| {
                    GpoError::MalformedContent(format!(
                        "invalid privilege assignment at line {line_no}: missing '='"
                    ))
                })?;

                let privilege = raw_key.trim();
                if privilege.is_empty() {
                    return Err(GpoError::MalformedContent(format!(
                        "invalid privilege assignment at line {line_no}: empty privilege name"
                    )));
                }

                // Strip inline comment starting with ';'
                let val_clean = match raw_val.find(';') {
                    Some(idx) => &raw_val[..idx],
                    None => raw_val,
                };

                let mut principals = Vec::new();
                for part in val_clean.split(',') {
                    let principal = part.trim();
                    if !principal.is_empty() && !principals.contains(&principal.to_string()) {
                        principals.push(principal.to_string());
                    }
                }

                // Check if this privilege was already assigned in a previous line
                if let Some(existing) = privilege_rights
                    .iter_mut()
                    .find(|p| p.privilege().eq_ignore_ascii_case(privilege))
                {
                    let mut merged = existing.principals().to_vec();
                    for p in principals {
                        if !merged.contains(&p) {
                            merged.push(p);
                        }
                    }
                    *existing = PrivilegeAssignment::new(existing.privilege().to_string(), merged);
                } else {
                    privilege_rights
                        .push(PrivilegeAssignment::new(privilege.to_string(), principals));
                }
            } else if section == "group membership" {
                let (raw_key, raw_val) = trimmed.split_once('=').ok_or_else(|| {
                    GpoError::MalformedContent(format!(
                        "invalid group membership entry at line {line_no}: missing '='"
                    ))
                })?;
                let key = raw_key.trim();
                let key_lower = key.to_ascii_lowercase();
                let (target, operation) = if key_lower.ends_with("__members") {
                    (
                        &key[..key.len() - "__Members".len()],
                        RestrictedGroupOperation::ReplaceMembers,
                    )
                } else if key_lower.ends_with("__memberof") {
                    (
                        &key[..key.len() - "__Memberof".len()],
                        RestrictedGroupOperation::AddToParentGroups,
                    )
                } else {
                    return Err(GpoError::MalformedContent(format!(
                        "invalid group membership entry at line {line_no}: expected __Members or __Memberof suffix"
                    )));
                };
                let target = target.trim();
                if target.is_empty() {
                    return Err(GpoError::MalformedContent(format!(
                        "invalid group membership entry at line {line_no}: empty target group"
                    )));
                }
                let val_clean = raw_val.split(';').next().unwrap_or_default();
                let principals = val_clean
                    .split(',')
                    .map(str::trim)
                    .filter(|value| !value.is_empty())
                    .map(str::to_string)
                    .collect();
                restricted_groups
                    .push(RestrictedGroupDirective::new(target, operation, principals));
            }
        }
    }

    Ok(GptTmplPolicy::with_entries(
        privilege_rights,
        restricted_groups,
    ))
}

/// Parses raw bytes of a `GptTmpl.inf` security template directly into a `GptTmplPolicy`.
pub fn parse_gpttmpl_bytes(raw: &[u8]) -> Result<GptTmplPolicy, GpoError> {
    let decoded = decode_gpttmpl_bytes(raw)?;
    parse_gpttmpl(&decoded)
}

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

    #[test]
    fn parse_standard_privilege_rights_synthetic() {
        let content = r#"
[Unicode]
Unicode=yes
[Version]
signature="$CHICAGO$"
revision=1
[Privilege Rights]
SeDebugPrivilege = *S-1-5-32-544
SeBackupPrivilege = *S-1-5-21-111-222-333-1001,*S-1-5-32-544
SeRemoteInteractiveLogonRight = *S-1-5-32-555
"#;

        let policy = parse_gpttmpl(content).expect("parsing should succeed");
        assert_eq!(policy.privilege_rights().len(), 3);

        let debug_priv = policy.get_privilege("SeDebugPrivilege").unwrap();
        assert_eq!(debug_priv.principals(), &["*S-1-5-32-544"]);
        assert_eq!(
            debug_priv.normalized_principals().collect::<Vec<_>>(),
            vec!["S-1-5-32-544"]
        );

        let backup_priv = policy.get_privilege("SeBackupPrivilege").unwrap();
        assert_eq!(
            backup_priv.principals(),
            &["*S-1-5-21-111-222-333-1001", "*S-1-5-32-544"]
        );
        assert_eq!(
            backup_priv.sid_candidates().collect::<Vec<_>>(),
            vec!["S-1-5-21-111-222-333-1001", "S-1-5-32-544"]
        );

        let rdp_priv = policy
            .get_privilege("SeRemoteInteractiveLogonRight")
            .unwrap();
        assert_eq!(rdp_priv.principals(), &["*S-1-5-32-555"]);
    }

    #[test]
    fn parse_handles_crlf_and_whitespace_and_comments() {
        let content = "; Header comment\r\n\r\n[Privilege Rights]\r\n  SeImpersonatePrivilege  =  *S-1-5-32-544 , *S-1-5-19  ; inline comment\r\nSeTcbPrivilege = \r\n";
        let policy = parse_gpttmpl(content).expect("parsing should succeed");

        let imp = policy.get_privilege("SeImpersonatePrivilege").unwrap();
        assert_eq!(imp.principals(), &["*S-1-5-32-544", "*S-1-5-19"]);
        assert_eq!(
            imp.sid_candidates().collect::<Vec<_>>(),
            vec!["S-1-5-32-544", "S-1-5-19"]
        );

        let tcb = policy.get_privilege("SeTcbPrivilege").unwrap();
        assert!(tcb.principals().is_empty());
    }

    #[test]
    fn parse_preserves_hash_character_in_principals_per_ms_gpsb() {
        // MS-GPSB section 2.2.6 allows '%' and '#' in PRINCIPALNAMESTRING.
        // '#' must NOT be treated as a comment delimiter.
        let content1 = "[Privilege Rights]\nSeServiceLogonRight = svc#backup\n";
        let policy1 = parse_gpttmpl(content1).unwrap();
        let p1 = policy1.get_privilege("SeServiceLogonRight").unwrap();
        assert_eq!(p1.principals(), &["svc#backup"]);

        // With standard ';' comment after '#' in principal name
        let content2 = "[Privilege Rights]\nSeServiceLogonRight = svc#backup ; valid comment\n";
        let policy2 = parse_gpttmpl(content2).unwrap();
        let p2 = policy2.get_privilege("SeServiceLogonRight").unwrap();
        assert_eq!(p2.principals(), &["svc#backup"]);
    }

    #[test]
    fn parse_rejects_malformed_lines_in_privilege_rights() {
        // Missing '=' delimiter (e.g. colon used instead)
        let bad_content1 = "[Privilege Rights]\nSeDebugPrivilege : *S-1-5-32-544\n";
        let err1 = parse_gpttmpl(bad_content1).unwrap_err();
        match err1 {
            GpoError::MalformedContent(msg) => {
                assert!(msg.contains("line 2"));
                assert!(msg.contains("missing '='"));
            }
            other => panic!("Unexpected error type: {other:?}"),
        }

        // Empty privilege key
        let bad_content2 = "[Privilege Rights]\n = *S-1-5-32-544\n";
        let err2 = parse_gpttmpl(bad_content2).unwrap_err();
        match err2 {
            GpoError::MalformedContent(msg) => {
                assert!(msg.contains("line 2"));
                assert!(msg.contains("empty privilege name"));
            }
            other => panic!("Unexpected error type: {other:?}"),
        }
    }

    #[test]
    fn parses_restricted_groups_without_applying_graph_semantics() {
        let content = r#"
[Group Membership]
*S-1-5-32-544__Members = *S-1-5-21-1-2-3-1001,DOMAIN\Helpdesk
DOMAIN\Helpdesk__Memberof = *S-1-5-32-555
*S-1-5-32-546__Members =
"#;
        let policy = parse_gpttmpl(content).unwrap();
        let directives = policy.restricted_groups();
        assert_eq!(directives.len(), 3);
        assert_eq!(directives[0].target(), "*S-1-5-32-544");
        assert_eq!(
            directives[0].operation(),
            RestrictedGroupOperation::ReplaceMembers
        );
        assert_eq!(
            directives[0].principals(),
            &["*S-1-5-21-1-2-3-1001", "DOMAIN\\Helpdesk"]
        );
        assert_eq!(
            directives[1].operation(),
            RestrictedGroupOperation::AddToParentGroups
        );
        assert!(directives[2].principals().is_empty());
    }

    #[test]
    fn rejects_unknown_restricted_group_suffixes() {
        let content = "[Group Membership]\nAdministrators__Unknown = DOMAIN\\alice\n";
        assert!(matches!(
            parse_gpttmpl(content),
            Err(GpoError::MalformedContent(_))
        ));
    }

    #[test]
    fn restricted_groups_preserve_comments_crlf_names_and_empty_values() {
        let content = "; synthetic fixture\r\n[Group Membership]\r\n  Local Operators__Members = DOMAIN\\alice, svc#backup ; comment\r\nLocal Operators__Memberof = *S-1-5-32-544, *S-1-5-32-555\r\nEmpty Group__Memberof = ; empty membership\r\n";
        let policy = parse_gpttmpl(content).unwrap();
        let groups = policy.restricted_groups();
        assert_eq!(groups.len(), 3);
        assert_eq!(groups[0].target(), "Local Operators");
        assert_eq!(
            groups[0].operation(),
            RestrictedGroupOperation::ReplaceMembers
        );
        assert_eq!(groups[0].principals(), &["DOMAIN\\alice", "svc#backup"]);
        assert_eq!(groups[1].target(), "Local Operators");
        assert_eq!(
            groups[1].operation(),
            RestrictedGroupOperation::AddToParentGroups
        );
        assert_eq!(groups[1].principals(), &["*S-1-5-32-544", "*S-1-5-32-555"]);
        assert!(groups[2].principals().is_empty());
    }

    #[test]
    fn restricted_groups_reject_missing_equals_and_empty_targets() {
        for entry in [
            "Administrators__Members : DOMAIN\\alice",
            "__Members = DOMAIN\\alice",
            "__Memberof = *S-1-5-32-544",
        ] {
            assert!(matches!(
                parse_gpttmpl(&format!("[Group Membership]\n{entry}\n")),
                Err(GpoError::MalformedContent(_))
            ));
        }
    }

    #[test]
    fn restricted_groups_decode_canonical_utf16le() {
        let text = "[Group Membership]\r\n*S-1-5-32-544__Members = DOMAIN\\alice, *S-1-5-21-1-2-3-1001\r\nLocal Operators__Memberof = *S-1-5-32-555\r\n";
        let mut bytes = vec![0xFF, 0xFE];
        for unit in text.encode_utf16() {
            bytes.extend_from_slice(&unit.to_le_bytes());
        }
        let policy = parse_gpttmpl_bytes(&bytes).unwrap();
        let groups = policy.restricted_groups();
        assert_eq!(groups.len(), 2);
        assert_eq!(groups[0].target(), "*S-1-5-32-544");
        assert_eq!(
            groups[0].operation(),
            RestrictedGroupOperation::ReplaceMembers
        );
        assert_eq!(
            groups[0].principals(),
            &["DOMAIN\\alice", "*S-1-5-21-1-2-3-1001"]
        );
        assert_eq!(
            groups[1].operation(),
            RestrictedGroupOperation::AddToParentGroups
        );
        assert_eq!(groups[1].principals(), &["*S-1-5-32-555"]);
    }

    #[test]
    fn parse_handles_utf16le_with_bom() {
        let text = "[Privilege Rights]\r\nSeDebugPrivilege = *S-1-5-32-544\r\n";
        let mut bytes = vec![0xFF, 0xFE]; // UTF-16LE BOM
        for u in text.encode_utf16() {
            bytes.extend_from_slice(&u.to_le_bytes());
        }

        let policy =
            parse_gpttmpl_bytes(&bytes).expect("UTF-16LE with BOM should decode and parse");
        let debug_priv = policy.get_privilege("SeDebugPrivilege").unwrap();
        assert_eq!(debug_priv.principals(), &["*S-1-5-32-544"]);
    }

    #[test]
    fn parse_handles_utf16be_with_bom() {
        let text = "[Privilege Rights]\r\nSeSecurityPrivilege = *S-1-5-32-544\r\n";
        let mut bytes = vec![0xFE, 0xFF]; // UTF-16BE BOM
        for u in text.encode_utf16() {
            bytes.extend_from_slice(&u.to_be_bytes());
        }

        let policy =
            parse_gpttmpl_bytes(&bytes).expect("UTF-16BE with BOM should decode and parse");
        let sec_priv = policy.get_privilege("SeSecurityPrivilege").unwrap();
        assert_eq!(sec_priv.principals(), &["*S-1-5-32-544"]);
    }

    #[test]
    fn parse_handles_utf8_with_bom() {
        let text = "[Privilege Rights]\r\nSeTakeOwnershipPrivilege = *S-1-5-32-544\r\n";
        let mut bytes = vec![0xEF, 0xBB, 0xBF]; // UTF-8 BOM
        bytes.extend_from_slice(text.as_bytes());

        let policy = parse_gpttmpl_bytes(&bytes).expect("UTF-8 with BOM should decode and parse");
        let own_priv = policy.get_privilege("SeTakeOwnershipPrivilege").unwrap();
        assert_eq!(own_priv.principals(), &["*S-1-5-32-544"]);
    }

    #[test]
    fn decode_rejects_utf32_boms() {
        let utf32le = vec![0xFF, 0xFE, 0x00, 0x00, 0x5B, 0x00, 0x00, 0x00];
        let err_le = decode_gpttmpl_bytes(&utf32le).unwrap_err();
        match err_le {
            GpoError::InvalidEncoding(msg) => assert!(msg.contains("UTF-32LE")),
            other => panic!("Unexpected error type: {other:?}"),
        }

        let utf32be = vec![0x00, 0x00, 0xFE, 0xFF, 0x00, 0x00, 0x00, 0x5B];
        let err_be = decode_gpttmpl_bytes(&utf32be).unwrap_err();
        match err_be {
            GpoError::InvalidEncoding(msg) => assert!(msg.contains("UTF-32BE")),
            other => panic!("Unexpected error type: {other:?}"),
        }
    }

    #[test]
    fn decode_rejects_invalid_utf16_surrogates() {
        // 0xD800 is an unpaired high surrogate
        let mut bytes = vec![0xFF, 0xFE];
        bytes.extend_from_slice(&0xD800u16.to_le_bytes());
        bytes.extend_from_slice(&0x0020u16.to_le_bytes()); // space

        let err = decode_gpttmpl_bytes(&bytes).unwrap_err();
        match err {
            GpoError::InvalidEncoding(msg) => assert!(msg.contains("Invalid UTF-16LE")),
            other => panic!("Unexpected error type: {other:?}"),
        }
    }

    #[test]
    fn parse_empty_and_missing_sections() {
        let empty_policy = parse_gpttmpl_bytes(b"").unwrap();
        assert!(empty_policy.privilege_rights().is_empty());

        let other_section = "[Version]\r\nsignature=\"$CHICAGO$\"\r\n";
        let policy_other = parse_gpttmpl(other_section).unwrap();
        assert!(policy_other.privilege_rights().is_empty());
    }

    #[test]
    fn parse_handles_duplicates_and_merges() {
        let content = r#"
[Privilege Rights]
SeDebugPrivilege = *S-1-5-32-544, *S-1-5-32-544
SeDebugPrivilege = *S-1-5-32-545
"#;
        let policy = parse_gpttmpl(content).unwrap();
        let debug_priv = policy.get_privilege("SeDebugPrivilege").unwrap();
        assert_eq!(debug_priv.principals(), &["*S-1-5-32-544", "*S-1-5-32-545"]);
    }

    #[test]
    fn parse_arbitrary_unknown_privilege_names_and_non_sid_principals() {
        let content = "[Privilege Rights]\nSeCustomPrivilege = *S-1-5-21-999-888-777-1000, DOMAIN\\CustomGroup\n";
        let policy = parse_gpttmpl(content).unwrap();
        let custom = policy.get_privilege("SeCustomPrivilege").unwrap();
        assert_eq!(
            custom.principals(),
            &["*S-1-5-21-999-888-777-1000", "DOMAIN\\CustomGroup"]
        );
        assert_eq!(
            custom.normalized_principals().collect::<Vec<_>>(),
            vec!["S-1-5-21-999-888-777-1000", "DOMAIN\\CustomGroup"]
        );
        assert_eq!(
            custom.sid_candidates().collect::<Vec<_>>(),
            vec!["S-1-5-21-999-888-777-1000"]
        );
    }

    #[test]
    fn decode_truncated_utf16_returns_error_without_panic() {
        let odd_bytes = vec![0xFF, 0xFE, 0x41]; // 3 bytes (BOM + 1 byte)
        let result = decode_gpttmpl_bytes(&odd_bytes);
        assert!(result.is_err());
        match result.unwrap_err() {
            GpoError::InvalidEncoding(msg) => assert!(msg.contains("Truncated")),
            other => panic!("Unexpected error type: {other:?}"),
        }
    }

    #[test]
    fn parse_handles_mixed_sections_and_case_insensitivity() {
        let content = r#"
[Version]
signature="$CHICAGO$"
revision=1

[PRIVILEGE RIGHTS]
SeAssignPrimaryTokenPrivilege = *S-1-5-19, *S-1-5-20

[Group Membership]
*S-1-5-32-544__Members = *S-1-5-21-1-2-3-500

[System Access]
MinimumPasswordAge = 1
"#;
        let policy = parse_gpttmpl(content).unwrap();
        assert_eq!(policy.privilege_rights().len(), 1);
        let priv_assign = policy
            .get_privilege("SeAssignPrimaryTokenPrivilege")
            .unwrap();
        assert_eq!(priv_assign.principals(), &["*S-1-5-19", "*S-1-5-20"]);
        assert_eq!(
            priv_assign.sid_candidates().collect::<Vec<_>>(),
            vec!["S-1-5-19", "S-1-5-20"]
        );
    }

    #[test]
    fn parse_handles_trailing_comma_and_non_asterisk_sids() {
        let content = r#"
[Privilege Rights]
SeLoadDriverPrivilege = S-1-5-32-544, *S-1-5-32-545,
"#;
        let policy = parse_gpttmpl(content).unwrap();
        let load_driver = policy.get_privilege("SeLoadDriverPrivilege").unwrap();
        assert_eq!(load_driver.principals(), &["S-1-5-32-544", "*S-1-5-32-545"]);
        assert_eq!(
            load_driver.sid_candidates().collect::<Vec<_>>(),
            vec!["S-1-5-32-544", "S-1-5-32-545"]
        );
    }
}