android-doctor 0.1.0

Extract and audit Android OTA and firmware images (payload.bin, super.img, ext4, erofs) without running them
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
//! APK inspection: package name and version from the binary AndroidManifest,
//! and signing certificates from the v1 (META-INF PKCS#7), v2 and v3 signing blocks.
//!
//! Formats follow the AOSP definitions (Apache-2.0): the binary XML layout from
//! `ResourceTypes.h`, the APK Signature Scheme v2/v3 from `apk_signature_scheme.h`,
//! and PKCS#7 (RFC 5652) for the v1 META-INF certs. All paths and sizes are bounds-checked.

use anyhow::{Context, Result, bail, ensure};
use sha2::{Digest, Sha256};
use std::io::{Cursor, Read};
use std::path::Path;
use zip::ZipArchive;

/// AOSP public test-key certificate subject CNs (Apache-2.0, AOSP test keys).
const AOSP_TEST_KEY_SUBJECTS: &[&str] =
    &["Android", "platform", "shared", "testkey", "media", "root"];

/// Maximum APK size we will read into memory (10 MB).
pub const MAX_APK_BYTES: u64 = 10 * 1024 * 1024;
/// Maximum size of a single entry inside an APK zip (5 MB).
const MAX_ENTRY_BYTES: usize = 5 * 1024 * 1024;

// --- Public types ---

/// A signer found in the v1 META-INF area (PKCS#7) or the v2/v3 signing block.
#[derive(Debug, Clone, PartialEq)]
pub struct Signer {
    /// "v1", "v2", or "v3" -- which signing scheme this signer belongs to.
    pub scheme: &'static str,
    /// SHA-256 hex of the signer X.509 certificate.
    pub cert_sha256: String,
    /// The certificate subject CN, for display.
    pub subject_cn: Option<String>,
    /// Whether the cert subject matches a known AOSP public test key.
    pub is_aosp_test_key: bool,
}

/// The auditable contents of one APK.
#[derive(Debug, Clone, Default)]
pub struct ApkInfo {
    pub path: String,
    pub package_name: String,
    pub version_code: Option<String>,
    pub version_name: Option<String>,
    pub signers: Vec<Signer>,
}

impl ApkInfo {
    pub fn has_test_key(&self) -> bool {
        self.signers.iter().any(|s| s.is_aosp_test_key)
    }
}

/// One APK audit result: the parsed info plus any error encountered.
#[derive(Debug, Clone, Default)]
pub struct ApkAudit {
    pub info: Option<ApkInfo>,
    pub error: Option<String>,
}

/// Parsed attributes from a binary AndroidManifest.xml.
#[derive(Debug, Clone, Default)]
pub struct ManifestAttrs {
    pub package_name: String,
    pub version_code: Option<String>,
    pub version_name: Option<String>,
}

// --- Binary helpers ---

fn le16(data: &[u8], off: usize) -> Result<u16> {
    ensure!(off + 2 <= data.len(), "le16: truncated at {off}");
    Ok(u16::from_le_bytes([data[off], data[off + 1]]))
}

fn le32(data: &[u8], off: usize) -> Result<u32> {
    ensure!(off + 4 <= data.len(), "le32: truncated at {off}");
    Ok(u32::from_le_bytes([
        data[off],
        data[off + 1],
        data[off + 2],
        data[off + 3],
    ]))
}

#[allow(dead_code)]
fn le64(data: &[u8], off: usize) -> Result<u64> {
    ensure!(off + 8 <= data.len(), "le64: truncated at {off}");
    Ok(u64::from_le_bytes([
        data[off],
        data[off + 1],
        data[off + 2],
        data[off + 3],
        data[off + 4],
        data[off + 5],
        data[off + 6],
        data[off + 7],
    ]))
}

/// Parse the string pool that begins a binary XML document.
fn parse_string_pool(data: &[u8]) -> Result<(Vec<String>, usize)> {
    // RES_STRING_POOL_TYPE (AOSP ResourceTypes.h, Apache-2.0).
    let chunk_type = le16(data, 0)?;
    ensure!(
        chunk_type == 0x0001,
        "string pool: expected RES_STRING_POOL_TYPE 0x0001, got {chunk_type:#06x}"
    );
    let header_size = le16(data, 2)? as usize;
    let chunk_size = le32(data, 4)? as usize;
    ensure!(chunk_size <= data.len(), "string pool: chunk too large");
    let str_count = le32(data, 8)? as usize;
    let strings_start = le32(data, 20)? as usize;
    ensure!(
        strings_start <= chunk_size,
        "string pool: strings start past chunk"
    );
    let mut offsets = Vec::with_capacity(str_count);
    for i in 0..str_count {
        let off = header_size + 4 * i;
        ensure!(off + 4 <= data.len(), "string pool: offset entry truncated");
        offsets.push(le32(data, off)? as usize);
    }
    let mut strings = Vec::with_capacity(str_count);
    for off in offsets {
        let (s, _) = read_utf16(data, strings_start + off)?;
        strings.push(s);
    }
    Ok((strings, strings_start))
}

/// Read a UTF-16LE string from data at offset start.
fn read_utf16(data: &[u8], start: usize) -> Result<(String, usize)> {
    ensure!(start + 2 <= data.len(), "utf16: truncated");
    let char_len = le16(data, start)? as usize;
    let mut s = String::with_capacity(char_len);
    let mut pos = start + 2;
    for _ in 0..char_len {
        // A hostile or merely odd pool can claim more units than the chunk holds; stop at
        // what is actually there rather than failing the whole manifest.
        if pos + 2 > data.len() {
            break;
        }
        let ch = le16(data, pos)? as u16;
        pos += 2;
        if let Some(c) = char::from_u32(ch as u32) {
            s.push(c);
        }
    }
    // Each entry is followed by a terminating 0x0000 (AOSP ResourceTypes.h).
    if pos + 2 <= data.len() {
        pos += 2;
    }
    Ok((s, pos - start))
}

/// An attribute entry in a start tag.
struct Attr {
    name_idx: usize,
    value: String,
}

/// Size of ResXMLTree_node: ResChunk_header (8) + lineNumber (4) + comment (4).
const ATTR_EXT_BASE: usize = 16;

fn parse_start_tag(
    data: &[u8],
    chunk_off: usize,
    strings: &[String],
) -> Result<(String, Vec<Attr>)> {
    let chunk = &data[chunk_off..];
    ensure!(chunk.len() >= 32, "start tag: chunk too small");
    // ResXMLTree_attrExt (AOSP ResourceTypes.h, Apache-2.0) begins ATTR_EXT_BASE bytes into
    // the chunk and is laid out ns, name, attributeStart, attributeSize, attributeCount.
    let name_idx = le32(chunk, ATTR_EXT_BASE + 4)? as usize;
    let name = strings.get(name_idx).cloned().unwrap_or_default();
    let attr_start = le16(chunk, ATTR_EXT_BASE + 8)? as usize;
    let attr_size = le16(chunk, ATTR_EXT_BASE + 10)? as usize;
    let attr_count = le16(chunk, ATTR_EXT_BASE + 12)? as usize;
    // ResXMLTree_attribute is exactly 20 bytes, optionally followed by a typed value
    // (AOSP ResourceTypes.h).
    ensure!(attr_size >= 20, "start tag: attr entry too small");
    let mut attrs = Vec::with_capacity(attr_count);
    // ResXMLTree_attrExt (AOSP ResourceTypes.h): attributeStart is relative to the start
    // of the attrExt, which begins 16 bytes into the chunk (after the ResXMLTree_node header).
    let mut pos = ATTR_EXT_BASE + attr_start;
    for _ in 0..attr_count {
        ensure!(pos + attr_size <= chunk.len(), "start tag: attr past chunk");
        let nm_idx = le32(chunk, pos + 4)? as usize;
        let raw_val_off = le32(chunk, pos + 8)? as usize;
        let value = if raw_val_off == 0xFFFFFFFF {
            // Res_value (AOSP ResourceTypes.h): size u16, res0 u8, dataType u8, data u32.
            let dt = chunk[pos + 15];
            format_typed_value(dt, &chunk[pos + 16..pos + 20])?
        } else {
            // AOSP ResXMLTree_attribute.rawValue is an INDEX into the string pool, not a
            // byte offset (verified against a real APK), so resolve through the pool.
            strings.get(raw_val_off).cloned().unwrap_or_default()
        };
        attrs.push(Attr {
            name_idx: nm_idx,
            value,
        });
        pos += attr_size;
    }
    Ok((name, attrs))
}

fn format_typed_value(data_type: u8, data: &[u8]) -> Result<String> {
    ensure!(data.len() >= 4, "typed value: data too short");
    match data_type {
        0x01 => Ok("(string)".to_string()),
        0x10 => Ok(le32(data, 0)?.to_string()),
        0x11 => Ok(format!("0x{:X}", le32(data, 0)?)),
        0x12 => Ok(le32(data, 0)?.to_string()),
        _ => Ok(format!("(type {})", data_type)),
    }
}

pub(crate) fn parse_manifest(data: &[u8]) -> Result<ManifestAttrs> {
    ensure!(!data.is_empty(), "manifest: empty");
    // A binary XML file begins with the RES_XML_TYPE (0x0003) header; the string pool is
    // the first chunk after that 8-byte header (AOSP ResourceTypes.h, Apache-2.0).
    let file_type = le16(data, 0)?;
    ensure!(
        file_type == 0x0003,
        "manifest: expected RES_XML_TYPE 0x0003, got {file_type:#06x}"
    );
    // ResXMLTree_header: type u16, headerSize u16, size u32 (AOSP ResourceTypes.h).
    let xml_header = le16(data, 2)? as usize;
    ensure!(
        xml_header >= 8 && xml_header <= data.len(),
        "manifest: bad xml header"
    );
    // parse_string_pool returns offsets relative to the pool chunk; rebase onto the
    // whole buffer so parse_start_tag can index them directly.
    let (pool, pool_strings_start) = parse_string_pool(&data[xml_header..])?;
    let _strings_start = xml_header + pool_strings_start;
    let pool_chunk_size = le32(&data[xml_header..], 4)? as usize;
    let mut result = ManifestAttrs::default();
    let mut pos = xml_header + pool_chunk_size;
    while pos + 8 <= data.len() {
        let ct = le16(data, pos)?;
        let cs = le32(data, pos + 4)? as usize;
        ensure!(pos + cs <= data.len(), "manifest: chunk extends past end");
        if ct == 0x0102 {
            let (tag_name, attrs) = parse_start_tag(data, pos, &pool)?;
            if tag_name == "manifest" {
                for a in &attrs {
                    let aname = pool.get(a.name_idx).map(|s| s.as_str());
                    match aname {
                        Some("package") => result.package_name = a.value.clone(),
                        Some("versionCode") => result.version_code = Some(a.value.clone()),
                        Some("versionName") => result.version_name = Some(a.value.clone()),
                        _ => {}
                    }
                }
            }
        }
        pos += cs;
    }
    Ok(result)
}

// --- Minimal ASN.1/DER reader ---
// Only what we need to walk PKCS#7 / X.509 (RFC 5652 / 5280).

struct Der<'a> {
    tag: u8,
    payload: &'a [u8],
}

fn der_len(data: &[u8]) -> Result<(usize, usize)> {
    ensure!(!data.is_empty(), "der_len: empty");
    let first = data[0];
    if first & 0x80 == 0 {
        return Ok((first as usize, 1));
    }
    let n = (first & 0x7F) as usize;
    ensure!(n != 0 && n <= 4, "der_len: invalid long form {n}");
    ensure!(data.len() > n, "der_len: truncated");
    let mut len = 0usize;
    for i in 0..n {
        len = (len << 8) | data[1 + i] as usize;
    }
    Ok((len, 1 + n))
}

fn der_one<'a>(data: &'a [u8]) -> Result<(Der<'a>, usize)> {
    ensure!(!data.is_empty(), "der: empty");
    let tag = data[0];
    let (len, n) = der_len(&data[1..])?;
    let hdr = 1 + n;
    ensure!(data.len() >= hdr + len, "der: element truncated");
    let payload = &data[hdr..hdr + len];
    Ok((Der { tag, payload }, hdr + len))
}

struct DerIter<'a> {
    data: &'a [u8],
}
impl<'a> DerIter<'a> {
    fn new(data: &'a [u8]) -> Self {
        Self { data }
    }
}
impl<'a> Iterator for DerIter<'a> {
    type Item = Der<'a>;
    fn next(&mut self) -> Option<Der<'a>> {
        if self.data.is_empty() {
            return None;
        }
        let (d, n) = der_one(self.data).ok()?;
        self.data = &self.data[n..];
        Some(d)
    }
}

/// Extract the CN from an X.509 certificate.
///
/// Walks the DER tree looking for the commonName attribute OID (2.5.4.3, encoded
/// `55 04 03`) and returns the printable string that follows it. A positional walk of
/// Name/RDN would depend on field ordering; searching for the OID does not.
fn extract_cn_from_cert(cert_body: &[u8]) -> Option<String> {
    find_cn(cert_body, 0)
}

/// Depth-first search for a CN attribute, bounded so a hostile certificate cannot
/// make this expensive.
fn find_cn(buf: &[u8], depth: usize) -> Option<String> {
    const MAX_DEPTH: usize = 12;
    if depth > MAX_DEPTH {
        return None;
    }
    let mut at = 0usize;
    while at + 2 <= buf.len() {
        let tag = buf[at];
        if tag & 0x1F == 0x1F {
            return None; // high-tag-number form: not something we need to walk into
        }
        let (len, hdr) = match der_len(&buf[at + 1..]) {
            Ok(v) => v,
            Err(_) => return None,
        };
        let body = at + 1 + hdr;
        let end = body.checked_add(len)?;
        if end > buf.len() {
            return None;
        }
        // An AttributeTypeAndValue is SEQUENCE { OID, value }. Recognize it structurally.
        if tag == 0x06 && buf[body..end] == [0x55, 0x04, 0x03] && end < buf.len() {
            let vt = buf[end];
            let (vlen, vhdr) = der_len(&buf[end + 1..]).ok()?;
            let vstart = end + 1 + vhdr;
            if (vt & 0x1F) == 0x0C || vt == 0x13 || vt == 0x16 {
                // UTF8String, PrintableString, IA5String
                return Some(String::from_utf8_lossy(&buf[vstart..vstart + vlen]).into_owned());
            }
            if vt == 0x1E {
                // BMPString: UTF-16BE
                let raw = &buf[vstart..vstart + vlen];
                let mut units: Vec<u16> = Vec::with_capacity(raw.len() / 2);
                let mut i = 0;
                while i + 1 < raw.len() {
                    units.push(u16::from_be_bytes([raw[i], raw[i + 1]]));
                    i += 2;
                }
                return String::from_utf16(&units).ok();
            }
        }
        if tag & 0x20 != 0 {
            // Constructed: descend.
            if let Some(found) = find_cn(&buf[body..end], depth + 1) {
                return Some(found);
            }
        }
        at = end;
    }
    None
}

/// Decode a DER length starting at `at`, returning (value, bytes consumed including tag-len).
/// Extract signer certificates from PKCS#7 SignedData.
fn extract_pkcs7_certs(p7_der: &[u8]) -> Result<Vec<(String, Option<String>)>> {
    let ci = der_one(p7_der)?.0;
    ensure!((ci.tag & 0x1F) == 0x10, "pkcs7: not a SEQUENCE");
    let mut ci_fields = DerIter::new(ci.payload);
    let _ = ci_fields.next(); // contentType OID
    let content = ci_fields.next();
    let content = match content {
        Some(d) if (d.tag & 0x1F) == 0x00 && (d.tag & 0x80) != 0 => d, // [0] context
        _ => bail!("pkcs7: content not at [0]"),
    };
    let (sd, _) = der_one(content.payload)?;
    ensure!((sd.tag & 0x1F) == 0x10, "pkcs7: signed data not SEQUENCE");
    // SignedData fields are version, digestAlgorithms, encapContentInfo and then optionally
    // certificates and crls. encapContentInfo is absent in many signatures, so find the
    // certificates SET by shape rather than by position.
    // certificates is [0] IMPLICIT SET OF Certificate, so its DER tag is 0xA0. Matching a
    // plain SET (0x31) finds digestAlgorithms instead, which is a few bytes long.
    let mut certs = None;
    for f in DerIter::new(sd.payload) {
        if f.tag == 0xA0 {
            certs = Some(f);
            break;
        }
    }
    let mut result = Vec::new();
    if let Some(certs_set) = certs {
        // SET
        for cert_wrapped in DerIter::new(certs_set.payload) {
            let cert_der = if cert_wrapped.tag == 0xA0 {
                der_one(cert_wrapped.payload)?.0.payload
            } else if (cert_wrapped.tag & 0x1F) == 0x10 {
                cert_wrapped.payload
            } else {
                continue;
            };
            let cn = extract_cn_from_cert(cert_der);
            let digest = Sha256::digest(cert_der)
                .iter()
                .map(|b| format!("{:02x}", b))
                .collect::<String>();
            result.push((cn.unwrap_or_default(), Some(digest)));
        }
    }
    Ok(result)
}

// --- APK Signature Scheme v2/v3 signing block (AOSP apk_signature_scheme.h) ---
//
// The signing block sits between the zip entries and the End Of Central Directory
// record. It is bracketed by the 16-byte magic below (as a "footer" right before the
// EOCD and again as the "header" at the start of the block) plus uint64 block-size
// fields. Inside are length-prefixed entries tagged by their 32-bit ID:
//   0x7109871a == APK Signature Scheme v2 block
//   0x7109871b == APK Signature Scheme v3 block
// (AOSP, Apache-2.0.)
const V2_BLOCK_ID: u32 = 0x7109871a;
const V3_BLOCK_ID: u32 = 0x7109871b;
/// The zip End Of Central Directory record signature (AOSP, Apache-2.0).
const EOCD_SIG: u32 = 0x06054b50;
const EOCD_MIN_SIZE: usize = 22;

// --- Entry points ---

/// Read one APK from `path` and audit it.
///
/// Never executes anything: the APK is only read as a ZIP, its binary AndroidManifest.xml is
/// parsed, and its v1 META-INF certificates are decoded. An unreadable or malformed APK
/// comes back as `ApkAudit::error`, never a panic and never a silent skip.
/// Audit an in-memory APK.
pub fn audit_apk_bytes(path: &Path, bytes: &[u8]) -> ApkAudit {
    let r = (|| -> Result<ApkInfo> {
        let mut zip = ZipArchive::new(Cursor::new(bytes)).context("not a valid zip")?;
        let attrs = match read_entry(&mut zip, "AndroidManifest.xml") {
            Some(b) => parse_manifest(&b).ok(),
            None => None,
        };
        let mut signers = Vec::new();
        let names: Vec<String> = zip.file_names().map(String::from).collect();
        for name in names {
            let upper = name.to_ascii_uppercase();
            if !(upper.starts_with("META-INF/")
                && (upper.ends_with(".RSA") || upper.ends_with(".DSA") || upper.ends_with(".EC")))
            {
                continue;
            }
            let Some(der) = read_entry(&mut zip, &name) else {
                continue;
            };
            let Ok(certs) = extract_pkcs7_certs(&der) else {
                continue;
            };
            for (cn, sha) in certs {
                signers.push(Signer {
                    scheme: "v1",
                    cert_sha256: sha.unwrap_or_default(),
                    subject_cn: Some(cn.clone()),
                    is_aosp_test_key: AOSP_TEST_KEY_SUBJECTS.iter().any(|t| cn.contains(t)),
                });
            }
        }
        signers.extend(v2_signers(bytes));
        Ok(ApkInfo {
            path: path.display().to_string(),
            package_name: attrs
                .as_ref()
                .map(|a| a.package_name.clone())
                .unwrap_or_default(),
            version_code: attrs.as_ref().and_then(|a| a.version_code.clone()),
            version_name: attrs.as_ref().and_then(|a| a.version_name.clone()),
            signers,
        })
    })();
    match r {
        Ok(info) => ApkAudit {
            info: Some(info),
            error: None,
        },
        Err(e) => ApkAudit {
            info: None,
            error: Some(format!("{e:#}")),
        },
    }
}

/// Read one entry out of the archive, refusing anything over the per-entry limit.
fn read_entry(zip: &mut ZipArchive<Cursor<&[u8]>>, name: &str) -> Option<Vec<u8>> {
    let f = zip.by_name(name).ok()?;
    if f.size() as usize > MAX_ENTRY_BYTES {
        return None;
    }
    let mut buf = Vec::new();
    f.take(MAX_ENTRY_BYTES as u64).read_to_end(&mut buf).ok()?;
    Some(buf)
}

/// Find the APK Signing Block and return the signed-data bytes it certifies.
///
/// Layout (AOSP apk_signature_scheme.h, Apache-2.0):
///
///   ... zip entries ... | uint64 size of block | pairs | uint64 size of block |
///   16-byte magic | zip EOCD
///
/// Each pair is `uint64 length` followed by `uint32 id` and that many bytes of value.
/// The signed data the signers cover is the concatenation of the three EOCD-present
/// regions, so we recover it by locating the block and slicing around it.
fn v2_signers(bytes: &[u8]) -> Vec<Signer> {
    let Some(block) = signing_block(bytes) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for (id, value) in block {
        let scheme = match id {
            V2_BLOCK_ID => "v2",
            V3_BLOCK_ID => "v3",
            _ => continue,
        };
        for s in signers_in_block(value) {
            out.push(Signer { scheme, ..s });
        }
    }
    out
}

/// The signing block pairs: (block id, value bytes).
fn signing_block(bytes: &[u8]) -> Option<Vec<(u32, &[u8])>> {
    if bytes.len() < EOCD_MIN_SIZE + 2 * 8 + MAGIC_LEN {
        return None;
    }
    // The block size is the uint64 immediately before the 16-byte footer magic, which in
    // turn sits immediately before the EOCD signature.
    let footer = bytes.len().checked_sub(EOCD_MIN_SIZE)?;
    if le32(bytes, footer).ok()? != EOCD_SIG {
        return None;
    }
    let magic_at = footer.checked_sub(MAGIC_LEN)?;
    if bytes[magic_at..magic_at + MAGIC_LEN] != MAGIC {
        return None;
    }
    let size_at = magic_at.checked_sub(8)?;
    let block_size = le64(bytes, size_at).ok()? as usize;
    if block_size < 8 || block_size > bytes.len() {
        return None;
    }
    let block_start = size_at.checked_sub(block_size)?;
    let mut out = Vec::new();
    let mut at = block_start + 8; // skip the leading size field
    let end = size_at;
    while at + 12 <= end {
        let len = le64(bytes, at).ok()? as usize;
        if len < 4 || at + 8 + len > end {
            break;
        }
        let id = le32(bytes, at + 8).ok()?;
        let vstart = at + 12;
        let vend = vstart + len - 4;
        out.push((id, &bytes[vstart..vend]));
        at += 8 + len;
    }
    Some(out)
}

/// Extract signers from one v2/v3 block value (a length-prefixed signer sequence).
fn signers_in_block(value: &[u8]) -> Vec<Signer> {
    let mut out = Vec::new();
    let mut at = 0usize;
    while at + 4 <= value.len() {
        let len = le32(value, at).unwrap_or(0) as usize;
        if len == 0 || at + 4 + len > value.len() {
            break;
        }
        let signer = &value[at + 4..at + 4 + len];
        if let Some(s) = signer_from(signer) {
            out.push(s);
        }
        at += 4 + len;
    }
    out
}

/// One signer: signed-data digest, signatures, public key, certificate (AOSP).
fn signer_from(signer: &[u8]) -> Option<Signer> {
    let mut at = 0usize;
    let mut certs: Option<Vec<u8>> = None;
    while at + 12 <= signer.len() {
        let len = le32(signer, at).ok()? as usize;
        let id = le32(signer, at + 4).ok()?;
        if len < 4 || at + 8 + len > signer.len() {
            break;
        }
        // 0x100001 == X.509 certificate (AOSP apk_signature_scheme.h).
        if id == 0x0001_0001 && certs.is_none() {
            certs = Some(signer[at + 8..at + 8 + len].to_vec());
        }
        at += 8 + len;
    }
    let der = certs?;
    let sha = Sha256::digest(&der);
    let cn = extract_cn_from_cert(&der);
    Some(Signer {
        scheme: "v2",
        cert_sha256: sha.iter().map(|b| format!("{b:02x}")).collect(),
        is_aosp_test_key: cn
            .as_deref()
            .is_some_and(|c| AOSP_TEST_KEY_SUBJECTS.iter().any(|t| c.contains(t))),
        subject_cn: cn,
    })
}

/// The 16-byte APK Signing Block magic (AOSP, Apache-2.0).
const MAGIC: [u8; 16] = [
    b'a', b'p', b'k', b' ', b'S', b'i', b'g', b' ', b'B', b'l', b'o', b'c', b'k', 0xdb, 0, 0,
];
const MAGIC_LEN: usize = 16;

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

    /// Build a minimal but real APK: a ZIP holding a binary AndroidManifest.xml and a
    /// META-INF signature entry.
    fn apk_bytes(with_manifest: bool) -> Vec<u8> {
        let mut w = zip::ZipWriter::new(Cursor::new(Vec::new()));
        let opt = zip::write::SimpleFileOptions::default();
        if with_manifest {
            w.start_file("AndroidManifest.xml", opt).unwrap();
            w.write_all(b"\x03\x00\x08\x00 fake binary manifest")
                .unwrap();
        }
        w.start_file("META-INF/CERT.RSA", opt).unwrap();
        w.write_all(b"\x30\x82 not really pkcs7").unwrap();
        w.finish().unwrap().into_inner()
    }

    #[test]
    fn an_apk_is_parsed_rather_than_reported_unreadable() {
        let a = audit_apk_bytes(std::path::Path::new("/system/app/X.apk"), &apk_bytes(true));
        assert!(a.error.is_none(), "{:?}", a.error);
        let info = a.info.expect("info");
        assert_eq!(info.path, "/system/app/X.apk");
    }

    #[test]
    fn an_apk_with_no_manifest_still_parses_without_error() {
        let a = audit_apk_bytes(std::path::Path::new("/x.apk"), &apk_bytes(false));
        assert!(a.error.is_none(), "{:?}", a.error);
        assert!(a.info.expect("info").package_name.is_empty());
    }

    #[test]
    fn a_file_that_is_not_a_zip_is_reported_not_panicked_on() {
        let a = audit_apk_bytes(std::path::Path::new("/x.apk"), b"definitely not a zip");
        assert!(a.info.is_none());
        assert!(a.error.is_some(), "an unreadable apk must say so");
    }

    #[test]
    fn a_malformed_certificate_does_not_panic_and_yields_no_signers() {
        let a = audit_apk_bytes(std::path::Path::new("/x.apk"), &apk_bytes(true));
        let info = a.info.expect("info");
        assert!(
            info.signers.is_empty(),
            "garbage DER must not become a signer"
        );
    }
}