Compare commits

...

26 Commits

Author SHA1 Message Date
Andrew Gunnerson dac4e8d328 Version 2.2.0
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-10-04 14:58:01 -04:00
Andrew Gunnerson 3cc078ccfb CHANGELOG.md: Add entry for PR #181
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-10-03 21:03:32 -04:00
Andrew Gunnerson b47b51114f Merge pull request #181 from chenxiaolong/deps
Update ring to 0.17.0
2023-10-03 21:02:26 -04:00
Andrew Gunnerson 09048a00d2 Update ring to 0.17.0
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-10-03 20:51:16 -04:00
Andrew Gunnerson ca0e80521f README.md: Fix typo in magisk-info subcommand
Fixes: #180

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-10-03 14:02:57 -04:00
Andrew Gunnerson 6491106df0 Add names to all Github Actions workflows
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-10-01 19:33:58 -04:00
Andrew Gunnerson 2e8fa31207 Merge pull request #179 from chenxiaolong/ci
ci.yml: Only cancel previous runs for pull requests
2023-10-01 19:24:48 -04:00
Andrew Gunnerson d69fdaadae ci.yml: Only cancel previous runs for pull requests
Fixes: #177

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-10-01 19:09:58 -04:00
Andrew Gunnerson f0a631951a CHANGELOG.md: Add entry for PR #178
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-10-01 16:39:13 -04:00
Andrew Gunnerson 83265e584a Merge pull request #178 from chenxiaolong/cpio
cpio: Only reassign inodes when missing
2023-10-01 16:38:13 -04:00
Andrew Gunnerson ddb8911efd cpio: Only reassign inodes when missing
This way, archives with hard links can pass through `cpio unpack` and
`cpio pack`, even though there's no explicit support for hard links.

This also changes the trailer entry logic to not set an inode number.
AOSP's mkbootfs and magiskboot both start at 300000 and increment by one
for each entry, including the trailer. However, GNU cpio, bsdcpio,
busybox, and toybox all set it to 0, which makes more sense given that
it doesn't represent anything on disk.

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-10-01 16:16:04 -04:00
Andrew Gunnerson 72be84b2fc CHANGELOG.md: Add entry for PR #176
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-09-30 23:19:53 -04:00
Andrew Gunnerson 81d77d8610 Merge pull request #176 from chenxiaolong/prost
Switch to prost for protobuf encoding/decoding
2023-09-30 23:18:55 -04:00
Andrew Gunnerson 4651b755ba Switch to prost for protobuf encoding/decoding
There are several things we had to work around with quick-protobuf, like
forcing no_std mode to use BTreeMaps and avoiding helper functions to
read and write non-size-delimited messages. In addition, the pb-rs code
generator doesn't support adding #[derive]s to enums and the existing
support for adding derives to structs is broken due to incorrect string
concatenation.

Prost doesn't have these limitations and bugs. I originally avoided it
because prost_build required the external `protoc` binary, but now that
the protox library exists, the code generation can be done entirely in
Rust without external tools.

Prost also fully supports adding custom attributes to structs, enums,
and fields. This will be helpful for future payload unpack and pack
commands where the payload manifest would have to be serialized to TOML.

The e2e checksums had to be updated because prost's serialized bytes on
the wire differ from quick-protobuf, despite having the same semantic
meaning. Since all checksums need to be updated anyway, the Magisk apk
and OTA images have all been updated to the latest versions.

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-09-30 22:27:46 -04:00
Andrew Gunnerson 979699e3dc CHANGELOG.md: Add entry for PR #175
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-09-30 20:03:06 -04:00
Andrew Gunnerson beee2c7c90 Merge pull request #175 from chenxiaolong/boot
boot: Rename header.toml to boot.toml for consistency
2023-09-30 20:00:11 -04:00
Andrew Gunnerson 206916e544 boot: Rename header.toml to boot.toml for consistency
This also changes the serialization to use a `type` field instead of
spewing the enum variant name everywhere.

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-09-30 19:43:04 -04:00
Andrew Gunnerson aaed44ad73 CHANGELOG.md: Add entry for PR #174
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-09-30 19:42:47 -04:00
Andrew Gunnerson 37b33f803a Merge pull request #174 from chenxiaolong/deps
Update dependencies
2023-09-30 19:41:30 -04:00
Andrew Gunnerson e72b55dc57 Update dependencies
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-09-30 19:23:30 -04:00
Andrew Gunnerson 5b01feb344 CHANGELOG.md: Add entry for PR #173
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-09-30 17:51:18 -04:00
Andrew Gunnerson 2f7556b530 Merge pull request #173 from chenxiaolong/cpio
Add CLI for packing and unpacking cpio archive
2023-09-30 17:49:54 -04:00
Andrew Gunnerson f25196f0a2 Add CLI for packing and unpacking cpio archive
The new commands behave exactly like the existing `avb` and `boot`
subcommands. This completes the last piece of the puzzle for exposing
useful interfaces to avbroot's internal parsers.

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-09-30 00:50:30 -04:00
Andrew Gunnerson 2735a6558e CHANGELOG.md: Add entry for PR #172
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-09-29 19:10:39 -04:00
Andrew Gunnerson 0c03fceb96 Merge pull request #172 from chenxiaolong/cpio
Add streaming CPIO reader and writer
2023-09-29 19:09:20 -04:00
Andrew Gunnerson 164274eb97 Add streaming CPIO reader and writer
The Magisk boot image patcher still reads all the entries into memory
for simplicity, but everything else now uses the streaming reader.

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2023-09-29 18:47:37 -04:00
38 changed files with 1658 additions and 803 deletions
+3 -2
View File
@@ -5,9 +5,10 @@ on:
- master
pull_request:
# This allows a subsequently queued workflow run to interrupt previous runs
# This allows a subsequently queued workflow run to interrupt previous runs, but
# only in pull requests.
concurrency:
group: '${{ github.workflow }} @ ${{ github.event.pull_request.head.label || github.head_ref || github.ref }}'
group: '${{ github.workflow }} @ ${{ github.head_ref || github.sha }}'
cancel-in-progress: true
jobs:
+1
View File
@@ -1,4 +1,5 @@
---
name: cargo-deny
on:
push:
branches:
+1
View File
@@ -1,4 +1,5 @@
---
name: Modules
on:
push:
branches:
+1
View File
@@ -1,4 +1,5 @@
---
name: Github Release
on:
push:
# Uncomment to test against a branch
+23
View File
@@ -7,6 +7,22 @@
to update the actual links at the bottom of the file.
-->
### Version 2.2.0
It's Android 14 release day! All versions of avbroot, including the old Python version, are compatible with Android 14 OTAs.
Changes:
* Add new unpack and pack commands for cpio archives (ramdisks) ([PR #173], [PR #178])
* Rename `header.toml` to `boot.toml` for the boot image unpack and pack commands ([PR #175])
* Also changes the file format a bit to make it more readable.
Behind-the-scenes changes:
* Add streaming CPIO reader and writer ([PR #172])
* Update dependencies ([PR #174], [PR #181])
* Switch to prost for protobuf encoding/decoding ([PR #176])
### Version 2.1.1
This release is all about hardening avbroot against untrusted (or corrupted) inputs. While all of avbroot's parsers are memory-safe, it's still possible for crashes to occur due to logic issues like allocating too much memory or dividing by zero. With this release, most of these potential issues have been fixed and fuzz tests have been added to help find more of these situations.
@@ -94,3 +110,10 @@ Behind-the-scenes changes:
[PR #169]: https://github.com/chenxiaolong/avbroot/pull/169
[PR #170]: https://github.com/chenxiaolong/avbroot/pull/170
[PR #171]: https://github.com/chenxiaolong/avbroot/pull/171
[PR #172]: https://github.com/chenxiaolong/avbroot/pull/172
[PR #173]: https://github.com/chenxiaolong/avbroot/pull/173
[PR #174]: https://github.com/chenxiaolong/avbroot/pull/174
[PR #175]: https://github.com/chenxiaolong/avbroot/pull/175
[PR #176]: https://github.com/chenxiaolong/avbroot/pull/176
[PR #178]: https://github.com/chenxiaolong/avbroot/pull/178
[PR #181]: https://github.com/chenxiaolong/avbroot/pull/181
Generated
+321 -229
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -4,7 +4,7 @@ members = ["avbroot", "e2e", "fuzz", "xtask"]
resolver = "2"
[workspace.package]
version = "2.1.1"
version = "2.2.0"
license = "GPL-3.0-only"
edition = "2021"
repository = "https://github.com/chenxiaolong/avbroot"
+43 -25
View File
@@ -68,7 +68,7 @@ By default, this command will not write to any file and fails if an image is cor
avbroot boot unpack -i <input boot image>
```
This subcommand unpacks all of the components of the boot image into the current directory by default (see `--help`). The header fields are saved to `header.toml` and each blob section is saved to a separate file. Each blob is written to disk as-is, without decompression.
This subcommand unpacks all of the components of the boot image into the current directory by default (see `--help`). The header fields are saved to `boot.toml` and each blob section is saved to a separate file. Each blob is written to disk as-is, without decompression.
### Packing a boot image
@@ -94,6 +94,48 @@ avbroot boot info -i <input boot image>
All of the `boot` subcommands show the boot image information. This specific subcommand just does it without performing any other operation. To show avbroot's internal representation of the information, pass in `-d`.
## `avbroot cpio`
### Unpacking a cpio archive
```bash
avbroot cpio unpack -i <input cpio archive>
```
This subcommand unpacks the cpio archive. The list of file entries and their metadata, like permissions, are written to `cpio.toml`. The contents of regular files are extracted to `cpio_tree/`. Other file types, like symlinks and block devices, are not extracted at all. Their information only exists in the TOML file.
The files inside the tree will have default permissions, ownership, and modification timestamps. This metadata exists only inside the TOML file in order to ensure that the behavior is the same across all platforms.
Both uncompressed archives and compressed archives (gzip or legacy lz4) are supported.
### Packing a cpio archive
```bash
avbroot cpio pack -o <output cpio archive>
```
This subcommand packs a new cpio archive from the file entries listed in `cpio.toml` and the file contents in `cpio_tree/`. Note that **only entries listed in the TOML file are packed**. Extra files inside the tree are silently ignored.
The files are packed in the order listed in the TOML file. When packing ramdisks specifically, it's important to ensure that files are listed after their parent directories (which also **must** exist). Otherwise, the kernel will ignore them. As long as the file paths don't contain anything weird (eg. `a//b` or `a/./b`), sorting the entires with `--sort` should do the trick.
The new archive will be written in the same format (compressed or uncompressed) as the original archive.
### Repacking a cpio archive
```bash
avbroot cpio repack -i <input cpio archive> -o <output cpio archive>
```
This is almost equivalent to running `avbroot cpio unpack` followed by `avbroot cpio pack`, except inode numbers will not be reassigned.
### Showing information about a cpio archive
```bash
avbroot cpio info -i <input cpio archive>
```
All of the `cpio` subcommands show details about all the entries in the archive. This specific subcommand just does it without performing any other operation.
## `avbroot fec`
This set of commands is for working with dm-verity FEC (forward error correction) data. The FEC data allows small errors in partition data to be corrected. This increases reliability of the system because when dm-verity encounters data that doesn't match the expected checksum, it will either trigger a kernel panic or reboot the system.
@@ -150,27 +192,3 @@ avbroot fec repair -i <input/output data file> -f <input FEC file>
This will repair the file in place. As described above, in each column, up to `parity / 2` bytes can be corrected.
Note that FEC is **not** a replacement for checksums, like SHA-256. When there are too many errors, the file can potentially be "successfully repaired" to some incorrect data.
## `avbroot ramdisk`
### Dumping a cpio archive
```bash
avbroot ramdisk dump -i <cpio archive>
```
This subcommand dumps all information about a cpio archive to stdout. This includes the compression format, all header fields (including the trailer entry), and all data. If an entry's data can be decoded as UTF-8, then it is printed out as text. Otherwise, the binary data is printed out `\x##`-encoded for non-ASCII bytes. The escape-encoded data is truncated to 512 bytes by default to avoid outputting too much data, but this behavior can be disabled with `--no-truncate`.
### Repacking a cpio archive
```bash
avbroot ramdisk repack -i <input cpio archive> -o <output cpio archive>
```
This subcommand repacks a cpio archive, including recompression if needed. This is useful for roundtrip testing of avbroot's cpio parser and compression handling. The uncompressed output should be identical to the uncompressed input, except:
* files are sorted by name
* inodes are reassigned, starting from 300000
* there is no excess padding at the end of the file
The compressed output may differ from what other tools produce due to differences in compression levels and header metadata. avbroot avoids specifying header information where possible (eg. gzip timestamp) for reproducibility.
+1 -1
View File
@@ -189,7 +189,7 @@ Magisk versions 25211 and newer require a writable partition for storing custom
Alternatively, avbroot can print out what Magisk detected by running:
```bash
avbroot ota magisk-info \
avbroot boot magisk-info \
--image magisk_patched-*.img
```
+5 -5
View File
@@ -29,7 +29,7 @@ num-bigint-dig = "0.8.4"
num-traits = "0.2.16"
phf = { version = "0.11.2", features = ["macros"] }
pkcs8 = { version = "0.10.2", features = ["encryption", "pem"] }
quick-protobuf = "0.8.1"
prost = "0.12.1"
rand = "0.8.5"
rayon = "1.7.0"
regex = { version = "1.9.4", default-features = false, features = ["perf", "std"] }
@@ -37,7 +37,7 @@ regex = { version = "1.9.4", default-features = false, features = ["perf", "std"
# because sha2 is significantly slower on older x86_64 CPUs without the SHA-NI
# instructions. sha2 is still used for signing purposes.
# https://github.com/RustCrypto/hashes/issues/327
ring = "0.16.20"
ring = "0.17.0"
rpassword = "7.2.0"
rsa = { version = "0.9.2", features = ["sha1", "sha2"] }
serde = { version = "1.0.188", features = ["derive"] }
@@ -45,7 +45,7 @@ sha1 = "0.10.5"
sha2 = "0.10.7"
tempfile = "3.8.0"
thiserror = "1.0.47"
toml_edit = { version = "0.19.14", features = ["serde"] }
toml_edit = { version = "0.20.1", features = ["serde"] }
topological-sort = "0.2.2"
x509-cert = { version = "0.2.4", features = ["builder"] }
@@ -77,8 +77,8 @@ features = ["deflate"]
rustix = { version = "0.38.9", default-features = false, features = ["process"] }
[build-dependencies]
# Disable the clap feature since it pulls in an ancient version of clap.
pb-rs = { version = "0.10.0", default-features = false }
prost-build = "0.12.1"
protox = "0.5.0"
[dev-dependencies]
assert_matches = "1.5.0"
+5 -11
View File
@@ -5,8 +5,6 @@
use std::{env, ffi::OsStr, fs, io, path::Path};
use pb_rs::{types::FileDescriptor, ConfigBuilder};
fn main() {
let out_dir = Path::new(&env::var("OUT_DIR").unwrap()).join("protobuf");
let in_dir = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap()).join("protobuf");
@@ -30,14 +28,10 @@ fn main() {
fs::create_dir_all(&out_dir).unwrap();
let config = ConfigBuilder::new(&protos, None, Some(&out_dir), &[in_dir])
.unwrap()
.dont_use_cow(true)
// We're using this as a means to force quick-protobuf to use BTreeMap
// instead of HashMap so that the serialized messages are reproducible.
// https://github.com/tafia/quick-protobuf/issues/251
.nostd(true)
.build();
let file_descriptors = protox::compile(&protos, [&in_dir]).unwrap();
FileDescriptor::run(&config).unwrap();
prost_build::Config::new()
.btree_map(["."])
.compile_fds(file_descriptors)
.unwrap();
}
+66 -55
View File
@@ -32,7 +32,7 @@ use crate::{
avb::{self, Descriptor},
bootimage::{self, BootImage, BootImageExt, RamdiskMeta},
compression::{self, CompressedFormat, CompressedReader, CompressedWriter},
cpio::{self, CpioEntryNew},
cpio::{self, CpioEntry, CpioEntryData},
},
stream::{self, FromReader, HashingWriter, SectionReader, ToWriter},
};
@@ -73,18 +73,25 @@ pub enum Error {
type Result<T> = std::result::Result<T, Error>;
fn load_ramdisk(data: &[u8]) -> Result<(Vec<CpioEntryNew>, CompressedFormat)> {
fn load_ramdisk(
data: &[u8],
cancel_signal: &AtomicBool,
) -> Result<(Vec<CpioEntry>, CompressedFormat)> {
let raw_reader = Cursor::new(data);
let mut reader = CompressedReader::new(raw_reader, false)?;
let entries = cpio::load(&mut reader, false)?;
let entries = cpio::load(&mut reader, false, cancel_signal)?;
Ok((entries, reader.format()))
}
fn save_ramdisk(entries: &[CpioEntryNew], format: CompressedFormat) -> Result<Vec<u8>> {
fn save_ramdisk(
entries: &[CpioEntry],
format: CompressedFormat,
cancel_signal: &AtomicBool,
) -> Result<Vec<u8>> {
let raw_writer = Cursor::new(vec![]);
let mut writer = CompressedWriter::new(raw_writer, format)?;
cpio::save(&mut writer, entries, false)?;
cpio::save(&mut writer, entries, false, cancel_signal)?;
let raw_writer = writer.finish()?;
Ok(raw_writer.into_inner())
@@ -193,7 +200,7 @@ impl MagiskRootPatcher {
/// entries as `.backup/<path>`.
///
/// Both lists and entries within the lists may be mutated.
fn apply_magisk_backup(old_entries: &mut [CpioEntryNew], new_entries: &mut Vec<CpioEntryNew>) {
fn apply_magisk_backup(old_entries: &mut [CpioEntry], new_entries: &mut Vec<CpioEntry>) {
cpio::sort(old_entries);
cpio::sort(new_entries);
@@ -205,20 +212,20 @@ impl MagiskRootPatcher {
loop {
match (old_iter.peek(), new_iter.peek()) {
(Some(&old), Some(&new)) => match old.name.cmp(&new.name) {
(Some(&old), Some(&new)) => match old.path.cmp(&new.path) {
Ordering::Less => {
to_back_up.push(old);
old_iter.next();
}
Ordering::Equal => {
if old.content != new.content {
if old.data != new.data {
to_back_up.push(old);
}
old_iter.next();
new_iter.next();
}
Ordering::Greater => {
rm_list.extend(&new.name);
rm_list.extend(&new.path);
rm_list.push(b'\0');
new_iter.next();
}
@@ -228,7 +235,7 @@ impl MagiskRootPatcher {
old_iter.next();
}
(None, Some(new)) => {
rm_list.extend(&new.name);
rm_list.extend(&new.path);
rm_list.push(b'\0');
new_iter.next();
}
@@ -236,22 +243,20 @@ impl MagiskRootPatcher {
}
}
// Intentially using 000 permissions to match Magisk.
new_entries.push(CpioEntryNew::new_directory(b".backup"));
new_entries.push(CpioEntry::new_directory(b".backup", 0));
for old_entry in to_back_up {
let mut new_entry = old_entry.clone();
new_entry.name = b".backup/".to_vec();
new_entry.name.extend(&old_entry.name);
new_entry.path = b".backup/".to_vec();
new_entry.path.extend(&old_entry.path);
new_entries.push(new_entry);
}
{
// Intentially using 000 permissions to match Magisk.
let mut entry = CpioEntryNew::new_file(b".backup/.rmlist");
entry.content = rm_list;
new_entries.push(entry);
}
new_entries.push(CpioEntry::new_file(
b".backup/.rmlist",
0,
CpioEntryData::Data(rm_list),
));
}
}
@@ -269,7 +274,7 @@ impl BootImagePatcher for MagiskRootPatcher {
BootImage::VendorV3Through4(b) => b.ramdisks.first(),
};
let (mut entries, ramdisk_format) = match ramdisk {
Some(r) if !r.is_empty() => load_ramdisk(r)?,
Some(r) if !r.is_empty() => load_ramdisk(r, cancel_signal)?,
_ => (vec![], CompressedFormat::Lz4Legacy),
};
@@ -280,13 +285,11 @@ impl BootImagePatcher for MagiskRootPatcher {
(b"overlay.d".as_slice(), 0o750),
(b"overlay.d/sbin".as_slice(), 0o750),
] {
let mut entry = CpioEntryNew::new_directory(path);
entry.mode |= perms;
entries.push(entry);
entries.push(CpioEntry::new_directory(path, perms));
}
// Delete the original init.
entries.retain(|e| e.name != b"init");
entries.retain(|e| e.path != b"init");
// Add magiskinit.
{
@@ -294,10 +297,11 @@ impl BootImagePatcher for MagiskRootPatcher {
let mut data = vec![];
zip_entry.read_to_end(&mut data)?;
let mut entry = CpioEntryNew::new_file(b"init");
entry.mode |= 0o750;
entry.content = data;
entries.push(entry);
entries.push(CpioEntry::new_file(
b"init",
0o750,
CpioEntryData::Data(data),
));
}
// Add xz-compressed magisk32 and magisk64.
@@ -326,10 +330,12 @@ impl BootImagePatcher for MagiskRootPatcher {
stream::copy(reader, &mut writer, cancel_signal)?;
let raw_writer = writer.finish()?;
let mut entry = CpioEntryNew::new_file(target);
entry.mode |= 0o644;
entry.content = raw_writer.into_inner();
entries.push(entry);
entries.push(CpioEntry::new_file(
target,
0o644,
CpioEntryData::Data(raw_writer.into_inner()),
));
}
// Create Magisk .backup directory structure.
@@ -359,17 +365,16 @@ impl BootImagePatcher for MagiskRootPatcher {
magisk_config.push_str(&format!("RANDOMSEED={:#x}\n", self.random_seed));
}
{
// Intentially using 000 permissions to match Magisk.
let mut entry = CpioEntryNew::new_file(b".backup/.magisk");
entry.content = magisk_config.into_bytes();
entries.push(entry);
}
entries.push(CpioEntry::new_file(
b".backup/.magisk",
0,
CpioEntryData::Data(magisk_config.into_bytes()),
));
// Repack ramdisk.
cpio::sort(&mut entries);
cpio::reassign_inodes(&mut entries);
let new_ramdisk = save_ramdisk(&entries, ramdisk_format)?;
cpio::assign_inodes(&mut entries, false)?;
let new_ramdisk = save_ramdisk(&entries, ramdisk_format, cancel_signal)?;
match boot_image {
BootImage::V0Through2(b) => b.ramdisk = new_ramdisk,
@@ -408,7 +413,10 @@ impl OtaCertPatcher {
Self { cert }
}
pub fn get_certificates(boot_image: &BootImage) -> Result<Vec<Certificate>> {
pub fn get_certificates(
boot_image: &BootImage,
cancel_signal: &AtomicBool,
) -> Result<Vec<Certificate>> {
let mut ramdisks = vec![];
match boot_image {
@@ -420,12 +428,15 @@ impl OtaCertPatcher {
let mut certificates = vec![];
for ramdisk in ramdisks {
let (entries, _) = load_ramdisk(ramdisk)?;
let Some(entry) = entries.iter().find(|e| e.name == Self::OTACERTS_PATH) else {
let (entries, _) = load_ramdisk(ramdisk, cancel_signal)?;
let Some(entry) = entries.iter().find(|e| e.path == Self::OTACERTS_PATH) else {
continue;
};
let CpioEntryData::Data(data) = &entry.data else {
continue;
};
let mut zip = ZipArchive::new(Cursor::new(&entry.content))?;
let mut zip = ZipArchive::new(Cursor::new(&data))?;
for index in 0..zip.len() {
let zip_entry = zip.by_index(index)?;
@@ -441,16 +452,16 @@ impl OtaCertPatcher {
Ok(certificates)
}
fn patch_ramdisk(&self, data: &mut Vec<u8>) -> Result<bool> {
let (mut entries, ramdisk_format) = load_ramdisk(data)?;
let Some(entry) = entries.iter_mut().find(|e| e.name == Self::OTACERTS_PATH) else {
fn patch_ramdisk(&self, data: &mut Vec<u8>, cancel_signal: &AtomicBool) -> Result<bool> {
let (mut entries, ramdisk_format) = load_ramdisk(data, cancel_signal)?;
let Some(entry) = entries.iter_mut().find(|e| e.path == Self::OTACERTS_PATH) else {
return Ok(false);
};
// Create a new otacerts archive. The old certs are ignored since
// flashing a stock OTA will render the device unbootable.
{
let raw_writer = Cursor::new(vec![]);
let raw_writer = Cursor::new(Vec::new());
let mut writer = ZipWriter::new(raw_writer);
let options = FileOptions::default().compression_method(CompressionMethod::Stored);
writer.start_file("ota.x509.pem", options)?;
@@ -458,26 +469,26 @@ impl OtaCertPatcher {
crypto::write_pem_cert(&mut writer, &self.cert)?;
let raw_writer = writer.finish()?;
entry.content = raw_writer.into_inner();
entry.data = CpioEntryData::Data(raw_writer.into_inner());
}
// Repack ramdisk.
*data = save_ramdisk(&entries, ramdisk_format)?;
*data = save_ramdisk(&entries, ramdisk_format, cancel_signal)?;
Ok(true)
}
}
impl BootImagePatcher for OtaCertPatcher {
fn patch(&self, boot_image: &mut BootImage, _cancel_signal: &AtomicBool) -> Result<()> {
fn patch(&self, boot_image: &mut BootImage, cancel_signal: &AtomicBool) -> Result<()> {
let patched_any = match boot_image {
BootImage::V0Through2(b) => self.patch_ramdisk(&mut b.ramdisk)?,
BootImage::V3Through4(b) => self.patch_ramdisk(&mut b.ramdisk)?,
BootImage::V0Through2(b) => self.patch_ramdisk(&mut b.ramdisk, cancel_signal)?,
BootImage::V3Through4(b) => self.patch_ramdisk(&mut b.ramdisk, cancel_signal)?,
BootImage::VendorV3Through4(b) => {
let mut patched = false;
for ramdisk in &mut b.ramdisks {
if self.patch_ramdisk(ramdisk)? {
if self.patch_ramdisk(ramdisk, cancel_signal)? {
patched = true;
break;
}
+3 -3
View File
@@ -8,7 +8,7 @@ use std::sync::atomic::AtomicBool;
use anyhow::Result;
use clap::{Parser, Subcommand};
use crate::cli::{avb, boot, completion, fec, key, ota, ramdisk};
use crate::cli::{avb, boot, completion, cpio, fec, key, ota};
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Subcommand)]
@@ -16,10 +16,10 @@ pub enum Command {
Avb(avb::AvbCli),
Boot(boot::BootCli),
Completion(completion::CompletionCli),
Cpio(cpio::CpioCli),
Fec(fec::FecCli),
Key(key::KeyCli),
Ota(ota::OtaCli),
Ramdisk(ramdisk::RamdiskCli),
/// (Deprecated: Use `avbroot ota patch` instead.)
Patch(ota::PatchCli),
/// (Deprecated: Use `avbroot ota extract` instead.)
@@ -42,10 +42,10 @@ pub fn main(cancel_signal: &AtomicBool) -> Result<()> {
Command::Avb(c) => avb::avb_main(&c, cancel_signal),
Command::Boot(c) => boot::boot_main(&c),
Command::Completion(c) => completion::completion_main(&c),
Command::Cpio(c) => cpio::cpio_main(&c, cancel_signal),
Command::Fec(c) => fec::fec_main(&c, cancel_signal),
Command::Key(c) => key::key_main(&c),
Command::Ota(c) => ota::ota_main(&c, cancel_signal),
Command::Ramdisk(c) => ramdisk::ramdisk_main(&c),
// Deprecated aliases.
Command::Patch(c) => ota::patch_subcommand(&c, cancel_signal),
Command::Extract(c) => ota::extract_subcommand(&c, cancel_signal),
+2 -2
View File
@@ -34,7 +34,7 @@ use crate::{
util,
};
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
struct AvbInfo {
header: Header,
footer: Option<Footer>,
@@ -782,7 +782,7 @@ enum AvbCommand {
Verify(VerifyCli),
}
/// Show information about AVB-protected images.
/// Pack, unpack, and inspect AVB-protected images.
#[derive(Debug, Parser)]
pub struct AvbCli {
#[command(subcommand)]
+13 -9
View File
@@ -13,7 +13,7 @@ use anyhow::{bail, Context, Result};
use clap::{Parser, Subcommand};
use crate::{
format::{avb::Header, bootimage::BootImage, compression::CompressedReader, cpio},
format::{avb::Header, bootimage::BootImage, compression::CompressedReader, cpio::CpioReader},
stream::{FromReader, ToWriter},
};
@@ -300,12 +300,16 @@ pub fn magisk_info_subcommand(cli: &MagiskInfoCli) -> Result<()> {
let reader = Cursor::new(ramdisk);
let reader = CompressedReader::new(reader, true)
.with_context(|| format!("Failed to load ramdisk #{i}"))?;
let entries = cpio::load(reader, false)
.with_context(|| format!("Failed to load ramdisk #{i} cpio"))?;
let mut cpio_reader = CpioReader::new(reader, false);
if let Some(e) = entries.iter().find(|e| e.name == b".backup/.magisk") {
io::stdout().write_all(&e.content)?;
return Ok(());
while let Some(entry) = cpio_reader
.next_entry()
.with_context(|| format!("Failed to read ramdisk #{i} cpio entry"))?
{
if entry.path == b".backup/.magisk" {
io::copy(&mut cpio_reader, &mut io::stdout())?;
return Ok(());
}
}
}
@@ -330,7 +334,7 @@ struct UnpackCli {
input: PathBuf,
/// Path to output header TOML.
#[arg(long, value_name = "FILE", value_parser, default_value = "header.toml")]
#[arg(long, value_name = "FILE", value_parser, default_value = "boot.toml")]
output_header: PathBuf,
/// Path to output kernel image.
@@ -390,7 +394,7 @@ struct PackCli {
output: PathBuf,
/// Path to input header TOML.
#[arg(long, value_name = "FILE", value_parser, default_value = "header.toml")]
#[arg(long, value_name = "FILE", value_parser, default_value = "boot.toml")]
input_header: PathBuf,
/// Path to input kernel image.
@@ -479,7 +483,7 @@ enum BootCommand {
MagiskInfo(MagiskInfoCli),
}
/// Pack or unpack boot images.
/// Pack, unpack, and inspect boot images.
#[derive(Debug, Parser)]
pub struct BootCli {
#[command(subcommand)]
+385
View File
@@ -0,0 +1,385 @@
/*
* SPDX-FileCopyrightText: 2023 Andrew Gunnerson
* SPDX-License-Identifier: GPL-3.0-only
*/
use std::{
fs::{self, File},
io::{BufReader, BufWriter, Seek},
path::{Path, PathBuf},
str,
sync::atomic::AtomicBool,
};
use anyhow::{anyhow, Context, Result};
use bstr::ByteSlice;
use cap_std::{ambient_authority, fs::Dir};
use clap::{Parser, Subcommand};
use num_traits::ToPrimitive;
use serde::{Deserialize, Serialize};
use crate::{
format::{
compression::{CompressedFormat, CompressedReader, CompressedWriter},
cpio::{self, CpioEntry, CpioEntryData, CpioEntryType, CpioReader, CpioWriter},
},
stream, util,
};
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
struct CpioInfo {
format: CompressedFormat,
entries: Vec<CpioEntry>,
}
fn open_reader(
path: &Path,
include_trailer: bool,
) -> Result<(
CpioReader<CompressedReader<BufReader<File>>>,
CompressedFormat,
)> {
let file =
File::open(path).with_context(|| format!("Failed to open cpio for reading: {path:?}"))?;
let reader = CompressedReader::new(BufReader::new(file), true)
.with_context(|| format!("Failed to open decompressor: {path:?}"))?;
let format = reader.format();
let cpio_reader = CpioReader::new(reader, include_trailer);
Ok((cpio_reader, format))
}
fn open_writer(
path: &Path,
format: CompressedFormat,
) -> Result<CpioWriter<CompressedWriter<BufWriter<File>>>> {
let file =
File::create(path).with_context(|| format!("Failed to open cpio for writing: {path:?}"))?;
let writer = CompressedWriter::new(BufWriter::new(file), format)
.with_context(|| format!("Failed to open compressor: {path:?}"))?;
let cpio_writer = CpioWriter::new(writer, false);
Ok(cpio_writer)
}
fn flush_writer(writer: CpioWriter<CompressedWriter<BufWriter<File>>>) -> Result<()> {
let compressed_writer = writer.finish().context("Failed to flush cpio writer")?;
let buf_writer = compressed_writer
.finish()
.context("Failed to flush compressor")?;
buf_writer.into_inner().context("Failed to flush file")?;
Ok(())
}
/// Read cpio information from TOML file.
fn read_info(path: &Path) -> Result<CpioInfo> {
let data = fs::read_to_string(path)
.with_context(|| format!("Failed to read cpio info TOML: {path:?}"))?;
let info = toml_edit::de::from_str(&data)
.with_context(|| format!("Failed to parse cpio info TOML: {path:?}"))?;
Ok(info)
}
/// Write cpio information to TOML file.
fn write_info(path: &Path, info: &CpioInfo) -> Result<()> {
let data = toml_edit::ser::to_string_pretty(info)
.with_context(|| format!("Failed to serialize cpio info TOML: {path:?}"))?;
fs::write(path, data).with_context(|| format!("Failed to write cpio info TOML: {path:?}"))?;
Ok(())
}
/// Open reader to the corresponding file inside the tree if the entry is a
/// regular file. Unsafe paths will result in an error.
fn open_tree_file(tree: &Dir, entry: &CpioEntry) -> Result<Option<(BufReader<File>, u32)>> {
if entry.file_type == CpioEntryType::Regular {
let path = entry
.path
.as_bstr()
.to_path()
.with_context(|| format!("Invalid entry path: {:?}", entry.path.as_bstr()))?;
let mut reader = tree
.open(path)
.map(|f| BufReader::new(f.into_std()))
.with_context(|| format!("Failed to open for reading: {path:?}"))?;
let file_size = reader
.seek(std::io::SeekFrom::End(0))
.with_context(|| format!("Failed to get file size: {path:?}"))?
.to_u32()
.ok_or_else(|| anyhow!("File is too large: {path:?}"))?;
reader
.rewind()
.with_context(|| format!("Failed to seek file: {path:?}"))?;
Ok(Some((reader, file_size)))
} else {
Ok(None)
}
}
/// Open writer to the corresponding file inside the tree if the entry is a
/// regular file. Intermediate directories are automatically created as needed.
/// Unsafe paths will result in an error.
fn create_tree_file(tree: &Dir, entry: &CpioEntry) -> Result<Option<BufWriter<File>>> {
if entry.file_type == CpioEntryType::Regular {
let path = entry
.path
.as_bstr()
.to_path()
.with_context(|| format!("Invalid entry path: {:?}", entry.path.as_bstr()))?;
let parent = util::parent_path(path);
tree.create_dir_all(parent)
.with_context(|| format!("Failed to create directory: {parent:?}"))?;
let writer = tree
.create(path)
.map(|f| BufWriter::new(f.into_std()))
.with_context(|| format!("Failed to open for writing: {path:?}"))?;
Ok(Some(writer))
} else {
Ok(None)
}
}
fn display_format(cli: &CpioCli, format: CompressedFormat) {
if !cli.quiet {
println!("Compression format: {format:?}");
}
}
fn display_entry(cli: &CpioCli, entry: &CpioEntry) {
if !cli.quiet {
println!();
println!("{entry}");
}
}
fn unpack_subcommand(
cpio_cli: &CpioCli,
cli: &UnpackCli,
cancel_signal: &AtomicBool,
) -> Result<()> {
let (mut reader, format) = open_reader(&cli.input, false)?;
let mut info = CpioInfo {
format,
entries: vec![],
};
display_format(cpio_cli, format);
let authority = ambient_authority();
Dir::create_ambient_dir_all(&cli.output_tree, authority)
.with_context(|| format!("Failed to create directory: {:?}", cli.output_tree))?;
let tree = Dir::open_ambient_dir(&cli.output_tree, authority)
.with_context(|| format!("Failed to open directory: {:?}", cli.output_tree))?;
while let Some(entry) = reader.next_entry().context("Failed to read cpio entry")? {
display_entry(cpio_cli, &entry);
if let Some(mut writer) = create_tree_file(&tree, &entry)? {
let file_size = entry.data.size()?;
stream::copy_n(&mut reader, &mut writer, file_size.into(), cancel_signal)
.context("Failed to copy data")?;
writer.into_inner().context("Failed to flush data")?;
}
info.entries.push(entry);
}
write_info(&cli.output_info, &info)?;
Ok(())
}
fn pack_subcommand(cpio_cli: &CpioCli, cli: &PackCli, cancel_signal: &AtomicBool) -> Result<()> {
let mut info = read_info(&cli.input_info)?;
let mut writer = open_writer(&cli.output, info.format)?;
display_format(cpio_cli, info.format);
if cli.sort {
cpio::sort(&mut info.entries);
}
cpio::assign_inodes(&mut info.entries, true)?;
let authority = ambient_authority();
let tree = Dir::open_ambient_dir(&cli.input_tree, authority)
.with_context(|| format!("Failed to open directory: {:?}", cli.input_tree))?;
for entry in &mut info.entries {
let out = open_tree_file(&tree, entry)?;
if let Some((_, file_size)) = &out {
entry.data = CpioEntryData::Size(*file_size);
}
display_entry(cpio_cli, entry);
writer
.start_entry(entry)
.context("Failed to write cpio entry")?;
if let Some((mut reader, file_size)) = out {
stream::copy_n(&mut reader, &mut writer, file_size.into(), cancel_signal)
.context("Failed to copy data")?;
}
}
flush_writer(writer)?;
Ok(())
}
fn repack_subcommand(
cpio_cli: &CpioCli,
cli: &RepackCli,
cancel_signal: &AtomicBool,
) -> Result<()> {
let (mut reader, format) = open_reader(&cli.input, false)?;
let mut writer = open_writer(&cli.output, format)?;
display_format(cpio_cli, format);
while let Some(entry) = reader.next_entry().context("Failed to read cpio entry")? {
display_entry(cpio_cli, &entry);
writer
.start_entry(&entry)
.context("Failed to write cpio entry")?;
if let CpioEntryData::Size(s) = &entry.data {
stream::copy_n(&mut reader, &mut writer, u64::from(*s), cancel_signal)
.context("Failed to copy cpio entry data")?;
}
}
flush_writer(writer)?;
Ok(())
}
fn info_subcommand(cpio_cli: &CpioCli, cli: &InfoCli) -> Result<()> {
let (mut reader, format) = open_reader(&cli.input, cli.trailer)?;
display_format(cpio_cli, format);
while let Some(entry) = reader.next_entry().context("Failed to read cpio entry")? {
display_entry(cpio_cli, &entry);
}
Ok(())
}
pub fn cpio_main(cli: &CpioCli, cancel_signal: &AtomicBool) -> Result<()> {
match &cli.command {
CpioCommand::Unpack(c) => unpack_subcommand(cli, c, cancel_signal),
CpioCommand::Pack(c) => pack_subcommand(cli, c, cancel_signal),
CpioCommand::Repack(c) => repack_subcommand(cli, c, cancel_signal),
CpioCommand::Info(c) => info_subcommand(cli, c),
}
}
/// Unpack a cpio archive.
///
/// Regular files will be extracted to the output tree directory, but not any
/// other type of file (eg. symlinks). All file metadata is written to the info
/// TOML file, like the UID/GID, permissions, and symlink targets.
///
/// If any paths inside the cpio archive are unsafe, the extraction process will
/// fail and exit. Extracted files are never written outside of the tree
/// directory, even if an external process tries to interfere.
#[derive(Debug, Parser)]
struct UnpackCli {
/// Path to input cpio file.
#[arg(short, long, value_name = "FILE", value_parser)]
input: PathBuf,
/// Path to output cpio info TOML.
#[arg(long, value_name = "FILE", value_parser, default_value = "cpio.toml")]
output_info: PathBuf,
/// Path to output files directory.
#[arg(long, value_name = "DIR", value_parser, default_value = "cpio_tree")]
output_tree: PathBuf,
}
/// Pack a cpio archive.
///
/// The new cpio archive will *only* contain files listed in the info TOML file.
/// Extra files inside the input tree directory that aren't listed will be
/// silently ignored. Entries are added to the archive in the order that they
/// are listed unless --sort is specified.
///
/// All fields inside the info TOML are used as-is. Missing fields in entries
/// are set to 0, aside from the inode number, which will be assigned a unique
/// value.
#[derive(Debug, Parser)]
struct PackCli {
/// Path to output cpio file.
#[arg(short, long, value_name = "FILE", value_parser)]
output: PathBuf,
/// Path to input info TOML.
#[arg(long, value_name = "FILE", value_parser, default_value = "cpio.toml")]
input_info: PathBuf,
/// Path to input files directory.
#[arg(long, value_name = "DIR", value_parser, default_value = "cpio_tree")]
input_tree: PathBuf,
/// Sort entries before packing.
#[arg(long)]
sort: bool,
}
/// Repack a cpio archive.
#[derive(Debug, Parser)]
struct RepackCli {
/// Path to input cpio file.
#[arg(short, long, value_name = "FILE", value_parser)]
input: PathBuf,
/// Path to output cpio file.
#[arg(short, long, value_name = "FILE", value_parser)]
output: PathBuf,
}
/// Display cpio entry information.
#[derive(Debug, Parser)]
struct InfoCli {
/// Path to input cpio file.
#[arg(short, long, value_name = "FILE", value_parser)]
input: PathBuf,
/// Show cpio trailer entry.
#[arg(long, global = true)]
trailer: bool,
}
#[derive(Debug, Subcommand)]
enum CpioCommand {
Unpack(UnpackCli),
Pack(PackCli),
Repack(RepackCli),
Info(InfoCli),
}
/// Pack, unpack, and inspect cpio archives.
#[derive(Debug, Parser)]
pub struct CpioCli {
#[command(subcommand)]
command: CpioCommand,
/// Don't print cpio entry information.
#[arg(short, long, global = true)]
quiet: bool,
}
+1 -1
View File
@@ -7,10 +7,10 @@ pub mod args;
pub mod avb;
pub mod boot;
pub mod completion;
pub mod cpio;
pub mod fec;
pub mod key;
pub mod ota;
pub mod ramdisk;
macro_rules! status {
($($arg:tt)*) => {
+3 -3
View File
@@ -535,7 +535,7 @@ fn patch_ota_payload(
&mut vbmeta_order,
clear_vbmeta_flags,
key_avb,
header_locked.manifest.block_size.into(),
header_locked.manifest.block_size().into(),
)?;
status!(
@@ -543,7 +543,7 @@ fn patch_ota_payload(
joined(sorted(input_streams.keys())),
);
let block_size = header_locked.manifest.block_size;
let block_size = header_locked.manifest.block_size();
drop(header_locked);
input_streams
@@ -1147,7 +1147,7 @@ pub fn verify_subcommand(cli: &VerifyCli, cancel_signal: &AtomicBool) -> Result<
.with_context(|| format!("Failed to read boot image: {path:?}"))?
};
let ramdisk_certs = OtaCertPatcher::get_certificates(&boot_image)
let ramdisk_certs = OtaCertPatcher::get_certificates(&boot_image, cancel_signal)
.context("Failed to read ramdisk's otacerts.zip")?;
if !ramdisk_certs.contains(&ota_cert) {
bail!("Ramdisk's otacerts.zip does not contain OTA certificate");
-150
View File
@@ -1,150 +0,0 @@
/*
* SPDX-FileCopyrightText: 2023 Andrew Gunnerson
* SPDX-License-Identifier: GPL-3.0-only
*/
use std::{
fs::File,
path::{Path, PathBuf},
str,
};
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use crate::format::{
compression::{CompressedFormat, CompressedReader, CompressedWriter},
cpio::{self, CpioEntryNew},
};
static CONTENT_BEGIN: &str = "----- BEGIN UTF-8 CONTENT -----";
static CONTENT_END: &str = "----- END UTF-8 CONTENT -----";
static CONTENT_END_NO_NEWLINE: &str = "----- END UTF-8 CONTENT (NO NEWLINE) -----";
static BINARY_BEGIN: &str = "----- BEGIN BINARY CONTENT -----";
static BINARY_END: &str = "----- END BINARY CONTENT -----";
static BINARY_END_TRUNCATED: &str = "----- END BINARY CONTENT (TRUNCATED) -----";
static NO_DATA: &str = "----- NO DATA -----";
fn print_content(data: &[u8], truncate: bool) {
if data.is_empty() {
println!("{NO_DATA}");
return;
}
if !data.contains(&b'\0') {
if let Ok(s) = str::from_utf8(data) {
if !s.contains(CONTENT_BEGIN)
&& !s.contains(CONTENT_END)
&& !s.contains(CONTENT_END_NO_NEWLINE)
{
println!("{CONTENT_BEGIN}");
print!("{s}");
if data.last() == Some(&b'\n') {
println!("{CONTENT_END}");
} else {
println!();
println!("{CONTENT_END_NO_NEWLINE}");
}
return;
}
}
}
println!("{BINARY_BEGIN}");
if data.len() > 512 && truncate {
println!("{}", data[..512].escape_ascii());
println!("{BINARY_END_TRUNCATED}");
} else {
println!("{}", data.escape_ascii());
println!("{BINARY_END}");
}
}
fn load_archive(
path: &Path,
include_trailer: bool,
) -> Result<(Vec<CpioEntryNew>, CompressedFormat)> {
let file = File::open(path)?;
let reader = CompressedReader::new(file, true)?;
let format = reader.format();
let entries = cpio::load(reader, include_trailer)?;
Ok((entries, format))
}
fn save_archive(path: &Path, entries: &[CpioEntryNew], format: CompressedFormat) -> Result<()> {
let file = File::create(path)?;
let mut writer = CompressedWriter::new(file, format)?;
cpio::save(&mut writer, entries, false)?;
writer.finish()?;
Ok(())
}
pub fn ramdisk_main(cli: &RamdiskCli) -> Result<()> {
match &cli.command {
RamdiskCommand::Dump(c) => {
let (entries, format) = load_archive(&c.input, true)
.with_context(|| format!("Failed to read cpio: {:?}", c.input))?;
println!("Compression format: {format:?}");
println!();
for entry in entries {
println!("{entry}");
print_content(&entry.content, !c.no_truncate);
println!();
}
}
RamdiskCommand::Repack(c) => {
let (entries, format) = load_archive(&c.input, false)
.with_context(|| format!("Failed to read cpio: {:?}", c.input))?;
save_archive(&c.output, &entries, format)
.with_context(|| format!("Failed to write cpio: {:?}", c.output))?;
}
}
Ok(())
}
/// Dump cpio headers and data.
#[derive(Debug, Parser)]
struct DumpCli {
/// Path to input cpio file.
#[arg(short, long, value_name = "FILE", value_parser)]
input: PathBuf,
/// Do not truncate binary file contents.
#[arg(long)]
no_truncate: bool,
}
/// Repack cpio archive.
#[derive(Debug, Parser)]
struct RepackCli {
/// Path to input cpio file.
#[arg(short, long, value_name = "FILE", value_parser)]
input: PathBuf,
/// Path to output cpio file.
#[arg(short, long, value_name = "FILE", value_parser)]
output: PathBuf,
}
#[derive(Debug, Subcommand)]
enum RamdiskCommand {
Dump(DumpCli),
Repack(RepackCli),
}
/// Show information about ramdisk cpio archives.
#[derive(Debug, Parser)]
pub struct RamdiskCli {
#[command(subcommand)]
command: RamdiskCommand,
}
+1 -1
View File
@@ -393,7 +393,7 @@ impl HashTreeDescriptor {
cancel_signal: &AtomicBool,
) -> io::Result<Vec<u8>> {
// Each digest must be a power of 2.
let digest_padding = algorithm.output_len.next_power_of_two() - algorithm.output_len;
let digest_padding = algorithm.output_len().next_power_of_two() - algorithm.output_len();
let mut buf = vec![0u8; block_size as usize];
let mut result = vec![];
+1
View File
@@ -1255,6 +1255,7 @@ impl<W: Write> ToWriter<W> for VendorBootImageV3Through4 {
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(tag = "type")]
pub enum BootImage {
V0Through2(BootImageV0Through2),
V3Through4(BootImageV3Through4),
+2 -1
View File
@@ -8,6 +8,7 @@ use std::io::{self, Read, Seek, Write};
use byteorder::{LittleEndian, WriteBytesExt};
use flate2::{read::GzDecoder, write::GzEncoder, Compression};
use lz4_flex::frame::FrameDecoder;
use serde::{Deserialize, Serialize};
use thiserror::Error;
static GZIP_MAGIC: &[u8; 2] = b"\x1f\x8b";
@@ -96,7 +97,7 @@ impl<W: Write> Write for Lz4LegacyEncoder<W> {
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum CompressedFormat {
None,
Gzip,
+544 -164
View File
@@ -4,18 +4,25 @@
*/
use std::{
borrow::Cow,
collections::{HashMap, HashSet},
fmt,
io::{self, Read, Write},
io::{self, Cursor, Read, Write},
ops::Range,
sync::atomic::AtomicBool,
};
use bstr::ByteSlice;
use num_traits::ToPrimitive;
use num_traits::{ToPrimitive, Zero};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::{
escape,
format::padding,
stream::{CountingReader, CountingWriter, FromReader, ToWriter, WriteZerosExt},
octal,
stream::{
self, CountingReader, CountingWriter, FromReader, ReadDiscardExt, ToWriter, WriteZerosExt,
},
util::NumBytes,
};
@@ -35,12 +42,9 @@ const C_ISCTG: u32 = 0o110000;
const IO_BLOCK_SIZE: u64 = 512;
/// The threshold when parsing an entry's filename where memory allocation
/// switches from allocating the exact size to resizing as necessary.
const REALLOC_NAME_THRESHOLD: usize = 1024;
/// The threshold when parsing an entry's contents where memory allocation
/// switches from allocating the exact size to resizing as necessary.
const REALLOC_DATA_THRESHOLD: usize = 1024 * 1024;
/// The threshold when reading data where memory allocation switches from
/// allocating the exact size to resizing as necessary.
const VEC_CAP_THRESHOLD: usize = 16384;
#[derive(Debug, Error)]
pub enum Error {
@@ -48,6 +52,10 @@ pub enum Error {
UnknownMagic([u8; 6]),
#[error("Hard links are not supported: {:?}", .0.as_bstr())]
HardLinksNotSupported(Vec<u8>),
#[error("Entry of type {0} should not have data: {:?}", .1.as_bstr())]
EntryHasData(CpioEntryType, Vec<u8>),
#[error("No inodes available for device {0:x},{1:x}")]
DeviceFull(u32, u32),
#[error("{0:?} field exceeds integer bounds")]
IntegerTooLarge(&'static str),
#[error("I/O error")]
@@ -94,56 +102,199 @@ fn write_int(mut writer: impl Write, mut value: u32) -> io::Result<()> {
}
/// Read a chunk of bytes from the reader. If `size` is less than
/// `realloc_thresh`, then the buffer is allocated with the exact size.
/// Otherwise, the buffer starts with a capacity of `realloc_thresh` and grows
/// as necessary. This avoids allocating excessive memory when the entry
/// [`VEC_CAP_THRESHOLD`], then the buffer is allocated with the exact size.
/// Otherwise, the buffer starts with a capacity of [`VEC_CAP_THRESHOLD`] and
/// grows as necessary. This avoids allocating excessive memory when the entry
/// specifies an excessively large value that's not backed by actual data.
fn read_data(mut reader: impl Read, size: usize, realloc_thresh: usize) -> io::Result<Vec<u8>> {
if size < realloc_thresh {
let mut buf = vec![0u8; size];
reader.read_exact(&mut buf)?;
Ok(buf)
} else {
let mut buf = Vec::with_capacity(realloc_thresh);
let mut offset = 0;
fn read_data(reader: impl Read, size: usize, cancel_signal: &AtomicBool) -> io::Result<Vec<u8>> {
let buf = Vec::with_capacity(size.min(VEC_CAP_THRESHOLD));
let mut cursor = Cursor::new(buf);
while offset < size {
let n = (size - offset).min(16384);
buf.resize(offset + n, 0);
reader.read_exact(&mut buf[offset..][..n])?;
offset += n;
stream::copy_n(reader, &mut cursor, size as u64, cancel_signal)?;
Ok(cursor.into_inner())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub enum CpioEntryType {
Pipe,
Char,
Directory,
Block,
Regular,
Symlink,
Socket,
Reserved,
Unknown(u16),
}
impl CpioEntryType {
pub fn from_mode(mode: u32) -> Self {
match mode & 0o170000 {
S_IFIFO => Self::Pipe,
S_IFCHR => Self::Char,
S_IFDIR => Self::Directory,
S_IFBLK => Self::Block,
S_IFREG => Self::Regular,
S_IFLNK => Self::Symlink,
S_IFSOCK => Self::Socket,
C_ISCTG => Self::Reserved,
m => Self::Unknown(m as u16),
}
}
Ok(buf)
pub fn to_mode(self) -> u32 {
match self {
Self::Pipe => S_IFIFO,
Self::Char => S_IFCHR,
Self::Directory => S_IFDIR,
Self::Block => S_IFBLK,
Self::Regular => S_IFREG,
Self::Symlink => S_IFLNK,
Self::Socket => S_IFSOCK,
Self::Reserved => C_ISCTG,
Self::Unknown(m) => m.into(),
}
}
}
fn file_type(mode: u32) -> u32 {
mode & 0o170000
}
#[derive(Clone, Default, PartialEq, Eq)]
pub struct CpioEntryNew {
pub ino: u32,
pub mode: u32,
pub uid: u32,
pub gid: u32,
pub nlink: u32,
pub mtime: u32,
pub dev_maj: u32,
pub dev_min: u32,
pub rdev_maj: u32,
pub rdev_min: u32,
pub chksum: u32,
pub name: Vec<u8>,
pub content: Vec<u8>,
}
impl fmt::Debug for CpioEntryNew {
impl fmt::Display for CpioEntryType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CpioEntryNew")
.field("ino", &self.ino)
.field("mode", &self.mode)
match self {
Self::Pipe => write!(f, "pipe"),
Self::Char => write!(f, "character device"),
Self::Directory => write!(f, "directory"),
Self::Block => write!(f, "block device"),
Self::Regular => write!(f, "regular file"),
Self::Symlink => write!(f, "symbolic link"),
Self::Socket => write!(f, "socket"),
Self::Reserved => write!(f, "reserved"),
Self::Unknown(m) => write!(f, "unknown ({m:o})"),
}
}
}
impl Default for CpioEntryType {
fn default() -> Self {
Self::Unknown(0)
}
}
#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CpioEntryData {
/// Size of entry's data. [`CpioReader`] and [`CpioWriter`] use this for
/// [`CpioEntryType::Regular`] entries to allow for lazy reads and writes.
Size(u32),
/// Entry's data. For [`CpioEntryType::Symlink`] entries, this is the
/// link target. For [`CpioEntryType::Regular`] entries, this is the file
/// content. [`CpioReader`] will never use this when reading regular files.
/// [`CpioWriter`] will write this immediately and lazy writes will not be
/// allowed.
Data(#[serde(with = "escape")] Vec<u8>),
}
impl fmt::Debug for CpioEntryData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Size(s) => f.debug_tuple("Size").field(s).finish(),
Self::Data(d) => f.debug_tuple("Data").field(&NumBytes(d.len())).finish(),
}
}
}
impl Default for CpioEntryData {
fn default() -> Self {
Self::Size(0)
}
}
impl CpioEntryData {
pub fn size(&self) -> Result<u32> {
let size = match self {
Self::Size(s) => *s,
Self::Data(d) => d
.len()
.to_u32()
.ok_or_else(|| Error::IntegerTooLarge("data_size"))?,
};
Ok(size)
}
fn is_size(&self) -> bool {
matches!(self, CpioEntryData::Size(_))
}
}
#[derive(Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct CpioEntry {
/// File path.
#[serde(with = "escape")]
pub path: Vec<u8>,
/// File data.
#[serde(default, skip_serializing_if = "CpioEntryData::is_size")]
pub data: CpioEntryData,
/// Inode number.
#[serde(default, skip_serializing_if = "Zero::is_zero")]
pub inode: u32,
/// File type portion of the `st_mode`-style mode.
pub file_type: CpioEntryType,
/// Permissions portion of the `st_mode`-style mode.
#[serde(default, skip_serializing_if = "Zero::is_zero", with = "octal")]
pub file_mode: u16,
/// Owner user ID.
#[serde(default, skip_serializing_if = "Zero::is_zero")]
pub uid: u32,
/// Owner group ID.
#[serde(default, skip_serializing_if = "Zero::is_zero")]
pub gid: u32,
/// Number of paths referencing the inode.
#[serde(default, skip_serializing_if = "Zero::is_zero")]
pub nlink: u32,
/// Modification timestamp in Unix time.
#[serde(default, skip_serializing_if = "Zero::is_zero")]
pub mtime: u32,
/// Major ID (class of device) for the device containing the inode.
#[serde(default, skip_serializing_if = "Zero::is_zero")]
pub dev_maj: u32,
/// Minor ID (specific device instance) for the device containing the inode.
#[serde(default, skip_serializing_if = "Zero::is_zero")]
pub dev_min: u32,
/// Major ID (class of device) represented by this entry. This is only
/// relevant for [`CpioEntryType::Char`] and [`CpioEntryType::Block`].
#[serde(default, skip_serializing_if = "Zero::is_zero")]
pub rdev_maj: u32,
/// Minor ID (specific device instance) represented by this entry. This is
/// only relevant for [`CpioEntryType::Char`] and [`CpioEntryType::Block`].
#[serde(default, skip_serializing_if = "Zero::is_zero")]
pub rdev_min: u32,
/// CRC32 checksum.
#[serde(default, skip_serializing_if = "Zero::is_zero")]
pub crc32: u32,
}
impl fmt::Debug for CpioEntry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CpioEntry")
.field("path", &self.path.as_bstr())
.field("data", &self.data)
.field("inode", &self.inode)
.field("file_type", &self.file_type)
.field("file_mode", &self.file_mode)
.field("uid", &self.uid)
.field("gid", &self.gid)
.field("nlink", &self.nlink)
@@ -152,84 +303,89 @@ impl fmt::Debug for CpioEntryNew {
.field("dev_min", &self.dev_min)
.field("rdev_maj", &self.rdev_maj)
.field("rdev_min", &self.rdev_min)
.field("chksum", &self.chksum)
.field("name", &self.name.as_bstr())
.field("content", &NumBytes(self.content.len()))
.field("crc32", &self.crc32)
.finish()
}
}
impl fmt::Display for CpioEntryNew {
impl fmt::Display for CpioEntry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let file_type_str = match file_type(self.mode) {
S_IFIFO => Cow::Borrowed("pipe"),
S_IFCHR => Cow::Borrowed("character device"),
S_IFDIR => Cow::Borrowed("directory"),
S_IFBLK => Cow::Borrowed("block device"),
S_IFREG => Cow::Borrowed("regular file"),
S_IFLNK => Cow::Borrowed("symbolic link"),
S_IFSOCK => Cow::Borrowed("socket"),
C_ISCTG => Cow::Borrowed("reserved"),
m => Cow::Owned(format!("unknown ({m:o})")),
};
writeln!(f, "Filename: {:?}", self.name.as_bstr())?;
writeln!(f, "Filetype: {file_type_str}")?;
writeln!(f, "Inode: {}", self.ino)?;
writeln!(f, "Mode: {:o}", self.mode)?;
writeln!(f, "UID: {}", self.uid)?;
writeln!(f, "GID: {}", self.gid)?;
writeln!(f, "Links: {}", self.nlink)?;
writeln!(f, "Modified: {}", self.mtime)?;
writeln!(f, "Device: {:x},{:x}", self.dev_maj, self.dev_min)?;
writeln!(f, "Device ID: {:x},{:x}", self.rdev_maj, self.rdev_min)?;
writeln!(f, "Checksum: {:x}", self.chksum)?;
writeln!(f, "Content: {:?}", NumBytes(self.content.len()))?;
writeln!(f, "Path: {:?}", self.path.as_bstr())?;
match &self.data {
CpioEntryData::Size(s) => {
writeln!(f, "Data: {:?}", &NumBytes(*s))?;
}
CpioEntryData::Data(d) => {
if self.file_type == CpioEntryType::Symlink {
writeln!(f, "Data: {:?}", d.as_bstr())?;
} else {
writeln!(f, "Data: {:?}", &NumBytes(d.len()))?;
}
}
}
writeln!(f, "Inode: {}", self.inode)?;
writeln!(f, "Type: {}", self.file_type)?;
writeln!(f, "Mode: {:o}", self.file_mode)?;
writeln!(f, "UID: {}", self.uid)?;
writeln!(f, "GID: {}", self.gid)?;
writeln!(f, "Links: {}", self.nlink)?;
writeln!(f, "Modtime: {}", self.mtime)?;
writeln!(f, "Idevice: {:x},{:x}", self.dev_maj, self.dev_min)?;
writeln!(f, "Rdevice: {:x},{:x}", self.rdev_maj, self.rdev_min)?;
write!(f, "CRC32: {:x}", self.crc32)?;
Ok(())
}
}
impl CpioEntryNew {
impl CpioEntry {
pub fn new_trailer() -> Self {
Self {
path: CPIO_TRAILER.to_vec(),
// Must be 1 for CRC format.
nlink: 1,
name: CPIO_TRAILER.to_vec(),
..Default::default()
}
}
pub fn new_symlink(link_target: &[u8], name: &[u8]) -> Self {
pub fn new_symlink(path: &[u8], link_target: &[u8]) -> Self {
Self {
mode: S_IFLNK | 0o777,
path: path.to_owned(),
data: CpioEntryData::Data(link_target.to_owned()),
file_type: CpioEntryType::Symlink,
file_mode: 0o777,
nlink: 1,
name: name.to_owned(),
content: link_target.to_owned(),
..Default::default()
}
}
pub fn new_directory(name: &[u8]) -> Self {
pub fn new_directory(path: &[u8], mode: u16) -> Self {
Self {
mode: S_IFDIR,
path: path.to_owned(),
file_type: CpioEntryType::Directory,
file_mode: mode,
nlink: 1,
name: name.to_owned(),
..Default::default()
}
}
pub fn new_file(name: &[u8]) -> Self {
pub fn new_file(path: &[u8], mode: u16, data: CpioEntryData) -> Self {
Self {
mode: S_IFREG,
path: path.to_owned(),
data,
file_type: CpioEntryType::Regular,
file_mode: mode,
nlink: 1,
name: name.to_owned(),
..Default::default()
}
}
pub fn is_trailer(&self) -> bool {
self.path == CPIO_TRAILER
}
}
impl<R: Read> FromReader<R> for CpioEntryNew {
impl<R: Read> FromReader<R> for CpioEntry {
type Error = Error;
fn from_reader(reader: R) -> Result<Self> {
@@ -242,45 +398,61 @@ impl<R: Read> FromReader<R> for CpioEntryNew {
return Err(Error::UnknownMagic(magic));
}
let ino = read_int(&mut reader)?;
let inode = read_int(&mut reader)?;
let mode = read_int(&mut reader)?;
let uid = read_int(&mut reader)?;
let gid = read_int(&mut reader)?;
let nlink = read_int(&mut reader)?;
let mtime = read_int(&mut reader)?;
let filesize = read_int(&mut reader)?;
let file_size = read_int(&mut reader)?;
let dev_maj = read_int(&mut reader)?;
let dev_min = read_int(&mut reader)?;
let rdev_maj = read_int(&mut reader)?;
let rdev_min = read_int(&mut reader)?;
let namesize = read_int(&mut reader)?;
let chksum = read_int(&mut reader)?;
let path_size = read_int(&mut reader)?;
let crc32 = read_int(&mut reader)?;
let mut name = read_data(
let mut path = read_data(
&mut reader,
namesize.to_usize().unwrap(),
REALLOC_NAME_THRESHOLD,
path_size.to_usize().unwrap(),
&AtomicBool::new(false),
)?;
if name.last() != Some(&b'\0') {
if path.last() != Some(&b'\0') {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Filename is not NULL-terminated",
)
.into());
}
name.pop();
path.pop();
padding::read_discard(&mut reader, 4)?;
let content = read_data(
&mut reader,
filesize.to_usize().unwrap(),
REALLOC_DATA_THRESHOLD,
)?;
padding::read_discard(&mut reader, 4)?;
let file_type = CpioEntryType::from_mode(mode);
let data = match file_type {
// Handled by CpioReader for streaming reads.
CpioEntryType::Regular => CpioEntryData::Size(file_size),
// Symlinks store the target in the file data.
CpioEntryType::Symlink => {
let content = read_data(
&mut reader,
file_size.to_usize().unwrap(),
&AtomicBool::new(false),
)?;
padding::read_discard(&mut reader, 4)?;
CpioEntryData::Data(content)
}
// No other entry type should have data.
t if file_size != 0 => return Err(Error::EntryHasData(t, path)),
_ => CpioEntryData::Size(0),
};
Ok(Self {
ino,
mode,
path,
data,
inode,
file_type,
file_mode: (mode & 0o7777) as u16,
uid,
gid,
nlink,
@@ -289,76 +461,236 @@ impl<R: Read> FromReader<R> for CpioEntryNew {
dev_min,
rdev_maj,
rdev_min,
chksum,
name,
content,
crc32,
})
}
}
impl<W: Write> ToWriter<W> for CpioEntryNew {
impl<W: Write> ToWriter<W> for CpioEntry {
type Error = Error;
fn to_writer(&self, writer: W) -> Result<()> {
let mut writer = CountingWriter::new(writer);
let filesize = self
.content
.len()
.to_u32()
.ok_or_else(|| Error::IntegerTooLarge("filesize"))?;
let namesize = self
.name
let path_size = self
.path
.len()
.checked_add(1)
.and_then(|s| s.to_u32())
.ok_or_else(|| Error::IntegerTooLarge("filesize"))?;
.ok_or_else(|| Error::IntegerTooLarge("path_size"))?;
if self.chksum == 0 {
let file_size = self.data.size()?;
if file_size != 0
&& self.file_type != CpioEntryType::Regular
&& self.file_type != CpioEntryType::Symlink
{
return Err(Error::EntryHasData(self.file_type, self.path.clone()));
}
if self.crc32 == 0 {
writer.write_all(MAGIC_NEW)?;
} else {
writer.write_all(MAGIC_NEW_CRC)?;
}
write_int(&mut writer, self.ino)?;
write_int(&mut writer, self.mode)?;
let mode = self.file_type.to_mode() | u32::from(self.file_mode & 0o7777);
write_int(&mut writer, self.inode)?;
write_int(&mut writer, mode)?;
write_int(&mut writer, self.uid)?;
write_int(&mut writer, self.gid)?;
write_int(&mut writer, self.nlink)?;
write_int(&mut writer, self.mtime)?;
write_int(&mut writer, filesize)?;
write_int(&mut writer, file_size)?;
write_int(&mut writer, self.dev_maj)?;
write_int(&mut writer, self.dev_min)?;
write_int(&mut writer, self.rdev_maj)?;
write_int(&mut writer, self.rdev_min)?;
write_int(&mut writer, namesize)?;
write_int(&mut writer, self.chksum)?;
write_int(&mut writer, path_size)?;
write_int(&mut writer, self.crc32)?;
writer.write_all(&self.name)?;
writer.write_all(&self.path)?;
writer.write_zeros_exact(1)?;
padding::write_zeros(&mut writer, 4)?;
writer.write_all(&self.content)?;
padding::write_zeros(&mut writer, 4)?;
if let CpioEntryData::Data(d) = &self.data {
writer.write_all(d)?;
padding::write_zeros(&mut writer, 4)?;
}
Ok(())
}
}
pub fn load(mut reader: impl Read, include_trailer: bool) -> Result<Vec<CpioEntryNew>> {
let mut entries = vec![];
pub struct CpioReader<R: Read> {
reader: R,
include_trailer: bool,
range: Option<Range<u64>>,
done: bool,
}
loop {
let entry = CpioEntryNew::from_reader(&mut reader)?;
if file_type(entry.mode) != S_IFDIR && entry.nlink > 1 {
return Err(Error::HardLinksNotSupported(entry.name));
impl<R: Read> CpioReader<R> {
pub fn new(reader: R, include_trailer: bool) -> Self {
Self {
reader,
include_trailer,
range: None,
done: false,
}
}
pub fn into_inner(self) -> R {
self.reader
}
fn skip_data(&mut self) -> io::Result<()> {
if let Some(range) = &mut self.range {
// This cannot overflow because cpio file sizes are 32 bit.
let n = range.end - range.start + padding::calc(range.end, 4);
self.reader.read_discard_exact(n)?;
self.range = None;
}
if entry.name == CPIO_TRAILER {
if include_trailer {
entries.push(entry);
Ok(())
}
pub fn next_entry(&mut self) -> Result<Option<CpioEntry>> {
if self.done {
return Ok(None);
}
self.skip_data()?;
let entry = CpioEntry::from_reader(&mut self.reader)?;
if entry.is_trailer() {
self.done = true;
if !self.include_trailer {
return Ok(None);
}
break;
} else if let CpioEntryData::Size(s) = entry.data {
self.range = Some(0..u64::from(s));
}
Ok(Some(entry))
}
}
impl<R: Read> Read for CpioReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let Some(range) = &mut self.range else {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"No entry opened",
));
};
let to_read = (range.end - range.start).min(buf.len() as u64) as usize;
let n = self.reader.read(&mut buf[..to_read])?;
range.start += n as u64;
Ok(n)
}
}
pub struct CpioWriter<W: Write> {
writer: CountingWriter<W>,
pad_to_block_size: bool,
range: Option<Range<u64>>,
max_inode: u32,
}
impl<W: Write> CpioWriter<W> {
pub fn new(writer: W, pad_to_block_size: bool) -> Self {
Self {
writer: CountingWriter::new(writer),
pad_to_block_size,
range: None,
max_inode: 0,
}
}
fn finish_entry(&mut self) -> io::Result<()> {
if let Some(range) = &mut self.range {
// This cannot overflow because cpio file sizes are 32 bit.
let n = range.end - range.start + padding::calc(range.end, 4);
self.writer.write_zeros_exact(n)?;
self.range = None;
}
Ok(())
}
pub fn start_entry(&mut self, entry: &CpioEntry) -> Result<()> {
self.finish_entry()?;
entry.to_writer(&mut self.writer)?;
if let CpioEntryData::Size(s) = entry.data {
self.range = Some(0..u64::from(s));
}
self.max_inode = self.max_inode.max(entry.inode);
Ok(())
}
pub fn finish(mut self) -> Result<W> {
self.finish_entry()?;
self.start_entry(&CpioEntry::new_trailer())?;
// Pad until the end of the block.
if self.pad_to_block_size {
padding::write_zeros(&mut self.writer, IO_BLOCK_SIZE)?;
}
Ok(self.writer.finish().0)
}
}
impl<W: Write> Write for CpioWriter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let Some(range) = &mut self.range else {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"No entry started",
));
};
let to_write = (range.end - range.start).min(buf.len() as u64) as usize;
let n = self.writer.write(&buf[..to_write])?;
range.start += n as u64;
Ok(n)
}
fn flush(&mut self) -> io::Result<()> {
self.writer.flush()
}
}
pub fn load(
reader: impl Read,
include_trailer: bool,
cancel_signal: &AtomicBool,
) -> Result<Vec<CpioEntry>> {
let mut cpio_reader = CpioReader::new(reader, include_trailer);
let mut entries = vec![];
while let Some(mut entry) = cpio_reader.next_entry()? {
stream::check_cancel(cancel_signal)?;
if entry.file_type != CpioEntryType::Directory && entry.nlink > 1 {
return Err(Error::HardLinksNotSupported(entry.path.clone()));
}
if let CpioEntryData::Size(s) = entry.data {
let data = read_data(&mut cpio_reader, s.to_usize().unwrap(), cancel_signal)?;
entry.data = CpioEntryData::Data(data);
}
entries.push(entry);
@@ -367,35 +699,83 @@ pub fn load(mut reader: impl Read, include_trailer: bool) -> Result<Vec<CpioEntr
Ok(entries)
}
pub fn sort(entries: &mut [CpioEntryNew]) {
entries.sort_by(|a, b| a.name.cmp(&b.name));
pub fn sort(entries: &mut [CpioEntry]) {
entries.sort_by(|a, b| a.path.cmp(&b.path));
}
pub fn reassign_inodes(entries: &mut [CpioEntryNew]) {
let mut inode = 300000;
for entry in entries {
entry.ino = inode;
inode += 1;
}
}
pub fn save(writer: impl Write, entries: &[CpioEntryNew], pad_to_block_size: bool) -> Result<()> {
let mut writer = CountingWriter::new(writer);
for entry in entries {
entry.to_writer(&mut writer)?;
/// Assign inodes to entries. If `missing_only` is true, then inodes are only
/// assigned if the inode field in an entry is set to 0.
///
/// New inodes are assigned starting immediately after the highest inode number
/// for a given ([`CpioEntry::dev_maj`], [`CpioEntry::dev_min`]) pair. If there
/// are no existing inodes assigned for a device, then the numbers begin at
/// 300000.
pub fn assign_inodes(entries: &mut [CpioEntry], missing_only: bool) -> Result<()> {
fn next_non_zero(i: u32) -> u32 {
if i == u32::MAX {
1
} else {
i.wrapping_add(1)
}
}
let mut trailer = CpioEntryNew::new_trailer();
// 1 higher than the highest inode if possible.
trailer.ino = entries.iter().map(|e| e.ino).max().map_or(0, |i| i + 1);
trailer.to_writer(&mut writer)?;
// (dev maj, dev min) -> (inode set, last assigned inode)
let mut inodes: HashMap<(u32, u32), (HashSet<u32>, u32)> = HashMap::new();
// Pad until the end of the block.
if pad_to_block_size {
padding::write_zeros(&mut writer, IO_BLOCK_SIZE)?;
if missing_only {
for entry in &mut *entries {
if entry.inode != 0 {
let key = (entry.dev_maj, entry.dev_min);
let (set, last) = inodes.entry(key).or_default();
set.insert(entry.inode);
*last = (*last).max(entry.inode);
}
}
}
for entry in entries {
if entry.inode == 0 {
let key = (entry.dev_maj, entry.dev_min);
let (set, last) = inodes
.entry(key)
.or_insert_with(|| (HashSet::new(), 299999));
let mut unused = next_non_zero(*last);
while set.contains(&unused) {
if unused == *last {
return Err(Error::DeviceFull(entry.dev_maj, entry.dev_min));
}
unused = next_non_zero(unused);
}
entry.inode = unused;
set.insert(unused);
*last = unused;
}
}
Ok(())
}
pub fn save(
writer: impl Write,
entries: &[CpioEntry],
pad_to_block_size: bool,
cancel_signal: &AtomicBool,
) -> Result<()> {
let mut cpio_writer = CpioWriter::new(writer, pad_to_block_size);
for entry in entries {
stream::check_cancel(cancel_signal)?;
cpio_writer.start_entry(entry)?;
// CpioEntryData::Data will have already been written.
}
cpio_writer.finish()?;
Ok(())
}
+10 -10
View File
@@ -13,6 +13,7 @@ use std::{
use cms::signed_data::SignedData;
use const_oid::{db::rfc5912, ObjectIdentifier};
use memchr::memmem;
use prost::Message;
use ring::digest::Context;
use rsa::{Pkcs1v15Sign, RsaPrivateKey};
use sha1::Sha1;
@@ -24,9 +25,8 @@ use zip::{result::ZipError, write::FileOptions, CompressionMethod, ZipArchive, Z
use crate::{
crypto,
format::payload::{self, PayloadHeader},
protobuf::build::tools::releasetools::{mod_OtaMetadata::OtaType, OtaMetadata},
protobuf::build::tools::releasetools::{ota_metadata::OtaType, OtaMetadata},
stream::{self, FromReader, HashingReader, HashingWriter},
util,
};
pub const PATH_METADATA: &str = "META-INF/com/android/metadata";
@@ -76,8 +76,8 @@ pub enum Error {
CmsSign(#[from] crypto::Error),
#[error("Payload error")]
Payload(#[from] payload::Error),
#[error("Protobuf error")]
Protobuf(#[from] quick_protobuf::Error),
#[error("Failed to decode protobuf message")]
ProtobufDecode(#[from] prost::DecodeError),
#[error("SPKI error")]
Spki(#[from] pkcs8::spki::Error),
#[error("x509 DER error")]
@@ -99,11 +99,11 @@ fn serialize_metadata(metadata: &OtaMetadata) -> Result<(String, Vec<u8>)> {
let mut pairs = BTreeMap::<String, String>::new();
match metadata.type_pb {
OtaType::AB => {
match metadata.r#type() {
OtaType::Ab => {
pairs.insert("ota-type".to_owned(), "AB".to_owned());
}
OtaType::BLOCK => {
OtaType::Block => {
pairs.insert("ota-type".to_owned(), "BLOCK".to_owned());
}
_ => {}
@@ -161,7 +161,7 @@ fn serialize_metadata(metadata: &OtaMetadata) -> Result<(String, Vec<u8>)> {
.into_iter()
.map(|(k, v)| format!("{k}={v}\n"))
.collect::<String>();
let modern_metadata = util::write_protobuf(metadata)?;
let modern_metadata = metadata.encode_to_vec();
Ok((legacy_metadata, modern_metadata))
}
@@ -299,7 +299,7 @@ pub fn add_metadata(
metadata_pb_raw: &[u8],
payload_metadata_size: u64,
) -> Result<OtaMetadata> {
let mut metadata: OtaMetadata = util::read_protobuf(metadata_pb_raw)?;
let mut metadata = OtaMetadata::decode(metadata_pb_raw)?;
let options = FileOptions::default().compression_method(CompressionMethod::Stored);
let mut zip_entries = zip_entries.to_owned();
@@ -523,7 +523,7 @@ pub fn parse_zip_ota_info(
let mut entry = zip.by_name(PATH_METADATA_PB)?;
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
util::read_protobuf::<OtaMetadata>(&buf)?
OtaMetadata::decode(buf.as_slice())?
};
let certificate = {
+28 -36
View File
@@ -14,7 +14,7 @@ use base64::Engine;
use byteorder::{BigEndian, ReadBytesExt};
use bzip2::write::BzDecoder;
use num_traits::ToPrimitive;
use quick_protobuf::MessageWrite;
use prost::Message;
use rayon::prelude::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator};
use ring::digest::{Context, Digest};
use rsa::{traits::PublicKeyParts, Pkcs1v15Sign, RsaPrivateKey};
@@ -30,14 +30,13 @@ use xz2::{
use crate::{
crypto,
protobuf::chromeos_update_engine::{
mod_InstallOperation, mod_Signatures::Signature, DeltaArchiveManifest, Extent,
install_operation::Type, signatures::Signature, DeltaArchiveManifest, Extent,
InstallOperation, PartitionInfo, PartitionUpdate, Signatures,
},
stream::{
self, CountingReader, CountingWriter, FromReader, HashingWriter, ReadDiscardExt, ReadSeek,
SharedCursor, WriteSeek,
},
util,
};
const OTA_MAGIC: &[u8; 4] = b"CrAU";
@@ -68,7 +67,7 @@ pub enum Error {
actual: String,
},
#[error("Unsupported partition operation: {0:?}")]
UnsupportedOperation(mod_InstallOperation::Type),
UnsupportedOperation(Type),
#[error("Expected sha256 {expected:?}, but have {actual:?}")]
MismatchedDigest {
expected: Option<String>,
@@ -90,8 +89,8 @@ pub enum Error {
FieldOutOfBounds(&'static str),
#[error("Crypto error")]
Crypto(#[from] crypto::Error),
#[error("Protobuf error")]
Protobuf(#[from] quick_protobuf::Error),
#[error("Failed to decode protobuf message")]
ProtobufDecode(#[from] prost::DecodeError),
#[error("XZ stream error")]
XzStream(#[from] xz2::stream::Error),
#[error("RSA error")]
@@ -153,7 +152,7 @@ impl<R: Read> FromReader<R> for PayloadHeader {
let mut manifest_raw = vec![0u8; manifest_size];
reader.read_exact(&mut manifest_raw)?;
let manifest: DeltaArchiveManifest = util::read_protobuf(&manifest_raw)?;
let manifest = DeltaArchiveManifest::decode(manifest_raw.as_slice())?;
// Skip manifest signatures.
reader.read_discard_exact(metadata_signature_size.into())?;
@@ -184,6 +183,7 @@ fn sign_digest(digest: &[u8], key: &RsaPrivateKey) -> Result<Signatures> {
data: Some(digest_signed),
// Always fits in even a u16.
unpadded_signature_size: Some(unpadded_size as u32),
..Default::default()
};
let signatures = Signatures {
@@ -329,14 +329,14 @@ impl<W: Write> PayloadWriter<W> {
ring::digest::digest(&ring::digest::SHA256, b"").as_ref(),
&key,
)?;
let dummy_sig_size = dummy_sig.get_size();
let dummy_sig_size = dummy_sig.encoded_len();
// Fill out the new payload signature information.
header.manifest.signatures_offset = Some(blob_size);
header.manifest.signatures_size = Some(dummy_sig_size as u64);
// Build new manifest.
let manifest_raw_new = util::write_protobuf(&header.manifest)?;
let manifest_raw_new = header.manifest.encode_to_vec();
// Excludes signatures (hashes are for signing).
let mut h_partial = Context::new(&ring::digest::SHA256);
@@ -364,7 +364,7 @@ impl<W: Write> PayloadWriter<W> {
// in the payload hash.
let metadata_hash = h_partial.clone().finish();
let metadata_sig = sign_digest(metadata_hash.as_ref(), &key)?;
let metadata_sig_raw = util::write_protobuf(&metadata_sig)?;
let metadata_sig_raw = metadata_sig.encode_to_vec();
write_hash!(inner, [h_full], &metadata_sig_raw)?;
Ok(Self {
@@ -392,7 +392,7 @@ impl<W: Write> PayloadWriter<W> {
// Append payload signature.
let payload_partial_hash = self.h_partial.clone().finish();
let payload_sig = sign_digest(payload_partial_hash.as_ref(), &self.key)?;
let payload_sig_raw = util::write_protobuf(&payload_sig)?;
let payload_sig_raw = payload_sig.encode_to_vec();
write_hash!(self.inner, [self.h_full], &payload_sig_raw)?;
// Everything before the blob.
@@ -600,18 +600,12 @@ impl<W: Write> CompressedPartitionWriter<W> {
num_blocks: Some(self.written / u64::from(self.block_size)),
};
let operation = InstallOperation {
type_pb: mod_InstallOperation::Type::REPLACE_XZ,
// Must be manually updated by the caller.
data_offset: None,
data_length: Some(size_compressed),
src_extents: vec![],
src_length: None,
dst_extents: vec![extent],
dst_length: None,
data_sha256_hash: Some(digest_compressed.as_ref().to_vec()),
src_sha256_hash: None,
};
// data_offset must be manually updated by the caller.
let mut operation = InstallOperation::default();
operation.set_type(Type::ReplaceXz);
operation.data_length = Some(size_compressed);
operation.dst_extents.push(extent);
operation.data_sha256_hash = Some(digest_compressed.as_ref().to_vec());
partition.operations.clear();
partition.operations.push(operation);
@@ -685,7 +679,7 @@ pub fn verify_payload(
)?;
let buf = writer.into_inner();
util::read_protobuf::<Signatures>(&buf)?
Signatures::decode(buf.as_slice())?
};
// Check the metadata signatures.
@@ -737,7 +731,7 @@ pub fn verify_payload(
)?;
let buf = writer.into_inner();
util::read_protobuf::<Signatures>(&buf)?
Signatures::decode(buf.as_slice())?
};
// Check the payload signatures.
@@ -797,10 +791,10 @@ pub fn apply_operation(
let mut hasher = Context::new(&ring::digest::SHA256);
match op.type_pb {
match op.r#type() {
// Handle ZERO/DISCARD specially since they don't require access to
// the payload blob.
mod_InstallOperation::Type::ZERO | mod_InstallOperation::Type::DISCARD => {
Type::Zero | Type::Discard => {
stream::copy_n_inspect(
io::repeat(0),
&mut writer,
@@ -823,7 +817,7 @@ pub fn apply_operation(
reader.seek(SeekFrom::Start(in_offset))?;
match other {
mod_InstallOperation::Type::REPLACE => {
Type::Replace => {
stream::copy_n_inspect(
&mut reader,
&mut writer,
@@ -832,7 +826,7 @@ pub fn apply_operation(
cancel_signal,
)?;
}
mod_InstallOperation::Type::REPLACE_BZ => {
Type::ReplaceBz => {
let mut decoder = BzDecoder::new(&mut writer);
stream::copy_n_inspect(
&mut reader,
@@ -843,7 +837,7 @@ pub fn apply_operation(
)?;
decoder.finish()?;
}
mod_InstallOperation::Type::REPLACE_XZ => {
Type::ReplaceXz => {
let mut decoder = XzDecoder::new(&mut writer);
stream::copy_n_inspect(
&mut reader,
@@ -854,7 +848,7 @@ pub fn apply_operation(
)?;
decoder.finish()?;
}
_ => return Err(Error::UnsupportedOperation(op.type_pb)),
_ => return Err(Error::UnsupportedOperation(op.r#type())),
}
}
}
@@ -862,9 +856,7 @@ pub fn apply_operation(
let expected_digest = op.data_sha256_hash.as_deref();
let digest = hasher.finish();
if expected_digest != Some(digest.as_ref())
&& op.type_pb != mod_InstallOperation::Type::ZERO
{
if expected_digest != Some(digest.as_ref()) && op.r#type() != Type::Zero {
return Err(Error::MismatchedDigest {
expected: expected_digest.map(hex::encode),
actual: hex::encode(digest.as_ref()),
@@ -902,7 +894,7 @@ pub fn extract_image_to_memory(
apply_operation(
reader,
writer,
header.manifest.block_size,
header.manifest.block_size(),
header.blob_offset,
op,
cancel_signal,
@@ -952,7 +944,7 @@ pub fn extract_images<'a>(
apply_operation(
reader,
writer,
header.manifest.block_size,
header.manifest.block_size(),
header.blob_offset,
op,
cancel_signal,
+1
View File
@@ -18,6 +18,7 @@ pub mod cli;
pub mod crypto;
pub mod escape;
pub mod format;
pub mod octal;
pub mod protobuf;
pub mod stream;
pub mod util;
+53
View File
@@ -0,0 +1,53 @@
/*
* SPDX-FileCopyrightText: 2023 Andrew Gunnerson
* SPDX-License-Identifier: GPL-3.0-only
*/
//! Hack to format an integer as an octal string because toml_edit can't output
//! octal-formatted integers and many other toml parsers can't parse it either.
use std::{
fmt::{self, Octal},
marker::PhantomData,
};
use num_traits::{Num, PrimInt};
use serde::{de::Visitor, Deserializer, Serializer};
pub fn serialize<S, T>(data: &T, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
T: PrimInt + Octal,
{
serializer.serialize_str(&format!("{data:o}"))
}
pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
T: PrimInt,
<T as Num>::FromStrRadixErr: fmt::Display,
{
struct OctalStrVisitor<T>(PhantomData<T>);
impl<'de, T> Visitor<'de> for OctalStrVisitor<T>
where
T: PrimInt,
<T as Num>::FromStrRadixErr: fmt::Display,
{
type Value = T;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "a string containing an octal number")
}
fn visit_str<E>(self, data: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
T::from_str_radix(data, 8).map_err(serde::de::Error::custom)
}
}
deserializer.deserialize_str(OctalStrVisitor(PhantomData))
}
+11 -1
View File
@@ -1 +1,11 @@
include!(concat!(env!("OUT_DIR"), "/protobuf/mod.rs"));
pub mod build {
pub mod tools {
pub mod releasetools {
include!(concat!(env!("OUT_DIR"), "/build.tools.releasetools.rs"));
}
}
}
pub mod chromeos_update_engine {
include!(concat!(env!("OUT_DIR"), "/chromeos_update_engine.rs"));
}
+4 -18
View File
@@ -5,17 +5,17 @@
use std::{fmt, path::Path};
use quick_protobuf::{BytesReader, MessageRead, MessageWrite, Writer};
use num_traits::PrimInt;
pub const ZEROS: [u8; 16384] = [0u8; 16384];
/// A small wrapper to format a number as a size in bytes.
#[derive(Clone, Copy)]
pub struct NumBytes(pub usize);
pub struct NumBytes<T: PrimInt>(pub T);
impl fmt::Debug for NumBytes {
impl<T: PrimInt + fmt::Debug> fmt::Debug for NumBytes<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.0 == 1 {
if self.0 == T::one() {
write!(f, "<{:?} byte>", self.0)
} else {
write!(f, "<{:?} bytes>", self.0)
@@ -37,20 +37,6 @@ pub fn is_zero(mut buf: &[u8]) -> bool {
true
}
/// Read a protobuf message with no leading size field.
pub fn read_protobuf<'a, M: MessageRead<'a>>(data: &'a [u8]) -> quick_protobuf::Result<M> {
let mut reader = BytesReader::from_bytes(data);
M::from_reader(&mut reader, data)
}
/// Write a protobuf message with no leading size field.
pub fn write_protobuf<M: MessageWrite>(message: &M) -> quick_protobuf::Result<Vec<u8>> {
let mut buf = Vec::with_capacity(message.get_size());
let mut writer = Writer::new(&mut buf);
message.write_message(&mut writer)?;
Ok(buf)
}
/// Get the non-empty parent of a path. If the path has no parent in the string,
/// then `.` is returned. This does not perform any filesystem operations.
pub fn parent_path(path: &Path) -> &Path {
+50
View File
@@ -0,0 +1,50 @@
/*
* SPDX-FileCopyrightText: 2023 Andrew Gunnerson
* SPDX-License-Identifier: GPL-3.0-only
*/
use std::io::{self, Cursor};
use avbroot::{
self,
format::cpio::{CpioEntryType, CpioReader, CpioWriter},
util,
};
#[test]
fn round_trip_archive() {
let data = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/data/archive.cpio",
));
assert_ne!(data.len() % 512, 0);
for pad_to_block_size in [false, true] {
println!("Pad to block size: {pad_to_block_size}");
let reader = Cursor::new(data);
let mut cpio_reader = CpioReader::new(reader, false);
let writer = Cursor::new(Vec::new());
let mut cpio_writer = CpioWriter::new(writer, pad_to_block_size);
while let Some(entry) = cpio_reader.next_entry().unwrap() {
cpio_writer.start_entry(&entry).unwrap();
if entry.file_type == CpioEntryType::Regular {
io::copy(&mut cpio_reader, &mut cpio_writer).unwrap();
}
}
let writer = cpio_writer.finish().unwrap();
let new_data = writer.get_ref().as_slice();
if pad_to_block_size {
assert!(new_data.starts_with(data));
assert!(util::is_zero(&new_data[data.len()..]));
assert_eq!(new_data.len() % 512, 0);
} else {
assert_eq!(new_data, data);
}
}
}
Binary file not shown.
+2 -2
View File
@@ -15,10 +15,10 @@ avbroot = { path = "../avbroot" }
clap = { version = "4.4.1", features = ["derive"] }
ctrlc = "3.4.0"
hex = { version = "0.4.3", features = ["serde"] }
ring = "0.16.20"
ring = "0.17.0"
serde = { version = "1.0.188", features = ["derive"] }
tempfile = "3.8.0"
toml_edit = { version = "0.19.14", features = ["serde"] }
toml_edit = { version = "0.20.1", features = ["serde"] }
# https://github.com/zip-rs/zip/pull/383
[dependencies.zip]
+62 -62
View File
@@ -1,86 +1,86 @@
[magisk]
"url" = "https://github.com/topjohnwu/Magisk/releases/download/v26.0/Magisk-v26.0.apk"
"hash" = "9e14d3d3ca1f1a2765f8ca215ebbf35ea5fd2896fb147eea581fcaa3b4e77d25"
"url" = "https://github.com/topjohnwu/Magisk/releases/download/v26.3/Magisk.v26.3.apk"
"hash" = "30ff6ec0709412adfcd0b735c0eb1f61cd9d589af4bdef4cf03c09b986b5acce"
# Google Pixel 7 Pro
# What's unique: init_boot (boot v4) + vendor_boot (vendor v4)
[device.cheetah]
url = "https://dl.google.com/dl/android/aosp/cheetah-ota-tq2a.230305.008.c1-6ac5ff2e.zip"
url = "https://dl.google.com/dl/android/aosp/cheetah-ota-tq3a.230901.001-6b881553.zip"
sections = [
{ start = 0, end = 151715 },
{ start = 21683150, end = 23179365 },
{ start = 2043499985, end = 2043508325 },
{ start = 2315331822, end = 2333060126 },
{ start = 2344084950, end = 2344090066 },
{ start = 0, end = 152523 },
{ start = 21750700, end = 23251455 },
{ start = 2044485458, end = 2044493782 },
{ start = 2316042420, end = 2333812318 },
{ start = 2344911202, end = 2344916318 },
]
hash.original.full = "6ac5ff2e14dc16755ea4ea30e6dbe25103b889a36a465194ef943bd0d665b91c"
hash.original.stripped = "549522015f0369a3b89385f532ab62235b47c2c39540bd0adaaf6acc81fdda94"
hash.patched.full = "b380720852e2a1e994bcf38064f577bac68b18e799cf8166cb6a7edb8a661cb4"
hash.patched.stripped = "560cdf4d7b25fb5bc650f96ae5a3c7593ac229a364bb39887287cfb734f6b377"
hash.avb_images."init_boot.img" = "fac9305ce22b897fbfb193968d5346f4c70f6c18c3060bb106226f134ce5f433"
hash.avb_images."vbmeta.img" = "0b3d719b751dd43bbec95d02b1bf57b5dae62e42a52502895892a207b773e77d"
hash.avb_images."vbmeta_system.img" = "cf8c77dcf0a4474d49b5bdc2a44bdb3646464d5212fbe12aa5d3c5f531742f4f"
hash.avb_images."vbmeta_vendor.img" = "660d8f61acd95a4f8ad416b4cbe126e9c039706462b4236ad723953c72ac49a8"
hash.avb_images."vendor_boot.img" = "c788d4d8eb7926ad1bfa2a9c000343c3c73cedc580449f5270a711feb620f033"
hash.original.full = "6b881553f012d582080642d660e1cf5c9e6fe41e9f1c6ab12ae87fab7894e307"
hash.original.stripped = "9befd7887a125ebd8e9ae0555469dababe6bc04b0aa41aa2562036782a6d87e0"
hash.patched.full = "6a08ae5c08e42b29ffc476511b6c60de8b77ba3f06c469a0a640e84cb95b9db9"
hash.patched.stripped = "479b4e203d432148baaf4eaa69205c2291ec10e8541c9a78e6d9b799e994f1e3"
hash.avb_images."init_boot.img" = "3bedb41be98c46241f11219021dfbb799a6d5c89e6e00d45a66f9a5b42e7dfbc"
hash.avb_images."vbmeta.img" = "e8e6e898ca73807edb43af0a0e86d4a94b14256def89581970287a9b1bf7a3ee"
hash.avb_images."vbmeta_system.img" = "dbb63e08f26f46ccda501d99058d513ff71e3d6302c14d587442b666ff08862a"
hash.avb_images."vbmeta_vendor.img" = "6ffa0a10e72c3371653be80de1380832b4d7f8bbf38a2bd861d44a4097a57117"
hash.avb_images."vendor_boot.img" = "8f9407435e1ea532e55be418d58e1b3a4f8e0794e3cf4e562e0a0414058c6108"
# Google Pixel 6a
# What's unique: boot (boot v4, no ramdisk) + vendor_boot (vendor v4, 2 ramdisks)
[device.bluejay]
url = "https://dl.google.com/dl/android/aosp/bluejay-ota-tq2a.230305.008.e1-915f9087.zip"
url = "https://dl.google.com/dl/android/aosp/bluejay-ota-tq3a.230901.001-1f1f0abe.zip"
sections = [
{ start = 0, end = 140787 },
{ start = 1060207, end = 21612852 },
{ start = 1886150700, end = 1886158844 },
{ start = 2069112987, end = 2092260102 },
{ start = 2098778558, end = 2098783674 },
{ start = 0, end = 142587 },
{ start = 1062619, end = 21678441 },
{ start = 1920893927, end = 1920902079 },
{ start = 2103596124, end = 2126776858 },
{ start = 2133324030, end = 2133329146 },
]
hash.original.full = "915f9087b627b6961be9bb447dc63a7a1083b536753a78715e98641eaeb9c9d1"
hash.original.stripped = "a3ee5b6e39e687665c31790118ab9f47715b0b8285ae9847dbf81307f963db14"
hash.patched.full = "bfa7b26d90bdc889a7a199439e1564b219e5e2dbfddc1657bc1c6b73229be67e"
hash.patched.stripped = "4e56ee4a8554f2b08ffc2f1470ad60b9b63d2b6fb469ed1f7c4b1204bbf8ad7d"
hash.avb_images."boot.img" = "a1a705092e7034d20b83c94d78291418e13c343b1573c1b11e0fc884fc00ae62"
hash.avb_images."vbmeta.img" = "3c123705be57ab142d2b43beef9b123eaad129df17a523b59b1d63b9122d28b0"
hash.avb_images."vbmeta_system.img" = "285b83e4290f3257dc3678f0c3191794830bb2d72fb0969b69fc8f09d7ddff12"
hash.avb_images."vbmeta_vendor.img" = "981f736586b91a9f4c93c4208a0d191a35ff15118c6fa505d755ee7fda8b2477"
hash.avb_images."vendor_boot.img" = "ceffcb4fdb33aa3bb2c70621060acd5af612206b21cc413d5c2d39fee25144ab"
hash.original.full = "1f1f0abe67a6f6f47287be6dafec2c12628de6a715b82ca7beddaf67ad22aca5"
hash.original.stripped = "38b15f5efdc7e056bc799859ba72ef9a73e93c61292c59f85fb4b9c31acc5f82"
hash.patched.full = "20f3eb522c45f8185c8c121ef2f6a18214345b85f3021d05841e1b002d348b3e"
hash.patched.stripped = "105f4305f886a79c03fcabd296a44ef498e2b9e602970c0ef6d8599b74a704b0"
hash.avb_images."boot.img" = "a19cb4d4fcc7f3e7d3046c3d19e2f243fb02513ca848ff92ad70d1ada55c4e65"
hash.avb_images."vbmeta.img" = "2d817e35f7b6cdc2edce58ef249a966fc677085b70a4aced4c829320aeef0be2"
hash.avb_images."vbmeta_system.img" = "98a050f0d53a016fbb78147b1b4a9bca3fde615aa4da34bf62c2e07a395104b5"
hash.avb_images."vbmeta_vendor.img" = "fac530f47f237e76f3c7c3cdfe96308170dd8e8f0b227d81114a489c69ba763c"
hash.avb_images."vendor_boot.img" = "6b66d8ea772dafc85e8745e88c9e05ff0401d062010c4d1ae0914b93cf3510aa"
# Google Pixel 4a 5G
# What's unique: boot (boot v3) + vendor_boot (vendor v3)
[device.bramble]
url = "https://dl.google.com/dl/android/aosp/bramble-ota-tq2a.230305.008.c1-a925dd09.zip"
url = "https://dl.google.com/dl/android/aosp/bramble-ota-tq3a.230901.001-6d107ffa.zip"
sections = [
{ start = 0, end = 140531 },
{ start = 496187, end = 11655082 },
{ start = 1650283561, end = 1650287993 },
{ start = 1884739919, end = 1908081011 },
{ start = 1910894027, end = 1910899144 },
{ start = 0, end = 142225 },
{ start = 497945, end = 11647087 },
{ start = 1683478307, end = 1683482723 },
{ start = 1917281683, end = 1940628772 },
{ start = 1943442548, end = 1943447665 },
]
hash.original.full = "a925dd09c8d613d46cf72677c16f4fadee18bc21734d57047c6ccf31f672507b"
hash.original.stripped = "79322b0b417359e8f072032de676d7e5bd2715a3b3554c48ed5cc9e9a25c6866"
hash.patched.full = "cf79cd60acd3635f5085d8bb411d4a8dc4d7e62440f62a14e7ea12f5a9b7cd8a"
hash.patched.stripped = "b684a78fe08014f1633e74d1f380e137823ba77a47ddf428bc649364f5548b75"
hash.avb_images."boot.img" = "2bbf2c6d2f82d454426b26ac3b4887b26ca0591b458e6cf137207ecbb8f7649d"
hash.avb_images."vbmeta.img" = "ab3b2487671b3fc28e163898621d6c068164d335b6ddd9b94e4fde9471c95d66"
hash.avb_images."vbmeta_system.img" = "2fcd52d7462916a8510bbb07f2f5a14200afe2de97568396fe75e04c5c283152"
hash.avb_images."vendor_boot.img" = "e27f157c4ebf4e958165997a4b87d4de1cfc34f4dea423a153327a27b053cac7"
hash.original.full = "6d107ffac1cd3da2c972112acc75957ed725e5c13d57ca724d9bcca5404fcebd"
hash.original.stripped = "5b889bdab3bb12ddcd3c243a56e1c58bedada8831069f49d56fe5098fb141e35"
hash.patched.full = "c2866d8959fea55884de6281403e7daf435cded62477181354eb76332446af28"
hash.patched.stripped = "a9ccefe44818560144f073bef8ae1c2c840cf8fff9dafb0e589bd5fd40cf0fea"
hash.avb_images."boot.img" = "8e7278a2e8ae44ffc5475717eb0e1aa56bfb7650aef34375b0fe92f790835f95"
hash.avb_images."vbmeta.img" = "b036132b867f52a86eef79716261f35b1eb50e843dc4fe42f72cce67b24ae2db"
hash.avb_images."vbmeta_system.img" = "9a7c6fd654e7a92aeffbdbd55ea0d87eee36f4c235e1b505423ad8a13a751a00"
hash.avb_images."vendor_boot.img" = "e774aa770fd9c0d19a509f212309f20b08da411f8830a7383646a65571437933"
# Google Pixel 4a
# What's unique: boot (boot v2)
[device.sunfish]
url = "https://dl.google.com/dl/android/aosp/sunfish-ota-tq2a.230305.008.c1-174fd16b.zip"
url = "https://dl.google.com/dl/android/aosp/sunfish-ota-tq3a.230805.001-01fd34b2.zip"
sections = [
{ start = 0, end = 129700 },
{ start = 476996, end = 34035261 },
{ start = 1624751947, end = 1624756371 },
{ start = 1823132563, end = 1823137581 },
{ start = 0, end = 131325 },
{ start = 478553, end = 34014760 },
{ start = 1658403115, end = 1658407531 },
{ start = 1855778567, end = 1855783585 },
]
hash.original.full = "174fd16b47ef994ea8f3cb0f3fb456df2654b0aa1f9ea6fb8e54e5c6319f2601"
hash.original.stripped = "943ce3ae2aac8a0ccd4a7e9d4e38a9c495c39639f2621c6853be4c7a3fa0fc26"
hash.patched.full = "cdfffa731f0aca0ab9eff1e7d7bfee8c4716054d64cf0a47e50f50da6cbdb849"
hash.patched.stripped = "35b720058c460dd28b00f40bed4bcd1d133522d42d00ba048172b3092a7444ee"
hash.avb_images."boot.img" = "22182f2efc7043f35d79e71abb400ce919c6b3b8419405e16469644932367ee6"
hash.avb_images."vbmeta.img" = "4cbe171bb37515f59cd4082cc2d982ca1edfeba9db09dd62c8959dd318423888"
hash.avb_images."vbmeta_system.img" = "7cdb590bfc1056a5a8c7606ff05e99eb344efe108296682698b5cfe83905e0cd"
hash.original.full = "01fd34b206152a3559039161c9874ab03df37da4268b86a9e0be899de5fc0af7"
hash.original.stripped = "cc311b5bd46e06cfdefbade794d33aa9bc3ceda4ad4f38bfe9f0dfc17033d207"
hash.patched.full = "b788d2d86008a3923734a40fb89ca98533116e51e10f35c0447beb956b236bf5"
hash.patched.stripped = "b174f530d63bfe753ab9435a910b01a1abb2e08a8628b50101f876ed2313e536"
hash.avb_images."boot.img" = "7cdb8e4a9b79d9c2b4d5a513c219082c0609cf6cab8cf07e122dcaaa2bd1ed63"
hash.avb_images."vbmeta.img" = "3679c7224e3e3e0793b4d1a031e116098460a6b4c5f3f88d5a3a0a4c65b21582"
hash.avb_images."vbmeta_system.img" = "1d3efa00fd1d44a594c7317072468fa95c23d83d2759d6d6e757783ceeabc594"
# OnePlus 10 Pro
# Build NE2215_11_C.26
@@ -107,10 +107,10 @@ sections = [
]
hash.original.full = "929f892fbd70699cf7f118a119aac1ae1b86351e1ada17715666fa4401e63472"
hash.original.stripped = "4eabaf79b6c2b5df305e3ecdc2b9570c0dd27350b4e8d6434584000c4989ff3d"
hash.patched.full = "3453b2eda97ca1ba7367fa9d0dd37b21a5065e2e57cc3bbe9a6f135349d42d0b"
hash.patched.stripped = "1a41e435bdbf4302761e719e218e8682145644c0fe276739c3265f392adbd74d"
hash.avb_images."boot.img" = "f5dc3b147c54589be8db00ca15257a3688424a9eb88bd9c2cec82ebf4f6bf859"
hash.avb_images."recovery.img" = "a42c0bf4f023cd24394184a33ee113783a9c89a7cc4c0c582a5f72cc23b72309"
hash.patched.full = "ec576b7430e5a2788e89f8bbe37ee81b116386d9b101865d3b75eb9c51a0db4c"
hash.patched.stripped = "ddd0cf1b42564f8c2980320c14f8e0eb125412eb7a13ae8fb52d35424546c235"
hash.avb_images."boot.img" = "480d7cf519326fcaa5106ecfbbeb907309068635f7f6a25e5e4571d525c4926a"
hash.avb_images."recovery.img" = "eeb0f67e2084174fced510f4b59a82022559ffbe1c20d2c0ea4757fcd989a3af"
hash.avb_images."vbmeta.img" = "c022cf79da301a8430af5c49704944c490707fa0306031fe3ea22c39ce4734f6"
hash.avb_images."vbmeta_system.img" = "749616b7f04487c05e9e363ad2071a0ab3bae29d497daf1f1a7695f7c8cfa82a"
hash.avb_images."vbmeta_vendor.img" = "a6037fce745384425fb12745b8568386b84fb57ca6f94f6e47bcf754de341ae4"
+3 -4
View File
@@ -26,6 +26,7 @@ use anyhow::{anyhow, bail, Context, Result};
use avbroot::{
cli::ota::{ExtractCli, PatchCli, VerifyCli},
format::{ota, payload::PayloadHeader},
protobuf::chromeos_update_engine::install_operation::Type,
stream::{self, FromReader, HashingReader, PSeekFile, SectionReader},
};
use clap::Parser;
@@ -121,13 +122,11 @@ fn strip_image(
.collect::<HashSet<_>>();
let mut data_holes = vec![];
use avbroot::protobuf::chromeos_update_engine::mod_InstallOperation::Type;
for p in &header.manifest.partitions {
if !required_images.contains(&p.partition_name) {
for op in &p.operations {
match op.type_pb {
Type::ZERO | Type::DISCARD => continue,
match op.r#type() {
Type::Zero | Type::Discard => continue,
_ => {
let start = payload_offset
+ header.blob_offset
+3 -2
View File
@@ -1,6 +1,6 @@
#[cfg(not(windows))]
mod fuzz {
use std::io::Cursor;
use std::{io::Cursor, sync::atomic::AtomicBool};
use avbroot::format::cpio;
use honggfuzz::fuzz;
@@ -8,8 +8,9 @@ mod fuzz {
pub fn main() {
loop {
fuzz!(|data: &[u8]| {
let cancel_signal = AtomicBool::new(false);
let reader = Cursor::new(data);
let _ = cpio::load(reader, true);
let _ = cpio::load(reader, true, &cancel_signal);
});
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
id=com.chiller3.avbroot.clearotacerts
name=clearotacerts
version=v2.1.1
versionCode=131329
version=v2.2.0
versionCode=131584
author=chenxiaolong
description=Block A/B OTAs by clearing verification certificates
+2 -2
View File
@@ -1,6 +1,6 @@
id=com.chiller3.avbroot.oemunlockonboot
name=oemunlockonboot
version=v2.1.1
versionCode=131329
version=v2.2.0
versionCode=131584
author=chenxiaolong
description=Enable OEM unlocking on every boot
+1 -1
View File
@@ -14,7 +14,7 @@ clap = { version = "4.4.1", features = ["derive"] }
human-sort = "0.2.2"
regex = { version = "1.9.4", default-features = false, features = ["perf", "std"] }
tempfile = "3.8.0"
toml_edit = "0.19.14"
toml_edit = "0.20.1"
walkdir = "2.3.3"
# https://github.com/zip-rs/zip/pull/383