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
//! Android Logical Partition (super.img) parsing and image splitting.
//!
//! Implements the AOSP `LpMetadataGeometry`, `LpMetadataHeader` and the four
//! partition/extent/group/block-device tables from
//! `system/core/fs_mgr/liblp/include/liblp/metadata_format.h` (Apache-2.0),
//! validated against the SR Labs extractor `liblp.py` (Apache-2.0).
//! All fields are little-endian; a sector is 512 bytes.
use anyhow::{Context, Result, ensure};
use sha2::{Digest, Sha256};

/// Offset of the primary LP geometry within the image.
const GEOMETRY_OFFSET: u64 = 4096;
/// `LpMetadataGeometry` total size in AOSP.
const GEOMETRY_SIZE: usize = 64;
/// `LpMetadataHeader` magic: "Lp0" reversed.
const LP_HEADER_MAGIC: u32 = 0x414C5030;
/// `LpMetadataGeometry` magic: "gDla".
const LP_GEOMETRY_MAGIC: u32 = 0x616C4467;
/// LP geometry magic as bytes "gDla" at offset 4096.
const LP_GEOMETRY_MAGIC_BYTES: [u8; 4] = *b"gDla";
/// Sector size in bytes.
pub const SECTOR_SIZE: u64 = 512;
/// Maximum entries per table to stop a hostile header from exhausting memory.
const MAX_ENTRIES: usize = 4096;
/// Maximum total partition image bytes.
pub const MAX_IMAGE_BYTES: u64 = 1u64 << 40;
/// Bytes the metadata blob occupies in a super image (header + tables). The AOSP
/// writer places the primary copy at offset 0 with a 4096-byte alignment.
const METADATA_ALIGN: u64 = 4096;

fn le16(b: &[u8], at: usize) -> u16 {
    u16::from_le_bytes([b[at], b[at + 1]])
}

fn le32(b: &[u8], at: usize) -> u32 {
    u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
}

fn le64(b: &[u8], at: usize) -> u64 {
    u64::from_le_bytes([
        b[at],
        b[at + 1],
        b[at + 2],
        b[at + 3],
        b[at + 4],
        b[at + 5],
        b[at + 6],
        b[at + 7],
    ])
}

/// A parsed SHA-256 digest stored as raw 32 bytes.
type Sha256Arr = [u8; 32];

/// `LpMetadataGeometry` (AOSP, Apache-2.0), 48 bytes meaningful + 16 bytes padding = 64.
#[allow(dead_code)]
struct Geometry {
    magic: u32,
    struct_size: u32,
    checksum: Sha256Arr,
    metadata_max_size: u32,
    metadata_slot_count: u32,
    logical_block_size: u32,
}

fn parse_geometry(b: &[u8]) -> Result<Geometry> {
    ensure!(!b.is_empty(), "super image is empty");
    ensure!(
        b.len() >= GEOMETRY_SIZE,
        "super image is too short for an LP geometry (need {GEOMETRY_SIZE} bytes, got {})",
        b.len()
    );
    let g = Geometry {
        magic: le32(b, 0),
        struct_size: le32(b, 4),
        checksum: read_sha256(b, 8),
        metadata_max_size: le32(b, 40),
        metadata_slot_count: le32(b, 44),
        logical_block_size: le32(b, 48),
    };
    ensure!(
        g.magic == LP_GEOMETRY_MAGIC,
        "super image: bad LP geometry magic {:#010x}",
        g.magic
    );
    ensure!(
        g.struct_size as usize >= GEOMETRY_SIZE,
        "LP geometry struct_size {} is too small",
        g.struct_size
    );
    ensure!(
        g.logical_block_size != 0 && g.logical_block_size.is_multiple_of(512),
        "LP geometry: invalid logical block size {}",
        g.logical_block_size
    );
    Ok(g)
}

/// Verify the geometry checksum: SHA-256 of the struct with the checksum field zeroed.
fn verify_geometry_checksum(g: &Geometry, b: &[u8]) -> Result<()> {
    let mut copy = b.to_vec();
    let start = 8;
    let end = start + 32;
    for byte in &mut copy[start..end] {
        *byte = 0;
    }
    let mut h = Sha256::new();
    h.update(&copy);
    let actual = h.finalize();
    ensure!(
        &g.checksum[..] == actual.as_slice(),
        "LP geometry: checksum mismatch"
    );
    Ok(())
}

/// Verify the metadata header checksum: SHA-256 of the header bytes, with the
/// header_checksum field itself zeroed, over the full header_size. AOSP verifies
/// the header region (8..header_size) with the checksum field zeroed.
fn verify_header_checksum(h: &MetadataHeader, hdr_bytes: &[u8]) -> Result<()> {
    ensure!(
        hdr_bytes.len() >= h.header_size as usize,
        "LP metadata: not enough bytes for header_size {} (got {})",
        h.header_size,
        hdr_bytes.len()
    );
    let mut copy = hdr_bytes[..h.header_size as usize].to_vec();
    // Zero the header_checksum field (at offset 12, 32 bytes) before hashing.
    for byte in &mut copy[12..44] {
        *byte = 0;
    }
    let mut hash = Sha256::new();
    hash.update(&copy);
    let actual = hash.finalize();
    ensure!(
        &h.header_checksum[..] == actual.as_slice(),
        "LP metadata: header checksum mismatch"
    );
    Ok(())
}

/// Verify the tables checksum: SHA-256 of the tables region (header_size..header_size+tables_size).
fn verify_tables_checksum(h: &MetadataHeader, tables_bytes: &[u8]) -> Result<()> {
    ensure!(
        tables_bytes.len() == h.tables_size as usize,
        "LP metadata: tables region is {} bytes but header says {}",
        tables_bytes.len(),
        h.tables_size
    );
    let mut hash = Sha256::new();
    hash.update(tables_bytes);
    let actual = hash.finalize();
    ensure!(
        &h.tables_checksum[..] == actual.as_slice(),
        "LP metadata: tables checksum mismatch"
    );
    Ok(())
}
fn read_sha256(b: &[u8], at: usize) -> [u8; 32] {
    let mut s = [0u8; 32];
    s.copy_from_slice(&b[at..at + 32]);
    s
}

/// One of the four table descriptors at the end of `LpMetadataHeader`.
struct TableDescriptor {
    offset: u32,
    num_entries: u32,
    entry_size: u32,
}

#[allow(dead_code)]
fn parse_table(b: &[u8], at: usize) -> TableDescriptor {
    TableDescriptor {
        offset: le32(b, at),
        num_entries: le32(b, at + 4),
        entry_size: le32(b, at + 8),
    }
}

/// `LpMetadataHeader` (AOSP, Apache-2.0): magic at 0, major u16, minor u16,
/// header_size u32, header_checksum sha256[32], tables_size u32,
/// tables_checksum sha256[32], then four table descriptors.
#[allow(dead_code)]
struct MetadataHeader {
    magic: u32,
    major: u16,
    minor: u16,
    header_size: u32,
    header_checksum: Sha256Arr,
    tables_size: u32,
    tables_checksum: Sha256Arr,
    partitions: TableDescriptor,
    extents: TableDescriptor,
    groups: TableDescriptor,
    block_devices: TableDescriptor,
}

/// Fixed header fields before the four table descriptors: 4 + 2 + 2 + 4 + 32 + 4 + 32 = 80.
const HEADER_FIXED_SIZE: usize = 80;
const HEADER_SIZE_MIN: usize = HEADER_FIXED_SIZE + 4 * 12;

#[allow(dead_code)]
fn parse_metadata_header(b: &[u8]) -> Result<MetadataHeader> {
    ensure!(
        b.len() >= HEADER_SIZE_MIN,
        "LP metadata header is too short (need {HEADER_SIZE_MIN} bytes, got {})",
        b.len()
    );
    let magic = le32(b, 0);
    ensure!(
        magic == LP_HEADER_MAGIC,
        "LP metadata: bad header magic {:#010x}",
        magic
    );
    let header = MetadataHeader {
        magic,
        major: le16(b, 4),
        minor: le16(b, 6),
        header_size: le32(b, 8),
        header_checksum: read_sha256(b, 12),
        tables_size: le32(b, 44),
        tables_checksum: read_sha256(b, 48),
        partitions: parse_table(b, 60),
        extents: parse_table(b, 72),
        groups: parse_table(b, 84),
        block_devices: parse_table(b, 96),
    };
    ensure!(
        header.header_size as usize >= HEADER_SIZE_MIN,
        "LP metadata header_size {} is too small",
        header.header_size
    );
    ensure!(
        header.major >= 1,
        "LP metadata: unsupported major version {}",
        header.major
    );
    Ok(header)
}

/// Slot-suffixed attribute flag bit.
#[allow(dead_code)]
const PARTITION_ATTR_SLOT_SUFFIXED: u32 = 0x1;
/// LP extent types.
const EXTENT_LINEAR: u32 = 0;
const EXTENT_ZERO: u32 = 1;

/// `LpMetadataPartition` (AOSP, Apache-2.0): name[36], attributes u32,
/// first_extent_index u32, num_extents u32, group_index u32. Total = 52 bytes.
const PARTITION_SIZE: usize = 52;

#[derive(Clone)]
#[allow(dead_code)]
struct Partition {
    name: String,
    attributes: u32,
    first_extent_index: u32,
    num_extents: u32,
    group_index: u32,
}

fn parse_partition(b: &[u8]) -> Result<Partition> {
    ensure!(b.len() >= PARTITION_SIZE, "partition entry is too short");
    let name = read_name(&b[0..36])?;
    Ok(Partition {
        name,
        attributes: le32(b, 36),
        first_extent_index: le32(b, 40),
        num_extents: le32(b, 44),
        group_index: le32(b, 48),
    })
}

/// `LpMetadataExtent` (AOSP, Apache-2.0): num_sectors u64, target_type u32,
/// target_data u64, target_source u32. Total = 28 bytes.
const EXTENT_SIZE: usize = 28;

#[derive(Clone, Copy)]
pub struct Extent {
    #[allow(dead_code)]
    /// Number of 512-byte sectors this extent covers.
    pub num_sectors: u64,
    /// Extent target type: 0 = linear (mapped), 1 = zero (unmapped).
    pub target_type: u32,
    /// For linear extents: the physical sector number in the image.
    pub target_data: u64,
    /// For linear extents: the source block device index.
    #[allow(dead_code)]
    pub target_source: u32,
}

fn parse_extent(b: &[u8]) -> Result<Extent> {
    ensure!(b.len() >= EXTENT_SIZE, "extent entry is too short");
    Ok(Extent {
        num_sectors: le64(b, 0),
        target_type: le32(b, 8),
        target_data: le64(b, 12),
        target_source: le32(b, 20),
    })
}

/// `LpMetadataPartitionGroup` (AOSP, Apache-2.0): name[36], flags u32,
/// maximum_size u64. Total = 48 bytes.
const GROUP_SIZE: usize = 48;

#[derive(Clone)]
#[allow(dead_code)]
struct Group {
    name: String,
    flags: u32,
    maximum_size: u64,
}

fn parse_group(b: &[u8]) -> Result<Group> {
    ensure!(b.len() >= GROUP_SIZE, "group entry is too short");
    let name = read_name(&b[0..36])?;
    Ok(Group {
        name,
        flags: le32(b, 36),
        maximum_size: le64(b, 40),
    })
}

/// `LpMetadataBlockDevice` (AOSP, Apache-2.0): first_logical_sector u64,
/// partition_name[36], flags u32, size u64. Total = 56 bytes.
const BLOCK_DEVICE_SIZE: usize = 56;

#[derive(Clone)]
#[allow(dead_code)]
struct BlockDevice {
    first_logical_sector: u64,
    partition_name: String,
    flags: u32,
    size: u64,
}

fn parse_block_device(b: &[u8]) -> Result<BlockDevice> {
    ensure!(
        b.len() >= BLOCK_DEVICE_SIZE,
        "block_device entry is too short"
    );
    let partition_name = read_name(&b[8..44])?;
    Ok(BlockDevice {
        first_logical_sector: le64(b, 0),
        partition_name,
        flags: le32(b, 44),
        size: le64(b, 48),
    })
}

/// Read a null-terminated name from a fixed-size byte slice.
fn read_name(b: &[u8]) -> Result<String> {
    let nul = b.iter().position(|&c| c == 0).unwrap_or(b.len());
    let name = &b[..nul];
    String::from_utf8(name.to_vec()).with_context(|| "LP name is not valid UTF-8")
}

type Tables = (Vec<Partition>, Vec<Extent>, Vec<Group>, Vec<BlockDevice>);
fn parse_tables(tables: &[u8], h: &MetadataHeader) -> Result<Tables> {
    let parts = parse_entries::<Partition>(tables, &h.partitions, PARTITION_SIZE, parse_partition)?;
    let extents = parse_entries::<Extent>(tables, &h.extents, EXTENT_SIZE, parse_extent)?;
    let groups = parse_entries::<Group>(tables, &h.groups, GROUP_SIZE, parse_group)?;
    let bdevs = parse_entries::<BlockDevice>(
        tables,
        &h.block_devices,
        BLOCK_DEVICE_SIZE,
        parse_block_device,
    )?;
    Ok((parts, extents, groups, bdevs))
}

fn parse_entries<T>(
    tables: &[u8],
    td: &TableDescriptor,
    entry_size: usize,
    parse_one: fn(&[u8]) -> Result<T>,
) -> Result<Vec<T>> {
    ensure!(td.entry_size as usize == entry_size, "wrong LP entry size");
    let total = td.num_entries as usize * entry_size;
    let start = td.offset as usize;
    ensure!(tables.len() >= start + total, "LP table truncated");
    ensure!(
        td.num_entries <= MAX_ENTRIES as u32,
        "LP table claims too many entries: {n}",
        n = td.num_entries
    );
    let mut out = Vec::with_capacity(td.num_entries as usize);
    let mut i = start;
    for _ in 0..td.num_entries {
        let chunk = tables
            .get(i..i + entry_size)
            .context("LP table entry is too short")?;
        out.push(parse_one(chunk)?);
        i += entry_size;
    }
    Ok(out)
}

/// A partition joined with its extents, for splitting a super image.
pub struct ParsedPart {
    name: String,
    extents: Vec<Extent>,
    _group: String,
}

/// Parse super image bytes into partitions with their extents.
/// Validates geometry + header + table checksums (AOSP, Apache-2.0).
pub fn parse_metadata(image: &[u8]) -> Result<Vec<ParsedPart>> {
    ensure!(!image.is_empty(), "super image is empty");
    let gstart = GEOMETRY_OFFSET as usize;
    let g = parse_geometry(
        image
            .get(gstart..gstart + GEOMETRY_SIZE)
            .context("super image too short for geometry")?,
    )?;
    verify_geometry_checksum(
        &g,
        image
            .get(gstart..gstart + GEOMETRY_SIZE)
            .context("super image too short for geometry")?,
    )?;
    let hdr_off = GEOMETRY_OFFSET + METADATA_ALIGN;
    let header_bytes = image
        .get(hdr_off as usize..)
        .context("no LP metadata header region")?;
    let h = parse_metadata_header(header_bytes)?;
    verify_header_checksum(&h, header_bytes)?;
    let tables_start = hdr_off as usize + h.header_size as usize;
    let tables = image
        .get(tables_start..tables_start + h.tables_size as usize)
        .context("LP tables region is truncated")?;
    verify_tables_checksum(&h, tables)?;
    let (parts, extents, _groups, _bdevs) = parse_tables(tables, &h)?;
    let mut out = Vec::new();
    for p in parts {
        let start = p.first_extent_index as usize;
        let end = start + p.num_extents as usize;
        let pext = extents
            .get(start..end)
            .context("partition extents out of range")?
            .to_vec();
        out.push(ParsedPart {
            name: p.name,
            extents: pext,
            _group: String::new(),
        });
    }
    Ok(out)
}

/// Split parsed super partitions into per-partition images; linear extents copy
/// from `image`, zero extents emit zeroes. `only` filters by partition name.
pub fn split_partitions(
    image: &[u8],
    parsed: &[ParsedPart],
    only: Option<&[String]>,
) -> Result<Vec<(String, Vec<u8>)>> {
    let mut out = Vec::new();
    'p: for part in parsed {
        if let Some(only) = only {
            let found = only.iter().any(|o| o == &part.name);
            if !found {
                continue 'p;
            }
        }
        let total: u64 = part
            .extents
            .iter()
            .map(|e| e.num_sectors * SECTOR_SIZE)
            .sum();
        ensure!(
            total <= MAX_IMAGE_BYTES,
            "partition {} is too large",
            part.name
        );
        let mut buf = Vec::with_capacity(total as usize);
        for e in &part.extents {
            ensure!(
                e.target_type == EXTENT_LINEAR || e.target_type == EXTENT_ZERO,
                "partition {}: unsupported extent type {}",
                part.name,
                e.target_type
            );
            let len = (e.num_sectors * SECTOR_SIZE) as usize;
            if e.target_type == EXTENT_ZERO {
                buf.extend(std::iter::repeat_n(0u8, len));
            } else {
                let start = (e.target_data * SECTOR_SIZE) as usize;
                let end = start + len;
                let chunk = image
                    .get(start..end)
                    .context("LP extent runs past end of super image")?;
                buf.extend_from_slice(chunk);
            }
        }
        out.push((part.name.clone(), buf));
    }
    Ok(out)
}

/// True if the file's bytes carry the LP geometry magic at offset 4096.
#[allow(dead_code)]
pub fn is_super(path: &std::path::Path) -> Result<bool> {
    let mut file = std::fs::File::open(path)?;
    use std::io::{Read, Seek, SeekFrom};
    file.seek(SeekFrom::Start(4096))?;
    let mut magic = [0u8; 4];
    let n = file.read(&mut magic)?;
    Ok(n == 4 && magic == LP_GEOMETRY_MAGIC_BYTES)
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::testutil::Scratch;

    #[test]
    fn is_super_detects_magic() {
        let mut img = vec![0u8; 8200];
        img[4096..4100].copy_from_slice(b"gDla");
        let d = Scratch::new("lp-super");
        let p = d.join("super.img");
        std::fs::write(&p, &img).unwrap();
        assert!(is_super(&p).unwrap());
    }

    #[test]
    fn is_super_rejects_plain_bytes() {
        let d = Scratch::new("lp-nosuper");
        let p = d.join("not.img");
        std::fs::write(&p, [0u8; 8200]).unwrap();
        assert!(!is_super(&p).unwrap());
    }
}