mirror of
https://github.com/chenxiaolong/avbroot.git
synced 2026-07-03 14:05:11 +02:00
Compare commits
73 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8ca4eb5ad9 | |||
| e2b1ccb7a1 | |||
| 71a31ae01b | |||
| 83d7ffbc5e | |||
| e397998d9e | |||
| 8ef22508f5 | |||
| bf42a6a75c | |||
| a2fe6fc9d8 | |||
| faeb1fe988 | |||
| f1b2c6f468 | |||
| 2f964bf113 | |||
| f393d7adc4 | |||
| 72a1c3f216 | |||
| 2db8d3826e | |||
| 1448e55205 | |||
| b3862a9c4a | |||
| 088db04673 | |||
| b1410c869d | |||
| dd6eaf8e78 | |||
| 0eac8e6614 | |||
| 8a4f90176e | |||
| bd166594e2 | |||
| 19129ae927 | |||
| fb2aaed042 | |||
| 182d937d34 | |||
| 113bdec6dc | |||
| 1f0d012ac0 | |||
| e4fbe00ea2 | |||
| ad0b3d5aa8 | |||
| f4394b0c21 | |||
| 9dd98fd715 | |||
| b6e3c68241 | |||
| 6fee5346bb | |||
| 7d786150cf | |||
| b922f0d23c | |||
| 1f2b2170b3 | |||
| da124e4e05 | |||
| 7b778515d1 | |||
| 98745afe33 | |||
| a47c501211 | |||
| f2e47a65d4 | |||
| e11ddd2ba7 | |||
| 5d66774d13 | |||
| 3f09a506a0 | |||
| 4664f8ea37 | |||
| 796e2a4fa2 | |||
| e6b60d5d0f | |||
| e8cb4a8d53 | |||
| b2d280eb20 | |||
| e2dc5174b4 | |||
| 80c47e9a02 | |||
| 65ba3ad5cc | |||
| a7438876ce | |||
| c039901a85 | |||
| 0cdc7172dd | |||
| 1296275418 | |||
| a62d0a5c91 | |||
| de433a2724 | |||
| c08af33343 | |||
| e224884591 | |||
| a525fc4550 | |||
| 8c6b0fdfc5 | |||
| 36d4ed19ad | |||
| f9b06b33e6 | |||
| 620c873be5 | |||
| e929ecbe44 | |||
| 31685713ef | |||
| 0dab7aa32c | |||
| ba6c1b1400 | |||
| 1ecbf1144d | |||
| 84fa6c6bc6 | |||
| 15b7db4631 | |||
| 1d9c1574da |
@@ -34,8 +34,7 @@ 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
|
||||
- os: ubuntu-latest
|
||||
name: aarch64-linux-android31
|
||||
targets:
|
||||
- aarch64-linux-android
|
||||
@@ -84,7 +83,7 @@ jobs:
|
||||
done
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: Swatinem/rust-cache@f0deed1e0edfc6a9be95417288c0e1099b1eeec3 # v2.7.7
|
||||
uses: Swatinem/rust-cache@9d47c6ad4b02e050fd481d890b2ea34778fd09d6 # v2.7.8
|
||||
with:
|
||||
key: ${{ matrix.artifact.name }}
|
||||
|
||||
@@ -155,7 +154,7 @@ jobs:
|
||||
run: cp LICENSE README.md target/output/
|
||||
|
||||
- name: Archive executable
|
||||
uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: avbroot-${{ steps.get_version.outputs.version }}-${{ matrix.artifact.name }}
|
||||
path: |
|
||||
|
||||
@@ -13,4 +13,4 @@ jobs:
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
|
||||
- name: Run cargo-deny
|
||||
uses: EmbarkStudios/cargo-deny-action@e2f4ede4a4e60ea15ff31bc0647485d80c66cfba # v2.0.4
|
||||
uses: EmbarkStudios/cargo-deny-action@34899fc7ba81ca6268d5947a7a16b4649013fea1 # v2.0.11
|
||||
|
||||
@@ -27,7 +27,7 @@ jobs:
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
|
||||
- name: Create release
|
||||
uses: softprops/action-gh-release@c95fe1489396fe8a9eb87c0abf8aa5b2ef267fda # v2.2.1
|
||||
uses: softprops/action-gh-release@da05d552573ad5aba039eaac05058a918a7bf631 # v2.2.2
|
||||
with:
|
||||
tag_name: v${{ steps.get_version.outputs.version }}
|
||||
name: Version ${{ steps.get_version.outputs.version }}
|
||||
|
||||
@@ -7,6 +7,61 @@
|
||||
to update the actual links at the bottom of the file.
|
||||
-->
|
||||
|
||||
### Version 3.17.1
|
||||
|
||||
* Update end-to-end tests to place streaming and seekable OTAs in separate directories for easier troubleshooting ([PR #463])
|
||||
* Update dependencies ([PR #464])
|
||||
* Add support for Magisk 30000 ([PR #467])
|
||||
|
||||
### Version 3.17.0
|
||||
|
||||
* Fix reserved space error when patching OTA zips larger than ~10 GB ([Issue #451], [PR #452])
|
||||
* Update dependencies ([PR #453])
|
||||
|
||||
### Version 3.16.1
|
||||
|
||||
* Add support for Magisk 29000 ([PR #448])
|
||||
* Update dependencies ([PR #449])
|
||||
|
||||
### Version 3.16.0
|
||||
|
||||
* Add support for CoW version 3 for virtual A/B ([Issue #441], [PR #442], [PR #445])
|
||||
* This was recently introduced with the Pixel 9a. Previous devices all used CoW version 2.
|
||||
* Add support for uncompressed CoW for virtual A/B ([PR #443])
|
||||
* This is not used on actual devices, but is very useful for testing the CoW estimation logic.
|
||||
* All differences between avbroot's and AOSP delta_generator's estimation logic are now fixed.
|
||||
* Add support for custom CoW compression levels for virtual A/B ([PR #444])
|
||||
* This is also not used on actual devices, but is supported by AOSP, so avbroot should support it too.
|
||||
* Update dependencies ([PR #446])
|
||||
|
||||
### Version 3.15.0
|
||||
|
||||
* Add support for changing the virtual A/B compression algorithm ([PR #437])
|
||||
* For devices that launched with Android <14, `--vabc-algo lz4` can significantly increase OTA installation speed when using a custom OTA updater app (with caveats). There is no difference when sideloading from recovery mode.
|
||||
* See [the documentation](./README.md#changing-virtual-ab-cow-compression-algorithm) for more details.
|
||||
* Switch back to the ring library now that it is maintained again ([PR #438])
|
||||
* Update dependencies ([PR #439])
|
||||
|
||||
### Version 3.14.0
|
||||
|
||||
* Report as many errors as possible before failing in `avbroot ota verify` and improve error messages ([Discussion #426], [PR #428], [PR #430])
|
||||
* Fix new clippy warnings introduced in Rust 1.85 ([PR #429])
|
||||
* Fix massive performance regression introduced in 3.13.0 for OTAs that use gzip for virtual A/B CoW compression ([Issue #433], [PR #434])
|
||||
* Update dependencies ([PR #435])
|
||||
|
||||
### Version 3.13.0
|
||||
|
||||
* Fix parsing Samsung `super.img` files in `avbroot lp` due to Samsung putting their own data structures in a region that's supposed to be filled with zeros ([PR #415])
|
||||
* Add advanced option to skip replacing the OTA certificate in the system image ([Discussion #417], [PR #418])
|
||||
* Switch to stable bzip2-rs release and use zlib-rs as the backend for flate2 ([PR #421])
|
||||
* Switch to the aws-lc cryptography library for SHA1 and SHA2 hashing ([PR #422])
|
||||
* The ring library is no longer maintained
|
||||
* Fix incorrect `Partitions aren't protected by AVB: system` warning when using `--skip-system-ota-cert` ([PR #423])
|
||||
* Discard unneeded temp file sooner when using `--skip-system-ota-cert` ([PR #424])
|
||||
* Make `avbroot lp`'s parser less strict so that it can load on-device `super` partitions ([PR #425])
|
||||
* The on-disk layout on virtual A/B devices violates some requirements stated in AOSP's documentation
|
||||
* Update dependencies ([PR #427])
|
||||
|
||||
### Version 3.12.0
|
||||
|
||||
* Add new `-p <name>` option to `avbroot ota extract` for extracting specific partitions ([PR #408])
|
||||
@@ -280,6 +335,8 @@ Behind-the-scenes changes:
|
||||
[Discussion #235]: https://github.com/chenxiaolong/avbroot/discussions/235
|
||||
[Discussion #286]: https://github.com/chenxiaolong/avbroot/discussions/286
|
||||
[Discussion #294]: https://github.com/chenxiaolong/avbroot/discussions/294
|
||||
[Discussion #417]: https://github.com/chenxiaolong/avbroot/discussions/417
|
||||
[Discussion #426]: https://github.com/chenxiaolong/avbroot/discussions/426
|
||||
[Issue #138]: https://github.com/chenxiaolong/avbroot/issues/138
|
||||
[Issue #144]: https://github.com/chenxiaolong/avbroot/issues/144
|
||||
[Issue #145]: https://github.com/chenxiaolong/avbroot/issues/145
|
||||
@@ -306,6 +363,9 @@ Behind-the-scenes changes:
|
||||
[Issue #356]: https://github.com/chenxiaolong/avbroot/issues/356
|
||||
[Issue #366]: https://github.com/chenxiaolong/avbroot/issues/366
|
||||
[Issue #393]: https://github.com/chenxiaolong/avbroot/issues/393
|
||||
[Issue #433]: https://github.com/chenxiaolong/avbroot/issues/433
|
||||
[Issue #441]: https://github.com/chenxiaolong/avbroot/issues/441
|
||||
[Issue #451]: https://github.com/chenxiaolong/avbroot/issues/451
|
||||
[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
|
||||
@@ -444,3 +504,31 @@ Behind-the-scenes changes:
|
||||
[PR #409]: https://github.com/chenxiaolong/avbroot/pull/409
|
||||
[PR #410]: https://github.com/chenxiaolong/avbroot/pull/410
|
||||
[PR #411]: https://github.com/chenxiaolong/avbroot/pull/411
|
||||
[PR #415]: https://github.com/chenxiaolong/avbroot/pull/415
|
||||
[PR #418]: https://github.com/chenxiaolong/avbroot/pull/418
|
||||
[PR #421]: https://github.com/chenxiaolong/avbroot/pull/421
|
||||
[PR #422]: https://github.com/chenxiaolong/avbroot/pull/422
|
||||
[PR #423]: https://github.com/chenxiaolong/avbroot/pull/423
|
||||
[PR #424]: https://github.com/chenxiaolong/avbroot/pull/424
|
||||
[PR #425]: https://github.com/chenxiaolong/avbroot/pull/425
|
||||
[PR #427]: https://github.com/chenxiaolong/avbroot/pull/427
|
||||
[PR #428]: https://github.com/chenxiaolong/avbroot/pull/428
|
||||
[PR #429]: https://github.com/chenxiaolong/avbroot/pull/429
|
||||
[PR #430]: https://github.com/chenxiaolong/avbroot/pull/430
|
||||
[PR #434]: https://github.com/chenxiaolong/avbroot/pull/434
|
||||
[PR #435]: https://github.com/chenxiaolong/avbroot/pull/435
|
||||
[PR #437]: https://github.com/chenxiaolong/avbroot/pull/437
|
||||
[PR #438]: https://github.com/chenxiaolong/avbroot/pull/438
|
||||
[PR #439]: https://github.com/chenxiaolong/avbroot/pull/439
|
||||
[PR #442]: https://github.com/chenxiaolong/avbroot/pull/442
|
||||
[PR #443]: https://github.com/chenxiaolong/avbroot/pull/443
|
||||
[PR #444]: https://github.com/chenxiaolong/avbroot/pull/444
|
||||
[PR #445]: https://github.com/chenxiaolong/avbroot/pull/445
|
||||
[PR #446]: https://github.com/chenxiaolong/avbroot/pull/446
|
||||
[PR #448]: https://github.com/chenxiaolong/avbroot/pull/448
|
||||
[PR #449]: https://github.com/chenxiaolong/avbroot/pull/449
|
||||
[PR #452]: https://github.com/chenxiaolong/avbroot/pull/452
|
||||
[PR #453]: https://github.com/chenxiaolong/avbroot/pull/453
|
||||
[PR #463]: https://github.com/chenxiaolong/avbroot/pull/463
|
||||
[PR #464]: https://github.com/chenxiaolong/avbroot/pull/464
|
||||
[PR #467]: https://github.com/chenxiaolong/avbroot/pull/467
|
||||
|
||||
Generated
+529
-323
File diff suppressed because it is too large
Load Diff
+2
-2
@@ -4,9 +4,9 @@ members = ["avbroot", "e2e", "fuzz", "xtask"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
version = "3.12.0"
|
||||
version = "3.17.1"
|
||||
license = "GPL-3.0-only"
|
||||
edition = "2021"
|
||||
edition = "2024"
|
||||
repository = "https://github.com/chenxiaolong/avbroot"
|
||||
|
||||
[workspace.lints.clippy]
|
||||
|
||||
@@ -2,12 +2,10 @@
|
||||
|
||||
(This page is also available in: [Russian (Русский)](./README.ru.md).)
|
||||
|
||||
avbroot is a program for patching Android A/B-style OTA images for root access while preserving AVB (Android Verified Boot) using custom signing keys. It is compatible with both Magisk and KernelSU. If desired, it can also just re-sign an OTA without enabling root access.
|
||||
avbroot is a tool for modifying Android A/B OTA images reproducibly and re-signing them with custom keys. It also includes a [collection of subcommands](./README.extra.md) for packing and unpacking numerous Android image formats.
|
||||
|
||||
Having a good understanding of how AVB and A/B OTAs work is recommended prior to using avbroot. At the very least, please make sure the [warnings and caveats](#warnings-and-caveats) are well-understood to avoid the risk of hard bricking.
|
||||
|
||||
**NOTE:** avbroot 2.0 has been rewritten in Rust and no longer relies on any AOSP code. The CLI is fully backwards compatible, but the old Python implementation can be found in the `python` branch if needed.
|
||||
|
||||
## Requirements
|
||||
|
||||
* Only devices that use modern A/B partitioning are supported. This is the case for most non-Samsung devices launched with Android 10 or newer. To check if a device uses this partitioning scheme, open the OTA zip file and check that:
|
||||
@@ -23,7 +21,7 @@ Having a good understanding of how AVB and A/B OTAs work is recommended prior to
|
||||
|
||||
avbroot applies the following patches to the partition images:
|
||||
|
||||
* The `boot` or `init_boot` image, depending on device, is patched to enable root access. For Magisk, the patch is equivalent to what would be normally done by the Magisk app.
|
||||
* The `boot` or `init_boot` image, depending on device, is patched to enable root access if requested.
|
||||
|
||||
* The `boot`, `recovery`, or `vendor_boot` image, depending on device, is patched to replace the OTA signature verification certificates with the custom OTA signing certificate. This allows future patched OTAs to be sideloaded from recovery mode after the bootloader has been locked. It also prevents accidental flashing of the original unpatched OTA.
|
||||
|
||||
@@ -31,7 +29,7 @@ avbroot applies the following patches to the partition images:
|
||||
|
||||
## Warnings and Caveats
|
||||
|
||||
* **Always leave the `OEM unlocking` checkbox enabled when using a locked bootloader with root.** This is critically important. Root access allows the boot partition to potentially be overwritten, either accidentally or intentionally, with an image that is not properly signed. In this scenario, if the checkbox is turned off, both the OS and recovery mode will be made unbootable and `fastboot flashing unlock` will not be allowed. This effectively renders the device **_hard bricked_**.
|
||||
* **Always leave the `OEM unlocking` checkbox enabled when using a locked bootloader while rooted.** This is critically important. Root access allows the boot partition to potentially be overwritten, either accidentally or intentionally, with an image that is not properly signed. In this scenario, if the checkbox is turned off, both the OS and recovery mode will be made unbootable and `fastboot flashing unlock` will not be allowed. This effectively renders the device **_hard bricked_**.
|
||||
|
||||
Repeat: **_ALWAYS leave `OEM unlocking` enabled if rooted._**
|
||||
|
||||
@@ -53,6 +51,8 @@ avbroot applies the following patches to the partition images:
|
||||
|
||||
3. Follow the steps to [generate signing keys](#generating-keys).
|
||||
|
||||
Skip this step if you're updating Android, Magisk, or KernelSU after you've performed an [initial setup](#initial-setup). [Updates](#updates) do not require signing keys since you have already generated them in the initial setup.
|
||||
|
||||
4. Patch the OTA zip. The base command is:
|
||||
|
||||
```bash
|
||||
@@ -225,21 +225,25 @@ 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.
|
||||
|
||||
10. That's it! To install future OS, Magisk, or KernelSU updates, see the [next section](#updates).
|
||||
10. That's it! To update the OS, Magisk, or KernelSU see the [next section](#updates).
|
||||
|
||||
## Updates
|
||||
|
||||
Updates to Android, Magisk, and KernelSU are all done the same way by patching (or repatching) the OTA.
|
||||
Updates to Android, Magisk, and KernelSU are all done the same way: by patching (or repatching) the OTA.
|
||||
|
||||
1. If Magisk or KernelSU is being updated, first install their new `.apk`. If you happen to open the app, make sure it **does not** flash the boot image. Cancel the boot image update prompts if needed.
|
||||
1. Generate a new patched OTA by following the steps in the [usage section](#usage).
|
||||
|
||||
2. Follow the step in the [usage section](#usage) to patch the new OTA.
|
||||
2. If Magisk or KernelSU is being updated, first install their new `.apk`. If you happen to open the app, make sure it **does not** flash the boot image. Cancel the boot image update prompts if needed.
|
||||
|
||||
3. Reboot to recovery mode. If the screen is stuck at a `No command` message, press the volume up button once while holding down the power button.
|
||||
|
||||
4. Sideload the patched OTA with `adb sideload`.
|
||||
|
||||
5. That's it!
|
||||
5. Restart your phone. Note: the phone will likely take a long time to startup after an OS update (a few minutes in some cases).
|
||||
|
||||
**Warning**: Due to how virtual A/B works, there is a snapshot merge operation that Android runs invisibly in the background after installing an OTA and rebooting. During the snapshot merge process, it's not possible to sideload another OTA from recovery mode. Avoid doing anything that could result in a boot loop (eg. installing modules) until this process is complete because there is no way to recover, aside from unlocking the bootloader (and wiping) again.
|
||||
|
||||
The status can be found by running `adb logcat -v color -s update_engine`. Alternatively, if [Custota](https://github.com/chenxiaolong/Custota) is installed (even if it's not configured to point to a custom OTA server), it will show a notification until the snapshot merge operation completes.
|
||||
|
||||
## Reverting to stock firmware
|
||||
|
||||
@@ -384,11 +388,28 @@ Note that avbroot will validate that the prepatched image is compatible with the
|
||||
|
||||
avbroot can be used for just re-signing an OTA by specifying `--rootless` instead of `--magisk`/`--prepatched`. With this option, the patched OTA will not be rooted. The only modification applied is the replacement of the OTA verification certificate so that the OS can be upgraded with future (patched) OTAs.
|
||||
|
||||
### Skipping recovery OTA certificate patches
|
||||
### Skipping OTA certificate patches
|
||||
|
||||
avbroot can skip modifying `otacerts.zip` in the recovery image with the `--skip-recovery-ota-cert` option. **Do not do this unless you have a good reason to do so.** (For example, if you've already manually inserted the OTA certificate into a boot image specified with `--prepatched` or `--replace`.) When this option is used with `--rootless` (and `--dsu` is not specified), then no modifications are performed on any boot image besides ensuring they are properly signed.
|
||||
avbroot can skip modifying `otacerts.zip` with the `--skip-system-ota-cert` and `--skip-recovery-ota-cert` options. **Do not use these unless you have a good reason to do so.**
|
||||
|
||||
When manually adding the OTA certificate to a boot image, [verifying the patched OTA](#verifying-otas) afterwards is recommended to ensure that it was properly done.
|
||||
When `--skip-system-ota-cert` is used, the OTA certificates in the `system` partition will not be modified. This prevents custom OTA updater apps from installing further patched OTAs while booted into Android.
|
||||
|
||||
When `--skip-recovery-ota-cert` is used, the OTA certificates in the `vendor_boot` or `recovery` partition will not be modified. **This prevents sideloading further patched OTAs from recovery mode.**
|
||||
|
||||
If `--skip-recovery-ota-cert` is used because the OTA certificate was already manually added to the boot image, then [verifying the patched OTA](#verifying-otas) afterwards is recommended to ensure that it was properly done. The verification process is only capable of checking the boot image's copy of the OTA certificates, not the system image's copy of them.
|
||||
|
||||
### Skipping all patches
|
||||
|
||||
To have avbroot make the absolute minimal changes:
|
||||
|
||||
* Specify `--skip-system-ota-cert`
|
||||
* Specify `--skip-recovery-ota-cert`
|
||||
* Specify `--rootless`
|
||||
* Omit `--dsu`
|
||||
|
||||
This will re-sign the `vbmeta` partition and the OTA with the custom keys, but leave all other partitions untouched.
|
||||
|
||||
**This should only be used for advanced troubleshooting.** Without the OTA certificate patches, the resulting OTA will not be able to install further updates.
|
||||
|
||||
### Replacing partitions
|
||||
|
||||
@@ -414,6 +435,18 @@ Verified boot is disabled by vbmeta's header flags: 0x3
|
||||
|
||||
To forcibly enable AVB (by clearing the flags), pass in `--clear-vbmeta-flags`.
|
||||
|
||||
### Changing virtual A/B CoW compression algorithm
|
||||
|
||||
The virtual A/B CoW compression algorithm can be changed by passing in `--vabc-algo <algo>` with `gz` or `lz4`. OTAs normally use an algorithm that is compatible with the initial version of Android shipped on the device.
|
||||
|
||||
* Devices launching with Android 12 support `gz` and `brotli` (unsupported by avbroot)
|
||||
* Devices launching with Android 14 support `lz4`
|
||||
* Devices launching with Android 15 support `zstd` (unsupported by avbroot)
|
||||
|
||||
Picking a fast algorithm, like lz4, can speed up OTA installation significantly when installing via a custom OTA updater app. However, there is no performance difference when sideloading an OTA from recovery mode.
|
||||
|
||||
Note that the currently running version of Android must support the specified compression algorithm or else the OTA will fail to install. For example, trying to install an Android 14 OTA that uses lz4 CoW compression will fail if the running system is Android 13.
|
||||
|
||||
### Non-interactive use
|
||||
|
||||
avbroot prompts for the private key passphrases interactively by default. To run avbroot non-interactively, either:
|
||||
|
||||
+97
-19
@@ -1,11 +1,9 @@
|
||||
# avbroot
|
||||
|
||||
avbroot – это программа для модификации OTA-образов Android A/B-формата с целью получения root-прав при сохранении прохождения AVB (Android Verified Boot) с использованием кастомных (пользовательских) ключей подписи. Она совместима как с Magisk, так и с KernelSU. При необходимости можно просто переподписать OTA, без получения root-доступа.
|
||||
avbroot – это утилита для воспроизводимой модификации OTA-образов Android A/B-формата и их переподписания пользовательскими ключами. Она также включает в себя [набор подкоманд](./README.extra.md) для упаковки и распаковки образов Android различных форматов.
|
||||
|
||||
Прежде чем использовать avbroot, рекомендуется иметь хорошее понимание того, как работают AVB и OTA в формате A/B. Как минимум, следует ознакомиться с [разделом предостережений,](#предостережения) чтобы избежать хардбрика устройства.
|
||||
|
||||
**ПРИМЕЧАНИЕ:** avbroot 2.0 была переписана на Rust и больше не имеет в основе никакого кода AOSP, а CLI полностью обратно совместим. Тем не менее, старую реализацию на Python можно найти в одноименной ветке `python`.
|
||||
|
||||
## Требования
|
||||
|
||||
* Поддерживаются только устройства, использующие современную A/B-разметку. Это большинство девайсов, выпускаемых с Android 10 и новее (за исключением устройств от Samsung). Чтобы проверить, использует ли ваш телефон необходимую схему разметки, откройте zip-архив OTA и проверьте:
|
||||
@@ -21,7 +19,7 @@ avbroot – это программа для модификации OTA-обра
|
||||
|
||||
avbroot модифицирует следующие образы:
|
||||
|
||||
* `boot` или `init_boot`, в зависимости от устройства, модифицируется для получения root-доступа. В случае с Magisk, патч будет эквивалентен тому, что производится в самом приложении Magisk.
|
||||
* `boot` или `init_boot`, в зависимости от устройства, модифицируется для получения root-доступа, если это запрашивается.
|
||||
|
||||
* `boot`, `recovery` или `vendor_boot`, в зависимости от устройства, модифицируется для замены сертификата проверки подписи OTA на пользовательский. Это позволяет устанавливать будущие пропатченные OTA через режим Recovery уже после блокировки загрузчика, то есть в качестве обновления. Также это предотвращает случайную установку оригинального непропатченного OTA.
|
||||
|
||||
@@ -122,7 +120,7 @@ avbroot модифицирует следующие образы:
|
||||
avbroot key encode-avb -k avb.key -o avb_pkmd.bin
|
||||
```
|
||||
|
||||
3. Сгенерируйте самоподписанный сертификат для ключа подписи OTA. Он используется режимом Recovery для проверки подписи OTA при сайдлоадинге обновления.
|
||||
3. Сгенерируйте самоподписанный сертификат для ключа подписи OTA. Он используется режимом Recovery для проверки подписи OTA при установке обновления.
|
||||
|
||||
```bash
|
||||
avbroot key generate-cert -k ota.key -o ota.crt
|
||||
@@ -185,7 +183,7 @@ avbroot совместим с любым стандартным 4096-битны
|
||||
fastboot flashall --skip-reboot
|
||||
```
|
||||
|
||||
Обратите внимание, что так прошиваются лишь те образы, что относятся к системе. Разделы загрузчика и модема же остаются нетронутыми из-за ограничений fastboot. Если они не обновлены до необходимой версии, или вы не уверены в этом, после прошивки перейдите к пункту [обновлений](#обновления) и установите пропатченный OTA-архив сайдлоадом в режиме Recovery. Прошивка полного OTA гарантирует, что абсолютно все разделы будут обновлены.
|
||||
Обратите внимание, что так прошиваются лишь те образы, что относятся к системе. Разделы загрузчика и модема же остаются нетронутыми из-за ограничений fastboot. Если они не обновлены до необходимой версии, или вы не уверены в этом, после прошивки перейдите к пункту [обновлений](#обновления) и установите пропатченный OTA в режиме Recovery. Прошивка полного OTA гарантирует, что абсолютно все разделы будут обновлены.
|
||||
|
||||
Для устройств Pixel есть ещё один вариант: запуск скрипта `flash-base.sh` из папки заводских образов (factory images) обновит загрузчик и модем.
|
||||
|
||||
@@ -255,11 +253,11 @@ avbroot совместим с любым стандартным 4096-битны
|
||||
|
||||
## OTA-обновления
|
||||
|
||||
avbroot заменяет `/system/etc/security/otacerts.zip` в разделах системы и Recovery на новый архив, содержащий пользовательский сертификат подписи OTA. Это предотвращает случайную установку непропатченных OTA как при загрузке в Android, так и при сайдлоадинге через Recovery.
|
||||
avbroot заменяет `/system/etc/security/otacerts.zip` в разделах системы и Recovery на новый архив, содержащий пользовательский сертификат подписи OTA. Это предотвращает случайную установку непропатченных OTA как из-под загруженной системы, так и при прошивке через Recovery.
|
||||
|
||||
Рекомендуется отключить приложение обновлений системы, чтобы оно не пыталось установить непропатченные OTA:
|
||||
Рекомендуется отключить системное приложение для обновлений, чтобы оно не пыталось установить непропатченные OTA:
|
||||
|
||||
* Стоковая прошивка: Отключите `Автоматические обновления системы` (Automatic system updates в англ.) в настройках для разработчиков.
|
||||
* Стоковая (заводская) прошивка: Отключите `Автоматические обновления системы` (Automatic system updates в англ.) в настройках для разработчиков.
|
||||
* Кастомная прошивка: Отключите приложение обновлений системы (или запретите ему доступ к Интернету) через Настройки -> Приложения -> Все приложения -> (меню/три точки) -> Показать системные -> (найдите приложение обновлений, например Обновления системы/Updater).
|
||||
|
||||
Это особенно важно для некоторых кастомных прошивок, поскольку их фирменное приложение для обновления системы может уйти в бесконечный цикл, загружая OTA-обновление, а затем повторяя попытку загрузки и установки при неудачной проверке подписи.
|
||||
@@ -295,6 +293,7 @@ Magisk версии 25211 и новее требует наличие разде
|
||||
--input /path/to/ota.zip \
|
||||
--directory . \
|
||||
--boot-only
|
||||
--partition <название раздела> # init_boot или boot, в зависимости от устройства
|
||||
```
|
||||
|
||||
2. Теперь нужно пропатчить загрузочный образ с помощью приложения Magisk. Это **ДОЛЖНО** быть сделано именно на целевом устройстве или устройстве той же модели! Имя раздела будет неверным и не подойдет, если пропатчить образ на устройстве иной модели.
|
||||
@@ -381,17 +380,34 @@ avbroot может подменить используемый загрузоч
|
||||
|
||||
avbroot можно использовать для простого переподписания OTA, указав аргумент `--rootless` вместо `--magisk`/`--prepatched`. В таком случае пропатченный OTA не будет рутирован. Единственная модификация, которая будет применена – это замена сертификата проверки OTA, чтобы систему можно было обновлять с помощью будущих пропатченных OTA.
|
||||
|
||||
### Пропуск патчинга сертификата OTA в разделе Recovery
|
||||
### Пропуск патчинга сертификата OTA
|
||||
|
||||
avbroot может пропустить изменение файла `otacerts.zip` в разделе Recovery с помощью опции `--skip-recovery-ota-cert`. **Не используйте эту функцию, если на то нет веской причины.** (Например, если вы уже самостоятельно встроили сертификат OTA в загрузочный образ (`boot.img`) и передаете его программе через опции `--prepatched` или `--replace`.) Если эта опция применяется совместно с `--rootless` (и без указания параметра `--dsu`), то в загрузочный образ не будут внесены никакие изменения, кроме обеспечения его корректной подписи.
|
||||
Вы можете пропустить изменение otacerts.zip, используя аргументы `--skip-system-ota-cert` и `--skip-recovery-ota-cert`. **Не используйте их без веской причины.**
|
||||
|
||||
Если вы вручную добавили сертификат OTA в загрузочный образ, рекомендуем [предварительно проверить пропатченный OTA.](#проверка-ota)
|
||||
При использовании `--skip-system-ota-cert`, сертификаты OTA в образе `system` изменены не будут. Это не позволит сторонним приложениям для OTA-обновлений устанавливать будущие пропатченные OTA из-под загруженной системы.
|
||||
|
||||
### Подмена разделов
|
||||
При использовании `--skip-recovery-ota-cert`, сертификаты OTA в образах `vendor_boot` или `recovery` изменены не будут. **Это не позволит устанавливать будущие пропатченные OTA в режиме Recovery.**
|
||||
|
||||
avbroot поддерживает подмену целых образов в OTA, даже тех, что не являются загрузочными (например, `vendor_dlkm`). Образ можно заменить, указав аргумент `--replace <имя раздела> /путь/к/образу.img`.
|
||||
Если вы используете аргумент `--skip-recovery-ota-cert`, потому что уже добавили сертификат OTA в загрузочный образ вручную, рекомендуетcя [проверить пропатченный OTA](#проверка-ota), дабы удостовериться, что замена произведена корректно. Процесс верификации проверяет только копию сертификатов OTA в загрузочном образе, не проверяя копию в образе системы.
|
||||
|
||||
Единственное, что меняется – это то, откуда считывается раздел. При использовании `--replace` вместо использования образа раздела из оригинального `payload.bin` в OTA, он берется напрямую по указанному вами пути. Таким образом, заменяющие образы разделов должны иметь правильные колонтитулы vbmeta, соответствующие оригинальным.
|
||||
### Пропуск всех патчей
|
||||
|
||||
Чтобы внести самый минимум изменений, укажите аргументы:
|
||||
|
||||
* `--skip-system-ota-cert`
|
||||
* `--skip-recovery-ota-cert`
|
||||
* `--rootless`
|
||||
* не используйте аргумент `--dsu`.
|
||||
|
||||
Так, пользовательскими ключами будут переподписаны лишь образ `vbmeta` и OTA, остальные разделы останутся нетронутыми.
|
||||
|
||||
**Это следует использовать только для устранения неполадок.** Без патчей сертификатов, поверх полученного OTA не получится установить никакие обновления.
|
||||
|
||||
### Подмена образов
|
||||
|
||||
avbroot поддерживает подмену целых образов в OTA, даже тех, что не являются загрузочными (например, `vendor_dlkm`). Образ можно заменить, используя аргумент `--replace <имя раздела> /путь/к/образу.img`.
|
||||
|
||||
Единственное, что меняется – это то, откуда считывается файл. При использовании `--replace` вместо образа раздела из оригинального `payload.bin` в OTA, он берется напрямую по указанному вами пути. Заменяющие образы разделов должны иметь правильные колонтитулы vbmeta, соответствующие оригинальным.
|
||||
|
||||
Это не влияет на ход применения пачтей. Например, при использовании Magisk, патч получения root-прав применяется к загрузочному образу одинаково, независимо от того, был ли он получен из оригинального `payload.bin` или это файл, указанный через `--replace`.
|
||||
|
||||
@@ -405,6 +421,18 @@ Verified boot is disabled by vbmeta's header flags: 0x3
|
||||
|
||||
Чтобы принудительно включить AVB (очистив флаги), укажите аргумент `--clear-vbmeta-flags`.
|
||||
|
||||
### Изменение алгоритма CoW сжатия для вирутального A/B
|
||||
|
||||
Алгоритм CoW (copy-on-write) сжатия для виртуального A/B можно изменить, используя аргумент `--vabc-algo <алгоритм>`, указав `gz` или `lz4`. Как правило, по умолчанию OTA использует алгоритм, который совместим с изначальной версией Android, на которой поставлялось устройство.
|
||||
|
||||
* Девайсы, поставляемые с Android 12, поддерживают `gz` и `brotli` (последний не поддерживается avbroot)
|
||||
* Девайсы, поставляемые с Android 14, поддерживают `lz4`
|
||||
* Девайсы, поставляемые с Android 15, поддерживают `zstd` (не поддерживается avbroot)
|
||||
|
||||
Выбор быстрого алгоритма, такого как lz4, может значительно ускорить установку OTA из-под системы (при использованием стороннего приложения для OTA-обновлений). Однако, при установке OTA в режиме Recovery, разницы в скорости не будет.
|
||||
|
||||
Обратите внимание, что текущая используемая версия Android должна поддерживать выбранный алгоритм сжатия. В противном случае установка завершится ошибкой. Например, попытка установить OTA-обновление с Android 14, использующее алгоритм lz4, приведет к ошибке, если установка производится из-под Android 13.
|
||||
|
||||
### Использование в неинтерактивном режиме
|
||||
|
||||
По умолчанию avbroot интерактивно запрашивает пароли к приватным ключам. Чтобы запустить avbroot в неинтерактивном режиме, можно:
|
||||
@@ -441,17 +469,20 @@ Verified boot is disabled by vbmeta's header flags: 0x3
|
||||
|
||||
* Использовать незашифрованные приватные ключи. Крайне не рекомендуется.
|
||||
|
||||
### Извлечение всей OTA
|
||||
### Извлечение образов из OTA
|
||||
|
||||
Чтобы извлечь все образы, содержащиеся в `payload.bin`, используйте команду:
|
||||
Чтобы извлечь образы разделов, содержащихся в `payload.bin`, используйте команду:
|
||||
|
||||
```bash
|
||||
avbroot ota extract \
|
||||
--input /путь/к/ota.zip \
|
||||
--directory extracted \
|
||||
--all
|
||||
--directory extracted
|
||||
```
|
||||
|
||||
По умолчанию извлекаются только те образы, которые потенциально могут быть пропатчены с помощью avbroot. Чтобы извлечь все образы, используйте опцию `--all`. Для извлечения конкретных образов используйте опцию `--partition <название раздела>`, которую можно указать несколько раз.
|
||||
|
||||
Эта команда также поддерживает извлечение встроенного сертификата OTA и публичного ключа AVB с помощью опций `--cert-ota` и `--public-key-avb`. Чтобы извлечь только эти компоненты, укажите аргумент `--none`, чтобы пропустить извлечение образов разделов.
|
||||
|
||||
### Режим записи ZIP
|
||||
|
||||
По умолчанию, avbroot использует потоковую запись для вывода OTA во время патчинга. Это означает, что он вычисляет дайджест sha256 для цифровой подписи одновременно с записью файла. Такой режим приводит к тому, что в ZIP-файле появляются описатели данных, что является частью стандарта ZIP и работает на подавляющем большинстве устройств. Однако некоторые устройства могут иметь некорректно работающие парсеры ZIP-файлов и не смогут правильно прочитать ZIP-файлы OTA, содержащие описатели данных. Если это так, используйте опцию `--zip-mode seekable` при патчинге.
|
||||
@@ -480,6 +511,53 @@ avbroot поддерживает делегирование всех опера
|
||||
|
||||
Обратите внимание, что avbroot проверит подпись, возвращенную внешней программой, на соответствие с публичным ключом. Это гарантирует, что процесс патчинга завершится ошибкой, если был использован неправильный приватный ключ.
|
||||
|
||||
### Размер страницы 16 КБ в настройках для разработчиков
|
||||
|
||||
На современных устройствах с Android 16 и выше, в настройках для разработчиков может появиться опция переключения на ядро с размером страницы 16 КБ. Однако, эта функция не будет работать в системе, пропатченной с помощью avbroot, поскольку переключение данной настройки осуществляется путём установки инкрементальной OTA:
|
||||
|
||||
* `/vendor/boot_otas/boot_ota_16k.zip` — используется для переключения на ядро с размером страницы 16 КБ (в разделе `boot` уже должно быть прошито ядро с размером страницы 4K)
|
||||
* `/vendor/boot_otas/boot_ota_4k.zip` — используется для переключения на ядро с размером страницы 4 КБ (в разделе `boot` уже должно быть прошито ядро с размером страницы 16K)
|
||||
|
||||
Эти файлы (в `boot_otas`) невозможно прошить на системе, пропатченной avbroot, потому что `payload.bin` внутри них подписан ключом производителя. Кроме того, это неполноценные OTA-файлы: у них нет метаданных, характерных для OTA, а сам zip-файл не подписан. Это просто обычный архив, который содержит подписанный `payload.bin`.
|
||||
|
||||
Поддержка `boot_otas` не планируется. Это потребует реализации функционала для модификации ФС в инкрементальных OTA и их дальнейшей обработки, что сделать очень непросто.
|
||||
|
||||
Если вы всё же хотите завести эту функцию, можно попробовать вручную подписать файлы в `boot_otas` собственным ключом. Поскольку инкрементальные OTA не пересоздаются, раздел `boot` должен оставаться без изменений во время выполнения команды `avbroot ota patch`.
|
||||
|
||||
1. Распакуйте `vendor.img` с помощью avbroot и [afsr](https://github.com/chenxiaolong/afsr):
|
||||
```bash
|
||||
avbroot avb unpack -i vendor.img
|
||||
afsr unpack -i raw.img
|
||||
```
|
||||
|
||||
2. Извлеките `payload.bin` из `boot_otas/boot_ota_16k.zip`.
|
||||
|
||||
3. Переподпишите `payload.bin` вашим OTA-ключом:
|
||||
```bash
|
||||
avbroot payload repack \
|
||||
-i payload.bin.orig \
|
||||
-o payload.bin \
|
||||
-k ota.key \
|
||||
--output-properties payload_properties.txt
|
||||
```
|
||||
|
||||
4. Создайте новый zip, включающий `payload.bin` и `payload_properties.txt`. Файлы должны быть добавлены без сжатия (например, с помощью `zip -0`).
|
||||
|
||||
5. Повторите эту процедуру для `boot_otas/boot_ota_4k.zip`.
|
||||
|
||||
6. Соберите `vendor.img` обратно и подпишите его вашим AVB-ключом:
|
||||
```bash
|
||||
afsr pack -o raw.img
|
||||
avbroot avb pack -o vendor.img -k avb.key --recompute-size
|
||||
```
|
||||
|
||||
7. Пропатчите обычный OTA-архив с прошивкой, подменив `vendor` на модифицированный образ:
|
||||
```bash
|
||||
avbroot ota patch \
|
||||
--replace vendor <модифицированный vendor.img> \
|
||||
<дальше указываются аргументы, как при обычном патчинге>
|
||||
```
|
||||
|
||||
## Сборка из исходного кода
|
||||
|
||||
Убедитесь, что у вас установлен [набор инструментов Rust.](https://www.rust-lang.org/ru/) Затем выполните:
|
||||
|
||||
+18
-20
@@ -13,28 +13,31 @@ anyhow = "1.0.75"
|
||||
base64 = "0.22.1"
|
||||
bitflags = { version = "2.4.1", features = ["serde"] }
|
||||
bstr = "1.6.2"
|
||||
bzip2 = "0.6.0"
|
||||
cap-std = "3.0.0"
|
||||
cap-tempfile = "3.0.0"
|
||||
clap = { version = "4.4.1", features = ["derive"] }
|
||||
clap_complete = "4.4.0"
|
||||
cms = { version = "0.2.2", features = ["std"] }
|
||||
# We can't upgrade to 0.10.0 until x509-cert updates it too, since it's part of
|
||||
# the public API.
|
||||
const-oid = "0.9.5"
|
||||
crc32fast = "1.4.2"
|
||||
ctrlc = "3.4.0"
|
||||
dlv-list = "0.6.0"
|
||||
flate2 = "1.0.27"
|
||||
flate2 = { version = "1.0.29", features = ["zlib-rs"] }
|
||||
gf256 = { version = "0.3.0", features = ["rs"] }
|
||||
hex = { version = "0.4.3", features = ["serde"] }
|
||||
liblzma = "0.3.0"
|
||||
liblzma = "0.4.1"
|
||||
lz4_flex = "0.11.1"
|
||||
memchr = "2.6.0"
|
||||
miniz_oxide = "0.8.0"
|
||||
num-bigint-dig = "0.8.4"
|
||||
num-traits = "0.2.16"
|
||||
passterm = "2.0.3"
|
||||
phf = { version = "0.11.2", features = ["macros"] }
|
||||
phf = { version = "0.12.1", features = ["macros"] }
|
||||
pkcs8 = { version = "0.10.2", features = ["encryption", "pem"] }
|
||||
prost = "0.13.1"
|
||||
prost = "0.14.1"
|
||||
# We can't upgrade to 0.9.0 until rsa updates its rand_core dependency.
|
||||
rand = "0.8.5"
|
||||
rayon = "1.7.0"
|
||||
regex = { version = "1.9.4", default-features = false, features = ["perf", "std"] }
|
||||
@@ -42,7 +45,7 @@ regex = { version = "1.9.4", default-features = false, features = ["perf", "std"
|
||||
# because sha2 is significantly slower on older x86_64 CPUs without the SHA-NI
|
||||
# instructions. sha2 is still used for signing purposes.
|
||||
# https://github.com/RustCrypto/hashes/issues/327
|
||||
ring = "0.17.0"
|
||||
ring = "0.17.14"
|
||||
rsa = { version = "0.9.2", features = ["sha1", "sha2"] }
|
||||
serde = { version = "1.0.188", features = ["derive"] }
|
||||
sha1 = "0.10.5"
|
||||
@@ -57,28 +60,23 @@ x509-cert = { version = "0.2.4", features = ["builder"] }
|
||||
zerocopy = { version = "0.8.10", features = ["std"] }
|
||||
zerocopy-derive = "0.8.5"
|
||||
|
||||
# Waiting for next stable release.
|
||||
[dependencies.bzip2]
|
||||
git = "https://github.com/trifectatechfoundation/bzip2-rs"
|
||||
rev = "09a87db73c0517a9715ab3fd96fbe4961d545aee"
|
||||
default-features = false
|
||||
features = ["libbz2-rs-sys"]
|
||||
|
||||
# https://github.com/zip-rs/zip/pull/383
|
||||
# https://github.com/zip-rs/zip2/pull/367
|
||||
# https://github.com/zip-rs/zip2/pull/368
|
||||
# For getting the data offset when writing new zip entries.
|
||||
[dependencies.zip]
|
||||
git = "https://github.com/chenxiaolong/zip"
|
||||
rev = "989101f9384b9e94e36e6e9e0f51908fdf98bde6"
|
||||
git = "https://github.com/chenxiaolong/zip2"
|
||||
rev = "59685f4dadbfee8cb3ea74c8fbb402b60d8137e8"
|
||||
default-features = false
|
||||
features = ["deflate"]
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2.158"
|
||||
rustix = { version = "0.38.9", default-features = false, features = ["process"] }
|
||||
rustix = { version = "1.0.3", default-features = false, features = ["process"] }
|
||||
|
||||
[build-dependencies]
|
||||
constcat = "0.5.0"
|
||||
prost-build = "0.13.1"
|
||||
protox = "0.7.0"
|
||||
constcat = "0.6.0"
|
||||
prost-build = "0.14.1"
|
||||
protox = "0.9.0"
|
||||
|
||||
[dev-dependencies]
|
||||
assert_matches = "1.5.0"
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::{
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::{Parser, Subcommand, ValueEnum};
|
||||
use tracing::{debug, Level};
|
||||
use tracing::{Level, debug};
|
||||
use tracing_subscriber::fmt::{format::Writer, time::FormatTime};
|
||||
|
||||
use crate::cli::{avb, boot, completion, cpio, fec, hashtree, key, lp, ota, payload, sparse};
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::{
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use cap_std::{
|
||||
ambient_authority,
|
||||
fs::{Dir, OpenOptions},
|
||||
@@ -19,7 +19,7 @@ use clap::{Args, Parser, Subcommand};
|
||||
use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
|
||||
use rsa::RsaPublicKey;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tracing::{debug_span, info, warn, Span};
|
||||
use tracing::{Span, debug_span, info, warn};
|
||||
|
||||
use crate::{
|
||||
crypto::{self, PassphraseSource, RsaSigningKey},
|
||||
@@ -27,7 +27,7 @@ use crate::{
|
||||
self, AlgorithmType, AppendedDescriptorMut, AppendedDescriptorRef, Descriptor, Footer,
|
||||
HashTreeDescriptor, Header, KernelCmdlineDescriptor,
|
||||
},
|
||||
stream::{self, check_cancel, PSeekFile, ReadFixedSizeExt, Reopen, ToWriter},
|
||||
stream::{self, PSeekFile, ReadFixedSizeExt, Reopen, ToWriter, check_cancel},
|
||||
util,
|
||||
};
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::{
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
use crate::{
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::{
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use bstr::ByteSlice;
|
||||
use cap_std::{ambient_authority, fs::Dir};
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::{
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use cap_std::{ambient_authority, fs::Dir};
|
||||
use clap::{CommandFactory, Parser, Subcommand};
|
||||
use rayon::iter::{
|
||||
|
||||
+473
-189
@@ -10,19 +10,21 @@ use std::{
|
||||
io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write},
|
||||
ops::Range,
|
||||
path::{Path, PathBuf},
|
||||
sync::{atomic::AtomicBool, Mutex},
|
||||
str::FromStr,
|
||||
sync::{Mutex, atomic::AtomicBool},
|
||||
};
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use bitflags::bitflags;
|
||||
use cap_std::{ambient_authority, fs::Dir};
|
||||
use cap_tempfile::TempDir;
|
||||
use clap::{value_parser, ArgAction, Args, Parser, Subcommand};
|
||||
use clap::{ArgAction, Args, Parser, Subcommand, value_parser};
|
||||
use rayon::{iter::IntoParallelRefIterator, prelude::ParallelIterator};
|
||||
use tempfile::NamedTempFile;
|
||||
use topological_sort::TopologicalSort;
|
||||
use tracing::{debug_span, info, warn};
|
||||
use tracing::{debug_span, error, info, warn};
|
||||
use x509_cert::Certificate;
|
||||
use zip::{write::FileOptions, CompressionMethod, ZipArchive, ZipWriter};
|
||||
use zip::{CompressionMethod, DateTime, ZipArchive, write::SimpleFileOptions};
|
||||
|
||||
use crate::{
|
||||
cli,
|
||||
@@ -31,7 +33,8 @@ use crate::{
|
||||
avb::{self, Descriptor, Header},
|
||||
ota::{self, SigningWriter, ZipEntry, ZipMode},
|
||||
padding,
|
||||
payload::{self, PayloadHeader, PayloadWriter, VabcAlgo},
|
||||
payload::{self, CowVersion, PayloadHeader, PayloadWriter, VabcAlgo, VabcParams},
|
||||
zip::ZipWriterWrapper,
|
||||
},
|
||||
patch::{
|
||||
boot::{
|
||||
@@ -72,48 +75,65 @@ fn sorted<T: Ord>(iter: impl Iterator<Item = T>) -> Vec<T> {
|
||||
items
|
||||
}
|
||||
|
||||
pub struct RequiredImages(HashSet<String>);
|
||||
bitflags! {
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PartitionFlags: u8 {
|
||||
const BOOT = 1 << 0;
|
||||
const SYSTEM = 1 << 1;
|
||||
const VBMETA = 1 << 2;
|
||||
const COW = 1 << 3;
|
||||
|
||||
impl RequiredImages {
|
||||
pub fn new(manifest: &DeltaArchiveManifest) -> Self {
|
||||
let partitions = manifest
|
||||
.partitions
|
||||
.iter()
|
||||
.map(|p| &p.partition_name)
|
||||
.filter(|n| Self::is_boot(n) || Self::is_system(n) || Self::is_vbmeta(n))
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
Self(partitions)
|
||||
const KNOWN = Self::BOOT.bits() | Self::SYSTEM.bits() | Self::VBMETA.bits();
|
||||
}
|
||||
|
||||
pub fn is_boot(name: &str) -> bool {
|
||||
name == "boot" || name == "init_boot" || name == "recovery" || name == "vendor_boot"
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct RequiredFlags: u8 {
|
||||
const SYSTEM = 1 << 0;
|
||||
const ALL_COW = 1 << 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the images required for patching. If [`RequiredFlags::SYSTEM`] is
|
||||
/// specified, then the system image is included. If [`RequiredFlags::ALL_COW`]
|
||||
/// is specified, then all images with CoW size estimates are included.
|
||||
pub fn get_required_images(
|
||||
manifest: &DeltaArchiveManifest,
|
||||
required_flags: RequiredFlags,
|
||||
) -> HashMap<String, PartitionFlags> {
|
||||
let mut result = HashMap::new();
|
||||
|
||||
for partition in &manifest.partitions {
|
||||
let name = &partition.partition_name;
|
||||
let mut flags = PartitionFlags::empty();
|
||||
|
||||
if name == "boot" || name == "init_boot" || name == "recovery" || name == "vendor_boot" {
|
||||
flags |= PartitionFlags::BOOT;
|
||||
} else if required_flags.contains(RequiredFlags::SYSTEM) && name == "system" {
|
||||
flags |= PartitionFlags::SYSTEM;
|
||||
} else if name.starts_with("vbmeta") {
|
||||
flags |= PartitionFlags::VBMETA;
|
||||
}
|
||||
|
||||
if partition.estimate_cow_size.is_some() {
|
||||
flags |= PartitionFlags::COW;
|
||||
}
|
||||
|
||||
// Skip completely unrecognized partitions.
|
||||
if flags.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip unrecognized CoW partitions unless we ask for them.
|
||||
if flags == PartitionFlags::COW && !required_flags.contains(RequiredFlags::ALL_COW) {
|
||||
continue;
|
||||
}
|
||||
|
||||
result.insert(name.clone(), flags);
|
||||
}
|
||||
|
||||
pub fn is_system(name: &str) -> bool {
|
||||
name == "system"
|
||||
}
|
||||
|
||||
pub fn is_vbmeta(name: &str) -> bool {
|
||||
name.starts_with("vbmeta")
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> impl Iterator<Item = &str> {
|
||||
self.0.iter().map(|n| n.as_str())
|
||||
}
|
||||
|
||||
pub fn iter_boot(&self) -> impl Iterator<Item = &str> {
|
||||
self.iter().filter(|n| Self::is_boot(n))
|
||||
}
|
||||
|
||||
pub fn iter_system(&self) -> impl Iterator<Item = &str> {
|
||||
self.iter().filter(|n| Self::is_system(n))
|
||||
}
|
||||
|
||||
pub fn iter_vbmeta(&self) -> impl Iterator<Item = &str> {
|
||||
self.iter().filter(|n| Self::is_vbmeta(n))
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
@@ -134,7 +154,7 @@ struct InputFile {
|
||||
/// operating system).
|
||||
fn open_input_files(
|
||||
payload: &(dyn ReadSeekReopen + Sync),
|
||||
required_images: &RequiredImages,
|
||||
required_images: &HashMap<String, PartitionFlags>,
|
||||
external_images: &HashMap<String, PathBuf>,
|
||||
header: &PayloadHeader,
|
||||
cancel_signal: &AtomicBool,
|
||||
@@ -144,8 +164,8 @@ fn open_input_files(
|
||||
// We always include replacement images that the user specifies, even if
|
||||
// they don't need to be patched.
|
||||
let all_images = required_images
|
||||
.iter()
|
||||
.chain(external_images.keys().map(|k| k.as_str()))
|
||||
.keys()
|
||||
.chain(external_images.keys())
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
for name in all_images {
|
||||
@@ -158,7 +178,7 @@ fn open_input_files(
|
||||
.map(PSeekFile::new)
|
||||
.with_context(|| format!("Failed to open external image: {path:?}"))?;
|
||||
input_files.insert(
|
||||
name.to_owned(),
|
||||
name.clone(),
|
||||
InputFile {
|
||||
file,
|
||||
state: InputFileState::External,
|
||||
@@ -174,7 +194,7 @@ fn open_input_files(
|
||||
payload::extract_image(payload, &file, header, name, cancel_signal)
|
||||
.with_context(|| format!("Failed to extract from original payload: {name}"))?;
|
||||
input_files.insert(
|
||||
name.to_owned(),
|
||||
name.clone(),
|
||||
InputFile {
|
||||
file,
|
||||
state: InputFileState::Extracted,
|
||||
@@ -190,15 +210,19 @@ fn open_input_files(
|
||||
/// necessarily patched. Each patcher will determine which image it should
|
||||
/// target. If the original image is signed, then it will be re-signed with
|
||||
/// `key_avb`.
|
||||
fn patch_boot_images<'a, 'b: 'a>(
|
||||
required_images: &'b RequiredImages,
|
||||
fn patch_boot_images(
|
||||
required_images: &HashMap<String, PartitionFlags>,
|
||||
input_files: &mut HashMap<String, InputFile>,
|
||||
boot_patchers: &[Box<dyn BootImagePatch + Sync>],
|
||||
key_avb: &RsaSigningKey,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let input_files = Mutex::new(input_files);
|
||||
let boot_partitions = required_images.iter_boot().collect::<Vec<_>>();
|
||||
let boot_partitions = required_images
|
||||
.iter()
|
||||
.filter(|(_, flags)| flags.contains(PartitionFlags::BOOT))
|
||||
.map(|(name, _)| name.as_str())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
info!(
|
||||
"Candidate boot images: {}",
|
||||
@@ -234,16 +258,23 @@ fn patch_boot_images<'a, 'b: 'a>(
|
||||
|
||||
/// Patch the single system image listed in `required_images` to replace the
|
||||
/// `otacerts.zip` contents.
|
||||
fn patch_system_image<'a, 'b: 'a>(
|
||||
required_images: &'b RequiredImages,
|
||||
fn patch_system_image<'a>(
|
||||
required_images: &'a HashMap<String, PartitionFlags>,
|
||||
input_files: &mut HashMap<String, InputFile>,
|
||||
cert_ota: &Certificate,
|
||||
key_avb: &RsaSigningKey,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<(&'b str, Vec<Range<u64>>)> {
|
||||
let Some(target) = required_images.iter_system().next() else {
|
||||
) -> Result<(&'a str, Vec<Range<u64>>)> {
|
||||
let mut system_iter = required_images
|
||||
.iter()
|
||||
.filter(|(_, flags)| flags.contains(PartitionFlags::SYSTEM))
|
||||
.map(|(name, _)| name);
|
||||
let Some(target) = system_iter.next() else {
|
||||
bail!("No system partition found");
|
||||
};
|
||||
if system_iter.next().is_some() {
|
||||
bail!("Multiple system partitions found");
|
||||
}
|
||||
|
||||
let _span = debug_span!("image", name = target).entered();
|
||||
|
||||
@@ -309,12 +340,13 @@ fn load_vbmeta_images(
|
||||
/// Check that all critical partitions within the payload are protected by a
|
||||
/// vbmeta image in `vbmeta_headers`.
|
||||
fn ensure_partitions_protected(
|
||||
required_images: &RequiredImages,
|
||||
required_images: &HashMap<String, PartitionFlags>,
|
||||
vbmeta_headers: &HashMap<String, Header>,
|
||||
) -> Result<()> {
|
||||
let critical_partitions = required_images
|
||||
.iter_boot()
|
||||
.chain(required_images.iter_vbmeta())
|
||||
.iter()
|
||||
.filter(|(_, flags)| flags.intersects(PartitionFlags::BOOT | PartitionFlags::VBMETA))
|
||||
.map(|(name, _)| name.as_str())
|
||||
.collect::<BTreeSet<_>>();
|
||||
|
||||
// vbmeta partitions first.
|
||||
@@ -373,8 +405,9 @@ fn get_vbmeta_patch_order(
|
||||
.get_mut(vbmeta_name.as_str())
|
||||
.unwrap()
|
||||
.insert(partition_name.to_owned());
|
||||
missing.remove(partition_name);
|
||||
}
|
||||
|
||||
missing.remove(partition_name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,7 +496,9 @@ fn update_security_descriptors(
|
||||
*pd = cd.clone();
|
||||
}
|
||||
_ => {
|
||||
bail!("{child_name} descriptor ({child_type}) does not match entry in {parent_name} ({parent_type})");
|
||||
bail!(
|
||||
"{child_name} descriptor ({child_type}) does not match entry in {parent_name} ({parent_type})"
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -473,7 +508,9 @@ fn update_security_descriptors(
|
||||
child_header.public_key.clone_into(&mut pd.public_key);
|
||||
}
|
||||
_ => {
|
||||
bail!("{child_name} descriptor ({parent_type}) in {parent_name} must be a chain descriptor");
|
||||
bail!(
|
||||
"{child_name} descriptor ({parent_type}) in {parent_name} must be a chain descriptor"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -545,6 +582,74 @@ fn update_metadata_descriptors(parent_header: &mut Header, child_header: &Header
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the VABC parameters from the payload header. This will fail if an
|
||||
/// unsupported VABC algorithm or CoW version is specified, but not if VABC is
|
||||
/// disabled.
|
||||
fn get_vabc_params(header: &PayloadHeader) -> Result<Option<VabcParams>> {
|
||||
// Only CoW v2 seems to exist in the wild currently, so that is all we
|
||||
// support.
|
||||
let Some(dpm) = &header.manifest.dynamic_partition_metadata else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
if !dpm.vabc_enabled() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let cow_version = match dpm.cow_version() {
|
||||
2 => CowVersion::V2,
|
||||
3 => CowVersion::V3,
|
||||
v => bail!("Unsupported CoW version: {v}"),
|
||||
};
|
||||
|
||||
let compression = dpm.vabc_compression_param();
|
||||
let Ok(vabc_algo) = VabcAlgo::from_str(compression) else {
|
||||
bail!("Unsupported VABC compression: {compression}");
|
||||
};
|
||||
|
||||
// This is unused by v2, but delta_generator sets it anyway.
|
||||
let Some(compression_factor) = dpm.compression_factor else {
|
||||
bail!("No CoW compression factor specified");
|
||||
};
|
||||
let Ok(compression_factor) = u32::try_from(compression_factor) else {
|
||||
bail!("CoW compression factor is too large: {compression_factor}");
|
||||
};
|
||||
|
||||
let vabc_params = VabcParams {
|
||||
version: cow_version,
|
||||
algo: vabc_algo,
|
||||
compression_factor,
|
||||
};
|
||||
|
||||
Ok(Some(vabc_params))
|
||||
}
|
||||
|
||||
/// Set the VABC algorithm in the payload header and return whether it was
|
||||
/// changed. This will fail if VABC was originally disabled. Returns whether the
|
||||
/// new algorithm is different from the old algorithm.
|
||||
fn set_vabc_algo(header: &mut PayloadHeader, vabc_algo: VabcAlgo) -> Result<bool> {
|
||||
let Some(dpm) = &mut header.manifest.dynamic_partition_metadata else {
|
||||
bail!("Dynamic partition metadata is missing");
|
||||
};
|
||||
|
||||
if !dpm.vabc_enabled() {
|
||||
bail!("Cannot change VABC algorithm when VABC is disabled");
|
||||
}
|
||||
|
||||
let compression = dpm.vabc_compression_param();
|
||||
let Ok(old_vabc_algo) = VabcAlgo::from_str(compression) else {
|
||||
bail!("Unsupported VABC compression: {compression}");
|
||||
};
|
||||
|
||||
if vabc_algo == old_vabc_algo {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
dpm.vabc_compression_param = Some(vabc_algo.to_string());
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Update vbmeta headers.
|
||||
///
|
||||
/// * If [`Header::flags`] is non-zero, then an error is returned because the
|
||||
@@ -565,6 +670,11 @@ fn update_vbmeta_headers(
|
||||
key: &RsaSigningKey,
|
||||
block_size: u64,
|
||||
) -> Result<()> {
|
||||
info!(
|
||||
"Patching vbmeta images: {}",
|
||||
joined(order.iter().map(|(n, _)| n)),
|
||||
);
|
||||
|
||||
for (name, deps) in order {
|
||||
let parent_header = headers.get_mut(name).unwrap();
|
||||
let orig_parent_header = parent_header.clone();
|
||||
@@ -592,7 +702,12 @@ fn update_vbmeta_headers(
|
||||
// Only sign and rewrite the image if we need to. Some vbmeta images may
|
||||
// have no dependencies and are only being processed to ensure that the
|
||||
// flags are set to a sane value.
|
||||
if parent_header != &orig_parent_header {
|
||||
//
|
||||
// The root vbmeta image is always signed because it is possible to
|
||||
// invoke avbroot is a way that no modifications are made (rootless +
|
||||
// skipping recovery otacerts.zip patch). We still want the result to be
|
||||
// bootable.
|
||||
if parent_header != &orig_parent_header || name == "vbmeta" {
|
||||
parent_header
|
||||
.set_algo_for_key(key)
|
||||
.with_context(|| format!("Failed to set signature algorithm: {name}"))?;
|
||||
@@ -638,6 +753,7 @@ pub fn compress_image(
|
||||
.map(PSeekFile::new)
|
||||
.with_context(|| format!("Failed to create temp file for: {name}"))?;
|
||||
|
||||
let vabc_params = get_vabc_params(header)?;
|
||||
let block_size = header.manifest.block_size();
|
||||
let partition = header
|
||||
.manifest
|
||||
@@ -646,6 +762,23 @@ pub fn compress_image(
|
||||
.find(|p| p.partition_name == name)
|
||||
.unwrap();
|
||||
|
||||
// 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 vabc_params = if partition.estimate_cow_size.is_some() {
|
||||
let Some(vabc_params) = vabc_params else {
|
||||
bail!("Partition has CoW estimate, but VABC is disabled: {name}");
|
||||
};
|
||||
|
||||
info!(
|
||||
"Needs updated {} CoW size estimate: {name}",
|
||||
vabc_params.algo,
|
||||
);
|
||||
|
||||
Some(vabc_params)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(r) = ranges {
|
||||
info!("Compressing partial image: {name}: {r:?}");
|
||||
|
||||
@@ -659,7 +792,26 @@ pub fn compress_image(
|
||||
cancel_signal,
|
||||
) {
|
||||
Ok(indices) => {
|
||||
// The changes we make usually aren't any less compressible, but
|
||||
// we'll still recompute the CoW size estimate to handle the
|
||||
// case where the user requested a different algorithm.
|
||||
if let Some(vabc_params) = vabc_params {
|
||||
let cow_estimate = payload::compute_cow_estimate(
|
||||
&*file,
|
||||
partition.operations.len() as u64,
|
||||
name,
|
||||
block_size,
|
||||
vabc_params,
|
||||
cancel_signal,
|
||||
)?;
|
||||
|
||||
partition.estimate_cow_size = Some(cow_estimate.size);
|
||||
partition.estimate_op_count_max =
|
||||
(vabc_params.version == CowVersion::V3).then_some(cow_estimate.num_ops);
|
||||
}
|
||||
|
||||
*file = writer;
|
||||
|
||||
return Ok(indices);
|
||||
}
|
||||
// If we can't take advantage of the optimization, we can still
|
||||
@@ -673,43 +825,20 @@ pub fn compress_image(
|
||||
|
||||
info!("Compressing full image: {name}");
|
||||
|
||||
// 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 vabc_algo = if partition.estimate_cow_size.is_some() {
|
||||
info!("Needs updated CoW size estimate: {name}");
|
||||
|
||||
// Only CoW v2 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();
|
||||
let Some(vabc_algo) = VabcAlgo::new(compression) else {
|
||||
bail!("Unsupported VABC compression: {compression}");
|
||||
};
|
||||
|
||||
Some(vabc_algo)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let (partition_info, operations, cow_estimate) =
|
||||
payload::compress_image(&*file, &writer, name, block_size, vabc_algo, cancel_signal)?;
|
||||
let (partition_info, operations, cow_estimate) = payload::compress_image(
|
||||
&*file,
|
||||
&writer,
|
||||
name,
|
||||
block_size,
|
||||
vabc_params,
|
||||
cancel_signal,
|
||||
)?;
|
||||
|
||||
partition.new_partition_info = Some(partition_info);
|
||||
partition.operations = operations;
|
||||
partition.estimate_cow_size = cow_estimate;
|
||||
partition.estimate_cow_size = cow_estimate.map(|e| e.size);
|
||||
let is_v3 = vabc_params.is_some_and(|p| p.version == CowVersion::V3);
|
||||
partition.estimate_op_count_max = cow_estimate.and_then(|e| is_v3.then_some(e.num_ops));
|
||||
|
||||
*file = writer;
|
||||
|
||||
@@ -717,13 +846,62 @@ pub fn compress_image(
|
||||
Ok(vec![0..partition.operations.len()])
|
||||
}
|
||||
|
||||
/// Recompute the CoW estimate for an image and update the OTA manifest
|
||||
/// partition entry appropriately. The input file is not modified.
|
||||
fn recow_image(
|
||||
name: &str,
|
||||
file: &mut PSeekFile,
|
||||
header: &mut PayloadHeader,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let _span = debug_span!("image", name).entered();
|
||||
|
||||
file.rewind()?;
|
||||
|
||||
let vabc_params = get_vabc_params(header)?;
|
||||
let block_size = header.manifest.block_size();
|
||||
let partition = header
|
||||
.manifest
|
||||
.partitions
|
||||
.iter_mut()
|
||||
.find(|p| p.partition_name == name)
|
||||
.unwrap();
|
||||
|
||||
if partition.estimate_cow_size.is_none() {
|
||||
bail!("Partition has no original CoW estimate: {name}");
|
||||
}
|
||||
|
||||
let Some(vabc_params) = vabc_params else {
|
||||
bail!("Partition has CoW estimate, but VABC is disabled: {name}");
|
||||
};
|
||||
|
||||
info!("Recomputing {} CoW size estimate: {name}", vabc_params.algo);
|
||||
|
||||
let cow_estimate = payload::compute_cow_estimate(
|
||||
&*file,
|
||||
partition.operations.len() as u64,
|
||||
name,
|
||||
block_size,
|
||||
vabc_params,
|
||||
cancel_signal,
|
||||
)?;
|
||||
|
||||
partition.estimate_cow_size = Some(cow_estimate.size);
|
||||
partition.estimate_op_count_max =
|
||||
(vabc_params.version == CowVersion::V3).then_some(cow_estimate.num_ops);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn patch_ota_payload(
|
||||
payload: &(dyn ReadSeekReopen + Sync),
|
||||
writer: impl Write,
|
||||
external_images: &HashMap<String, PathBuf>,
|
||||
boot_patchers: &[Box<dyn BootImagePatch + Sync>],
|
||||
skip_system_ota_cert: bool,
|
||||
clear_vbmeta_flags: bool,
|
||||
vabc_algo_override: Option<VabcAlgo>,
|
||||
key_avb: &RsaSigningKey,
|
||||
key_ota: &RsaSigningKey,
|
||||
cert_ota: &Certificate,
|
||||
@@ -735,6 +913,16 @@ fn patch_ota_payload(
|
||||
bail!("Payload is a delta OTA, not a full OTA");
|
||||
}
|
||||
|
||||
let mut required_flags = RequiredFlags::empty();
|
||||
if !skip_system_ota_cert {
|
||||
required_flags |= RequiredFlags::SYSTEM;
|
||||
}
|
||||
if let Some(vabc_algo) = vabc_algo_override {
|
||||
if set_vabc_algo(&mut header, vabc_algo)? {
|
||||
required_flags |= RequiredFlags::ALL_COW;
|
||||
}
|
||||
}
|
||||
|
||||
let all_partitions = header
|
||||
.manifest
|
||||
.partitions
|
||||
@@ -750,11 +938,17 @@ fn patch_ota_payload(
|
||||
}
|
||||
}
|
||||
|
||||
// Determine what images need to be patched. For simplicity, we pre-read all
|
||||
// vbmeta images since they're tiny. They're discarded later if the they
|
||||
// don't need to be modified.
|
||||
let required_images = RequiredImages::new(&header.manifest);
|
||||
let vbmeta_images = required_images.iter_vbmeta().collect::<HashSet<_>>();
|
||||
let required_images = get_required_images(&header.manifest, required_flags);
|
||||
let vbmeta_images = required_images
|
||||
.iter()
|
||||
.filter(|(_, flags)| flags.contains(PartitionFlags::VBMETA))
|
||||
.map(|(name, _)| name.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
let cow_images = required_images
|
||||
.iter()
|
||||
.filter(|(_, flags)| flags.contains(PartitionFlags::COW))
|
||||
.map(|(name, _)| name.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
// The set of source images to be inserted into the new payload, replacing
|
||||
// what was in the original payload. Initially, this refers to either user
|
||||
@@ -777,18 +971,17 @@ fn patch_ota_payload(
|
||||
cancel_signal,
|
||||
)?;
|
||||
|
||||
// Main patching operation is done. Unmodified boot images no longer need to
|
||||
// be kept around.
|
||||
input_files
|
||||
.retain(|n, f| !(f.state == InputFileState::Extracted && RequiredImages::is_boot(n)));
|
||||
|
||||
let (system_target, system_ranges) = patch_system_image(
|
||||
&required_images,
|
||||
&mut input_files,
|
||||
cert_ota,
|
||||
key_avb,
|
||||
cancel_signal,
|
||||
)?;
|
||||
let system_result = if skip_system_ota_cert {
|
||||
None
|
||||
} else {
|
||||
Some(patch_system_image(
|
||||
&required_images,
|
||||
&mut input_files,
|
||||
cert_ota,
|
||||
key_avb,
|
||||
cancel_signal,
|
||||
)?)
|
||||
};
|
||||
|
||||
let mut vbmeta_headers = load_vbmeta_images(&mut input_files, &vbmeta_images)?;
|
||||
|
||||
@@ -796,11 +989,6 @@ fn patch_ota_payload(
|
||||
|
||||
let mut vbmeta_order = get_vbmeta_patch_order(&input_files, &vbmeta_headers)?;
|
||||
|
||||
info!(
|
||||
"Patching vbmeta images: {}",
|
||||
joined(vbmeta_order.iter().map(|(n, _)| n)),
|
||||
);
|
||||
|
||||
update_vbmeta_headers(
|
||||
&mut input_files,
|
||||
&mut vbmeta_headers,
|
||||
@@ -810,7 +998,19 @@ fn patch_ota_payload(
|
||||
header.manifest.block_size().into(),
|
||||
)?;
|
||||
|
||||
// Unmodified vbmeta images no longer need to be kept around either.
|
||||
// Recompute CoW estimates for partitions we don't modify.
|
||||
input_files
|
||||
.iter_mut()
|
||||
.filter(|(name, f)| {
|
||||
f.state == InputFileState::Extracted && cow_images.contains(name.as_str())
|
||||
})
|
||||
.try_for_each(|(name, input_file)| {
|
||||
recow_image(name, &mut input_file.file, &mut header, cancel_signal)
|
||||
})?;
|
||||
|
||||
// Drop all unmodified images. We only want to compress modified images.
|
||||
// For recowed images, the payload header was already updated with the new
|
||||
// estimate. The actual data can be copied from the original payload.
|
||||
input_files.retain(|_, f| f.state != InputFileState::Extracted);
|
||||
|
||||
let mut compressed_files = input_files
|
||||
@@ -822,8 +1022,12 @@ fn patch_ota_payload(
|
||||
&mut header,
|
||||
// We can only perform the optimization of avoiding
|
||||
// recompression if the image came from the original payload.
|
||||
if name == system_target && !external_images.contains_key(&name) {
|
||||
Some(&system_ranges)
|
||||
if let Some((system_target, system_ranges)) = &system_result {
|
||||
if name == *system_target && !external_images.contains_key(&name) {
|
||||
Some(system_ranges)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
},
|
||||
@@ -912,10 +1116,12 @@ fn patch_ota_payload(
|
||||
fn patch_ota_zip(
|
||||
raw_reader: &PSeekFile,
|
||||
zip_reader: &mut ZipArchive<impl Read + Seek>,
|
||||
mut zip_writer: &mut ZipWriter<impl Write>,
|
||||
mut zip_writer: &mut ZipWriterWrapper<impl Write>,
|
||||
external_images: &HashMap<String, PathBuf>,
|
||||
boot_patchers: &[Box<dyn BootImagePatch + Sync>],
|
||||
skip_system_ota_cert: bool,
|
||||
clear_vbmeta_flags: bool,
|
||||
vabc_algo_override: Option<VabcAlgo>,
|
||||
zip_mode: ZipMode,
|
||||
key_avb: &RsaSigningKey,
|
||||
key_ota: &RsaSigningKey,
|
||||
@@ -964,7 +1170,8 @@ fn patch_ota_zip(
|
||||
// threshold. This should be sufficient since the output file is likely
|
||||
// to be larger.
|
||||
let use_zip64 = reader.size() >= 0xffffffff;
|
||||
let options = FileOptions::default()
|
||||
let options = SimpleFileOptions::default()
|
||||
.last_modified_time(DateTime::default())
|
||||
.compression_method(CompressionMethod::Stored)
|
||||
.large_file(use_zip64);
|
||||
|
||||
@@ -1001,12 +1208,9 @@ fn patch_ota_zip(
|
||||
}
|
||||
|
||||
// All remaining entries are written immediately.
|
||||
zip_writer
|
||||
.start_file_with_extra_data(path, options)
|
||||
.with_context(|| format!("Failed to begin new zip entry: {path}"))?;
|
||||
let offset = zip_writer
|
||||
.end_extra_data()
|
||||
.with_context(|| format!("Failed to end new zip entry: {path}"))?;
|
||||
.start_file(path, options)
|
||||
.with_context(|| format!("Failed to begin new zip entry: {path}"))?;
|
||||
let mut writer = CountingWriter::new(&mut zip_writer);
|
||||
|
||||
match path.as_str() {
|
||||
@@ -1037,7 +1241,9 @@ fn patch_ota_zip(
|
||||
&mut writer,
|
||||
external_images,
|
||||
boot_patchers,
|
||||
skip_system_ota_cert,
|
||||
clear_vbmeta_flags,
|
||||
vabc_algo_override,
|
||||
key_avb,
|
||||
key_ota,
|
||||
cert_ota,
|
||||
@@ -1303,7 +1509,11 @@ pub fn patch_subcommand(cli: &PatchCli, cancel_signal: &AtomicBool) -> Result<()
|
||||
)));
|
||||
} else {
|
||||
assert!(cli.root.rootless);
|
||||
};
|
||||
}
|
||||
|
||||
if cli.skip_system_ota_cert {
|
||||
warn!("Not inserting OTA cert into system image; sideloading further updates may fail");
|
||||
}
|
||||
|
||||
if cli.skip_recovery_ota_cert {
|
||||
warn!("Not inserting OTA cert into recovery image; sideloading further updates may fail");
|
||||
@@ -1333,11 +1543,11 @@ pub fn patch_subcommand(cli: &PatchCli, cancel_signal: &AtomicBool) -> Result<()
|
||||
let mut zip_writer = match cli.zip_mode {
|
||||
ZipMode::Streaming => {
|
||||
let signing_writer = SigningWriter::new_streaming(temp_writer);
|
||||
ZipWriter::new_streaming(signing_writer)
|
||||
ZipWriterWrapper::new_streaming(signing_writer)
|
||||
}
|
||||
ZipMode::Seekable => {
|
||||
let signing_writer = SigningWriter::new_seekable(temp_writer);
|
||||
ZipWriter::new(signing_writer)
|
||||
ZipWriterWrapper::new_seekable(signing_writer)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1347,7 +1557,9 @@ pub fn patch_subcommand(cli: &PatchCli, cancel_signal: &AtomicBool) -> Result<()
|
||||
&mut zip_writer,
|
||||
&external_images,
|
||||
&boot_patchers,
|
||||
cli.skip_system_ota_cert,
|
||||
cli.clear_vbmeta_flags,
|
||||
cli.vabc_algo,
|
||||
cli.zip_mode,
|
||||
&key_avb,
|
||||
&key_ota,
|
||||
@@ -1469,22 +1681,20 @@ pub fn extract_subcommand(cli: &ExtractCli, cancel_signal: &AtomicBool) -> Resul
|
||||
|
||||
unique_images.extend(cli.extract.partition.iter().cloned());
|
||||
} else if !cli.extract.none {
|
||||
let images = RequiredImages::new(&header.manifest);
|
||||
let images = get_required_images(&header.manifest, RequiredFlags::SYSTEM)
|
||||
.into_iter()
|
||||
.filter(|(_, flags)| !cli.extract.boot_only || flags.contains(PartitionFlags::BOOT))
|
||||
.map(|(name, _)| name);
|
||||
|
||||
if cli.extract.boot_only {
|
||||
unique_images.extend(images.iter_boot().map(|n| n.to_owned()));
|
||||
} else {
|
||||
unique_images.extend(images.iter().map(|n| n.to_owned()));
|
||||
}
|
||||
unique_images.extend(images);
|
||||
}
|
||||
|
||||
if let Some(path) = &cli.cert_ota {
|
||||
info!("Extracting embedded OTA certificate from zip signature");
|
||||
|
||||
let ota_sig = ota::parse_ota_sig(&mut raw_reader)?;
|
||||
let embedded_cert = ota_sig.embedded_cert()?;
|
||||
|
||||
crypto::write_pem_cert_file(path, embedded_cert)
|
||||
crypto::write_pem_cert_file(path, &ota_sig.cert)
|
||||
.with_context(|| format!("Failed to write OTA certificate: {path:?}"))?;
|
||||
}
|
||||
|
||||
@@ -1667,6 +1877,15 @@ pub fn extract_subcommand(cli: &ExtractCli, cancel_signal: &AtomicBool) -> Resul
|
||||
}
|
||||
|
||||
pub fn verify_subcommand(cli: &VerifyCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let mut errors = 0;
|
||||
|
||||
macro_rules! fail_later {
|
||||
($($arg:tt)+) => {
|
||||
error!($($arg)+);
|
||||
errors += 1;
|
||||
};
|
||||
}
|
||||
|
||||
let raw_reader = File::open(&cli.input)
|
||||
.map(PSeekFile::new)
|
||||
.with_context(|| format!("Failed to open for reading: {:?}", cli.input))?;
|
||||
@@ -1674,27 +1893,38 @@ pub fn verify_subcommand(cli: &VerifyCli, cancel_signal: &AtomicBool) -> Result<
|
||||
|
||||
info!("Verifying whole-file signature");
|
||||
|
||||
let embedded_cert = ota::verify_ota(&mut reader, cancel_signal)?;
|
||||
let ota_sig = ota::parse_ota_sig(&mut reader).context("Failed to parse OTA signature")?;
|
||||
|
||||
let (metadata, ota_cert, header, properties) = ota::parse_zip_ota_info(&mut reader)?;
|
||||
if embedded_cert != ota_cert {
|
||||
bail!(
|
||||
"CMS embedded certificate does not match {}",
|
||||
if let Err(e) = ota_sig
|
||||
.verify_ota(&mut reader, cancel_signal)
|
||||
.context("Failed to verify OTA against embedded certificate")
|
||||
{
|
||||
fail_later!("{e:?}");
|
||||
}
|
||||
|
||||
let (metadata, ota_cert, header, properties) =
|
||||
ota::parse_zip_ota_info(&mut reader).context("Failed to parse OTA metadata")?;
|
||||
if ota_cert != ota_sig.cert {
|
||||
fail_later!(
|
||||
"{} does not match CMS embedded certificate",
|
||||
ota::PATH_OTACERT,
|
||||
);
|
||||
} else if let Some(p) = &cli.cert_ota {
|
||||
let verify_cert = crypto::read_pem_cert_file(p)
|
||||
.with_context(|| format!("Failed to load certificate: {p:?}"))?;
|
||||
|
||||
if embedded_cert != verify_cert {
|
||||
bail!("OTA has a valid signature, but was not signed with: {p:?}");
|
||||
if ota_sig.cert != verify_cert {
|
||||
fail_later!("OTA has a valid signature, but was not signed with: {p:?}");
|
||||
}
|
||||
} else {
|
||||
warn!("Whole-file signature is valid, but its trust is unknown");
|
||||
}
|
||||
|
||||
ota::verify_metadata(&mut reader, &metadata, header.blob_offset)
|
||||
.context("Failed to verify OTA metadata offsets")?;
|
||||
if let Err(e) = ota::verify_metadata(&mut reader, &metadata, header.blob_offset)
|
||||
.context("Failed to verify OTA metadata offsets")
|
||||
{
|
||||
fail_later!("{e:?}");
|
||||
}
|
||||
|
||||
info!("Verifying payload");
|
||||
|
||||
@@ -1712,7 +1942,12 @@ pub fn verify_subcommand(cli: &VerifyCli, cancel_signal: &AtomicBool) -> Result<
|
||||
let section_reader = SectionReader::new(&mut reader, pf_payload.offset, pf_payload.size)
|
||||
.context("Failed to directly open payload section")?;
|
||||
|
||||
payload::verify_payload(section_reader, &ota_cert, &properties, cancel_signal)?;
|
||||
if let Err(e) =
|
||||
payload::verify_payload(section_reader, &ota_sig.cert, &properties, cancel_signal)
|
||||
.context("Failed to verify payload signatures and digests")
|
||||
{
|
||||
fail_later!("{e:?}");
|
||||
}
|
||||
|
||||
info!("Extracting partition images to temporary directory");
|
||||
|
||||
@@ -1739,40 +1974,8 @@ pub fn verify_subcommand(cli: &VerifyCli, cancel_signal: &AtomicBool) -> Result<
|
||||
|
||||
info!("Verifying partition hashes");
|
||||
|
||||
verify_partition_hashes(&temp_dir, &header, &unique_images, cancel_signal)?;
|
||||
|
||||
if cli.skip_recovery_ota_cert {
|
||||
warn!("Not verifying recovery ramdisk's otacerts.zip");
|
||||
} else {
|
||||
info!("Checking recovery ramdisk's otacerts.zip");
|
||||
|
||||
let required_images = RequiredImages::new(&header.manifest);
|
||||
let boot_images =
|
||||
boot::load_boot_images(&required_images.iter_boot().collect::<Vec<_>>(), |name| {
|
||||
Ok(Box::new(
|
||||
temp_dir
|
||||
.open(format!("{name}.img"))
|
||||
.map(|f| PSeekFile::new(f.into_std()))?,
|
||||
))
|
||||
})
|
||||
.context("Failed to load all boot images")?;
|
||||
let targets = OtaCertPatcher::new(ota_cert.clone())
|
||||
.find_targets(&boot_images, cancel_signal)
|
||||
.context("Failed to find boot image containing otacerts.zip")?;
|
||||
|
||||
if targets.is_empty() {
|
||||
bail!("No boot image contains otacerts.zip");
|
||||
}
|
||||
|
||||
for target in targets {
|
||||
let boot_image = &boot_images[target].boot_image;
|
||||
let ramdisk_certs = OtaCertPatcher::get_certificates(boot_image, cancel_signal)
|
||||
.context("Failed to read {target}'s otacerts.zip")?;
|
||||
|
||||
if !ramdisk_certs.contains(&ota_cert) {
|
||||
bail!("{target}'s otacerts.zip does not contain OTA certificate");
|
||||
}
|
||||
}
|
||||
if let Err(e) = verify_partition_hashes(&temp_dir, &header, &unique_images, cancel_signal) {
|
||||
fail_later!("{e:?}");
|
||||
}
|
||||
|
||||
info!("Verifying AVB signatures");
|
||||
@@ -1790,16 +1993,77 @@ pub fn verify_subcommand(cli: &VerifyCli, cancel_signal: &AtomicBool) -> Result<
|
||||
let mut seen = HashSet::<String>::new();
|
||||
let mut descriptors = HashMap::<String, Descriptor>::new();
|
||||
|
||||
cli::avb::verify_headers(
|
||||
if let Err(e) = cli::avb::verify_headers(
|
||||
&temp_dir,
|
||||
"vbmeta",
|
||||
public_key.as_ref(),
|
||||
&mut seen,
|
||||
&mut descriptors,
|
||||
)?;
|
||||
cli::avb::verify_descriptors(&temp_dir, &descriptors, false, cancel_signal)?;
|
||||
)
|
||||
.context("Failed to verify AVB signatures")
|
||||
{
|
||||
fail_later!("{e:?}");
|
||||
}
|
||||
|
||||
info!("Signatures are all valid!");
|
||||
if let Err(e) = cli::avb::verify_descriptors(&temp_dir, &descriptors, false, cancel_signal)
|
||||
.context("Failed to verify images against AVB descriptors")
|
||||
{
|
||||
fail_later!("{e:?}");
|
||||
}
|
||||
|
||||
info!("Checking recovery ramdisk's otacerts.zip");
|
||||
|
||||
let required_images = get_required_images(&header.manifest, RequiredFlags::empty());
|
||||
let boot_image_names = required_images
|
||||
.iter()
|
||||
.filter(|(_, flags)| flags.contains(PartitionFlags::BOOT))
|
||||
.map(|(name, _)| name.as_str())
|
||||
.collect::<Vec<_>>();
|
||||
let boot_images = boot::load_boot_images(&boot_image_names, |name| {
|
||||
Ok(Box::new(
|
||||
temp_dir
|
||||
.open(format!("{name}.img"))
|
||||
.map(|f| PSeekFile::new(f.into_std()))?,
|
||||
))
|
||||
})
|
||||
.context("Failed to load all boot images")?;
|
||||
let targets = OtaCertPatcher::new(ota_cert.clone())
|
||||
.find_targets(&boot_images, cancel_signal)
|
||||
.context("Failed to find boot image containing otacerts.zip")?;
|
||||
|
||||
if targets.is_empty() {
|
||||
let msg = "No boot image contains otacerts.zip";
|
||||
|
||||
if cli.skip_recovery_ota_cert {
|
||||
warn!("{msg}");
|
||||
} else {
|
||||
fail_later!("{msg}");
|
||||
}
|
||||
}
|
||||
|
||||
for target in targets {
|
||||
let boot_image = &boot_images[target].boot_image;
|
||||
let ramdisk_certs = OtaCertPatcher::get_certificates(boot_image, cancel_signal)
|
||||
.with_context(|| format!("Failed to read {target}'s otacerts.zip"))?;
|
||||
|
||||
if !ramdisk_certs.contains(&ota_cert) {
|
||||
let msg = format!(
|
||||
"{target}'s otacerts.zip does not contain the certificate that signed the OTA"
|
||||
);
|
||||
|
||||
if cli.skip_recovery_ota_cert {
|
||||
warn!("{msg}");
|
||||
} else {
|
||||
fail_later!("{msg}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if errors == 0 {
|
||||
info!("OK!");
|
||||
} else {
|
||||
bail!("Encountered {errors} error(s) during verification");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1981,11 +2245,19 @@ pub struct PatchCli {
|
||||
)]
|
||||
pub ignore_prepatched_compat: u8,
|
||||
|
||||
/// Skip adding OTA certificate to system image.
|
||||
///
|
||||
/// DO NOT USE THIS unless you've manually added the certificate to the
|
||||
/// system image already. Otherwise, installing further updates via a custom
|
||||
/// OTA updater app while booted into Android will not be possible.
|
||||
#[arg(long, help_heading = HEADING_OTHER)]
|
||||
pub skip_system_ota_cert: bool,
|
||||
|
||||
/// Skip adding OTA certificate to recovery image.
|
||||
///
|
||||
/// DO NOT USE THIS unless you've manually added the certificate to the
|
||||
/// recovery image already. Otherwise, sideloading further updates will not
|
||||
/// be possible.
|
||||
/// recovery image already. Otherwise, sideloading further updates while
|
||||
/// booted into recovery mode will not be possible.
|
||||
///
|
||||
/// When this option is used with --rootless, the boot images in the OTA
|
||||
/// will not be modified.
|
||||
@@ -2000,6 +2272,18 @@ pub struct PatchCli {
|
||||
#[arg(long, help_heading = HEADING_OTHER)]
|
||||
pub clear_vbmeta_flags: bool,
|
||||
|
||||
/// Override the virtual A/B CoW compression algorithm.
|
||||
///
|
||||
/// This will slow down the patching process because every dynamic partition
|
||||
/// needs to be extracted to recompute the CoW size estimate. However, if a
|
||||
/// faster algorithm is chosen, then OTA installation using an OTA updater
|
||||
/// app will be faster. This does not affect sideloading from recovery mode.
|
||||
///
|
||||
/// Note that selecting a newer algorithm will prevent upgrading from older
|
||||
/// Android versions before support for the algorithm was introduced.
|
||||
#[arg(long, value_name = "ALGO", help_heading = HEADING_OTHER)]
|
||||
pub vabc_algo: Option<VabcAlgo>,
|
||||
|
||||
/// Zip creation mode for the output OTA zip.
|
||||
///
|
||||
/// The streaming mode produces zip files that contain data descriptors.
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::{
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use cap_std::{ambient_authority, fs::Dir};
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
use tracing::info;
|
||||
|
||||
@@ -10,10 +10,10 @@ use std::{
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use clap::{Parser, Subcommand};
|
||||
use crc32fast::Hasher;
|
||||
use zerocopy::{little_endian, IntoBytes};
|
||||
use zerocopy::{IntoBytes, little_endian};
|
||||
|
||||
use crate::{
|
||||
format::{
|
||||
@@ -122,13 +122,13 @@ fn find_allocated_regions(
|
||||
loop {
|
||||
stream::check_cancel(cancel_signal)?;
|
||||
|
||||
start = match rustix::fs::seek(reader, SeekFrom::Data(end as i64)) {
|
||||
start = match rustix::fs::seek(reader, SeekFrom::Data(end)) {
|
||||
Ok(offset) => offset,
|
||||
Err(e) if e == Errno::NXIO => break,
|
||||
Err(e) => return Err(e).with_context(|| format!("Failed to seek to data: {path:?}")),
|
||||
};
|
||||
|
||||
end = rustix::fs::seek(reader, SeekFrom::Hole(start as i64))
|
||||
end = rustix::fs::seek(reader, SeekFrom::Hole(start))
|
||||
.with_context(|| format!("Failed to seek to hole: {path:?}"))?;
|
||||
|
||||
result.push(start..end);
|
||||
|
||||
@@ -21,25 +21,25 @@ use cms::{
|
||||
};
|
||||
use passterm::PromptError;
|
||||
use pkcs8::{
|
||||
pkcs5::{pbes2, scrypt},
|
||||
DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey, EncryptedPrivateKeyInfo,
|
||||
LineEnding, PrivateKeyInfo,
|
||||
pkcs5::{pbes2, scrypt},
|
||||
};
|
||||
use rand::RngCore;
|
||||
use rsa::{
|
||||
pkcs1v15::SigningKey, traits::PublicKeyParts, Pkcs1v15Sign, RsaPrivateKey, RsaPublicKey,
|
||||
Pkcs1v15Sign, RsaPrivateKey, RsaPublicKey, pkcs1v15::SigningKey, traits::PublicKeyParts,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha1::Sha1;
|
||||
use sha2::{Digest, Sha256, Sha512};
|
||||
use thiserror::Error;
|
||||
use x509_cert::{
|
||||
Certificate,
|
||||
builder::{Builder, CertificateBuilder, Profile},
|
||||
der::{pem::PemLabel, referenced::OwnedToRef, Any, Decode, DecodePem, EncodePem},
|
||||
der::{Any, Decode, DecodePem, EncodePem, pem::PemLabel, referenced::OwnedToRef},
|
||||
serial_number::SerialNumber,
|
||||
spki::{AlgorithmIdentifierOwned, SubjectPublicKeyInfoOwned},
|
||||
time::Validity,
|
||||
Certificate,
|
||||
};
|
||||
|
||||
use crate::util::DebugString;
|
||||
@@ -144,6 +144,7 @@ pub enum PassphraseSource {
|
||||
|
||||
impl PassphraseSource {
|
||||
pub fn new(key_file: &Path, pass_file: Option<&Path>, env_var: Option<&OsStr>) -> Self {
|
||||
#[allow(clippy::option_if_let_else)]
|
||||
if let Some(v) = env_var {
|
||||
Self::EnvVar(v.to_owned())
|
||||
} else if let Some(p) = pass_file {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::{fmt, marker::PhantomData};
|
||||
|
||||
use bstr::{ByteSlice, ByteVec};
|
||||
use serde::{de::Visitor, Deserializer, Serializer};
|
||||
use serde::{Deserializer, Serializer, de::Visitor};
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Clone, Debug, Error)]
|
||||
|
||||
+15
-16
@@ -14,10 +14,10 @@ use bstr::ByteSlice;
|
||||
use num_bigint_dig::{ModInverse, ToBigInt};
|
||||
use num_traits::{Pow, ToPrimitive};
|
||||
use ring::digest::{Algorithm, Context};
|
||||
use rsa::{traits::PublicKeyParts, BigUint, RsaPublicKey};
|
||||
use rsa::{BigUint, RsaPublicKey, traits::PublicKeyParts};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
use zerocopy::{big_endian, FromBytes, IntoBytes};
|
||||
use zerocopy::{FromBytes, IntoBytes, big_endian};
|
||||
use zerocopy_derive::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};
|
||||
|
||||
use crate::{
|
||||
@@ -163,7 +163,7 @@ pub enum Error {
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
pub(crate) fn ring_algorithm(name: &str, for_verify: bool) -> Result<&'static Algorithm> {
|
||||
pub(crate) fn digest_algorithm(name: &str, for_verify: bool) -> Result<&'static Algorithm> {
|
||||
match name {
|
||||
"sha1" if for_verify => Ok(&ring::digest::SHA1_FOR_LEGACY_USE_ONLY),
|
||||
"sha256" => Ok(&ring::digest::SHA256),
|
||||
@@ -292,7 +292,7 @@ trait DescriptorTag {
|
||||
|
||||
/// Raw on-disk layout for the AVB property descriptor after the prefix.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawPropertyDescriptor {
|
||||
key_size: big_endian::U64,
|
||||
value_size: big_endian::U64,
|
||||
@@ -395,7 +395,7 @@ impl<W: Write> ToWriter<W> for PropertyDescriptor {
|
||||
|
||||
/// Raw on-disk layout for the AVB hash tree descriptor after the prefix.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawHashTreeDescriptor {
|
||||
dm_verity_version: big_endian::U32,
|
||||
image_size: big_endian::U64,
|
||||
@@ -534,7 +534,7 @@ impl HashTreeDescriptor {
|
||||
ranges: Option<&[Range<u64>]>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let algorithm = ring_algorithm(&self.hash_algorithm, false)?;
|
||||
let algorithm = digest_algorithm(&self.hash_algorithm, false)?;
|
||||
let hash_tree = HashTree::new(self.data_block_size, algorithm, &self.salt);
|
||||
let (root_digest, hash_tree_data) = match ranges {
|
||||
Some(r) => {
|
||||
@@ -642,7 +642,7 @@ impl HashTreeDescriptor {
|
||||
) -> Result<()> {
|
||||
self.check_offsets()?;
|
||||
|
||||
let algorithm = ring_algorithm(&self.hash_algorithm, true)?;
|
||||
let algorithm = digest_algorithm(&self.hash_algorithm, true)?;
|
||||
|
||||
util::check_bounds(self.tree_size, ..=HASH_TREE_MAX_SIZE)
|
||||
.map_err(|e| Error::IntOutOfBounds("HashTree::tree_size", e))?;
|
||||
@@ -860,7 +860,7 @@ impl<W: Write> ToWriter<W> for HashTreeDescriptor {
|
||||
|
||||
/// Raw on-disk layout for the AVB hash descriptor after the prefix.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawHashDescriptor {
|
||||
image_size: big_endian::U64,
|
||||
hash_algorithm: [u8; 32],
|
||||
@@ -906,7 +906,7 @@ impl HashDescriptor {
|
||||
for_verify: bool,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<ring::digest::Digest> {
|
||||
let algorithm = ring_algorithm(&self.hash_algorithm, for_verify)?;
|
||||
let algorithm = digest_algorithm(&self.hash_algorithm, for_verify)?;
|
||||
let mut context = Context::new(algorithm);
|
||||
context.update(&self.salt);
|
||||
|
||||
@@ -1065,7 +1065,7 @@ impl<W: Write> ToWriter<W> for HashDescriptor {
|
||||
/// Raw on-disk layout for the AVB kernel command line descriptor after the
|
||||
/// prefix.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawKernelCmdlineDescriptor {
|
||||
flags: big_endian::U32,
|
||||
cmdline_len: big_endian::U32,
|
||||
@@ -1139,7 +1139,7 @@ impl<W: Write> ToWriter<W> for KernelCmdlineDescriptor {
|
||||
|
||||
/// Raw on-disk layout for the AVB chain partition descriptor after the prefix.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawChainPartitionDescriptor {
|
||||
rollback_index_location: big_endian::U32,
|
||||
partition_name_len: big_endian::U32,
|
||||
@@ -1258,7 +1258,7 @@ impl<W: Write> ToWriter<W> for ChainPartitionDescriptor {
|
||||
|
||||
/// Raw on-disk layout for the AVB descriptor prefix.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawDescriptor {
|
||||
tag: big_endian::U64,
|
||||
num_bytes_following: big_endian::U64,
|
||||
@@ -1458,7 +1458,7 @@ impl<'a> TryFrom<&'a mut Descriptor> for AppendedDescriptorMut<'a> {
|
||||
|
||||
/// Raw on-disk layout for the AVB header.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawHeader {
|
||||
/// Magic value. This should be equal to [`HEADER_MAGIC`].
|
||||
magic: [u8; 4],
|
||||
@@ -1927,7 +1927,7 @@ impl<W: Write> ToWriter<W> for Header {
|
||||
|
||||
/// Raw on-disk layout for the AVB footer.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawFooter {
|
||||
/// Magic value. This should be equal to [`FOOTER_MAGIC`].
|
||||
magic: [u8; 4],
|
||||
@@ -2015,10 +2015,9 @@ impl<W: Write> ToWriter<W> for Footer {
|
||||
|
||||
/// Raw on-disk layout for the AVB binary public key header.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawPublicKey {
|
||||
key_num_bits: big_endian::U32,
|
||||
#[expect(unused)]
|
||||
n0inv: big_endian::U32,
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ use num_traits::ToPrimitive;
|
||||
use ring::digest::Context;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
use zerocopy::{little_endian, FromBytes, IntoBytes};
|
||||
use zerocopy::{FromBytes, IntoBytes, little_endian};
|
||||
use zerocopy_derive::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};
|
||||
|
||||
use crate::{
|
||||
@@ -117,7 +117,7 @@ pub trait BootImageExt {
|
||||
|
||||
/// Raw on-disk layout for the v0 image header.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawV0 {
|
||||
/// Magic value. This should be equal to [`BOOT_MAGIC`].
|
||||
magic: [u8; 8],
|
||||
@@ -139,7 +139,7 @@ struct RawV0 {
|
||||
|
||||
/// Raw on-disk layout for the extra v1 image header fields.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawV1Extra {
|
||||
recovery_dtbo_size: little_endian::U32,
|
||||
recovery_dtbo_offset: little_endian::U64,
|
||||
@@ -148,7 +148,7 @@ struct RawV1Extra {
|
||||
|
||||
/// Raw on-disk layout for the extra v2 image header fields.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawV2Extra {
|
||||
dtb_size: little_endian::U32,
|
||||
dtb_addr: little_endian::U64,
|
||||
@@ -269,6 +269,7 @@ impl fmt::Display for BootImageV0Through2 {
|
||||
|
||||
impl BootImageExt for BootImageV0Through2 {
|
||||
fn header_version(&self) -> u32 {
|
||||
#[allow(clippy::bool_to_int_with_if)]
|
||||
if self.v2_extra.is_some() {
|
||||
2
|
||||
} else if self.v1_extra.is_some() {
|
||||
@@ -595,7 +596,7 @@ impl<W: Write> ToWriter<W> for BootImageV0Through2 {
|
||||
|
||||
/// Raw on-disk layout for the v3 image header.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawV3 {
|
||||
/// Magic value. This should be equal to [`BOOT_MAGIC`].
|
||||
magic: [u8; 8],
|
||||
@@ -610,7 +611,7 @@ struct RawV3 {
|
||||
|
||||
/// Raw on-disk layout for the extra v4 image header fields.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawV4Extra {
|
||||
signature_size: little_endian::U32,
|
||||
}
|
||||
@@ -668,11 +669,7 @@ impl fmt::Display for BootImageV3Through4 {
|
||||
|
||||
impl BootImageExt for BootImageV3Through4 {
|
||||
fn header_version(&self) -> u32 {
|
||||
if self.v4_extra.is_some() {
|
||||
4
|
||||
} else {
|
||||
3
|
||||
}
|
||||
if self.v4_extra.is_some() { 4 } else { 3 }
|
||||
}
|
||||
|
||||
fn header_size(&self) -> u32 {
|
||||
@@ -961,7 +958,7 @@ impl<W: Write> ToWriter<W> for BootImageV3Through4 {
|
||||
|
||||
/// Raw on-disk layout for the vendor v3 image header.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawVendorV3 {
|
||||
/// Magic value. This should be equal to [`VENDOR_BOOT_MAGIC`].
|
||||
magic: [u8; 8],
|
||||
@@ -980,7 +977,7 @@ struct RawVendorV3 {
|
||||
|
||||
/// Raw on-disk layout for the extra vendor v4 image header fields.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawVendorV4Extra {
|
||||
vendor_ramdisk_table_size: little_endian::U32,
|
||||
vendor_ramdisk_table_entry_num: little_endian::U32,
|
||||
@@ -990,7 +987,7 @@ struct RawVendorV4Extra {
|
||||
|
||||
/// Raw on-disk layout for the vendor v4 ramdisk table entry.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawVendorV4RamdiskTableEntry {
|
||||
ramdisk_size: little_endian::U32,
|
||||
ramdisk_offset: little_endian::U32,
|
||||
@@ -1093,11 +1090,7 @@ impl fmt::Display for VendorBootImageV3Through4 {
|
||||
|
||||
impl BootImageExt for VendorBootImageV3Through4 {
|
||||
fn header_version(&self) -> u32 {
|
||||
if self.v4_extra.is_some() {
|
||||
4
|
||||
} else {
|
||||
3
|
||||
}
|
||||
if self.v4_extra.is_some() { 4 } else { 3 }
|
||||
}
|
||||
|
||||
fn header_size(&self) -> u32 {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::io::{self, Read, Seek, Write};
|
||||
|
||||
use flate2::{read::GzDecoder, write::GzEncoder, Compression};
|
||||
use flate2::{Compression, read::GzDecoder, write::GzEncoder};
|
||||
use liblzma::{
|
||||
read::XzDecoder,
|
||||
stream::{Check, Stream},
|
||||
|
||||
@@ -76,7 +76,7 @@ pub struct InvalidHexCharError(RawHexU32, char);
|
||||
|
||||
/// ASCII-encoded hex integer value used in cpio header fields.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawHexU32([u8; 8]);
|
||||
|
||||
impl fmt::Debug for RawHexU32 {
|
||||
@@ -121,7 +121,7 @@ impl TryFrom<RawHexU32> for u32 {
|
||||
|
||||
/// Raw on-disk layout for the cpio header.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawHeader {
|
||||
/// Magic value. This should be equal to [`MAGIC_NEW`] or [`MAGIC_NEW_CRC`].
|
||||
magic: [u8; 6],
|
||||
@@ -771,11 +771,7 @@ pub fn sort(entries: &mut [CpioEntry]) {
|
||||
/// 300000.
|
||||
pub fn assign_inodes(entries: &mut [CpioEntry], missing_only: bool) -> Result<()> {
|
||||
fn next_non_zero(i: u32) -> u32 {
|
||||
if i == u32::MAX {
|
||||
1
|
||||
} else {
|
||||
i.wrapping_add(1)
|
||||
}
|
||||
if i == u32::MAX { 1 } else { i.wrapping_add(1) }
|
||||
}
|
||||
|
||||
// (dev maj, dev min) -> (inode set, last assigned inode)
|
||||
|
||||
@@ -16,7 +16,7 @@ use rayon::{
|
||||
slice::{ParallelSlice, ParallelSliceMut},
|
||||
};
|
||||
use thiserror::Error;
|
||||
use zerocopy::{little_endian, FromBytes, IntoBytes};
|
||||
use zerocopy::{FromBytes, IntoBytes, little_endian};
|
||||
use zerocopy_derive::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};
|
||||
|
||||
use crate::{
|
||||
@@ -592,7 +592,7 @@ impl Fec {
|
||||
|
||||
/// Raw on-disk layout for the FEC image header.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawHeader {
|
||||
/// Magic value. This should be equal to [`FEC_MAGIC`].
|
||||
magic: little_endian::U32,
|
||||
@@ -827,7 +827,7 @@ impl<W: Write> ToWriter<W> for FecImage {
|
||||
mod tests {
|
||||
use std::{
|
||||
io::{Cursor, Seek},
|
||||
sync::{atomic::AtomicBool, Arc},
|
||||
sync::{Arc, atomic::AtomicBool},
|
||||
};
|
||||
|
||||
use assert_matches::assert_matches;
|
||||
|
||||
@@ -16,7 +16,7 @@ use rayon::{
|
||||
};
|
||||
use ring::digest::{Algorithm, Context};
|
||||
use thiserror::Error;
|
||||
use zerocopy::{little_endian, FromBytes, IntoBytes};
|
||||
use zerocopy::{FromBytes, IntoBytes, little_endian};
|
||||
use zerocopy_derive::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};
|
||||
|
||||
use crate::{
|
||||
@@ -431,7 +431,7 @@ impl HashTree {
|
||||
|
||||
/// Raw on-disk layout for our custom hash tree image header.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawHeader {
|
||||
/// Magic value. This should be equal to [`HashTreeImage::MAGIC`].
|
||||
magic: [u8; 16],
|
||||
@@ -492,8 +492,8 @@ impl HashTreeImage {
|
||||
const MAGIC: &'static [u8; 16] = b"avbroot!hashtree";
|
||||
const VERSION: u16 = 1;
|
||||
|
||||
fn ring_algorithm(name: &str) -> Result<&'static Algorithm> {
|
||||
avb::ring_algorithm(name, false)
|
||||
fn digest_algorithm(name: &str) -> Result<&'static Algorithm> {
|
||||
avb::digest_algorithm(name, false)
|
||||
.map_err(|_| Error::UnsupportedHashAlgorithm(name.to_owned().into_bytes()))
|
||||
}
|
||||
|
||||
@@ -509,8 +509,8 @@ impl HashTreeImage {
|
||||
.reopen_boxed()
|
||||
.and_then(|mut f| f.seek(SeekFrom::End(0)))
|
||||
.map_err(Error::InputReopen)?;
|
||||
let ring_algorithm = Self::ring_algorithm(algorithm)?;
|
||||
let hash_tree = HashTree::new(block_size, ring_algorithm, salt);
|
||||
let digest_algorithm = Self::digest_algorithm(algorithm)?;
|
||||
let hash_tree = HashTree::new(block_size, digest_algorithm, salt);
|
||||
let (root_digest, hash_tree_data) = hash_tree.generate(input, image_size, cancel_signal)?;
|
||||
|
||||
Ok(Self {
|
||||
@@ -530,8 +530,8 @@ impl HashTreeImage {
|
||||
ranges: &[Range<u64>],
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let ring_algorithm = Self::ring_algorithm(&self.algorithm)?;
|
||||
let hash_tree = HashTree::new(self.block_size, ring_algorithm, &self.salt);
|
||||
let digest_algorithm = Self::digest_algorithm(&self.algorithm)?;
|
||||
let hash_tree = HashTree::new(self.block_size, digest_algorithm, &self.salt);
|
||||
|
||||
self.root_digest = hash_tree.update(
|
||||
input,
|
||||
@@ -550,8 +550,8 @@ impl HashTreeImage {
|
||||
input: &(dyn ReadSeekReopen + Sync),
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let ring_algorithm = Self::ring_algorithm(&self.algorithm)?;
|
||||
let hash_tree = HashTree::new(self.block_size, ring_algorithm, &self.salt);
|
||||
let digest_algorithm = Self::digest_algorithm(&self.algorithm)?;
|
||||
let hash_tree = HashTree::new(self.block_size, digest_algorithm, &self.salt);
|
||||
|
||||
hash_tree.verify(
|
||||
input,
|
||||
|
||||
+61
-63
@@ -1,8 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2024 Andrew Gunnerson
|
||||
// SPDX-FileCopyrightText: 2024-2025 Andrew Gunnerson
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::{
|
||||
cmp::Ordering,
|
||||
fmt,
|
||||
io::{self, Read, Seek, Write},
|
||||
mem,
|
||||
@@ -14,7 +13,7 @@ use bitflags::bitflags;
|
||||
use bstr::ByteSlice;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
use zerocopy::{byteorder::little_endian, FromBytes, FromZeros, Immutable, IntoBytes};
|
||||
use zerocopy::{FromBytes, FromZeros, Immutable, IntoBytes, byteorder::little_endian};
|
||||
use zerocopy_derive::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};
|
||||
|
||||
use crate::{
|
||||
@@ -22,7 +21,7 @@ use crate::{
|
||||
stream::{
|
||||
CountingReader, FromReader, ReadDiscardExt, ReadFixedSizeExt, ToWriter, WriteZerosExt,
|
||||
},
|
||||
util::{self, is_zero, DebugString},
|
||||
util::{self, DebugString, is_zero},
|
||||
};
|
||||
|
||||
/// Magic value for [`RawGeometry::magic`].
|
||||
@@ -152,10 +151,8 @@ pub enum Error {
|
||||
ExtentTypeZeroNotEmpty { index: usize },
|
||||
#[error("Extent #{index}: Invalid type: {extent_type}")]
|
||||
ExtentInvalidType { index: usize, extent_type: u32 },
|
||||
#[error("Extent #{index}: Overlaps previous extent")]
|
||||
ExtentOverlapsPrevious { index: usize },
|
||||
#[error("Extent #{index}: Earlier block device index than previous extent")]
|
||||
ExtentDeviceNotConsecutive { index: usize },
|
||||
#[error("Extent #{index}: Overlaps another extent: #{other}")]
|
||||
ExtentOverlapsAnother { index: usize, other: usize },
|
||||
#[error("Extent #{index}: Block device index too large")]
|
||||
ExtentDeviceIndexTooLarge { index: usize },
|
||||
// Partition group errors.
|
||||
@@ -253,7 +250,7 @@ impl PartitionAttributes {
|
||||
|
||||
/// Raw on-disk layout for the metadata geometry.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawGeometry {
|
||||
/// Magic value. This should be equal to [`GEOMETRY_MAGIC`].
|
||||
magic: little_endian::U32,
|
||||
@@ -335,7 +332,7 @@ impl RawGeometry {
|
||||
|
||||
/// Raw on-disk layout for a table descriptor within a [`RawHeader`].
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawTableDescriptor {
|
||||
/// Offset relative to the end of the [`RawHeader`].
|
||||
offset: little_endian::U32,
|
||||
@@ -394,7 +391,7 @@ impl RawTableDescriptor {
|
||||
|
||||
/// Raw on-disk layout for the metadata header.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawHeader {
|
||||
/// Magic value. This should be equal to [`HEADER_MAGIC`].
|
||||
magic: little_endian::U32,
|
||||
@@ -572,7 +569,7 @@ impl RawHeader {
|
||||
|
||||
/// A potentially invalid raw partition name string.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct PartitionName([u8; 36]);
|
||||
|
||||
impl fmt::Debug for PartitionName {
|
||||
@@ -598,17 +595,15 @@ impl PartitionName {
|
||||
|
||||
fn validate(&self) -> Result<()> {
|
||||
let (prefix, suffix) = self.split();
|
||||
let mut has_alnum = false;
|
||||
|
||||
for b in prefix {
|
||||
match b {
|
||||
b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => has_alnum = true,
|
||||
b'_' => {}
|
||||
_ => return Err(Error::PartitionNameInvalid(DebugString::new(self))),
|
||||
}
|
||||
}
|
||||
// AOSP liblp's metadata_format.h says "Characters may only be
|
||||
// alphanumeric or _", but AOSP creates partitions named like
|
||||
// "system_b-cow".
|
||||
let prefix_valid = prefix
|
||||
.iter()
|
||||
.all(|b| matches!(*b, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-'));
|
||||
|
||||
if has_alnum && is_zero(suffix) {
|
||||
if prefix_valid && is_zero(suffix) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::PartitionNameInvalid(DebugString::new(self)))
|
||||
@@ -644,7 +639,7 @@ impl FromStr for PartitionName {
|
||||
|
||||
/// Raw on-disk layout for an entry in the logical partitions table.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawPartition {
|
||||
/// Partition name in ASCII. This must be unique across all partitions.
|
||||
name: PartitionName,
|
||||
@@ -706,7 +701,7 @@ impl RawPartition {
|
||||
.first_extent_index
|
||||
.get()
|
||||
.checked_add(self.num_extents.get())
|
||||
.map_or(true, |n| n as usize > extents.len())
|
||||
.is_none_or(|n| n as usize > extents.len())
|
||||
{
|
||||
return Err(Error::PartitionExtentIndicesTooLarge {
|
||||
name: DebugString::new(self.name),
|
||||
@@ -735,7 +730,7 @@ impl RawPartition {
|
||||
|
||||
/// Raw on-disk layout for an entry in the extent table.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawExtent {
|
||||
/// Number of [`SECTOR_SIZE`]-byte sectors in this extent.
|
||||
num_sectors: little_endian::U64,
|
||||
@@ -817,7 +812,7 @@ impl RawExtent {
|
||||
return Err(Error::ExtentInvalidType {
|
||||
index,
|
||||
extent_type: n,
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -827,7 +822,7 @@ impl RawExtent {
|
||||
|
||||
/// Raw on-disk layout for an entry in the partition groups table.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawPartitionGroup {
|
||||
/// Partition group name in ASCII. This must be unique across all groups.
|
||||
name: PartitionName,
|
||||
@@ -894,7 +889,7 @@ impl RawPartitionGroup {
|
||||
|
||||
/// Raw on-disk layout for an entry in the block devices table.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawBlockDevice {
|
||||
/// The first [`SECTOR_SIZE`]-byte sector where actual data for the logical
|
||||
/// partitions can be allocated.
|
||||
@@ -1010,23 +1005,29 @@ impl RawMetadataSlot {
|
||||
extent.validate(i, &self.block_devices)?;
|
||||
}
|
||||
|
||||
// Ensure that all extents are in increasing order and not overlapping.
|
||||
let mut iter = self
|
||||
// Ensure that all extents are not overlapping. We have to sort here
|
||||
// because the extents may not be in order when loading the super
|
||||
// partition on an actual device. Also, AOSP liblp's `metadata_format.h`
|
||||
// says "Gaps between extents are not allowed", but AOSP frequently
|
||||
// creates this situation after a virtual A/B CoW merge.
|
||||
let mut sorted_extents = self
|
||||
.extents
|
||||
.iter()
|
||||
.filter(|e| e.target_type.get() == RawExtent::TARGET_TYPE_LINEAR)
|
||||
.enumerate();
|
||||
while let (Some((_, a)), Some((i, b))) = (iter.next(), iter.next()) {
|
||||
match a.target_source.get().cmp(&b.target_source.get()) {
|
||||
Ordering::Equal => {
|
||||
if a.target_data.get() + a.num_sectors.get() > b.target_data.get() {
|
||||
return Err(Error::ExtentOverlapsPrevious { index: i });
|
||||
}
|
||||
}
|
||||
Ordering::Greater => {
|
||||
return Err(Error::ExtentDeviceNotConsecutive { index: i });
|
||||
}
|
||||
Ordering::Less => {}
|
||||
.enumerate()
|
||||
.filter(|(_, e)| e.target_type.get() == RawExtent::TARGET_TYPE_LINEAR)
|
||||
.collect::<Vec<_>>();
|
||||
sorted_extents.sort_by_key(|(_, e)| (e.target_source, e.target_data));
|
||||
|
||||
for window in sorted_extents.windows(2) {
|
||||
let ((a_i, a), (b_i, b)) = (window[0], window[1]);
|
||||
|
||||
if a.target_source == b.target_source
|
||||
&& a.target_data.get() + a.num_sectors.get() > b.target_data.get()
|
||||
{
|
||||
return Err(Error::ExtentOverlapsAnother {
|
||||
index: b_i,
|
||||
other: a_i,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1060,14 +1061,19 @@ impl RawMetadata {
|
||||
.read_exact(&mut buf)
|
||||
.map_err(|e| Error::DataRead("geometry", e))?;
|
||||
|
||||
let image_type = if util::is_zero(&buf) {
|
||||
ImageType::Normal
|
||||
} else {
|
||||
ImageType::Empty
|
||||
};
|
||||
// For non-empty images, AOSP says the first block is supposed to be
|
||||
// filled with zeros, but Samsung puts their own SignerVer02 structure
|
||||
// in there, so we can't rely on that.
|
||||
let mut geometry = RawGeometry::ref_from_prefix(&buf).unwrap().0;
|
||||
|
||||
let geometry = match image_type {
|
||||
ImageType::Normal => {
|
||||
let image_type = match geometry.validate() {
|
||||
Ok(()) => {
|
||||
// This is an empty image for use with fastboot. These have no
|
||||
// extra padding at the beginning of the file nor backup copies
|
||||
// of the geometry and metadata structs.
|
||||
ImageType::Empty
|
||||
}
|
||||
Err(Error::GeometryInvalidMagic(_)) => {
|
||||
// This is an normal non-empty image, which has extra padding at
|
||||
// the beginning to avoid having the geometry struct interpreted
|
||||
// as a boot sector.
|
||||
@@ -1077,7 +1083,7 @@ impl RawMetadata {
|
||||
.read_exact(&mut buf)
|
||||
.map_err(|e| Error::DataRead("geometry_primary", e))?;
|
||||
|
||||
let mut geometry = RawGeometry::ref_from_prefix(&buf).unwrap().0;
|
||||
geometry = RawGeometry::ref_from_prefix(&buf).unwrap().0;
|
||||
|
||||
if geometry.validate().is_ok() {
|
||||
// Skip the backup copy.
|
||||
@@ -1094,17 +1100,9 @@ impl RawMetadata {
|
||||
geometry.validate()?;
|
||||
}
|
||||
|
||||
geometry
|
||||
}
|
||||
ImageType::Empty => {
|
||||
// This is an empty image for use with fastboot. These have no
|
||||
// extra padding at the beginning of the file nor backup copies
|
||||
// of the geometry and metadata structs.
|
||||
let geometry = RawGeometry::ref_from_prefix(&buf).unwrap().0;
|
||||
geometry.validate()?;
|
||||
|
||||
geometry
|
||||
ImageType::Normal
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
|
||||
Ok((image_type, geometry.to_owned()))
|
||||
@@ -1642,7 +1640,7 @@ impl TryFrom<&RawMetadataSlot> for MetadataSlot {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(raw_slot: &RawMetadataSlot) -> Result<Self> {
|
||||
let mut slot = MetadataSlot {
|
||||
let mut slot = Self {
|
||||
major_version: raw_slot.header.major_version.get(),
|
||||
minor_version: raw_slot.header.minor_version.get(),
|
||||
groups: Vec::with_capacity(raw_slot.groups.len()),
|
||||
@@ -1722,7 +1720,7 @@ impl TryFrom<&MetadataSlot> for RawMetadataSlot {
|
||||
fn try_from(slot: &MetadataSlot) -> Result<Self> {
|
||||
let header_size = RawHeader::size_for_version(slot.major_version, slot.minor_version);
|
||||
|
||||
let mut raw_slot = RawMetadataSlot {
|
||||
let mut raw_slot = Self {
|
||||
header: RawHeader {
|
||||
magic: HEADER_MAGIC.into(),
|
||||
major_version: slot.major_version.into(),
|
||||
@@ -1939,7 +1937,7 @@ impl TryFrom<&Metadata> for RawMetadata {
|
||||
// We only do the bare minimum calculations needed here to fill out the
|
||||
// raw fields. There is no semantic validation.
|
||||
|
||||
let mut raw_metadata = RawMetadata {
|
||||
let mut raw_metadata = Self {
|
||||
image_type: metadata.image_type,
|
||||
geometry: RawGeometry {
|
||||
magic: GEOMETRY_MAGIC.into(),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// SPDX-FileCopyrightText: 2023 Andrew Gunnerson
|
||||
// SPDX-FileCopyrightText: 2023-2025 Andrew Gunnerson
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
pub mod avb;
|
||||
@@ -13,3 +13,4 @@ pub mod padding;
|
||||
pub mod payload;
|
||||
pub mod sparse;
|
||||
pub mod verityrs;
|
||||
pub mod zip;
|
||||
|
||||
+139
-100
@@ -12,18 +12,21 @@ use std::{
|
||||
|
||||
use clap::ValueEnum;
|
||||
use cms::signed_data::SignedData;
|
||||
use const_oid::{db::rfc5912, ObjectIdentifier};
|
||||
use const_oid::{ObjectIdentifier, db::rfc5912};
|
||||
use memchr::memmem;
|
||||
use prost::Message;
|
||||
use ring::digest::Context;
|
||||
use ring::digest::{Algorithm, Context};
|
||||
use thiserror::Error;
|
||||
use x509_cert::{der::Encode, Certificate};
|
||||
use zip::{result::ZipError, write::FileOptions, CompressionMethod, ZipArchive, ZipWriter};
|
||||
use x509_cert::{Certificate, der::Encode};
|
||||
use zip::{CompressionMethod, DateTime, ZipArchive, result::ZipError, write::SimpleFileOptions};
|
||||
|
||||
use crate::{
|
||||
crypto::{self, RsaPublicKeyExt, RsaSigningKey, SignatureAlgorithm},
|
||||
format::payload::{self, PayloadHeader},
|
||||
protobuf::build::tools::releasetools::{ota_metadata::OtaType, OtaMetadata},
|
||||
format::{
|
||||
payload::{self, PayloadHeader},
|
||||
zip::ZipWriterWrapper,
|
||||
},
|
||||
protobuf::build::tools::releasetools::{OtaMetadata, ota_metadata::OtaType},
|
||||
stream::{self, FromReader, HashingReader, HashingWriter, ReadFixedSizeExt},
|
||||
};
|
||||
|
||||
@@ -323,6 +326,15 @@ fn compute_property_files(
|
||||
max_length: Option<usize>,
|
||||
want_pb: bool,
|
||||
) -> Result<String> {
|
||||
// AOSP's ota_utils.py reserves 15 bytes for the `<offset>:<size>`
|
||||
// placeholder. Since the size of `metadata.pb` is almost always 4 digits,
|
||||
// this prevents the offset from exceeding 10 digits. In the wild, there are
|
||||
// OTA files larger than 10 GB. With ota_utils.py, this limit is never
|
||||
// reached because it puts the OTA metadata files at the beginning of the
|
||||
// zip. However, avbroot needs to put them at the end due to streaming
|
||||
// writes, so we reserve an additional byte to allow offsets <100 GB.
|
||||
const RESERVATION_SIZE: usize = 16;
|
||||
|
||||
let compute = |path: &'static str| -> Result<String> {
|
||||
let entry = entries
|
||||
.iter()
|
||||
@@ -355,9 +367,9 @@ fn compute_property_files(
|
||||
}
|
||||
|
||||
if max_length.is_none() {
|
||||
tokens.push(format!("metadata:{}", " ".repeat(15)));
|
||||
tokens.push(format!("metadata:{}", " ".repeat(RESERVATION_SIZE)));
|
||||
if want_pb {
|
||||
tokens.push(format!("metadata.pb:{}", " ".repeat(15)));
|
||||
tokens.push(format!("metadata.pb:{}", " ".repeat(RESERVATION_SIZE)));
|
||||
}
|
||||
} else {
|
||||
tokens.push(compute(PATH_METADATA)?);
|
||||
@@ -377,7 +389,7 @@ fn compute_property_files(
|
||||
}
|
||||
|
||||
let remain = l - joined.len();
|
||||
joined.extend(iter::repeat(' ').take(remain));
|
||||
joined.extend(iter::repeat_n(' ', remain));
|
||||
}
|
||||
|
||||
Ok(joined)
|
||||
@@ -426,14 +438,16 @@ impl fmt::Display for ZipMode {
|
||||
/// directory would start.
|
||||
pub fn add_metadata(
|
||||
zip_entries: &[ZipEntry],
|
||||
zip_writer: &mut ZipWriter<impl Write>,
|
||||
zip_writer: &mut ZipWriterWrapper<impl Write>,
|
||||
next_offset: u64,
|
||||
metadata: &OtaMetadata,
|
||||
payload_metadata_size: u64,
|
||||
zip_mode: ZipMode,
|
||||
) -> Result<OtaMetadata> {
|
||||
let mut metadata = metadata.clone();
|
||||
let options = FileOptions::default().compression_method(CompressionMethod::Stored);
|
||||
let options = SimpleFileOptions::default()
|
||||
.last_modified_time(DateTime::default())
|
||||
.compression_method(CompressionMethod::Stored);
|
||||
|
||||
let mut zip_entries = zip_entries.to_owned();
|
||||
add_payload_metadata_entry(&mut zip_entries, payload_metadata_size)?;
|
||||
@@ -453,25 +467,19 @@ pub fn add_metadata(
|
||||
let (legacy_raw, modern_raw) = serialize_metadata(&metadata);
|
||||
let raw_writer = Cursor::new(Vec::new());
|
||||
let mut writer = match zip_mode {
|
||||
ZipMode::Streaming => ZipWriter::new_streaming(raw_writer),
|
||||
ZipMode::Seekable => ZipWriter::new(raw_writer),
|
||||
ZipMode::Streaming => ZipWriterWrapper::new_streaming(raw_writer),
|
||||
ZipMode::Seekable => ZipWriterWrapper::new_seekable(raw_writer),
|
||||
};
|
||||
|
||||
writer
|
||||
.start_file_with_extra_data(PATH_METADATA, options)
|
||||
.map_err(|e| Error::ZipEntryStart(PATH_METADATA, e))?;
|
||||
let legacy_offset = writer
|
||||
.end_extra_data()
|
||||
.start_file(PATH_METADATA, options)
|
||||
.map_err(|e| Error::ZipEntryStart(PATH_METADATA, e))?;
|
||||
writer
|
||||
.write_all(legacy_raw.as_bytes())
|
||||
.map_err(|e| Error::ZipEntryWrite(PATH_METADATA, e))?;
|
||||
|
||||
writer
|
||||
.start_file_with_extra_data(PATH_METADATA_PB, options)
|
||||
.map_err(|e| Error::ZipEntryStart(PATH_METADATA_PB, e))?;
|
||||
let modern_offset = writer
|
||||
.end_extra_data()
|
||||
.start_file(PATH_METADATA_PB, options)
|
||||
.map_err(|e| Error::ZipEntryStart(PATH_METADATA_PB, e))?;
|
||||
writer
|
||||
.write_all(&modern_raw)
|
||||
@@ -500,21 +508,15 @@ pub fn add_metadata(
|
||||
{
|
||||
let (legacy_raw, modern_raw) = serialize_metadata(&metadata);
|
||||
|
||||
zip_writer
|
||||
.start_file_with_extra_data(PATH_METADATA, options)
|
||||
.map_err(|e| Error::ZipEntryStart(PATH_METADATA, e))?;
|
||||
let legacy_offset = zip_writer
|
||||
.end_extra_data()
|
||||
.start_file(PATH_METADATA, options)
|
||||
.map_err(|e| Error::ZipEntryStart(PATH_METADATA, e))?;
|
||||
zip_writer
|
||||
.write_all(legacy_raw.as_bytes())
|
||||
.map_err(|e| Error::ZipEntryWrite(PATH_METADATA, e))?;
|
||||
|
||||
zip_writer
|
||||
.start_file_with_extra_data(PATH_METADATA_PB, options)
|
||||
.map_err(|e| Error::ZipEntryStart(PATH_METADATA_PB, e))?;
|
||||
let modern_offset = zip_writer
|
||||
.end_extra_data()
|
||||
.start_file(PATH_METADATA_PB, options)
|
||||
.map_err(|e| Error::ZipEntryStart(PATH_METADATA_PB, e))?;
|
||||
zip_writer
|
||||
.write_all(&modern_raw)
|
||||
@@ -566,14 +568,14 @@ pub fn verify_metadata(
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OtaSignature {
|
||||
struct RawOtaSignature {
|
||||
/// Decoded CMS structure.
|
||||
pub signed_data: SignedData,
|
||||
signed_data: SignedData,
|
||||
/// Length of the file (from the beginning) that's covered by the signature.
|
||||
pub hashed_size: u64,
|
||||
hashed_size: u64,
|
||||
}
|
||||
|
||||
impl OtaSignature {
|
||||
impl RawOtaSignature {
|
||||
pub fn embedded_cert(&self) -> Result<&Certificate> {
|
||||
let mut iter = crypto::iter_cms_certs(&self.signed_data);
|
||||
|
||||
@@ -589,9 +591,107 @@ impl OtaSignature {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OtaSignature {
|
||||
pub cert: Certificate,
|
||||
pub digest_algo: &'static Algorithm,
|
||||
pub sig_algo: SignatureAlgorithm,
|
||||
pub sig: Vec<u8>,
|
||||
pub data_size: u64,
|
||||
}
|
||||
|
||||
impl TryFrom<RawOtaSignature> for OtaSignature {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(raw_ota_sig: RawOtaSignature) -> Result<Self> {
|
||||
let cert = raw_ota_sig.embedded_cert()?;
|
||||
|
||||
// Make sure this is a signature scheme we can handle. There's currently
|
||||
// no Rust library to verify arbitrary CMS signatures for large files
|
||||
// without fully reading them into memory.
|
||||
let signers_len = raw_ota_sig.signed_data.signer_infos.0.len();
|
||||
if signers_len != 1 {
|
||||
return Err(Error::NotOneCmsSignerInfo(signers_len));
|
||||
}
|
||||
|
||||
let signer = raw_ota_sig.signed_data.signer_infos.0.get(0).unwrap();
|
||||
if signer.digest_alg.oid != rfc5912::ID_SHA_256
|
||||
&& signer.digest_alg.oid != rfc5912::ID_SHA_1
|
||||
{
|
||||
return Err(Error::UnsupportedDigestAlgorithm(signer.digest_alg.oid));
|
||||
} else if signer.signature_algorithm.oid != rfc5912::RSA_ENCRYPTION
|
||||
&& signer.signature_algorithm.oid != rfc5912::SHA_256_WITH_RSA_ENCRYPTION
|
||||
{
|
||||
return Err(Error::UnsupportedSignatureAlgorithm(
|
||||
signer.signature_algorithm.oid,
|
||||
));
|
||||
}
|
||||
|
||||
// We support SHA1 for verification only.
|
||||
let (digest_algo, sig_algo) = if signer.digest_alg.oid == rfc5912::ID_SHA_256 {
|
||||
(&ring::digest::SHA256, SignatureAlgorithm::Sha256WithRsa)
|
||||
} else {
|
||||
(
|
||||
&ring::digest::SHA1_FOR_LEGACY_USE_ONLY,
|
||||
SignatureAlgorithm::Sha1WithRsa,
|
||||
)
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
cert: cert.clone(),
|
||||
digest_algo,
|
||||
sig_algo,
|
||||
sig: signer.signature.as_bytes().to_vec(),
|
||||
data_size: raw_ota_sig.hashed_size,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl OtaSignature {
|
||||
/// Verify an OTA zip against its embedded certificate. This function makes
|
||||
/// no assertion about whether the certificate is actually trusted.
|
||||
///
|
||||
/// CMS signed attributes are intentionally not supported because AOSP
|
||||
/// recovery does not support them either. It expects the CMS [`SignedData`]
|
||||
/// structure to be used for nothing more than a raw signature transport
|
||||
/// mechanism.
|
||||
pub fn verify_ota(
|
||||
&self,
|
||||
mut reader: impl Read + Seek,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let public_key = crypto::get_public_key(&self.cert).map_err(Error::OtaCertExtractPubKey)?;
|
||||
|
||||
// Manually hash the parts of the file covered by the signature.
|
||||
reader
|
||||
.seek(SeekFrom::Start(0))
|
||||
.map_err(|e| Error::DataRead("raw_data", e))?;
|
||||
|
||||
let mut hashing_reader = HashingReader::new(reader, Context::new(self.digest_algo));
|
||||
|
||||
stream::copy_n(
|
||||
&mut hashing_reader,
|
||||
io::sink(),
|
||||
self.data_size,
|
||||
cancel_signal,
|
||||
)
|
||||
.map_err(|e| Error::DataRead("raw_data", e))?;
|
||||
|
||||
let (_, context) = hashing_reader.finish();
|
||||
let digest = context.finish();
|
||||
|
||||
// Verify the signature against the public key.
|
||||
public_key
|
||||
.verify_sig(self.sig_algo, digest.as_ref(), &self.sig)
|
||||
.map_err(Error::CmsVerify)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse the CMS signature from the OTA zip comment. This does not perform any
|
||||
/// parsing of zip data structures.
|
||||
pub fn parse_ota_sig(mut reader: impl Read + Seek) -> Result<OtaSignature> {
|
||||
fn parse_raw_ota_sig(mut reader: impl Read + Seek) -> Result<RawOtaSignature> {
|
||||
let file_size = reader
|
||||
.seek(SeekFrom::End(0))
|
||||
.map_err(|e| Error::DataRead("file_size", e))?;
|
||||
@@ -642,77 +742,16 @@ pub fn parse_ota_sig(mut reader: impl Read + Seek) -> Result<OtaSignature> {
|
||||
// length field.
|
||||
let hashed_size = file_size - 2 - u64::from(comment_size);
|
||||
|
||||
Ok(OtaSignature {
|
||||
Ok(RawOtaSignature {
|
||||
signed_data,
|
||||
hashed_size,
|
||||
})
|
||||
}
|
||||
|
||||
/// Verify an OTA zip against its embedded certificates. This function makes no
|
||||
/// assertion about whether the certificate is actually trusted. Returns the
|
||||
/// embedded certificate.
|
||||
///
|
||||
/// CMS signed attributes are intentionally not supported because AOSP recovery
|
||||
/// does not support them either. It expects the CMS [`SignedData`] structure to
|
||||
/// be used for nothing more than a raw signature transport mechanism.
|
||||
pub fn verify_ota(mut reader: impl Read + Seek, cancel_signal: &AtomicBool) -> Result<Certificate> {
|
||||
let ota_sig = parse_ota_sig(&mut reader)?;
|
||||
let cert = ota_sig.embedded_cert()?;
|
||||
let public_key = crypto::get_public_key(cert).map_err(Error::OtaCertExtractPubKey)?;
|
||||
|
||||
// Make sure this is a signature scheme we can handle. There's currently no
|
||||
// Rust library to verify arbitrary CMS signatures for large files without
|
||||
// fully reading them into memory.
|
||||
let signers_len = ota_sig.signed_data.signer_infos.0.len();
|
||||
if signers_len != 1 {
|
||||
return Err(Error::NotOneCmsSignerInfo(signers_len));
|
||||
}
|
||||
|
||||
let signer = ota_sig.signed_data.signer_infos.0.get(0).unwrap();
|
||||
if signer.digest_alg.oid != rfc5912::ID_SHA_256 && signer.digest_alg.oid != rfc5912::ID_SHA_1 {
|
||||
return Err(Error::UnsupportedDigestAlgorithm(signer.digest_alg.oid));
|
||||
} else if signer.signature_algorithm.oid != rfc5912::RSA_ENCRYPTION
|
||||
&& signer.signature_algorithm.oid != rfc5912::SHA_256_WITH_RSA_ENCRYPTION
|
||||
{
|
||||
return Err(Error::UnsupportedSignatureAlgorithm(
|
||||
signer.signature_algorithm.oid,
|
||||
));
|
||||
}
|
||||
|
||||
// Manually hash the parts of the file covered by the signature.
|
||||
reader
|
||||
.seek(SeekFrom::Start(0))
|
||||
.map_err(|e| Error::DataRead("raw_data", e))?;
|
||||
|
||||
// We support SHA1 for verification only.
|
||||
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,
|
||||
SignatureAlgorithm::Sha1WithRsa,
|
||||
)
|
||||
};
|
||||
|
||||
let mut hashing_reader = HashingReader::new(reader, Context::new(algorithm));
|
||||
|
||||
stream::copy_n(
|
||||
&mut hashing_reader,
|
||||
io::sink(),
|
||||
ota_sig.hashed_size,
|
||||
cancel_signal,
|
||||
)
|
||||
.map_err(|e| Error::DataRead("raw_data", e))?;
|
||||
|
||||
let (_, context) = hashing_reader.finish();
|
||||
let digest = context.finish();
|
||||
|
||||
// Verify the signature against the public key.
|
||||
public_key
|
||||
.verify_sig(algo, digest.as_ref(), signer.signature.as_bytes())
|
||||
.map_err(Error::CmsVerify)?;
|
||||
|
||||
Ok(cert.clone())
|
||||
/// Parse the signature information from the CMS signature embedded in the OTA
|
||||
/// zip archive comment.
|
||||
pub fn parse_ota_sig(reader: impl Read + Seek) -> Result<OtaSignature> {
|
||||
parse_raw_ota_sig(reader)?.try_into()
|
||||
}
|
||||
|
||||
/// Get and parse the protobuf-encoded OTA metadata, the PEM-encoded otacert,
|
||||
|
||||
+431
-77
@@ -1,22 +1,26 @@
|
||||
// SPDX-FileCopyrightText: 2022-2024 Andrew Gunnerson
|
||||
// SPDX-FileCopyrightText: 2022-2025 Andrew Gunnerson
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
fmt,
|
||||
io::{self, Cursor, Read, Seek, SeekFrom, Write},
|
||||
ops::Range,
|
||||
num::NonZeroU32,
|
||||
ops::{Add, Range},
|
||||
str::FromStr,
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use bzip2::write::BzDecoder;
|
||||
use flate2::{Compression, write::GzEncoder};
|
||||
use liblzma::{
|
||||
stream::{Check, Stream},
|
||||
write::XzDecoder,
|
||||
write::XzEncoder,
|
||||
};
|
||||
use num_traits::CheckedAdd;
|
||||
use prost::Message;
|
||||
use rayon::{
|
||||
iter::{IndexedParallelIterator, IntoParallelRefMutIterator},
|
||||
@@ -26,14 +30,14 @@ use ring::digest::{Context, Digest};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
use x509_cert::Certificate;
|
||||
use zerocopy::{big_endian, FromBytes, IntoBytes};
|
||||
use zerocopy::{FromBytes, IntoBytes, big_endian};
|
||||
use zerocopy_derive::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};
|
||||
|
||||
use crate::{
|
||||
crypto::{self, RsaPublicKeyExt, RsaSigningKey, SignatureAlgorithm},
|
||||
protobuf::chromeos_update_engine::{
|
||||
install_operation::Type, signatures::Signature, DeltaArchiveManifest, Extent,
|
||||
InstallOperation, PartitionInfo, PartitionUpdate, Signatures,
|
||||
DeltaArchiveManifest, Extent, InstallOperation, PartitionInfo, PartitionUpdate, Signatures,
|
||||
install_operation::Type, signatures::Signature,
|
||||
},
|
||||
stream::{
|
||||
self, CountingReader, FromReader, HashingWriter, ReadDiscardExt, ReadFixedSizeExt,
|
||||
@@ -47,6 +51,11 @@ const PAYLOAD_VERSION: u64 = 2;
|
||||
|
||||
const MANIFEST_MAX_SIZE: usize = 4 * 1024 * 1024;
|
||||
|
||||
/// Size of each extent. This matches what AOSP's delta_generator does. We also
|
||||
/// require this to be a multiple of the block size and a multiple of the
|
||||
/// maximum CoW compression chunk size.
|
||||
const CHUNK_SIZE: u64 = 2 * 1024 * 1024;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
#[error("Unknown magic: {0:?}")]
|
||||
@@ -76,6 +85,10 @@ pub enum Error {
|
||||
expected: Option<String>,
|
||||
actual: String,
|
||||
},
|
||||
#[error("Invalid block size: {0}")]
|
||||
InvalidBlockSize(u32),
|
||||
#[error("Invalid maximum CoW compression chunk size: {0}")]
|
||||
InvalidMaxCompressionChunkSize(u32),
|
||||
#[error("Size of {name} ({size}) is not aligned to the block size ({block_size})")]
|
||||
InvalidPartitionSize {
|
||||
name: String,
|
||||
@@ -108,7 +121,9 @@ pub enum Error {
|
||||
DataWrite(&'static str, #[source] io::Error),
|
||||
#[error("Expected {expected} bytes, but only wrote {actual} bytes")]
|
||||
UnwrittenData { actual: u64, expected: u64 },
|
||||
#[error("I/O error when applying {op_type:?} operation for {num_blocks} blocks starting at {start_block}")]
|
||||
#[error(
|
||||
"I/O error when applying {op_type:?} operation for {num_blocks} blocks starting at {start_block}"
|
||||
)]
|
||||
OperationApply {
|
||||
op_type: Type,
|
||||
start_block: u64,
|
||||
@@ -121,6 +136,8 @@ pub enum Error {
|
||||
InputOpen(String, #[source] io::Error),
|
||||
#[error("Failed to open output file for partition: {0}")]
|
||||
OutputOpen(String, #[source] io::Error),
|
||||
#[error("Failed to GZ compress partition image chunk")]
|
||||
GzCompress(#[source] io::Error),
|
||||
#[error("Failed to initialize XZ encoder")]
|
||||
XzInit(#[source] liblzma::stream::Error),
|
||||
#[error("Failed to XZ compress partition image chunk")]
|
||||
@@ -135,7 +152,7 @@ type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Raw on-disk layout for the payload header.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawHeader {
|
||||
/// Magic value. This should be equal to [`PAYLOAD_MAGIC`].
|
||||
magic: [u8; 4],
|
||||
@@ -919,6 +936,8 @@ pub fn extract_images<'a>(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Compress raw data into a chunk to be used with a [`Type::ReplaceXz`]
|
||||
/// [`InstallOperation`].
|
||||
fn compress_chunk(raw_data: &[u8], cancel_signal: &AtomicBool) -> Result<(Vec<u8>, Digest)> {
|
||||
let reader = Cursor::new(raw_data);
|
||||
let writer = Cursor::new(Vec::new());
|
||||
@@ -943,51 +962,390 @@ fn compress_chunk(raw_data: &[u8], cancel_signal: &AtomicBool) -> Result<(Vec<u8
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub enum VabcAlgo {
|
||||
pub enum CowVersion {
|
||||
V2,
|
||||
V3,
|
||||
}
|
||||
|
||||
impl CowVersion {
|
||||
/// Compute the size overhead required to store the headers and footers
|
||||
/// needed for this version of the on-disk CoW format.
|
||||
fn size_overhead(self, cow_replace_ops: u64, payload_install_ops: u64) -> u64 {
|
||||
const BUFFER_REGION_DEFAULT_SIZE: u64 = 2 * 1024 * 1024;
|
||||
const CLUSTER_OPS: u64 = 200;
|
||||
const NUM_RESUME_POINTS: u64 = 4;
|
||||
const SIZEOF_COW_FOOTER_V2: u64 = 84;
|
||||
const SIZEOF_COW_HEADER_V2: u64 = 38;
|
||||
const SIZEOF_COW_HEADER_V3: u64 = SIZEOF_COW_HEADER_V2 + 40;
|
||||
const SIZEOF_COW_OPERATION_V2: u64 = 20;
|
||||
const SIZEOF_COW_OPERATION_V3: u64 = 16;
|
||||
const SIZEOF_RESUME_POINT_V3: u64 = 16;
|
||||
|
||||
let mut overhead = 0;
|
||||
|
||||
match self {
|
||||
Self::V2 => {
|
||||
// sizeof(CowHeader).
|
||||
// AOSP: CowWriterV2::InitPos()
|
||||
overhead += SIZEOF_COW_HEADER_V2;
|
||||
|
||||
// header_.buffer_size. update_engine uses the default value.
|
||||
// AOSP: CowWriterV2::InitPos()
|
||||
overhead += BUFFER_REGION_DEFAULT_SIZE;
|
||||
|
||||
// Add all the CoW operation headers:
|
||||
//
|
||||
// - There is a kCowReplaceOp for each compressed chunk.
|
||||
// - There is a kCowLabelOp for each InstallOperation in the
|
||||
// payload. This is added by delta_generator in CowDryRun().
|
||||
// - There is a kCowClusterOp at the end of each cluster of
|
||||
// operations (which includes the kCowClusterOp itself). The
|
||||
// cluster size used to be 200, but was changed to 1024 in
|
||||
// 5e8e488c13cbff9e0a305ce7c22fd6a13aabb886. We'll use the
|
||||
// smaller value because it's better to overestimate.
|
||||
//
|
||||
// AOSP: CowWriterV2::EmitClusterIfNeeded()
|
||||
let cow_label_ops = payload_install_ops;
|
||||
let cow_cluster_ops = (cow_replace_ops + cow_label_ops).div_ceil(CLUSTER_OPS - 1);
|
||||
|
||||
// A cluster cannot be truncated, so round up to the nearest
|
||||
// cluster boundary.
|
||||
// AOSP: CowWriterV2::AddOperation()
|
||||
overhead += cow_cluster_ops * CLUSTER_OPS * SIZEOF_COW_OPERATION_V2;
|
||||
|
||||
// sizeof(CowFooter).
|
||||
// AOSP: CowWriterV2::GetCowSizeInfo()
|
||||
overhead += SIZEOF_COW_FOOTER_V2;
|
||||
}
|
||||
Self::V3 => {
|
||||
// AOSP: CowWriterV3::OpenForWrite() -> GetDataOffset()
|
||||
overhead += SIZEOF_COW_HEADER_V3;
|
||||
overhead += BUFFER_REGION_DEFAULT_SIZE;
|
||||
overhead += NUM_RESUME_POINTS * SIZEOF_RESUME_POINT_V3;
|
||||
|
||||
// Add an operation header (sizeof(CowOperationV3)) for each
|
||||
// chunk of compressed data.
|
||||
// AOSP: CowWriterV3::WriteOperation()
|
||||
overhead += cow_replace_ops * SIZEOF_COW_OPERATION_V3;
|
||||
}
|
||||
}
|
||||
|
||||
overhead
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum ChunkingMethod {
|
||||
/// Compress data in block sized chunks each iteration.
|
||||
Exact,
|
||||
/// Compress data in chunks where each chunk is sized at the largest power
|
||||
/// of 2 that's `<=` the specified size and the remaining input size.
|
||||
MaxPowerOf2(NonZeroU32),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct ChunkingParams {
|
||||
block_size: u32,
|
||||
method: ChunkingMethod,
|
||||
}
|
||||
|
||||
impl ChunkingParams {
|
||||
fn chunk_size(self, num_blocks: u64) -> u32 {
|
||||
match self.method {
|
||||
ChunkingMethod::Exact => self.block_size,
|
||||
ChunkingMethod::MaxPowerOf2(max_chunk_size) => {
|
||||
assert!(
|
||||
max_chunk_size.is_power_of_two() && max_chunk_size.get() % self.block_size == 0
|
||||
);
|
||||
|
||||
let mut chunk_size = max_chunk_size.get();
|
||||
while chunk_size > self.block_size {
|
||||
let min_blocks = chunk_size / self.block_size;
|
||||
if num_blocks >= u64::from(min_blocks) {
|
||||
return chunk_size;
|
||||
}
|
||||
|
||||
chunk_size >>= 1;
|
||||
}
|
||||
|
||||
self.block_size
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct CowEstimate {
|
||||
/// Size of estimate in bytes.
|
||||
pub size: u64,
|
||||
/// Number of CoW operations (v3 only).
|
||||
pub num_ops: u64,
|
||||
}
|
||||
|
||||
impl CowEstimate {
|
||||
/// Add fudge factor to account for overhead.
|
||||
fn fudged(&self, payload_install_ops: u64, cow_version: CowVersion) -> Option<Self> {
|
||||
let version_overhead = cow_version.size_overhead(self.num_ops, payload_install_ops);
|
||||
|
||||
let mut size = self.size.checked_add(version_overhead)?;
|
||||
|
||||
// delta_generator adds 1% overhead to the original CoW size estimate,
|
||||
// even if compression is disabled. We'll do the same too. For the
|
||||
// compressed scenario, we rely on this more because lz4_flex and
|
||||
// zlib-rs usually compress better than the lz4 and zlib implementations
|
||||
// used by libsnapshot_cow.
|
||||
size += size / 100;
|
||||
|
||||
// AOSP: PartitionProcessor::Run()
|
||||
let num_ops = self.num_ops.max(25);
|
||||
|
||||
Some(Self { size, num_ops })
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for CowEstimate {
|
||||
type Output = Self;
|
||||
|
||||
fn add(self, rhs: Self) -> Self::Output {
|
||||
Self {
|
||||
size: self.size + rhs.size,
|
||||
num_ops: self.num_ops + rhs.num_ops,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CheckedAdd for CowEstimate {
|
||||
fn checked_add(&self, rhs: &Self) -> Option<Self> {
|
||||
Some(Self {
|
||||
size: self.size.checked_add(rhs.size)?,
|
||||
num_ops: self.num_ops.checked_add(rhs.num_ops)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub enum VabcAlgoKind {
|
||||
None,
|
||||
Lz4,
|
||||
Gzip,
|
||||
Gz,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct VabcAlgo {
|
||||
/// Compression algorithm.
|
||||
pub kind: VabcAlgoKind,
|
||||
/// Compression level. AOSP allows this to be present even if the algorithm
|
||||
/// can't use it.
|
||||
pub level: Option<u32>,
|
||||
}
|
||||
|
||||
impl VabcAlgo {
|
||||
pub fn new(name: &str) -> Option<Self> {
|
||||
match name {
|
||||
"lz4" => Some(Self::Lz4),
|
||||
"gz" => Some(Self::Gzip),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Compute the compressed size of the raw data when split into chunks based
|
||||
/// on the specified [`ChunkingParams`]. The length of `raw_data` must be a
|
||||
/// multiple of the block size or else this will panic. The compressed data
|
||||
/// for each chunk is temporarily stored in memory, but discarded after each
|
||||
/// loop iteration.
|
||||
fn compressed_size(self, mut raw_data: &[u8], chunking: ChunkingParams) -> Result<CowEstimate> {
|
||||
assert!(raw_data.len() as u64 % u64::from(chunking.block_size) == 0);
|
||||
|
||||
fn compressed_size(self, mut raw_data: &[u8], block_size: u32) -> u64 {
|
||||
let mut total = 0;
|
||||
let mut size = 0;
|
||||
let mut num_ops = 0;
|
||||
|
||||
while !raw_data.is_empty() {
|
||||
let n = raw_data.len().min(block_size as usize);
|
||||
let compressed = match self {
|
||||
Self::Lz4 => lz4_flex::block::compress(&raw_data[..n]),
|
||||
// We use the miniz_oxide backend for flate2, but flate2 doesn't
|
||||
// expose a nice function for compressing to a vec, so just use
|
||||
// miniz_oxide directly.
|
||||
Self::Gzip => miniz_oxide::deflate::compress_to_vec_zlib(&raw_data[..n], 9),
|
||||
let num_blocks = raw_data.len() as u64 / u64::from(chunking.block_size);
|
||||
let chunk_size = chunking.chunk_size(num_blocks) as usize;
|
||||
let (chunk, remaining) = raw_data.split_at(chunk_size);
|
||||
|
||||
// This should match CompressWorker::GetDefaultCompressionLevel() in
|
||||
// AOSP's libsnapshot.
|
||||
//
|
||||
// CoW v3 uses the raw data instead of the compressed data if the
|
||||
// raw data is smaller. Because we use a different implementation of
|
||||
// the compression algorithms, we don't implement this. It's safer
|
||||
// to just overestimate and use the (larger) compressed size.
|
||||
size += match self.kind {
|
||||
VabcAlgoKind::None => chunk_size as u64,
|
||||
VabcAlgoKind::Lz4 => lz4_flex::block::compress(chunk).len() as u64,
|
||||
VabcAlgoKind::Gz => {
|
||||
let level = self.level.map_or(Compression::best(), Compression::new);
|
||||
let mut encoder = GzEncoder::new(Vec::new(), level);
|
||||
encoder.write_all(chunk).map_err(Error::GzCompress)?;
|
||||
encoder.finish().map_err(Error::GzCompress)?.len() as u64
|
||||
}
|
||||
};
|
||||
|
||||
total += compressed.len().min(n) as u64;
|
||||
|
||||
raw_data = &raw_data[n..];
|
||||
num_ops += 1;
|
||||
raw_data = remaining;
|
||||
}
|
||||
|
||||
total
|
||||
Ok(CowEstimate { size, num_ops })
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for VabcAlgo {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Lz4 => f.write_str("lz4"),
|
||||
Self::Gzip => f.write_str("gz"),
|
||||
let name = match self.kind {
|
||||
VabcAlgoKind::None => "none",
|
||||
VabcAlgoKind::Lz4 => "lz4",
|
||||
VabcAlgoKind::Gz => "gz",
|
||||
};
|
||||
|
||||
f.write_str(name)?;
|
||||
|
||||
if let Some(level) = self.level {
|
||||
write!(f, ",{level}")?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Error)]
|
||||
#[error("Invalid VABC algorithm: {0:?} (must be {{none|lz4|gz}}[,<level>])")]
|
||||
pub struct InvalidVabcAlgo(String);
|
||||
|
||||
impl FromStr for VabcAlgo {
|
||||
type Err = InvalidVabcAlgo;
|
||||
|
||||
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
|
||||
let (prefix, suffix) = s.split_once(',').unwrap_or((s, ""));
|
||||
|
||||
// AOSP allows any algorithm to accept a level, even if it's unused.
|
||||
let level = if !suffix.is_empty() {
|
||||
Some(suffix.parse().map_err(|_| InvalidVabcAlgo(s.to_owned()))?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let kind = match prefix {
|
||||
"" | "none" => VabcAlgoKind::None,
|
||||
"lz4" => VabcAlgoKind::Lz4,
|
||||
"gz" => VabcAlgoKind::Gz,
|
||||
_ => return Err(InvalidVabcAlgo(s.to_owned())),
|
||||
};
|
||||
|
||||
Ok(Self { kind, level })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct VabcParams {
|
||||
/// CoW on-disk format version.
|
||||
pub version: CowVersion,
|
||||
/// CoW compression algorithm.
|
||||
pub algo: VabcAlgo,
|
||||
/// The maximum number of bytes to compress at a time.
|
||||
pub compression_factor: u32,
|
||||
}
|
||||
|
||||
/// Ensure that the partition size is aligned to the block size and that the
|
||||
/// block size and compression factor are factors of our [`CHUNK_SIZE`].
|
||||
fn validate_partition_size(
|
||||
partition_name: &str,
|
||||
file_size: u64,
|
||||
block_size: u32,
|
||||
compression_factor: u32,
|
||||
) -> Result<()> {
|
||||
if block_size == 0 || !block_size.is_power_of_two() || CHUNK_SIZE % u64::from(block_size) != 0 {
|
||||
return Err(Error::InvalidBlockSize(block_size));
|
||||
}
|
||||
|
||||
if compression_factor == 0
|
||||
|| !compression_factor.is_power_of_two()
|
||||
|| CHUNK_SIZE % u64::from(compression_factor) != 0
|
||||
{
|
||||
return Err(Error::InvalidMaxCompressionChunkSize(compression_factor));
|
||||
}
|
||||
|
||||
if file_size % u64::from(block_size) != 0 {
|
||||
return Err(Error::InvalidPartitionSize {
|
||||
name: partition_name.to_owned(),
|
||||
size: file_size,
|
||||
block_size,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compute the VABC CoW size estimate. For a more accurate size estimate with
|
||||
/// CoW version 2, `payload_install_ops` must be equal to the number of
|
||||
/// [`InstallOperation`]s in the payload. The caller must update
|
||||
/// [`PartitionUpdate::estimate_cow_size`] and
|
||||
/// [`PartitionUpdate::estimate_op_count_max`] or else update_engine may fail to
|
||||
/// flash the partition due to running out of space on the CoW block device.
|
||||
pub fn compute_cow_estimate(
|
||||
input: &(dyn ReadSeekReopen + Sync),
|
||||
payload_install_ops: u64,
|
||||
partition_name: &str,
|
||||
block_size: u32,
|
||||
vabc_params: VabcParams,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<CowEstimate> {
|
||||
let file_size = input
|
||||
.reopen_boxed()
|
||||
.and_then(|mut r| r.seek(SeekFrom::End(0)))
|
||||
.map_err(|e| Error::InputOpen(partition_name.to_owned(), e))?;
|
||||
let final_chunk_different = file_size % CHUNK_SIZE != 0;
|
||||
|
||||
validate_partition_size(
|
||||
partition_name,
|
||||
file_size,
|
||||
block_size,
|
||||
vabc_params.compression_factor,
|
||||
)?;
|
||||
|
||||
let chunking = ChunkingParams {
|
||||
block_size,
|
||||
method: match vabc_params.version {
|
||||
CowVersion::V2 => ChunkingMethod::Exact,
|
||||
CowVersion::V3 => {
|
||||
ChunkingMethod::MaxPowerOf2(vabc_params.compression_factor.try_into().unwrap())
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let chunks_total = file_size.div_ceil(CHUNK_SIZE);
|
||||
|
||||
let initial_estimate = (0..chunks_total)
|
||||
.into_par_iter()
|
||||
.map(|chunk| -> Result<CowEstimate> {
|
||||
let data = (|| {
|
||||
let mut reader = input.reopen_boxed()?;
|
||||
reader.seek(SeekFrom::Start(chunk * CHUNK_SIZE))?;
|
||||
|
||||
let chunk_size = if final_chunk_different && chunk == chunks_total - 1 {
|
||||
file_size % CHUNK_SIZE
|
||||
} else {
|
||||
CHUNK_SIZE
|
||||
};
|
||||
|
||||
stream::check_cancel(cancel_signal)?;
|
||||
reader.read_vec_exact(chunk_size as usize)
|
||||
})()
|
||||
.map_err(Error::ChunkRead)?;
|
||||
|
||||
vabc_params.algo.compressed_size(&data, chunking)
|
||||
})
|
||||
.try_fold(
|
||||
CowEstimate::default,
|
||||
|total, chunk_estimate| -> Result<CowEstimate> {
|
||||
total
|
||||
.checked_add(&chunk_estimate?)
|
||||
.ok_or(Error::IntOverflow("initial_estimate"))
|
||||
},
|
||||
)
|
||||
.try_reduce(CowEstimate::default, |total, partial| {
|
||||
total
|
||||
.checked_add(&partial)
|
||||
.ok_or(Error::IntOverflow("initial_estimate"))
|
||||
})?;
|
||||
|
||||
initial_estimate
|
||||
.fudged(payload_install_ops, vabc_params.version)
|
||||
.ok_or(Error::IntOverflow("fudged_estimate"))
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -996,21 +1354,17 @@ impl fmt::Display for VabcAlgo {
|
||||
/// update [`InstallOperation::data_offset`] in each operation manually because
|
||||
/// the initial values are relative to 0.
|
||||
///
|
||||
/// If `vabc_algo` is set, the VABC CoW v2 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.
|
||||
/// If `vabc_algo` is set, the VABC CoW size estimate will also be computed.
|
||||
/// This is more efficient than separately calling [`compute_cow_estimate`]
|
||||
/// since the input does not need to be read twice.
|
||||
pub fn compress_image(
|
||||
input: &(dyn ReadSeekReopen + Sync),
|
||||
output: &(dyn WriteSeekReopen + Sync),
|
||||
partition_name: &str,
|
||||
block_size: u32,
|
||||
vabc_algo: Option<VabcAlgo>,
|
||||
vabc_params: Option<VabcParams>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<(PartitionInfo, Vec<InstallOperation>, Option<u64>)> {
|
||||
const CHUNK_SIZE: u64 = 2 * 1024 * 1024;
|
||||
) -> Result<(PartitionInfo, Vec<InstallOperation>, Option<CowEstimate>)> {
|
||||
const CHUNK_GROUP: u64 = 32;
|
||||
|
||||
let file_size = input
|
||||
@@ -1019,18 +1373,23 @@ pub fn compress_image(
|
||||
.map_err(|e| Error::InputOpen(partition_name.to_owned(), e))?;
|
||||
let final_chunk_different = file_size % CHUNK_SIZE != 0;
|
||||
|
||||
if file_size % u64::from(block_size) != 0 || CHUNK_SIZE % u64::from(block_size) != 0 {
|
||||
return Err(Error::InvalidPartitionSize {
|
||||
name: partition_name.to_owned(),
|
||||
size: file_size,
|
||||
block_size,
|
||||
});
|
||||
}
|
||||
let compression_factor = vabc_params.map_or(block_size, |p| p.compression_factor);
|
||||
validate_partition_size(partition_name, file_size, block_size, compression_factor)?;
|
||||
|
||||
let chunking = ChunkingParams {
|
||||
block_size,
|
||||
method: match vabc_params.map(|p| p.version) {
|
||||
Some(CowVersion::V3) => {
|
||||
ChunkingMethod::MaxPowerOf2(compression_factor.try_into().unwrap())
|
||||
}
|
||||
_ => ChunkingMethod::Exact,
|
||||
},
|
||||
};
|
||||
|
||||
let chunks_total = file_size.div_ceil(CHUNK_SIZE);
|
||||
let mut bytes_compressed = 0;
|
||||
let mut bytes_compressed = 0u64;
|
||||
let mut context_uncompressed = Context::new(&ring::digest::SHA256);
|
||||
let mut cow_estimate = 0;
|
||||
let mut initial_estimate = CowEstimate::default();
|
||||
let mut operations = vec![];
|
||||
|
||||
// Read the file one group at a time. This allows for some parallelization
|
||||
@@ -1067,10 +1426,12 @@ pub fn compress_image(
|
||||
let mut compressed_data_group = uncompressed_data_group
|
||||
.into_par_iter()
|
||||
.map(
|
||||
|(raw_offset, raw_data)| -> Result<(Vec<u8>, InstallOperation, u64)> {
|
||||
|(raw_offset, raw_data)| -> Result<(Vec<u8>, InstallOperation, CowEstimate)> {
|
||||
let (data, digest_compressed) = compress_chunk(&raw_data, cancel_signal)?;
|
||||
let cow_size =
|
||||
vabc_algo.map_or(0, |a| a.compressed_size(&raw_data, block_size));
|
||||
let cow_estimate = vabc_params
|
||||
.map(|p| p.algo.compressed_size(&raw_data, chunking))
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
|
||||
let extent = Extent {
|
||||
start_block: Some(raw_offset / u64::from(block_size)),
|
||||
@@ -1083,15 +1444,19 @@ pub fn compress_image(
|
||||
operation.dst_extents.push(extent);
|
||||
operation.data_sha256_hash = Some(digest_compressed.as_ref().to_vec());
|
||||
|
||||
Ok((data, operation, cow_size))
|
||||
Ok((data, operation, cow_estimate))
|
||||
},
|
||||
)
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
|
||||
for (data, operation, cow_size) in &mut compressed_data_group {
|
||||
for (data, operation, cow_estimate) in &mut compressed_data_group {
|
||||
operation.data_offset = Some(bytes_compressed);
|
||||
bytes_compressed += data.len() as u64;
|
||||
cow_estimate += *cow_size;
|
||||
bytes_compressed = bytes_compressed
|
||||
.checked_add(data.len() as u64)
|
||||
.ok_or(Error::IntOverflow("bytes_compressed"))?;
|
||||
initial_estimate = initial_estimate
|
||||
.checked_add(cow_estimate)
|
||||
.ok_or(Error::IntOverflow("initial_estimate"))?;
|
||||
}
|
||||
|
||||
let group_operations = compressed_data_group
|
||||
@@ -1115,25 +1480,12 @@ pub fn compress_image(
|
||||
hash: Some(digest_uncompressed.as_ref().to_vec()),
|
||||
};
|
||||
|
||||
let cow_estimate = if vabc_algo.is_some() {
|
||||
// lz4_flex and miniz_oxide usually compress better than the lz4 and
|
||||
// zlib implementations used by libsnapshot_cow. Make up for this by
|
||||
// adding percentage-based overhead.
|
||||
cow_estimate += cow_estimate / 100;
|
||||
|
||||
// We also need to account for constant overhead, especially with
|
||||
// smaller partitions. We can match what delta_generator normally adds
|
||||
// in CowWriterV2::InitPos() exactly. Since we only ever create full
|
||||
// OTAs, we can assume that all CoW operations are kCowReplaceOp.
|
||||
|
||||
// sizeof(CowHeader).
|
||||
cow_estimate += 38;
|
||||
// header_.buffer_size (equal to BUFFER_REGION_DEFAULT_SIZE).
|
||||
cow_estimate += 2 * 1024 * 1024;
|
||||
// CowOptions::cluster_ops * sizeof(CowOperationV2).
|
||||
cow_estimate += 200 * 20;
|
||||
|
||||
Some(cow_estimate)
|
||||
let cow_estimate = if let Some(p) = vabc_params {
|
||||
Some(
|
||||
initial_estimate
|
||||
.fudged(operations.len() as u64, p.version)
|
||||
.ok_or(Error::IntOverflow("fudged_estimate"))?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -1280,6 +1632,8 @@ pub fn compress_modified_image(
|
||||
writer.seek(SeekFrom::Start(operation.data_offset.unwrap()))?;
|
||||
writer.write_all(&data)?;
|
||||
|
||||
// Clippy doesn't know we're returning a Range.
|
||||
#[allow(clippy::range_plus_one)]
|
||||
Ok(i..i + 1)
|
||||
})
|
||||
.collect::<io::Result<Vec<_>>>()
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::{
|
||||
use crc32fast::Hasher;
|
||||
use dlv_list::{Index, VecList};
|
||||
use thiserror::Error;
|
||||
use zerocopy::{byteorder::little_endian, FromBytes, IntoBytes};
|
||||
use zerocopy::{FromBytes, IntoBytes, byteorder::little_endian};
|
||||
use zerocopy_derive::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};
|
||||
|
||||
use crate::stream::ReadDiscardExt;
|
||||
@@ -106,7 +106,7 @@ type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Raw on-disk layout for the header.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawHeader {
|
||||
/// Magic value. This should be equal to [`HEADER_MAGIC`].
|
||||
magic: little_endian::U32,
|
||||
@@ -159,7 +159,7 @@ impl RawHeader {
|
||||
return Err(Error::UnsupportedMajorVersion(self.major_version.get()));
|
||||
}
|
||||
|
||||
if self.file_hdr_sz.get() < mem::size_of::<RawHeader>() as u16 {
|
||||
if self.file_hdr_sz.get() < mem::size_of::<Self>() as u16 {
|
||||
return Err(Error::InvalidFileHeaderSize(self.file_hdr_sz.get()));
|
||||
} else if self.chunk_hdr_sz.get() < mem::size_of::<RawChunk>() as u16 {
|
||||
return Err(Error::InvalidChunkHeaderSize(self.chunk_hdr_sz.get()));
|
||||
@@ -173,7 +173,7 @@ impl RawHeader {
|
||||
}
|
||||
|
||||
fn excess_raw_header_bytes(&self) -> u16 {
|
||||
self.file_hdr_sz.get() - mem::size_of::<RawHeader>() as u16
|
||||
self.file_hdr_sz.get() - mem::size_of::<Self>() as u16
|
||||
}
|
||||
|
||||
fn excess_raw_chunk_bytes(&self) -> u16 {
|
||||
@@ -183,7 +183,7 @@ impl RawHeader {
|
||||
|
||||
/// Raw on-disk layout for the chunk header.
|
||||
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
|
||||
#[repr(packed)]
|
||||
#[repr(C, packed)]
|
||||
struct RawChunk {
|
||||
/// Chunk type. Must be [`CHUNK_TYPE_RAW`], [`CHUNK_TYPE_FILL`],
|
||||
/// [`CHUNK_TYPE_DONT_CARE`], or [`CHUNK_TYPE_CRC32`].
|
||||
@@ -225,7 +225,7 @@ impl RawChunk {
|
||||
return Err(Error::InvalidChunkType {
|
||||
index,
|
||||
chunk_type: t,
|
||||
})
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -811,7 +811,7 @@ impl<R: Read> SparseReader<R> {
|
||||
data = ChunkData::Crc32(expected.get());
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
}
|
||||
|
||||
let chunk = Chunk {
|
||||
bounds: ChunkBounds {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// SPDX-FileCopyrightText: 2025 Andrew Gunnerson
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::io::{self, Seek, SeekFrom, Write};
|
||||
|
||||
use zip::{
|
||||
ZipWriter,
|
||||
result::ZipResult,
|
||||
write::{FileOptionExtension, FileOptions, StreamWriter},
|
||||
};
|
||||
|
||||
/// A wrapper around a seekable writer. `W` must implement [`Seek`], but only
|
||||
/// during the creation of a new instance. The resulting type can be stored in a
|
||||
/// parent container where the generic type does not implement [`Seek`].
|
||||
pub struct SeekWriter<W: Write> {
|
||||
inner: W,
|
||||
seek_fn: fn(&mut W, SeekFrom) -> io::Result<u64>,
|
||||
}
|
||||
|
||||
impl<W: Write> SeekWriter<W> {
|
||||
pub fn into_inner(self) -> W {
|
||||
self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write + Seek> SeekWriter<W> {
|
||||
pub fn new(inner: W) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
seek_fn: W::seek,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write> Write for SeekWriter<W> {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.inner.write(buf)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.inner.flush()
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write> Seek for SeekWriter<W> {
|
||||
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
|
||||
(self.seek_fn)(&mut self.inner, pos)
|
||||
}
|
||||
}
|
||||
|
||||
/// This is an ugly hack to have a single type represent both seekable and
|
||||
/// streaming [`ZipWriter`]s. `W` only needs to implement [`Seek`] when creating
|
||||
/// a seekable instance via [`Self::new_seekable`].
|
||||
pub enum ZipWriterWrapper<W: Write> {
|
||||
Streaming(ZipWriter<StreamWriter<W>>),
|
||||
Seekable(ZipWriter<SeekWriter<W>>),
|
||||
}
|
||||
|
||||
impl<W: Write + Seek> ZipWriterWrapper<W> {
|
||||
pub fn new_seekable(inner: W) -> Self {
|
||||
Self::Seekable(ZipWriter::new(SeekWriter::new(inner)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write> ZipWriterWrapper<W> {
|
||||
pub fn new_streaming(inner: W) -> Self {
|
||||
Self::Streaming(ZipWriter::new_stream(inner))
|
||||
}
|
||||
|
||||
pub fn start_file(
|
||||
&mut self,
|
||||
name: impl ToString,
|
||||
options: FileOptions<impl FileOptionExtension>,
|
||||
) -> ZipResult<u64> {
|
||||
match self {
|
||||
Self::Streaming(z) => z.start_file(name, options),
|
||||
Self::Seekable(z) => z.start_file(name, options),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finish(self) -> ZipResult<W> {
|
||||
match self {
|
||||
Self::Streaming(z) => Ok(z.finish()?.into_inner()),
|
||||
Self::Seekable(z) => Ok(z.finish()?.into_inner()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write> Write for ZipWriterWrapper<W> {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
match self {
|
||||
Self::Streaming(z) => z.write(buf),
|
||||
Self::Seekable(z) => z.write(buf),
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
match self {
|
||||
Self::Streaming(z) => z.flush(),
|
||||
Self::Seekable(z) => z.flush(),
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -4,8 +4,8 @@
|
||||
use std::{
|
||||
process::ExitCode,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::{
|
||||
};
|
||||
|
||||
use num_traits::{Num, PrimInt};
|
||||
use serde::{de::Visitor, Deserializer, Serializer};
|
||||
use serde::{Deserializer, Serializer, de::Visitor};
|
||||
|
||||
pub fn serialize<S, T>(data: &T, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
|
||||
@@ -24,9 +24,9 @@ use regex::bytes::Regex;
|
||||
use ring::digest::Context;
|
||||
use rsa::RsaPublicKey;
|
||||
use thiserror::Error;
|
||||
use tracing::{debug, debug_span, trace, warn, Span};
|
||||
use tracing::{Span, debug, debug_span, trace, warn};
|
||||
use x509_cert::Certificate;
|
||||
use zip::{result::ZipError, ZipArchive};
|
||||
use zip::{ZipArchive, result::ZipError};
|
||||
|
||||
use crate::{
|
||||
crypto::{self, RsaSigningKey},
|
||||
@@ -194,7 +194,7 @@ impl MagiskRootPatcher {
|
||||
// replaced by PREINITDEVICE
|
||||
// - Versions newer than the latest supported version are assumed to support
|
||||
// the same features as the latest version
|
||||
const VERS_SUPPORTED: &'static [Range<u32>] = &[25102..25207, 25211..28200];
|
||||
const VERS_SUPPORTED: &'static [Range<u32>] = &[25102..25207, 25211..30100];
|
||||
const VER_PREINIT_DEVICE: RangeFrom<u32> = 25211..;
|
||||
const VER_RANDOM_SEED: Range<u32> = 25211..26103;
|
||||
const VER_PATCH_VBMETA: Range<u32> = Self::VERS_SUPPORTED[0].start..26202;
|
||||
@@ -432,7 +432,7 @@ impl BootImagePatch for MagiskRootPatcher {
|
||||
targets.push("init_boot");
|
||||
} else if boot_images.contains_key("boot") {
|
||||
targets.push("boot");
|
||||
};
|
||||
}
|
||||
|
||||
Ok(targets)
|
||||
}
|
||||
@@ -781,7 +781,7 @@ impl DsuPubKeyPatcher {
|
||||
e.data = data;
|
||||
} else {
|
||||
entries.push(CpioEntry::new_file(Self::AVBROOT_KEY_PATH, 0o644, data));
|
||||
};
|
||||
}
|
||||
|
||||
*ramdisk = save_ramdisk(&entries, ramdisk_format, cancel_signal)?;
|
||||
|
||||
@@ -971,7 +971,7 @@ impl BootImagePatch for PrepatchedImagePatcher {
|
||||
targets.push("init_boot");
|
||||
} else if boot_images.contains_key("boot") {
|
||||
targets.push("boot");
|
||||
};
|
||||
}
|
||||
|
||||
Ok(targets)
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@ use std::{borrow::Cow, cmp::Ordering, io::Cursor, path::Path};
|
||||
use bitflags::bitflags;
|
||||
use thiserror::Error;
|
||||
use tracing::trace;
|
||||
use x509_cert::{der::asn1::BitString, Certificate};
|
||||
use zip::{result::ZipError, write::FileOptions, CompressionMethod, ZipWriter};
|
||||
use x509_cert::{Certificate, der::asn1::BitString};
|
||||
use zip::{CompressionMethod, DateTime, ZipWriter, result::ZipError, write::SimpleFileOptions};
|
||||
|
||||
use crate::{crypto, format::ota};
|
||||
|
||||
@@ -79,7 +79,9 @@ pub fn create_zip(cert: &Certificate, flags: OtaCertBuildFlags) -> Result<Vec<u8
|
||||
CompressionMethod::Stored
|
||||
};
|
||||
|
||||
let options = FileOptions::default().compression_method(compression_method);
|
||||
let options = SimpleFileOptions::default()
|
||||
.last_modified_time(DateTime::default())
|
||||
.compression_method(compression_method);
|
||||
let name = "ota.x509.pem";
|
||||
writer.start_file(name, options).map_err(Error::ZipWrite)?;
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::{
|
||||
use memchr::memmem;
|
||||
use rayon::iter::{IntoParallelIterator, ParallelIterator};
|
||||
use thiserror::Error;
|
||||
use tracing::{debug, debug_span, trace, Span};
|
||||
use tracing::{Span, debug, debug_span, trace};
|
||||
use x509_cert::Certificate;
|
||||
use zip::ZipArchive;
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#![allow(clippy::all)]
|
||||
#![allow(clippy::nursery)]
|
||||
#![allow(clippy::pedantic)]
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@ use std::{
|
||||
fs::File,
|
||||
io::{self, BufReader, BufWriter, Cursor, Read, Seek, SeekFrom, Write},
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc, Mutex, RwLock,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -37,8 +37,8 @@ allow = [
|
||||
"GPL-3.0",
|
||||
"ISC",
|
||||
"MIT",
|
||||
"OpenSSL",
|
||||
"Unicode-3.0",
|
||||
"Zlib",
|
||||
]
|
||||
|
||||
[[licenses.clarify]]
|
||||
@@ -69,6 +69,5 @@ bypass = [
|
||||
unknown-registry = "deny"
|
||||
unknown-git = "deny"
|
||||
allow-git = [
|
||||
"https://github.com/chenxiaolong/zip",
|
||||
"https://github.com/trifectatechfoundation/bzip2-rs",
|
||||
"https://github.com/chenxiaolong/zip2",
|
||||
]
|
||||
|
||||
+6
-4
@@ -14,7 +14,7 @@ avbroot = { path = "../avbroot" }
|
||||
clap = { version = "4.4.1", features = ["derive"] }
|
||||
ctrlc = "3.4.0"
|
||||
hex = { version = "0.4.3", features = ["serde"] }
|
||||
ring = "0.17.0"
|
||||
ring = "0.17.14"
|
||||
rsa = { version = "0.9.6", features = ["hazmat"] }
|
||||
serde = { version = "1.0.188", features = ["derive"] }
|
||||
tempfile = "3.8.0"
|
||||
@@ -24,10 +24,12 @@ tracing = "0.1.40"
|
||||
tracing-subscriber = "0.3.18"
|
||||
x509-cert = "0.2.5"
|
||||
|
||||
# https://github.com/zip-rs/zip/pull/383
|
||||
# https://github.com/zip-rs/zip2/pull/367
|
||||
# https://github.com/zip-rs/zip2/pull/368
|
||||
# For getting the data offset when writing new zip entries.
|
||||
[dependencies.zip]
|
||||
git = "https://github.com/chenxiaolong/zip"
|
||||
rev = "989101f9384b9e94e36e6e9e0f51908fdf98bde6"
|
||||
git = "https://github.com/chenxiaolong/zip2"
|
||||
rev = "59685f4dadbfee8cb3ea74c8fbb402b60d8137e8"
|
||||
default-features = false
|
||||
|
||||
[features]
|
||||
|
||||
+26
-25
@@ -12,8 +12,10 @@ security_patch_level = "2024-01-01"
|
||||
# Google Pixel 7 Pro
|
||||
# What's unique: init_boot (boot v4) + vendor_boot (vendor v4)
|
||||
|
||||
[profile.pixel_v4_gki]
|
||||
vabc_algo = "Lz4"
|
||||
[profile.pixel_v4_gki.vabc]
|
||||
# CoW v3 is used starting with the Google Pixel 9a.
|
||||
version = "V3"
|
||||
algo = { kind = "Lz4" }
|
||||
|
||||
[profile.pixel_v4_gki.partitions.boot]
|
||||
avb.signed = true
|
||||
@@ -49,18 +51,19 @@ data.version = "vendor_v4"
|
||||
data.ramdisks = [["otacerts", "first_stage", "dsu_key_dir"]]
|
||||
|
||||
[profile.pixel_v4_gki.hashes_streaming]
|
||||
original = "c00f891f941f3dddb28966f7b07f3acea773bee104dace82b37c2d1341f09422"
|
||||
patched = "ce9d8ee97828d233809742a5d3f23aa27b042675b1935ca9e3df0592c55788fd"
|
||||
original = "ef6261cd9ebea90f036e52a46160a400c5b8f6ef24ed2469c4a1e9689987aa06"
|
||||
patched = "37fd353a766a7b9a339fbf51fa79c703e94640dc6a2c6310d79357aaefcc7ca1"
|
||||
|
||||
[profile.pixel_v4_gki.hashes_seekable]
|
||||
original = "96a6c366b5de1c3b10d4d6cb4ca503c83ac4cd9ca952a965cceb041990ba7022"
|
||||
patched = "e7b4609ba7a23609211dcae143bc43f091f286fbbb3a9301c02ee25614d35deb"
|
||||
original = "8a2c717607c10dfa5483d6f9a9f37b3d978acaf8d2ea18e36544af267943e750"
|
||||
patched = "2c4734c9e1d028ee6aaf02bb416e5e173857faffd2ca067366790655147b3afa"
|
||||
|
||||
# Google Pixel 6a
|
||||
# What's unique: boot (boot v4, no ramdisk) + vendor_boot (vendor v4, 2 ramdisks)
|
||||
|
||||
[profile.pixel_v4_non_gki]
|
||||
vabc_algo = "Lz4"
|
||||
[profile.pixel_v4_non_gki.vabc]
|
||||
version = "V2"
|
||||
algo = { kind = "Lz4" }
|
||||
|
||||
[profile.pixel_v4_non_gki.partitions.boot]
|
||||
avb.signed = true
|
||||
@@ -90,18 +93,19 @@ data.version = "vendor_v4"
|
||||
data.ramdisks = [["init", "otacerts", "first_stage", "dsu_key_dir"], ["dlkm"]]
|
||||
|
||||
[profile.pixel_v4_non_gki.hashes_streaming]
|
||||
original = "4d692bc777b568b0626d3c08d2e6f83f1b472db5ad903486daaec6a78d0cc26e"
|
||||
patched = "e27673e4f30933710c11d51f0e73849068cbe9bc9f54e6076bdd93f9a5c8ea0a"
|
||||
original = "630220ef813a2b4743d1941179cc9705da86ad4805f1c52341dcb38fbce3d29e"
|
||||
patched = "b725e91751fe58aed20495aecbf9b4bdc14d2799cd88dcbd58f3a3b02b3af15b"
|
||||
|
||||
[profile.pixel_v4_non_gki.hashes_seekable]
|
||||
original = "ea27ecd9718c17b63400b2548680bb3cee93ce63b4fc44ff9654ca0d9c5372a8"
|
||||
patched = "3456b14e014cf565a808a9e834d9105a23539f07b2c460db19c9384aadbc3b93"
|
||||
original = "1afbe6867ded345d941098ee7c7fcf94a3df52c50ff96ab8f3a67b2ab957259a"
|
||||
patched = "4357b977249006b101002c961916f962787315a80b8608494c6a1f0cf09cecd1"
|
||||
|
||||
# Google Pixel 4a 5G
|
||||
# What's unique: boot (boot v3) + vendor_boot (vendor v3)
|
||||
|
||||
[profile.pixel_v3]
|
||||
vabc_algo = "Lz4"
|
||||
[profile.pixel_v3.vabc]
|
||||
version = "V2"
|
||||
algo = { kind = "Gz" }
|
||||
|
||||
[profile.pixel_v3.partitions.boot]
|
||||
avb.signed = true
|
||||
@@ -132,19 +136,16 @@ data.version = "vendor_v3"
|
||||
data.ramdisks = [["otacerts", "first_stage", "dsu_key_dir"]]
|
||||
|
||||
[profile.pixel_v3.hashes_streaming]
|
||||
original = "f432dc7931520feb238474aa707dd5299747562ffe6129f3f763b5f11ac473ab"
|
||||
patched = "3850a2e73bd783a1ec4a70c59f37d2374e017c20df7ab4b591182b14d187c18e"
|
||||
original = "9b65037343d45211e0f9706929cba34643a9c54274d1b39740c43f45974984e0"
|
||||
patched = "fb23ab9616968b38b96d1e5e6a503154f89aebc1741e89a9e9dfd2c4d9946b05"
|
||||
|
||||
[profile.pixel_v3.hashes_seekable]
|
||||
original = "7d29ecc6780953c22052a576b8dc85066c8667a875e918a786a08ff4545b47d1"
|
||||
patched = "9f6342940b7cfbeb27b0567f006bb35cbee910ef038ec535403c662d5252ca71"
|
||||
original = "e581934887dd93b8a9d9c3aa5dec1d48aa7e01bf01ac507e8c5fb256b59cbe7d"
|
||||
patched = "669a826abc6d67e7e0b1def724aa7b470461087255c65663d195df1426a355f0"
|
||||
|
||||
# Google Pixel 4a
|
||||
# What's unique: boot (boot v2)
|
||||
|
||||
[profile.pixel_v2]
|
||||
vabc_algo = "Gzip"
|
||||
|
||||
[profile.pixel_v2.partitions.boot]
|
||||
avb.signed = false
|
||||
data.type = "boot"
|
||||
@@ -168,9 +169,9 @@ data.type = "vbmeta"
|
||||
data.deps = ["system"]
|
||||
|
||||
[profile.pixel_v2.hashes_streaming]
|
||||
original = "1b45235b58054009cc496f6c3ee11d3dc16ed5c388c861761e26a6fce83103a0"
|
||||
patched = "193b2dc70dd465d686f35c7b7f74d2cc1b06a55e48cf5c2e4df0f667e03032fc"
|
||||
original = "f10ee15c900a474cc6bbefa705f272cef42636ea096e75563d2d78f6c4327fd1"
|
||||
patched = "6929f65909037f5550a53982b71e96bdf69ab876bc5e86702c469ed601be8a9a"
|
||||
|
||||
[profile.pixel_v2.hashes_seekable]
|
||||
original = "52284308fae10cbaf09ade14e92f3bbe6149751a42bff15432982fcef8d890ab"
|
||||
patched = "7ad74ac87ddcaf34938017e6149a646041d70926e31ecda93e156e9397467b3b"
|
||||
original = "4e863d251b9ff6eaa1511f9c03e9bdb8919650b2e0eaf23e33892a639edafcaf"
|
||||
patched = "9a103222e73df70a097281525546d25c850df2ae7a2ba715aa5dfbbba3f7972b"
|
||||
|
||||
+21
-14
@@ -1,14 +1,14 @@
|
||||
// SPDX-FileCopyrightText: 2023-2024 Andrew Gunnerson
|
||||
// SPDX-FileCopyrightText: 2023-2025 Andrew Gunnerson
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::{collections::BTreeMap, fs, path::Path};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use avbroot::format::payload::VabcAlgo;
|
||||
use avbroot::format::payload::{CowVersion, VabcAlgo};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use toml_edit::DocumentMut;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Serialize, Deserialize)]
|
||||
pub struct Sha256Hash(
|
||||
#[serde(
|
||||
serialize_with = "hex::serialize",
|
||||
@@ -17,7 +17,7 @@ pub struct Sha256Hash(
|
||||
pub [u8; 32],
|
||||
);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct OtaInfo {
|
||||
pub device: String,
|
||||
@@ -29,7 +29,7 @@ pub struct OtaInfo {
|
||||
pub security_patch_level: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Avb {
|
||||
pub signed: bool,
|
||||
@@ -55,7 +55,7 @@ pub enum BootVersion {
|
||||
VendorV4,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct BootData {
|
||||
pub version: BootVersion,
|
||||
@@ -71,19 +71,19 @@ pub enum DmVerityContent {
|
||||
SystemOtacerts,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct DmVerityData {
|
||||
pub content: DmVerityContent,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct VbmetaData {
|
||||
pub deps: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum Data {
|
||||
Boot(BootData),
|
||||
@@ -91,30 +91,37 @@ pub enum Data {
|
||||
Vbmeta(VbmetaData),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Hashes {
|
||||
pub original: Sha256Hash,
|
||||
pub patched: Sha256Hash,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Partition {
|
||||
pub avb: Avb,
|
||||
pub data: Data,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct VabcSettings {
|
||||
pub version: CowVersion,
|
||||
pub algo: VabcAlgo,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Profile {
|
||||
pub vabc_algo: Option<VabcAlgo>,
|
||||
pub vabc: Option<VabcSettings>,
|
||||
pub partitions: BTreeMap<String, Partition>,
|
||||
pub hashes_streaming: Hashes,
|
||||
pub hashes_seekable: Hashes,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Config {
|
||||
pub ota_info: OtaInfo,
|
||||
|
||||
+59
-41
@@ -1,4 +1,4 @@
|
||||
// SPDX-FileCopyrightText: 2023-2024 Andrew Gunnerson
|
||||
// SPDX-FileCopyrightText: 2023-2025 Andrew Gunnerson
|
||||
// SPDX-FileCopyrightText: 2023 Pascal Roeleven
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
@@ -14,12 +14,12 @@ use std::{
|
||||
path::{Path, PathBuf},
|
||||
slice,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use avbroot::{
|
||||
cli::ota::{ExtractCli, PatchCli, VerifyCli},
|
||||
crypto::{self, PassphraseSource, RsaSigningKey},
|
||||
@@ -36,11 +36,12 @@ use avbroot::{
|
||||
cpio::{self, CpioEntry, CpioEntryData},
|
||||
ota::{self, SigningWriter, ZipEntry, ZipMode},
|
||||
padding,
|
||||
payload::{self, PayloadHeader, PayloadWriter},
|
||||
payload::{self, CowVersion, PayloadHeader, PayloadWriter, VabcParams},
|
||||
zip::ZipWriterWrapper,
|
||||
},
|
||||
patch::otacert::{self, OtaCertBuildFlags},
|
||||
protobuf::{
|
||||
build::tools::releasetools::{ota_metadata::OtaType, DeviceState, OtaMetadata},
|
||||
build::tools::releasetools::{DeviceState, OtaMetadata, ota_metadata::OtaType},
|
||||
chromeos_update_engine::{
|
||||
DeltaArchiveManifest, DynamicPartitionGroup, DynamicPartitionMetadata, PartitionUpdate,
|
||||
},
|
||||
@@ -48,12 +49,12 @@ use avbroot::{
|
||||
stream::{self, CountingWriter, FromReader, HashingReader, PSeekFile, Reopen, ToWriter},
|
||||
};
|
||||
use clap::Parser;
|
||||
use rsa::{rand_core::OsRng, traits::PublicKeyParts, BigUint};
|
||||
use rsa::{BigUint, rand_core::OsRng, traits::PublicKeyParts};
|
||||
use tempfile::TempDir;
|
||||
use topological_sort::TopologicalSort;
|
||||
use tracing::{info, info_span};
|
||||
use x509_cert::Certificate;
|
||||
use zip::{write::FileOptions, CompressionMethod, ZipWriter};
|
||||
use zip::{CompressionMethod, DateTime, ZipWriter, write::SimpleFileOptions};
|
||||
|
||||
use crate::{
|
||||
cli::{Cli, Command, HelperCli, ListCli, PassSource, ProfileGroup, TestCli},
|
||||
@@ -97,7 +98,7 @@ fn verify_hash(path: &Path, sha256: &[u8; 32], cancel_signal: &AtomicBool) -> Re
|
||||
fn append_avb(
|
||||
file: &mut PSeekFile,
|
||||
name: &str,
|
||||
avb: &Avb,
|
||||
avb: Avb,
|
||||
hash_tree: bool,
|
||||
ota_info: &OtaInfo,
|
||||
key_avb: &RsaSigningKey,
|
||||
@@ -295,7 +296,7 @@ fn create_ramdisk(
|
||||
fn create_boot_image(
|
||||
file: &mut PSeekFile,
|
||||
name: &str,
|
||||
avb: &Avb,
|
||||
avb: Avb,
|
||||
boot_data: &BootData,
|
||||
ota_info: &OtaInfo,
|
||||
key_avb: &RsaSigningKey,
|
||||
@@ -374,7 +375,7 @@ fn create_boot_image(
|
||||
.ramdisks
|
||||
.iter()
|
||||
.map(|c_list| {
|
||||
if c_list.iter().any(|c| *c == RamdiskContent::Dlkm) {
|
||||
if c_list.contains(&RamdiskContent::Dlkm) {
|
||||
RamdiskMeta {
|
||||
ramdisk_type: bootimage::VENDOR_RAMDISK_TYPE_DLKM,
|
||||
ramdisk_name: "dlkm".to_owned(),
|
||||
@@ -422,8 +423,8 @@ fn create_boot_image(
|
||||
fn create_dm_verity_image(
|
||||
file: &mut PSeekFile,
|
||||
name: &str,
|
||||
avb: &Avb,
|
||||
dm_verity_data: &DmVerityData,
|
||||
avb: Avb,
|
||||
dm_verity_data: DmVerityData,
|
||||
ota_info: &OtaInfo,
|
||||
key_avb: &RsaSigningKey,
|
||||
cert_ota: &Certificate,
|
||||
@@ -451,7 +452,7 @@ fn create_dm_verity_image(
|
||||
fn create_vbmeta_image(
|
||||
file: &mut PSeekFile,
|
||||
name: &str,
|
||||
avb: &Avb,
|
||||
avb: Avb,
|
||||
vbmeta_data: &VbmetaData,
|
||||
inputs: &BTreeMap<String, PSeekFile>,
|
||||
key: &RsaSigningKey,
|
||||
@@ -537,7 +538,7 @@ fn create_partition_images(
|
||||
create_boot_image(
|
||||
&mut file,
|
||||
name,
|
||||
&partition.avb,
|
||||
partition.avb,
|
||||
data,
|
||||
ota_info,
|
||||
key_avb,
|
||||
@@ -550,8 +551,8 @@ fn create_partition_images(
|
||||
create_dm_verity_image(
|
||||
&mut file,
|
||||
name,
|
||||
&partition.avb,
|
||||
data,
|
||||
partition.avb,
|
||||
*data,
|
||||
ota_info,
|
||||
key_avb,
|
||||
cert_ota,
|
||||
@@ -560,7 +561,7 @@ fn create_partition_images(
|
||||
.with_context(|| format!("Failed to create dm-verity image: {name}"))?;
|
||||
}
|
||||
Data::Vbmeta(data) => {
|
||||
create_vbmeta_image(&mut file, name, &partition.avb, data, &files, key_avb)
|
||||
create_vbmeta_image(&mut file, name, partition.avb, data, &files, key_avb)
|
||||
.with_context(|| format!("Failed to create vbmeta image: {name}"))?;
|
||||
}
|
||||
}
|
||||
@@ -580,6 +581,8 @@ fn create_payload(
|
||||
key_ota: &RsaSigningKey,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<(String, u64)> {
|
||||
const COMPRESSION_FACTOR: u32 = 64 * 1024;
|
||||
|
||||
let dynamic_partitions_names = partitions
|
||||
.iter()
|
||||
.filter(|(_, p)| matches!(&p.data, Data::DmVerity(_)))
|
||||
@@ -594,17 +597,23 @@ fn create_payload(
|
||||
.map(PSeekFile::new)
|
||||
.with_context(|| format!("Failed to create temp file for: {name}"))?;
|
||||
|
||||
let vabc_algo = if dynamic_partitions_names.contains(name) {
|
||||
profile.vabc_algo
|
||||
let vabc_params = if dynamic_partitions_names.contains(name) {
|
||||
profile.vabc.map(|v| VabcParams {
|
||||
version: v.version,
|
||||
algo: v.algo,
|
||||
compression_factor: COMPRESSION_FACTOR,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let (partition_info, operations, cow_estimate) =
|
||||
payload::compress_image(file, &writer, name, 4096, vabc_algo, cancel_signal)?;
|
||||
payload::compress_image(file, &writer, name, 4096, vabc_params, cancel_signal)?;
|
||||
|
||||
compressed.insert(name, writer);
|
||||
|
||||
let is_v3 = profile.vabc.is_some_and(|e| e.version == CowVersion::V3);
|
||||
|
||||
payload_partitions.push(PartitionUpdate {
|
||||
partition_name: name.clone(),
|
||||
run_postinstall: None,
|
||||
@@ -624,8 +633,8 @@ fn create_payload(
|
||||
fec_roots: None,
|
||||
version: None,
|
||||
merge_operations: vec![],
|
||||
estimate_cow_size: cow_estimate,
|
||||
estimate_op_count_max: None,
|
||||
estimate_cow_size: cow_estimate.map(|e| e.size),
|
||||
estimate_op_count_max: cow_estimate.and_then(|e| is_v3.then_some(e.num_ops)),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -645,11 +654,16 @@ fn create_payload(
|
||||
partition_names: dynamic_partitions_names,
|
||||
}],
|
||||
snapshot_enabled: Some(true),
|
||||
vabc_enabled: Some(true),
|
||||
vabc_compression_param: profile.vabc_algo.map(|a| a.to_string()),
|
||||
cow_version: Some(2),
|
||||
// Everything below is meant to be unset if VABC is not
|
||||
// supported.
|
||||
vabc_enabled: profile.vabc.map(|_| true),
|
||||
vabc_compression_param: profile.vabc.map(|v| v.algo.to_string()),
|
||||
cow_version: profile.vabc.map(|v| match v.version {
|
||||
CowVersion::V2 => 2,
|
||||
CowVersion::V3 => 3,
|
||||
}),
|
||||
vabc_feature_set: None,
|
||||
compression_factor: None,
|
||||
compression_factor: profile.vabc.map(|_| COMPRESSION_FACTOR.into()),
|
||||
}),
|
||||
partial_update: None,
|
||||
apex_info: vec![],
|
||||
@@ -728,14 +742,15 @@ fn create_ota(
|
||||
let mut zip_writer = match zip_mode {
|
||||
ZipMode::Streaming => {
|
||||
let signing_writer = SigningWriter::new_streaming(raw_writer);
|
||||
ZipWriter::new_streaming(signing_writer)
|
||||
ZipWriterWrapper::new_streaming(signing_writer)
|
||||
}
|
||||
ZipMode::Seekable => {
|
||||
let signing_writer = SigningWriter::new_seekable(raw_writer);
|
||||
ZipWriter::new(signing_writer)
|
||||
ZipWriterWrapper::new_seekable(signing_writer)
|
||||
}
|
||||
};
|
||||
let options = FileOptions::default()
|
||||
let options = SimpleFileOptions::default()
|
||||
.last_modified_time(DateTime::default())
|
||||
.compression_method(CompressionMethod::Stored)
|
||||
.large_file(false);
|
||||
|
||||
@@ -745,12 +760,9 @@ fn create_ota(
|
||||
|
||||
for path in [ota::PATH_OTACERT, ota::PATH_PAYLOAD, ota::PATH_PROPERTIES] {
|
||||
// All remaining entries are written immediately.
|
||||
zip_writer
|
||||
.start_file_with_extra_data(path, options)
|
||||
.with_context(|| format!("Failed to begin new zip entry: {path}"))?;
|
||||
let offset = zip_writer
|
||||
.end_extra_data()
|
||||
.with_context(|| format!("Failed to end new zip entry: {path}"))?;
|
||||
.start_file(path, options)
|
||||
.with_context(|| format!("Failed to begin new zip entry: {path}"))?;
|
||||
let mut writer = CountingWriter::new(&mut zip_writer);
|
||||
|
||||
match path {
|
||||
@@ -851,6 +863,7 @@ fn create_fake_magisk(output: &Path) -> Result<()> {
|
||||
let raw_writer =
|
||||
File::create(output).with_context(|| format!("Failed to open for writing: {output:?}"))?;
|
||||
let mut zip_writer = ZipWriter::new(raw_writer);
|
||||
let options = SimpleFileOptions::default().last_modified_time(DateTime::default());
|
||||
|
||||
for path in [
|
||||
"assets/stub.apk",
|
||||
@@ -867,12 +880,12 @@ fn create_fake_magisk(output: &Path) -> Result<()> {
|
||||
"lib/x86_64/libmagisk64.so",
|
||||
"lib/x86_64/libmagiskinit.so",
|
||||
] {
|
||||
zip_writer.start_file(path, FileOptions::default())?;
|
||||
zip_writer.start_file(path, options)?;
|
||||
write!(zip_writer, "dummy contents for {path}")?;
|
||||
}
|
||||
|
||||
// avbroot looks for the version number in this file.
|
||||
zip_writer.start_file("assets/util_functions.sh", FileOptions::default())?;
|
||||
zip_writer.start_file("assets/util_functions.sh", options)?;
|
||||
zip_writer.write_all(b"MAGISK_VER_CODE=27000\n")?;
|
||||
|
||||
Ok(())
|
||||
@@ -1127,7 +1140,7 @@ fn clean_boot_image_certs(path: &Path, cancel_signal: &AtomicBool) -> Result<()>
|
||||
.iter_mut()
|
||||
.find(|e| e.path == b"system/etc/security/otacerts.zip")
|
||||
{
|
||||
let mut zip_writer = ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let zip_writer = ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let empty_zip = zip_writer.finish()?.into_inner();
|
||||
|
||||
entry.data = CpioEntryData::Data(empty_zip);
|
||||
@@ -1189,6 +1202,7 @@ fn test_subcommand(cli: &TestCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
Some(_) => None,
|
||||
None => Some(TempDir::new().context("Failed to create temp directory")?),
|
||||
};
|
||||
#[allow(clippy::option_if_let_else)]
|
||||
let work_dir = match &cli.config.work_dir {
|
||||
Some(w) => w.as_path(),
|
||||
None => work_temp_dir.as_ref().unwrap().path(),
|
||||
@@ -1220,8 +1234,9 @@ fn test_subcommand(cli: &TestCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
] {
|
||||
let _span = info_span!("profile", name, %zip_mode).entered();
|
||||
|
||||
// Can't used NamedTempFile because avbroot does atomic replaces.
|
||||
let profile_dir = work_dir.join(name);
|
||||
// Can't use NamedTempFile because avbroot does atomic replaces.
|
||||
let mut profile_dir = work_dir.join(name);
|
||||
profile_dir.push(zip_mode.to_string());
|
||||
let out_original = profile_dir.join("ota.zip");
|
||||
let out_magisk = profile_dir.join("ota_magisk.zip");
|
||||
let out_prepatched = profile_dir.join("ota_prepatched.zip");
|
||||
@@ -1324,7 +1339,7 @@ fn helper_mode() -> Result<()> {
|
||||
let cli = HelperCli::parse();
|
||||
|
||||
let private_key_path = {
|
||||
let parent = cli.public_key.parent().unwrap_or(Path::new("."));
|
||||
let parent = cli.public_key.parent().unwrap_or_else(|| Path::new("."));
|
||||
let name = cli
|
||||
.public_key
|
||||
.file_name()
|
||||
@@ -1398,7 +1413,10 @@ fn main() -> Result<()> {
|
||||
if env::var_os(ENV_HELPER_MODE).is_some() {
|
||||
return helper_mode();
|
||||
}
|
||||
env::set_var(ENV_HELPER_MODE, "true");
|
||||
// SAFETY: No multithreading at this point.
|
||||
unsafe {
|
||||
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));
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
// SPDX-FileCopyrightText: 2023 Andrew Gunnerson
|
||||
// SPDX-FileCopyrightText: 2023-2025 Andrew Gunnerson
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
fmt,
|
||||
fmt::{self, Write as _},
|
||||
fs::{self, File},
|
||||
io::{BufRead, BufReader},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
use anyhow::{anyhow, bail, Result};
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use regex::Regex;
|
||||
|
||||
use crate::WORKSPACE_DIR;
|
||||
@@ -108,7 +108,7 @@ fn update_changelog_links(path: &Path, base_url: &str) -> Result<()> {
|
||||
}
|
||||
|
||||
for (link_ref, link) in links {
|
||||
result.push_str(&format!("{link_ref}: {link}\n"));
|
||||
let _ = writeln!(result, "{link_ref}: {link}");
|
||||
}
|
||||
|
||||
fs::write(path, result)?;
|
||||
|
||||
@@ -7,9 +7,9 @@ use std::{
|
||||
path::Path,
|
||||
};
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use anyhow::{Result, bail};
|
||||
use clap::Parser;
|
||||
use toml_edit::{value, DocumentMut};
|
||||
use toml_edit::{DocumentMut, value};
|
||||
|
||||
use crate::WORKSPACE_DIR;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user