img4-dump 3.0.0

Extracts payloads and metadata from Apple IMG4/IM4P/IM4M/IM4R; decrypts with user-supplied IV+Key; optional LZFSE/LZSS decompress.
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
use anyhow::{anyhow, bail, Result};
use der_parser::der::{parse_der, Class, DerObject};
use serde::Serialize;
use log::{debug, warn};
use std::collections::HashMap;
use once_cell::sync::Lazy;

/// Top-level kind detected
#[derive(Copy, Clone, Debug, Serialize)]
pub enum ContainerKind {
    Img4,
    Im4pStandalone,
    Im4mStandalone,
}

/// Fully-owned parse result (no lifetime ties to local parser temps)
#[derive(Debug)]
pub struct Parsed {
    pub kind: ContainerKind,
    pub im4p: Option<Im4p>,
    pub im4m: Option<Im4m>,
    pub im4r: Option<Vec<u8>>,
}

#[derive(Debug, Clone)]
pub struct KbagEntry {
    pub kclass: u64,   // 1=prod, 2=dev
    pub iv: Vec<u8>,   // 16 bytes
    pub key: Vec<u8>,  // 16/24/32 bytes
}

/// Redacted, JSON-safe view of a KBAG entry. The raw IV and (potentially
/// plaintext) AES key are NEVER serialized into the summary — only their
/// lengths and the key class are exposed. The cleartext bytes remain available
/// internally (on `KbagEntry`) solely for the explicit `--decrypt` path.
#[derive(Debug, Clone, Serialize)]
pub struct KbagEntryInfo {
    pub kclass: u64,
    pub iv_len: usize,
    pub key_len: usize,
}

impl From<&KbagEntry> for KbagEntryInfo {
    fn from(e: &KbagEntry) -> Self {
        KbagEntryInfo { kclass: e.kclass, iv_len: e.iv.len(), key_len: e.key.len() }
    }
}

/// Human/JSON-facing compression descriptor.
#[derive(Debug, Clone, Serialize)]
pub struct CompressionInfo {
    pub algorithm: String,                 // "lzss" | "lzfse" | "unknown(<id>)"
    pub method_id: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uncompressed_size: Option<u64>,
}

impl From<&Im4pCompression> for CompressionInfo {
    fn from(c: &Im4pCompression) -> Self {
        let algorithm = match c.method_id {
            0 => "lzss".to_string(),
            1 => "lzfse".to_string(),
            other => format!("unknown({other})"),
        };
        CompressionInfo { algorithm, method_id: c.method_id, uncompressed_size: c.uncompressed_len }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct Im4pCompression {
    pub method_id: u64,                 // 0=LZSS, 1=LZFSE (A1)
    pub uncompressed_len: Option<u64>,  // may be absent in some images
}

#[derive(Debug)]
pub struct Im4p {
    pub r#type: String,
    pub version: String,
    pub data: Vec<u8>,
    pub kbag_der: Option<Vec<u8>>,
    pub kbag_summary: Option<Vec<KbagEntry>>,
    pub compression: Option<Im4pCompression>,
    /// Payload-scoped properties from the with-properties (PAYP) IM4P variant.
    pub payload_properties: Option<Vec<TypedIm4mProperty>>,
}

#[derive(Debug)]
pub struct Im4m {
    /// Raw DER bytes of the IM4M sequence (owned).
    pub raw: Vec<u8>,
}

/// Legacy untyped property value (kept for backwards compatibility)
#[allow(dead_code)]
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", content = "value")]
pub enum Im4mValue {
    Integer(u128),                     // DER INTEGER (non-negative, as commonly used in IM4M)
    Boolean(bool),                     // DER BOOLEAN
    Ia5String(String),                 // DER IA5String
    OctetString(String),               // hex
    BitString(String),                 // hex (unused bits not modeled)
    Null,                              // DER NULL
    SequenceLen(usize),                // for unexpected SEQUENCE payloads
    SetLen(usize),                     // for unexpected SET payloads
    Unknown { class_id: u8, tag: u32, len: usize },
}

/// Legacy untyped property structure (kept for backwards compatibility)
#[allow(dead_code)]
#[derive(Debug, Clone, Serialize)]
pub struct Im4mProperty {
    pub key: String,   // 4-char IA5 tag (e.g., "DGST","CEPO")
    pub value: Im4mValue,
}

/// Enhanced property value with type information
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub enum Im4mPropertyValue {
    Integer { value: u64 },
    Boolean { value: bool },
    String { value: String },
    OctetString { value: String }, // Hex-encoded
    Digest { value: String },      // Hex-encoded, specifically for properties known to be digests
    Unknown { der_type: String, #[serde(skip_serializing_if = "Option::is_none")] hex_value: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] hex_values: Option<Vec<String>> },
}

/// Typed property structure with metadata
#[derive(Debug, Clone, Serialize)]
pub struct TypedIm4mProperty {
    pub key: String,
    pub name: String,
    pub description: String,
    pub value: Im4mPropertyValue,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anomaly: Option<String>,
}

/// Image manifest structure (kept for future use)
#[allow(dead_code)]
#[derive(Debug, Clone, Serialize)]
pub struct Im4mImageManifest {
    pub fourcc: String,  // e.g. "krnl", "bstc"
    pub properties: Vec<Im4mProperty>,
}

#[derive(Debug, Clone, Serialize)]
pub struct Im4pInfo {
    pub r#type: String,
    pub version: String,
    pub data_len: usize,
    pub kbag: Option<Vec<KbagEntryInfo>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compression: Option<CompressionInfo>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payload_properties: Option<Vec<TypedIm4mProperty>>,
}

#[derive(Debug, Clone, Serialize)]
pub struct Im4mInfoSummary {
    pub version: Option<u64>,
    pub manifest_property_tags: Vec<String>,
    pub images_present: Vec<String>,
    pub cert_chain_len: Option<usize>,
    pub signature_len: Option<usize>,
}

/// Property metadata from XNU headers
struct PropertyMetadata {
    name: &'static str,
    description: &'static str,
    expected_type: ExpectedDerType,
}

#[derive(Debug)]
enum ExpectedDerType {
    Boolean,
    Integer,
    OctetString,
    Digest,
    Ia5String,
}

/// Known Image4 properties from XNU headers
static KNOWN_PROPERTIES: Lazy<HashMap<&'static str, PropertyMetadata>> = Lazy::new(|| {
    let mut m = HashMap::new();
    m.insert("CEPO", PropertyMetadata { name: "ChipEpoch", description: "Chip Epoch", expected_type: ExpectedDerType::Integer });
    m.insert("BORD", PropertyMetadata { name: "BoardId", description: "Board Identifier", expected_type: ExpectedDerType::Integer });
    m.insert("CHIP", PropertyMetadata { name: "ChipId", description: "Chip Identifier", expected_type: ExpectedDerType::Integer });
    m.insert("SDOM", PropertyMetadata { name: "SecurityDomain", description: "Security Domain", expected_type: ExpectedDerType::Integer });
    m.insert("ECID", PropertyMetadata { name: "ExclusiveChipId", description: "Unique Chip Identifier", expected_type: ExpectedDerType::Integer });
    m.insert("CPRO", PropertyMetadata { name: "CertificateProductionStatus", description: "Certificate Production Status", expected_type: ExpectedDerType::Boolean });
    m.insert("CSEC", PropertyMetadata { name: "CertificateSecurityMode", description: "Certificate Security Mode", expected_type: ExpectedDerType::Boolean });
    m.insert("EPRO", PropertyMetadata { name: "EffectiveProductionStatus", description: "Effective Production Status", expected_type: ExpectedDerType::Boolean });
    m.insert("ESEC", PropertyMetadata { name: "EffectiveSecurityMode", description: "Effective Security Mode", expected_type: ExpectedDerType::Boolean });
    m.insert("IUOU", PropertyMetadata { name: "InternalUseOnlyUnit", description: "Internal Use Only Unit", expected_type: ExpectedDerType::Boolean });
    m.insert("AMNM", PropertyMetadata { name: "AllowMixNMatch", description: "Allow Mix-n-Match", expected_type: ExpectedDerType::Boolean });
    m.insert("UDID", PropertyMetadata { name: "UniqueDeviceIdentifier", description: "Unique Device Identifier (digest)", expected_type: ExpectedDerType::Digest });
    m.insert("DGST", PropertyMetadata { name: "Digest", description: "Payload Digest", expected_type: ExpectedDerType::Digest });
    m.insert("BNCN", PropertyMetadata { name: "BootNonce", description: "Boot Nonce", expected_type: ExpectedDerType::OctetString });
    m.insert("love", PropertyMetadata { name: "LongOsVersion", description: "Long OS Version", expected_type: ExpectedDerType::Ia5String });
    m.insert("augs", PropertyMetadata { name: "AugmentedManifest", description: "Augmented Manifest", expected_type: ExpectedDerType::Integer });
    m.insert("clas", PropertyMetadata { name: "Class", description: "Manifest Class", expected_type: ExpectedDerType::Integer });
    m.insert("fchp", PropertyMetadata { name: "FusingChip", description: "Fusing Chip", expected_type: ExpectedDerType::Integer });
    m.insert("pave", PropertyMetadata { name: "PlatformVersion", description: "Platform Version", expected_type: ExpectedDerType::Integer });
    m.insert("srvn", PropertyMetadata { name: "SecurityRevision", description: "Security Revision", expected_type: ExpectedDerType::Integer });
    m.insert("styp", PropertyMetadata { name: "SystemType", description: "System Type", expected_type: ExpectedDerType::Integer });
    m.insert("type", PropertyMetadata { name: "Type", description: "Image Type", expected_type: ExpectedDerType::Ia5String });
    m.insert("upcl", PropertyMetadata { name: "UpgradeClaim", description: "Upgrade Claim", expected_type: ExpectedDerType::Integer });
    m.insert("vnum", PropertyMetadata { name: "VersionNumber", description: "Version Number", expected_type: ExpectedDerType::Integer });
    m.insert("gdmg", PropertyMetadata { name: "GlobalDigest", description: "Global Digest", expected_type: ExpectedDerType::Digest });
    m.insert("ginc", PropertyMetadata { name: "GlobalIncrement", description: "Global Increment", expected_type: ExpectedDerType::Integer });
    m.insert("ginf", PropertyMetadata { name: "GlobalInfo", description: "Global Info", expected_type: ExpectedDerType::Integer });
    m.insert("gtcd", PropertyMetadata { name: "GlobalTrustedCode", description: "Global Trusted Code", expected_type: ExpectedDerType::Integer });
    m.insert("gtgv", PropertyMetadata { name: "GlobalTrustGlobalVersion", description: "Global Trust Global Version", expected_type: ExpectedDerType::Integer });
    m
});

fn parse_im4p_compression(obj: &DerObject) -> Result<Im4pCompression> {
    let seq = obj.as_sequence().map_err(|_| anyhow!("compression not SEQUENCE"))?;

    if seq.is_empty() { bail!("compression SEQUENCE empty"); }

    let id = seq[0].as_u64().map_err(|_| anyhow!("compression id not INTEGER"))?;

    // The uncompressed size is informational; a value too large for u64 (only
    // possible at absurd >=2^63 sizes) must not sink the whole compression block —
    // keep the algorithm id and report the size as unknown.
    let uncl = seq.get(1).and_then(|o| o.as_u64().ok());

    Ok(Im4pCompression { method_id: id, uncompressed_len: uncl })
}

/// Extract a labeled property container of the canonical shape
/// `SEQUENCE { IA5String(label), SET { properties } }`. IM4R and the IM4P PAYP
/// payload-properties block share this exact structure, so both reuse this.
fn extract_property_set(obj: &DerObject, expected_label: &str) -> Result<Vec<TypedIm4mProperty>> {
    let seq = obj
        .as_sequence()
        .map_err(|_| anyhow!("{expected_label}: not SEQUENCE"))?;

    let label = seq
        .get(0)
        .and_then(ia5str)
        .ok_or_else(|| anyhow!("{expected_label}: label missing"))?;
    if label != expected_label {
        bail!("{expected_label}: label is '{label}'");
    }

    let prop_set = seq
        .get(1)
        .ok_or_else(|| anyhow!("{expected_label}: missing property SET"))?
        .as_set()
        .map_err(|_| anyhow!("{expected_label}: properties not in a SET"))?;

    let mut out = Vec::new();
    for prop_obj in prop_set {
        collect_typed_props_from_obj(prop_obj, &mut out)?;
    }
    Ok(out)
}

/// Extract properties from IM4R using formal structure: SEQUENCE { "IM4R", SET { properties } }
pub fn extract_im4r_properties(raw: &[u8]) -> Result<Vec<TypedIm4mProperty>> {
    let (_, obj) = parse_der(raw).map_err(|e| anyhow!("IM4R DER: {e}"))?;
    extract_property_set(&obj, "IM4R")
}

/// Legacy function for backwards compatibility - extracts only BNCN nonce
#[allow(dead_code)]
#[deprecated(note = "Use extract_im4r_properties instead")]
pub fn extract_im4r_bncn_nonce(raw: &[u8]) -> Result<Option<Vec<u8>>> {
    let props = extract_im4r_properties(raw)?;
    for prop in props {
        if prop.key == "BNCN" {
            if let Im4mPropertyValue::OctetString { value: hex_val } = prop.value {
                return Ok(Some(hex::decode(hex_val).unwrap_or_default()));
            }
        }
    }
    Ok(None)
}

pub fn parse_img4_like(bytes: &[u8]) -> Result<Parsed> {
    debug!("parse_img4_like: starting, input length {}", bytes.len());
    let (_, obj) = parse_der(bytes).map_err(|e| anyhow!("DER: {}", e))?;
    let seq = obj.as_sequence().map_err(|_| anyhow!("top-level not SEQUENCE"))?;

    let label_str = seq
        .get(0)
        .and_then(ia5str)
        .ok_or_else(|| anyhow!("missing label"))?;
    debug!("top-level label: {}", label_str);

    if label_str == "IMG4" {
        // IMG4: ["IMG4", IM4P, [0] IM4M?, [1] IM4R?]
        debug!("Detected IMG4 container");
        let im4p = parse_im4p_from_der_obj(
            seq.get(1)
                .ok_or_else(|| anyhow!("IMG4 missing IM4P"))?,
        )?;
        debug!("Parsed IM4P successfully");

        let mut im4m = None;
        let mut im4r = None;

        for child in &seq[2..] {
            let hdr = child.header.clone();
            if hdr.class() == Class::ContextSpecific {
                let t = hdr.tag().0;
                if t == 0 {
                    debug!("Found context-specific [0] (IM4M)");
                    // [0] contains the complete DER of IM4M: keep raw bytes, validate label
                    if let Ok(inner_der) = child.as_slice() {
                        im4m = Some(im4m_from_bytes(inner_der)?);
                        debug!("Parsed IM4M from context-specific tag");
                    }
                } else if t == 1 {
                    debug!("Found context-specific [1] (IM4R)");
                    // [1] IM4R opaque
                    if let Ok(bytes) = child.as_slice() {
                        im4r = Some(bytes.to_vec());
                        debug!("Captured IM4R payload, {} bytes", bytes.len());
                    }
                }
            }
        }

        Ok(Parsed {
            kind: ContainerKind::Img4,
            im4p: Some(im4p),
            im4m,
            im4r,
        })
    } else if label_str == "IM4P" {
        debug!("Detected standalone IM4P");
        let im4p = parse_im4p_from_der_obj(&obj)?;
        Ok(Parsed {
            kind: ContainerKind::Im4pStandalone,
            im4p: Some(im4p),
            im4m: None,
            im4r: None,
        })
    } else if label_str == "IM4M" {
        debug!("Detected standalone IM4M");
        // Standalone IM4M: use the entire input as raw DER, validate label
        let im4m = im4m_from_bytes(bytes)?;
        Ok(Parsed {
            kind: ContainerKind::Im4mStandalone,
            im4p: None,
            im4m: Some(im4m),
            im4r: None,
        })
    } else {
        warn!("Unknown top-level label: {}", label_str);
        bail!("unknown top-level label: {label_str}");
    }
}

fn parse_im4p_from_der_obj(obj: &DerObject) -> Result<Im4p> {
    debug!("parse_im4p_from_der_obj: entering");
    let seq = obj.as_sequence().map_err(|_| anyhow!("IM4P not SEQUENCE"))?;

    // 0: "IM4P"
    let s0 = seq
        .get(0)
        .and_then(ia5str)
        .ok_or_else(|| anyhow!("IM4P label missing"))?;
    if s0 != "IM4P" {
        bail!("IM4P[0] != \"IM4P\"");
    }
    debug!("IM4P label confirmed");

    // 1: type (4 ASCII)
    let ty = seq
        .get(1)
        .and_then(ia5str)
        .ok_or_else(|| anyhow!("IM4P type missing"))?
        .to_string();
    debug!("IM4P type: {}", ty);

    // 2: version/description. The spec carries this as a short string; tolerate
    // non-UTF8 bytes by rendering lossily rather than rejecting a valid payload.
    let version_str = seq
        .get(2)
        .and_then(as_bytes)
        .map(|b| String::from_utf8_lossy(b).into_owned())
        .ok_or_else(|| anyhow!("IM4P version missing"))?;
    debug!("IM4P version: {}", version_str);

    // 3: payload data
    let data = seq
        .get(3)
        .and_then(as_bytes)
        .ok_or_else(|| anyhow!("IM4P data missing"))?
        .to_vec();
    debug!("IM4P payload size: {} bytes", data.len());

    // Optional trailing elements [4..] are matched by DER TAG/content, not by a
    // fixed index — mirroring the spec's DERParseSequenceToObject, which keys off
    // each item's tag. In particular, KBAG (OCTET STRING) may be absent while
    // compression (SEQUENCE) is present (e.g. an unencrypted-but-compressed
    // kernelcache), in which case positional indexing would silently misread the
    // layout and drop the compression block.
    let mut kbag_der_vec: Option<Vec<u8>> = None;
    let mut compression: Option<Im4pCompression> = None;
    let mut payload_properties: Option<Vec<TypedIm4mProperty>> = None;

    for item in seq.iter().skip(4) {
        let tag = item.header.tag().0;
        let universal = item.header.class() == Class::Universal;
        if universal && tag == 4 {
            // OCTET STRING -> KBAG (DER-encoded keybag)
            match as_bytes(item) {
                Some(b) if kbag_der_vec.is_none() => kbag_der_vec = Some(b.to_vec()),
                Some(_) => warn!("IM4P: extra OCTET STRING element ignored"),
                None => {}
            }
        } else if universal && tag == 16 {
            // SEQUENCE -> compression { INTEGER, INTEGER } OR PAYP { IA5 "PAYP", SET }
            match item.as_sequence() {
                Ok(children) if children.first().and_then(ia5str) == Some("PAYP") => {
                    match extract_property_set(item, "PAYP") {
                        Ok(props) => {
                            debug!("IM4P PAYP: {} payload properties", props.len());
                            payload_properties = Some(props);
                        }
                        Err(e) => warn!("IM4P PAYP parse failed: {}", e),
                    }
                }
                Ok(_) => {
                    // A non-PAYP universal SEQUENCE is expected to be the
                    // compression block. If it does not parse as one, warn and
                    // continue rather than aborting the whole payload — matching
                    // the lenient handling of the other optional arms (an
                    // inspection tool should still surface everything else).
                    match parse_im4p_compression(item) {
                        Ok(c) => {
                            debug!(
                                "IM4P compression: id={}, uncompressed_len={:?}",
                                c.method_id, c.uncompressed_len
                            );
                            compression = Some(c);
                        }
                        Err(e) => warn!("IM4P: SEQUENCE element is neither PAYP nor valid compression: {}", e),
                    }
                }
                Err(_) => debug!("IM4P: ignoring malformed SEQUENCE element"),
            }
        } else {
            debug!(
                "IM4P: ignoring unexpected optional element (class={:?}, tag={})",
                item.header.class(),
                tag
            );
        }
    }

    if kbag_der_vec.is_some() {
        debug!("IM4P contains KBAG");
    } else {
        debug!("IM4P does not contain KBAG");
    }
    let kbag_summary = match &kbag_der_vec {
        Some(kraw) => match parse_kbag_summary(kraw) {
            Ok(summary) => {
                debug!("Parsed KBAG with {} entries", summary.len());
                Some(summary)
            }
            Err(e) => {
                warn!("Failed to parse KBAG: {}", e);
                None
            }
        },
        None => None,
    };

    Ok(Im4p {
        r#type: ty,
        version: version_str,
        data,
        kbag_der: kbag_der_vec,
        kbag_summary,
        compression,
        payload_properties,
    })
}

fn parse_kbag_summary(kbag_der: &[u8]) -> Result<Vec<KbagEntry>> {
    debug!(
        "parse_kbag_summary: entering, KBAG DER size {} bytes",
        kbag_der.len()
    );
    let (_, obj) = parse_der(kbag_der).map_err(|e| anyhow!("KBAG DER: {e}"))?;
    let seq = obj.as_sequence().map_err(|_| anyhow!("KBAG not SEQUENCE"))?;

    let mut out = Vec::new();
    for (idx, entry) in seq.iter().enumerate() {
        let es = entry
            .as_sequence()
            .map_err(|_| anyhow!("KBAG entry not SEQUENCE"))?;
        // Each entry is { INTEGER class, OCTET iv, OCTET key }. The reference
        // library never parses KBAG internals, so tolerate (ignore) any extra
        // trailing fields a future format revision might add.
        if es.len() < 3 {
            bail!("KBAG entry malformed (expected >= 3 fields, got {})", es.len());
        }
        let kclass = es[0].as_u64().map_err(|_| anyhow!("KBAG class not INTEGER"))?;
        let iv = es[1].as_slice().map_err(|_| anyhow!("KBAG iv not OCTET STRING"))?.to_vec();
        let key = es[2].as_slice().map_err(|_| anyhow!("KBAG key not OCTET STRING"))?.to_vec();
        debug!(
            "KBAG entry {}: class={}, iv_len={}, key_len={}",
            idx,
            kclass,
            iv.len(),
            key.len()
        );
        out.push(KbagEntry { kclass, iv, key });
    }
    debug!("parse_kbag_summary: finished, total {} entries", out.len());
    Ok(out)
}

/// Build an Im4m by **owning the exact raw DER bytes** and validating the label.
fn im4m_from_bytes(bytes: &[u8]) -> Result<Im4m> {
    debug!(
        "im4m_from_bytes: entering, candidate DER size {} bytes",
        bytes.len()
    );
    let (_, obj) = parse_der(bytes).map_err(|e| anyhow!("IM4M DER: {e}"))?;
    let seq = obj.as_sequence().map_err(|_| anyhow!("IM4M not SEQUENCE"))?;
    let lbl = seq
        .get(0)
        .and_then(ia5str)
        .ok_or_else(|| anyhow!("IM4M label missing"))?;
    if lbl != "IM4M" {
        bail!("label != IM4M");
    }
    debug!("IM4M label confirmed");
    Ok(Im4m { raw: bytes.to_vec() })
}

/// A single image object inside the manifest body (e.g. "krnl", "sepi"), with
/// its own property set.
#[derive(Debug, Clone, Serialize)]
pub struct Im4mImage {
    pub fourcc: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    pub properties: Vec<TypedIm4mProperty>,
}

/// Structured view of the IM4M manifest body: the global manifest properties
/// (MANP) plus each per-image object group. This mirrors the spec structure
/// (MANB -> { MANP, <image>, ... }) instead of guessing from loose 4CC tokens.
#[derive(Debug, Clone, Serialize)]
pub struct Im4mManifestData {
    pub manifest_properties: Vec<TypedIm4mProperty>,
    pub images: Vec<Im4mImage>,
}

/// Walk IM4M -> MANB -> { MANP, <image objects> } and return a structured view.
/// Each node is located by its actual DER structure (private-tagged wrappers
/// containing `SEQUENCE { IA5String(4cc), SET { properties } }`).
pub fn extract_im4m_manifest(raw: &[u8]) -> Result<Im4mManifestData> {
    let (_, obj) = parse_der(raw).map_err(|e| anyhow!("IM4M DER: {e}"))?;
    let seq = obj.as_sequence().map_err(|_| anyhow!("IM4M not SEQUENCE"))?;

    let mut manifest_properties = Vec::new();
    let mut images = Vec::new();

    // IM4M[2] is the manifest body: a SET wrapping the MANB object.
    let body = seq.get(2).ok_or_else(|| anyhow!("IM4M missing manifest body"))?;
    let body_set = body.as_set().map_err(|_| anyhow!("IM4M body not a SET"))?;

    for wrapper in body_set {
        // Each member is a private-tagged wrapper around SEQUENCE { IA5, SET }.
        let inner = match wrapper.as_slice() {
            Ok(b) => b,
            Err(_) => continue,
        };
        let manb_seq_obj = match parse_der(inner) {
            Ok((_, o)) => o,
            Err(_) => continue,
        };
        let manb_seq = match manb_seq_obj.as_sequence() {
            Ok(s) => s,
            Err(_) => continue,
        };
        if manb_seq.get(0).and_then(ia5str) != Some("MANB") {
            continue;
        }
        let manb_set = match manb_seq.get(1).and_then(|o| o.as_set().ok()) {
            Some(s) => s,
            None => continue,
        };

        for child in manb_set {
            // child = [private 4cc] -> SEQUENCE { IA5 4cc, SET { props } }
            let cinner = match child.as_slice() {
                Ok(b) => b,
                Err(_) => continue,
            };
            let cseq_obj = match parse_der(cinner) {
                Ok((_, o)) => o,
                Err(_) => continue,
            };
            let cseq = match cseq_obj.as_sequence() {
                Ok(s) => s,
                Err(_) => continue,
            };
            let label = match cseq.get(0).and_then(ia5str) {
                Some(l) => l.to_string(),
                None => continue,
            };

            let mut props = Vec::new();
            if let Some(pset) = cseq.get(1).and_then(|o| o.as_set().ok()) {
                for p in pset {
                    collect_typed_props_from_obj(p, &mut props)?;
                }
            }

            if label == "MANP" {
                manifest_properties = props;
            } else {
                let name = crate::fourcc::get_description(&label);
                images.push(Im4mImage { fourcc: label, name, properties: props });
            }
        }
    }

    images.sort_by(|a, b| a.fourcc.cmp(&b.fourcc));
    Ok(Im4mManifestData { manifest_properties, images })
}

pub fn summarize_im4m(im4m: &Im4m) -> Result<Im4mInfoSummary> {
    debug!(
        "summarize_im4m: start, raw DER size {} bytes",
        im4m.raw.len()
    );

    // Decode top-level to extract version, signature, cert chain lengths (as before)
    let (_, obj) = parse_der(&im4m.raw).map_err(|e| anyhow!("IM4M DER: {e}"))?;
    let seq = obj.as_sequence().map_err(|_| anyhow!("IM4M not SEQUENCE"))?;

    let lbl = seq
        .get(0)
        .and_then(ia5str)
        .ok_or_else(|| anyhow!("IM4M label missing"))?;

    if lbl != "IM4M" {
        bail!("label != IM4M");
    }

    debug!("IM4M label validated");

    // IM4M[1] is the manifest version INTEGER. The reference decoder
    // (DERImg4DecodeManifestCommon) accepts only 0..=2 and hard-fails otherwise;
    // as an analysis tool we record the value and flag (rather than reject) any
    // out-of-range version so an unusual manifest can still be inspected.
    let version = seq.get(1).and_then(|o| o.as_u64().ok());
    match version {
        Some(v) if v > 2 => warn!("IM4M version {} is out of spec range 0..=2", v),
        Some(v) => debug!("IM4M version: {}", v),
        None => warn!("IM4M version field missing or not an integer"),
    }

    let signature_len = seq
        .get(3)
        .and_then(|o| o.as_slice().ok())
        .map(|b| b.len());
    debug!("IM4M signature length: {:?}", signature_len);

    let cert_chain_len = seq
        .get(4)
        .and_then(|o| o.as_sequence().ok())
        .map(|s| s.len());
    debug!("IM4M cert chain length: {:?}", cert_chain_len);

    // collect all IA5 strings (4-char) anywhere inside IM4M (including under private/context-specific)
    let mut tokens = Vec::<String>::new();
    scan_der_collect_ia5_fourccs(&im4m.raw, &mut tokens)?;
    debug!("Collected {} IA5 tokens before dedup", tokens.len());
    dedup_stable(&mut tokens);
    debug!("Token count after dedup: {}", tokens.len());

    // Populate fields
    let manifest_property_tags = tokens
        .iter()
        .filter(|s| s.as_str() == "MANB" || s.as_str() == "MANP")
        .cloned()
        .collect::<Vec<_>>();
    debug!(
        "Manifest property tags identified: {:?}",
        manifest_property_tags
    );

    // Images are enumerated structurally (MANB's child objects other than MANP),
    // which is exact, rather than guessing from loose lowercase 4CC tokens.
    let images_present = match extract_im4m_manifest(&im4m.raw) {
        Ok(m) => m.images.into_iter().map(|i| i.fourcc).collect::<Vec<_>>(),
        Err(e) => {
            warn!("structural image enumeration failed: {}", e);
            Vec::new()
        }
    };
    debug!("Images present identified: {:?}", images_present);

    Ok(Im4mInfoSummary {
        version,
        manifest_property_tags,
        images_present,
        cert_chain_len,
        signature_len,
    })
}

/// Extract certificate chain from IM4M.
/// Returns a Vec of DER-encoded X.509 certificates (owned).
pub fn extract_im4m_cert_chain(raw: &[u8]) -> anyhow::Result<Vec<Vec<u8>>> {
    // Hand-rolled DER walk over attacker-controlled bytes. Every offset derived
    // from a parsed length is validated against the buffer (and against the
    // enclosing element) before it is used to slice, so malformed input yields a
    // clean error rather than an out-of-bounds panic.
    let mut out: Vec<Vec<u8>> = Vec::new();

    // Bounds-checked suffix accessor.
    let at = |p: usize| -> Result<&[u8]> {
        raw.get(p..).ok_or_else(|| anyhow!("IM4M: offset {p} past end ({})", raw.len()))
    };
    let advance = |p: usize, by: usize| -> Result<usize> {
        p.checked_add(by).ok_or_else(|| anyhow!("IM4M: offset overflow"))
    };

    // Top-level IM4M SEQUENCE header.
    let mut pos = 0usize;
    let (tag_len, _, _, _) = der_read_tag(at(pos)?).map_err(|e| anyhow!("IM4M tag: {e}"))?;
    pos = advance(pos, tag_len)?;
    let (len_len, _) = der_read_len(at(pos)?).map_err(|e| anyhow!("IM4M len: {e}"))?;
    pos = advance(pos, len_len)?;

    // Skip to index 4 (the certificate chain) by walking elements 0..4.
    for idx in 0..5 {
        let (tag_len, class, _constructed, tag_no) =
            der_read_tag(at(pos)?).map_err(|e| anyhow!("elem[{idx}] tag: {e}"))?;
        pos = advance(pos, tag_len)?;
        let (len_len, elem_len) =
            der_read_len(at(pos)?).map_err(|e| anyhow!("elem[{idx}] len: {e}"))?;
        pos = advance(pos, len_len)?;

        let elem_end = advance(pos, elem_len)?;
        if elem_end > raw.len() {
            bail!("elem[{idx}] content ({elem_len} bytes) exceeds buffer");
        }

        if idx == 4 {
            // The cert chain container should be a SEQUENCE; anything else => no certs.
            if class != 0 || tag_no != 16 {
                return Ok(Vec::new());
            }

            let chain_end = elem_end;
            while pos < chain_end {
                let cert_start = pos;
                let (cert_tag_len, cert_class, _cert_constructed, cert_tag) =
                    der_read_tag(at(pos)?).map_err(|e| anyhow!("cert tag: {e}"))?;
                pos = advance(pos, cert_tag_len)?;
                let (cert_len_len, cert_len) =
                    der_read_len(at(pos)?).map_err(|e| anyhow!("cert len: {e}"))?;
                pos = advance(pos, cert_len_len)?;

                let content_end = advance(pos, cert_len)?;
                if content_end > chain_end {
                    bail!("cert content ({cert_len} bytes) exceeds cert chain");
                }

                debug!(
                    "cert[{}]: @{:04x} class={}, tag={}, len={}",
                    out.len(), cert_start, cert_class, cert_tag, cert_len
                );

                match (cert_class, cert_tag) {
                    // OCTET STRING: content is the DER cert.
                    (0, 4) => out.push(raw[pos..content_end].to_vec()),
                    // SEQUENCE: the full TLV is the DER cert.
                    (0, 16) => out.push(raw[cert_start..content_end].to_vec()),
                    _ => {
                        let content = &raw[pos..content_end];
                        if !content.is_empty() && content[0] == 0x30 {
                            out.push(content.to_vec());
                        } else {
                            out.push(encode_der_sequence(content));
                        }
                    }
                }

                pos = content_end;
            }
            break;
        } else {
            // Skip this element's content.
            pos = elem_end;
        }
    }

    Ok(out)
}

/// Build a valid DER SEQUENCE (0x30) around `content`.
fn encode_der_sequence(content: &[u8]) -> Vec<u8> {
    let mut v = Vec::with_capacity(1 + der_len_encoded_bytes(content.len()) + content.len());
    v.push(0x30); // UNIVERSAL SEQUENCE (constructed)
    write_der_len(&mut v, content.len());
    v.extend_from_slice(content);
    v
}

fn der_len_encoded_bytes(len: usize) -> usize {
    if len < 128 { 1 } else {
        let mut n = 0usize;
        let mut tmp = len;
        while tmp > 0 { n += 1; tmp >>= 8; }
        1 + n
    }
}

fn write_der_len(buf: &mut Vec<u8>, len: usize) {
    if len < 128 {
        buf.push(len as u8);
    } else {
        // Long-form definite length per DER
        let mut bytes = [0u8; 8]; // enough for usize on 64-bit
        let mut n = 0usize;
        let mut tmp = len;
        while tmp > 0 {
            bytes[7 - n] = (tmp & 0xFF) as u8;
            tmp >>= 8;
            n += 1;
        }
        buf.push(0x80 | (n as u8));
        buf.extend_from_slice(&bytes[8 - n..]);
    }
}

/// Extracts all properties of the form SEQUENCE { IA5String(4CC), ANY } found anywhere in the IM4M.
/// Returns the legacy untyped property structure for backwards compatibility.
#[allow(dead_code)]
pub fn extract_im4m_properties(raw: &[u8]) -> Result<Vec<Im4mProperty>> {
    let (_, obj) = parse_der(raw).map_err(|e| anyhow!("IM4M DER: {e}"))?;
    let mut out = Vec::<Im4mProperty>::new();
    collect_props_from_obj(&obj, &mut out)?;
    Ok(out)
}

#[allow(dead_code)]
fn collect_props_from_obj(o: &DerObject, out: &mut Vec<Im4mProperty>) -> Result<()> {
    // If this is a SEQUENCE, check for the { IA5String(4CC), ANY } pattern
    if let Ok(seq) = o.as_sequence() {
        if seq.len() >= 2 {
            if let Some(k) = ia5str(&seq[0]) {
                if k.len() == 4 && k.chars().all(|c| c.is_ascii_graphic()) {
                    let v = decode_any_value(&seq[1])?;
                    out.push(Im4mProperty { key: k.to_string(), value: v });
                }
            }
        }
        // Recurse into children regardless, since properties can nest
        for ch in seq {
            collect_props_from_obj(ch, out)?;
        }
        return Ok(());
    }

    // If this is a SET, also recurse
    if let Ok(set) = o.as_set() {
        for ch in set {
            collect_props_from_obj(ch, out)?;
        }
        return Ok(());
    }

    // For any constructed object (context/private/application), parse its content as DER and recurse
    let h = &o.header;
    if h.is_constructed() {
        if let Ok(bytes) = o.as_slice() {
            let mut off = 0usize;
            while off < bytes.len() {
                let (rem, child) = parse_der(&bytes[off..]).map_err(|e| anyhow!("inner DER: {e}"))?;
                let consumed = bytes[off..].len() - rem.len();
                collect_props_from_obj(&child, out)?;
                off += consumed;
            }
        }
    }
    Ok(())
}

/// Collect typed properties with metadata
fn collect_typed_props_from_obj(o: &DerObject, out: &mut Vec<TypedIm4mProperty>) -> Result<()> {
    if let Ok(seq) = o.as_sequence() {
        if seq.len() >= 2 {
            if let Some(k) = ia5str(&seq[0]) {
                if k.len() == 4 && k.chars().all(|c| c.is_ascii_graphic()) {
                    let (value, anomaly) = decode_typed_value(&seq[1], Some(k))?;
                    let meta = KNOWN_PROPERTIES.get(k);
                    let (name, description) = if let Some(m) = meta {
                        (m.name.to_string(), m.description.to_string())
                    } else {
                        ("UnknownProperty".to_string(), "An unknown or undocumented property.".to_string())
                    };
                    out.push(TypedIm4mProperty {
                        key: k.to_string(),
                        name,
                        description,
                        value,
                        anomaly,
                    });
                }
            }
        }
        for ch in seq {
            collect_typed_props_from_obj(ch, out)?;
        }
        return Ok(());
    }

    if let Ok(set) = o.as_set() {
        for ch in set {
            collect_typed_props_from_obj(ch, out)?;
        }
        return Ok(());
    }

    let h = &o.header;
    if h.is_constructed() {
        if let Ok(bytes) = o.as_slice() {
            let mut off = 0usize;
            while off < bytes.len() {
                let (rem, child) = parse_der(&bytes[off..]).map_err(|e| anyhow!("inner DER: {e}"))?;
                let consumed = bytes[off..].len() - rem.len();
                collect_typed_props_from_obj(&child, out)?;
                off += consumed;
            }
        }
    }
    Ok(())
}

/// Decode a DER INTEGER value: returns `Integer` when it fits in u64, otherwise
/// the raw big-endian magnitude as hex (Apple manifests use 64-bit integers, but
/// we never silently truncate a wider one to zero).
fn integer_value(o: &DerObject) -> Im4mPropertyValue {
    match o.as_u64() {
        Ok(i) => Im4mPropertyValue::Integer { value: i },
        Err(_) => Im4mPropertyValue::Unknown {
            der_type: "INTEGER".to_string(),
            hex_value: Some(hex::encode(o.as_slice().unwrap_or_default())),
            hex_values: None,
        },
    }
}

/// Decode a value with type hint from property metadata
fn decode_typed_value(o: &DerObject, key_hint: Option<&str>) -> Result<(Im4mPropertyValue, Option<String>)> {
    let meta = key_hint.and_then(|k| KNOWN_PROPERTIES.get(k));
    let mut anomaly = None;

    let val = match meta.map(|m| &m.expected_type) {
        Some(ExpectedDerType::Boolean) => {
            if let Ok(b) = o.as_bool() {
                Im4mPropertyValue::Boolean { value: b }
            } else {
                anomaly = Some(format!("Expected BOOLEAN, got {:?}", o.header.tag()));
                Im4mPropertyValue::Unknown {
                    der_type: format!("{:?}", o.header.tag()),
                    hex_value: Some(hex::encode(o.as_slice().unwrap_or_default())),
                    hex_values: None,
                }
            }
        }
        Some(ExpectedDerType::Integer) => {
            if o.header.tag().0 == 2 {
                // A genuine INTEGER: fits-in-u64 -> Integer, else hex magnitude.
                integer_value(o)
            } else {
                anomaly = Some(format!("Expected INTEGER, got {:?}", o.header.tag()));
                Im4mPropertyValue::Unknown {
                    der_type: format!("{:?}", o.header.tag()),
                    hex_value: Some(hex::encode(o.as_slice().unwrap_or_default())),
                    hex_values: None,
                }
            }
        }
        Some(ExpectedDerType::Digest) => {
            if let Ok(s) = o.as_slice() {
                Im4mPropertyValue::Digest { value: hex::encode(s) }
            } else {
                anomaly = Some(format!("Expected OCTET STRING for Digest, got {:?}", o.header.tag()));
                Im4mPropertyValue::Unknown {
                    der_type: format!("{:?}", o.header.tag()),
                    hex_value: Some(hex::encode(o.as_slice().unwrap_or_default())),
                    hex_values: None,
                }
            }
        }
        Some(ExpectedDerType::OctetString) => {
            if let Ok(s) = o.as_slice() {
                Im4mPropertyValue::OctetString { value: hex::encode(s) }
            } else {
                anomaly = Some(format!("Expected OCTET STRING, got {:?}", o.header.tag()));
                Im4mPropertyValue::Unknown {
                    der_type: format!("{:?}", o.header.tag()),
                    hex_value: Some(hex::encode(o.as_slice().unwrap_or_default())),
                    hex_values: None,
                }
            }
        }
        Some(ExpectedDerType::Ia5String) => {
            if let Some(s) = ia5str(o) {
                Im4mPropertyValue::String { value: s.to_string() }
            } else {
                anomaly = Some(format!("Expected IA5String, got {:?}", o.header.tag()));
                Im4mPropertyValue::Unknown {
                    der_type: format!("{:?}", o.header.tag()),
                    hex_value: Some(hex::encode(o.as_slice().unwrap_or_default())),
                    hex_values: None,
                }
            }
        }
        None => {
            // Fallback for unknown keys
            match o.header.tag().0 {
                1 => Im4mPropertyValue::Boolean { value: o.as_bool().unwrap_or(false) },
                2 => integer_value(o),
                4 => Im4mPropertyValue::OctetString { value: hex::encode(o.as_slice().unwrap_or_default()) },
                22 => Im4mPropertyValue::String { value: ia5str(o).unwrap_or("").to_string() },
                16 | 17 => {
                    // SEQUENCE (16) or SET (17) - recursively collect child elements
                    let (type_name, children) = if o.header.tag().0 == 16 {
                        ("Sequence", o.as_sequence().ok())
                    } else {
                        ("Set", o.as_set().ok())
                    };
                    
                    if let Some(items) = children {
                        if items.is_empty() {
                            Im4mPropertyValue::Unknown {
                                der_type: format!("{}(empty)", type_name),
                                hex_value: None,
                                hex_values: None,
                            }
                        } else {
                            // Recursively encode children for debugging
                            let mut parts = Vec::new();
                            for child in items {
                                if let Ok(slice) = child.as_slice() {
                                    parts.push(hex::encode(slice));
                                }
                            }
                            Im4mPropertyValue::Unknown {
                                der_type: format!("{}({} elements)", type_name, items.len()),
                                hex_value: None,
                                hex_values: Some(parts),
                            }
                        }
                    } else {
                        Im4mPropertyValue::Unknown {
                            der_type: format!("{}(malformed)", type_name),
                            hex_value: Some(hex::encode(o.as_slice().unwrap_or_default())),
                            hex_values: None,
                        }
                    }
                }
                _ => Im4mPropertyValue::Unknown {
                    der_type: format!("{:?}", o.header.tag()),
                    hex_value: Some(hex::encode(o.as_slice().unwrap_or_default())),
                    hex_values: None,
                },
            }
        }
    };
    Ok((val, anomaly))
}

#[allow(dead_code)]
fn decode_any_value(o: &DerObject) -> Result<Im4mValue> {
    let h = &o.header;
    // Convert the Class enum into its underlying integer representation
    let class_num = h.class() as u8;
    let tag = h.tag().0;
    // UNIVERSAL = 0; tag numbers per X.690
    if class_num == 0 {
        match tag {
            1 => {
                // BOOLEAN
                let b = o.as_bool().map_err(|_| anyhow!("BOOLEAN decode"))?;
                return Ok(Im4mValue::Boolean(b));
            }
            2 => {
                // INTEGER (treat as non-negative big-int; IM4M integers are typically small)
                // If negative occurs, map via two's complement to u128 magnitude.
                if let Ok(u) = o.as_u64() {
                    return Ok(Im4mValue::Integer(u as u128));
                }
                // Fallback: read raw bytes and decode as unsigned magnitude
                if let Ok(bytes) = o.as_slice() {
                    let mut acc: u128 = 0;
                    for &b in bytes {
                        acc = (acc << 8) | (b as u128);
                    }
                    return Ok(Im4mValue::Integer(acc));
                }
                return Ok(Im4mValue::Unknown { class_id: class_num, tag, len: o.length().definite()? });
            }
            3 => {
                // BIT STRING
                if let Ok(bytes) = o.as_slice() {
                    return Ok(Im4mValue::BitString(hex::encode(bytes)));
                }
                return Ok(Im4mValue::Unknown { class_id: class_num, tag, len: o.length().definite()? });
            }
            4 => {
                // OCTET STRING
                if let Ok(bytes) = o.as_slice() {
                    return Ok(Im4mValue::OctetString(hex::encode(bytes)));
                }
                return Ok(Im4mValue::Unknown { class_id: class_num, tag, len: o.length().definite()? });
            }
            5 => return Ok(Im4mValue::Null),
            16 => {
                if let Ok(seq) = o.as_sequence() {
                    return Ok(Im4mValue::SequenceLen(seq.len()));
                }
                return Ok(Im4mValue::Unknown { class_id: class_num, tag, len: o.length().definite()? });
            }
            17 => {
                if let Ok(set) = o.as_set() {
                    return Ok(Im4mValue::SetLen(set.len()));
                }
                return Ok(Im4mValue::Unknown { class_id: class_num, tag, len: o.length().definite()? });
            }
            22 => {
                if let Some(s) = ia5str(o) {
                    return Ok(Im4mValue::Ia5String(s.to_string()));
                }
                return Ok(Im4mValue::Unknown { class_id: class_num, tag, len: o.length().definite()? });
            }
            _ => {
                if let Ok(bytes) = o.as_slice() {
                    return Ok(Im4mValue::Unknown { class_id: class_num, tag, len: bytes.len() });
                }
                return Ok(Im4mValue::Unknown { class_id: class_num, tag, len: o.length().definite()? });
            }
        }
    } else {
        // Non-universal: leave as Unknown, but include tag class/tag number
        if let Ok(bytes) = o.as_slice() {
            return Ok(Im4mValue::Unknown { class_id: class_num, tag, len: bytes.len() });
        }
        Ok(Im4mValue::Unknown { class_id: class_num, tag, len: o.length().definite()? })
    }
}

// ---------- helpers (append these near existing helpers) ----------

fn dedup_stable(v: &mut Vec<String>) {
    v.sort();
    v.dedup();
}

/// Class-agnostic DER walker that collects IA5String tokens of length 4, recursively.
/// Handles constructed UNIVERSAL/PRIVATE/CONTEXT-SPECIFIC by parsing child DER items inside the value region.
///
/// DER assumptions: definite length (Image4 is DER). Indefinite lengths are rejected.
fn scan_der_collect_ia5_fourccs(input: &[u8], out: &mut Vec<String>) -> Result<()> {
    let mut off = 0usize;
    while off < input.len() {
        let (tag_len, class, constructed, tag_no) = der_read_tag(&input[off..])?;
        let len_off = off + tag_len;
        let (len_len, content_len) = der_read_len(&input[len_off..])?;
        let hdr_len = tag_len + len_len;

        let val_start = off + hdr_len;
        let val_end = val_start
            .checked_add(content_len)
            .ok_or_else(|| anyhow!("overflow"))?;
        if val_end > input.len() {
            bail!("IM4M: element exceeds buffer");
        }

        // Collect IA5String 4CCs (UNIVERSAL class, tag_no == 22)
        if class == 0 && tag_no == 22 {
            let s = &input[val_start..val_end];
            if let Ok(su) = std::str::from_utf8(s) {
                if su.len() == 4 && su.chars().all(|c| c.is_ascii_graphic()) {
                    out.push(su.to_string());
                    debug!("Found IA5 token: {}", su);
                }
            }
        }

        // Recurse into constructed values (any class): their content is a concatenation of DER elements.
        if constructed {
            debug!(
                "Recursing into constructed tag (class={}, tag_no={}) at offset {}",
                class, tag_no, off
            );
            scan_der_collect_ia5_fourccs(&input[val_start..val_end], out)?;
        }

        off = val_end;
    }
    Ok(())
}

/// Parse DER tag header: returns (bytes_consumed, class(0..3), constructed, tag_number)
fn der_read_tag(i: &[u8]) -> Result<(usize, u8, bool, u32)> {
    if i.is_empty() {
        bail!("short tag");
    }
    let b0 = i[0];
    let class = (b0 & 0b1100_0000) >> 6; // 0=universal,1=application,2=context,3=private
    let constructed = (b0 & 0b0010_0000) != 0;
    let mut tag_no = (b0 & 0b0001_1111) as u32;
    let mut idx = 1usize;

    if tag_no == 0b1_1111 {
        // High-tag-number form: base-128 big-endian, MSB=1 continuation, last MSB=0.
        // A u32 tag number fits in at most 5 base-128 groups (5*7 = 35 >= 32); a
        // crafted header with more (or wider) groups must not be allowed to shift
        // past 32 bits (which panics in debug and silently wraps in release).
        tag_no = 0;
        let mut groups = 0usize;
        loop {
            if idx >= i.len() {
                bail!("short high-tag-number");
            }
            let b = i[idx];
            idx += 1;
            groups += 1;
            if groups > 5 || (tag_no >> 25) != 0 {
                bail!("high-tag-number overflows u32");
            }
            tag_no = (tag_no << 7) | (b & 0x7F) as u32;
            if (b & 0x80) == 0 {
                break;
            }
        }
    }

    Ok((idx, class, constructed, tag_no))
}

/// Parse a definite-length field: returns (bytes_consumed, content_length).
///
/// Safety-critical malformations (indefinite form, the reserved 0xFF marker, and
/// length fields too wide for `usize`) are rejected. Non-minimal-but-safe
/// encodings (a long form used for a small value, or leading zero octets) are
/// accepted deliberately — being BER-lenient here only makes the walker more
/// robust on slightly-off inputs and never compromises memory safety.
fn der_read_len(i: &[u8]) -> Result<(usize, usize)> {
    if i.is_empty() {
        bail!("short length");
    }
    let b0 = i[0];
    if (b0 & 0x80) == 0 {
        // short form
        Ok((1, (b0 & 0x7F) as usize))
    } else {
        let n = (b0 & 0x7F) as usize;
        if n == 0 {
            // Indefinite form is illegal in DER and would otherwise be read as len 0.
            bail!("indefinite length not allowed in DER");
        }
        if n == 0x7F {
            // 0xFF is reserved by X.690.
            bail!("reserved length form (0xFF)");
        }
        // Reject a length field that cannot fit in usize on this platform. With this
        // bound the accumulation below cannot overflow (n <= 8 on 64-bit, <= 4 on
        // 32-bit). This is the critical safety check.
        if n > core::mem::size_of::<usize>() {
            bail!("length field too large ({n} octets) for this platform");
        }
        if i.len() < 1 + n {
            bail!("short long-form length");
        }
        let mut len: usize = 0;
        for &b in &i[1..=n] {
            len = (len << 8) | (b as usize);
        }
        Ok((1 + n, len))
    }
}

/* ---------- helpers ---------- */

fn as_bytes<'a>(o: &'a DerObject<'a>) -> Option<&'a [u8]> {
    o.as_slice().ok()
}
fn ia5str<'a>(o: &'a DerObject<'a>) -> Option<&'a str> {
    o.as_slice().ok().and_then(|s| std::str::from_utf8(s).ok())
}

/// Public accessor for property metadata (used by fourcc module for fallback)
pub fn get_property_metadata(code: &str) -> Option<String> {
    KNOWN_PROPERTIES.get(code).map(|meta| {
        format!("{} ({})", meta.name, meta.description)
    })
}

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

    // ---- der_read_len: definite-length safety ----

    #[test]
    fn len_short_form() {
        assert_eq!(der_read_len(&[0x05]).unwrap(), (1, 5));
        assert_eq!(der_read_len(&[0x00]).unwrap(), (1, 0));
        assert_eq!(der_read_len(&[0x7F]).unwrap(), (1, 127));
    }

    #[test]
    fn len_long_form() {
        assert_eq!(der_read_len(&[0x82, 0x01, 0x00]).unwrap(), (3, 256));
        assert_eq!(der_read_len(&[0x81, 0x80]).unwrap(), (2, 128));
    }

    #[test]
    fn len_indefinite_rejected() {
        assert!(der_read_len(&[0x80]).is_err());
    }

    #[test]
    fn len_reserved_rejected() {
        assert!(der_read_len(&[0xFF, 0, 0, 0, 0, 0, 0, 0, 0]).is_err());
    }

    #[test]
    fn len_oversized_rejected_no_overflow() {
        // 0x89 => 9 length octets; must be rejected on every platform (no shl panic).
        let buf = [0x89u8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
        assert!(der_read_len(&buf).is_err());
    }

    #[test]
    fn len_truncated_rejected() {
        assert!(der_read_len(&[0x82, 0x01]).is_err()); // claims 2 octets, only 1 present
        assert!(der_read_len(&[]).is_err());
    }

    // ---- der_read_tag: high-tag-number safety ----

    #[test]
    fn tag_low_form() {
        let (used, class, constructed, tag) = der_read_tag(&[0x30]).unwrap();
        assert_eq!((used, class, constructed, tag), (1, 0, true, 16));
        let (used, class, constructed, tag) = der_read_tag(&[0x16]).unwrap();
        assert_eq!((used, class, constructed, tag), (1, 0, false, 22));
    }

    #[test]
    fn tag_high_form_ok() {
        // private, constructed, tag = 'MANB' (0x4D414E42) in base-128.
        let bytes = [0xE0u8 | 0x1F, 0x84, 0xEA, 0x85, 0x9C, 0x42];
        let (_used, class, constructed, tag) = der_read_tag(&bytes).unwrap();
        assert_eq!(class, 3);
        assert!(constructed);
        assert_eq!(tag, 0x4D414E42);
    }

    #[test]
    fn tag_high_form_overflow_rejected_no_panic() {
        // 7 continuation groups -> would shift past 32 bits; must error, not panic.
        let bytes = [0x1Fu8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F];
        assert!(der_read_tag(&bytes).is_err());
    }

    #[test]
    fn tag_high_form_truncated_rejected() {
        assert!(der_read_tag(&[0x1F, 0x84]).is_err()); // continuation bit set, buffer ends
    }

    // ---- extract_im4m_cert_chain: bounds safety on malformed input ----

    /// A cert whose declared length runs past the chain must error, not panic.
    #[test]
    fn cert_chain_overrun_is_rejected() {
        // IM4M = SEQUENCE { "IM4M", INTEGER 0, SET{}, OCTET{}, SEQUENCE{ bad-cert } }
        // The cert chain's single element is `30 7F` (claims 127 bytes, none present).
        let inner: Vec<u8> = [
            &[0x16, 0x04, b'I', b'M', b'4', b'M'][..], // elem0
            &[0x02, 0x01, 0x00][..],                   // elem1 INTEGER 0
            &[0x31, 0x00][..],                         // elem2 SET {}
            &[0x04, 0x00][..],                         // elem3 OCTET {}
            &[0x30, 0x02, 0x30, 0x7F][..],             // elem4 SEQUENCE { 30 7F }
        ]
        .concat();
        let mut raw = vec![0x30u8, inner.len() as u8];
        raw.extend_from_slice(&inner);
        let r = extract_im4m_cert_chain(&raw);
        assert!(r.is_err(), "overrunning cert length must be rejected");
    }

    /// A truncated IM4M (header only) must error cleanly.
    #[test]
    fn cert_chain_truncated_is_rejected() {
        assert!(extract_im4m_cert_chain(&[0x30]).is_err());
        assert!(extract_im4m_cert_chain(&[]).is_err());
    }

    /// A well-formed 2-cert chain is extracted intact.
    #[test]
    fn cert_chain_valid_two_certs() {
        let cert_a = [0x30u8, 0x03, 0x02, 0x01, 0x07]; // SEQUENCE { INTEGER 7 }
        let cert_b = [0x30u8, 0x03, 0x02, 0x01, 0x09];
        let mut chain = Vec::new();
        chain.extend_from_slice(&cert_a);
        chain.extend_from_slice(&cert_b);
        let mut elem4 = vec![0x30u8, chain.len() as u8];
        elem4.extend_from_slice(&chain);
        let inner: Vec<u8> = [
            &[0x16, 0x04, b'I', b'M', b'4', b'M'][..],
            &[0x02, 0x01, 0x00][..],
            &[0x31, 0x00][..],
            &[0x04, 0x00][..],
            &elem4[..],
        ]
        .concat();
        let mut raw = vec![0x30u8, inner.len() as u8];
        raw.extend_from_slice(&inner);
        let certs = extract_im4m_cert_chain(&raw).unwrap();
        assert_eq!(certs.len(), 2);
        assert_eq!(certs[0], cert_a);
        assert_eq!(certs[1], cert_b);
    }
}