Compare commits

...

25 Commits

Author SHA1 Message Date
Andrew Gunnerson e18ef20e4d Version 3.4.1
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-07-28 18:04:20 -04:00
Andrew Gunnerson b140620ed3 CHANGELOG.md: Add entry for PR #323
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-07-28 18:03:16 -04:00
Andrew Gunnerson dd9d8959fd Add support for Magisk 27006
Version 27006 now requires init-ld to be included in the ramdisk.

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-07-28 17:58:13 -04:00
Andrew Gunnerson 9a7cece973 CHANGELOG.md: Add entry for PR #321
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-07-15 21:44:29 -04:00
Andrew Gunnerson aac3aded78 Update all dependencies
Version 1.6.0 of the bytes library was yanked. There's no vulnerability
that impacts avbroot, but it was tripping the cargo-deny checks.

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-07-15 21:32:14 -04:00
Andrew Gunnerson 24320d4fae README.md: Move signature verification instructions to shared repo
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-07-14 18:23:55 -04:00
Ivan Katrovsky 6800ae073e README.ru.md: update translation
Sync with https://github.com/chenxiaolong/avbroot/commit/4d90ee2ac6223ec9e4ca1b1b77d84973ad90cd75

Signed-off-by: Ivan Katrovsky <notbugreporter@proton.me>
2024-07-06 02:37:41 -04:00
Andrew Gunnerson 4d90ee2ac6 README.md: Document that uninstalling Magisk will also flash an unsigned boot image
Closes: #318

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-07-05 19:45:27 -04:00
Ivan Katrovsky 6b087c0844 README.ru.md: update translation
Sync with https://github.com/chenxiaolong/avbroot/commit/d384a8a99bda591a6299f8f76f693eeb1725cb0f

Signed-off-by: Ivan Katrovsky <notbugreporter@proton.me>
2024-07-05 15:46:26 +03:00
Andrew Gunnerson d384a8a99b README.md: Document that fastboot >=34 is required
Older versions of fastboot have bugs that cause the reboot to fastbootd
mode to be skipped, causing failures when flashing dynamic partitions.

Fixes: #314

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-07-04 16:20:22 -04:00
Andrew Gunnerson bc358c62af Version 3.4.0
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-26 19:52:44 -04:00
Andrew Gunnerson fc05cb901a CHANGELOG.md: Add entry for PR #312
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-26 19:52:11 -04:00
Andrew Gunnerson 031ac8aa31 cli/avb: Add --public-key option for extract-avb subcommand
Issue: #312

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-26 19:46:24 -04:00
Andrew Gunnerson 4a1dab4069 Add support for signing with an external program
By default, the helper program is invoked in a way that is compatible
with avbtool's --signing_helper. However, the arguments have been
extended slightly to allow passing in the passphrase file or environment
variable for non-interactive use.

Fixes: #310

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-26 19:46:22 -04:00
Andrew Gunnerson bf885e40cf CHANGELOG.md: Add entry for PR #311
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-24 18:15:49 -04:00
Andrew Gunnerson c2a441cf78 avb: AlgorithmType: Fail on unknown key types
This is never reachable due to additional checks in every code path that
invokes sign() and verify(), but still better to be correct.

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-24 17:54:50 -04:00
Andrew Gunnerson f6c6a9509a Version 3.3.0
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-23 15:51:57 -04:00
Andrew Gunnerson 5a00995366 CHANGELOG.md: Add entry for PR #309
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-22 18:47:28 -04:00
Andrew Gunnerson edf537aad6 Add payload subcommand for dumping payload.bin header
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-22 18:42:46 -04:00
Andrew Gunnerson f006f20209 CHANGELOG.md: Add entry for PR #307
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-22 18:38:44 -04:00
Andrew Gunnerson f36c1ca451 payload: Fudge CoW size estimate by 1%
lz4_flex appears to compress system images better than the original lz4
implementation used in libsnapshot_cow, so the estimates are too low.

Fixes: #306

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-21 22:36:41 -04:00
Andrew Gunnerson 29b72961a3 Update CoW size estimate when replacing entire dynamic partitions
Otherwise, if the partition size increases or the data becomes more
incompressible, update_engine might fail to flash the partition due to
the CoW block device running out of space.

Since all known VABC-enabled OTAs in the wild currently use CoW v2 with
lz4 compression, this is the only configuration we support. CoW v3 also
exists in AOSP's libsnapshot_cow, but is much more complicated to
implement and is not yet used, even in the Android 15 beta OTAs.

Fixes: #306

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-21 21:51:49 -04:00
Andrew Gunnerson e105efb6d3 Version 3.2.3
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-14 18:26:14 -04:00
Andrew Gunnerson 2a7df104ed CHANGELOG.md: Add entry for PR #304
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-14 18:17:06 -04:00
Andrew Gunnerson 8e52a9cf8c Add support for cross-compiling to Android
The precompiled binaries are compiled for aarch64 API 31, which should
work for every device that avbroot supports.

Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
2024-06-14 17:49:15 -04:00
27 changed files with 1083 additions and 451 deletions
+35 -4
View File
@@ -19,6 +19,7 @@ jobs:
# https://github.com/rust-lang/rust/issues/78210
RUSTFLAGS: -C strip=symbols -C target-feature=+crt-static
TARGETS: ${{ join(matrix.artifact.targets, ' ') || matrix.artifact.name }}
ANDROID_API: ${{ matrix.artifact.android_api }}
strategy:
fail-fast: false
matrix:
@@ -33,6 +34,12 @@ jobs:
- aarch64-apple-darwin
- x86_64-apple-darwin
combine: lipo
# ubuntu-latest is not 24.04 yet and 22.04's qemu-user-static segfaults.
- os: ubuntu-24.04
name: aarch64-linux-android31
targets:
- aarch64-linux-android
android_api: '31'
steps:
- name: Check out repository
uses: actions/checkout@v4
@@ -40,6 +47,26 @@ jobs:
# For git describe
fetch-depth: 0
- name: Install qemu-user-static
if: ${{ contains(matrix.artifact.name, 'android') }}
shell: bash
run: |
sudo apt-get -y update
sudo apt-get -y install qemu-user-static
- name: Set Android temporary directory
if: ${{ contains(matrix.artifact.name, 'android') }}
shell: bash
run: |
echo "TMPDIR=/tmp" >> "${GITHUB_ENV}"
- name: Install cargo-android
shell: bash
run: |
cargo install \
--git https://github.com/chenxiaolong/cargo-android \
--tag v0.1.1
- name: Get version
id: get_version
shell: bash
@@ -63,7 +90,8 @@ jobs:
shell: bash
run: |
for target in ${TARGETS}; do
cargo clippy --release --workspace --features static \
cargo android \
clippy --release --workspace --features static \
--target "${target}"
done
@@ -71,7 +99,8 @@ jobs:
shell: bash
run: |
for target in ${TARGETS}; do
cargo build --release --workspace --features static \
cargo android \
build --release --workspace --features static \
--target "${target}"
done
@@ -79,7 +108,8 @@ jobs:
shell: bash
run: |
for target in ${TARGETS}; do
cargo test --release --workspace --features static \
cargo android \
test --release --workspace --features static \
--target "${target}"
done
@@ -87,7 +117,8 @@ jobs:
shell: bash
run: |
for target in ${TARGETS}; do
cargo run --release -p e2e --features static \
cargo android \
run --release -p e2e --features static \
--target "${target}" \
-- test -a -c e2e/e2e.toml
done
+30
View File
@@ -7,6 +7,27 @@
to update the actual links at the bottom of the file.
-->
### Version 3.4.1
* Update all dependencies ([PR #321])
* Add support for Magisk 27006 ([PR #323])
### Version 3.4.0
* Fix (unreachable) minor error handling logic when attempting to use unsupported AVB signing algorithms ([PR #311])
* Add support for performing signing operations with external programs ([Issue #310], [PR #312])
* See the linked issue for an example of how to sign with a Yubikey.
### Version 3.3.0
* Recompute CoW size estimate when replacing dynamic partitions ([Issue #306], [PR #307])
* Fixes out of space error when flashing a patched OTA that uses `--replace` to replace a dynamic partition (eg. `system`) with a larger or more incompressible image
* Add `avbroot payload info` subcommand for inspecting `payload.bin` headers ([PR #309])
### Version 3.2.3
* Add prebuilt binary for Android (aarch64) ([PR #304])
### Version 3.2.2
* Add new `--recompute-size` option to `avbroot avb pack` to automatically recompute the image size for resizable images ([Discussion #294], [PR #296])
@@ -207,6 +228,8 @@ Behind-the-scenes changes:
[Issue #285]: https://github.com/chenxiaolong/avbroot/issues/285
[Issue #291]: https://github.com/chenxiaolong/avbroot/issues/291
[Issue #301]: https://github.com/chenxiaolong/avbroot/issues/301
[Issue #306]: https://github.com/chenxiaolong/avbroot/issues/306
[Issue #310]: https://github.com/chenxiaolong/avbroot/issues/310
[PR #130]: https://github.com/chenxiaolong/avbroot/pull/130
[PR #132]: https://github.com/chenxiaolong/avbroot/pull/132
[PR #133]: https://github.com/chenxiaolong/avbroot/pull/133
@@ -295,3 +318,10 @@ Behind-the-scenes changes:
[PR #293]: https://github.com/chenxiaolong/avbroot/pull/293
[PR #296]: https://github.com/chenxiaolong/avbroot/pull/296
[PR #297]: https://github.com/chenxiaolong/avbroot/pull/297
[PR #304]: https://github.com/chenxiaolong/avbroot/pull/304
[PR #307]: https://github.com/chenxiaolong/avbroot/pull/307
[PR #309]: https://github.com/chenxiaolong/avbroot/pull/309
[PR #311]: https://github.com/chenxiaolong/avbroot/pull/311
[PR #312]: https://github.com/chenxiaolong/avbroot/pull/312
[PR #321]: https://github.com/chenxiaolong/avbroot/pull/321
[PR #323]: https://github.com/chenxiaolong/avbroot/pull/323
Generated
+138 -183
View File
@@ -66,9 +66,9 @@ dependencies = [
[[package]]
name = "anstyle-query"
version = "1.0.3"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a64c907d4e79225ac72e2a354c9ce84d50ebb4586dee56c82b3ee73004f537f5"
checksum = "ad186efb764318d35165f1758e7dcef3b10628e26d41a44bc5550652e6804391"
dependencies = [
"windows-sys 0.52.0",
]
@@ -109,7 +109,7 @@ checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0"
[[package]]
name = "avbroot"
version = "3.2.2"
version = "3.4.1"
dependencies = [
"anyhow",
"assert_matches",
@@ -178,9 +178,9 @@ checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"
[[package]]
name = "bitflags"
version = "2.5.0"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1"
checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
[[package]]
name = "block-buffer"
@@ -219,9 +219,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "bytes"
version = "1.6.0"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9"
checksum = "a12916984aab3fa6e39d655a33e09c0071eb36d6ab3aea5c2d78551f1df6d952"
[[package]]
name = "bzip2"
@@ -244,9 +244,9 @@ dependencies = [
[[package]]
name = "cap-primitives"
version = "3.1.0"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00172660727e2d7f808e7cc2bfffd093fdb3ea2ff2ef819289418a3c3ffab5ac"
checksum = "6d00bd8d26c4270d950eaaa837387964a2089a1c3c349a690a1fa03221d29531"
dependencies = [
"ambient-authority",
"fs-set-times",
@@ -261,9 +261,9 @@ dependencies = [
[[package]]
name = "cap-std"
version = "3.1.0"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8cd9187bb3f7478a4c135ea10473a41a5f029d2ac800c1adf64f35ec7d4c8603"
checksum = "19eb8e3d71996828751c1ed3908a439639752ac6bdc874e41469ef7fc15fbd7f"
dependencies = [
"cap-primitives",
"io-extras",
@@ -273,9 +273,9 @@ dependencies = [
[[package]]
name = "cap-tempfile"
version = "3.1.0"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccdf3787d405176792605744d5fd59dcc66703f743c0c628516d7a5518b1e4de"
checksum = "53880047c3f37cd64947775f0526795498d614182603a718c792616b762ce777"
dependencies = [
"cap-std",
"rand",
@@ -294,13 +294,12 @@ dependencies = [
[[package]]
name = "cc"
version = "1.0.97"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "099a5357d84c4c61eb35fc8eafa9a79a902c2f76911e5747ced4e032edd8d9b4"
checksum = "324c74f2155653c90b04f25b2a47a8a631360cb908f92a772695f430c7e31052"
dependencies = [
"jobserver",
"libc",
"once_cell",
]
[[package]]
@@ -327,9 +326,9 @@ dependencies = [
[[package]]
name = "clap"
version = "4.5.4"
version = "4.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0"
checksum = "64acc1846d54c1fe936a78dc189c34e28d3f5afc348403f28ecf53660b9b8462"
dependencies = [
"clap_builder",
"clap_derive",
@@ -337,9 +336,9 @@ dependencies = [
[[package]]
name = "clap_builder"
version = "4.5.2"
version = "4.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4"
checksum = "6fb8393d67ba2e7bfaf28a23458e4e2b543cc73a99595511eb207fdb8aede942"
dependencies = [
"anstream",
"anstyle",
@@ -349,30 +348,30 @@ dependencies = [
[[package]]
name = "clap_complete"
version = "4.5.2"
version = "4.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd79504325bf38b10165b02e89b4347300f855f273c4cb30c4a3209e6583275e"
checksum = "5b4be9c4c4b1f30b78d8a750e0822b6a6102d97e62061c583a6c1dea2dfb33ae"
dependencies = [
"clap",
]
[[package]]
name = "clap_derive"
version = "4.5.4"
version = "4.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64"
checksum = "2bac35c6dafb060fd4d275d9a4ffae97917c13a6327903a8be2153cd964f7085"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 2.0.64",
"syn 2.0.71",
]
[[package]]
name = "clap_lex"
version = "0.7.0"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce"
checksum = "4b82cf0babdbd58558212896d1a4272303a57bdb245c2bf1147185fb45640e70"
[[package]]
name = "cms"
@@ -409,9 +408,9 @@ dependencies = [
[[package]]
name = "crc32fast"
version = "1.4.0"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3855a8a784b474f333699ef2bbca9db2c4a1f6d9088a90a2d25b1eb53111eaa"
checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3"
dependencies = [
"cfg-if",
]
@@ -437,9 +436,9 @@ dependencies = [
[[package]]
name = "crossbeam-utils"
version = "0.8.19"
version = "0.8.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "248e3bacc7dc6baa3b21e405ee045c3047101a49145e7e9eca583ab4c2ca5345"
checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80"
[[package]]
name = "crypto-common"
@@ -511,13 +510,13 @@ dependencies = [
[[package]]
name = "der_derive"
version = "0.7.2"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fe87ce4529967e0ba1dcf8450bab64d97dfd5010a6256187ffe2e43e6f0e049"
checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.64",
"syn 2.0.71",
]
[[package]]
@@ -534,7 +533,7 @@ dependencies = [
[[package]]
name = "e2e"
version = "3.2.2"
version = "3.4.1"
dependencies = [
"anyhow",
"avbroot",
@@ -555,9 +554,9 @@ dependencies = [
[[package]]
name = "either"
version = "1.12.0"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3dca9240753cf90908d7e4aac30f630662b02aebaa1b58a3cadabdb23385b58b"
checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
[[package]]
name = "equivalent"
@@ -595,9 +594,9 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]]
name = "flagset"
version = "0.4.5"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdeb3aa5e95cf9aabc17f060cfa0ced7b83f042390760ca53bf09df9968acaa1"
checksum = "b3ea1ec5f8307826a5b71094dd91fc04d4ae75d5709b20ad351c7fb4815c86ec"
[[package]]
name = "flate2"
@@ -628,7 +627,7 @@ dependencies = [
[[package]]
name = "fuzz"
version = "3.2.2"
version = "3.4.1"
dependencies = [
"avbroot",
"honggfuzz",
@@ -710,9 +709,9 @@ dependencies = [
[[package]]
name = "honggfuzz"
version = "0.5.55"
version = "0.5.56"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "848e9c511092e0daa0a35a63e8e6e475a3e8f870741448b9f6028d69b142f18e"
checksum = "7c76b6234c13c9ea73946d1379d33186151148e0da231506b964b44f3d023505"
dependencies = [
"arbitrary",
"lazy_static",
@@ -800,11 +799,11 @@ dependencies = [
[[package]]
name = "lazy_static"
version = "1.4.0"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
dependencies = [
"spin 0.5.2",
"spin",
]
[[package]]
@@ -815,18 +814,18 @@ checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c"
[[package]]
name = "liblzma"
version = "0.3.1"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "717c314a016664dec8c5b42f72dce3b23bc42b0399b712604c816d4f528ec99a"
checksum = "243510a5543c358949902b9e76daec3a32d7b03a43abce823e7c62a1a8360172"
dependencies = [
"liblzma-sys",
]
[[package]]
name = "liblzma-sys"
version = "0.3.3"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2897528b23db157f02481ed7dd11d05421885fd5b5b4020c5ddb95bef6d47b4a"
checksum = "83cf78d20a45b5c0f3c7da2dcac255b230efe7d8684282bd35873164c1491187"
dependencies = [
"cc",
"libc",
@@ -847,18 +846,9 @@ checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89"
[[package]]
name = "log"
version = "0.4.21"
version = "0.4.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
[[package]]
name = "logos"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c000ca4d908ff18ac99b93a062cb8958d331c3220719c52e77cb19cc6ac5d2c1"
dependencies = [
"logos-derive 0.13.0",
]
checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
[[package]]
name = "logos"
@@ -866,21 +856,7 @@ version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "161971eb88a0da7ae0c333e1063467c5b5727e7fb6b710b8db4814eade3a42e8"
dependencies = [
"logos-derive 0.14.0",
]
[[package]]
name = "logos-codegen"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc487311295e0002e452025d6b580b77bb17286de87b57138f3b5db711cded68"
dependencies = [
"beef",
"fnv",
"proc-macro2",
"quote",
"regex-syntax 0.6.29",
"syn 2.0.64",
"logos-derive",
]
[[package]]
@@ -894,17 +870,8 @@ dependencies = [
"lazy_static",
"proc-macro2",
"quote",
"regex-syntax 0.8.3",
"syn 2.0.64",
]
[[package]]
name = "logos-derive"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbfc0d229f1f42d790440136d941afd806bc9e949e2bcb8faa813b0f00d1267e"
dependencies = [
"logos-codegen 0.13.0",
"regex-syntax",
"syn 2.0.71",
]
[[package]]
@@ -913,7 +880,7 @@ version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c2a69b3eb68d5bd595107c9ee58d7e07fe2bb5e360cc85b0f084dedac80de0a"
dependencies = [
"logos-codegen 0.14.0",
"logos-codegen",
]
[[package]]
@@ -933,15 +900,15 @@ checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
[[package]]
name = "memchr"
version = "2.7.2"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "memmap2"
version = "0.5.10"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83faa42c0a078c393f6b29d5db232d8be22776a891f8f56e5284faee4a20b327"
checksum = "fe751422e4a8caa417e13c3ea66452215d7d63e19e604f4980461212f3ae1322"
dependencies = [
"libc",
]
@@ -966,14 +933,14 @@ checksum = "dcf09caffaac8068c346b6df2a7fc27a177fd20b39421a39ce0a211bde679a6c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.64",
"syn 2.0.71",
]
[[package]]
name = "miniz_oxide"
version = "0.7.3"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87dfd01fe195c66b572b37921ad8803d010623c0aca821bea2302239d155cdae"
checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08"
dependencies = [
"adler",
]
@@ -1125,7 +1092,7 @@ dependencies = [
"phf_shared",
"proc-macro2",
"quote",
"syn 2.0.64",
"syn 2.0.71",
]
[[package]]
@@ -1200,14 +1167,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e"
dependencies = [
"proc-macro2",
"syn 2.0.64",
"syn 2.0.71",
]
[[package]]
name = "proc-macro2"
version = "1.0.82"
version = "1.0.86"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ad3d49ab951a01fbaafe34f2ec74122942fe18a3f9814c3268f1bb72042131b"
checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77"
dependencies = [
"unicode-ident",
]
@@ -1239,7 +1206,7 @@ dependencies = [
"prost",
"prost-types",
"regex",
"syn 2.0.64",
"syn 2.0.71",
"tempfile",
]
@@ -1253,7 +1220,7 @@ dependencies = [
"itertools",
"proc-macro2",
"quote",
"syn 2.0.64",
"syn 2.0.71",
]
[[package]]
@@ -1262,7 +1229,7 @@ version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f5eec97d5d34bdd17ad2db2219aabf46b054c6c41bd5529767c9ce55be5898f"
dependencies = [
"logos 0.14.0",
"logos",
"miette",
"once_cell",
"prost",
@@ -1280,9 +1247,9 @@ dependencies = [
[[package]]
name = "protox"
version = "0.6.0"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a29b3c5596eb23a849deba860b53ffd468199d9ad5fe4402a7d55379e16aa2d2"
checksum = "ac532509cee918d40f38c3e12f8ef9230f215f017d54de7dd975015538a42ce7"
dependencies = [
"bytes",
"miette",
@@ -1295,11 +1262,11 @@ dependencies = [
[[package]]
name = "protox-parse"
version = "0.6.0"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "033b939d76d358f7c32120c86c71f515bae45e64f2bde455200356557276276c"
checksum = "7f6c33f43516fe397e2f930779d720ca12cd057f7da4cd6326a0ef78d69dee96"
dependencies = [
"logos 0.13.0",
"logos",
"miette",
"prost-types",
"thiserror",
@@ -1366,38 +1333,32 @@ dependencies = [
[[package]]
name = "regex"
version = "1.10.4"
version = "1.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c"
checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax 0.8.3",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.6"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea"
checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax 0.8.3",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.6.29"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1"
[[package]]
name = "regex-syntax"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56"
checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b"
[[package]]
name = "ring"
@@ -1409,7 +1370,7 @@ dependencies = [
"cfg-if",
"getrandom",
"libc",
"spin 0.9.8",
"spin",
"untrusted",
"windows-sys 0.52.0",
]
@@ -1509,22 +1470,22 @@ checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b"
[[package]]
name = "serde"
version = "1.0.202"
version = "1.0.204"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "226b61a0d411b2ba5ff6d7f73a476ac4f8bb900373459cd00fab8512828ba395"
checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.202"
version = "1.0.204"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6048858004bcff69094cd972ed40a32500f153bd3be9f716b2eed2e8217c4838"
checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.64",
"syn 2.0.71",
]
[[package]]
@@ -1589,12 +1550,6 @@ version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]]
name = "spin"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
[[package]]
name = "spin"
version = "0.9.8"
@@ -1631,9 +1586,9 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.5.0"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
@@ -1648,9 +1603,9 @@ dependencies = [
[[package]]
name = "syn"
version = "2.0.64"
version = "2.0.71"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ad3dee41f36859875573074334c200d1add8e4a87bb37113ebd31d926b7b11f"
checksum = "b146dcf730474b4bcd16c311627b31ede9ab149045db4d6088b3becaea046462"
dependencies = [
"proc-macro2",
"quote",
@@ -1671,22 +1626,22 @@ dependencies = [
[[package]]
name = "thiserror"
version = "1.0.61"
version = "1.0.62"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709"
checksum = "f2675633b1499176c2dff06b0856a27976a8f9d436737b4cf4f312d4d91d8bbb"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.61"
version = "1.0.62"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533"
checksum = "d20468752b09f49e909e55a5d338caa8bedf615594e9d80bc4c565d30faf798c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.64",
"syn 2.0.71",
]
[[package]]
@@ -1717,7 +1672,7 @@ checksum = "8d9ef545650e79f30233c0003bcc2504d7efac6dad25fca40744de773fe2049c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.64",
"syn 2.0.71",
]
[[package]]
@@ -1731,9 +1686,9 @@ dependencies = [
[[package]]
name = "toml_edit"
version = "0.22.13"
version = "0.22.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c127785850e8c20836d49732ae6abfa47616e60bf9d9f57c43c250361a9db96c"
checksum = "d59a3a72298453f564e2b111fa896f8d07fabb36f51f06d7e875fc5e0b5a3ef1"
dependencies = [
"indexmap",
"serde",
@@ -1767,7 +1722,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.64",
"syn 2.0.71",
]
[[package]]
@@ -1829,9 +1784,9 @@ checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "unicode-width"
version = "0.1.12"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68f5e5f3158ecfd4b8ff6fe086db7c8467a2dfdac97fe420f2b7c4aa97af66d6"
checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d"
[[package]]
name = "untrusted"
@@ -1841,15 +1796,15 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "utf8parse"
version = "0.2.1"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "uuid"
version = "1.8.0"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a183cf7feeba97b4dd1c0d46788634f6221d87fa961b305bed08c851829efcc0"
checksum = "81dfa00651efa65069b0b6b651f4aaa31ba9e3c3ce0137aaad053604ee7e0314"
dependencies = [
"getrandom",
]
@@ -1909,7 +1864,7 @@ version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.5",
"windows-targets 0.52.6",
]
[[package]]
@@ -1929,18 +1884,18 @@ dependencies = [
[[package]]
name = "windows-targets"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm 0.52.5",
"windows_aarch64_msvc 0.52.5",
"windows_i686_gnu 0.52.5",
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm",
"windows_i686_msvc 0.52.5",
"windows_x86_64_gnu 0.52.5",
"windows_x86_64_gnullvm 0.52.5",
"windows_x86_64_msvc 0.52.5",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
[[package]]
@@ -1951,9 +1906,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
@@ -1963,9 +1918,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
@@ -1975,15 +1930,15 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_gnu"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
@@ -1993,9 +1948,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_i686_msvc"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
@@ -2005,9 +1960,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
@@ -2017,9 +1972,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
@@ -2029,15 +1984,15 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
version = "0.6.8"
version = "0.6.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3c52e9c97a68071b23e836c9380edae937f17b9c4667bd021973efc689f618d"
checksum = "59b5e5f6c299a3c7890b876a2a587f3115162487e704907d9b6cd29473052ba1"
dependencies = [
"memchr",
]
@@ -2068,7 +2023,7 @@ dependencies = [
[[package]]
name = "xtask"
version = "3.2.2"
version = "3.4.1"
dependencies = [
"anyhow",
"clap",
@@ -2078,9 +2033,9 @@ dependencies = [
[[package]]
name = "zeroize"
version = "1.7.0"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d"
checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde"
dependencies = [
"zeroize_derive",
]
@@ -2093,7 +2048,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.64",
"syn 2.0.71",
]
[[package]]
+1 -1
View File
@@ -4,7 +4,7 @@ members = ["avbroot", "e2e", "fuzz", "xtask"]
resolver = "2"
[workspace.package]
version = "3.2.2"
version = "3.4.1"
license = "GPL-3.0-only"
edition = "2021"
repository = "https://github.com/chenxiaolong/avbroot"
+10
View File
@@ -252,3 +252,13 @@ avbroot hash-tree verify -i <input data file> -H <input hash tree file>
```
This will check if the input file has any corrupted blocks. Currently, the command cannot report which specific blocks are corrupted, only whether the file is valid.
## `avbroot payload`
### Showing payload header information
```bash
avbroot payload info -i <payload>
```
This subcommand shows all of the payload header fields (which will likely be extremely long).
+53 -27
View File
@@ -35,7 +35,11 @@ avbroot applies the following patches to the partition images:
Repeat: **_ALWAYS leave `OEM unlocking` enabled if rooted._**
* Any operation that causes an improperly-signed boot image to be flashed will result in the device being unbootable and unrecoverable without unlocking the bootloader again (and thus, triggering a data wipe). This includes the `Direct install` method for updating Magisk. Magisk updates **must** be done by repatching the OTA, not via the app.
* Any operation that causes an improperly-signed boot image to be flashed will result in the device being unbootable and unrecoverable without unlocking the bootloader again (and thus, triggering a data wipe). A couple ways an improperly-signed boot image could be flashed include:
* The `Direct install` method for updating Magisk. Magisk updates **must** be done by repatching the OTA, not via the app.
* The `Uninstall Magisk` feature in Magisk. If root access is no longer needed, Magisk **must** be removed by repatching the OTA with the `--rootless` option, not via the app.
If the boot image is ever modified, **do not reboot**. [Open an issue](https://github.com/chenxiaolong/avbroot/issues/new) for support and be very clear about what steps were done that lead to the situation. If Android is still running and root access works, it might be possible to recover without wiping and starting over.
@@ -126,21 +130,27 @@ When patching OTAs for multiple devices, generating unique keys for each device
avbroot key generate-cert -k ota.key -o ota.crt
```
The commands above are provided for convenience. avbroot is compatible with any standard PKCS8-encoded 4096-bit RSA private key and PEM-encoded X509 certificate, like those generated by openssl.
The commands above are provided for convenience. avbroot is compatible with any standard PKCS#8-encoded 4096-bit RSA private key and PEM-encoded X509 certificate, like those generated by openssl.
If you lose your AVB or OTA signing key, you will no longer be able to sign new OTA zips. You will have to generate new signing keys and unlock your bootloader again (triggering a data wipe). Follow the [Usage section](#usage) as if doing an initial setup.
## Initial setup
1. Reboot into fastboot mode and unlock the bootloader if it isn't already unlocked. This will trigger a data wipe.
1. Make sure that the version of fastboot is 34 or newer. Older versions have bugs that prevent the `fastboot flashall` command (required later) from working properly.
```bash
fastboot --version
```
2. Reboot into fastboot mode and unlock the bootloader if it isn't already unlocked. This will trigger a data wipe.
```bash
fastboot flashing unlock
```
2. When setting things up for the first time, the device must already be running the correct OS. Flash the original unpatched OTA if needed.
3. When setting things up for the first time, the device must already be running the correct OS. Flash the original unpatched OTA if needed.
3. Extract the partition images from the patched OTA that are different from the original.
4. Extract the partition images from the patched OTA that are different from the original.
```bash
avbroot ota extract \
@@ -151,7 +161,7 @@ If you lose your AVB or OTA signing key, you will no longer be able to sign new
If you prefer to extract and flash all OS partitions just to be safe, pass in `--all`.
4. Flash the partition images that were extracted.
5. Flash the partition images that were extracted.
```bash
ANDROID_PRODUCT_OUT=extracted fastboot flashall --skip-reboot
@@ -161,7 +171,7 @@ If you lose your AVB or OTA signing key, you will no longer be able to sign new
Alternatively, for Pixel devices, running `flash-base.sh` from the factory image will also update the bootloader and modem.
5. Set up the custom AVB public key in the bootloader after rebooting from fastbootd to bootloader.
6. Set up the custom AVB public key in the bootloader after rebooting from fastbootd to bootloader.
```bash
fastboot reboot-bootloader
@@ -169,7 +179,7 @@ If you lose your AVB or OTA signing key, you will no longer be able to sign new
fastboot flash avb_custom_key /path/to/avb_pkmd.bin
```
6. **[Optional]** Before locking the bootloader, reboot into Android once to confirm that everything is properly signed.
7. **[Optional]** Before locking the bootloader, reboot into Android once to confirm that everything is properly signed.
Install the Magisk or KernelSU app and run the following command:
@@ -183,7 +193,7 @@ If you lose your AVB or OTA signing key, you will no longer be able to sign new
init: [libfs_avb]Returning avb_handle with status: Success
```
7. Reboot back into fastboot and lock the bootloader. This will trigger a data wipe again.
8. Reboot back into fastboot and lock the bootloader. This will trigger a data wipe again.
```bash
fastboot flashing lock
@@ -195,7 +205,7 @@ If you lose your AVB or OTA signing key, you will no longer be able to sign new
**WARNING**: If you are flashing CalyxOS, the setup wizard will [automatically turn off the `OEM unlocking` switch](https://github.com/CalyxOS/platform_packages_apps_SetupWizard/blob/7d2df25cedcbff83ddb608e628f9d97b38259c26/src/org/lineageos/setupwizard/SetupWizardApp.java#L135-L140). Make sure to manually reenable it again from Android's developer settings. Consider using the [`OEMUnlockOnBoot` module](https://github.com/chenxiaolong/OEMUnlockOnBoot) to automatically ensure OEM unlocking is enabled on every boot.
8. That's it! To install future OS, Magisk, or KernelSU updates, see the [next section](#updates).
9. That's it! To install future OS, Magisk, or KernelSU updates, see the [next section](#updates).
## Updates
@@ -426,6 +436,28 @@ avbroot ota extract \
--all
```
### Signing with an external program
avbroot supports delegating all RSA signing operations to an external program with the `--signing-helper` option. When using this option, the `--key-avb` and `--key-ota` options must be given a public key instead of a private key.
For each signing operation, avbroot will invoke the program with:
```bash
<helper> <algorithm> <public key>
```
The algorithm is one of `SHA{256,512}_RSA{2048,4096}` and the public key is what was passed to avbroot. The program can use the public key to find the corresponding private key (eg. on a hardware security module). avbroot will write a PKCS#1 v1.5 padded digest to `stdin` and the helper program is expected to perform a raw RSA signing operation and write the raw signature (octet string matching key size) to `stdout`.
By default, this behavior is compatible with the `--signing_helper` option in AOSP's avbtool. However, avbroot additionally extends the arguments to support non-interactive use. If `--pass-{avb,ota}-file` or `--pass-{avb,ota}-env-var` are used, then the helper program will be invoked with two additional arguments that point to the password file or environment variable.
```bash
<helper> <algorithm> <public key> file <pass file>
# or
<helper> <algorithm> <public key> env <env file>
```
Note that avbroot will verify the signature returned by helper program against the public key. This ensures that the patching process will fail appropriately if the wrong private key was used.
## Building from source
Make sure the [Rust toolchain](https://www.rust-lang.org/) is installed. Then run:
@@ -440,25 +472,19 @@ Debug builds work too, but they will run significantly slower (in the sha256 com
By default, the executable links to the system's bzip2 and liblzma libraries, which are the only external libraries avbroot depends on. To compile and statically link these two libraries, pass in `--features static`.
### Android cross-compilation
To cross-compile for Android, install [cargo-android](https://github.com/chenxiaolong/cargo-android) and use the `cargo android` wrapper. To make a release build for aarch64, run:
```bash
cargo android build --release --target aarch64-linux-android
```
It is possible to run the tests if the host is running Linux, qemu-user-static is installed, and the executable is built with `RUSTFLAGS=-C target-feature=+crt-static` and `--features static`.
## Verifying digital signatures
First, save the public key to a file listing the keys to be trusted. This is the same key listed in [the author's profile](https://github.com/chenxiaolong/).
```bash
echo 'avbroot ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDOe6/tBnO7xZhAWXRj3ApUYgn+XZ0wnQiXM8B7tPgv4' > avbroot_trusted_keys
```
Then, verify the signature of the zip file using the list of trusted keys.
```bash
ssh-keygen -Y verify -f avbroot_trusted_keys -I avbroot -n file -s <file>.zip.sig < <file>.zip
```
If the file is successfully verified, the output will be:
```
Good "file" signature for avbroot with ED25519 key SHA256:Ct0HoRyrFLrnF9W+A/BKEiJmwx7yWkgaW/JvghKrboA
```
To verify the digital signatures of the downloads, follow [the steps here](https://github.com/chenxiaolong/chenxiaolong/blob/master/VERIFY_SSH_SIGNATURES.md).
## Contributing
+19 -9
View File
@@ -33,7 +33,11 @@ avbroot модифицирует следующие образы:
Повторюсь: **_ВСЕГДА оставляйте `Заводскую разблокировку` включенной при наличии root-прав._**
* Любая операция, приводящая к прошивке некорректно подписанного загрузочного образа, приведет к тому, что устройство больше не сможет загрузиться в систему/режим Recovery, а для его восстановления потребуется повторная разблокировка загрузчика (и, следовательно, стирание всех пользовательских данных). Это же относится и к методу `Прямой установки` для обновления Magisk. Обновление Magisk **должно выполняться только путем обновления OTA,** а не через Magisk Manager.
* Любая операция, приводящая к прошивке некорректно подписанного загрузочного образа, приведет к тому, что устройство больше не сможет загрузиться в систему/режим Recovery, а для его восстановления потребуется повторная разблокировка загрузчика (и, следовательно, стирание всех пользовательских данных). К подобным операциям в том числе относятся:
* Метод `Прямой установки` для обновления Magisk. Magisk можно обновлять **только путем репатчинга OTA,** но не через его приложение.
* Функция `Удаление Magisk` в приложении Magisk. Если вам больше не нужен root-доступ, Magisk **должен быть удален путем репатчинга OTA** с использованием параметра `--rootless`, но не через его приложение.
Если в загрузочный раздел были внесены какие-либо изменения, **не перезагружайтесь**. Обратитесь за помощью, [открыв Issue,](https://github.com/chenxiaolong/avbroot/issues/new) и четко разъясните, какие конкретные действия привели к возникновению такой ситуации. Если Android всё еще работает и доступ к root-правам сохранился – вероятно, получится откатить изменения до исходного состояния, не стирая ваши данные.
@@ -130,15 +134,21 @@ avbroot совместим с любым стандартным 4096-битны
## Первоначальная настройка
1. Перезагрузитесь в режим fastboot и разблокируйте загрузчик, если не сделали этого ранее. Это приведет к стиранию всех пользовательских данных.
1. Убедитесь, что вы используете утилиту fastboot версии 34 или новее. Предыдущие версии содержат баги, что не позволяют команде `fastboot flashall` (которая понадобится по ходу инструкции) работать правильно.
```bash
fastboot --version
```
2. Перезагрузитесь в режим fastboot и разблокируйте загрузчик, если не сделали этого ранее. Это приведет к стиранию всех пользовательских данных.
```bash
fastboot flashing unlock
```
2. Перед первой установкой, на устройстве уже должна быть установлена в оригинальном виде та прошивка, пропатченную версию которой вы собираетесь ставить. Если это не так, сначала установите оригинальную непропатченную OTA.
3. Перед первой установкой, на устройстве уже должна быть установлена в оригинальном виде та прошивка, пропатченную версию которой вы собираетесь ставить. Если это не так, сначала установите оригинальную непропатченную OTA.
3. Извлекаем из пропатченного OTA модифицированные образы:
4. Извлекаем из пропатченного OTA модифицированные образы:
```bash
avbroot ota extract \
@@ -149,7 +159,7 @@ avbroot совместим с любым стандартным 4096-битны
Если вы на всякий случай хотите прошить вообще все разделы из ОТА, извлечь их можно, указав аргумент `--all`.
4. Прошейте извлеченные образы разделов.
5. Прошейте извлеченные образы разделов.
```bash
ANDROID_PRODUCT_OUT=extracted fastboot flashall --skip-reboot
@@ -159,7 +169,7 @@ avbroot совместим с любым стандартным 4096-битны
Для устройств Pixel есть ещё один вариант: запуск скрипта `flash-base.sh` из папки заводских образов (factory images) обновит загрузчик и модем.
5. После перезагрузки из fastbootd в загрузчик (bootloader), установите пользовательский публичный ключ AVB в загрузчик:
6. После перезагрузки из fastbootd в загрузчик (bootloader), установите пользовательский публичный ключ AVB в загрузчик:
```bash
fastboot reboot-bootloader
@@ -167,7 +177,7 @@ avbroot совместим с любым стандартным 4096-битны
fastboot flash avb_custom_key /путь/к/avb_pkmd.bin
```
6. **[Опционально]** Перед блокировкой загрузчика загрузитесь в систему, дабы убедиться, что все подписано правильно.
7. **[Опционально]** Перед блокировкой загрузчика загрузитесь в систему, дабы убедиться, что все подписано правильно.
Установите приложение Magisk или KernelSU и выполните следующую команду:
@@ -181,7 +191,7 @@ avbroot совместим с любым стандартным 4096-битны
init: [libfs_avb]Returning avb_handle with status: Success
```
7. Перезагрузитесь в fastboot и заблокируйте загрузчик. Это снова приведет к стиранию данных.
8. Перезагрузитесь в fastboot и заблокируйте загрузчик. Это снова приведет к стиранию данных.
```bash
fastboot flashing lock
@@ -193,7 +203,7 @@ avbroot совместим с любым стандартным 4096-битны
**ПРЕДУПРЕЖДЕНИЕ**: Если вы прошили CalyxOS, мастер настройки [автоматически отключит опцию `Заводской разблокировки`.](https://github.com/CalyxOS/platform_packages_apps_SetupWizard/blob/7d2df25cedcbff83ddb608e628f9d97b38259c26/src/org/lineageos/setupwizard/SetupWizardApp.java#L135-L140) Не забудьте снова включить её вручную в настройках для разработчиков. Для перестраховки можете использовать [модуль `OEMUnlockOnBoot`,](https://github.com/chenxiaolong/OEMUnlockOnBoot) который автоматически включает пункт Заводской разблокировки при каждом запуске системы.
8. Готово. Установка последующих обновлений системы, Magisk или KernelSU, описывается в [следующем разделе.](#обновления)
9. Готово! Установка последующих обновлений системы, Magisk или KernelSU, описывается в [следующем разделе.](#обновления)
## Обновления
+4 -2
View File
@@ -1,5 +1,5 @@
/*
* SPDX-FileCopyrightText: 2023 Andrew Gunnerson
* SPDX-FileCopyrightText: 2023-2024 Andrew Gunnerson
* SPDX-License-Identifier: GPL-3.0-only
*/
@@ -15,7 +15,7 @@ use clap::{Parser, Subcommand, ValueEnum};
use tracing::{debug, Level};
use tracing_subscriber::fmt::{format::Writer, time::FormatTime};
use crate::cli::{avb, boot, completion, cpio, fec, hashtree, key, ota};
use crate::cli::{avb, boot, completion, cpio, fec, hashtree, key, ota, payload};
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Subcommand)]
@@ -28,6 +28,7 @@ pub enum Command {
HashTree(hashtree::HashTreeCli),
Key(key::KeyCli),
Ota(ota::OtaCli),
Payload(payload::PayloadCli),
/// (Deprecated: Use `avbroot ota patch` instead.)
Patch(ota::PatchCli),
/// (Deprecated: Use `avbroot ota extract` instead.)
@@ -163,6 +164,7 @@ pub fn main(logging_initialized: &AtomicBool, cancel_signal: &AtomicBool) -> Res
Command::HashTree(c) => hashtree::hash_tree_main(&c, cancel_signal),
Command::Key(c) => key::key_main(&c),
Command::Ota(c) => ota::ota_main(&c, cancel_signal),
Command::Payload(c) => payload::payload_main(&c),
// Deprecated aliases.
Command::Patch(c) => ota::patch_subcommand(&c, cancel_signal),
Command::Extract(c) => ota::extract_subcommand(&c, cancel_signal),
+34 -8
View File
@@ -25,7 +25,7 @@ use serde::{Deserialize, Serialize};
use tracing::{debug_span, info, warn, Span};
use crate::{
crypto::{self, PassphraseSource},
crypto::{self, PassphraseSource, RsaSigningKey},
format::avb::{
self, AlgorithmType, AppendedDescriptorMut, AppendedDescriptorRef, Descriptor, Footer,
HashTreeDescriptor, Header, KernelCmdlineDescriptor,
@@ -383,12 +383,26 @@ fn sign_or_clear(info: &mut AvbInfo, orig_header: &Header, key_group: &KeyGroup)
key_group.pass_file.as_deref(),
key_group.pass_env_var.as_deref(),
);
let private_key = crypto::read_pem_key_file(key_path, &source)
.with_context(|| format!("Failed to load key: {key_path:?}"))?;
let signing_key = if let Some(helper) = &key_group.signing_helper {
let public_key = crypto::read_pem_public_key_file(key_path)
.with_context(|| format!("Failed to load key: {key_path:?}"))?;
info.header.set_algo_for_key(&private_key)?;
RsaSigningKey::External {
program: helper.clone(),
public_key_file: key_path.clone(),
public_key,
passphrase_source: source,
}
} else {
let private_key = crypto::read_pem_key_file(key_path, &source)
.with_context(|| format!("Failed to load key: {key_path:?}"))?;
RsaSigningKey::Internal(private_key)
};
info.header.set_algo_for_key(&signing_key)?;
info.header
.sign(&private_key)
.sign(&signing_key)
.context("Failed to sign new AVB header")?;
}
SignAction::Clear => {
@@ -743,12 +757,15 @@ struct DisplayGroup {
#[derive(Debug, Args)]
struct KeyGroup {
/// Path to private key for signing.
/// Path to signing key.
///
/// A private key is needed if packing an image where the original header
/// A signing key is needed if packing an image where the original header
/// was signed and the header needs to be modified (eg. for a new checksum).
/// If the header was originally not signed, then the private key is not
/// If the header was originally not signed, then the signing key is not
/// used, unless --force is specified.
///
/// This should normally be a private key. However, if --signing-helper is
/// used, then it should be a public key instead.
#[arg(short, long, value_name = "FILE", value_parser)]
key: Option<PathBuf>,
@@ -768,6 +785,15 @@ struct KeyGroup {
/// File containing private key passphrase.
#[arg(long, value_name = "FILE", value_parser, group = "pass")]
pass_file: Option<PathBuf>,
/// External program for signing.
///
/// If this option is specified, then --key must refer to a public key. The
/// program will be invoked as:
///
/// <program> <algo> <public key> [file <pass file>|env <pass env>]
#[arg(long, value_name = "PROGRAM", value_parser)]
signing_helper: Option<PathBuf>,
}
/// Unpack an AVB image.
+7
View File
@@ -55,6 +55,9 @@ pub fn key_main(cli: &KeyCli) -> Result<()> {
.with_context(|| format!("Failed to load key: {p:?}"))?;
private_key.to_public_key()
} else if let Some(p) = &c.input.public_key {
crypto::read_pem_public_key_file(p)
.with_context(|| format!("Failed to load public key: {p:?}"))?
} else if let Some(p) = &c.input.cert {
let certificate = crypto::read_pem_cert_file(p)
.with_context(|| format!("Failed to load certificate: {p:?}"))?;
@@ -93,6 +96,10 @@ struct PublicKeyInputGroup {
#[arg(short, long, value_name = "FILE", value_parser)]
key: Option<PathBuf>,
/// Path to public key.
#[arg(short, long, value_name = "FILE", value_parser, conflicts_with_all = ["pass_env_var", "pass_file"])]
public_key: Option<PathBuf>,
/// Path to certificate.
#[arg(short, long, value_name = "FILE", value_parser, conflicts_with_all = ["pass_env_var", "pass_file"])]
cert: Option<PathBuf>,
+2 -1
View File
@@ -1,5 +1,5 @@
/*
* SPDX-FileCopyrightText: 2023 Andrew Gunnerson
* SPDX-FileCopyrightText: 2023-2024 Andrew Gunnerson
* SPDX-License-Identifier: GPL-3.0-only
*/
@@ -12,3 +12,4 @@ pub mod fec;
pub mod hashtree;
pub mod key;
pub mod ota;
pub mod payload;
+88 -18
View File
@@ -21,7 +21,6 @@ use cap_std::{ambient_authority, fs::Dir};
use cap_tempfile::TempDir;
use clap::{value_parser, ArgAction, Args, Parser, Subcommand};
use rayon::{iter::IntoParallelRefIterator, prelude::ParallelIterator};
use rsa::RsaPrivateKey;
use tempfile::NamedTempFile;
use topological_sort::TopologicalSort;
use tracing::{debug_span, info, warn};
@@ -30,7 +29,7 @@ use zip::{write::FileOptions, CompressionMethod, ZipArchive, ZipWriter};
use crate::{
cli,
crypto::{self, PassphraseSource},
crypto::{self, PassphraseSource, RsaSigningKey},
format::{
avb::{self, Descriptor, Header},
ota::{self, SigningWriter, ZipEntry},
@@ -197,7 +196,7 @@ fn patch_boot_images<'a, 'b: 'a>(
required_images: &'b RequiredImages,
input_files: &mut HashMap<String, InputFile>,
boot_patchers: Vec<Box<dyn BootImagePatch + Sync>>,
key_avb: &RsaPrivateKey,
key_avb: &RsaSigningKey,
cancel_signal: &AtomicBool,
) -> Result<()> {
let input_files = Mutex::new(input_files);
@@ -241,7 +240,7 @@ fn patch_system_image<'a, 'b: 'a>(
required_images: &'b RequiredImages,
input_files: &mut HashMap<String, InputFile>,
cert_ota: &Certificate,
key_avb: &RsaPrivateKey,
key_avb: &RsaSigningKey,
cancel_signal: &AtomicBool,
) -> Result<(&'b str, Vec<Range<u64>>)> {
let Some(target) = required_images.iter_system().next() else {
@@ -565,7 +564,7 @@ fn update_vbmeta_headers(
headers: &mut HashMap<String, Header>,
order: &mut [(String, HashSet<String>)],
clear_vbmeta_flags: bool,
key: &RsaPrivateKey,
key: &RsaSigningKey,
block_size: u64,
) -> Result<()> {
for (name, deps) in order {
@@ -674,12 +673,40 @@ fn compress_image(
info!("Compressing full image: {name}");
// Otherwise, compress the entire image.
let (partition_info, operations) =
payload::compress_image(&*file, &writer, name, block_size, cancel_signal)?;
// Otherwise, compress the entire image. If VABC is enabled, we need to
// update the CoW size estimate or else the CoW block device may run out of
// space during flashing.
let need_cow = partition.estimate_cow_size.is_some();
if need_cow {
info!("Needs updated CoW size estimate: {name}");
// Only CoW v2 + lz4 seems to exist in the wild currently, so that is
// all we support.
let Some(dpm) = &header.manifest.dynamic_partition_metadata else {
bail!("Dynamic partition metadata is missing");
};
if !dpm.vabc_enabled() {
bail!("Partition has CoW estimate, but VABC is disabled: {name}");
}
let cow_version = dpm.cow_version();
if dpm.cow_version() != 2 {
bail!("Unsupported CoW version: {cow_version}");
}
let compression = dpm.vabc_compression_param();
if compression != "lz4" {
bail!("Unsupported VABC compression: {compression}");
}
}
let (partition_info, operations, cow_estimate) =
payload::compress_image(&*file, &writer, name, block_size, need_cow, cancel_signal)?;
partition.new_partition_info = Some(partition_info);
partition.operations = operations;
partition.estimate_cow_size = cow_estimate;
*file = writer;
@@ -694,8 +721,8 @@ fn patch_ota_payload(
external_images: &HashMap<String, PathBuf>,
boot_patchers: Vec<Box<dyn BootImagePatch + Sync>>,
clear_vbmeta_flags: bool,
key_avb: &RsaPrivateKey,
key_ota: &RsaPrivateKey,
key_avb: &RsaSigningKey,
key_ota: &RsaSigningKey,
cert_ota: &Certificate,
cancel_signal: &AtomicBool,
) -> Result<(String, u64)> {
@@ -888,8 +915,8 @@ fn patch_ota_zip(
external_images: &HashMap<String, PathBuf>,
mut boot_patchers: Vec<Box<dyn BootImagePatch + Sync>>,
clear_vbmeta_flags: bool,
key_avb: &RsaPrivateKey,
key_ota: &RsaPrivateKey,
key_avb: &RsaSigningKey,
key_ota: &RsaSigningKey,
cert_ota: &Certificate,
cancel_signal: &AtomicBool,
) -> Result<(OtaMetadata, u64)> {
@@ -1190,10 +1217,38 @@ pub fn patch_subcommand(cli: &PatchCli, cancel_signal: &AtomicBool) -> Result<()
cli.pass_ota_env_var.as_deref(),
);
let key_avb = crypto::read_pem_key_file(&cli.key_avb, &source_avb)
.with_context(|| format!("Failed to load key: {:?}", cli.key_avb))?;
let key_ota = crypto::read_pem_key_file(&cli.key_ota, &source_ota)
.with_context(|| format!("Failed to load key: {:?}", cli.key_ota))?;
let (key_avb, key_ota) = if let Some(helper) = &cli.signing_helper {
let public_key_avb = crypto::read_pem_public_key_file(&cli.key_avb)
.with_context(|| format!("Failed to load key: {:?}", cli.key_avb))?;
let public_key_ota = crypto::read_pem_public_key_file(&cli.key_ota)
.with_context(|| format!("Failed to load key: {:?}", cli.key_ota))?;
let key_avb = RsaSigningKey::External {
program: helper.clone(),
public_key_file: cli.key_avb.clone(),
public_key: public_key_avb,
passphrase_source: source_avb,
};
let key_ota = RsaSigningKey::External {
program: helper.clone(),
public_key_file: cli.key_ota.clone(),
public_key: public_key_ota,
passphrase_source: source_ota,
};
(key_avb, key_ota)
} else {
let private_key_avb = crypto::read_pem_key_file(&cli.key_avb, &source_avb)
.with_context(|| format!("Failed to load key: {:?}", cli.key_avb))?;
let private_key_ota = crypto::read_pem_key_file(&cli.key_ota, &source_ota)
.with_context(|| format!("Failed to load key: {:?}", cli.key_ota))?;
let key_avb = RsaSigningKey::Internal(private_key_avb);
let key_ota = RsaSigningKey::Internal(private_key_ota);
(key_avb, key_ota)
};
let cert_ota = crypto::read_pem_cert_file(&cli.cert_ota)
.with_context(|| format!("Failed to load certificate: {:?}", cli.cert_ota))?;
@@ -1720,7 +1775,10 @@ pub struct PatchCli {
#[arg(short, long, value_name = "FILE", value_parser, help_heading = HEADING_PATH)]
pub output: Option<PathBuf>,
/// Private key for signing vbmeta images.
/// Signing key for vbmeta headers.
///
/// This should normally be a private key. However, if --signing-helper is
/// used, then it should be a public key instead.
#[arg(
long,
alias = "privkey-avb",
@@ -1730,7 +1788,10 @@ pub struct PatchCli {
)]
pub key_avb: PathBuf,
/// Private key for signing the OTA.
/// Signing key for the OTA.
///
/// This should normally be a private key. However, if --signing-helper is
/// used, then it should be a public key instead.
#[arg(
long,
alias = "privkey-ota",
@@ -1788,6 +1849,15 @@ pub struct PatchCli {
)]
pub pass_ota_file: Option<PathBuf>,
/// External program for signing.
///
/// If this option is specified, then --key-avb and --key-ota must refer to
/// public keys. The program will be invoked as:
///
/// <program> <algo> <public key> [file <pass file>|env <pass env>]
#[arg(long, value_name = "PROGRAM", value_parser, help_heading = HEADING_KEY)]
pub signing_helper: Option<PathBuf>,
/// Use partition image from a file instead of the original payload.
#[arg(
long,
+49
View File
@@ -0,0 +1,49 @@
/*
* SPDX-FileCopyrightText: 2024 Andrew Gunnerson
* SPDX-License-Identifier: GPL-3.0-only
*/
use std::{fs::File, io::BufReader, path::PathBuf};
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use crate::{format::payload::PayloadHeader, stream::FromReader};
fn info_subcommand(cli: &InfoCli) -> Result<()> {
let mut reader = File::open(&cli.input)
.map(BufReader::new)
.with_context(|| format!("Failed to open payload: {:?}", cli.input))?;
let header = PayloadHeader::from_reader(&mut reader)
.with_context(|| format!("Failed to read payload: {:?}", cli.input))?;
println!("{header:#?}");
Ok(())
}
pub fn payload_main(cli: &PayloadCli) -> Result<()> {
match &cli.command {
PayloadCommand::Info(c) => info_subcommand(c),
}
}
/// Display payload information.
#[derive(Debug, Parser)]
struct InfoCli {
/// Path to input payload file.
#[arg(short, long, value_name = "FILE", value_parser)]
input: PathBuf,
}
#[derive(Debug, Subcommand)]
enum PayloadCommand {
Info(InfoCli),
}
/// Inspect OTA payloads.
#[derive(Debug, Parser)]
pub struct PayloadCli {
#[command(subcommand)]
command: PayloadCommand,
}
+252 -9
View File
@@ -1,5 +1,5 @@
/*
* SPDX-FileCopyrightText: 2023 Andrew Gunnerson
* SPDX-FileCopyrightText: 2023-2024 Andrew Gunnerson
* SPDX-License-Identifier: GPL-3.0-only
*/
@@ -9,6 +9,7 @@ use std::{
fs::{self, File, OpenOptions},
io::{self, BufReader, BufWriter, Read, Write},
path::{Path, PathBuf},
process::{Command, ExitStatus, Stdio},
time::Duration,
};
@@ -22,12 +23,16 @@ use cms::{
};
use pkcs8::{
pkcs5::{pbes2, scrypt},
DecodePrivateKey, EncodePrivateKey, EncodePublicKey, EncryptedPrivateKeyInfo, LineEnding,
PrivateKeyInfo,
DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey, EncryptedPrivateKeyInfo,
LineEnding, PrivateKeyInfo,
};
use rand::RngCore;
use rsa::{pkcs1v15::SigningKey, Pkcs1v15Sign, RsaPrivateKey, RsaPublicKey};
use sha2::Sha256;
use rsa::{
pkcs1v15::SigningKey, traits::PublicKeyParts, Pkcs1v15Sign, RsaPrivateKey, RsaPublicKey,
};
use serde::{Deserialize, Serialize};
use sha1::Sha1;
use sha2::{Digest, Sha256, Sha512};
use thiserror::Error;
use x509_cert::{
builder::{Builder, CertificateBuilder, Profile},
@@ -40,6 +45,20 @@ use x509_cert::{
#[derive(Debug, Error)]
pub enum Error {
#[error("Signature algorithm not supported: {0:?}")]
UnsupportedAlgorithm(SignatureAlgorithm),
#[error("RSA key size ({}) not supported", .0 * 8)]
UnsupportedKey(usize),
#[error("Invalid digest length ({0} bytes) for {1:?}")]
InvalidDigestLength(usize, SignatureAlgorithm),
#[error("Invalid signature length ({0} bytes) for {1:?}")]
InvalidSignatureLength(usize, SignatureAlgorithm),
#[error("Failed to run command: {0}")]
CommandSpawnFailed(String, #[source] io::Error),
#[error("Command failed with status: {1}: {0}")]
CommandExecutionFailed(String, ExitStatus),
#[error("Signature from signing helper does not match public key: {0:?}")]
SigningHelperBadSignature(PathBuf),
#[error("Passphrases do not match")]
ConfirmPassphrase,
#[error("Failed to read environment variable: {0:?}")]
@@ -54,6 +73,10 @@ pub enum Error {
SaveKeyEncrypted(#[source] pkcs8::Error),
#[error("Failed to save unencrypted private key")]
SaveKeyUnencrypted(#[source] pkcs8::Error),
#[error("Failed to RSA sign digest")]
RsaSign(#[source] rsa::Error),
#[error("Failed to RSA verify signature")]
RsaVerify(#[source] rsa::Error),
#[error("X509 error")]
X509(#[from] x509_cert::builder::Error),
#[error("SPKI error")]
@@ -68,6 +91,34 @@ pub enum Error {
type Result<T> = std::result::Result<T, Error>;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub enum SignatureAlgorithm {
Sha1WithRsa,
Sha256WithRsa,
Sha512WithRsa,
}
impl SignatureAlgorithm {
/// Length of digest required by the signing algorithm.
pub fn digest_len(self) -> usize {
match self {
Self::Sha1WithRsa => Sha1::output_size(),
Self::Sha256WithRsa => Sha256::output_size(),
Self::Sha512WithRsa => Sha512::output_size(),
}
}
/// Compute the digest of the specified data.
pub fn hash(self, data: &[u8]) -> Vec<u8> {
match self {
Self::Sha1WithRsa => Sha1::digest(data).to_vec(),
Self::Sha256WithRsa => Sha256::digest(data).to_vec(),
Self::Sha512WithRsa => Sha512::digest(data).to_vec(),
}
}
}
#[derive(Clone)]
pub enum PassphraseSource {
Prompt(String),
EnvVar(OsString),
@@ -110,6 +161,181 @@ impl PassphraseSource {
}
}
fn check_key_size(size: usize) -> Result<()> {
// RustCrypto does not support 8192-bit keys.
if size > 4096 / 8 {
return Err(Error::UnsupportedKey(size));
}
Ok(())
}
/// Copied from rsa-0.9.6 since the function is not exported.
fn pkcs1v15_sign_pad(prefix: &[u8], hashed: &[u8], k: usize) -> rsa::Result<Vec<u8>> {
let hash_len = hashed.len();
let t_len = prefix.len() + hashed.len();
if k < t_len + 11 {
return Err(rsa::Error::MessageTooLong);
}
// EM = 0x00 || 0x01 || PS || 0x00 || T
let mut em = vec![0xff; k];
em[0] = 0;
em[1] = 1;
em[k - t_len - 1] = 0;
em[k - t_len..k - hash_len].copy_from_slice(prefix);
em[k - hash_len..k].copy_from_slice(hashed);
Ok(em)
}
#[derive(Clone)]
pub enum RsaSigningKey {
Internal(RsaPrivateKey),
External {
program: PathBuf,
public_key_file: PathBuf,
public_key: RsaPublicKey,
passphrase_source: PassphraseSource,
},
}
impl RsaSigningKey {
/// Size of key in bytes.
pub fn size(&self) -> usize {
match self {
Self::Internal(key) => key.size(),
Self::External { public_key, .. } => public_key.size(),
}
}
/// Get the public key portion of the signing key.
pub fn to_public_key(&self) -> RsaPublicKey {
match self {
RsaSigningKey::Internal(key) => key.to_public_key(),
RsaSigningKey::External { public_key, .. } => public_key.clone(),
}
}
/// Sign the digest with the specified signature algorithm.
pub fn sign(&self, algo: SignatureAlgorithm, digest: &[u8]) -> Result<Vec<u8>> {
if digest.len() != algo.digest_len() {
return Err(Error::InvalidDigestLength(digest.len(), algo));
}
check_key_size(self.size())?;
let scheme = match algo {
// We don't support signing with insecure algorithms.
SignatureAlgorithm::Sha1WithRsa => return Err(Error::UnsupportedAlgorithm(algo)),
SignatureAlgorithm::Sha256WithRsa => Pkcs1v15Sign::new::<Sha256>(),
SignatureAlgorithm::Sha512WithRsa => Pkcs1v15Sign::new::<Sha512>(),
};
match self {
Self::Internal(key) => key.sign(scheme, digest).map_err(Error::RsaSign),
Self::External {
program,
public_key,
public_key_file,
passphrase_source,
} => {
let key_bits = public_key.size() * 8;
let algo_str = match algo {
SignatureAlgorithm::Sha1WithRsa => unreachable!(),
SignatureAlgorithm::Sha256WithRsa => format!("SHA256_RSA{key_bits}"),
SignatureAlgorithm::Sha512WithRsa => format!("SHA512_RSA{key_bits}"),
};
let mut command = Command::new(program);
command.arg(algo_str);
command.arg(public_key_file);
match passphrase_source {
PassphraseSource::Prompt(_) => {}
PassphraseSource::EnvVar(v) => {
command.arg("env");
command.arg(v);
}
PassphraseSource::File(p) => {
command.arg("file");
command.arg(p);
}
}
command.stdin(Stdio::piped());
command.stdout(Stdio::piped());
command.stderr(Stdio::inherit());
let mut child = command
.spawn()
.map_err(|e| Error::CommandSpawnFailed(format!("{command:?}"), e))?;
// We don't bother with spawning a thread. The pipe capacity on
// all major OSs is significantly larger than the digest, so we
// don't risk deadlocking even if the process doesn't read from
// stdin.
//
// Pipe capacities:
// * Linux: 64 KiB
// * macOS: 4 KiB, 16 KiB (usually), or 64 KiB
// * Windows: 4 KiB
let padded_digest = pkcs1v15_sign_pad(&scheme.prefix, digest, public_key.size())?;
child.stdin.as_mut().unwrap().write_all(&padded_digest)?;
let child = child.wait_with_output()?;
if !child.status.success() {
return Err(Error::CommandExecutionFailed(
format!("{command:?}"),
child.status,
));
} else if child.stdout.len() != self.size() {
return Err(Error::InvalidSignatureLength(child.stdout.len(), algo));
}
// Check that the helper signed with the proper key.
if let Err(e) = self.to_public_key().verify_sig(algo, digest, &child.stdout) {
return match e {
Error::RsaVerify(_) => {
Err(Error::SigningHelperBadSignature(public_key_file.clone()))
}
e => Err(e),
};
}
Ok(child.stdout)
}
}
}
}
pub trait RsaPublicKeyExt {
fn verify_sig(&self, algo: SignatureAlgorithm, digest: &[u8], signature: &[u8]) -> Result<()>;
}
impl RsaPublicKeyExt for RsaPublicKey {
/// Verify the signature against the specified key.
fn verify_sig(&self, algo: SignatureAlgorithm, digest: &[u8], signature: &[u8]) -> Result<()> {
// Check this explicitly so we can provide a better error message.
if digest.len() != algo.digest_len() {
return Err(Error::InvalidDigestLength(digest.len(), algo));
}
check_key_size(self.size())?;
let scheme = match algo {
SignatureAlgorithm::Sha1WithRsa => Pkcs1v15Sign::new::<Sha1>(),
SignatureAlgorithm::Sha256WithRsa => Pkcs1v15Sign::new::<Sha256>(),
SignatureAlgorithm::Sha512WithRsa => Pkcs1v15Sign::new::<Sha512>(),
};
self.verify(scheme, digest, signature)
.map_err(Error::RsaVerify)
}
}
/// Generate an 4096-bit RSA key pair.
pub fn generate_rsa_key_pair() -> Result<RsaPrivateKey> {
let mut rng = rand::thread_rng();
@@ -228,6 +454,16 @@ pub fn write_pem_cert_file(path: &Path, cert: &Certificate) -> Result<()> {
write_pem_cert(writer, cert)
}
/// Read PEM-encoded PKCS8 public key from a reader.
pub fn read_pem_public_key(mut reader: impl Read) -> Result<RsaPublicKey> {
let mut data = String::new();
reader.read_to_string(&mut data)?;
let key = RsaPublicKey::from_public_key_pem(&data)?;
Ok(key)
}
/// Write PEM-encoded PKCS8 public key to a writer.
pub fn write_pem_public_key(mut writer: impl Write, key: &RsaPublicKey) -> Result<()> {
let data = key.to_public_key_pem(LineEnding::LF)?;
@@ -237,6 +473,14 @@ pub fn write_pem_public_key(mut writer: impl Write, key: &RsaPublicKey) -> Resul
Ok(())
}
/// Read PEM-encoded PKCS8 public key from a file.
pub fn read_pem_public_key_file(path: &Path) -> Result<RsaPublicKey> {
let file = File::open(path)?;
let reader = BufReader::new(file);
read_pem_public_key(reader)
}
/// Write PEM-encoded PKCS8 public key to a file.
pub fn write_pem_public_key_file(path: &Path, key: &RsaPublicKey) -> Result<()> {
let file = File::create(path)?;
@@ -351,7 +595,7 @@ pub fn get_public_key(cert: &Certificate) -> Result<RsaPublicKey> {
}
/// Check if a certificate matches a private key.
pub fn cert_matches_key(cert: &Certificate, key: &RsaPrivateKey) -> Result<bool> {
pub fn cert_matches_key(cert: &Certificate, key: &RsaSigningKey) -> Result<bool> {
let public_key = get_public_key(cert)?;
Ok(key.to_public_key() == public_key)
@@ -389,12 +633,11 @@ pub fn get_cms_certs(sd: &SignedData) -> Vec<Certificate> {
/// a transport mechanism for a raw signature. Thus, we need to ensure that the
/// signature covers nothing but the raw data.
pub fn cms_sign_external(
key: &RsaPrivateKey,
key: &RsaSigningKey,
cert: &Certificate,
digest: &[u8],
) -> Result<ContentInfo> {
let scheme = Pkcs1v15Sign::new::<Sha256>();
let signature = key.sign(scheme, digest)?;
let signature = key.sign(SignatureAlgorithm::Sha256WithRsa, digest)?;
let digest_algorithm = AlgorithmIdentifierOwned {
oid: const_oid::db::rfc5912::ID_SHA_256,
+56 -81
View File
@@ -16,12 +16,12 @@ use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use num_bigint_dig::{ModInverse, ToBigInt};
use num_traits::{Pow, ToPrimitive};
use ring::digest::{Algorithm, Context};
use rsa::{traits::PublicKeyParts, BigUint, Pkcs1v15Sign, RsaPrivateKey, RsaPublicKey};
use rsa::{traits::PublicKeyParts, BigUint, RsaPublicKey};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256, Sha512};
use thiserror::Error;
use crate::{
crypto::{self, RsaPublicKeyExt, RsaSigningKey, SignatureAlgorithm},
escape,
format::{
fec::{self, Fec},
@@ -103,12 +103,9 @@ pub enum Error {
UnsupportedAlgorithm(AlgorithmType),
#[error("Hashing algorithm not supported: {0:?}")]
UnsupportedHashAlgorithm(String),
#[error("Incorrect key size ({key_size} bytes) for algorithm {algo:?} ({} bytes)", algo.public_key_len())]
IncorrectKeySize {
key_size: usize,
algo: AlgorithmType,
},
#[error("RSA key size (0) is not compatible with any AVB signing algorithm")]
#[error("Incorrect key size ({}) for algorithm {1:?}", .0 * 8)]
IncorrectKeySize(usize, AlgorithmType),
#[error("RSA key size ({}) is not compatible with any AVB signing algorithm", .0 * 8)]
UnsupportedKey(usize),
#[error("Hash tree does not immediately follow image data")]
HashTreeGap,
@@ -120,18 +117,18 @@ pub enum Error {
MismatchedFecBlockSizes { data: u32, hash: u32 },
#[error("Must have exactly one hash or hash tree descriptor")]
NoAppendedDescriptor,
#[error("Failed to RSA sign digest")]
RsaSign(#[source] rsa::Error),
#[error("Failed to RSA verify signature")]
RsaVerify(#[source] rsa::Error),
#[error("{0} byte image size is too small to fit header")]
TooSmallForHeader(u64),
#[error("{0} byte image size is too small to fit footer")]
TooSmallForFooter(u64),
#[error("Crypto error")]
Crypto(#[from] crypto::Error),
#[error("Hash tree error")]
HashTree(#[from] hashtree::Error),
#[error("FEC error")]
Fec(#[from] fec::Error),
#[error("RSA error")]
Rsa(#[from] rsa::Error),
#[error("I/O error")]
Io(#[from] io::Error),
}
@@ -156,6 +153,7 @@ pub enum AlgorithmType {
Sha512Rsa2048,
Sha512Rsa4096,
Sha512Rsa8192,
#[serde(untagged)]
Unknown(u32),
}
@@ -186,18 +184,24 @@ impl AlgorithmType {
}
}
pub fn hash_len(self) -> usize {
pub fn to_digest_algorithm(self) -> Option<SignatureAlgorithm> {
match self {
Self::None | Self::Unknown(_) => 0,
Self::Sha256Rsa2048 | Self::Sha256Rsa4096 | Self::Sha256Rsa8192 => {
Sha256::output_size()
Some(SignatureAlgorithm::Sha256WithRsa)
}
Self::Sha512Rsa2048 | Self::Sha512Rsa4096 | Self::Sha512Rsa8192 => {
Sha512::output_size()
Some(SignatureAlgorithm::Sha512WithRsa)
}
_ => None,
}
}
pub fn digest_len(self) -> usize {
self.to_digest_algorithm()
.map(|a| a.digest_len())
.unwrap_or_default()
}
pub fn signature_len(self) -> usize {
match self {
Self::None | Self::Unknown(_) => 0,
@@ -217,49 +221,36 @@ impl AlgorithmType {
}
pub fn hash(self, data: &[u8]) -> Vec<u8> {
match self {
Self::None | Self::Unknown(_) => vec![],
Self::Sha256Rsa2048 | Self::Sha256Rsa4096 | Self::Sha256Rsa8192 => {
Sha256::digest(data).to_vec()
}
Self::Sha512Rsa2048 | Self::Sha512Rsa4096 | Self::Sha512Rsa8192 => {
Sha512::digest(data).to_vec()
}
}
}
pub fn sign(self, key: &RsaPrivateKey, digest: &[u8]) -> Result<Vec<u8>> {
let signature = match self {
Self::None | Self::Unknown(_) => vec![],
Self::Sha256Rsa2048 | Self::Sha256Rsa4096 | Self::Sha256Rsa8192 => {
let scheme = Pkcs1v15Sign::new::<Sha256>();
key.sign(scheme, digest).map_err(Error::RsaSign)?
}
Self::Sha512Rsa2048 | Self::Sha512Rsa4096 | Self::Sha512Rsa8192 => {
let scheme = Pkcs1v15Sign::new::<Sha512>();
key.sign(scheme, digest).map_err(Error::RsaSign)?
}
let Some(algo) = self.to_digest_algorithm() else {
return vec![];
};
Ok(signature)
algo.hash(data)
}
pub fn sign(self, key: &RsaSigningKey, digest: &[u8]) -> Result<Vec<u8>> {
let Some(algo) = self.to_digest_algorithm() else {
return if self == Self::None {
Ok(vec![])
} else {
Err(Error::UnsupportedAlgorithm(self))
};
};
key.sign(algo, digest).map_err(|e| e.into())
}
pub fn verify(self, key: &RsaPublicKey, digest: &[u8], signature: &[u8]) -> Result<()> {
match self {
Self::None | Self::Unknown(_) => {}
Self::Sha256Rsa2048 | Self::Sha256Rsa4096 | Self::Sha256Rsa8192 => {
let scheme = Pkcs1v15Sign::new::<Sha256>();
key.verify(scheme, digest, signature)
.map_err(Error::RsaVerify)?;
}
Self::Sha512Rsa2048 | Self::Sha512Rsa4096 | Self::Sha512Rsa8192 => {
let scheme = Pkcs1v15Sign::new::<Sha512>();
key.verify(scheme, digest, signature)
.map_err(Error::RsaVerify)?;
}
}
let Some(algo) = self.to_digest_algorithm() else {
return if self == Self::None {
Ok(())
} else {
Err(Error::UnsupportedAlgorithm(self))
};
};
Ok(())
key.verify_sig(algo, digest, signature)
.map_err(|e| e.into())
}
}
@@ -1461,7 +1452,7 @@ impl Header {
result.ok_or(Error::NoAppendedDescriptor)
}
pub fn set_algo_for_key(&mut self, key: &RsaPrivateKey) -> Result<()> {
pub fn set_algo_for_key(&mut self, key: &RsaSigningKey) -> Result<()> {
let key_raw = encode_public_key(&key.to_public_key())?;
for algo in [AlgorithmType::Sha256Rsa2048, AlgorithmType::Sha256Rsa4096] {
@@ -1481,30 +1472,17 @@ impl Header {
self.public_key_metadata.clear();
}
pub fn sign(&mut self, key: &RsaPrivateKey) -> Result<()> {
pub fn sign(&mut self, key: &RsaSigningKey) -> Result<()> {
let key_raw = encode_public_key(&key.to_public_key())?;
// RustCrypto does not support 8192-bit keys.
match self.algorithm_type {
AlgorithmType::Sha256Rsa8192
| AlgorithmType::Sha512Rsa8192
| AlgorithmType::Unknown(_) => {
return Err(Error::UnsupportedAlgorithm(self.algorithm_type));
}
_ => {}
}
if key_raw.len() != self.algorithm_type.public_key_len() {
return Err(Error::IncorrectKeySize {
key_size: key_raw.len(),
algo: self.algorithm_type,
});
return Err(Error::IncorrectKeySize(key.size(), self.algorithm_type));
}
// The public key and the sizes of the hash and signature are included
// in the data that's about to be signed.
self.public_key = key_raw;
self.hash.resize(self.algorithm_type.hash_len(), 0);
self.hash.resize(self.algorithm_type.digest_len(), 0);
self.signature
.resize(self.algorithm_type.signature_len(), 0);
@@ -1525,18 +1503,16 @@ impl Header {
/// and return the public key. If the header is not signed, then `None` is
/// returned.
pub fn verify(&self) -> Result<Option<RsaPublicKey>> {
// RustCrypto does not support 8192-bit keys.
match self.algorithm_type {
AlgorithmType::None => return Ok(None),
a @ AlgorithmType::Sha256Rsa8192
| a @ AlgorithmType::Sha512Rsa8192
| a @ AlgorithmType::Unknown(_) => return Err(Error::UnsupportedAlgorithm(a)),
_ => {}
}
// Reconstruct the public key.
let public_key = decode_public_key(&self.public_key)?;
if self.public_key.len() != self.algorithm_type.public_key_len() {
return Err(Error::IncorrectKeySize(
public_key.size(),
self.algorithm_type,
));
}
let mut without_auth_writer = Cursor::new(Vec::new());
self.to_writer_internal(&mut without_auth_writer, true)?;
let without_auth = without_auth_writer.into_inner();
@@ -1825,8 +1801,7 @@ pub fn decode_public_key(data: &[u8]) -> Result<RsaPublicKey> {
reader.read_exact(&mut modulus_raw)?;
let modulus = BigUint::from_bytes_be(&modulus_raw);
let public_key =
RsaPublicKey::new(modulus, BigUint::from(65537u32)).map_err(Error::RsaVerify)?;
let public_key = RsaPublicKey::new(modulus, BigUint::from(65537u32))?;
Ok(public_key)
}
+3 -3
View File
@@ -1,5 +1,5 @@
/*
* SPDX-FileCopyrightText: 2023 Andrew Gunnerson
* SPDX-FileCopyrightText: 2023-2024 Andrew Gunnerson
* SPDX-License-Identifier: GPL-3.0-only
*/
@@ -12,11 +12,11 @@ use std::{
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use num_traits::ToPrimitive;
use ring::digest::Context;
use rsa::RsaPrivateKey;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::{
crypto::RsaSigningKey,
format::{
avb::{self, Descriptor, Header},
padding,
@@ -765,7 +765,7 @@ impl BootImageV3Through4 {
/// Sign the boot image with a legacy VTS signature. Returns true if the
/// image was successfully signed. Returns false if there's no vbmeta
/// structure to sign in [`V4Extra::signature`].
pub fn sign(&mut self, key: &RsaPrivateKey) -> Result<bool> {
pub fn sign(&mut self, key: &RsaSigningKey) -> Result<bool> {
let mut context = Context::new(&ring::digest::SHA256);
let image_size;
+6 -11
View File
@@ -15,15 +15,12 @@ use const_oid::{db::rfc5912, ObjectIdentifier};
use memchr::memmem;
use prost::Message;
use ring::digest::Context;
use rsa::{Pkcs1v15Sign, RsaPrivateKey};
use sha1::Sha1;
use sha2::Sha256;
use thiserror::Error;
use x509_cert::{der::Encode, Certificate};
use zip::{result::ZipError, write::FileOptions, CompressionMethod, ZipArchive, ZipWriter};
use crate::{
crypto,
crypto::{self, RsaPublicKeyExt, RsaSigningKey, SignatureAlgorithm},
format::payload::{self, PayloadHeader},
protobuf::build::tools::releasetools::{ota_metadata::OtaType, OtaMetadata},
stream::{self, FromReader, HashingReader, HashingWriter},
@@ -88,8 +85,6 @@ pub enum Error {
Spki(#[from] pkcs8::spki::Error),
#[error("x509 DER error")]
Der(#[from] x509_cert::der::Error),
#[error("RSA error")]
Rsa(#[from] rsa::Error),
#[error("Zip error")]
Zip(#[from] ZipError),
#[error("I/O error")]
@@ -586,12 +581,12 @@ pub fn verify_ota(mut reader: impl Read + Seek, cancel_signal: &AtomicBool) -> R
reader.seek(SeekFrom::Start(0))?;
// We support SHA1 for verification only.
let (algorithm, scheme) = if signer.digest_alg.oid == rfc5912::ID_SHA_256 {
(&ring::digest::SHA256, Pkcs1v15Sign::new::<Sha256>())
let (algorithm, algo) = if signer.digest_alg.oid == rfc5912::ID_SHA_256 {
(&ring::digest::SHA256, SignatureAlgorithm::Sha256WithRsa)
} else {
(
&ring::digest::SHA1_FOR_LEGACY_USE_ONLY,
Pkcs1v15Sign::new::<Sha1>(),
SignatureAlgorithm::Sha1WithRsa,
)
};
@@ -603,7 +598,7 @@ pub fn verify_ota(mut reader: impl Read + Seek, cancel_signal: &AtomicBool) -> R
let digest = context.finish();
// Verify the signature against the public key.
public_key.verify(scheme, digest.as_ref(), signer.signature.as_bytes())?;
public_key.verify_sig(algo, digest.as_ref(), signer.signature.as_bytes())?;
Ok(cert.clone())
}
@@ -661,7 +656,7 @@ impl<W: Write> SigningWriter<W> {
}
}
pub fn finish(mut self, key: &RsaPrivateKey, cert: &Certificate) -> Result<W> {
pub fn finish(mut self, key: &RsaSigningKey, cert: &Certificate) -> Result<W> {
if self.used < self.queue.len() {
return Err(
io::Error::new(io::ErrorKind::InvalidData, "Too small to contain EOCD").into(),
+52 -19
View File
@@ -1,5 +1,5 @@
/*
* SPDX-FileCopyrightText: 2022-2023 Andrew Gunnerson
* SPDX-FileCopyrightText: 2022-2024 Andrew Gunnerson
* SPDX-License-Identifier: GPL-3.0-only
*/
@@ -26,13 +26,11 @@ use rayon::{
prelude::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator},
};
use ring::digest::{Context, Digest};
use rsa::{traits::PublicKeyParts, Pkcs1v15Sign, RsaPrivateKey};
use sha2::Sha256;
use thiserror::Error;
use x509_cert::Certificate;
use crate::{
crypto,
crypto::{self, RsaPublicKeyExt, RsaSigningKey, SignatureAlgorithm},
protobuf::chromeos_update_engine::{
install_operation::Type, signatures::Signature, DeltaArchiveManifest, Extent,
InstallOperation, PartitionInfo, PartitionUpdate, Signatures,
@@ -100,8 +98,6 @@ pub enum Error {
ProtobufDecode(#[from] prost::DecodeError),
#[error("XZ stream error")]
XzStream(#[from] liblzma::stream::Error),
#[error("RSA error")]
Rsa(#[from] rsa::Error),
#[error("I/O error")]
Io(#[from] io::Error),
}
@@ -175,9 +171,8 @@ impl<R: Read> FromReader<R> for PayloadHeader {
/// Sign `digest` with `key` and return a [`Signatures`] protobuf struct with
/// the signature padded to the maximum size.
fn sign_digest(digest: &[u8], key: &RsaPrivateKey) -> Result<Signatures> {
let scheme = Pkcs1v15Sign::new::<Sha256>();
let mut digest_signed = key.sign(scheme, digest)?;
fn sign_digest(digest: &[u8], key: &RsaSigningKey) -> Result<Signatures> {
let mut digest_signed = key.sign(SignatureAlgorithm::Sha256WithRsa, digest)?;
assert!(
digest_signed.len() <= key.size(),
"Signature exceeds maximum size",
@@ -214,8 +209,7 @@ fn verify_digest(digest: &[u8], signatures: &Signatures, cert: &Certificate) ->
};
let without_padding = &data[..size as usize];
let scheme = Pkcs1v15Sign::new::<Sha256>();
match public_key.verify(scheme, digest, without_padding) {
match public_key.verify_sig(SignatureAlgorithm::Sha256WithRsa, digest, without_padding) {
Ok(_) => return Ok(()),
Err(e) => last_error = Some(e),
}
@@ -292,7 +286,7 @@ pub struct PayloadWriter<W: Write> {
h_partial: Context,
/// Includes signatures (hashes are for properties file).
h_full: Context,
key: RsaPrivateKey,
key: RsaSigningKey,
}
/// Write data to a writer and one or more hashers.
@@ -315,7 +309,7 @@ impl<W: Write> PayloadWriter<W> {
/// fields are ignored and internally recomputed to guarantee that there are
/// no gaps. All partitions' install operation data is written to the blob
/// section in order.
pub fn new(mut inner: W, mut header: PayloadHeader, key: RsaPrivateKey) -> Result<Self> {
pub fn new(mut inner: W, mut header: PayloadHeader, key: RsaSigningKey) -> Result<Self> {
let mut blob_size = 0;
// The blob must contain all data in sequential order with no gaps.
@@ -890,6 +884,21 @@ fn compress_chunk(raw_data: &[u8], cancel_signal: &AtomicBool) -> Result<(Vec<u8
Ok((data, digest_compressed))
}
fn compress_cow_size(mut raw_data: &[u8], block_size: u32) -> u64 {
let mut total = 0;
while !raw_data.is_empty() {
let n = raw_data.len().min(block_size as usize);
let compressed = lz4_flex::block::compress(&raw_data[..n]);
total += compressed.len().min(n) as u64;
raw_data = &raw_data[n..];
}
total
}
/// Compress the image and return the corresponding information to insert into
/// the payload manifest's [`PartitionUpdate`] instance. The uncompressed data
/// is split into 2 MiB chunks, which are read and compressed in parallel, and
@@ -897,13 +906,21 @@ fn compress_chunk(raw_data: &[u8], cancel_signal: &AtomicBool) -> Result<(Vec<u8
/// a corresponding [`InstallOperation`] in the return value. The caller must
/// update [`InstallOperation::data_offset`] in each operation manually because
/// the initial values are relative to 0.
///
/// If `need_cow_estimate` is true, the VABC CoW v2 + lz4 size estimate will be
/// computed. The caller must update [`PartitionUpdate::estimate_cow_size`] with
/// this value or else update_engine may fail to flash the partition due to
/// running out of space on the CoW block device. CoW v2 + other algorithms and
/// also CoW v3 are currently unsupported because there currently are no known
/// OTAs that use those configurations.
pub fn compress_image(
input: &(dyn ReadSeekReopen + Sync),
output: &(dyn WriteSeekReopen + Sync),
partition_name: &str,
block_size: u32,
need_cow_estimate: bool,
cancel_signal: &AtomicBool,
) -> Result<(PartitionInfo, Vec<InstallOperation>)> {
) -> Result<(PartitionInfo, Vec<InstallOperation>, Option<u64>)> {
const CHUNK_SIZE: u64 = 2 * 1024 * 1024;
const CHUNK_GROUP: u64 = 32;
@@ -921,6 +938,7 @@ pub fn compress_image(
let chunks_total = file_size.div_ceil(CHUNK_SIZE);
let mut bytes_compressed = 0;
let mut context_uncompressed = Context::new(&ring::digest::SHA256);
let mut cow_estimate = 0;
let mut operations = vec![];
// Read the file one group at a time. This allows for some parallelization
@@ -957,8 +975,13 @@ pub fn compress_image(
let mut compressed_data_group = uncompressed_data_group
.into_par_iter()
.map(
|(raw_offset, raw_data)| -> Result<(Vec<u8>, InstallOperation)> {
|(raw_offset, raw_data)| -> Result<(Vec<u8>, InstallOperation, u64)> {
let (data, digest_compressed) = compress_chunk(&raw_data, cancel_signal)?;
let cow_size = if need_cow_estimate {
compress_cow_size(&raw_data, block_size)
} else {
0
};
let extent = Extent {
start_block: Some(raw_offset / u64::from(block_size)),
@@ -971,19 +994,20 @@ pub fn compress_image(
operation.dst_extents.push(extent);
operation.data_sha256_hash = Some(digest_compressed.as_ref().to_vec());
Ok((data, operation))
Ok((data, operation, cow_size))
},
)
.collect::<Result<Vec<_>>>()?;
for (data, operation) in &mut compressed_data_group {
for (data, operation, cow_size) in &mut compressed_data_group {
operation.data_offset = Some(bytes_compressed);
bytes_compressed += data.len() as u64;
cow_estimate += *cow_size;
}
let group_operations = compressed_data_group
.into_par_iter()
.map(|(data, operation)| -> Result<InstallOperation> {
.map(|(data, operation, _)| -> Result<InstallOperation> {
let mut writer = output.reopen_boxed()?;
writer.seek(SeekFrom::Start(operation.data_offset.unwrap()))?;
writer.write_all(&data)?;
@@ -1001,7 +1025,16 @@ pub fn compress_image(
hash: Some(digest_uncompressed.as_ref().to_vec()),
};
Ok((partition_info, operations))
let cow_estimate = if need_cow_estimate {
// Because lz4_flex compresses better than official lz4.
let fudge = cow_estimate / 100;
Some(cow_estimate + fudge)
} else {
None
};
Ok((partition_info, operations, cow_estimate))
}
fn extents_sorted(operations: &[InstallOperation]) -> bool {
+11 -3
View File
@@ -23,14 +23,14 @@ use liblzma::{
use rayon::iter::{IntoParallelRefIterator, IntoParallelRefMutIterator, ParallelIterator};
use regex::bytes::Regex;
use ring::digest::Context;
use rsa::{RsaPrivateKey, RsaPublicKey};
use rsa::RsaPublicKey;
use thiserror::Error;
use tracing::{debug, debug_span, trace, warn, Span};
use x509_cert::Certificate;
use zip::{result::ZipError, ZipArchive};
use crate::{
crypto,
crypto::{self, RsaSigningKey},
format::{
avb::{self, AppendedDescriptorMut, Footer, Header},
bootimage::{self, BootImage, BootImageExt, RamdiskMeta},
@@ -161,6 +161,7 @@ impl MagiskRootPatcher {
const VER_XZ_BACKUP: Range<u32> =
26403..Self::VERS_SUPPORTED[Self::VERS_SUPPORTED.len() - 1].end;
const ZIP_INIT_LD: &'static str = "lib/arm64-v8a/libinit-ld.so";
const ZIP_LIBMAGISK: &'static str = "lib/arm64-v8a/libmagisk.so";
const ZIP_LIBMAGISK32: &'static str = "lib/armeabi-v7a/libmagisk32.so";
const ZIP_LIBMAGISK64: &'static str = "lib/arm64-v8a/libmagisk64.so";
@@ -462,6 +463,13 @@ impl BootImagePatch for MagiskRootPatcher {
xz_files.insert(Self::ZIP_STUB, b"overlay.d/sbin/stub.xz");
}
// Add init-ld, which only exists after Magisk commit
// 33aebb59763b6ec27209563035303700e998633d
if zip.file_names().any(|n| n == Self::ZIP_INIT_LD) {
debug!("Magisk init-ld found");
xz_files.insert(Self::ZIP_INIT_LD, b"overlay.d/sbin/init-ld.xz");
}
for (source, target) in xz_files {
let reader = zip
.by_name(source)
@@ -1122,7 +1130,7 @@ pub fn patch_boot_images<'a>(
names: &[&'a str],
open_input: impl Fn(&str) -> io::Result<Box<dyn ReadSeek>> + Sync,
open_output: impl Fn(&str) -> io::Result<Box<dyn WriteSeek>> + Sync,
key: &RsaPrivateKey,
key: &RsaSigningKey,
patchers: &[Box<dyn BootImagePatch + Sync>],
cancel_signal: &AtomicBool,
) -> Result<HashSet<&'a str>> {
+2 -2
View File
@@ -11,13 +11,13 @@ use std::{
use memchr::memmem;
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use rsa::RsaPrivateKey;
use thiserror::Error;
use tracing::{debug, debug_span, trace, Span};
use x509_cert::Certificate;
use zip::ZipArchive;
use crate::{
crypto::RsaSigningKey,
format::{
avb::{self, AppendedDescriptorMut, Footer},
ota,
@@ -111,7 +111,7 @@ pub fn patch_system_image(
input: &(dyn ReadSeekReopen + Sync),
output: &(dyn WriteSeekReopen + Sync),
certificate: &Certificate,
key: &RsaPrivateKey,
key: &RsaSigningKey,
cancel_signal: &AtomicBool,
) -> Result<(Vec<Range<u64>>, Vec<Range<u64>>)> {
// This must be a multiple of normal filesystem block sizes (eg. 4 KiB).
+4 -2
View File
@@ -14,6 +14,7 @@ use rsa::RsaPrivateKey;
use avbroot::{
self,
crypto::RsaSigningKey,
format::avb::{
self, AlgorithmType, AppendedDescriptorMut, AppendedDescriptorRef,
ChainPartitionDescriptor, Descriptor, Footer, HashDescriptor, HashTreeDescriptor, Header,
@@ -22,7 +23,7 @@ use avbroot::{
stream::SharedCursor,
};
fn get_test_key() -> RsaPrivateKey {
fn get_test_key() -> RsaSigningKey {
let data = include_str!(concat!(
env!("CARGO_WORKSPACE_DIR"),
"/e2e/keys/TEST_KEY_DO_NOT_USE_avb.key",
@@ -32,7 +33,8 @@ fn get_test_key() -> RsaPrivateKey {
"/e2e/keys/TEST_KEY_DO_NOT_USE_avb.passphrase",
));
RsaPrivateKey::from_pkcs8_encrypted_pem(data, passphrase.trim_end()).unwrap()
let key = RsaPrivateKey::from_pkcs8_encrypted_pem(data, passphrase.trim_end()).unwrap();
RsaSigningKey::Internal(key)
}
fn repeat_str(s: &str, max_len: usize) -> String {
+4 -2
View File
@@ -7,6 +7,7 @@ use std::io::Cursor;
use avbroot::{
self,
crypto::RsaSigningKey,
format::{
avb::{AlgorithmType, Descriptor, HashDescriptor, Header},
bootimage::{
@@ -19,7 +20,7 @@ use avbroot::{
use pkcs8::DecodePrivateKey;
use rsa::RsaPrivateKey;
fn get_test_key() -> RsaPrivateKey {
fn get_test_key() -> RsaSigningKey {
let data = include_str!(concat!(
env!("CARGO_WORKSPACE_DIR"),
"/e2e/keys/TEST_KEY_DO_NOT_USE_avb.key",
@@ -29,7 +30,8 @@ fn get_test_key() -> RsaPrivateKey {
"/e2e/keys/TEST_KEY_DO_NOT_USE_avb.passphrase",
));
RsaPrivateKey::from_pkcs8_encrypted_pem(data, passphrase.trim_end()).unwrap()
let key = RsaPrivateKey::from_pkcs8_encrypted_pem(data, passphrase.trim_end()).unwrap();
RsaSigningKey::Internal(key)
}
fn repeat(s: &str, max_len: usize) -> String {
-2
View File
@@ -62,8 +62,6 @@ include-workspace = true
bypass = [
# Copies of unmodified crashwrangler objects for old macOS versions.
{ name = "honggfuzz", allow-globs = ["honggfuzz/third_party/mac/CrashReport_*.o"] },
# Test files for liblzma's test suite
{ name = "liblzma-sys", allow-globs = ["xz/tests/compress_prepared_bcj_*"] },
]
[sources]
+1 -1
View File
@@ -15,7 +15,7 @@ clap = { version = "4.4.1", features = ["derive"] }
ctrlc = "3.4.0"
hex = { version = "0.4.3", features = ["serde"] }
ring = "0.17.0"
rsa = "0.9.6"
rsa = { version = "0.9.6", features = ["hazmat"] }
serde = { version = "1.0.188", features = ["derive"] }
tempfile = "3.8.0"
toml_edit = { version = "0.22.9", features = ["serde"] }
+8 -8
View File
@@ -46,8 +46,8 @@ data.version = "vendor_v4"
data.ramdisks = [["otacerts", "first_stage", "dsu_key_dir"]]
[profile.pixel_v4_gki.hashes]
original = "24a0a62cc08b96563f4872aee2fdd4a84d1a977b55c326dd9d4ddd92a1d326ea"
patched = "29889670efea78bace221742b19e8ace88b67137fc2f46dcd9dbdf67e4e42267"
original = "6b140c378d21eae2fa4fc581bce13a689b21bd32f5fba865698d1fd322f2f8c6"
patched = "a68b3a44c0cf015a225f92837c05fd0dec6e159584c5880eff30d12daa7123ff"
# Google Pixel 6a
# What's unique: boot (boot v4, no ramdisk) + vendor_boot (vendor v4, 2 ramdisks)
@@ -80,8 +80,8 @@ data.version = "vendor_v4"
data.ramdisks = [["init", "otacerts", "first_stage", "dsu_key_dir"], ["dlkm"]]
[profile.pixel_v4_non_gki.hashes]
original = "0e7d0924a68d46e00abe96abfa0e5f3a98d5d15a32bef7401b91fca9a19748e8"
patched = "1a2f53d9ac3a1da75e5e7502110bda437c5a725764f16656c564d42460136279"
original = "31963e6f81986c6686111f50e36b89e4d85ee5c02bc8e5ecd560528bc98d6fe7"
patched = "a13173a006ad94b25db682bb14fde2e36891417727d6541bdf5f9bca57d26751"
# Google Pixel 4a 5G
# What's unique: boot (boot v3) + vendor_boot (vendor v3)
@@ -115,8 +115,8 @@ data.version = "vendor_v3"
data.ramdisks = [["otacerts", "first_stage", "dsu_key_dir"]]
[profile.pixel_v3.hashes]
original = "533e6f233cb98c98c945044c2ee81a6069e66baee6f7dbcfbf7523795a11215e"
patched = "1eeae9dba0302c2d469bd03c8bccdc0469c171204dbd676a20cb6620d2d11c5c"
original = "e684aacb54464098c1b8e3f499efe35dff10ea792e89d71a83404620d0108b3e"
patched = "49e810ae76154bccf2dc7d810b9eec19d23a5b8fa32381469660488d0a25121b"
# Google Pixel 4a
# What's unique: boot (boot v2)
@@ -144,5 +144,5 @@ data.type = "vbmeta"
data.deps = ["system"]
[profile.pixel_v2.hashes]
original = "958dfa428abd2901178b90147903d7857ed78d6c016f6cb3af30d024a22a8f9a"
patched = "b0d18ef350ca7b6499b7de4b0182f4ac3be7288ad238ce888708643e750f7631"
original = "ee9568797d9195985f14753b89949d8ebb08c8863a32eceeeec6e8d94661b1cf"
patched = "e413f1f87ee5ba53d402edad03b0df8af451b5b0323202a9d32b8327d433d340"
+26 -2
View File
@@ -3,10 +3,10 @@
* SPDX-License-Identifier: GPL-3.0-only
*/
use std::path::PathBuf;
use std::{ffi::OsString, path::PathBuf};
use avbroot::cli::args::{LogFormat, LogLevel};
use clap::{Args, Parser, Subcommand};
use clap::{Args, Parser, Subcommand, ValueEnum};
#[derive(Debug, Args)]
pub struct ProfileGroup {
@@ -76,3 +76,27 @@ pub struct Cli {
#[arg(long, global = true, value_name = "FORMAT", default_value_t = LogFormat::Medium)]
pub log_format: LogFormat,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub enum PassSource {
Env,
File,
}
#[derive(Debug, Parser)]
pub struct HelperCli {
/// Signature algorithm.
pub algorithm: String,
/// Public key.
#[arg(value_name = "FILE", value_parser)]
pub public_key: PathBuf,
/// Non-interactive password source.
#[arg(value_name = "SOURCE")]
pub pass_source: PassSource,
/// Non-interactive password source value.
#[arg(value_name = "VALUE", value_parser)]
pub pass_source_value: OsString,
}
+188 -53
View File
@@ -9,10 +9,11 @@ mod config;
use std::{
collections::{BTreeMap, BTreeSet},
ffi::OsStr,
env,
ffi::{OsStr, OsString},
fs::{self, File},
io::{self, BufReader, BufWriter, Cursor, Seek, SeekFrom, Write},
path::Path,
io::{self, BufReader, BufWriter, Cursor, Read, Seek, SeekFrom, Write},
path::{Path, PathBuf},
sync::{
atomic::{AtomicBool, Ordering},
Arc,
@@ -22,7 +23,7 @@ use std::{
use anyhow::{anyhow, bail, Context, Result};
use avbroot::{
cli::ota::{ExtractCli, PatchCli, VerifyCli},
crypto::{self, PassphraseSource},
crypto::{self, PassphraseSource, RsaSigningKey},
format::{
avb::{
self, AlgorithmType, ChainPartitionDescriptor, Descriptor, Footer, HashDescriptor,
@@ -48,15 +49,15 @@ use avbroot::{
stream::{self, CountingWriter, HashingReader, PSeekFile, Reopen, ToWriter},
};
use clap::Parser;
use rsa::RsaPrivateKey;
use tempfile::{NamedTempFile, TempDir};
use rsa::{rand_core::OsRng, traits::PublicKeyParts, BigUint};
use tempfile::TempDir;
use topological_sort::TopologicalSort;
use tracing::{info, info_span};
use x509_cert::Certificate;
use zip::{write::FileOptions, CompressionMethod, ZipWriter};
use crate::{
cli::{Cli, Command, ListCli, ProfileGroup, TestCli},
cli::{Cli, Command, HelperCli, ListCli, PassSource, ProfileGroup, TestCli},
config::{
Avb, BootData, BootVersion, Config, Data, DmVerityContent, DmVerityData, OtaInfo,
Partition, Profile, RamdiskContent, VbmetaData,
@@ -100,7 +101,7 @@ fn append_avb(
avb: &Avb,
hash_tree: bool,
ota_info: &OtaInfo,
key_avb: &RsaPrivateKey,
key_avb: &RsaSigningKey,
cancel_signal: &AtomicBool,
) -> Result<()> {
let image_size = file.seek(SeekFrom::End(0))?;
@@ -298,7 +299,7 @@ fn create_boot_image(
avb: &Avb,
boot_data: &BootData,
ota_info: &OtaInfo,
key_avb: &RsaPrivateKey,
key_avb: &RsaSigningKey,
cert_ota: &Certificate,
cancel_signal: &AtomicBool,
) -> Result<()> {
@@ -425,7 +426,7 @@ fn create_dm_verity_image(
avb: &Avb,
dm_verity_data: &DmVerityData,
ota_info: &OtaInfo,
key_avb: &RsaPrivateKey,
key_avb: &RsaSigningKey,
cert_ota: &Certificate,
cancel_signal: &AtomicBool,
) -> Result<()> {
@@ -454,7 +455,7 @@ fn create_vbmeta_image(
avb: &Avb,
vbmeta_data: &VbmetaData,
inputs: &BTreeMap<String, PSeekFile>,
key: &RsaPrivateKey,
key: &RsaSigningKey,
) -> Result<()> {
let mut descriptors = Vec::new();
@@ -506,7 +507,7 @@ fn create_vbmeta_image(
fn create_partition_images(
partitions: &BTreeMap<String, Partition>,
ota_info: &OtaInfo,
key_avb: &RsaPrivateKey,
key_avb: &RsaSigningKey,
cert_ota: &Certificate,
cancel_signal: &AtomicBool,
) -> Result<BTreeMap<String, PSeekFile>> {
@@ -576,7 +577,7 @@ fn create_payload(
partitions: &BTreeMap<String, Partition>,
inputs: &BTreeMap<String, PSeekFile>,
ota_info: &OtaInfo,
key_ota: &RsaPrivateKey,
key_ota: &RsaSigningKey,
cancel_signal: &AtomicBool,
) -> Result<(String, u64)> {
let dynamic_partitions_names = partitions
@@ -593,8 +594,14 @@ fn create_payload(
.map(PSeekFile::new)
.with_context(|| format!("Failed to create temp file for: {name}"))?;
let (partition_info, operations) =
payload::compress_image(file, &writer, name, 4096, cancel_signal)?;
let (partition_info, operations, cow_estimate) = payload::compress_image(
file,
&writer,
name,
4096,
dynamic_partitions_names.contains(name),
cancel_signal,
)?;
compressed.insert(name, writer);
@@ -617,7 +624,7 @@ fn create_payload(
fec_roots: None,
version: None,
merge_operations: vec![],
estimate_cow_size: None,
estimate_cow_size: cow_estimate,
});
}
@@ -638,7 +645,7 @@ fn create_payload(
}],
snapshot_enabled: Some(true),
vabc_enabled: Some(true),
vabc_compression_param: Some("gz".to_owned()),
vabc_compression_param: Some("lz4".to_owned()),
cow_version: Some(2),
vabc_feature_set: None,
}),
@@ -692,8 +699,8 @@ fn create_ota(
output: &Path,
ota_info: &OtaInfo,
profile: &Profile,
key_avb: &RsaPrivateKey,
key_ota: &RsaPrivateKey,
key_avb: &RsaSigningKey,
key_ota: &RsaSigningKey,
cert_ota: &Certificate,
cancel_signal: &AtomicBool,
) -> Result<()> {
@@ -823,12 +830,16 @@ fn create_fake_magisk(output: &Path) -> Result<()> {
for path in [
"assets/stub.apk",
"lib/arm64-v8a/libinit-ld.so",
"lib/arm64-v8a/libmagisk64.so",
"lib/arm64-v8a/libmagiskinit.so",
"lib/armeabi-v7a/libinit-ld.so",
"lib/armeabi-v7a/libmagisk32.so",
"lib/armeabi-v7a/libmagiskinit.so",
"lib/x86/libinit-ld.so",
"lib/x86/libmagisk32.so",
"lib/x86/libmagiskinit.so",
"lib/x86_64/libinit-ld.so",
"lib/x86_64/libmagisk64.so",
"lib/x86_64/libmagiskinit.so",
] {
@@ -844,15 +855,18 @@ fn create_fake_magisk(output: &Path) -> Result<()> {
}
struct KeySet {
avb_key: RsaPrivateKey,
ota_key: RsaPrivateKey,
avb_key: RsaSigningKey,
ota_key: RsaSigningKey,
ota_cert: Certificate,
avb_key_file: NamedTempFile,
avb_pass_file: NamedTempFile,
avb_pkmd_file: NamedTempFile,
ota_key_file: NamedTempFile,
ota_pass_file: NamedTempFile,
ota_cert_file: NamedTempFile,
_key_dir: TempDir,
avb_key_file: PathBuf,
avb_public_key_file: PathBuf,
avb_pass_file: PathBuf,
avb_pkmd_file: PathBuf,
ota_key_file: PathBuf,
ota_public_key_file: PathBuf,
ota_pass_file: PathBuf,
ota_cert_file: PathBuf,
}
macro_rules! new_keys_with_prefix {
@@ -901,13 +915,8 @@ macro_rules! new_keys_with_prefix {
}
impl KeySet {
fn write_temp(data: &[u8]) -> Result<NamedTempFile> {
let mut temp_file =
NamedTempFile::new().context("Failed to create temp file for test keys")?;
temp_file
.write_all(data)
.with_context(|| format!("Failed to write test key data: {:?}", temp_file.path()))?;
Ok(temp_file)
fn write(path: &Path, data: &[u8]) -> Result<()> {
fs::write(path, data).with_context(|| format!("Failed to write test key data: {path:?}"))
}
fn new_with_data(
@@ -918,36 +927,54 @@ impl KeySet {
ota_pass: &[u8],
ota_cert: &[u8],
) -> Result<Self> {
let avb_key_file = Self::write_temp(avb_key)?;
let avb_pass_file = Self::write_temp(avb_pass)?;
let avb_pkmd_file = Self::write_temp(avb_pkmd)?;
let ota_key_file = Self::write_temp(ota_key)?;
let ota_pass_file = Self::write_temp(ota_pass)?;
let ota_cert_file = Self::write_temp(ota_cert)?;
let key_dir = TempDir::new().context("Failed to create temp directory")?;
let avb_key_file = key_dir.path().join("avb.key");
let avb_public_key_file = key_dir.path().join("avb.public.key");
let avb_pass_file = key_dir.path().join("avb.passphrase");
let avb_pkmd_file = key_dir.path().join("avb_pkmd.bin");
let ota_key_file = key_dir.path().join("ota.key");
let ota_public_key_file = key_dir.path().join("ota.public.key");
let ota_pass_file = key_dir.path().join("ota.passphrase");
let ota_cert_file = key_dir.path().join("ota.crt");
Self::write(&avb_key_file, avb_key)?;
Self::write(&avb_pass_file, avb_pass)?;
Self::write(&avb_pkmd_file, avb_pkmd)?;
Self::write(&ota_key_file, ota_key)?;
Self::write(&ota_pass_file, ota_pass)?;
Self::write(&ota_cert_file, ota_cert)?;
let avb_key = crypto::read_pem_key_file(
avb_key_file.path(),
&PassphraseSource::File(avb_pass_file.path().to_owned()),
&avb_key_file,
&PassphraseSource::File(avb_pass_file.clone()),
)
.map(RsaSigningKey::Internal)
.context("Failed to load AVB test key")?;
let ota_key = crypto::read_pem_key_file(
ota_key_file.path(),
&PassphraseSource::File(ota_pass_file.path().to_owned()),
&ota_key_file,
&PassphraseSource::File(ota_pass_file.clone()),
)
.map(RsaSigningKey::Internal)
.context("Failed to load OTA test key")?;
let ota_cert = crypto::read_pem_cert_file(ota_cert_file.path())
.context("Failed to load OTA test cert")?;
crypto::write_pem_public_key_file(&avb_public_key_file, &avb_key.to_public_key())?;
crypto::write_pem_public_key_file(&ota_public_key_file, &ota_key.to_public_key())?;
let ota_cert =
crypto::read_pem_cert_file(&ota_cert_file).context("Failed to load OTA test cert")?;
Ok(Self {
avb_key,
ota_key,
ota_cert,
_key_dir: key_dir,
avb_key_file,
avb_public_key_file,
avb_pass_file,
avb_pkmd_file,
ota_key_file,
ota_public_key_file,
ota_pass_file,
ota_cert_file,
})
@@ -960,12 +987,20 @@ impl KeySet {
fn patch_image(
input_file: &Path,
output_file: &Path,
system_image_file: &Path,
extra_args: &[&OsStr],
keys: &KeySet,
signing_helper: bool,
cancel_signal: &AtomicBool,
) -> Result<()> {
info!("Patching OTA: {input_file:?} -> {output_file:?}");
let (avb_key_file, ota_key_file) = if signing_helper {
(&keys.avb_public_key_file, &keys.ota_public_key_file)
} else {
(&keys.avb_key_file, &keys.ota_key_file)
};
// We're intentionally using the CLI interface.
let mut args: Vec<&OsStr> = vec![
OsStr::new("patch"),
@@ -973,18 +1008,29 @@ fn patch_image(
input_file.as_os_str(),
OsStr::new("--output"),
output_file.as_os_str(),
OsStr::new("--replace"),
OsStr::new("system"),
system_image_file.as_os_str(),
OsStr::new("--key-avb"),
keys.avb_key_file.path().as_os_str(),
avb_key_file.as_os_str(),
OsStr::new("--pass-avb-file"),
keys.avb_pass_file.path().as_os_str(),
keys.avb_pass_file.as_os_str(),
OsStr::new("--key-ota"),
keys.ota_key_file.path().as_os_str(),
ota_key_file.as_os_str(),
OsStr::new("--pass-ota-file"),
keys.ota_pass_file.path().as_os_str(),
keys.ota_pass_file.as_os_str(),
OsStr::new("--cert-ota"),
keys.ota_cert_file.path().as_os_str(),
keys.ota_cert_file.as_os_str(),
OsStr::new("--dsu"),
];
let argv0: OsString;
if signing_helper {
argv0 = env::args_os().next().unwrap();
args.push(OsStr::new("--signing-helper"));
args.push(&argv0);
}
args.extend_from_slice(extra_args);
let cli = PatchCli::try_parse_from(args)?;
@@ -1016,9 +1062,9 @@ fn verify_image(input_file: &Path, keys: &KeySet, cancel_signal: &AtomicBool) ->
OsStr::new("--input"),
input_file.as_os_str(),
OsStr::new("--public-key-avb"),
keys.avb_pkmd_file.path().as_os_str(),
keys.avb_pkmd_file.as_os_str(),
OsStr::new("--cert-ota"),
keys.ota_cert_file.path().as_os_str(),
keys.ota_cert_file.as_os_str(),
])?;
avbroot::cli::ota::verify_subcommand(&cli, cancel_signal)?;
@@ -1119,11 +1165,18 @@ fn test_subcommand(cli: &TestCli, cancel_signal: &AtomicBool) -> Result<()> {
.with_context(|| format!("[{name}] Failed to verify original OTA hash"))?;
// Patch once using Magisk.
extract_image(&out_original, &profile_dir, cancel_signal)
.with_context(|| format!("[{name}] Failed to extract OTA"))?;
let system_image = profile_dir.join("system.img");
patch_image(
&out_original,
&out_magisk,
&system_image,
&args_magisk,
&test_keys,
false,
cancel_signal,
)
.with_context(|| format!("[{name}] Failed to patch OTA"))?;
@@ -1149,8 +1202,10 @@ fn test_subcommand(cli: &TestCli, cancel_signal: &AtomicBool) -> Result<()> {
patch_image(
&out_original,
&out_prepatched,
&system_image,
&args_prepatched,
&test_keys,
true,
cancel_signal,
)
.with_context(|| format!("[{name}] Failed to patch OTA"))?;
@@ -1175,7 +1230,87 @@ fn list_subcommand(cli: &ListCli) -> Result<()> {
Ok(())
}
/// A basic --signing-helper implementation that just signs via RustCrypto.
fn helper_mode() -> Result<()> {
let cli = HelperCli::parse();
let private_key_path = {
let parent = cli.public_key.parent().unwrap_or(Path::new("."));
let name = cli
.public_key
.file_name()
.and_then(|n| n.to_str())
.ok_or_else(|| anyhow!("Bad filename: {:?}", cli.public_key))?;
parent.join(name.replace(".public", ""))
};
let source = match cli.pass_source {
PassSource::Env => PassphraseSource::EnvVar(cli.pass_source_value),
PassSource::File => PassphraseSource::File(cli.pass_source_value.into()),
};
let private_key = crypto::read_pem_key_file(&private_key_path, &source)
.with_context(|| format!("Failed to load private key: {private_key_path:?}"))?;
let public_key = crypto::read_pem_public_key_file(&cli.public_key)
.with_context(|| format!("Failed to load public key: {:?}", cli.public_key))?;
if private_key.to_public_key() != public_key {
bail!("Private key does not match public key");
}
let (hash_algo, key_algo) = cli
.algorithm
.split_once('_')
.ok_or_else(|| anyhow!("Unknown algorithm: {:?}", cli.algorithm))?;
if key_algo != format!("RSA{}", private_key.size() * 8) {
bail!(
"{key_algo} does not match key size ({})",
private_key.size() * 8
);
} else if hash_algo != "SHA256" && hash_algo != "SHA512" {
bail!("Unknown hash algorithm: {hash_algo}");
}
let mut padded_digest = vec![];
io::stdin()
.read_to_end(&mut padded_digest)
.context("Failed to read padded digest from stdin")?;
if padded_digest.len() != private_key.size() {
bail!(
"Padded digest size ({}) bytes does not match key size ({})",
padded_digest.len(),
private_key.size()
);
}
// The input is already padded, so perform a raw RSA signing operation.
let mut signature = rsa::hazmat::rsa_decrypt_and_check(
&private_key,
None::<&mut OsRng>,
&BigUint::from_bytes_be(&padded_digest),
)
.context("Failed to sign digest")?
.to_bytes_le();
signature.resize(private_key.size(), 0);
signature.reverse();
io::stdout()
.write_all(&signature)
.context("Failed to write signature to stdout")?;
Ok(())
}
fn main() -> Result<()> {
const ENV_HELPER_MODE: &str = "E2E_HELPER_MODE";
// Re-invoking ourselves will execute as the helper script instead.
if env::var_os(ENV_HELPER_MODE).is_some() {
return helper_mode();
}
env::set_var(ENV_HELPER_MODE, "true");
// Set up a cancel signal so we can properly clean up any temporary files.
let cancel_signal = Arc::new(AtomicBool::new(false));
{