mirror of
https://github.com/chenxiaolong/avbroot.git
synced 2026-07-03 14:05:11 +02:00
Compare commits
27 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| dff2fff028 | |||
| 67bca2e58c | |||
| 1f08cb6d40 | |||
| ed68f09cb9 | |||
| 64c11c2dc3 | |||
| 5115134b5a | |||
| a2d81d6bfe | |||
| c5709b90f6 | |||
| 2928b96f1f | |||
| 5638a8bb4d | |||
| a582d0b3e6 | |||
| 1d08ffa527 | |||
| a95ce56246 | |||
| ca6ce1fb37 | |||
| d7a46dcaaf | |||
| a4978aaac0 | |||
| 6ca4023b0d | |||
| acc3308d37 | |||
| 9ca3a690df | |||
| 335c04711e | |||
| fb7be77480 | |||
| e683fce4ab | |||
| 7493cdc5fa | |||
| 8f49f49154 | |||
| bc6fdd8513 | |||
| f6c86473c3 | |||
| d0d51f562c |
+38
-15
@@ -1,42 +1,65 @@
|
||||
<!--
|
||||
When adding new changelog entries, use [Issue #0] to link to issues and
|
||||
[PR #0 @user] to link to pull requests. Then run:
|
||||
[PR #0] to link to pull requests. Then run:
|
||||
|
||||
cargo xtask update-changelog
|
||||
|
||||
to update the actual links at the bottom of the file.
|
||||
-->
|
||||
|
||||
### Version 2.1.0
|
||||
|
||||
* Add support for dm-verify FEC (forward error correction) ([Issue #145], [PR #146])
|
||||
* `ota verify` and `avb verify` will now check the FEC data.
|
||||
* Print status and warning messages to stderr ([PR #149])
|
||||
* Add new `avb unpack`, `avb pack`, and `avb repack` commands for AVB images ([Issue #144], [Issue #148], [PR #152])
|
||||
* `avb verify` now optionally accepts `--repair` to fix corrupted dm-verity images.
|
||||
|
||||
Behind-the-scenes changes:
|
||||
|
||||
* Remove unnecessary use of `Arc` ([PR #147])
|
||||
* Use bstr crate to escape mostly UTF-8 binary data ([PR #150])
|
||||
* Improve error fields and error contest ([PR #153])
|
||||
|
||||
### Version 2.0.3
|
||||
|
||||
* Upgrade xz version in precompiled binaries ([Issue #138], [PR #139 @chenxiaolong])
|
||||
* Upgrade xz version in precompiled binaries ([Issue #138], [PR #139])
|
||||
* This fixes the `ota extract` and `ota verify` commands in some multithreaded situations.
|
||||
* Add `--version` option to print out avbroot's version ([Issue #138], [PR #140 @chenxiaolong])
|
||||
* Add `--version` option to print out avbroot's version ([Issue #138], [PR #140])
|
||||
|
||||
### Version 2.0.2
|
||||
|
||||
* Fix `data_offset` being set for payload operations that don't need it ([PR #136 @chenxiaolong])
|
||||
* Fix `data_offset` being set for payload operations that don't need it ([PR #136])
|
||||
* This fixes patched stock OnePlus images from being rejected when flashing.
|
||||
|
||||
Behind-the-scenes changes:
|
||||
|
||||
* Move full OTA check to CLI functions to allow library functions to parse delta OTAs ([PR #135 @chenxiaolong])
|
||||
* Remove unnecessary use of `anyhow` macro ([PR #137 @chenxiaolong])
|
||||
* Move full OTA check to CLI functions to allow library functions to parse delta OTAs ([PR #135])
|
||||
* Remove unnecessary use of `anyhow` macro ([PR #137])
|
||||
|
||||
### Version 2.0.1
|
||||
|
||||
* Add support for Magisk 263xx ([PR #132 @chenxiaolong])
|
||||
* Add support for Magisk 263xx ([PR #132])
|
||||
|
||||
### Version 2.0.0
|
||||
|
||||
* Initial Rust release. The old Python implementation can be found in the `python` branch. ([PR #130 @chenxiaolong])
|
||||
* Initial Rust release. The old Python implementation can be found in the `python` branch. ([PR #130])
|
||||
|
||||
<!-- Do not manually edit the lines below. Use `cargo xtask update-changelog` to regenerate. -->
|
||||
[Issue #138]: https://github.com/chenxiaolong/avbroot/issues/138
|
||||
[PR #130 @chenxiaolong]: https://github.com/chenxiaolong/avbroot/pull/130
|
||||
[PR #132 @chenxiaolong]: https://github.com/chenxiaolong/avbroot/pull/132
|
||||
[PR #135 @chenxiaolong]: https://github.com/chenxiaolong/avbroot/pull/135
|
||||
[PR #136 @chenxiaolong]: https://github.com/chenxiaolong/avbroot/pull/136
|
||||
[PR #137 @chenxiaolong]: https://github.com/chenxiaolong/avbroot/pull/137
|
||||
[PR #139 @chenxiaolong]: https://github.com/chenxiaolong/avbroot/pull/139
|
||||
[PR #140 @chenxiaolong]: https://github.com/chenxiaolong/avbroot/pull/140
|
||||
[Issue #144]: https://github.com/chenxiaolong/avbroot/issues/144
|
||||
[Issue #145]: https://github.com/chenxiaolong/avbroot/issues/145
|
||||
[Issue #148]: https://github.com/chenxiaolong/avbroot/issues/148
|
||||
[PR #130]: https://github.com/chenxiaolong/avbroot/pull/130
|
||||
[PR #132]: https://github.com/chenxiaolong/avbroot/pull/132
|
||||
[PR #135]: https://github.com/chenxiaolong/avbroot/pull/135
|
||||
[PR #136]: https://github.com/chenxiaolong/avbroot/pull/136
|
||||
[PR #137]: https://github.com/chenxiaolong/avbroot/pull/137
|
||||
[PR #139]: https://github.com/chenxiaolong/avbroot/pull/139
|
||||
[PR #140]: https://github.com/chenxiaolong/avbroot/pull/140
|
||||
[PR #146]: https://github.com/chenxiaolong/avbroot/pull/146
|
||||
[PR #147]: https://github.com/chenxiaolong/avbroot/pull/147
|
||||
[PR #149]: https://github.com/chenxiaolong/avbroot/pull/149
|
||||
[PR #150]: https://github.com/chenxiaolong/avbroot/pull/150
|
||||
[PR #152]: https://github.com/chenxiaolong/avbroot/pull/152
|
||||
[PR #153]: https://github.com/chenxiaolong/avbroot/pull/153
|
||||
|
||||
Generated
+114
-500
@@ -2,15 +2,6 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "addr2line"
|
||||
version = "0.21.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb"
|
||||
dependencies = [
|
||||
"gimli",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "adler"
|
||||
version = "1.0.2"
|
||||
@@ -97,6 +88,19 @@ version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9"
|
||||
|
||||
[[package]]
|
||||
name = "attohttpc"
|
||||
version = "0.26.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f77d243921b0979fbbd728dd2d5162e68ac8252976797c24eb5b3a6af9090dc"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"http",
|
||||
"log",
|
||||
"native-tls",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.1.0"
|
||||
@@ -105,11 +109,12 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
|
||||
|
||||
[[package]]
|
||||
name = "avbroot"
|
||||
version = "2.0.3"
|
||||
version = "2.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"assert_matches",
|
||||
"base64",
|
||||
"bstr",
|
||||
"byteorder",
|
||||
"bzip2",
|
||||
"clap",
|
||||
@@ -118,6 +123,7 @@ dependencies = [
|
||||
"const-oid",
|
||||
"ctrlc",
|
||||
"flate2",
|
||||
"gf256",
|
||||
"hex",
|
||||
"lz4_flex",
|
||||
"memchr",
|
||||
@@ -146,21 +152,6 @@ dependencies = [
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "backtrace"
|
||||
version = "0.3.69"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837"
|
||||
dependencies = [
|
||||
"addr2line",
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"miniz_oxide",
|
||||
"object",
|
||||
"rustc-demangle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.21.3"
|
||||
@@ -203,6 +194,17 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bstr"
|
||||
version = "1.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c2f7349907b712260e64b0afe2f84692af14a454be26187d9df565c7f69266a"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.13.0"
|
||||
@@ -217,9 +219,9 @@ checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.4.0"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be"
|
||||
checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223"
|
||||
|
||||
[[package]]
|
||||
name = "bzip2"
|
||||
@@ -315,7 +317,7 @@ dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.29",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -445,6 +447,41 @@ dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.12.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5f2c43f534ea4b0b049015d00269734195e6d3f0f6635cb692251aca6f9f8b3c"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"darling_macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_core"
|
||||
version = "0.12.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e91455b86830a1c21799d94524df0845183fa55bafd9aa137b01c7d1065fa36"
|
||||
dependencies = [
|
||||
"fnv",
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strsim",
|
||||
"syn 1.0.109",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.12.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29b5acf0dea37a7f66f7b25d2c5e93fd46f8f6968b1a5d7a3e02e97768afc95a"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"quote",
|
||||
"syn 1.0.109",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der"
|
||||
version = "0.7.8"
|
||||
@@ -466,7 +503,7 @@ checksum = "5fe87ce4529967e0ba1dcf8450bab64d97dfd5010a6256187ffe2e43e6f0e049"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.29",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -483,19 +520,17 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "e2e"
|
||||
version = "2.0.3"
|
||||
version = "2.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"attohttpc",
|
||||
"avbroot",
|
||||
"clap",
|
||||
"ctrlc",
|
||||
"hex",
|
||||
"reqwest",
|
||||
"ring",
|
||||
"serde",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"toml_edit",
|
||||
"zip",
|
||||
]
|
||||
@@ -506,15 +541,6 @@ version = "1.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07"
|
||||
|
||||
[[package]]
|
||||
name = "encoding_rs"
|
||||
version = "0.8.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.1"
|
||||
@@ -542,6 +568,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "evalexpr"
|
||||
version = "6.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfc25fd417983cc7f203394ebb89eba18e2df1b0ac1be2673091b5aca52b595f"
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.0.0"
|
||||
@@ -594,67 +626,6 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-channel"
|
||||
version = "0.3.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c"
|
||||
|
||||
[[package]]
|
||||
name = "futures-io"
|
||||
version = "0.3.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964"
|
||||
|
||||
[[package]]
|
||||
name = "futures-macro"
|
||||
version = "0.3.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-sink"
|
||||
version = "0.3.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e"
|
||||
|
||||
[[package]]
|
||||
name = "futures-task"
|
||||
version = "0.3.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-io",
|
||||
"futures-macro",
|
||||
"futures-sink",
|
||||
"futures-task",
|
||||
"memchr",
|
||||
"pin-project-lite",
|
||||
"pin-utils",
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
@@ -677,35 +648,27 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gimli"
|
||||
version = "0.28.0"
|
||||
name = "gf256"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0"
|
||||
|
||||
[[package]]
|
||||
name = "h2"
|
||||
version = "0.3.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91fc23aa11be92976ef4729127f1a74adf36d8436f7816b185d18df956790833"
|
||||
checksum = "00ad9760c1b289e26006c2ed8cc950807c842e6c51f64532c806bc2ef7a34c79"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"fnv",
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
"futures-util",
|
||||
"http",
|
||||
"indexmap 1.9.3",
|
||||
"slab",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
"cfg-if",
|
||||
"gf256-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.12.3"
|
||||
name = "gf256-macros"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
|
||||
checksum = "3b084923ea97216d84ff299a428609b85e68c130c5320a86ed778c204f9e19cd"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"evalexpr",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 1.0.109",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
@@ -754,29 +717,6 @@ dependencies = [
|
||||
"itoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http-body"
|
||||
version = "0.4.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"http",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904"
|
||||
|
||||
[[package]]
|
||||
name = "httpdate"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
|
||||
|
||||
[[package]]
|
||||
name = "human-sort"
|
||||
version = "0.2.2"
|
||||
@@ -784,41 +724,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "140a09c9305e6d5e557e2ed7cbc68e05765a7d4213975b87cb04920689cc6219"
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "0.14.27"
|
||||
name = "ident_case"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ffb1cfd654a8219eaef89881fdb3bb3b1cdc5fa75ded05d6933b2b382e395468"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"h2",
|
||||
"http",
|
||||
"http-body",
|
||||
"httparse",
|
||||
"httpdate",
|
||||
"itoa",
|
||||
"pin-project-lite",
|
||||
"socket2 0.4.9",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
"want",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-tls"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hyper",
|
||||
"native-tls",
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
]
|
||||
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
|
||||
|
||||
[[package]]
|
||||
name = "idna"
|
||||
@@ -830,16 +739,6 @@ dependencies = [
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "1.9.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"hashbrown 0.12.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.0.0"
|
||||
@@ -847,7 +746,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown 0.14.0",
|
||||
"hashbrown",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -860,12 +759,6 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ipnet"
|
||||
version = "2.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6"
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.9"
|
||||
@@ -948,12 +841,6 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
version = "0.3.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
||||
|
||||
[[package]]
|
||||
name = "minimal-lexical"
|
||||
version = "0.2.1"
|
||||
@@ -969,17 +856,6 @@ dependencies = [
|
||||
"adler",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "0.8.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"wasi",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "native-tls"
|
||||
version = "0.2.11"
|
||||
@@ -1078,15 +954,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "object"
|
||||
version = "0.32.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ac5bbd07aea88c60a577a1ce218075ffd59208b2d7ca97adf9bfc5aeb21ebe"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.18.0"
|
||||
@@ -1116,7 +983,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.29",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1127,9 +994,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
|
||||
|
||||
[[package]]
|
||||
name = "openssl-sys"
|
||||
version = "0.9.92"
|
||||
version = "0.9.93"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db7e971c2c2bba161b2d2fdf37080177eff520b3bc044787c7f1f5f9e78d869b"
|
||||
checksum = "db4d56a4c0478783083cfafcc42493dd4a981d41669da64b4572a2a089b51b1d"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
@@ -1202,7 +1069,7 @@ dependencies = [
|
||||
"phf_shared",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.29",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1214,18 +1081,6 @@ dependencies = [
|
||||
"siphasher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58"
|
||||
|
||||
[[package]]
|
||||
name = "pin-utils"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
|
||||
|
||||
[[package]]
|
||||
name = "pkcs1"
|
||||
version = "0.7.5"
|
||||
@@ -1393,45 +1248,6 @@ version = "0.7.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da"
|
||||
|
||||
[[package]]
|
||||
name = "reqwest"
|
||||
version = "0.11.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e9ad3fe7488d7e34558a2033d45a0c90b72d97b4f80705666fea71472e2e6a1"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
"encoding_rs",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"h2",
|
||||
"http",
|
||||
"http-body",
|
||||
"hyper",
|
||||
"hyper-tls",
|
||||
"ipnet",
|
||||
"js-sys",
|
||||
"log",
|
||||
"mime",
|
||||
"native-tls",
|
||||
"once_cell",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tokio-util",
|
||||
"tower-service",
|
||||
"url",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-streams",
|
||||
"web-sys",
|
||||
"winreg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.16.20"
|
||||
@@ -1492,12 +1308,6 @@ dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-demangle"
|
||||
version = "0.1.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "0.38.10"
|
||||
@@ -1511,12 +1321,6 @@ dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741"
|
||||
|
||||
[[package]]
|
||||
name = "salsa20"
|
||||
version = "0.10.2"
|
||||
@@ -1601,18 +1405,7 @@ checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.105"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "693151e1ac27563d6dbcec9dee9fbd5da8539b20fa14ad3752b2e6d363ace360"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"ryu",
|
||||
"serde",
|
||||
"syn 2.0.29",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1624,18 +1417,6 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_urlencoded"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
|
||||
dependencies = [
|
||||
"form_urlencoded",
|
||||
"itoa",
|
||||
"ryu",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.10.5"
|
||||
@@ -1658,15 +1439,6 @@ dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "2.1.0"
|
||||
@@ -1683,41 +1455,12 @@ version = "0.3.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "62bb4feee49fdd9f707ef802e22365a35de4b7b299de4763d44bfea899442ff9"
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.4.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2538b18701741680e0322a2302176d3253a35388e2e62f172f64f4f16605f877"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spin"
|
||||
version = "0.5.2"
|
||||
@@ -1752,6 +1495,17 @@ version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "1.0.109"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.29"
|
||||
@@ -1793,7 +1547,7 @@ checksum = "6bb623b56e39ab7dcd4b1b98bb6c8f8d907ed255b18de254088016b27a8ee19b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.29",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1811,70 +1565,6 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.32.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "17ed6077ed6cd6c74735e21f37eb16dc3935f96878b1fe961074089cc80893f9"
|
||||
dependencies = [
|
||||
"backtrace",
|
||||
"bytes",
|
||||
"libc",
|
||||
"mio",
|
||||
"num_cpus",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2 0.5.3",
|
||||
"tokio-macros",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-macros"
|
||||
version = "2.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-native-tls"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"
|
||||
dependencies = [
|
||||
"native-tls",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-stream"
|
||||
version = "0.1.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "397c988d37662c7dda6d2208364a706264bf3d6138b11d436cbac0ad38832842"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-util"
|
||||
version = "0.7.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "806fe8c2c87eccc8b3267cbae29ed3ab2d0bd37fca70ab622e46aaa9375ddb7d"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "0.6.3"
|
||||
@@ -1890,7 +1580,7 @@ version = "0.19.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8123f27e969974a3dfba720fdb560be359f57b44302d280ba72e76a74480e8a"
|
||||
dependencies = [
|
||||
"indexmap 2.0.0",
|
||||
"indexmap",
|
||||
"serde",
|
||||
"serde_spanned",
|
||||
"toml_datetime",
|
||||
@@ -1903,38 +1593,6 @@ version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ea68304e134ecd095ac6c3574494fc62b909f416c4fca77e440530221e549d3d"
|
||||
|
||||
[[package]]
|
||||
name = "tower-service"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52"
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.37"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"pin-project-lite",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-core"
|
||||
version = "0.1.31"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "try-lock"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed"
|
||||
|
||||
[[package]]
|
||||
name = "twox-hash"
|
||||
version = "1.6.3"
|
||||
@@ -2017,15 +1675,6 @@ dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "want"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
|
||||
dependencies = [
|
||||
"try-lock",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.11.0+wasi-snapshot-preview1"
|
||||
@@ -2053,22 +1702,10 @@ dependencies = [
|
||||
"once_cell",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.29",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-futures"
|
||||
version = "0.4.37"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro"
|
||||
version = "0.2.87"
|
||||
@@ -2087,7 +1724,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.29",
|
||||
"wasm-bindgen-backend",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
@@ -2098,19 +1735,6 @@ version = "0.2.87"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-streams"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4609d447824375f43e1ffbc051b50ad8f4b3ae8219680c94452ea05eb240ac7"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"js-sys",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-sys"
|
||||
version = "0.3.64"
|
||||
@@ -2227,16 +1851,6 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winreg"
|
||||
version = "0.50.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x509-cert"
|
||||
version = "0.2.4"
|
||||
@@ -2252,7 +1866,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "2.0.3"
|
||||
version = "2.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ members = ["avbroot", "e2e", "xtask"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
version = "2.0.3"
|
||||
version = "2.1.0"
|
||||
license = "GPL-3.0-only"
|
||||
edition = "2021"
|
||||
repository = "https://github.com/chenxiaolong/avbroot"
|
||||
|
||||
+95
-2
@@ -6,10 +6,44 @@ Note that while avbroot maintains a stable command line interface for the patchi
|
||||
|
||||
## `avbroot avb`
|
||||
|
||||
### Unpacking an AVB image
|
||||
|
||||
```bash
|
||||
avbroot avb unpack -i <input AVB image>
|
||||
```
|
||||
|
||||
This subcommand unpacks the vbmeta header and footer into `avb.toml`. If a footer is present, then the corresponding raw partition image is extracted into `raw.img`. Root vbmeta images (eg. `vbmeta` and `vbmeta_vendor`) do not have footers, while appended vbmeta images (eg. `boot` and `system`) do.
|
||||
|
||||
The vbmeta descriptor digests are validated during unpacking. For dm-verity images, if the image is corrupt, avbroot will attempt to use the FEC data to repair the file. If there is unrepairable data corruption, the command will fail, though the corrupted `raw.img` will still be fully written. If, for whatever reason, a successful exit status of 0 is needed even for corrupted files, use `--ignore-invalid`.
|
||||
|
||||
### Packing an AVB image
|
||||
|
||||
```bash
|
||||
avbroot avb pack -o <output AVB image> [--key <AVB private key>]
|
||||
```
|
||||
|
||||
This subcommand packs a new AVB image from the `avb.toml` file and, for appended vbmeta images, the `raw.img` file.
|
||||
|
||||
* If the original image was signed and the new data is unmodified, then the original signature is used as-is. (This means just unpacking and packing an image will always result in a byte-for-byte identical file.)
|
||||
* If the original image was signed and the new data is modified, then the newly packed image will be signed with the `--key`.
|
||||
* If the original image was not signed, then the newly packed image is not signed.
|
||||
* To force an image to be signed, use `--key <path> --force`.
|
||||
* To force an image to be unsigned, use `--force` without specifying `--key`.
|
||||
|
||||
### Repacking an AVB image
|
||||
|
||||
```bash
|
||||
avbroot avb repack -i <input AVB image> -o <output AVB image>
|
||||
```
|
||||
|
||||
This subcommand is equivalent to `avbroot avb unpack` followed by `avbroot avb pack`, except it doesn't need to write any intermediate files to disk.
|
||||
|
||||
This is useful for repairing a dm-verify image or for re-signing any image with a specific key.
|
||||
|
||||
### Showing vbmeta header and footer information
|
||||
|
||||
```bash
|
||||
avbroot avb dump -i <image>
|
||||
avbroot avb info -i <image>
|
||||
```
|
||||
|
||||
This subcommand shows all of the vbmeta header and footer fields. `vbmeta` partition images will only have a header, while partitions with actual data (eg. boot images) will have both a header and a footer.
|
||||
@@ -20,10 +54,12 @@ This subcommand shows all of the vbmeta header and footer fields. `vbmeta` parti
|
||||
avbroot avb verify -i <root vbmeta image> -p <public key>
|
||||
```
|
||||
|
||||
This subcommand verifies the vbmeta header signature and the hashes for all vbmeta descriptors (including hashtree descriptors). If the vbmeta image has a chain descriptor for another partition, that partition image will be verified as well (recursively). All partitions are expected to be in the same directory as the vbmeta image being verified.
|
||||
This subcommand verifies the vbmeta header signature and the hashes for all vbmeta descriptors (including hash tree descriptors). If the vbmeta image has a chain descriptor for another partition, that partition image will be verified as well (recursively). All partitions are expected to be in the same directory as the vbmeta image being verified.
|
||||
|
||||
If `-p` is omitted, the signatures and hashes are checked only for validity, not that they are trusted.
|
||||
|
||||
By default, this command will not write to any file and fails if an image is corrupt or invalid. To attempt to repair corrupted dm-verity images, pass in `--repair`.
|
||||
|
||||
## `avbroot boot`
|
||||
|
||||
### Unpacking a boot image
|
||||
@@ -58,6 +94,63 @@ avbroot boot info -i <input boot image>
|
||||
|
||||
All of the `boot` subcommands show the boot image information. This specific subcommand just does it without performing any other operation. To show avbroot's internal representation of the information, pass in `-d`.
|
||||
|
||||
## `avbroot fec`
|
||||
|
||||
This set of commands is for working with dm-verity FEC (forward error correction) data. The FEC data allows small errors in partition data to be corrected. This increases reliability of the system because when dm-verity encounters data that doesn't match the expected checksum, it will either trigger a kernel panic or reboot the system.
|
||||
|
||||
The same raw FEC data can be stored in several ways:
|
||||
|
||||
* cryptsetup's `veritysetup` does not use any file format at all. It must be told the FEC location and parameters using the `--fec-*` options.
|
||||
* AOSP's AVB 2.0 stores the FEC data inside the partition as `[Partition data][Hash tree][FEC data]`. The location and parameters are stored in the vbmeta hash tree descriptors.
|
||||
* AOSP's `fec` tool stores the FEC data in a standalone file with a header containing the FEC parameters.
|
||||
|
||||
The `avbroot fec` commands use AOSP's standalone FEC file format.
|
||||
|
||||
The FEC data is not generated from a sequential read of the input file, but rather from an interleaved read. If the input file's offsets are visualized as a 2D table:
|
||||
|
||||
```
|
||||
| 0 1 2 3 ... 4095 |
|
||||
| 4096 4097 4098 4099 ... 8191 |
|
||||
| 8192 8193 8194 8195 ... 12287 |
|
||||
| .... .... .... .... ... ..... |
|
||||
```
|
||||
|
||||
then the file access pattern can be thought of as being column-by-column instead of row-by-row.
|
||||
|
||||
Data correction happens at the codeword level. A Reed-Solomon codeword is 255 bytes where some portion is file data and the rest is parity data. AOSP and avbroot both default to 253 bytes of data and 2 bytes of parity information. Each column in the table represents the 253-byte data portion of the codeword. Larger files have more columns.
|
||||
|
||||
A contiguous sequence of corrupted data will span multiple columns. Since error correction happens at the column level, this interleaving increases the chances of recovery. For more details about the specifics, see the implementation in [`fec.rs`](./avbroot/src/format/fec.rs).
|
||||
|
||||
### Generating FEC data
|
||||
|
||||
```bash
|
||||
avbroot fec generate -i <input data file> -f <output FEC file>
|
||||
```
|
||||
|
||||
The default behavior is to use 2 bytes of parity information per 253 bytes of input data. Within each 253-byte column described above, this is sufficient for correcting a single corrupted byte in the column (`⌊parity / 2⌋` bytes in general).
|
||||
|
||||
The number of parity bytes (between 2 and 24, inclusive) can be configured using `--parity`.
|
||||
|
||||
### Verifying a file
|
||||
|
||||
```bash
|
||||
avbroot fec verify -i <input data file> -f <input FEC file>
|
||||
```
|
||||
|
||||
This will check if the input file has any corrupted bytes. This command runs significantly faster than `avbroot fec repair` and is useful if only detection of corrupted data is needed.
|
||||
|
||||
Note that FEC is **not** a replacement for checksums, like SHA-256. When there are too many errors, there can be false positives where the corrupted data is reported as being valid.
|
||||
|
||||
### Repairing a file
|
||||
|
||||
```bash
|
||||
avbroot fec repair -i <input/output data file> -f <input FEC file>
|
||||
```
|
||||
|
||||
This will repair the file in place. As described above, in each column, up to `parity / 2` bytes can be corrected.
|
||||
|
||||
Note that FEC is **not** a replacement for checksums, like SHA-256. When there are too many errors, the file can potentially be "successfully repaired" to some incorrect data.
|
||||
|
||||
## `avbroot ramdisk`
|
||||
|
||||
### Dumping a cpio archive
|
||||
|
||||
@@ -64,6 +64,8 @@ The boot-related components are signed with an AVB key and OTA-related component
|
||||
|
||||
The commands above are provided for convenience. avbroot is compatible with any standard PKCS8-encoded 4096-bit RSA private key and X509 certificate (eg. like those generated by openssl).
|
||||
|
||||
If you lose your AVB or OTA signing key you will no longer be able to sign new OTA zips. You will have to generate new signing keys and unlock your bootloader again (including a data wipe). Follow the [Usage section](#usage) as if doing an initial setup.
|
||||
|
||||
## Usage
|
||||
|
||||
1. Make sure the caveats listed above are understood. It is possible to hard brick by doing the wrong thing!
|
||||
@@ -153,6 +155,8 @@ Unpatched OTA updates are already blocked in recovery because the original OTA c
|
||||
|
||||
The `clearotacerts` module additionally makes A/B OTAs fail while booted into Android to prevent accidental manual updates. The module simply overrides `/system/etc/security/otacerts.zip` at runtime with an empty zip so that even if an OTA is downloaded, signature verification will fail.
|
||||
|
||||
At least in CalyxOS the Updater app does not respect the `Automatic system updates` setting and may enter an infinite loop downloading the OTA update and restarting the download when signature verification fails. If this happens on your ROM, you can try to either remove network access from the Updater app or disable the Updater app altogether (if your ROM allows you to do so). In CalyxOS it is possible to go to `Settings > Apps > See all apps`, open the three-dot menu, `Show system`, then find the `System updater` app and disable it.
|
||||
|
||||
Alternatively, see [Custota](https://github.com/chenxiaolong/Custota) for a custom OTA updater app that pulls from a self-hosted OTA server.
|
||||
|
||||
### `oemunlockonboot`: Enable OEM unlocking on every boot
|
||||
|
||||
+3
-1
@@ -11,6 +11,7 @@ publish = false
|
||||
[dependencies]
|
||||
anyhow = "1.0.75"
|
||||
base64 = "0.21.3"
|
||||
bstr = "1.6.2"
|
||||
byteorder = "1.4.3"
|
||||
clap = { version = "4.4.1", features = ["derive"] }
|
||||
clap_complete = "4.4.0"
|
||||
@@ -18,7 +19,8 @@ cms = { version = "0.2.2", features = ["std"] }
|
||||
const-oid = "0.9.5"
|
||||
ctrlc = "3.4.0"
|
||||
flate2 = "1.0.27"
|
||||
hex = "0.4.3"
|
||||
gf256 = { version = "0.3.0", features = ["rs"] }
|
||||
hex = { version = "0.4.3", features = ["serde"] }
|
||||
lz4_flex = "0.11.1"
|
||||
memchr = "2.6.0"
|
||||
num-bigint-dig = "0.8.4"
|
||||
|
||||
+24
-20
@@ -11,9 +11,10 @@ use std::{
|
||||
num::ParseIntError,
|
||||
ops::Range,
|
||||
path::{Path, PathBuf},
|
||||
sync::{atomic::AtomicBool, Arc},
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
|
||||
use bstr::ByteSlice;
|
||||
use regex::bytes::Regex;
|
||||
use ring::digest::Context;
|
||||
use rsa::RsaPrivateKey;
|
||||
@@ -28,22 +29,21 @@ use zip::{result::ZipError, write::FileOptions, CompressionMethod, ZipArchive, Z
|
||||
use crate::{
|
||||
crypto,
|
||||
format::{
|
||||
avb::{self, AlgorithmType, Descriptor},
|
||||
avb::{self, Descriptor},
|
||||
bootimage::{self, BootImage, BootImageExt, RamdiskMeta},
|
||||
compression::{self, CompressedFormat, CompressedReader, CompressedWriter},
|
||||
cpio::{self, CpioEntryNew},
|
||||
},
|
||||
stream::{self, FromReader, HashingWriter, SectionReader, ToWriter},
|
||||
util::EscapedString,
|
||||
};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
#[error("Boot image has no vbmeta footer")]
|
||||
NoFooter,
|
||||
#[error("No hash descriptor found in vbmeta footer")]
|
||||
#[error("No hash descriptor found in vbmeta header")]
|
||||
NoHashDescriptor,
|
||||
#[error("Found multiple hash descriptors in vbmeta footer")]
|
||||
#[error("Found multiple hash descriptors in vbmeta header")]
|
||||
MultipleHashDescriptors,
|
||||
#[error("Validation error: {0}")]
|
||||
Validation(String),
|
||||
@@ -66,7 +66,9 @@ pub enum Error {
|
||||
#[error("Zip error")]
|
||||
Zip(#[from] ZipError),
|
||||
#[error("I/O error")]
|
||||
IoError(#[from] io::Error),
|
||||
Io(#[from] io::Error),
|
||||
#[error("File I/O error")]
|
||||
File(PathBuf, #[source] io::Error),
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
@@ -89,7 +91,7 @@ fn save_ramdisk(entries: &[CpioEntryNew], format: CompressedFormat) -> Result<Ve
|
||||
}
|
||||
|
||||
pub trait BootImagePatcher {
|
||||
fn patch(&self, boot_image: &mut BootImage, cancel_signal: &Arc<AtomicBool>) -> Result<()>;
|
||||
fn patch(&self, boot_image: &mut BootImage, cancel_signal: &AtomicBool) -> Result<()>;
|
||||
}
|
||||
|
||||
/// Root a boot image with Magisk.
|
||||
@@ -161,7 +163,7 @@ impl MagiskRootPatcher {
|
||||
}
|
||||
|
||||
fn get_version(path: &Path) -> Result<u32> {
|
||||
let reader = File::open(path)?;
|
||||
let reader = File::open(path).map_err(|e| Error::File(path.to_owned(), e))?;
|
||||
let reader = BufReader::new(reader);
|
||||
let mut zip = ZipArchive::new(reader)?;
|
||||
let entry = zip.by_name("assets/util_functions.sh")?;
|
||||
@@ -254,8 +256,9 @@ impl MagiskRootPatcher {
|
||||
}
|
||||
|
||||
impl BootImagePatcher for MagiskRootPatcher {
|
||||
fn patch(&self, boot_image: &mut BootImage, cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
let zip_reader = File::open(&self.apk_path)?;
|
||||
fn patch(&self, boot_image: &mut BootImage, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let zip_reader =
|
||||
File::open(&self.apk_path).map_err(|e| Error::File(self.apk_path.clone(), e))?;
|
||||
let mut zip = ZipArchive::new(BufReader::new(zip_reader))?;
|
||||
|
||||
// Load the first ramdisk. If it doesn't exist, we have to generate one
|
||||
@@ -466,7 +469,7 @@ impl OtaCertPatcher {
|
||||
}
|
||||
|
||||
impl BootImagePatcher for OtaCertPatcher {
|
||||
fn patch(&self, boot_image: &mut BootImage, _cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
fn patch(&self, boot_image: &mut BootImage, _cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let patched_any = match boot_image {
|
||||
BootImage::V0Through2(b) => self.patch_ramdisk(&mut b.ramdisk)?,
|
||||
BootImage::V3Through4(b) => self.patch_ramdisk(&mut b.ramdisk)?,
|
||||
@@ -488,8 +491,8 @@ impl BootImagePatcher for OtaCertPatcher {
|
||||
// out of future updates if the OTA certificate mechanism has changed.
|
||||
if !patched_any {
|
||||
return Err(Error::Validation(format!(
|
||||
"No ramdisk contains {}",
|
||||
EscapedString::new(Self::OTACERTS_PATH),
|
||||
"No ramdisk contains {:?}",
|
||||
Self::OTACERTS_PATH.as_bstr(),
|
||||
)));
|
||||
}
|
||||
|
||||
@@ -557,9 +560,10 @@ impl PrepatchedImagePatcher {
|
||||
}
|
||||
|
||||
impl BootImagePatcher for PrepatchedImagePatcher {
|
||||
fn patch(&self, boot_image: &mut BootImage, _cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
fn patch(&self, boot_image: &mut BootImage, _cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let prepatched_image = {
|
||||
let raw_reader = File::open(&self.prepatched)?;
|
||||
let raw_reader = File::open(&self.prepatched)
|
||||
.map_err(|e| Error::File(self.prepatched.clone(), e))?;
|
||||
BootImage::from_reader(BufReader::new(raw_reader))?
|
||||
};
|
||||
|
||||
@@ -735,10 +739,10 @@ pub fn patch_boot(
|
||||
writer: impl Write + Seek,
|
||||
key: &RsaPrivateKey,
|
||||
patchers: &[Box<dyn BootImagePatcher + Send>],
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let (mut header, footer, image_size) = avb::load_image(&mut reader)?;
|
||||
let Some(footer) = footer else {
|
||||
let Some(mut footer) = footer else {
|
||||
return Err(Error::NoFooter);
|
||||
};
|
||||
|
||||
@@ -749,6 +753,8 @@ pub fn patch_boot(
|
||||
patcher.patch(&mut boot_image, cancel_signal)?;
|
||||
}
|
||||
|
||||
header.set_algo_for_key(key)?;
|
||||
|
||||
let mut descriptor_iter = header.descriptors.iter_mut().filter_map(|d| {
|
||||
if let Descriptor::Hash(h) = d {
|
||||
Some(h)
|
||||
@@ -768,8 +774,6 @@ pub fn patch_boot(
|
||||
boot_image.to_writer(&mut hashing_writer)?;
|
||||
let (mut writer, context) = hashing_writer.finish();
|
||||
|
||||
header.algorithm_type = AlgorithmType::Sha256Rsa4096;
|
||||
|
||||
descriptor.image_size = writer.stream_position()?;
|
||||
descriptor.hash_algorithm = "sha256".to_owned();
|
||||
descriptor.root_digest = context.finish().as_ref().to_vec();
|
||||
@@ -782,7 +786,7 @@ pub fn patch_boot(
|
||||
header.sign(key)?;
|
||||
}
|
||||
|
||||
avb::write_appended_image(writer, &header, &footer, image_size)?;
|
||||
avb::write_appended_image(writer, &header, &mut footer, image_size)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
* SPDX-License-Identifier: GPL-3.0-only
|
||||
*/
|
||||
|
||||
use std::sync::{atomic::AtomicBool, Arc};
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
use crate::cli::{avb, boot, completion, key, ota, ramdisk};
|
||||
use crate::cli::{avb, boot, completion, fec, key, ota, ramdisk};
|
||||
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
#[derive(Debug, Subcommand)]
|
||||
@@ -16,6 +16,7 @@ pub enum Command {
|
||||
Avb(avb::AvbCli),
|
||||
Boot(boot::BootCli),
|
||||
Completion(completion::CompletionCli),
|
||||
Fec(fec::FecCli),
|
||||
Key(key::KeyCli),
|
||||
Ota(ota::OtaCli),
|
||||
Ramdisk(ramdisk::RamdiskCli),
|
||||
@@ -34,13 +35,14 @@ pub struct Cli {
|
||||
pub command: Command,
|
||||
}
|
||||
|
||||
pub fn main(cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
pub fn main(cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
|
||||
match cli.command {
|
||||
Command::Avb(c) => avb::avb_main(&c, cancel_signal),
|
||||
Command::Boot(c) => boot::boot_main(&c),
|
||||
Command::Completion(c) => completion::completion_main(&c),
|
||||
Command::Fec(c) => fec::fec_main(&c, cancel_signal),
|
||||
Command::Key(c) => key::key_main(&c),
|
||||
Command::Ota(c) => ota::ota_main(&c, cancel_signal),
|
||||
Command::Ramdisk(c) => ramdisk::ramdisk_main(&c),
|
||||
|
||||
+626
-78
@@ -5,25 +5,281 @@
|
||||
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
ffi::OsStr,
|
||||
fs::{self, File},
|
||||
io::{self, BufReader},
|
||||
ffi::{OsStr, OsString},
|
||||
fs::{self, File, OpenOptions},
|
||||
io::{self, BufReader, BufWriter, Seek, SeekFrom, Write},
|
||||
path::{Path, PathBuf},
|
||||
str,
|
||||
sync::{atomic::AtomicBool, Arc},
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use clap::{Parser, Subcommand};
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
|
||||
use rsa::RsaPublicKey;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
cli::{status, warning},
|
||||
format::avb::{self, Descriptor},
|
||||
stream::PSeekFile,
|
||||
crypto::{self, PassphraseSource},
|
||||
format::avb::{
|
||||
self, AlgorithmType, AppendedDescriptorMut, AppendedDescriptorRef, Descriptor, Footer,
|
||||
Header,
|
||||
},
|
||||
stream::{self, PSeekFile},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
|
||||
struct AvbInfo {
|
||||
header: Header,
|
||||
footer: Option<Footer>,
|
||||
image_size: u64,
|
||||
}
|
||||
|
||||
fn read_avb_image(path: &Path) -> Result<(AvbInfo, BufReader<File>)> {
|
||||
let file = File::open(path)
|
||||
.with_context(|| format!("Failed to open AVB image for reading: {path:?}"))?;
|
||||
let mut reader = BufReader::new(file);
|
||||
let (header, footer, image_size) = avb::load_image(&mut reader)
|
||||
.with_context(|| format!("Failed to load AVB image: {path:?}"))?;
|
||||
|
||||
let info = AvbInfo {
|
||||
header,
|
||||
footer,
|
||||
image_size,
|
||||
};
|
||||
|
||||
Ok((info, reader))
|
||||
}
|
||||
|
||||
fn write_avb_image(file: PSeekFile, info: &mut AvbInfo) -> Result<()> {
|
||||
let mut writer = BufWriter::new(file);
|
||||
|
||||
if let Some(f) = &mut info.footer {
|
||||
avb::write_appended_image(&mut writer, &info.header, f, info.image_size)
|
||||
.context("Failed to write appended AVB image")?;
|
||||
} else {
|
||||
avb::write_root_image(&mut writer, &info.header, 4096)
|
||||
.context("Failed to write root AVB image")?;
|
||||
}
|
||||
|
||||
writer.flush().context("Failed to flush writes")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read AVB information from TOML file.
|
||||
fn read_info(path: &Path) -> Result<AvbInfo> {
|
||||
let data = fs::read_to_string(path)
|
||||
.with_context(|| format!("Failed to read AVB info TOML: {path:?}"))?;
|
||||
let info = toml_edit::de::from_str(&data)
|
||||
.with_context(|| format!("Failed to parse AVB info TOML: {path:?}"))?;
|
||||
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// Write AVB information to TOML file.
|
||||
fn write_info(path: &Path, info: &AvbInfo) -> Result<()> {
|
||||
let data = toml_edit::ser::to_string_pretty(info)
|
||||
.with_context(|| format!("Failed to serialize AVB info TOML: {path:?}"))?;
|
||||
fs::write(path, data).with_context(|| format!("Failed to write AVB info TOML: {path:?}"))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copy `size` bytes from `reader` into a new file `path` that's opened as
|
||||
/// both readable and writable.
|
||||
fn write_raw(
|
||||
path: &Path,
|
||||
reader: &mut BufReader<File>,
|
||||
size: u64,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<PSeekFile> {
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.open(path)
|
||||
.map(PSeekFile::new)
|
||||
.with_context(|| format!("Failed to open raw image for writing: {path:?}"))?;
|
||||
let mut writer = BufWriter::new(file);
|
||||
|
||||
reader
|
||||
.rewind()
|
||||
.with_context(|| format!("Failed to seek file: {path:?}"))?;
|
||||
stream::copy_n(reader, &mut writer, size, cancel_signal)
|
||||
.with_context(|| format!("Failed to copy raw image: {path:?}"))?;
|
||||
|
||||
let file = writer
|
||||
.into_inner()
|
||||
.with_context(|| format!("Failed to flush writes: {path:?}"))?;
|
||||
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// Copy a raw image into `path` and verify the descriptor. If corruption is
|
||||
/// detected and FEC data is available, then a repair is attempted.
|
||||
fn write_raw_and_verify(
|
||||
path: &Path,
|
||||
reader: &mut BufReader<File>,
|
||||
info: &AvbInfo,
|
||||
ignore_invalid: bool,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<PSeekFile> {
|
||||
let f = info.footer.as_ref().expect("Not an appended image");
|
||||
|
||||
let descriptor = info.header.appended_descriptor()?;
|
||||
|
||||
// The hash tree and FEC need to be present for verification. We don't
|
||||
// verify against the original file because a repair would require writes.
|
||||
let copy_size = match descriptor {
|
||||
AppendedDescriptorRef::HashTree(d) => d.image_size + d.tree_size + d.fec_size,
|
||||
AppendedDescriptorRef::Hash(d) => d.image_size,
|
||||
};
|
||||
|
||||
let raw_file = write_raw(path, reader, copy_size, cancel_signal)?;
|
||||
|
||||
let result = verify_and_repair(None, raw_file.reopen(), descriptor, true, cancel_signal);
|
||||
|
||||
// Chop off the old hash tree and FEC data.
|
||||
raw_file.set_len(f.original_image_size)?;
|
||||
|
||||
if let Err(e) = result {
|
||||
if ignore_invalid {
|
||||
warning!("{e:?}");
|
||||
} else {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(raw_file)
|
||||
}
|
||||
|
||||
/// Copy a raw image into `path` and update the appended descriptor with the new
|
||||
/// digests, offsets, and sizes.
|
||||
fn write_raw_and_update(
|
||||
path: &Path,
|
||||
reader: &mut BufReader<File>,
|
||||
info: &mut AvbInfo,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<PSeekFile> {
|
||||
assert!(info.footer.is_some(), "Not an appended image");
|
||||
|
||||
let image_size = reader
|
||||
.seek(SeekFrom::End(0))
|
||||
.context("Failed to get input data size")?;
|
||||
|
||||
let mut raw_file = write_raw(path, reader, image_size, cancel_signal)?;
|
||||
|
||||
match info.header.appended_descriptor_mut()? {
|
||||
AppendedDescriptorMut::HashTree(d) => {
|
||||
d.image_size = image_size;
|
||||
d.update(
|
||||
|| Ok(Box::new(raw_file.reopen())),
|
||||
|| Ok(Box::new(raw_file.reopen())),
|
||||
cancel_signal,
|
||||
)
|
||||
.context("Failed to update hash tree descriptor")?;
|
||||
}
|
||||
AppendedDescriptorMut::Hash(d) => {
|
||||
d.image_size = image_size;
|
||||
raw_file.rewind()?;
|
||||
d.update(&mut raw_file, cancel_signal)
|
||||
.context("Failed to update hash descriptor")?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(raw_file)
|
||||
}
|
||||
|
||||
/// Sign or clear header signatures based on whether the original header was
|
||||
/// signed. If the original header was signed and is unchanged, then the
|
||||
/// original signature is used as-is. If the force option is specified, then
|
||||
/// the header is signed or cleared based on the presence of the private key
|
||||
/// parameter.
|
||||
fn sign_or_clear(info: &mut AvbInfo, orig_header: &Header, key_group: &KeyGroup) -> Result<()> {
|
||||
enum SignAction {
|
||||
None,
|
||||
Sign,
|
||||
Clear,
|
||||
}
|
||||
|
||||
let originally_signed = !info.header.signature.is_empty();
|
||||
let mut sign_action = if originally_signed && &info.header != orig_header {
|
||||
SignAction::Sign
|
||||
} else {
|
||||
// If the original image was signed, we can preserve the existing
|
||||
// signature since no changes were made. If the original image was not
|
||||
// signed, then there's nothing to do anyway.
|
||||
SignAction::None
|
||||
};
|
||||
|
||||
if key_group.force {
|
||||
sign_action = if key_group.key.is_some() {
|
||||
SignAction::Sign
|
||||
} else {
|
||||
SignAction::Clear
|
||||
};
|
||||
}
|
||||
|
||||
match sign_action {
|
||||
SignAction::None => {
|
||||
if originally_signed {
|
||||
status!("Preserving original AVB header signature");
|
||||
} else {
|
||||
status!("Leaving AVB header unsigned");
|
||||
}
|
||||
}
|
||||
SignAction::Sign => {
|
||||
if originally_signed {
|
||||
status!("Replacing AVB header signature");
|
||||
} else {
|
||||
status!("Signing AVB header");
|
||||
}
|
||||
|
||||
let Some(key_path) = &key_group.key else {
|
||||
bail!("Need to sign new AVB header, but no private key was specified");
|
||||
};
|
||||
|
||||
let passphrase = if let Some(v) = &key_group.pass_env_var {
|
||||
PassphraseSource::EnvVar(v.clone())
|
||||
} else if let Some(p) = &key_group.pass_file {
|
||||
PassphraseSource::File(p.clone())
|
||||
} else {
|
||||
PassphraseSource::Prompt(format!("Enter passphrase for {key_path:?}: "))
|
||||
};
|
||||
let private_key = crypto::read_pem_key_file(key_path, &passphrase)
|
||||
.with_context(|| format!("Failed to load key: {key_path:?}"))?;
|
||||
|
||||
info.header.set_algo_for_key(&private_key)?;
|
||||
info.header
|
||||
.sign(&private_key)
|
||||
.context("Failed to sign new AVB header")?;
|
||||
}
|
||||
SignAction::Clear => {
|
||||
if originally_signed {
|
||||
status!("Clearing AVB header signature");
|
||||
} else {
|
||||
status!("Leaving AVB header unsigned");
|
||||
}
|
||||
|
||||
info.header.algorithm_type = AlgorithmType::None;
|
||||
info.header.clear_sig();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Dump AVB information to stdout.
|
||||
fn display_info(display: &DisplayGroup, info: &AvbInfo) {
|
||||
if !display.quiet {
|
||||
println!("{info:#?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensure that the partition name won't cause directory traversals.
|
||||
fn ensure_name_is_safe(name: &str) -> Result<()> {
|
||||
if Path::new(name).file_name() != Some(OsStr::new(name)) {
|
||||
bail!("Unsafe partition name: {name}");
|
||||
@@ -34,7 +290,7 @@ fn ensure_name_is_safe(name: &str) -> Result<()> {
|
||||
|
||||
/// Recursively verify an image's vbmeta header and all of the chained images.
|
||||
/// `seen` is used to prevent cycles. `descriptors` will contain all of the hash
|
||||
/// and hashtree descriptors that need to be verified.
|
||||
/// and hash tree descriptors that need to be verified.
|
||||
pub fn verify_headers(
|
||||
directory: &Path,
|
||||
name: &str,
|
||||
@@ -81,7 +337,7 @@ pub fn verify_headers(
|
||||
};
|
||||
|
||||
match descriptor {
|
||||
avb::Descriptor::Hashtree(_) | avb::Descriptor::Hash(_) => {
|
||||
avb::Descriptor::HashTree(_) | avb::Descriptor::Hash(_) => {
|
||||
if let Some(prev) = descriptors.get(target_name) {
|
||||
if prev != descriptor {
|
||||
bail!("{name} descriptor does not match previous encounter");
|
||||
@@ -104,16 +360,80 @@ pub fn verify_headers(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verify the descriptor for a file. For hash tree descriptors, if FEC data is
|
||||
/// available and `repair` is true, then attempt to repair data in the event of
|
||||
/// corruption. `file` must be opened as read-write for the repair operation to
|
||||
/// work.
|
||||
fn verify_and_repair(
|
||||
name: Option<&str>,
|
||||
mut file: PSeekFile,
|
||||
descriptor: AppendedDescriptorRef,
|
||||
repair: bool,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let suffix = match name {
|
||||
Some(n) => format!(" for: {n}"),
|
||||
None => String::new(),
|
||||
};
|
||||
|
||||
match descriptor {
|
||||
AppendedDescriptorRef::HashTree(d) => {
|
||||
status!("Verifying hash tree descriptor{suffix}");
|
||||
|
||||
match d.verify(|| Ok(Box::new(file.reopen())), cancel_signal) {
|
||||
Err(
|
||||
e @ avb::Error::InvalidRootDigest { .. }
|
||||
| e @ avb::Error::InvalidHashTree { .. },
|
||||
) if repair => {
|
||||
warning!("Failed to verify hash tree descriptor{suffix}: {e}");
|
||||
warning!("Attempting to repair using FEC data{suffix}");
|
||||
|
||||
d.repair(
|
||||
|| Ok(Box::new(file.reopen())),
|
||||
|| Ok(Box::new(file.reopen())),
|
||||
cancel_signal,
|
||||
)
|
||||
.with_context(|| format!("Failed to repair data{suffix}"))?;
|
||||
|
||||
d.verify(|| Ok(Box::new(file.reopen())), cancel_signal)
|
||||
.map(|_| {
|
||||
status!("Successfully repaired data{suffix}");
|
||||
})
|
||||
}
|
||||
ret => ret,
|
||||
}
|
||||
.with_context(|| format!("Failed to verify hash tree descriptor{suffix}"))?;
|
||||
}
|
||||
AppendedDescriptorRef::Hash(d) => {
|
||||
status!("Verifying hash descriptor{suffix}");
|
||||
|
||||
file.rewind()?;
|
||||
d.verify(file, cancel_signal)
|
||||
.with_context(|| format!("Failed to verify hash descriptor{suffix}"))?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verify hash and hash tree descriptor digests and FEC data against their
|
||||
/// corresponding input files.
|
||||
pub fn verify_descriptors(
|
||||
directory: &Path,
|
||||
descriptors: &HashMap<String, Descriptor>,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
repair: bool,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
descriptors
|
||||
.par_iter()
|
||||
.map(|(name, descriptor)| {
|
||||
let path = directory.join(format!("{name}.img"));
|
||||
let reader = match File::open(&path).map(PSeekFile::new) {
|
||||
let file = match OpenOptions::new()
|
||||
.read(true)
|
||||
.write(repair)
|
||||
.open(&path)
|
||||
.map(PSeekFile::new)
|
||||
{
|
||||
Ok(f) => f,
|
||||
// Some devices, like bluejay, have vbmeta descriptors that
|
||||
// refer to partitions that exist on the device, but not in the
|
||||
@@ -127,91 +447,309 @@ pub fn verify_descriptors(
|
||||
}
|
||||
};
|
||||
|
||||
match descriptor {
|
||||
Descriptor::Hashtree(d) => {
|
||||
status!("Verifying hashtree descriptor for: {name}");
|
||||
d.verify(
|
||||
|| Ok(Box::new(BufReader::new(reader.clone()))),
|
||||
cancel_signal,
|
||||
)
|
||||
.with_context(|| format!("Failed to verify hashtree descriptor for: {name}"))?;
|
||||
}
|
||||
Descriptor::Hash(d) => {
|
||||
status!("Verifying hash descriptor for: {name}");
|
||||
d.verify(BufReader::new(reader), cancel_signal)
|
||||
.with_context(|| format!("Failed to verify hash descriptor for: {name}"))?;
|
||||
}
|
||||
_ => unreachable!("Non-verifiable descriptor: {descriptor:?}"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
verify_and_repair(
|
||||
Some(name),
|
||||
file,
|
||||
descriptor.try_into()?,
|
||||
repair,
|
||||
cancel_signal,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn avb_main(cli: &AvbCli, cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
match &cli.command {
|
||||
AvbCommand::Dump(c) => {
|
||||
let raw_reader = File::open(&c.input)
|
||||
.with_context(|| format!("Failed to open for reading: {:?}", c.input))?;
|
||||
let reader = BufReader::new(raw_reader);
|
||||
let (header, footer, image_size) = avb::load_image(reader)
|
||||
.with_context(|| format!("Failed to load vbmeta structures: {:?}", c.input))?;
|
||||
fn unpack_subcommand(cli: &UnpackCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let (info, mut reader) = read_avb_image(&cli.input)?;
|
||||
display_info(&cli.display, &info);
|
||||
|
||||
println!("Image size: {image_size}");
|
||||
println!("Header: {header:#?}");
|
||||
println!("Footer: {footer:#?}");
|
||||
}
|
||||
AvbCommand::Verify(c) => {
|
||||
let public_key = if let Some(p) = &c.public_key {
|
||||
let data = fs::read(p).with_context(|| format!("Failed to read file: {p:?}"))?;
|
||||
let key = avb::decode_public_key(&data)
|
||||
.with_context(|| format!("Failed to decode public key: {p:?}"))?;
|
||||
write_info(&cli.output_info, &info)?;
|
||||
|
||||
Some(key)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let directory = c.input.parent().unwrap_or_else(|| Path::new("."));
|
||||
let name = c
|
||||
.input
|
||||
.file_stem()
|
||||
.with_context(|| format!("Path is not a file: {:?}", c.input))?
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow!("Invalid UTF-8: {:?}", c.input))?;
|
||||
|
||||
let mut seen = HashSet::<String>::new();
|
||||
let mut descriptors = HashMap::<String, Descriptor>::new();
|
||||
|
||||
verify_headers(
|
||||
directory,
|
||||
name,
|
||||
public_key.as_ref(),
|
||||
&mut seen,
|
||||
&mut descriptors,
|
||||
)?;
|
||||
verify_descriptors(directory, &descriptors, cancel_signal)?;
|
||||
|
||||
status!("Successfully verified all vbmeta signatures and hashes");
|
||||
}
|
||||
if info.footer.is_some() {
|
||||
write_raw_and_verify(
|
||||
&cli.output_raw,
|
||||
&mut reader,
|
||||
&info,
|
||||
cli.ignore_invalid,
|
||||
cancel_signal,
|
||||
)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Dump AVB header and footer information.
|
||||
fn pack_subcommand(cli: &PackCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let mut info = read_info(&cli.input_info)?;
|
||||
let orig_header = info.header.clone();
|
||||
|
||||
let file = if info.footer.is_some() {
|
||||
let mut reader = File::open(&cli.input_raw)
|
||||
.map(BufReader::new)
|
||||
.with_context(|| {
|
||||
format!("Failed to open raw image for reading: {:?}", cli.input_raw)
|
||||
})?;
|
||||
|
||||
write_raw_and_update(&cli.output, &mut reader, &mut info, cancel_signal)?
|
||||
} else {
|
||||
File::create(&cli.output)
|
||||
.map(PSeekFile::new)
|
||||
.with_context(|| format!("Failed to open output for writing: {:?}", cli.output))?
|
||||
};
|
||||
|
||||
sign_or_clear(&mut info, &orig_header, &cli.key)?;
|
||||
|
||||
write_avb_image(file, &mut info)?;
|
||||
|
||||
// We display the info at the very end after both the header and footer are
|
||||
// updated so that incorrect/incomplete information isn't shown.
|
||||
display_info(&cli.display, &info);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn repack_subcommand(cli: &RepackCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let (mut info, mut reader) = read_avb_image(&cli.input)?;
|
||||
let orig_header = info.header.clone();
|
||||
|
||||
let file = if info.footer.is_some() {
|
||||
let file = write_raw_and_verify(&cli.output, &mut reader, &info, false, cancel_signal)?;
|
||||
|
||||
// Write new hash tree and FEC data instead of copying the original.
|
||||
// THere could have been errors in the original FEC data itself.
|
||||
if let AppendedDescriptorMut::HashTree(d) = info.header.appended_descriptor_mut()? {
|
||||
d.update(
|
||||
|| Ok(Box::new(file.reopen())),
|
||||
|| Ok(Box::new(file.reopen())),
|
||||
cancel_signal,
|
||||
)?;
|
||||
}
|
||||
|
||||
file
|
||||
} else {
|
||||
File::create(&cli.output)
|
||||
.map(PSeekFile::new)
|
||||
.with_context(|| format!("Failed to open for writing: {:?}", cli.output))?
|
||||
};
|
||||
|
||||
sign_or_clear(&mut info, &orig_header, &cli.key)?;
|
||||
|
||||
write_avb_image(file, &mut info)?;
|
||||
|
||||
// We display the info at the very end after both the header and footer are
|
||||
// updated so that incorrect/incomplete information isn't shown.
|
||||
display_info(&cli.display, &info);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn info_subcommand(cli: &InfoCli) -> Result<()> {
|
||||
let (info, _) = read_avb_image(&cli.input)?;
|
||||
display_info(&cli.display, &info);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_subcommand(cli: &VerifyCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let public_key = if let Some(p) = &cli.public_key {
|
||||
let data = fs::read(p).with_context(|| format!("Failed to read file: {p:?}"))?;
|
||||
let key = avb::decode_public_key(&data)
|
||||
.with_context(|| format!("Failed to decode public key: {p:?}"))?;
|
||||
|
||||
Some(key)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let directory = cli.input.parent().unwrap_or_else(|| Path::new("."));
|
||||
let name = cli
|
||||
.input
|
||||
.file_stem()
|
||||
.with_context(|| format!("Path is not a file: {:?}", cli.input))?
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow!("Invalid UTF-8: {:?}", cli.input))?;
|
||||
|
||||
let mut seen = HashSet::<String>::new();
|
||||
let mut descriptors = HashMap::<String, Descriptor>::new();
|
||||
|
||||
verify_headers(
|
||||
directory,
|
||||
name,
|
||||
public_key.as_ref(),
|
||||
&mut seen,
|
||||
&mut descriptors,
|
||||
)?;
|
||||
verify_descriptors(directory, &descriptors, cli.repair, cancel_signal)?;
|
||||
|
||||
status!("Successfully verified all vbmeta signatures and hashes");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn avb_main(cli: &AvbCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
match &cli.command {
|
||||
AvbCommand::Unpack(c) => unpack_subcommand(c, cancel_signal),
|
||||
AvbCommand::Pack(c) => pack_subcommand(c, cancel_signal),
|
||||
AvbCommand::Repack(c) => repack_subcommand(c, cancel_signal),
|
||||
AvbCommand::Info(c) => info_subcommand(c),
|
||||
AvbCommand::Verify(c) => verify_subcommand(c, cancel_signal),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
struct DisplayGroup {
|
||||
/// Don't print AVB image information.
|
||||
#[arg(short, long, global = true)]
|
||||
quiet: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
struct KeyGroup {
|
||||
/// Path to private key for signing.
|
||||
///
|
||||
/// A private key is needed if packing an image where the original header
|
||||
/// was signed and the header needs to be modified (eg. for a new checksum).
|
||||
/// If the header was originally not signed, then the private key is not
|
||||
/// used, unless --force is specified.
|
||||
#[arg(short, long, value_name = "FILE", value_parser)]
|
||||
key: Option<PathBuf>,
|
||||
|
||||
/// Force signing or clearing signature.
|
||||
///
|
||||
/// If --key is specified, then the output is signed, regardless if the
|
||||
/// original image was signed. Similarly, if --key is not specified, then
|
||||
/// the output is left unsigned, even if the image is unchanged and it's
|
||||
/// possible to preserve an existing signature.
|
||||
#[arg(short, long)]
|
||||
force: bool,
|
||||
|
||||
/// Environment variable containing private key passphrase.
|
||||
#[arg(long, value_name = "ENV_VAR", value_parser, group = "pass")]
|
||||
pass_env_var: Option<OsString>,
|
||||
|
||||
/// File containing private key passphrase.
|
||||
#[arg(long, value_name = "FILE", value_parser, group = "pass")]
|
||||
pass_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// Unpack an AVB image.
|
||||
///
|
||||
/// This command splits an AVB image into an AVB info TOML file and a raw image.
|
||||
/// For root AVB images (eg. vbmeta), only the info file is created, which will
|
||||
/// contain a header section. For appended AVB images (eg. boot), the raw image
|
||||
/// will be written and the info file will additionally have a footer section.
|
||||
///
|
||||
/// For appended AVB images that contain a hash tree descriptor (eg. dm-verity
|
||||
/// protected system image), FEC data, if available, will be used to repair the
|
||||
/// extracted raw image in the event of data corruption.
|
||||
#[derive(Debug, Parser)]
|
||||
struct DumpCli {
|
||||
/// Path to input image.
|
||||
struct UnpackCli {
|
||||
/// Path to input AVB image.
|
||||
#[arg(short, long, value_name = "FILE", value_parser)]
|
||||
input: PathBuf,
|
||||
|
||||
/// Path to output AVB info TOML.
|
||||
///
|
||||
/// The file will always contain a header section, but a footer section will
|
||||
/// only be present if the input is an appended AVB image.
|
||||
#[arg(long, value_name = "FILE", value_parser, default_value = "avb.toml")]
|
||||
output_info: PathBuf,
|
||||
|
||||
/// Path to output raw image.
|
||||
///
|
||||
/// Only appended AVB images will have a raw image.
|
||||
#[arg(long, value_name = "FILE", value_parser, default_value = "raw.img")]
|
||||
output_raw: PathBuf,
|
||||
|
||||
// Ignore invalid digests or FEC data.
|
||||
#[arg(long)]
|
||||
ignore_invalid: bool,
|
||||
|
||||
#[command(flatten)]
|
||||
display: DisplayGroup,
|
||||
}
|
||||
|
||||
/// Pack an AVB image.
|
||||
///
|
||||
/// This command creates an AVB image from the AVB info toml file and the raw
|
||||
/// image components. If the info file does not contain a footer, then a root
|
||||
/// image is created. Otherwise, an appended image is created and a raw image
|
||||
/// must be specified.
|
||||
///
|
||||
/// For appended images, the checksums in the header's descriptors and the
|
||||
/// offsets in the footer will be updated. If the header fields are updated and
|
||||
/// the header was originally signed, then the newly created image will also be
|
||||
/// signed. If a signed image is repacked without modification, then the
|
||||
/// original signature is used as-is.
|
||||
#[derive(Debug, Parser)]
|
||||
struct PackCli {
|
||||
/// Path to output AVB image.
|
||||
#[arg(short, long, value_name = "FILE", value_parser)]
|
||||
output: PathBuf,
|
||||
|
||||
/// Path to input AVB info TOML.
|
||||
///
|
||||
/// If an appended image is being created, then the hash or hash tree
|
||||
/// descriptor in the header will be updated with the new digest, offset,
|
||||
/// and size field values. There must be exactly one hash or hash tree
|
||||
/// descriptor. The offset and size fields in the footer will be updated as
|
||||
/// well.
|
||||
///
|
||||
/// For root images, all header descriptor fields are left unmodified.
|
||||
#[arg(long, value_name = "FILE", value_parser, default_value = "avb.toml")]
|
||||
input_info: PathBuf,
|
||||
|
||||
/// Path to input raw image.
|
||||
///
|
||||
/// Appended AVB images require a raw image.
|
||||
#[arg(long, value_name = "FILE", value_parser, default_value = "raw.img")]
|
||||
input_raw: PathBuf,
|
||||
|
||||
#[command(flatten)]
|
||||
key: KeyGroup,
|
||||
|
||||
#[command(flatten)]
|
||||
display: DisplayGroup,
|
||||
}
|
||||
|
||||
/// Repack an AVB image.
|
||||
///
|
||||
/// This command is equivalent to running `unpack` and `pack`, except without
|
||||
/// storing the unpacked data to disk.
|
||||
#[derive(Debug, Parser)]
|
||||
struct RepackCli {
|
||||
/// Path to input AVB image.
|
||||
#[arg(short, long, value_name = "FILE", value_parser)]
|
||||
input: PathBuf,
|
||||
|
||||
/// Path to output AVB image.
|
||||
#[arg(short, long, value_name = "FILE", value_parser)]
|
||||
output: PathBuf,
|
||||
|
||||
#[command(flatten)]
|
||||
key: KeyGroup,
|
||||
|
||||
#[command(flatten)]
|
||||
display: DisplayGroup,
|
||||
}
|
||||
|
||||
/// Display AVB header and footer information.
|
||||
#[derive(Debug, Parser)]
|
||||
struct InfoCli {
|
||||
/// Path to input AVB image.
|
||||
#[arg(short, long, value_name = "FILE", value_parser)]
|
||||
input: PathBuf,
|
||||
|
||||
#[command(flatten)]
|
||||
display: DisplayGroup,
|
||||
}
|
||||
|
||||
/// Verify vbmeta signatures.
|
||||
///
|
||||
/// If the header contains chain descriptors, then those images will be
|
||||
/// recursively verified. For hash tree descriptors, the FEC (forward error
|
||||
/// correction) data will also be verified.
|
||||
#[derive(Debug, Parser)]
|
||||
struct VerifyCli {
|
||||
/// Path to input image.
|
||||
/// Path to input AVB image.
|
||||
#[arg(short, long, value_name = "FILE", value_parser)]
|
||||
input: PathBuf,
|
||||
|
||||
@@ -221,11 +759,21 @@ struct VerifyCli {
|
||||
/// validity, not whether they are trusted.
|
||||
#[arg(short, long, value_name = "FILE", value_parser)]
|
||||
public_key: Option<PathBuf>,
|
||||
|
||||
/// Repair corrupted files using FEC data if possible.
|
||||
///
|
||||
/// Only images with hash tree descriptors can contain FEC data.
|
||||
#[arg(short, long)]
|
||||
repair: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
enum AvbCommand {
|
||||
Dump(DumpCli),
|
||||
Unpack(UnpackCli),
|
||||
Pack(PackCli),
|
||||
Repack(RepackCli),
|
||||
#[command(alias = "dump")]
|
||||
Info(InfoCli),
|
||||
Verify(VerifyCli),
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,9 @@ fn write_image(path: &Path, image: &BootImage) -> Result<()> {
|
||||
image
|
||||
.to_writer(&mut writer)
|
||||
.with_context(|| format!("Failed to write boot image: {path:?}"))?;
|
||||
writer.flush()?;
|
||||
writer
|
||||
.flush()
|
||||
.with_context(|| format!("Failed to flush boot image: {path:?}"))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2023 Andrew Gunnerson
|
||||
* SPDX-License-Identifier: GPL-3.0-only
|
||||
*/
|
||||
|
||||
use std::{
|
||||
fs::{File, OpenOptions},
|
||||
io::{BufReader, BufWriter, Write},
|
||||
path::{Path, PathBuf},
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
use crate::{
|
||||
format::fec::FecImage,
|
||||
stream::{FromReader, PSeekFile, ToWriter},
|
||||
};
|
||||
|
||||
fn open_input(path: &Path, rw: bool) -> Result<PSeekFile> {
|
||||
OpenOptions::new()
|
||||
.read(true)
|
||||
.write(rw)
|
||||
.open(path)
|
||||
.map(PSeekFile::new)
|
||||
.with_context(|| format!("Failed to open file: {path:?}"))
|
||||
}
|
||||
|
||||
fn read_fec(path: &Path) -> Result<FecImage> {
|
||||
let reader = File::open(path)
|
||||
.map(BufReader::new)
|
||||
.with_context(|| format!("Failed to open for reading: {path:?}"))?;
|
||||
let fec = FecImage::from_reader(reader)
|
||||
.with_context(|| format!("Failed to read FEC data: {path:?}"))?;
|
||||
|
||||
Ok(fec)
|
||||
}
|
||||
|
||||
fn write_fec(path: &Path, fec: &FecImage) -> Result<()> {
|
||||
let mut writer = File::create(path)
|
||||
.map(BufWriter::new)
|
||||
.with_context(|| format!("Failed to open for writing: {path:?}"))?;
|
||||
fec.to_writer(&mut writer)
|
||||
.with_context(|| format!("Failed to write FEC data: {path:?}"))?;
|
||||
writer
|
||||
.flush()
|
||||
.with_context(|| format!("Failed to flush FEC data: {path:?}"))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generate_subcommand(cli: &GenerateCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let input = open_input(&cli.input, false)?;
|
||||
|
||||
let fec = FecImage::generate(|| Ok(Box::new(input.reopen())), cli.parity, cancel_signal)
|
||||
.context("Failed to generate FEC data")?;
|
||||
|
||||
write_fec(&cli.fec, &fec)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_subcommand(cli: &VerifyCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let input = open_input(&cli.input, false)?;
|
||||
let fec = read_fec(&cli.fec)?;
|
||||
|
||||
fec.verify(|| Ok(Box::new(input.reopen())), cancel_signal)
|
||||
.context("Failed to verify data")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn repair_subcommand(cli: &RepairCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let input = open_input(&cli.input, true)?;
|
||||
let fec = read_fec(&cli.fec)?;
|
||||
|
||||
// The separate buffered readers and writers are safe because the function
|
||||
// guarantees that every thread touches disjoint offsets and every offset is
|
||||
// read and written at most once.
|
||||
fec.repair(
|
||||
|| Ok(Box::new(input.reopen())),
|
||||
|| Ok(Box::new(input.reopen())),
|
||||
cancel_signal,
|
||||
)
|
||||
.context("Failed to repair file")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn fec_main(cli: &FecCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
match &cli.command {
|
||||
FecCommand::Generate(c) => generate_subcommand(c, cancel_signal),
|
||||
FecCommand::Verify(c) => verify_subcommand(c, cancel_signal),
|
||||
FecCommand::Repair(c) => repair_subcommand(c, cancel_signal),
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate FEC data for a file.
|
||||
#[derive(Debug, Parser)]
|
||||
struct GenerateCli {
|
||||
/// Path to input data.
|
||||
#[arg(short, long, value_name = "FILE", value_parser)]
|
||||
input: PathBuf,
|
||||
|
||||
/// Path to output FEC data.
|
||||
#[arg(short, long, value_name = "FILE", value_parser)]
|
||||
fec: PathBuf,
|
||||
|
||||
/// Number of parity bytes per RS block (min 2, max 24).
|
||||
#[arg(short, long, value_name = "BYTES", default_value = "2")]
|
||||
parity: u8,
|
||||
}
|
||||
|
||||
/// Verify that a file contains no errors.
|
||||
#[derive(Debug, Parser)]
|
||||
struct VerifyCli {
|
||||
/// Path to input data.
|
||||
#[arg(short, long, value_name = "FILE", value_parser)]
|
||||
input: PathBuf,
|
||||
|
||||
/// Path to input FEC data.
|
||||
#[arg(short, long, value_name = "FILE", value_parser)]
|
||||
fec: PathBuf,
|
||||
}
|
||||
|
||||
/// Repair a file.
|
||||
#[derive(Debug, Parser)]
|
||||
struct RepairCli {
|
||||
/// Path to data.
|
||||
///
|
||||
/// The file will be modified in place.
|
||||
#[arg(short, long, value_name = "FILE", value_parser)]
|
||||
input: PathBuf,
|
||||
|
||||
/// Path to input FEC data.
|
||||
#[arg(short, long, value_name = "FILE", value_parser)]
|
||||
fec: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
enum FecCommand {
|
||||
Generate(GenerateCli),
|
||||
Verify(VerifyCli),
|
||||
Repair(RepairCli),
|
||||
}
|
||||
|
||||
/// Generate dm-verity FEC data and verify/repair files.
|
||||
///
|
||||
/// These commands operate on FEC files with AOSP's header format.
|
||||
#[derive(Debug, Parser)]
|
||||
pub struct FecCli {
|
||||
#[command(subcommand)]
|
||||
command: FecCommand,
|
||||
}
|
||||
@@ -61,7 +61,8 @@ pub fn key_main(cli: &KeyCli) -> Result<()> {
|
||||
let certificate = crypto::read_pem_cert_file(p)
|
||||
.with_context(|| format!("Failed to load certificate: {p:?}"))?;
|
||||
|
||||
crypto::get_public_key(&certificate)?
|
||||
crypto::get_public_key(&certificate)
|
||||
.with_context(|| format!("Failed to extract public key: {p:?}"))?
|
||||
} else {
|
||||
unreachable!()
|
||||
};
|
||||
|
||||
@@ -7,19 +7,20 @@ pub mod args;
|
||||
pub mod avb;
|
||||
pub mod boot;
|
||||
pub mod completion;
|
||||
pub mod fec;
|
||||
pub mod key;
|
||||
pub mod ota;
|
||||
pub mod ramdisk;
|
||||
|
||||
macro_rules! status {
|
||||
($($arg:tt)*) => {
|
||||
println!("\x1b[1m[*] {}\x1b[0m", format!($($arg)*))
|
||||
eprintln!("\x1b[1m[*] {}\x1b[0m", format!($($arg)*))
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! warning {
|
||||
($($arg:tt)*) => {
|
||||
println!("\x1b[1;31m[WARNING] {}\x1b[0m", format!($($arg)+))
|
||||
eprintln!("\x1b[1;31m[WARNING] {}\x1b[0m", format!($($arg)*))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+30
-35
@@ -11,7 +11,7 @@ use std::{
|
||||
fs::{self, File},
|
||||
io::{self, BufReader, BufWriter, Cursor, Read, Seek, SeekFrom, Write},
|
||||
path::{Path, PathBuf},
|
||||
sync::{atomic::AtomicBool, Arc, Mutex},
|
||||
sync::{atomic::AtomicBool, Mutex},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
@@ -31,7 +31,7 @@ use crate::{
|
||||
crypto::{self, PassphraseSource},
|
||||
format::{
|
||||
avb::Header,
|
||||
avb::{self, AlgorithmType, Descriptor},
|
||||
avb::{self, Descriptor},
|
||||
bootimage::BootImage,
|
||||
ota::{self, SigningWriter, ZipEntry},
|
||||
padding,
|
||||
@@ -143,7 +143,7 @@ fn open_input_streams(
|
||||
required_images: &HashMap<String, String>,
|
||||
external_images: &HashMap<String, PathBuf>,
|
||||
header: &PayloadHeader,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<HashMap<String, Box<dyn ReadSeek + Send>>> {
|
||||
let mut input_streams = HashMap::<String, Box<dyn ReadSeek + Send>>::new();
|
||||
|
||||
@@ -185,7 +185,7 @@ fn patch_boot_images(
|
||||
root_patcher: Option<Box<dyn BootImagePatcher + Send>>,
|
||||
key_avb: &RsaPrivateKey,
|
||||
cert_ota: &Certificate,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let mut boot_patchers = HashMap::<&str, Vec<Box<dyn BootImagePatcher + Send>>>::new();
|
||||
boot_patchers
|
||||
@@ -344,16 +344,7 @@ fn update_vbmeta_descriptors(
|
||||
}
|
||||
}
|
||||
|
||||
// avbroot doesn't support any other types.
|
||||
if parent_header.algorithm_type != AlgorithmType::Sha256Rsa4096 {
|
||||
parent_header.algorithm_type = AlgorithmType::Sha256Rsa4096;
|
||||
|
||||
status!(
|
||||
"{} signature algorithm type changed to {:?}",
|
||||
name,
|
||||
parent_header.algorithm_type
|
||||
);
|
||||
}
|
||||
parent_header.set_algo_for_key(key)?;
|
||||
|
||||
for dep in deps.iter() {
|
||||
// This can't fail since the descriptor must have existed for the
|
||||
@@ -382,7 +373,7 @@ fn update_vbmeta_descriptors(
|
||||
(Descriptor::Hash(pd), Descriptor::Hash(d)) => {
|
||||
*pd = d.clone();
|
||||
}
|
||||
(Descriptor::Hashtree(pd), Descriptor::Hashtree(d)) => {
|
||||
(Descriptor::HashTree(pd), Descriptor::HashTree(d)) => {
|
||||
*pd = d.clone();
|
||||
}
|
||||
_ => {
|
||||
@@ -426,7 +417,7 @@ fn compress_image(
|
||||
mut stream: &mut Box<dyn ReadSeek + Send>,
|
||||
header: &Mutex<PayloadHeader>,
|
||||
block_size: u32,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
stream.rewind()?;
|
||||
|
||||
@@ -460,7 +451,7 @@ fn patch_ota_payload(
|
||||
key_avb: &RsaPrivateKey,
|
||||
key_ota: &RsaPrivateKey,
|
||||
cert_ota: &Certificate,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<(String, u64)> {
|
||||
let header =
|
||||
PayloadHeader::from_reader(open_payload()?).context("Failed to load OTA payload header")?;
|
||||
@@ -565,7 +556,7 @@ fn patch_ota_payload(
|
||||
let header_locked = header.lock().unwrap();
|
||||
let mut payload_writer = PayloadWriter::new(writer, header_locked.clone(), key_ota.clone())
|
||||
.context("Failed to write payload header")?;
|
||||
let mut orig_payload_reader = open_payload()?;
|
||||
let mut orig_payload_reader = open_payload().context("Failed to open payload")?;
|
||||
|
||||
while payload_writer
|
||||
.begin_next_operation()
|
||||
@@ -581,7 +572,9 @@ fn patch_ota_payload(
|
||||
|
||||
if let Some(mut reader) = input_streams.remove(&name) {
|
||||
// Copy from our replacement image.
|
||||
reader.rewind()?;
|
||||
reader
|
||||
.rewind()
|
||||
.with_context(|| format!("Failed to seek image: {name}"))?;
|
||||
|
||||
stream::copy_n(&mut reader, &mut payload_writer, data_length, cancel_signal)
|
||||
.with_context(|| format!("Failed to copy from replacement image: {name}"))?;
|
||||
@@ -630,7 +623,7 @@ fn patch_ota_zip(
|
||||
key_avb: &RsaPrivateKey,
|
||||
key_ota: &RsaPrivateKey,
|
||||
cert_ota: &Certificate,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<(OtaMetadata, u64)> {
|
||||
let mut missing = BTreeSet::from([
|
||||
ota::PATH_METADATA_PB,
|
||||
@@ -725,7 +718,7 @@ fn patch_ota_zip(
|
||||
// The zip library doesn't provide us with a seekable
|
||||
// reader, so we make our own from the underlying file.
|
||||
Ok(Box::new(SectionReader::new(
|
||||
BufReader::new(raw_reader.clone()),
|
||||
BufReader::new(raw_reader.reopen()),
|
||||
payload_offset,
|
||||
payload_size,
|
||||
)?))
|
||||
@@ -797,7 +790,7 @@ fn extract_ota_zip(
|
||||
payload_size: u64,
|
||||
header: &PayloadHeader,
|
||||
images: &BTreeSet<String>,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
for name in images {
|
||||
if Path::new(name).file_name() != Some(OsStr::new(name)) {
|
||||
@@ -828,12 +821,12 @@ fn extract_ota_zip(
|
||||
payload::extract_images(
|
||||
|| {
|
||||
Ok(Box::new(SectionReader::new(
|
||||
BufReader::new(raw_reader.clone()),
|
||||
BufReader::new(raw_reader.reopen()),
|
||||
payload_offset,
|
||||
payload_size,
|
||||
)?))
|
||||
},
|
||||
|name| Ok(Box::new(BufWriter::new(output_files[name].clone()))),
|
||||
|name| Ok(Box::new(BufWriter::new(output_files[name].reopen()))),
|
||||
header,
|
||||
images.iter().map(|n| n.as_str()),
|
||||
cancel_signal,
|
||||
@@ -843,7 +836,7 @@ fn extract_ota_zip(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn patch_subcommand(cli: &PatchCli, cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
pub fn patch_subcommand(cli: &PatchCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let output = cli.output.as_ref().map_or_else(
|
||||
|| {
|
||||
let mut s = cli.input.clone().into_os_string();
|
||||
@@ -923,7 +916,7 @@ pub fn patch_subcommand(cli: &PatchCli, cancel_signal: &Arc<AtomicBool>) -> Resu
|
||||
let raw_reader = File::open(&cli.input)
|
||||
.map(PSeekFile::new)
|
||||
.with_context(|| format!("Failed to open for reading: {:?}", cli.input))?;
|
||||
let mut zip_reader = ZipArchive::new(BufReader::new(raw_reader.clone()))
|
||||
let mut zip_reader = ZipArchive::new(BufReader::new(raw_reader.reopen()))
|
||||
.with_context(|| format!("Failed to read zip: {:?}", cli.input))?;
|
||||
|
||||
// Open the output file for reading too, so we can verify offsets later.
|
||||
@@ -969,7 +962,7 @@ pub fn patch_subcommand(cli: &PatchCli, cancel_signal: &Arc<AtomicBool>) -> Resu
|
||||
|
||||
// We do a lot of low-level hackery. Reopen and verify offsets.
|
||||
status!("Verifying metadata offsets");
|
||||
temp_writer.rewind()?;
|
||||
temp_writer.rewind().context("Failed to seek output zip")?;
|
||||
ota::verify_metadata(
|
||||
BufReader::new(&mut temp_writer),
|
||||
&metadata,
|
||||
@@ -1008,11 +1001,11 @@ pub fn patch_subcommand(cli: &PatchCli, cancel_signal: &Arc<AtomicBool>) -> Resu
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn extract_subcommand(cli: &ExtractCli, cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
pub fn extract_subcommand(cli: &ExtractCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let raw_reader = File::open(&cli.input)
|
||||
.map(PSeekFile::new)
|
||||
.with_context(|| format!("Failed to open for reading: {:?}", cli.input))?;
|
||||
let mut zip = ZipArchive::new(BufReader::new(raw_reader.clone()))
|
||||
let mut zip = ZipArchive::new(BufReader::new(raw_reader.reopen()))
|
||||
.with_context(|| format!("Failed to read zip: {:?}", cli.input))?;
|
||||
let payload_entry = zip
|
||||
.by_name(ota::PATH_PAYLOAD)
|
||||
@@ -1022,10 +1015,11 @@ pub fn extract_subcommand(cli: &ExtractCli, cancel_signal: &Arc<AtomicBool>) ->
|
||||
|
||||
// Open the payload data directly.
|
||||
let mut payload_reader = SectionReader::new(
|
||||
BufReader::new(raw_reader.clone()),
|
||||
BufReader::new(raw_reader.reopen()),
|
||||
payload_offset,
|
||||
payload_size,
|
||||
)?;
|
||||
)
|
||||
.context("Failed to directly open payload section")?;
|
||||
|
||||
let header = PayloadHeader::from_reader(&mut payload_reader)
|
||||
.context("Failed to load OTA payload header")?;
|
||||
@@ -1067,7 +1061,7 @@ pub fn extract_subcommand(cli: &ExtractCli, cancel_signal: &Arc<AtomicBool>) ->
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn verify_subcommand(cli: &VerifyCli, cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
pub fn verify_subcommand(cli: &VerifyCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let raw_reader = File::open(&cli.input)
|
||||
.map(PSeekFile::new)
|
||||
.with_context(|| format!("Failed to open for reading: {:?}", cli.input))?;
|
||||
@@ -1110,7 +1104,8 @@ pub fn verify_subcommand(cli: &VerifyCli, cancel_signal: &Arc<AtomicBool>) -> Re
|
||||
.find(|pf| pf.name == ota::PATH_PAYLOAD)
|
||||
.ok_or_else(|| anyhow!("Missing property files entry: {}", ota::PATH_PAYLOAD))?;
|
||||
|
||||
let section_reader = SectionReader::new(&mut reader, pf_payload.offset, pf_payload.size)?;
|
||||
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)?;
|
||||
|
||||
@@ -1177,14 +1172,14 @@ pub fn verify_subcommand(cli: &VerifyCli, cancel_signal: &Arc<AtomicBool>) -> Re
|
||||
&mut seen,
|
||||
&mut descriptors,
|
||||
)?;
|
||||
cli::avb::verify_descriptors(temp_dir.path(), &descriptors, cancel_signal)?;
|
||||
cli::avb::verify_descriptors(temp_dir.path(), &descriptors, false, cancel_signal)?;
|
||||
|
||||
status!("Signatures are all valid!");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn ota_main(cli: &OtaCli, cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
pub fn ota_main(cli: &OtaCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
match &cli.command {
|
||||
OtaCommand::Patch(c) => patch_subcommand(c, cancel_signal),
|
||||
OtaCommand::Extract(c) => extract_subcommand(c, cancel_signal),
|
||||
|
||||
@@ -12,12 +12,9 @@ use std::{
|
||||
use anyhow::{Context, Result};
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
use crate::{
|
||||
format::{
|
||||
compression::{CompressedFormat, CompressedReader, CompressedWriter},
|
||||
cpio::{self, CpioEntryNew},
|
||||
},
|
||||
util::EscapedString,
|
||||
use crate::format::{
|
||||
compression::{CompressedFormat, CompressedReader, CompressedWriter},
|
||||
cpio::{self, CpioEntryNew},
|
||||
};
|
||||
|
||||
static CONTENT_BEGIN: &str = "----- BEGIN UTF-8 CONTENT -----";
|
||||
@@ -59,10 +56,10 @@ fn print_content(data: &[u8], truncate: bool) {
|
||||
println!("{BINARY_BEGIN}");
|
||||
|
||||
if data.len() > 512 && truncate {
|
||||
println!("{}", EscapedString::new_unquoted(&data[..512]));
|
||||
println!("{}", data[..512].escape_ascii());
|
||||
println!("{BINARY_END_TRUNCATED}");
|
||||
} else {
|
||||
println!("{}", EscapedString::new_unquoted(&data));
|
||||
println!("{}", data.escape_ascii());
|
||||
println!("{BINARY_END}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ pub enum Error {
|
||||
#[error("DER error")]
|
||||
Der(#[from] x509_cert::der::Error),
|
||||
#[error("RSA error")]
|
||||
RsaSign(#[from] rsa::Error),
|
||||
Rsa(#[from] rsa::Error),
|
||||
#[error("I/O error")]
|
||||
Io(#[from] io::Error),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2023 Andrew Gunnerson
|
||||
* SPDX-License-Identifier: GPL-3.0-only
|
||||
*/
|
||||
|
||||
use std::{fmt, marker::PhantomData};
|
||||
|
||||
use bstr::{ByteSlice, ByteVec};
|
||||
use serde::{de::Visitor, Deserializer, Serializer};
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Clone, Debug, Error)]
|
||||
pub enum Error {
|
||||
#[error("Decoded string size ({actual}) does not match expected size ({expected})")]
|
||||
BadLength { expected: usize, actual: usize },
|
||||
}
|
||||
|
||||
pub trait FromEscaped: Sized {
|
||||
type Error;
|
||||
|
||||
fn from_escaped(data: &str) -> Result<Self, Self::Error>;
|
||||
}
|
||||
|
||||
impl FromEscaped for Vec<u8> {
|
||||
type Error = Error;
|
||||
|
||||
fn from_escaped(data: &str) -> Result<Self, Self::Error> {
|
||||
Ok(Self::unescape_bytes(data))
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> FromEscaped for [u8; N] {
|
||||
type Error = Error;
|
||||
|
||||
fn from_escaped(data: &str) -> Result<Self, Self::Error> {
|
||||
// Wasteful allocation, but bstr doesn't expose its decoder iterator in
|
||||
// its public API.
|
||||
let decoded = Vec::<u8>::from_escaped(data)?;
|
||||
let mut buf = [0u8; N];
|
||||
|
||||
if decoded.len() != buf.len() {
|
||||
return Err(Error::BadLength {
|
||||
expected: buf.len(),
|
||||
actual: decoded.len(),
|
||||
});
|
||||
}
|
||||
|
||||
buf.copy_from_slice(&decoded);
|
||||
|
||||
Ok(buf)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn serialize<S, T>(data: T, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
T: AsRef<[u8]>,
|
||||
{
|
||||
let s = data.as_ref().escape_bytes().to_string();
|
||||
serializer.serialize_str(&s)
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
T: FromEscaped,
|
||||
<T as FromEscaped>::Error: fmt::Display,
|
||||
{
|
||||
struct EscapedStrVisitor<T>(PhantomData<T>);
|
||||
|
||||
impl<'de, T> Visitor<'de> for EscapedStrVisitor<T>
|
||||
where
|
||||
T: FromEscaped,
|
||||
<T as FromEscaped>::Error: fmt::Display,
|
||||
{
|
||||
type Value = T;
|
||||
|
||||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "an escaped string")
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, data: &str) -> Result<Self::Value, E>
|
||||
where
|
||||
E: serde::de::Error,
|
||||
{
|
||||
FromEscaped::from_escaped(data).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
deserializer.deserialize_str(EscapedStrVisitor(PhantomData))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use assert_matches::assert_matches;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn decode_vec() {
|
||||
for s in ["", "abc", "你好", "💩", "\x00", "\t\r\n"] {
|
||||
let escaped_s = s.as_bytes().escape_bytes().to_string();
|
||||
let decoded = Vec::<u8>::from_escaped(&escaped_s).unwrap();
|
||||
|
||||
assert_eq!(decoded, s.as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_array() {
|
||||
assert_matches!(
|
||||
<[u8; 4]>::from_escaped(r"\t\r\n"),
|
||||
Err(Error::BadLength {
|
||||
expected: 4,
|
||||
actual: 3,
|
||||
})
|
||||
);
|
||||
assert_matches!(
|
||||
<[u8; 4]>::from_escaped(r"\t\r\n\x00\x00"),
|
||||
Err(Error::BadLength {
|
||||
expected: 4,
|
||||
actual: 5,
|
||||
})
|
||||
);
|
||||
assert_matches!(
|
||||
<[u8; 4]>::from_escaped(r"\t\r\n\x00"),
|
||||
Ok(data) if data == *b"\t\r\n\x00"
|
||||
);
|
||||
|
||||
assert_matches!(
|
||||
<[u8; 0]>::from_escaped(r"\t"),
|
||||
Err(Error::BadLength {
|
||||
expected: 0,
|
||||
actual: 1,
|
||||
})
|
||||
);
|
||||
assert_matches!(
|
||||
<[u8; 0]>::from_escaped(r""),
|
||||
Ok(data) if data.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_serde() {
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct TestData {
|
||||
#[serde(with = "super")]
|
||||
contents: Vec<u8>,
|
||||
}
|
||||
|
||||
let mut contents = b"foo\xffbar".to_vec();
|
||||
contents.extend("💩".as_bytes());
|
||||
|
||||
let data = TestData { contents };
|
||||
let serialized = toml_edit::ser::to_string(&data).unwrap();
|
||||
|
||||
assert_eq!(serialized, "contents = 'foo\\xFFbar💩'\n");
|
||||
|
||||
let new_data: TestData = toml_edit::de::from_str(&serialized).unwrap();
|
||||
assert_eq!(data.contents, new_data.contents);
|
||||
}
|
||||
}
|
||||
+440
-110
@@ -7,28 +7,31 @@ use std::{
|
||||
cmp, fmt,
|
||||
io::{self, Cursor, Read, Seek, SeekFrom, Write},
|
||||
str,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
},
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
|
||||
use bstr::ByteSlice;
|
||||
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
|
||||
use num_bigint_dig::{ModInverse, ToBigInt};
|
||||
use num_traits::{Pow, ToPrimitive};
|
||||
use rayon::prelude::{IntoParallelIterator, ParallelIterator};
|
||||
use ring::digest::{Algorithm, Context};
|
||||
use rsa::{traits::PublicKeyParts, BigUint, Pkcs1v15Sign, RsaPrivateKey, RsaPublicKey};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256, Sha512};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{
|
||||
format::padding,
|
||||
escape,
|
||||
format::{
|
||||
fec::{self, Fec},
|
||||
padding,
|
||||
},
|
||||
stream::{
|
||||
self, CountingReader, FromReader, ReadDiscardExt, ReadSeek, ReadStringExt, ToWriter,
|
||||
WriteStringExt, WriteZerosExt,
|
||||
WriteSeek, WriteStringExt, WriteZerosExt,
|
||||
},
|
||||
util::{self, EscapedString},
|
||||
util,
|
||||
};
|
||||
|
||||
pub const VERSION_MAJOR: u32 = 1;
|
||||
@@ -57,8 +60,6 @@ pub enum Error {
|
||||
PaddingTooLong,
|
||||
#[error("{0:?} field padding contains non-zero bytes")]
|
||||
PaddingNotZero(&'static str),
|
||||
#[error("{0:?} field + {1:?} field is out of bounds")]
|
||||
OutOfBounds(&'static str, &'static str),
|
||||
#[error("{0:?} field size does not equal size of contained items")]
|
||||
IncorrectCombinedSize(&'static str),
|
||||
#[error("Invalid VBMeta header magic: {0:?}")]
|
||||
@@ -71,25 +72,50 @@ pub enum Error {
|
||||
UnsupportedAlgorithm(AlgorithmType),
|
||||
#[error("Hashing algorithm not supported: {0:?}")]
|
||||
UnsupportedHashAlgorithm(String),
|
||||
#[error("Incorrect key size ({0} bytes) for algorithm {1:?} ({2} bytes)")]
|
||||
IncorrectKeySize(usize, AlgorithmType, usize),
|
||||
#[error("Expected root digest {0}, but have {1}")]
|
||||
InvalidRootDigest(String, String),
|
||||
#[error("Expected hash tree {0}, but have {1}")]
|
||||
InvalidHashtree(String, String),
|
||||
#[error("Incorrect key size ({key_size} bytes) for algorithm {algo:?} ({} bytes)", algo.public_key_len())]
|
||||
IncorrectKeySize {
|
||||
key_size: usize,
|
||||
algo: AlgorithmType,
|
||||
},
|
||||
#[error("RSA key size (0) is not compatible with any AVB signing algorithm")]
|
||||
UnsupportedKey(usize),
|
||||
#[error("Expected root digest {expected}, but have {actual}")]
|
||||
InvalidRootDigest { expected: String, actual: String },
|
||||
#[error("Expected hash tree {expected}, but have {actual}")]
|
||||
InvalidHashTree { expected: String, actual: String },
|
||||
#[error("Hash tree does not immediately follow image data")]
|
||||
HashTreeGap,
|
||||
#[error("FEC data does not immediately follow hash tree")]
|
||||
FecDataGap,
|
||||
#[error("Cannot repair image because there is no FEC data")]
|
||||
FecMissing,
|
||||
#[error("FEC requires data block size ({data}) and hash block size ({hash}) to match")]
|
||||
MismatchedFecBlockSizes { data: u32, hash: u32 },
|
||||
#[error("Must have exactly one hash or hash tree descriptor")]
|
||||
NoAppendedDescriptor,
|
||||
#[error("Failed to RSA sign digest")]
|
||||
RsaSignError(rsa::Error),
|
||||
RsaSign(#[source] rsa::Error),
|
||||
#[error("Failed to RSA verify signature")]
|
||||
RsaVerifyError(rsa::Error),
|
||||
RsaVerify(#[source] rsa::Error),
|
||||
#[error("{0} byte image size is too small to fit header or footer")]
|
||||
ImageSizeTooSmall(u64),
|
||||
#[error("FEC error")]
|
||||
Fec(#[from] fec::Error),
|
||||
#[error("I/O error")]
|
||||
IoError(#[from] io::Error),
|
||||
Io(#[from] io::Error),
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
fn ring_algorithm(name: &str) -> Result<&'static Algorithm> {
|
||||
match name {
|
||||
"sha256" => Ok(&ring::digest::SHA256),
|
||||
"sha512" => Ok(&ring::digest::SHA512),
|
||||
a => Err(Error::UnsupportedHashAlgorithm(a.to_owned())),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
|
||||
pub enum AlgorithmType {
|
||||
None,
|
||||
Sha256Rsa2048,
|
||||
@@ -175,11 +201,11 @@ impl AlgorithmType {
|
||||
Self::None | Self::Unknown(_) => vec![],
|
||||
Self::Sha256Rsa2048 | Self::Sha256Rsa4096 | Self::Sha256Rsa8192 => {
|
||||
let scheme = Pkcs1v15Sign::new::<Sha256>();
|
||||
key.sign(scheme, digest).map_err(Error::RsaSignError)?
|
||||
key.sign(scheme, digest).map_err(Error::RsaSign)?
|
||||
}
|
||||
Self::Sha512Rsa2048 | Self::Sha512Rsa4096 | Self::Sha512Rsa8192 => {
|
||||
let scheme = Pkcs1v15Sign::new::<Sha512>();
|
||||
key.sign(scheme, digest).map_err(Error::RsaSignError)?
|
||||
key.sign(scheme, digest).map_err(Error::RsaSign)?
|
||||
}
|
||||
};
|
||||
|
||||
@@ -192,12 +218,12 @@ impl AlgorithmType {
|
||||
Self::Sha256Rsa2048 | Self::Sha256Rsa4096 | Self::Sha256Rsa8192 => {
|
||||
let scheme = Pkcs1v15Sign::new::<Sha256>();
|
||||
key.verify(scheme, digest, signature)
|
||||
.map_err(Error::RsaVerifyError)?;
|
||||
.map_err(Error::RsaVerify)?;
|
||||
}
|
||||
Self::Sha512Rsa2048 | Self::Sha512Rsa4096 | Self::Sha512Rsa8192 => {
|
||||
let scheme = Pkcs1v15Sign::new::<Sha512>();
|
||||
key.verify(scheme, digest, signature)
|
||||
.map_err(Error::RsaVerifyError)?;
|
||||
.map_err(Error::RsaVerify)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,9 +239,10 @@ trait DescriptorTag {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, PartialEq)]
|
||||
#[derive(Clone, Eq, PartialEq, Deserialize, Serialize)]
|
||||
pub struct PropertyDescriptor {
|
||||
pub key: String,
|
||||
#[serde(with = "escape")]
|
||||
pub value: Vec<u8>,
|
||||
}
|
||||
|
||||
@@ -223,7 +250,7 @@ impl fmt::Debug for PropertyDescriptor {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("PropertyDescriptor")
|
||||
.field("key", &self.key)
|
||||
.field("value", &EscapedString::new(&self.value))
|
||||
.field("value", &self.value.as_bstr())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
@@ -283,8 +310,8 @@ impl<W: Write> ToWriter<W> for PropertyDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, PartialEq)]
|
||||
pub struct HashtreeDescriptor {
|
||||
#[derive(Clone, Eq, PartialEq, Deserialize, Serialize)]
|
||||
pub struct HashTreeDescriptor {
|
||||
pub dm_verity_version: u32,
|
||||
pub image_size: u64,
|
||||
pub tree_offset: u64,
|
||||
@@ -296,15 +323,18 @@ pub struct HashtreeDescriptor {
|
||||
pub fec_size: u64,
|
||||
pub hash_algorithm: String,
|
||||
pub partition_name: String,
|
||||
#[serde(with = "hex")]
|
||||
pub salt: Vec<u8>,
|
||||
#[serde(with = "hex")]
|
||||
pub root_digest: Vec<u8>,
|
||||
pub flags: u32,
|
||||
#[serde(with = "hex")]
|
||||
pub reserved: [u8; 60],
|
||||
}
|
||||
|
||||
impl fmt::Debug for HashtreeDescriptor {
|
||||
impl fmt::Debug for HashTreeDescriptor {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("HashtreeDescriptor")
|
||||
f.debug_struct("HashTreeDescriptor")
|
||||
.field("dm_verity_version", &self.dm_verity_version)
|
||||
.field("image_size", &self.image_size)
|
||||
.field("tree_offset", &self.tree_offset)
|
||||
@@ -324,7 +354,7 @@ impl fmt::Debug for HashtreeDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
impl HashtreeDescriptor {
|
||||
impl HashTreeDescriptor {
|
||||
/// Calculate the hash tree digests for a single level of the tree. If the
|
||||
/// reader's position is block-aligned and `image_size` is a multiple of the
|
||||
/// block size, then this function can also be used to calculate the digests
|
||||
@@ -337,7 +367,7 @@ impl HashtreeDescriptor {
|
||||
block_size: u32,
|
||||
algorithm: &'static Algorithm,
|
||||
salt: &[u8],
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> io::Result<Vec<u8>> {
|
||||
// Each digest must be a power of 2.
|
||||
let digest_padding = algorithm.output_len.next_power_of_two() - algorithm.output_len;
|
||||
@@ -345,12 +375,7 @@ impl HashtreeDescriptor {
|
||||
let mut result = vec![];
|
||||
|
||||
while image_size > 0 {
|
||||
if cancel_signal.load(Ordering::SeqCst) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"Received cancel signal",
|
||||
));
|
||||
}
|
||||
stream::check_cancel(cancel_signal)?;
|
||||
|
||||
let n = image_size.min(buf.len() as u64) as usize;
|
||||
reader.read_exact(&mut buf[..n])?;
|
||||
@@ -384,7 +409,7 @@ impl HashtreeDescriptor {
|
||||
block_size: u32,
|
||||
algorithm: &'static Algorithm,
|
||||
salt: &[u8],
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> io::Result<Vec<u8>> {
|
||||
assert!(
|
||||
image_size > block_size as u64,
|
||||
@@ -418,7 +443,7 @@ impl HashtreeDescriptor {
|
||||
block_size: u32,
|
||||
algorithm: &'static Algorithm,
|
||||
salt: &[u8],
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> io::Result<(Vec<u8>, Vec<u8>)> {
|
||||
// Small files are hashed directly, exactly like a hash descriptor.
|
||||
if image_size <= u64::from(block_size) {
|
||||
@@ -480,19 +505,140 @@ impl HashtreeDescriptor {
|
||||
Ok((root_hash, hash_tree))
|
||||
}
|
||||
|
||||
/// Verify the root hash and hash tree against the input reader in parallel.
|
||||
/// `open_input` will be called from multiple threads and must return
|
||||
/// independently seekable handles the the same file.
|
||||
/// Ensure that the image data is immediately followed by the hash tree and
|
||||
/// then the FEC data.
|
||||
fn check_offsets(&self) -> Result<()> {
|
||||
if self.tree_offset != self.image_size {
|
||||
return Err(Error::HashTreeGap);
|
||||
}
|
||||
|
||||
// The FEC data section is optional.
|
||||
if self.fec_num_roots != 0 {
|
||||
if self.fec_offset != self.tree_offset + self.tree_size {
|
||||
return Err(Error::FecDataGap);
|
||||
} else if self.data_block_size != self.hash_block_size {
|
||||
return Err(Error::MismatchedFecBlockSizes {
|
||||
data: self.data_block_size,
|
||||
hash: self.hash_block_size,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get [`Fec`] instance with the parameters from this descriptor.
|
||||
fn get_fec(&self) -> Result<(Fec, usize)> {
|
||||
if self.fec_num_roots == 0 {
|
||||
return Err(Error::FecMissing);
|
||||
}
|
||||
|
||||
let fec_size = self
|
||||
.fec_size
|
||||
.to_usize()
|
||||
.ok_or_else(|| Error::IntegerTooLarge("fec_size"))?;
|
||||
let parity = self
|
||||
.fec_num_roots
|
||||
.to_u8()
|
||||
.ok_or_else(|| Error::IntegerTooLarge("fec_num_roots"))?;
|
||||
|
||||
// The FEC covers the hash tree as well.
|
||||
let fec = Fec::new(
|
||||
self.image_size + self.tree_size,
|
||||
self.data_block_size,
|
||||
parity,
|
||||
)?;
|
||||
|
||||
Ok((fec, fec_size))
|
||||
}
|
||||
|
||||
/// Update the root hash, hash tree, and FEC data. The hash tree and FEC
|
||||
/// data will be written immediately following the image data at offset
|
||||
/// [`Self::image_size`]. Both `open_input` and `open_output` may be called
|
||||
/// from multiple threads and must return independently seekable handles to
|
||||
/// the same file. It is guaranteed that every thread will read and write
|
||||
/// disjoint file offsets.
|
||||
///
|
||||
/// Due to the nature of the file access patterns needed to generate the
|
||||
/// hash tree and FEC data, the entire file will be read twice. However, if
|
||||
/// [`Self::fec_num_roots`] is 0, no FEC data will be computed nor written.
|
||||
///
|
||||
/// The fields in this instance are updated atomically. No fields are
|
||||
/// updated if an error occurs. The input file can be restored back to its
|
||||
/// original state by truncating it to [`Self::image_size`].
|
||||
pub fn update(
|
||||
&mut self,
|
||||
open_input: impl Fn() -> io::Result<Box<dyn ReadSeek>> + Sync,
|
||||
open_output: impl Fn() -> io::Result<Box<dyn WriteSeek>> + Sync,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let algorithm = ring_algorithm(&self.hash_algorithm)?;
|
||||
let (root_digest, hash_tree) = Self::calculate_hash_tree(
|
||||
&open_input,
|
||||
self.image_size,
|
||||
self.data_block_size,
|
||||
algorithm,
|
||||
&self.salt,
|
||||
cancel_signal,
|
||||
)?;
|
||||
|
||||
let tree_size = hash_tree
|
||||
.len()
|
||||
.to_u64()
|
||||
.ok_or_else(|| Error::IntegerTooLarge("tree_size"))?;
|
||||
|
||||
let mut writer = open_output()?;
|
||||
writer.seek(SeekFrom::Start(self.image_size))?;
|
||||
writer.write_all(&hash_tree)?;
|
||||
|
||||
// The FEC data section is optional.
|
||||
if self.fec_num_roots != 0 {
|
||||
if self.data_block_size != self.hash_block_size {
|
||||
return Err(Error::MismatchedFecBlockSizes {
|
||||
data: self.data_block_size,
|
||||
hash: self.hash_block_size,
|
||||
});
|
||||
}
|
||||
|
||||
let parity = self
|
||||
.fec_num_roots
|
||||
.to_u8()
|
||||
.ok_or_else(|| Error::IntegerTooLarge("fec_num_roots"))?;
|
||||
|
||||
// The FEC covers the hash tree as well.
|
||||
let fec = Fec::new(self.image_size + tree_size, self.data_block_size, parity)?;
|
||||
|
||||
let fec_data = fec.generate(open_input, cancel_signal)?;
|
||||
let fec_size = fec_data
|
||||
.len()
|
||||
.to_u64()
|
||||
.ok_or_else(|| Error::IntegerTooLarge("fec_size"))?;
|
||||
|
||||
// Already seeked to FEC.
|
||||
writer.write_all(&fec_data)?;
|
||||
|
||||
self.fec_offset = self.image_size + tree_size;
|
||||
self.fec_size = fec_size;
|
||||
}
|
||||
|
||||
self.tree_offset = self.image_size;
|
||||
self.tree_size = tree_size;
|
||||
self.root_digest = root_digest;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verify the root hash, hash tree, and FEC data. `open_input` will be
|
||||
/// called from multiple threads and must return independently seekable
|
||||
/// handles to the same file.
|
||||
pub fn verify(
|
||||
&self,
|
||||
open_input: impl Fn() -> io::Result<Box<dyn ReadSeek>> + Sync,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let algorithm = match self.hash_algorithm.as_str() {
|
||||
"sha256" => &ring::digest::SHA256,
|
||||
"sha512" => &ring::digest::SHA512,
|
||||
a => return Err(Error::UnsupportedHashAlgorithm(a.to_owned())),
|
||||
};
|
||||
self.check_offsets()?;
|
||||
|
||||
let algorithm = ring_algorithm(&self.hash_algorithm)?;
|
||||
let tree_size = self
|
||||
.tree_size
|
||||
.to_usize()
|
||||
@@ -508,10 +654,10 @@ impl HashtreeDescriptor {
|
||||
)?;
|
||||
|
||||
if self.root_digest != actual_root_digest {
|
||||
return Err(Error::InvalidRootDigest(
|
||||
hex::encode(&self.root_digest),
|
||||
hex::encode(actual_root_digest),
|
||||
));
|
||||
return Err(Error::InvalidRootDigest {
|
||||
expected: hex::encode(&self.root_digest),
|
||||
actual: hex::encode(actual_root_digest),
|
||||
});
|
||||
}
|
||||
|
||||
let mut reader = open_input()?;
|
||||
@@ -525,21 +671,67 @@ impl HashtreeDescriptor {
|
||||
let expected = ring::digest::digest(algorithm, &hash_tree);
|
||||
let actual = ring::digest::digest(algorithm, &actual_hash_tree);
|
||||
|
||||
return Err(Error::InvalidRootDigest(
|
||||
hex::encode(expected),
|
||||
hex::encode(actual),
|
||||
));
|
||||
return Err(Error::InvalidHashTree {
|
||||
expected: hex::encode(expected),
|
||||
actual: hex::encode(actual),
|
||||
});
|
||||
}
|
||||
|
||||
// The FEC data section is optional.
|
||||
if self.fec_num_roots != 0 {
|
||||
let (fec, fec_size) = self.get_fec()?;
|
||||
|
||||
let mut fec_data = vec![0u8; fec_size];
|
||||
// Already seeked to FEC.
|
||||
reader.read_exact(&mut fec_data)?;
|
||||
|
||||
fec.verify(open_input, &fec_data, cancel_signal)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Try to repair errors in the input file using the FEC data. Both
|
||||
/// `open_input` and `open_output` may be called from multiple threads and
|
||||
/// must return independently seekable handles to the same file.
|
||||
///
|
||||
/// Due to the nature of FEC, when there are too many errors, it's possible
|
||||
/// for the data to be miscorrected to a "valid" state. [`Self::verify()`]
|
||||
/// should be called after the repair is complete to ensure that the data is
|
||||
/// actually valid.
|
||||
pub fn repair(
|
||||
&self,
|
||||
open_input: impl Fn() -> io::Result<Box<dyn ReadSeek>> + Sync,
|
||||
open_output: impl Fn() -> io::Result<Box<dyn WriteSeek>> + Sync,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
self.check_offsets()?;
|
||||
|
||||
// The FEC data section is optional.
|
||||
if self.fec_size == 0 {
|
||||
return Err(Error::FecMissing);
|
||||
}
|
||||
|
||||
let mut reader = open_input()?;
|
||||
reader.seek(SeekFrom::Start(self.fec_offset))?;
|
||||
|
||||
let (fec, fec_size) = self.get_fec()?;
|
||||
|
||||
let mut fec_data = vec![0u8; fec_size];
|
||||
// Already seeked to FEC.
|
||||
reader.read_exact(&mut fec_data)?;
|
||||
|
||||
fec.repair(open_input, open_output, &fec_data, cancel_signal)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl DescriptorTag for HashtreeDescriptor {
|
||||
impl DescriptorTag for HashTreeDescriptor {
|
||||
const TAG: u64 = 1;
|
||||
}
|
||||
|
||||
impl<R: Read> FromReader<R> for HashtreeDescriptor {
|
||||
impl<R: Read> FromReader<R> for HashTreeDescriptor {
|
||||
type Error = Error;
|
||||
|
||||
fn from_reader(mut reader: R) -> Result<Self> {
|
||||
@@ -601,7 +793,7 @@ impl<R: Read> FromReader<R> for HashtreeDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write> ToWriter<W> for HashtreeDescriptor {
|
||||
impl<W: Write> ToWriter<W> for HashTreeDescriptor {
|
||||
type Error = Error;
|
||||
|
||||
fn to_writer(&self, mut writer: W) -> Result<()> {
|
||||
@@ -656,14 +848,17 @@ impl<W: Write> ToWriter<W> for HashtreeDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, PartialEq)]
|
||||
#[derive(Clone, Eq, PartialEq, Deserialize, Serialize)]
|
||||
pub struct HashDescriptor {
|
||||
pub image_size: u64,
|
||||
pub hash_algorithm: String,
|
||||
pub partition_name: String,
|
||||
#[serde(with = "hex")]
|
||||
pub salt: Vec<u8>,
|
||||
#[serde(with = "hex")]
|
||||
pub root_digest: Vec<u8>,
|
||||
pub flags: u32,
|
||||
#[serde(with = "hex")]
|
||||
pub reserved: [u8; 60],
|
||||
}
|
||||
|
||||
@@ -682,14 +877,12 @@ impl fmt::Debug for HashDescriptor {
|
||||
}
|
||||
|
||||
impl HashDescriptor {
|
||||
/// Verify the root hash against the input reader.
|
||||
pub fn verify(&self, reader: impl Read, cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
let algorithm = match self.hash_algorithm.as_str() {
|
||||
"sha256" => &ring::digest::SHA256,
|
||||
"sha512" => &ring::digest::SHA512,
|
||||
a => return Err(Error::UnsupportedHashAlgorithm(a.to_owned())),
|
||||
};
|
||||
|
||||
fn calculate(
|
||||
&self,
|
||||
reader: impl Read,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<ring::digest::Digest> {
|
||||
let algorithm = ring_algorithm(&self.hash_algorithm)?;
|
||||
let mut context = Context::new(algorithm);
|
||||
context.update(&self.salt);
|
||||
|
||||
@@ -701,13 +894,25 @@ impl HashDescriptor {
|
||||
cancel_signal,
|
||||
)?;
|
||||
|
||||
let digest = context.finish();
|
||||
Ok(context.finish())
|
||||
}
|
||||
|
||||
/// Update the root hash from the input reader's contents.
|
||||
pub fn update(&mut self, reader: impl Read, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let digest = self.calculate(reader, cancel_signal)?;
|
||||
self.root_digest = digest.as_ref().to_vec();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verify the root hash against the input reader.
|
||||
pub fn verify(&self, reader: impl Read, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let digest = self.calculate(reader, cancel_signal)?;
|
||||
|
||||
if self.root_digest != digest.as_ref() {
|
||||
return Err(Error::InvalidRootDigest(
|
||||
hex::encode(&self.root_digest),
|
||||
hex::encode(digest),
|
||||
));
|
||||
return Err(Error::InvalidRootDigest {
|
||||
expected: hex::encode(&self.root_digest),
|
||||
actual: hex::encode(digest),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -811,7 +1016,7 @@ impl<W: Write> ToWriter<W> for HashDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
|
||||
pub struct KernelCmdlineDescriptor {
|
||||
pub flags: u32,
|
||||
pub cmdline: String,
|
||||
@@ -858,11 +1063,13 @@ impl<W: Write> ToWriter<W> for KernelCmdlineDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, PartialEq)]
|
||||
#[derive(Clone, Eq, PartialEq, Deserialize, Serialize)]
|
||||
pub struct ChainPartitionDescriptor {
|
||||
pub rollback_index_location: u32,
|
||||
pub partition_name: String,
|
||||
#[serde(with = "hex")]
|
||||
pub public_key: Vec<u8>,
|
||||
#[serde(with = "hex")]
|
||||
pub reserved: [u8; 64],
|
||||
}
|
||||
|
||||
@@ -939,20 +1146,25 @@ impl<W: Write> ToWriter<W> for ChainPartitionDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum Descriptor {
|
||||
Property(PropertyDescriptor),
|
||||
Hashtree(HashtreeDescriptor),
|
||||
HashTree(HashTreeDescriptor),
|
||||
Hash(HashDescriptor),
|
||||
KernelCmdline(KernelCmdlineDescriptor),
|
||||
ChainPartition(ChainPartitionDescriptor),
|
||||
Unknown(u64, Vec<u8>),
|
||||
Unknown {
|
||||
tag: u64,
|
||||
#[serde(with = "hex")]
|
||||
data: Vec<u8>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Descriptor {
|
||||
pub fn partition_name(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::Hashtree(d) => Some(&d.partition_name),
|
||||
Self::HashTree(d) => Some(&d.partition_name),
|
||||
Self::Hash(d) => Some(&d.partition_name),
|
||||
Self::ChainPartition(d) => Some(&d.partition_name),
|
||||
_ => None,
|
||||
@@ -974,9 +1186,9 @@ impl<R: Read> FromReader<R> for Descriptor {
|
||||
let d = PropertyDescriptor::from_reader(&mut inner_reader)?;
|
||||
Self::Property(d)
|
||||
}
|
||||
HashtreeDescriptor::TAG => {
|
||||
let d = HashtreeDescriptor::from_reader(&mut inner_reader)?;
|
||||
Self::Hashtree(d)
|
||||
HashTreeDescriptor::TAG => {
|
||||
let d = HashTreeDescriptor::from_reader(&mut inner_reader)?;
|
||||
Self::HashTree(d)
|
||||
}
|
||||
HashDescriptor::TAG => {
|
||||
let d = HashDescriptor::from_reader(&mut inner_reader)?;
|
||||
@@ -997,7 +1209,7 @@ impl<R: Read> FromReader<R> for Descriptor {
|
||||
let mut data = vec![0u8; nbf];
|
||||
inner_reader.read_exact(&mut data)?;
|
||||
|
||||
Self::Unknown(tag, data)
|
||||
Self::Unknown { tag, data }
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1022,7 +1234,7 @@ impl<W: Write> ToWriter<W> for Descriptor {
|
||||
d.to_writer(&mut inner_writer)?;
|
||||
d.get_tag()
|
||||
}
|
||||
Self::Hashtree(d) => {
|
||||
Self::HashTree(d) => {
|
||||
d.to_writer(&mut inner_writer)?;
|
||||
d.get_tag()
|
||||
}
|
||||
@@ -1038,7 +1250,7 @@ impl<W: Write> ToWriter<W> for Descriptor {
|
||||
d.to_writer(&mut inner_writer)?;
|
||||
d.get_tag()
|
||||
}
|
||||
Self::Unknown(tag, data) => {
|
||||
Self::Unknown { tag, data } => {
|
||||
inner_writer.write_all(data)?;
|
||||
*tag
|
||||
}
|
||||
@@ -1060,20 +1272,61 @@ impl<W: Write> ToWriter<W> for Descriptor {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum AppendedDescriptorRef<'a> {
|
||||
HashTree(&'a HashTreeDescriptor),
|
||||
Hash(&'a HashDescriptor),
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<&'a Descriptor> for AppendedDescriptorRef<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: &'a Descriptor) -> Result<Self> {
|
||||
match value {
|
||||
Descriptor::HashTree(d) => Ok(Self::HashTree(d)),
|
||||
Descriptor::Hash(d) => Ok(Self::Hash(d)),
|
||||
_ => Err(Error::NoAppendedDescriptor),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
pub enum AppendedDescriptorMut<'a> {
|
||||
HashTree(&'a mut HashTreeDescriptor),
|
||||
Hash(&'a mut HashDescriptor),
|
||||
}
|
||||
|
||||
impl<'a> TryFrom<&'a mut Descriptor> for AppendedDescriptorMut<'a> {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(value: &'a mut Descriptor) -> Result<Self> {
|
||||
match value {
|
||||
Descriptor::HashTree(d) => Ok(Self::HashTree(d)),
|
||||
Descriptor::Hash(d) => Ok(Self::Hash(d)),
|
||||
_ => Err(Error::NoAppendedDescriptor),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, PartialEq, Deserialize, Serialize)]
|
||||
pub struct Header {
|
||||
pub required_libavb_version_major: u32,
|
||||
pub required_libavb_version_minor: u32,
|
||||
pub algorithm_type: AlgorithmType,
|
||||
#[serde(with = "hex")]
|
||||
pub hash: Vec<u8>,
|
||||
#[serde(with = "hex")]
|
||||
pub signature: Vec<u8>,
|
||||
#[serde(with = "hex")]
|
||||
pub public_key: Vec<u8>,
|
||||
#[serde(with = "hex")]
|
||||
pub public_key_metadata: Vec<u8>,
|
||||
pub descriptors: Vec<Descriptor>,
|
||||
pub rollback_index: u64,
|
||||
pub flags: u32,
|
||||
pub rollback_index_location: u32,
|
||||
pub release_string: String,
|
||||
#[serde(with = "hex")]
|
||||
pub reserved: [u8; 80],
|
||||
}
|
||||
|
||||
@@ -1199,6 +1452,78 @@ impl Header {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the first hash or hash tree descriptor if there is only one. This is
|
||||
/// the case for appended AVB images.
|
||||
pub fn appended_descriptor(&self) -> Result<AppendedDescriptorRef> {
|
||||
let mut result = None;
|
||||
|
||||
for descriptor in &self.descriptors {
|
||||
match descriptor {
|
||||
Descriptor::HashTree(d) => {
|
||||
if result.is_some() {
|
||||
return Err(Error::NoAppendedDescriptor);
|
||||
}
|
||||
result = Some(AppendedDescriptorRef::HashTree(d));
|
||||
}
|
||||
Descriptor::Hash(d) => {
|
||||
if result.is_some() {
|
||||
return Err(Error::NoAppendedDescriptor);
|
||||
}
|
||||
result = Some(AppendedDescriptorRef::Hash(d));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
result.ok_or(Error::NoAppendedDescriptor)
|
||||
}
|
||||
|
||||
/// Get the first hash or hash tree descriptor if there is only one. This is
|
||||
/// the case for appended AVB images.
|
||||
pub fn appended_descriptor_mut(&mut self) -> Result<AppendedDescriptorMut> {
|
||||
let mut result = None;
|
||||
|
||||
for descriptor in &mut self.descriptors {
|
||||
match descriptor {
|
||||
Descriptor::HashTree(d) => {
|
||||
if result.is_some() {
|
||||
return Err(Error::NoAppendedDescriptor);
|
||||
}
|
||||
result = Some(AppendedDescriptorMut::HashTree(d));
|
||||
}
|
||||
Descriptor::Hash(d) => {
|
||||
if result.is_some() {
|
||||
return Err(Error::NoAppendedDescriptor);
|
||||
}
|
||||
result = Some(AppendedDescriptorMut::Hash(d));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
result.ok_or(Error::NoAppendedDescriptor)
|
||||
}
|
||||
|
||||
pub fn set_algo_for_key(&mut self, key: &RsaPrivateKey) -> Result<()> {
|
||||
let key_raw = encode_public_key(&key.to_public_key())?;
|
||||
|
||||
for algo in [AlgorithmType::Sha256Rsa2048, AlgorithmType::Sha256Rsa4096] {
|
||||
if key_raw.len() == algo.public_key_len() {
|
||||
self.algorithm_type = algo;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::UnsupportedKey(key.size()))
|
||||
}
|
||||
|
||||
pub fn clear_sig(&mut self) {
|
||||
self.hash.clear();
|
||||
self.signature.clear();
|
||||
self.public_key.clear();
|
||||
self.public_key_metadata.clear();
|
||||
}
|
||||
|
||||
pub fn sign(&mut self, key: &RsaPrivateKey) -> Result<()> {
|
||||
let key_raw = encode_public_key(&key.to_public_key())?;
|
||||
|
||||
@@ -1213,11 +1538,10 @@ impl Header {
|
||||
}
|
||||
|
||||
if key_raw.len() != self.algorithm_type.public_key_len() {
|
||||
return Err(Error::IncorrectKeySize(
|
||||
key_raw.len(),
|
||||
self.algorithm_type,
|
||||
self.algorithm_type.public_key_len(),
|
||||
));
|
||||
return Err(Error::IncorrectKeySize {
|
||||
key_size: key_raw.len(),
|
||||
algo: self.algorithm_type,
|
||||
});
|
||||
}
|
||||
|
||||
// The public key and the sizes of the hash and signature are included
|
||||
@@ -1384,7 +1708,7 @@ impl<R: Read> FromReader<R> for Header {
|
||||
.checked_add(hash_size)
|
||||
.map_or(false, |s| s > auth_block.len())
|
||||
{
|
||||
return Err(Error::OutOfBounds("hash_offset", "hash_size"));
|
||||
return Err(Error::IntegerTooLarge("hash_offset + hash_size"));
|
||||
}
|
||||
let hash = &auth_block[hash_offset..hash_offset + hash_size];
|
||||
|
||||
@@ -1392,7 +1716,7 @@ impl<R: Read> FromReader<R> for Header {
|
||||
.checked_add(signature_size)
|
||||
.map_or(false, |s| s > auth_block.len())
|
||||
{
|
||||
return Err(Error::OutOfBounds("signature_offset", "signature_size"));
|
||||
return Err(Error::IntegerTooLarge("signature_offset + signature_size"));
|
||||
}
|
||||
let signature = &auth_block[signature_offset..signature_offset + signature_size];
|
||||
|
||||
@@ -1402,7 +1726,9 @@ impl<R: Read> FromReader<R> for Header {
|
||||
.checked_add(public_key_size)
|
||||
.map_or(false, |s| s > aux_block.len())
|
||||
{
|
||||
return Err(Error::OutOfBounds("public_key_offset", "public_key_size"));
|
||||
return Err(Error::IntegerTooLarge(
|
||||
"public_key_offset + public_key_size",
|
||||
));
|
||||
}
|
||||
let public_key = &aux_block[public_key_offset..public_key_offset + public_key_size];
|
||||
|
||||
@@ -1410,9 +1736,8 @@ impl<R: Read> FromReader<R> for Header {
|
||||
.checked_add(public_key_metadata_size)
|
||||
.map_or(false, |s| s > aux_block.len())
|
||||
{
|
||||
return Err(Error::OutOfBounds(
|
||||
"public_key_metadata_offset",
|
||||
"public_key_metadata_size",
|
||||
return Err(Error::IntegerTooLarge(
|
||||
"public_key_metadata_offset + public_key_metadata_size",
|
||||
));
|
||||
}
|
||||
let public_key_metadata = &aux_block
|
||||
@@ -1456,13 +1781,14 @@ impl<W: Write> ToWriter<W> for Header {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, PartialEq)]
|
||||
#[derive(Clone, Eq, PartialEq, Deserialize, Serialize)]
|
||||
pub struct Footer {
|
||||
pub version_major: u32,
|
||||
pub version_minor: u32,
|
||||
pub original_image_size: u64,
|
||||
pub vbmeta_offset: u64,
|
||||
pub vbmeta_size: u64,
|
||||
#[serde(with = "hex")]
|
||||
pub reserved: [u8; 28],
|
||||
}
|
||||
|
||||
@@ -1585,7 +1911,7 @@ pub fn decode_public_key(data: &[u8]) -> Result<RsaPublicKey> {
|
||||
|
||||
let modulus = BigUint::from_bytes_be(&modulus_raw);
|
||||
let public_key =
|
||||
RsaPublicKey::new(modulus, BigUint::from(65537u32)).map_err(Error::RsaVerifyError)?;
|
||||
RsaPublicKey::new(modulus, BigUint::from(65537u32)).map_err(Error::RsaVerify)?;
|
||||
|
||||
Ok(public_key)
|
||||
}
|
||||
@@ -1600,7 +1926,7 @@ pub fn load_image(mut reader: impl Read + Seek) -> Result<(Header, Option<Footer
|
||||
|
||||
let footer = match Footer::from_reader(&mut reader) {
|
||||
Ok(f) => Some(f),
|
||||
Err(e @ Error::IoError(_)) => return Err(e),
|
||||
Err(e @ Error::Io(_)) => return Err(e),
|
||||
Err(_) => None,
|
||||
};
|
||||
|
||||
@@ -1621,20 +1947,20 @@ pub fn load_image(mut reader: impl Read + Seek) -> Result<(Header, Option<Footer
|
||||
fn write_image_internal(
|
||||
mut writer: impl Write + Seek,
|
||||
header: &Header,
|
||||
footer: Option<&Footer>,
|
||||
footer: Option<&mut Footer>,
|
||||
image_size: Option<u64>,
|
||||
block_size: u64,
|
||||
) -> Result<()> {
|
||||
let original_image_size = writer.seek(SeekFrom::End(0))?;
|
||||
let eof_image_size = writer.seek(SeekFrom::End(0))?;
|
||||
|
||||
// The header must be block-aligned.
|
||||
let vbmeta_offset = if block_size > 0 {
|
||||
let padding_size = padding::write_zeros(&mut writer, block_size)?;
|
||||
original_image_size
|
||||
eof_image_size
|
||||
.checked_add(padding_size)
|
||||
.ok_or_else(|| Error::IntegerTooLarge("vbmeta_offset"))?
|
||||
} else {
|
||||
original_image_size
|
||||
eof_image_size
|
||||
};
|
||||
|
||||
header.to_writer(&mut writer)?;
|
||||
@@ -1660,12 +1986,16 @@ fn write_image_internal(
|
||||
let footer_offset = image_size.unwrap() - Footer::SIZE as u64;
|
||||
writer.seek(SeekFrom::Start(footer_offset))?;
|
||||
|
||||
let mut new_footer = f.clone();
|
||||
new_footer.original_image_size = original_image_size;
|
||||
new_footer.vbmeta_offset = vbmeta_offset;
|
||||
new_footer.vbmeta_size = vbmeta_end - vbmeta_offset;
|
||||
let original_image_size = match header.appended_descriptor()? {
|
||||
AppendedDescriptorRef::HashTree(d) => d.image_size,
|
||||
AppendedDescriptorRef::Hash(d) => d.image_size,
|
||||
};
|
||||
|
||||
new_footer.to_writer(&mut writer)?;
|
||||
f.original_image_size = original_image_size;
|
||||
f.vbmeta_offset = vbmeta_offset;
|
||||
f.vbmeta_size = vbmeta_end - vbmeta_offset;
|
||||
|
||||
f.to_writer(&mut writer)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -1683,7 +2013,7 @@ pub fn write_root_image(writer: impl Write + Seek, header: &Header, block_size:
|
||||
pub fn write_appended_image(
|
||||
writer: impl Write + Seek,
|
||||
header: &Header,
|
||||
footer: &Footer,
|
||||
footer: &mut Footer,
|
||||
image_size: u64,
|
||||
) -> Result<()> {
|
||||
// avbtool hardcodes a 4096 block size for appended non-sparse images.
|
||||
|
||||
@@ -18,7 +18,7 @@ pub enum Error {
|
||||
#[error("Unknown compression format")]
|
||||
UnknownFormat,
|
||||
#[error("I/O error")]
|
||||
IoError(#[from] io::Error),
|
||||
Io(#[from] io::Error),
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
@@ -9,13 +9,14 @@ use std::{
|
||||
io::{self, Read, Write},
|
||||
};
|
||||
|
||||
use bstr::ByteSlice;
|
||||
use num_traits::ToPrimitive;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{
|
||||
format::padding,
|
||||
stream::{CountingReader, CountingWriter, FromReader, ToWriter, WriteZerosExt},
|
||||
util::{EscapedString, NumBytes},
|
||||
util::NumBytes,
|
||||
};
|
||||
|
||||
const MAGIC_NEW: &[u8; 6] = b"070701";
|
||||
@@ -38,12 +39,12 @@ const IO_BLOCK_SIZE: u64 = 512;
|
||||
pub enum Error {
|
||||
#[error("Unknown magic: {0:?}")]
|
||||
UnknownMagic([u8; 6]),
|
||||
#[error("Hard links are not supported: {0}")]
|
||||
HardLinksNotSupported(EscapedString<Vec<u8>>),
|
||||
#[error("Hard links are not supported: {:?}", .0.as_bstr())]
|
||||
HardLinksNotSupported(Vec<u8>),
|
||||
#[error("{0:?} field exceeds integer bounds")]
|
||||
IntegerTooLarge(&'static str),
|
||||
#[error("I/O error")]
|
||||
IoError(#[from] io::Error),
|
||||
Io(#[from] io::Error),
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
@@ -60,7 +61,7 @@ fn read_int(mut reader: impl Read) -> io::Result<u32> {
|
||||
let digit = c.to_digit(16).ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("{0}: Invalid hex char: {1}", EscapedString::new(&buf), c),
|
||||
format!("{:?}: Invalid hex char: {c}", buf.as_bstr()),
|
||||
)
|
||||
})?;
|
||||
|
||||
@@ -120,7 +121,7 @@ impl fmt::Debug for CpioEntryNew {
|
||||
.field("rdev_maj", &self.rdev_maj)
|
||||
.field("rdev_min", &self.rdev_min)
|
||||
.field("chksum", &self.chksum)
|
||||
.field("name", &EscapedString::new(&self.name))
|
||||
.field("name", &self.name.as_bstr())
|
||||
.field("content", &NumBytes(self.content.len()))
|
||||
.finish()
|
||||
}
|
||||
@@ -140,7 +141,7 @@ impl fmt::Display for CpioEntryNew {
|
||||
m => Cow::Owned(format!("unknown ({m:o})")),
|
||||
};
|
||||
|
||||
writeln!(f, "Filename: {}", EscapedString::new(&self.name))?;
|
||||
writeln!(f, "Filename: {:?}", self.name.as_bstr())?;
|
||||
writeln!(f, "Filetype: {file_type_str}")?;
|
||||
writeln!(f, "Inode: {}", self.ino)?;
|
||||
writeln!(f, "Mode: {:o}", self.mode)?;
|
||||
@@ -312,7 +313,7 @@ pub fn load(mut reader: impl Read, include_trailer: bool) -> Result<Vec<CpioEntr
|
||||
loop {
|
||||
let entry = CpioEntryNew::from_reader(&mut reader)?;
|
||||
if file_type(entry.mode) != S_IFDIR && entry.nlink > 1 {
|
||||
return Err(Error::HardLinksNotSupported(EscapedString::new(entry.name)));
|
||||
return Err(Error::HardLinksNotSupported(entry.name));
|
||||
}
|
||||
|
||||
if entry.name == CPIO_TRAILER {
|
||||
|
||||
@@ -0,0 +1,824 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2023 Andrew Gunnerson
|
||||
* SPDX-License-Identifier: GPL-3.0-only
|
||||
*/
|
||||
|
||||
use std::{
|
||||
fmt,
|
||||
io::{self, Cursor, Read, Seek, SeekFrom, Write},
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
|
||||
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
|
||||
use num_traits::ToPrimitive;
|
||||
use rayon::{
|
||||
prelude::{IndexedParallelIterator, ParallelIterator},
|
||||
slice::{ParallelSlice, ParallelSliceMut},
|
||||
};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{
|
||||
format::verityrs,
|
||||
stream::{self, FromReader, ReadSeek, ToWriter, WriteSeek, WriteZerosExt},
|
||||
util::NumBytes,
|
||||
};
|
||||
|
||||
// Not to be confused with the 255-byte RS block size.
|
||||
const FEC_BLOCK_SIZE: usize = 4096;
|
||||
const FEC_HEADER_SIZE: usize = 60;
|
||||
const FEC_MAGIC: u32 = 0xFECFECFE;
|
||||
const FEC_VERSION: u32 = 0;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
#[error("FEC with parity byte count of {0} is not supported")]
|
||||
UnsupportedParity(u8),
|
||||
#[error("Cannot calculate FEC for empty data")]
|
||||
InputEmpty,
|
||||
#[error("Input size ({input}) is not a multiple of FEC block size ({block})")]
|
||||
NotBlockAligned { input: u64, block: u32 },
|
||||
#[error("FEC should have size {expected} for input size {input}, but has size {actual}")]
|
||||
InvalidFecSize {
|
||||
input: u64,
|
||||
expected: usize,
|
||||
actual: usize,
|
||||
},
|
||||
#[error("Cannot repair data due to too many errors")]
|
||||
TooManyErrors,
|
||||
#[error("Input data contains errors")]
|
||||
HasErrors,
|
||||
#[error("Data is too small to contain FEC headers")]
|
||||
DataTooSmall,
|
||||
#[error("The two FEC headers are different")]
|
||||
HeadersDifferent,
|
||||
#[error("Invalid FEC header magic: {0:#x}")]
|
||||
InvalidHeaderMagic(u32),
|
||||
#[error("Unsupported FEC header version: {0}")]
|
||||
UnsupportedHeaderVersion(u32),
|
||||
#[error("Invalid FEC header size: {0}")]
|
||||
InvalidHeaderSize(u32),
|
||||
#[error("FEC size in header {value} does not match available data ({available})")]
|
||||
InvalidHeaderFecSize { value: usize, available: usize },
|
||||
#[error("Expected FEC digest {expected}, but have {actual}")]
|
||||
InvalidFecDigest { expected: String, actual: String },
|
||||
#[error("{0:?} field exceeds integer bounds")]
|
||||
IntegerTooLarge(&'static str),
|
||||
#[error("I/O error")]
|
||||
Io(#[from] io::Error),
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// A small wrapper around a byte array to represent a single Reed-Solomon
|
||||
/// codeword for any `RS(255, K)`.
|
||||
struct Codeword {
|
||||
data: [u8; 255],
|
||||
rs_k: u8,
|
||||
}
|
||||
|
||||
impl Codeword {
|
||||
fn new(rs_k: u8) -> Self {
|
||||
Self {
|
||||
data: [0u8; 255],
|
||||
rs_k,
|
||||
}
|
||||
}
|
||||
|
||||
fn data(&self) -> &[u8] {
|
||||
&self.data[..usize::from(self.rs_k)]
|
||||
}
|
||||
|
||||
fn data_mut(&mut self) -> &mut [u8] {
|
||||
&mut self.data[..usize::from(self.rs_k)]
|
||||
}
|
||||
|
||||
fn parity(&mut self) -> &[u8] {
|
||||
&self.data[usize::from(self.rs_k)..]
|
||||
}
|
||||
|
||||
fn parity_mut(&mut self) -> &mut [u8] {
|
||||
&mut self.data[usize::from(self.rs_k)..]
|
||||
}
|
||||
|
||||
fn all(&self) -> &[u8] {
|
||||
&self.data
|
||||
}
|
||||
|
||||
fn all_mut(&mut self) -> &mut [u8] {
|
||||
&mut self.data
|
||||
}
|
||||
}
|
||||
|
||||
/// Since Rust's built-in .div_ceil() is still nightly-only.
|
||||
fn div_ceil(dividend: u64, divisor: u64) -> u64 {
|
||||
dividend / divisor + u64::from(dividend % divisor != 0)
|
||||
}
|
||||
|
||||
/// A type for performing FEC generation, verification, and error correction for
|
||||
/// a specific file size and Reed Solomon configuration. The implementation uses
|
||||
/// dm-verity's interleaving access pattern.
|
||||
///
|
||||
/// The interleaving access pattern can be visualized by placing the file
|
||||
/// offsets in a two-dimensional grid. For example, when reading a 2072576-byte
|
||||
/// file for calculating RS(255, 253):
|
||||
///
|
||||
/// ```text
|
||||
/// | <-------- Round 0 --------> | <-------- Round 1 --------> |
|
||||
/// |-----------------------------|-----------------------------|
|
||||
/// ^ | 0 1 ... 4095 | 4096 4097 ... 8191 |
|
||||
/// | | 8192 8192 ... 12287 | 12288 12289 ... 16383 |
|
||||
/// rs_k | 16384 16385 ... 20479 | 20480 20481 ... 24575 |
|
||||
/// | | ....... ....... ... ....... | ....... ....... ... ....... |
|
||||
/// v | 2064384 2064385 ... 2068479 | 2068480 2068481 ... 2072575 |
|
||||
/// ```
|
||||
///
|
||||
/// A regular sequential read of the file is traversing the grid row-by-row,
|
||||
/// while an interleaving read is traversing the grid column-by-column. Each
|
||||
/// column is always `rs_k` items tall, so each column forms the data portion of
|
||||
/// an RS codeword. The number of columns is always a multiple of the FEC block
|
||||
/// size. Since RS operates on fixed-size codewords and a file size might not
|
||||
/// always fill the grid completely, out-of-bounds offsets are treated as if
|
||||
/// they contain a `\0` byte.
|
||||
///
|
||||
/// All operations are multithreaded with I/O operations parallelized at the
|
||||
/// "round" level and RS operations parallelized at the column level.
|
||||
pub struct Fec {
|
||||
file_size: u64,
|
||||
block_size: u32,
|
||||
rs_k: u8,
|
||||
rounds: u64,
|
||||
}
|
||||
|
||||
impl Fec {
|
||||
pub fn new(file_size: u64, block_size: u32, parity: u8) -> Result<Self> {
|
||||
if file_size == 0 {
|
||||
return Err(Error::InputEmpty);
|
||||
} else if file_size % u64::from(block_size) != 0 {
|
||||
return Err(Error::NotBlockAligned {
|
||||
input: file_size,
|
||||
block: block_size,
|
||||
});
|
||||
}
|
||||
|
||||
let rs_k = 255 - parity;
|
||||
if !verityrs::FN_ENCODE.contains_key(&rs_k) {
|
||||
return Err(Error::UnsupportedParity(parity));
|
||||
}
|
||||
|
||||
let blocks = div_ceil(file_size, u64::from(block_size));
|
||||
let rounds = div_ceil(blocks, u64::from(rs_k));
|
||||
|
||||
Ok(Self {
|
||||
file_size,
|
||||
block_size,
|
||||
rs_k,
|
||||
rounds,
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the number of parity bytes per codeword.
|
||||
#[inline]
|
||||
fn parity(&self) -> u8 {
|
||||
255 - self.rs_k
|
||||
}
|
||||
|
||||
/// Get the size of the FEC data needed to cover the entire file.
|
||||
#[inline]
|
||||
fn fec_size(&self) -> usize {
|
||||
usize::from(self.parity()) * self.rounds as usize * self.block_size as usize
|
||||
}
|
||||
|
||||
/// Get the backing file offset for the specified `offset` in the
|
||||
/// interleaved view.
|
||||
fn backing_offset(&self, offset: u64) -> u64 {
|
||||
let rs_k = u64::from(self.rs_k);
|
||||
|
||||
offset / rs_k + offset % rs_k * self.rounds * u64::from(self.block_size)
|
||||
}
|
||||
|
||||
/// Read a raw sequential block from the backing file, starting at offset
|
||||
/// `offset` in the interleaved view. This reads a horizontal block-aligned
|
||||
/// slice in the file offset grid.
|
||||
fn read_seq_block(
|
||||
&self,
|
||||
mut reader: impl Read + Seek,
|
||||
offset: u64,
|
||||
buf: &mut [u8],
|
||||
) -> io::Result<()> {
|
||||
assert_eq!(
|
||||
buf.len(),
|
||||
self.block_size as usize,
|
||||
"Buffer does not match block size",
|
||||
);
|
||||
|
||||
let backing_offset = self.backing_offset(offset);
|
||||
|
||||
// Out of bounds offsets are treated as if they contain zeros.
|
||||
if backing_offset >= self.file_size {
|
||||
buf.fill(0);
|
||||
} else {
|
||||
reader.seek(SeekFrom::Start(backing_offset))?;
|
||||
reader.read_exact(buf)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write a raw sequential block to the backing file, starting at offset
|
||||
/// `offset` in the interleaved view. This writes a horizontal block-aligned
|
||||
/// slice in the file offset grid.
|
||||
fn write_seq_block(
|
||||
&self,
|
||||
mut writer: impl Write + Seek,
|
||||
offset: u64,
|
||||
buf: &[u8],
|
||||
) -> io::Result<()> {
|
||||
assert_eq!(
|
||||
buf.len(),
|
||||
self.block_size as usize,
|
||||
"Buffer does not match block size",
|
||||
);
|
||||
|
||||
let backing_offset = self.backing_offset(offset);
|
||||
|
||||
// Out of bounds offsets are ignored.
|
||||
if backing_offset < self.file_size {
|
||||
writer.seek(SeekFrom::Start(backing_offset))?;
|
||||
writer.write_all(buf)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read the nth round from the file. The data is laid out sequentially
|
||||
/// (row-by-row).
|
||||
fn read_round(&self, mut reader: impl Read + Seek, round: u64) -> io::Result<Vec<u8>> {
|
||||
let mut grid = vec![0u8; usize::from(self.rs_k) * self.block_size as usize];
|
||||
|
||||
for row in 0..self.rs_k {
|
||||
let interleaved_offset =
|
||||
round * u64::from(self.rs_k) * u64::from(self.block_size) + u64::from(row);
|
||||
let row_start = usize::from(row) * self.block_size as usize;
|
||||
let row_end = row_start + self.block_size as usize;
|
||||
let row_slice = &mut grid[row_start..row_end];
|
||||
|
||||
self.read_seq_block(&mut reader, interleaved_offset, row_slice)?;
|
||||
}
|
||||
|
||||
Ok(grid)
|
||||
}
|
||||
|
||||
/// Write the nth round to the file. The data is expected to be laid out
|
||||
/// sequentially (row-by-row).
|
||||
fn write_round(
|
||||
&self,
|
||||
mut writer: impl Write + Seek,
|
||||
round: u64,
|
||||
grid: &[u8],
|
||||
) -> io::Result<()> {
|
||||
for row in 0..self.rs_k {
|
||||
let interleaved_offset =
|
||||
round * u64::from(self.rs_k) * u64::from(self.block_size) + u64::from(row);
|
||||
let row_start = usize::from(row) * self.block_size as usize;
|
||||
let row_end = row_start + self.block_size as usize;
|
||||
let row_slice = &grid[row_start..row_end];
|
||||
|
||||
self.write_seq_block(&mut writer, interleaved_offset, row_slice)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the nth RS codeword from a round's grid.
|
||||
fn get_codeword(&self, grid: &[u8], column: usize) -> Codeword {
|
||||
let mut codeword = Codeword::new(self.rs_k);
|
||||
let data = codeword.data_mut();
|
||||
|
||||
for row in 0..usize::from(self.rs_k) {
|
||||
data[row] = grid[row * self.block_size as usize + column];
|
||||
}
|
||||
|
||||
codeword
|
||||
}
|
||||
|
||||
/// Put the nth RS codeword into a round's grid.
|
||||
fn put_codeword(&self, grid: &mut [u8], column: usize, codeword: &Codeword) {
|
||||
let data = codeword.data();
|
||||
|
||||
for row in 0..usize::from(self.rs_k) {
|
||||
grid[row * self.block_size as usize + column] = data[row];
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate FEC data for a single round.
|
||||
fn generate_one_round(
|
||||
&self,
|
||||
reader: impl Read + Seek,
|
||||
round: u64,
|
||||
fec: &mut [u8],
|
||||
) -> Result<()> {
|
||||
assert_eq!(
|
||||
fec.len(),
|
||||
usize::from(self.parity()) * self.block_size as usize,
|
||||
"FEC buffer length does not match block size",
|
||||
);
|
||||
|
||||
let grid = self.read_round(reader, round)?;
|
||||
let encode = verityrs::FN_ENCODE[&self.rs_k];
|
||||
let parity = usize::from(self.parity());
|
||||
|
||||
for (column, buf) in fec.chunks_exact_mut(parity).enumerate() {
|
||||
let mut codeword = self.get_codeword(&grid, column);
|
||||
encode(codeword.all_mut());
|
||||
buf.copy_from_slice(codeword.parity());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verify file data for a single round.
|
||||
fn verify_one_round(&self, reader: impl Read + Seek, round: u64, fec: &[u8]) -> Result<()> {
|
||||
assert_eq!(
|
||||
fec.len(),
|
||||
usize::from(self.parity()) * self.block_size as usize,
|
||||
"FEC buffer length does not match block size",
|
||||
);
|
||||
|
||||
let grid = self.read_round(reader, round)?;
|
||||
let is_correct = verityrs::FN_IS_CORRECT[&self.rs_k];
|
||||
let parity = usize::from(self.parity());
|
||||
|
||||
for (column, buf) in fec.chunks_exact(parity).enumerate() {
|
||||
let mut codeword = self.get_codeword(&grid, column);
|
||||
codeword.parity_mut().copy_from_slice(buf);
|
||||
|
||||
if !is_correct(codeword.all()) {
|
||||
return Err(Error::HasErrors);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Repair file data for a single round.
|
||||
fn repair_one_round(
|
||||
&self,
|
||||
reader: impl Read + Seek,
|
||||
writer: impl Write + Seek,
|
||||
round: u64,
|
||||
fec: &[u8],
|
||||
) -> Result<u64> {
|
||||
assert_eq!(
|
||||
fec.len(),
|
||||
usize::from(self.parity()) * self.block_size as usize,
|
||||
"FEC buffer length does not match block size",
|
||||
);
|
||||
|
||||
let mut grid = self.read_round(reader, round)?;
|
||||
let correct_errors = verityrs::FN_CORRECT_ERRORS[&self.rs_k];
|
||||
let parity = usize::from(self.parity());
|
||||
let mut num_corrected = 0;
|
||||
|
||||
for (column, buf) in fec.chunks_exact(parity).enumerate() {
|
||||
let mut codeword = self.get_codeword(&grid, column);
|
||||
codeword.parity_mut().copy_from_slice(buf);
|
||||
|
||||
let n = correct_errors(codeword.all_mut()).ok_or(Error::TooManyErrors)?;
|
||||
if n > 0 {
|
||||
self.put_codeword(&mut grid, column, &codeword);
|
||||
}
|
||||
|
||||
num_corrected += n as u64;
|
||||
}
|
||||
|
||||
if num_corrected > 0 {
|
||||
self.write_round(writer, round, &grid)?;
|
||||
}
|
||||
|
||||
Ok(num_corrected)
|
||||
}
|
||||
|
||||
/// Generate FEC data for the file. The file size must match the file size
|
||||
/// given to [`Self::new()`].
|
||||
///
|
||||
/// This function is multithreaded and uses rayon's global thread pool.
|
||||
pub fn generate(
|
||||
&self,
|
||||
open_input: impl Fn() -> io::Result<Box<dyn ReadSeek>> + Sync,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<Vec<u8>> {
|
||||
let fec_size = self.fec_size();
|
||||
let mut fec = vec![0u8; fec_size];
|
||||
|
||||
fec.par_chunks_exact_mut(fec_size / self.rounds as usize)
|
||||
.enumerate()
|
||||
.map(|(round, buf)| -> Result<()> {
|
||||
stream::check_cancel(cancel_signal)?;
|
||||
|
||||
let reader = open_input()?;
|
||||
self.generate_one_round(reader, round as u64, buf)
|
||||
})
|
||||
.collect::<Result<()>>()?;
|
||||
|
||||
Ok(fec)
|
||||
}
|
||||
|
||||
/// Verify that the file contains no errors. This is significantly faster
|
||||
/// than [`Self::repair()`] if only error detection, not correction, is
|
||||
/// needed.
|
||||
///
|
||||
/// This function is multithreaded and uses rayon's global thread pool.
|
||||
pub fn verify(
|
||||
&self,
|
||||
open_input: impl Fn() -> io::Result<Box<dyn ReadSeek>> + Sync,
|
||||
fec: &[u8],
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let fec_size = self.fec_size();
|
||||
if fec.len() != fec_size {
|
||||
return Err(Error::InvalidFecSize {
|
||||
input: self.file_size,
|
||||
expected: fec_size,
|
||||
actual: fec.len(),
|
||||
});
|
||||
}
|
||||
|
||||
fec.par_chunks_exact(fec_size / self.rounds as usize)
|
||||
.enumerate()
|
||||
.map(|(round, buf)| -> Result<()> {
|
||||
stream::check_cancel(cancel_signal)?;
|
||||
|
||||
let reader = open_input()?;
|
||||
self.verify_one_round(reader, round as u64, buf)
|
||||
})
|
||||
.collect::<Result<()>>()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Repair the file. Up to `parity / 2` bytes per codeword can be repaired.
|
||||
/// If the file is successfully repaired, the number of repaired bytes is
|
||||
/// returned. If the file is corrupt beyond repair, [`Error::TooManyErrors`]
|
||||
/// is returned. It's not safe to assume that as much data as possible has
|
||||
/// been repaired when [`Error::TooManyErrors`] is returned due to fail-fast
|
||||
/// behavior.
|
||||
///
|
||||
/// This function corrects errors at unknown locations only. Correcting
|
||||
/// erasures at known locations is not supported.
|
||||
///
|
||||
/// This function is multithreaded and uses rayon's global thread pool.
|
||||
pub fn repair(
|
||||
&self,
|
||||
open_input: impl Fn() -> io::Result<Box<dyn ReadSeek>> + Sync,
|
||||
open_output: impl Fn() -> io::Result<Box<dyn WriteSeek>> + Sync,
|
||||
fec: &[u8],
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<u64> {
|
||||
let fec_size = self.fec_size();
|
||||
if fec.len() != fec_size {
|
||||
return Err(Error::InvalidFecSize {
|
||||
input: self.file_size,
|
||||
expected: fec_size,
|
||||
actual: fec.len(),
|
||||
});
|
||||
}
|
||||
|
||||
let num_corrected = fec
|
||||
.par_chunks_exact(fec_size / self.rounds as usize)
|
||||
.enumerate()
|
||||
.map(|(round, buf)| -> Result<u64> {
|
||||
stream::check_cancel(cancel_signal)?;
|
||||
|
||||
let reader = open_input()?;
|
||||
let writer = open_output()?;
|
||||
self.repair_one_round(reader, writer, round as u64, buf)
|
||||
})
|
||||
.collect::<Result<Vec<u64>>>()?
|
||||
.into_iter()
|
||||
.sum();
|
||||
|
||||
Ok(num_corrected)
|
||||
}
|
||||
}
|
||||
|
||||
/// A type for reading and writing AOSP's standalone FEC image format.
|
||||
///
|
||||
/// The FEC data parser in this implementation is strict. All header fields,
|
||||
/// like the version, header size, and digest, must be valid and both copies of
|
||||
/// the header must match.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct FecImage {
|
||||
pub fec: Vec<u8>,
|
||||
pub data_size: u64,
|
||||
pub parity: u8,
|
||||
}
|
||||
|
||||
impl fmt::Debug for FecImage {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Fec")
|
||||
.field("fec", &NumBytes(self.fec.len()))
|
||||
.field("data_size", &self.data_size)
|
||||
.field("parity", &self.parity)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl FecImage {
|
||||
/// Generate FEC data for a file. `parity` is the number of parity bytes per
|
||||
/// 255-byte Reed-Solomon codeword.
|
||||
pub fn generate(
|
||||
open_input: impl Fn() -> io::Result<Box<dyn ReadSeek>> + Sync,
|
||||
parity: u8,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<Self> {
|
||||
let data_size = {
|
||||
let mut file = open_input()?;
|
||||
file.seek(SeekFrom::End(0))?
|
||||
};
|
||||
let fec = Fec::new(data_size, FEC_BLOCK_SIZE as u32, parity)?;
|
||||
let fec_data = fec.generate(open_input, cancel_signal)?;
|
||||
|
||||
Ok(Self {
|
||||
fec: fec_data,
|
||||
data_size,
|
||||
parity,
|
||||
})
|
||||
}
|
||||
|
||||
/// Check that a file contains no errors. This is significantly faster than
|
||||
/// [`Self::repair()`] if performing a repair is not necessary.
|
||||
pub fn verify(
|
||||
&self,
|
||||
open_input: impl Fn() -> io::Result<Box<dyn ReadSeek>> + Sync,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let fec = Fec::new(self.data_size, FEC_BLOCK_SIZE as u32, self.parity)?;
|
||||
fec.verify(open_input, &self.fec, cancel_signal)
|
||||
}
|
||||
|
||||
/// Repair a file using this instance's FEC data. The maximum correctable
|
||||
/// errors per 255-byte codeword is half of [`Self::parity`]. Returns the
|
||||
/// number of bytes corrected if the file is successfully repaired or
|
||||
/// [`Error::TooManyErrors`] if the file cannot be repaired. This function
|
||||
/// fails fast. If an RS codeword cannot be repaired, other potentially
|
||||
/// repairable codewords may not be repaired.
|
||||
///
|
||||
/// Note that if there are too many errors inside a certain codeword, it's
|
||||
/// possible for there to be a false positive where the corrupted codeword
|
||||
/// is "corrected" into an incorrect value. FEC error detection is not a
|
||||
/// replacement for cryptographically secure digests.
|
||||
///
|
||||
/// The inputs and outputs should point to the same underlying file because
|
||||
/// only regions where errors are corrected are written. It is guaranteed
|
||||
/// that multiple threads will always read and write disjoint file offsets.
|
||||
pub fn repair(
|
||||
&self,
|
||||
open_input: impl Fn() -> io::Result<Box<dyn ReadSeek>> + Sync,
|
||||
open_output: impl Fn() -> io::Result<Box<dyn WriteSeek>> + Sync,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<u64> {
|
||||
let fec = Fec::new(self.data_size, FEC_BLOCK_SIZE as u32, self.parity)?;
|
||||
fec.repair(open_input, open_output, &self.fec, cancel_signal)
|
||||
}
|
||||
|
||||
/// Build one instance of the FEC header. The caller is responsible for
|
||||
/// writing it to both of the header locations at the end of the file.
|
||||
fn build_header(&self) -> Result<[u8; FEC_HEADER_SIZE]> {
|
||||
let fec_size = self
|
||||
.fec
|
||||
.len()
|
||||
.to_u32()
|
||||
.ok_or_else(|| Error::IntegerTooLarge("fec_size"))?;
|
||||
|
||||
let mut writer = Cursor::new([0u8; FEC_HEADER_SIZE]);
|
||||
|
||||
let digest = ring::digest::digest(&ring::digest::SHA256, &self.fec);
|
||||
|
||||
writer.write_u32::<LittleEndian>(FEC_MAGIC)?;
|
||||
writer.write_u32::<LittleEndian>(FEC_VERSION)?;
|
||||
writer.write_u32::<LittleEndian>(FEC_HEADER_SIZE as u32)?;
|
||||
writer.write_u32::<LittleEndian>(self.parity.into())?;
|
||||
writer.write_u32::<LittleEndian>(fec_size)?;
|
||||
writer.write_u64::<LittleEndian>(self.data_size)?;
|
||||
writer.write_all(digest.as_ref())?;
|
||||
|
||||
Ok(writer.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: Read> FromReader<R> for FecImage {
|
||||
type Error = Error;
|
||||
|
||||
fn from_reader(mut reader: R) -> Result<Self> {
|
||||
// Avoid requiring seekable readers since we need to read everything
|
||||
// into memory anyway.
|
||||
let mut fec = Vec::new();
|
||||
reader.read_to_end(&mut fec)?;
|
||||
|
||||
if fec.len() < FEC_BLOCK_SIZE {
|
||||
return Err(Error::DataTooSmall);
|
||||
}
|
||||
|
||||
// Make sure both headers match.
|
||||
let header1_offset = fec.len() - FEC_BLOCK_SIZE;
|
||||
let header2_offset = fec.len() - FEC_HEADER_SIZE;
|
||||
let header1_raw = &fec[header1_offset..header1_offset + FEC_HEADER_SIZE];
|
||||
let header2_raw = &fec[header2_offset..header2_offset + FEC_HEADER_SIZE];
|
||||
|
||||
if header1_raw != header2_raw {
|
||||
return Err(Error::HeadersDifferent);
|
||||
}
|
||||
|
||||
let mut header_reader = Cursor::new(header1_raw);
|
||||
|
||||
let magic = header_reader.read_u32::<LittleEndian>()?;
|
||||
if magic != FEC_MAGIC {
|
||||
return Err(Error::InvalidHeaderMagic(magic));
|
||||
}
|
||||
|
||||
let version = header_reader.read_u32::<LittleEndian>()?;
|
||||
if version != FEC_VERSION {
|
||||
return Err(Error::UnsupportedHeaderVersion(version));
|
||||
}
|
||||
|
||||
let header_size = header_reader.read_u32::<LittleEndian>()?;
|
||||
if header_size != FEC_HEADER_SIZE as u32 {
|
||||
return Err(Error::InvalidHeaderSize(header_size));
|
||||
}
|
||||
|
||||
let parity = header_reader
|
||||
.read_u32::<LittleEndian>()?
|
||||
.to_u8()
|
||||
.ok_or_else(|| Error::IntegerTooLarge("parity"))?;
|
||||
|
||||
let fec_size = header_reader
|
||||
.read_u32::<LittleEndian>()?
|
||||
.to_usize()
|
||||
.ok_or_else(|| Error::IntegerTooLarge("fec_size"))?;
|
||||
let actual_fec_size = fec.len() - FEC_BLOCK_SIZE;
|
||||
if fec_size != actual_fec_size {
|
||||
return Err(Error::InvalidHeaderFecSize {
|
||||
value: fec_size,
|
||||
available: actual_fec_size,
|
||||
});
|
||||
}
|
||||
|
||||
let input_size = header_reader.read_u64::<LittleEndian>()?;
|
||||
|
||||
let mut digest = [0u8; 32];
|
||||
header_reader.read_exact(&mut digest)?;
|
||||
|
||||
// Chop off headers.
|
||||
fec.resize(fec_size, 0);
|
||||
|
||||
let actual_digest = ring::digest::digest(&ring::digest::SHA256, &fec);
|
||||
if digest != actual_digest.as_ref() {
|
||||
return Err(Error::InvalidFecDigest {
|
||||
expected: hex::encode(digest),
|
||||
actual: hex::encode(actual_digest),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
fec,
|
||||
data_size: input_size,
|
||||
parity,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write> ToWriter<W> for FecImage {
|
||||
type Error = Error;
|
||||
|
||||
fn to_writer(&self, mut writer: W) -> Result<()> {
|
||||
let header = self.build_header()?;
|
||||
|
||||
writer.write_all(&self.fec)?;
|
||||
writer.write_all(&header)?;
|
||||
writer.write_zeros_exact((FEC_BLOCK_SIZE - 2 * FEC_HEADER_SIZE) as u64)?;
|
||||
writer.write_all(&header)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
io::Seek,
|
||||
sync::{atomic::AtomicBool, Arc},
|
||||
};
|
||||
|
||||
use assert_matches::assert_matches;
|
||||
use rand::RngCore;
|
||||
|
||||
use crate::stream::SharedCursor;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn corrupt_byte(file: &mut SharedCursor, offset: u64) {
|
||||
let mut buf = [0u8; 1];
|
||||
|
||||
file.seek(SeekFrom::Start(offset)).unwrap();
|
||||
file.read_exact(&mut buf).unwrap();
|
||||
|
||||
buf[0] = buf[0].wrapping_add(1);
|
||||
|
||||
file.seek(SeekFrom::Start(offset)).unwrap();
|
||||
file.write_all(&buf).unwrap();
|
||||
}
|
||||
|
||||
fn run_test(block_size: u32, rs_k: u8) {
|
||||
let cancel_signal = Arc::new(AtomicBool::new(false));
|
||||
let parity = 255 - rs_k;
|
||||
|
||||
// Generate data big enough to span multiple rounds, but don't fill the
|
||||
// offset grid to ensure that the out-of-bounds-is-0 behavior works.
|
||||
let size = usize::from(rs_k) * block_size as usize * 3 - block_size as usize;
|
||||
let mut file = SharedCursor::default();
|
||||
let orig_digest = {
|
||||
let mut buf = vec![0u8; size];
|
||||
rand::thread_rng().fill_bytes(&mut buf);
|
||||
file.write_all(&buf).unwrap();
|
||||
ring::digest::digest(&ring::digest::SHA256, &buf)
|
||||
};
|
||||
|
||||
let fec = Fec::new(size as u64, block_size, parity).unwrap();
|
||||
assert_eq!(fec.rounds, 3);
|
||||
|
||||
let num_codewords = fec.rounds as usize * block_size as usize;
|
||||
|
||||
// Generate FEC data.
|
||||
let fec_data = fec
|
||||
.generate(|| Ok(Box::new(file.reopen())), &cancel_signal)
|
||||
.unwrap();
|
||||
|
||||
// Verify that there are no errors.
|
||||
fec.verify(|| Ok(Box::new(file.reopen())), &fec_data, &cancel_signal)
|
||||
.unwrap();
|
||||
|
||||
// Verify that errors are detected.
|
||||
corrupt_byte(&mut file, 0);
|
||||
assert_matches!(
|
||||
fec.verify(|| Ok(Box::new(file.reopen())), &fec_data, &cancel_signal,),
|
||||
Err(Error::HasErrors)
|
||||
);
|
||||
|
||||
// Corrupt one byte in every single codeword.
|
||||
for offset in 1..num_codewords {
|
||||
corrupt_byte(&mut file, offset as u64);
|
||||
}
|
||||
|
||||
// Verify that all the single-byte errors can be fixed.
|
||||
fec.repair(
|
||||
|| Ok(Box::new(file.reopen())),
|
||||
|| Ok(Box::new(file.reopen())),
|
||||
&fec_data,
|
||||
&cancel_signal,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let repaired_digest = {
|
||||
let mut buf = Vec::new();
|
||||
file.rewind().unwrap();
|
||||
file.read_to_end(&mut buf).unwrap();
|
||||
ring::digest::digest(&ring::digest::SHA256, &buf)
|
||||
};
|
||||
assert_eq!(repaired_digest.as_ref(), orig_digest.as_ref());
|
||||
|
||||
// We don't test for Error::TooManyErrors because of the chance of false
|
||||
// positives due to the nature of RS.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generate_verify_repair() {
|
||||
for block_size in [1, 2, 4, 8, 16, 32, 64] {
|
||||
for rs_k in verityrs::FN_ENCODE.keys() {
|
||||
println!("Testing block_size={block_size}, rs_k={rs_k}");
|
||||
run_test(block_size, *rs_k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_image() {
|
||||
let cancel_signal = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let mut file = SharedCursor::default();
|
||||
{
|
||||
let mut buf = [0u8; FEC_BLOCK_SIZE];
|
||||
rand::thread_rng().fill_bytes(&mut buf);
|
||||
file.write_all(&buf).unwrap();
|
||||
}
|
||||
|
||||
let image = FecImage::generate(|| Ok(Box::new(file.reopen())), 2, &cancel_signal).unwrap();
|
||||
|
||||
let mut fec_file = Cursor::new(Vec::new());
|
||||
image.to_writer(&mut fec_file).unwrap();
|
||||
|
||||
fec_file.rewind().unwrap();
|
||||
let new_image = FecImage::from_reader(&mut fec_file).unwrap();
|
||||
|
||||
assert_eq!(image, new_image);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ pub mod avb;
|
||||
pub mod bootimage;
|
||||
pub mod compression;
|
||||
pub mod cpio;
|
||||
pub mod fec;
|
||||
pub mod ota;
|
||||
pub mod padding;
|
||||
pub mod payload;
|
||||
pub mod verityrs;
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::{
|
||||
collections::BTreeMap,
|
||||
io::{self, Cursor, Read, Seek, SeekFrom, Write},
|
||||
iter,
|
||||
sync::{atomic::AtomicBool, Arc},
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
|
||||
use cms::signed_data::SignedData;
|
||||
@@ -64,8 +64,8 @@ pub enum Error {
|
||||
UnsupportedDigestAlgorithm(ObjectIdentifier),
|
||||
#[error("Unsupported signature algorithm: {0}")]
|
||||
UnsupportedSignatureAlgorithm(ObjectIdentifier),
|
||||
#[error("Expected entry offsets {0:?}, but have {1:?}")]
|
||||
MismatchedPropertyFiles(String, String),
|
||||
#[error("Expected entry offsets {expected:?}, but have {actual:?}")]
|
||||
MismatchedPropertyFiles { expected: String, actual: String },
|
||||
#[error("Property files {0:?} exceed {1} byte reserved space")]
|
||||
InsufficientReservedSpace(String, usize),
|
||||
#[error("Invalid property file entry: {0:?}")]
|
||||
@@ -389,7 +389,10 @@ pub fn verify_metadata(
|
||||
for (key, value) in &metadata.property_files {
|
||||
let new_value = compute_property_files(key, &zip_entries, Some(value.len()))?;
|
||||
if *value != new_value {
|
||||
return Err(Error::MismatchedPropertyFiles(value.clone(), new_value));
|
||||
return Err(Error::MismatchedPropertyFiles {
|
||||
expected: value.clone(),
|
||||
actual: new_value,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -452,10 +455,7 @@ fn parse_ota_sig(mut reader: impl Read + Seek) -> Result<(SignedData, u64)> {
|
||||
/// 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: &Arc<AtomicBool>,
|
||||
) -> Result<Certificate> {
|
||||
pub fn verify_ota(mut reader: impl Read + Seek, cancel_signal: &AtomicBool) -> Result<Certificate> {
|
||||
let (sd, hashed_size) = parse_ota_sig(&mut reader)?;
|
||||
|
||||
// Make sure the certificate in the CMS structure matches the otacert zip
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
io::{self, Cursor, Read, Seek, SeekFrom, Write},
|
||||
sync::{atomic::AtomicBool, Arc},
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
@@ -51,22 +51,33 @@ pub enum Error {
|
||||
UnsupportedVersion(u64),
|
||||
#[error("Payload contains no signatures")]
|
||||
NoSignatures,
|
||||
#[error("Blob offset should be {0}, but is {1}")]
|
||||
InvalidBlobOffset(u64, u64),
|
||||
#[error("Payload signatures offset should be {0}, but is {1}")]
|
||||
InvalidPayloadSignaturesOffset(u64, u64),
|
||||
#[error("Blob offset should be {expected}, but is {actual}")]
|
||||
InvalidBlobOffset { expected: u64, actual: u64 },
|
||||
#[error("Payload signatures offset should be {expected}, but is {actual}")]
|
||||
InvalidPayloadSignaturesOffset { expected: u64, actual: u64 },
|
||||
#[error("Invalid payload properties line: {0:?}")]
|
||||
InvalidPropertiesLine(String),
|
||||
#[error("Duplicate payload property: {0:?}")]
|
||||
DuplicateProperty(String),
|
||||
#[error("Payload property {0:?} ({1:?}) does not match expected value {2:?}")]
|
||||
InvalidProperty(String, String, Option<String>),
|
||||
#[error("Payload property {key:?} ({actual:?}) does not match expected value {expected:?}")]
|
||||
InvalidProperty {
|
||||
key: String,
|
||||
expected: Option<String>,
|
||||
actual: String,
|
||||
},
|
||||
#[error("Unsupported partition operation: {0:?}")]
|
||||
UnsupportedOperation(mod_InstallOperation::Type),
|
||||
#[error("Expected sha256 {0:?}, but have {1:?}")]
|
||||
MismatchedDigest(Option<String>, String),
|
||||
#[error("Size of {0} ({1}) is not aligned to the block size ({2})")]
|
||||
InvalidPartitionSize(String, u64, u32),
|
||||
#[error("Expected sha256 {expected:?}, but have {actual:?}")]
|
||||
MismatchedDigest {
|
||||
expected: Option<String>,
|
||||
actual: String,
|
||||
},
|
||||
#[error("Size of {name} ({size}) is not aligned to the block size ({block_size})")]
|
||||
InvalidPartitionSize {
|
||||
name: String,
|
||||
size: u64,
|
||||
block_size: u32,
|
||||
},
|
||||
#[error("Partition not found in payload: {0}")]
|
||||
MissingPartition(String),
|
||||
#[error("Partitions not found in payload: {0:?}")]
|
||||
@@ -553,11 +564,11 @@ impl<W: Write> CompressedPartitionWriter<W> {
|
||||
/// size, hash, and install operation metadata.
|
||||
pub fn finish(mut self, partition: &mut PartitionUpdate) -> Result<W> {
|
||||
if self.written % u64::from(self.block_size) != 0 {
|
||||
return Err(Error::InvalidPartitionSize(
|
||||
partition.partition_name.clone(),
|
||||
self.written,
|
||||
self.block_size,
|
||||
));
|
||||
return Err(Error::InvalidPartitionSize {
|
||||
name: partition.partition_name.clone(),
|
||||
size: self.written,
|
||||
block_size: self.block_size,
|
||||
});
|
||||
}
|
||||
|
||||
self.inner.flush()?;
|
||||
@@ -619,7 +630,7 @@ pub fn verify_payload(
|
||||
mut reader: impl Read + Seek,
|
||||
cert: &Certificate,
|
||||
properties_raw: &str,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let header = PayloadHeader::from_reader(&mut reader)?;
|
||||
reader.rewind()?;
|
||||
@@ -675,7 +686,10 @@ pub fn verify_payload(
|
||||
{
|
||||
let actual = reader.stream_position()?;
|
||||
if header.blob_offset != actual {
|
||||
return Err(Error::InvalidBlobOffset(header.blob_offset, actual));
|
||||
return Err(Error::InvalidBlobOffset {
|
||||
expected: header.blob_offset,
|
||||
actual,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -697,7 +711,7 @@ pub fn verify_payload(
|
||||
let expected = header.blob_offset + payload_signatures_offset;
|
||||
let actual = reader.stream_position()?;
|
||||
if expected != actual {
|
||||
return Err(Error::InvalidPayloadSignaturesOffset(expected, actual));
|
||||
return Err(Error::InvalidPayloadSignaturesOffset { expected, actual });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -735,11 +749,11 @@ pub fn verify_payload(
|
||||
let expected_value = expected_properties.get(&key);
|
||||
|
||||
if expected_value != Some(&actual_value) {
|
||||
return Err(Error::InvalidProperty(
|
||||
return Err(Error::InvalidProperty {
|
||||
key,
|
||||
actual_value,
|
||||
expected_value.cloned(),
|
||||
));
|
||||
expected: expected_value.cloned(),
|
||||
actual: actual_value,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -753,7 +767,7 @@ pub fn apply_operation(
|
||||
block_size: u32,
|
||||
blob_offset: u64,
|
||||
op: &InstallOperation,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
for extent in &op.dst_extents {
|
||||
let start_block = extent
|
||||
@@ -842,10 +856,10 @@ pub fn apply_operation(
|
||||
if expected_digest != Some(digest.as_ref())
|
||||
&& op.type_pb != mod_InstallOperation::Type::ZERO
|
||||
{
|
||||
return Err(Error::MismatchedDigest(
|
||||
expected_digest.map(hex::encode),
|
||||
hex::encode(digest.as_ref()),
|
||||
));
|
||||
return Err(Error::MismatchedDigest {
|
||||
expected: expected_digest.map(hex::encode),
|
||||
actual: hex::encode(digest.as_ref()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -859,7 +873,7 @@ pub fn extract_image_to_memory(
|
||||
open_payload: impl Fn() -> io::Result<Box<dyn ReadSeek>> + Sync,
|
||||
header: &PayloadHeader,
|
||||
partition_name: &str,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<SharedCursor> {
|
||||
let partition = header
|
||||
.manifest
|
||||
@@ -874,7 +888,7 @@ pub fn extract_image_to_memory(
|
||||
.par_iter()
|
||||
.map(|op| -> Result<()> {
|
||||
let reader = open_payload()?;
|
||||
let writer = stream.clone();
|
||||
let writer = stream.reopen();
|
||||
|
||||
apply_operation(
|
||||
reader,
|
||||
@@ -900,7 +914,7 @@ pub fn extract_images<'a>(
|
||||
open_output: impl Fn(&str) -> io::Result<Box<dyn WriteSeek>> + Sync,
|
||||
header: &PayloadHeader,
|
||||
partition_names: impl IntoIterator<Item = &'a str>,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let mut remaining = partition_names.into_iter().collect::<HashSet<_>>();
|
||||
// We parallelize at the operation level or else one thread might get stuck
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2023 Andrew Gunnerson
|
||||
* SPDX-License-Identifier: GPL-3.0-only
|
||||
*/
|
||||
|
||||
// The gf256 library uses compile-time proc macro code generation. Since
|
||||
// dm-verity supports RS(255, 231) through RS(255, 253), we'll generate RS
|
||||
// implementations for every supported configuration.
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use gf256::rs::rs;
|
||||
use phf::phf_map;
|
||||
|
||||
#[rs(block = 255, data = 231)]
|
||||
mod rs255w231 {}
|
||||
#[rs(block = 255, data = 232)]
|
||||
mod rs255w232 {}
|
||||
#[rs(block = 255, data = 233)]
|
||||
mod rs255w233 {}
|
||||
#[rs(block = 255, data = 234)]
|
||||
mod rs255w234 {}
|
||||
#[rs(block = 255, data = 235)]
|
||||
mod rs255w235 {}
|
||||
#[rs(block = 255, data = 236)]
|
||||
mod rs255w236 {}
|
||||
#[rs(block = 255, data = 237)]
|
||||
mod rs255w237 {}
|
||||
#[rs(block = 255, data = 238)]
|
||||
mod rs255w238 {}
|
||||
#[rs(block = 255, data = 239)]
|
||||
mod rs255w239 {}
|
||||
#[rs(block = 255, data = 240)]
|
||||
mod rs255w240 {}
|
||||
#[rs(block = 255, data = 241)]
|
||||
mod rs255w241 {}
|
||||
#[rs(block = 255, data = 242)]
|
||||
mod rs255w242 {}
|
||||
#[rs(block = 255, data = 243)]
|
||||
mod rs255w243 {}
|
||||
#[rs(block = 255, data = 244)]
|
||||
mod rs255w244 {}
|
||||
#[rs(block = 255, data = 245)]
|
||||
mod rs255w245 {}
|
||||
#[rs(block = 255, data = 246)]
|
||||
mod rs255w246 {}
|
||||
#[rs(block = 255, data = 247)]
|
||||
mod rs255w247 {}
|
||||
#[rs(block = 255, data = 248)]
|
||||
mod rs255w248 {}
|
||||
#[rs(block = 255, data = 249)]
|
||||
mod rs255w249 {}
|
||||
#[rs(block = 255, data = 250)]
|
||||
mod rs255w250 {}
|
||||
#[rs(block = 255, data = 251)]
|
||||
mod rs255w251 {}
|
||||
#[rs(block = 255, data = 252)]
|
||||
mod rs255w252 {}
|
||||
#[rs(block = 255, data = 253)]
|
||||
mod rs255w253 {}
|
||||
|
||||
pub static FN_ENCODE: phf::Map<u8, fn(&mut [u8])> = phf_map! {
|
||||
231u8 => rs255w231::encode,
|
||||
232u8 => rs255w232::encode,
|
||||
233u8 => rs255w233::encode,
|
||||
234u8 => rs255w234::encode,
|
||||
235u8 => rs255w235::encode,
|
||||
236u8 => rs255w236::encode,
|
||||
237u8 => rs255w237::encode,
|
||||
238u8 => rs255w238::encode,
|
||||
239u8 => rs255w239::encode,
|
||||
240u8 => rs255w240::encode,
|
||||
241u8 => rs255w241::encode,
|
||||
242u8 => rs255w242::encode,
|
||||
243u8 => rs255w243::encode,
|
||||
244u8 => rs255w244::encode,
|
||||
245u8 => rs255w245::encode,
|
||||
246u8 => rs255w246::encode,
|
||||
247u8 => rs255w247::encode,
|
||||
248u8 => rs255w248::encode,
|
||||
249u8 => rs255w249::encode,
|
||||
250u8 => rs255w250::encode,
|
||||
251u8 => rs255w251::encode,
|
||||
252u8 => rs255w252::encode,
|
||||
253u8 => rs255w253::encode,
|
||||
};
|
||||
|
||||
pub static FN_IS_CORRECT: phf::Map<u8, fn(&[u8]) -> bool> = phf_map! {
|
||||
231u8 => rs255w231::is_correct,
|
||||
232u8 => rs255w232::is_correct,
|
||||
233u8 => rs255w233::is_correct,
|
||||
234u8 => rs255w234::is_correct,
|
||||
235u8 => rs255w235::is_correct,
|
||||
236u8 => rs255w236::is_correct,
|
||||
237u8 => rs255w237::is_correct,
|
||||
238u8 => rs255w238::is_correct,
|
||||
239u8 => rs255w239::is_correct,
|
||||
240u8 => rs255w240::is_correct,
|
||||
241u8 => rs255w241::is_correct,
|
||||
242u8 => rs255w242::is_correct,
|
||||
243u8 => rs255w243::is_correct,
|
||||
244u8 => rs255w244::is_correct,
|
||||
245u8 => rs255w245::is_correct,
|
||||
246u8 => rs255w246::is_correct,
|
||||
247u8 => rs255w247::is_correct,
|
||||
248u8 => rs255w248::is_correct,
|
||||
249u8 => rs255w249::is_correct,
|
||||
250u8 => rs255w250::is_correct,
|
||||
251u8 => rs255w251::is_correct,
|
||||
252u8 => rs255w252::is_correct,
|
||||
253u8 => rs255w253::is_correct,
|
||||
};
|
||||
|
||||
// Each one of these has its own error type, but the functions can only fail one
|
||||
// way (too many corrupt bytes), so just throw away the error and return an
|
||||
// Option instead.
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub static FN_CORRECT_ERRORS: phf::Map<u8, fn(&mut [u8]) -> Option<usize>> = phf_map! {
|
||||
231u8 => |data: &mut [u8]| rs255w231::correct_errors(data).ok(),
|
||||
232u8 => |data: &mut [u8]| rs255w232::correct_errors(data).ok(),
|
||||
233u8 => |data: &mut [u8]| rs255w233::correct_errors(data).ok(),
|
||||
234u8 => |data: &mut [u8]| rs255w234::correct_errors(data).ok(),
|
||||
235u8 => |data: &mut [u8]| rs255w235::correct_errors(data).ok(),
|
||||
236u8 => |data: &mut [u8]| rs255w236::correct_errors(data).ok(),
|
||||
237u8 => |data: &mut [u8]| rs255w237::correct_errors(data).ok(),
|
||||
238u8 => |data: &mut [u8]| rs255w238::correct_errors(data).ok(),
|
||||
239u8 => |data: &mut [u8]| rs255w239::correct_errors(data).ok(),
|
||||
240u8 => |data: &mut [u8]| rs255w240::correct_errors(data).ok(),
|
||||
241u8 => |data: &mut [u8]| rs255w241::correct_errors(data).ok(),
|
||||
242u8 => |data: &mut [u8]| rs255w242::correct_errors(data).ok(),
|
||||
243u8 => |data: &mut [u8]| rs255w243::correct_errors(data).ok(),
|
||||
244u8 => |data: &mut [u8]| rs255w244::correct_errors(data).ok(),
|
||||
245u8 => |data: &mut [u8]| rs255w245::correct_errors(data).ok(),
|
||||
246u8 => |data: &mut [u8]| rs255w246::correct_errors(data).ok(),
|
||||
247u8 => |data: &mut [u8]| rs255w247::correct_errors(data).ok(),
|
||||
248u8 => |data: &mut [u8]| rs255w248::correct_errors(data).ok(),
|
||||
249u8 => |data: &mut [u8]| rs255w249::correct_errors(data).ok(),
|
||||
250u8 => |data: &mut [u8]| rs255w250::correct_errors(data).ok(),
|
||||
251u8 => |data: &mut [u8]| rs255w251::correct_errors(data).ok(),
|
||||
252u8 => |data: &mut [u8]| rs255w252::correct_errors(data).ok(),
|
||||
253u8 => |data: &mut [u8]| rs255w253::correct_errors(data).ok(),
|
||||
};
|
||||
@@ -16,6 +16,7 @@ extern crate alloc;
|
||||
pub mod boot;
|
||||
pub mod cli;
|
||||
pub mod crypto;
|
||||
pub mod escape;
|
||||
pub mod format;
|
||||
pub mod protobuf;
|
||||
pub mod stream;
|
||||
|
||||
+53
-35
@@ -12,10 +12,11 @@ use std::{
|
||||
},
|
||||
};
|
||||
|
||||
use bstr::ByteSlice;
|
||||
use num_traits::ToPrimitive;
|
||||
use ring::digest::Context;
|
||||
|
||||
use crate::util::{self, EscapedString};
|
||||
use crate::util;
|
||||
|
||||
/// A trait for seekable readers. This is only needed because `dyn Read + Seek`
|
||||
/// is not a valid construct in Rust yet.
|
||||
@@ -118,7 +119,7 @@ impl<R: Read> ReadStringExt for R {
|
||||
String::from_utf8(buf).map_err(|e| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("Invalid UTF-8: {}: {e}", EscapedString::new(e.as_bytes())),
|
||||
format!("Invalid UTF-8: {:?}: {e}", e.as_bytes().as_bstr()),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -138,7 +139,7 @@ impl<R: Read> ReadStringExt for R {
|
||||
String::from_utf8(buf).map_err(|e| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("Invalid UTF-8: {}: {e}", EscapedString::new(e.as_bytes())),
|
||||
format!("Invalid UTF-8: {:?}: {e}", e.as_bytes().as_bstr()),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -398,9 +399,10 @@ impl<W: Write + Seek> Write for HolePunchingWriter<W> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A file wrapper that uses a userspace file offset. A cloned instances uses
|
||||
/// the same underlying kernel file descriptor, but a new userspace file offset.
|
||||
#[derive(Clone)]
|
||||
/// A file wrapper that uses a userspace file offset. A reopened instance uses
|
||||
/// the same underlying kernel file descriptor, but a new userspace file offset,
|
||||
/// initially set to 0.
|
||||
#[derive(Debug)]
|
||||
pub struct PSeekFile {
|
||||
// The lock is needed because flush() takes a `&mut self`.
|
||||
file: Arc<RwLock<File>>,
|
||||
@@ -415,6 +417,13 @@ impl PSeekFile {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reopen(&self) -> Self {
|
||||
Self {
|
||||
file: self.file.clone(),
|
||||
offset: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_len(&self, size: u64) -> io::Result<()> {
|
||||
let file_locked = self.file.read().unwrap();
|
||||
file_locked.set_len(size)
|
||||
@@ -509,17 +518,24 @@ impl Seek for PSeekFile {
|
||||
/// readers into different parts of the same [`SharedCursor`] writer and the
|
||||
/// read operation is significantly more expensive than the write operation (eg.
|
||||
/// due to decompression).
|
||||
#[derive(Clone, Default)]
|
||||
#[derive(Default)]
|
||||
pub struct SharedCursor {
|
||||
inner: Arc<Mutex<Cursor<Vec<u8>>>>,
|
||||
offset: u64,
|
||||
}
|
||||
|
||||
impl SharedCursor {
|
||||
pub fn clone_rewind(&self) -> Self {
|
||||
let mut new = self.clone();
|
||||
new.offset = 0;
|
||||
new
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reopen(&self) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone(),
|
||||
offset: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -560,6 +576,21 @@ impl Seek for SharedCursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an I/O error with the [`io::ErrorKind::Interrupted`] type if
|
||||
/// `cancel_signal` is true. This should be called frequently in I/O loops for
|
||||
/// cancellation to be responsive.
|
||||
#[inline]
|
||||
pub fn check_cancel(cancel_signal: &AtomicBool) -> io::Result<()> {
|
||||
if cancel_signal.load(Ordering::SeqCst) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"Received cancel signal",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copy exactly `size` bytes from `reader` to `writer`, invoking `inspect`
|
||||
/// after every buffer read iteration. If either `reader` or `writer` reaches
|
||||
/// EOF before `size` bytes are copied, an error is returned. The operation is
|
||||
@@ -569,17 +600,12 @@ pub fn copy_n_inspect(
|
||||
mut writer: impl Write,
|
||||
mut size: u64,
|
||||
mut inspect: impl FnMut(&[u8]),
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> io::Result<()> {
|
||||
let mut buf = [0u8; 16384];
|
||||
|
||||
while size > 0 {
|
||||
if cancel_signal.load(Ordering::SeqCst) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"Received cancel signal",
|
||||
));
|
||||
}
|
||||
check_cancel(cancel_signal)?;
|
||||
|
||||
let to_read = size.min(buf.len() as u64) as usize;
|
||||
reader.read_exact(&mut buf[..to_read])?;
|
||||
@@ -599,7 +625,7 @@ pub fn copy_n(
|
||||
reader: impl Read,
|
||||
writer: impl Write,
|
||||
size: u64,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> io::Result<()> {
|
||||
copy_n_inspect(reader, writer, size, |_| {}, cancel_signal)
|
||||
}
|
||||
@@ -610,18 +636,13 @@ pub fn copy_n(
|
||||
pub fn copy(
|
||||
mut reader: impl Read,
|
||||
mut writer: impl Write,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> io::Result<u64> {
|
||||
let mut buf = [0u8; 16384];
|
||||
let mut copied = 0;
|
||||
|
||||
loop {
|
||||
if cancel_signal.load(Ordering::SeqCst) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Interrupted,
|
||||
"Received cancel signal",
|
||||
));
|
||||
}
|
||||
check_cancel(cancel_signal)?;
|
||||
|
||||
let n = reader.read(&mut buf)?;
|
||||
if n == 0 {
|
||||
@@ -640,10 +661,7 @@ pub fn copy(
|
||||
mod tests {
|
||||
use std::{
|
||||
io::{self, Cursor, Read, Seek, SeekFrom, Write},
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
},
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
use ring::digest::Context;
|
||||
@@ -830,8 +848,8 @@ mod tests {
|
||||
fn pseek_file() {
|
||||
let raw_file = tempfile::tempfile().unwrap();
|
||||
let mut a = PSeekFile::new(raw_file);
|
||||
let mut b = a.clone();
|
||||
let mut c = b.clone();
|
||||
let mut b = a.reopen();
|
||||
let mut c = b.reopen();
|
||||
|
||||
b.write_all(b"foobar").unwrap();
|
||||
c.write_all(b"hello").unwrap();
|
||||
@@ -850,8 +868,8 @@ mod tests {
|
||||
#[test]
|
||||
fn shared_cursor() {
|
||||
let mut a = SharedCursor::default();
|
||||
let mut b = a.clone();
|
||||
let mut c = b.clone();
|
||||
let mut b = a.reopen();
|
||||
let mut c = b.reopen();
|
||||
|
||||
b.write_all(b"foobar").unwrap();
|
||||
c.write_all(b"hello").unwrap();
|
||||
@@ -869,7 +887,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn copy() {
|
||||
let cancel_signal = Arc::new(AtomicBool::new(false));
|
||||
let cancel_signal = AtomicBool::new(false);
|
||||
let mut reader = Cursor::new(b"foobar");
|
||||
let mut writer = Cursor::new([0u8; 6]);
|
||||
|
||||
|
||||
@@ -23,72 +23,6 @@ impl fmt::Debug for NumBytes {
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper around a byte slice to format it as ASCII with invalid bytes
|
||||
/// escaped as `\x##`.
|
||||
#[derive(Clone)]
|
||||
pub struct EscapedString<T: AsRef<[u8]>> {
|
||||
inner: T,
|
||||
quoted: bool,
|
||||
}
|
||||
|
||||
impl<T: AsRef<[u8]>> EscapedString<T> {
|
||||
pub fn new(inner: T) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
quoted: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_unquoted(inner: T) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
quoted: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_inner(self) -> T {
|
||||
self.inner
|
||||
}
|
||||
|
||||
pub fn get_ref(&self) -> &T {
|
||||
&self.inner
|
||||
}
|
||||
|
||||
pub fn get_mut(&mut self) -> &mut T {
|
||||
&mut self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsRef<[u8]>> fmt::Debug for EscapedString<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let escaped: String = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.iter()
|
||||
.flat_map(|b| b.escape_ascii())
|
||||
.map(char::from)
|
||||
.collect();
|
||||
|
||||
if self.quoted {
|
||||
write!(f, "\"")?;
|
||||
}
|
||||
|
||||
write!(f, "{escaped}")?;
|
||||
|
||||
if self.quoted {
|
||||
write!(f, "\"")?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsRef<[u8]>> fmt::Display for EscapedString<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
fmt::Debug::fmt(&self, f)
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if a byte slice is all zeros.
|
||||
pub fn is_zero(mut buf: &[u8]) -> bool {
|
||||
while !buf.is_empty() {
|
||||
|
||||
+126
-16
@@ -3,13 +3,20 @@
|
||||
* SPDX-License-Identifier: GPL-3.0-only
|
||||
*/
|
||||
|
||||
use std::io::{self, Cursor, Read, Seek, SeekFrom};
|
||||
use std::{
|
||||
io::{Cursor, Read, Seek, SeekFrom, Write},
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
|
||||
use assert_matches::assert_matches;
|
||||
use pkcs8::DecodePrivateKey;
|
||||
use rsa::RsaPrivateKey;
|
||||
|
||||
use avbroot::{self, format::avb};
|
||||
use avbroot::{
|
||||
self,
|
||||
format::avb::{self, AppendedDescriptorMut, AppendedDescriptorRef},
|
||||
stream::{self, SharedCursor},
|
||||
};
|
||||
|
||||
fn get_test_key() -> RsaPrivateKey {
|
||||
let data = include_str!(concat!(
|
||||
@@ -35,11 +42,14 @@ fn round_trip_root_image() {
|
||||
let (mut header, footer, _) = avb::load_image(reader).unwrap();
|
||||
assert_matches!(footer, None);
|
||||
|
||||
let key = get_test_key();
|
||||
|
||||
assert_eq!(header.verify().unwrap().unwrap(), key.to_public_key());
|
||||
|
||||
// Clear out the signature-related fields and re-sign.
|
||||
header.hash.clear();
|
||||
header.signature.clear();
|
||||
header.public_key.clear();
|
||||
let key = get_test_key();
|
||||
header.sign(&key).unwrap();
|
||||
|
||||
let mut writer = Cursor::new(Vec::new());
|
||||
@@ -50,33 +60,133 @@ fn round_trip_root_image() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_appended_image() {
|
||||
fn round_trip_appended_hash_image() {
|
||||
let data = include_bytes!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/tests/data/vbmeta_appended.img",
|
||||
"/tests/data/vbmeta_appended_hash.img",
|
||||
));
|
||||
let mut reader = Cursor::new(data);
|
||||
let cancel_signal = AtomicBool::new(false);
|
||||
|
||||
let (mut header, footer, _) = avb::load_image(&mut reader).unwrap();
|
||||
let footer = footer.unwrap();
|
||||
let (mut header, footer, image_size) = avb::load_image(&mut reader).unwrap();
|
||||
let mut footer = footer.unwrap();
|
||||
|
||||
let key = get_test_key();
|
||||
|
||||
assert_eq!(header.verify().unwrap().unwrap(), key.to_public_key());
|
||||
|
||||
// Verify the digest.
|
||||
match header.appended_descriptor().unwrap() {
|
||||
AppendedDescriptorRef::HashTree(_) => panic!("Expected hash descriptor"),
|
||||
AppendedDescriptorRef::Hash(d) => {
|
||||
reader.rewind().unwrap();
|
||||
d.verify(&mut reader, &cancel_signal).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
let mut writer = Cursor::new(Vec::new());
|
||||
|
||||
// Copy the partition data.
|
||||
reader.seek(SeekFrom::Start(0)).unwrap();
|
||||
stream::copy_n(
|
||||
&mut reader,
|
||||
&mut writer,
|
||||
footer.original_image_size,
|
||||
&cancel_signal,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Regenerate the digest.
|
||||
match header.appended_descriptor_mut().unwrap() {
|
||||
AppendedDescriptorMut::HashTree(_) => panic!("Expected hash descriptor"),
|
||||
AppendedDescriptorMut::Hash(d) => {
|
||||
d.root_digest.clear();
|
||||
writer.rewind().unwrap();
|
||||
d.update(&mut writer, &cancel_signal).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
// Clear out the signature-related fields and re-sign.
|
||||
header.hash.clear();
|
||||
header.signature.clear();
|
||||
header.public_key.clear();
|
||||
let key = get_test_key();
|
||||
header.sign(&key).unwrap();
|
||||
|
||||
let mut writer = Cursor::new(Vec::new());
|
||||
|
||||
// Copy the partition data.
|
||||
let image_size = reader.seek(SeekFrom::End(0)).unwrap();
|
||||
reader.seek(SeekFrom::Start(0)).unwrap();
|
||||
io::copy(&mut reader.take(footer.original_image_size), &mut writer).unwrap();
|
||||
|
||||
// Write new vbmeta structures.
|
||||
avb::write_appended_image(&mut writer, &header, &footer, image_size).unwrap();
|
||||
avb::write_appended_image(&mut writer, &header, &mut footer, image_size).unwrap();
|
||||
let new_data = writer.into_inner();
|
||||
|
||||
assert_eq!(data, new_data.as_slice());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_appended_hash_tree_image() {
|
||||
let data = include_bytes!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/tests/data/vbmeta_appended_hash_tree.img",
|
||||
));
|
||||
let mut reader = SharedCursor::default();
|
||||
reader.write_all(data).unwrap();
|
||||
let cancel_signal = AtomicBool::new(false);
|
||||
|
||||
let (mut header, footer, image_size) = avb::load_image(&mut reader).unwrap();
|
||||
let mut footer = footer.unwrap();
|
||||
|
||||
let key = get_test_key();
|
||||
|
||||
assert_eq!(header.verify().unwrap().unwrap(), key.to_public_key());
|
||||
|
||||
// Verify the hash tree and FEC data.
|
||||
match header.appended_descriptor().unwrap() {
|
||||
AppendedDescriptorRef::HashTree(d) => {
|
||||
d.verify(|| Ok(Box::new(reader.reopen())), &cancel_signal)
|
||||
.unwrap();
|
||||
}
|
||||
AppendedDescriptorRef::Hash(_) => panic!("Expected hash tree descriptor"),
|
||||
}
|
||||
|
||||
let mut writer = SharedCursor::default();
|
||||
|
||||
// Copy the partition data, excluding the hash tree and FEC data.
|
||||
reader.seek(SeekFrom::Start(0)).unwrap();
|
||||
stream::copy_n(
|
||||
&mut reader,
|
||||
&mut writer,
|
||||
footer.original_image_size,
|
||||
&cancel_signal,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Regenerate the hash tree and FEC data.
|
||||
match header.appended_descriptor_mut().unwrap() {
|
||||
AppendedDescriptorMut::HashTree(d) => {
|
||||
d.root_digest.clear();
|
||||
d.tree_offset = 0;
|
||||
d.tree_size = 0;
|
||||
d.fec_offset = 0;
|
||||
d.fec_size = 0;
|
||||
|
||||
d.update(
|
||||
|| Ok(Box::new(writer.reopen())),
|
||||
|| Ok(Box::new(writer.reopen())),
|
||||
&cancel_signal,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
AppendedDescriptorMut::Hash(_) => panic!("Expected hash tree descriptor"),
|
||||
}
|
||||
|
||||
// Clear out the signature-related fields and re-sign.
|
||||
header.hash.clear();
|
||||
header.signature.clear();
|
||||
header.public_key.clear();
|
||||
header.sign(&key).unwrap();
|
||||
|
||||
// Write new vbmeta structures.
|
||||
avb::write_appended_image(&mut writer, &header, &mut footer, image_size).unwrap();
|
||||
let mut new_data = Vec::new();
|
||||
writer.rewind().unwrap();
|
||||
writer.read_to_end(&mut new_data).unwrap();
|
||||
|
||||
assert_eq!(data, new_data.as_slice());
|
||||
}
|
||||
|
||||
Binary file not shown.
File diff suppressed because one or more lines are too long
+1
-3
@@ -10,16 +10,14 @@ publish = false
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.75"
|
||||
attohttpc = "0.26.1"
|
||||
avbroot = { path = "../avbroot" }
|
||||
clap = { version = "4.4.1", features = ["derive"] }
|
||||
ctrlc = "3.4.0"
|
||||
hex = { version = "0.4.3", features = ["serde"] }
|
||||
reqwest = { version = "0.11.20", features = ["stream"] }
|
||||
ring = "0.16.20"
|
||||
serde = { version = "1.0.188", features = ["derive"] }
|
||||
tempfile = "3.8.0"
|
||||
tokio = { version = "1.32.0", features = ["signal", "rt-multi-thread", "macros"] }
|
||||
tokio-stream = "0.1.14"
|
||||
toml_edit = { version = "0.19.14", features = ["serde"] }
|
||||
|
||||
# https://github.com/zip-rs/zip/pull/383
|
||||
|
||||
+160
-155
@@ -4,29 +4,28 @@
|
||||
*/
|
||||
|
||||
use std::{
|
||||
cmp,
|
||||
collections::{HashMap, VecDeque},
|
||||
fs::{self, OpenOptions},
|
||||
io::{self, Seek, SeekFrom, Write},
|
||||
io::{self, Read, Seek, SeekFrom, Write},
|
||||
ops::Range,
|
||||
path::{Path, PathBuf},
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
mpsc::{self, Sender},
|
||||
},
|
||||
thread::{self, ThreadId},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use avbroot::stream::PSeekFile;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::{
|
||||
runtime::Runtime,
|
||||
signal::ctrl_c,
|
||||
sync::{mpsc, oneshot},
|
||||
task::{self, JoinSet},
|
||||
};
|
||||
use tokio_stream::StreamExt;
|
||||
|
||||
/// Minimum download chunk size per task.
|
||||
const MIN_CHUNK_SIZE: u64 = 1024 * 1024;
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
pub trait ProgressDisplay {
|
||||
fn progress(&mut self, current: u64, total: u64);
|
||||
|
||||
@@ -112,11 +111,21 @@ impl ProgressDisplay for BasicProgressDisplay {
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ProgressMessage {
|
||||
task_id: u64,
|
||||
bytes: u64,
|
||||
// Controller replies with new ending offset
|
||||
resp: oneshot::Sender<u64>,
|
||||
enum MessageData {
|
||||
Progress {
|
||||
bytes: u64,
|
||||
// Controller replies with a new ending offset.
|
||||
resp: Sender<u64>,
|
||||
},
|
||||
Completion {
|
||||
result: Result<()>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Message {
|
||||
id: ThreadId,
|
||||
data: MessageData,
|
||||
}
|
||||
|
||||
/// Download a contiguous byte range. The number of bytes downloaded per loop
|
||||
@@ -125,65 +134,70 @@ struct ProgressMessage {
|
||||
/// download via the oneshot channel in the `resp` field. An appropriate error
|
||||
/// will be returned if the full range (subject to modification) cannot be fully
|
||||
/// downloaded (eg. premature EOF is an error).
|
||||
async fn download_range(
|
||||
task_id: u64,
|
||||
fn download_range(
|
||||
url: &str,
|
||||
mut file: PSeekFile,
|
||||
initial_range: Range<u64>,
|
||||
channel: mpsc::Sender<ProgressMessage>,
|
||||
channel: Sender<Message>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
assert!(initial_range.start < initial_range.end);
|
||||
|
||||
let client = reqwest::ClientBuilder::new().build()?;
|
||||
|
||||
let response = client
|
||||
.get(url)
|
||||
let mut response = attohttpc::get(url)
|
||||
.connect_timeout(TIMEOUT)
|
||||
.read_timeout(TIMEOUT)
|
||||
.header(
|
||||
reqwest::header::RANGE,
|
||||
format!("bytes={}-{}", initial_range.start, initial_range.end - 1),
|
||||
"Range",
|
||||
&format!("bytes={}-{}", initial_range.start, initial_range.end - 1),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.and_then(|r| r.error_for_status())
|
||||
.with_context(|| format!("Failed to start download for range: {initial_range:?}"))?;
|
||||
let mut stream = response.bytes_stream();
|
||||
|
||||
let mut range = initial_range.clone();
|
||||
let mut buf = [0u8; 65536];
|
||||
|
||||
while range.start < range.end {
|
||||
let data = if let Some(x) = stream.next().await {
|
||||
x?
|
||||
} else {
|
||||
return Err(anyhow!("Unexpected EOF from server"));
|
||||
};
|
||||
if cancel_signal.load(Ordering::SeqCst) {
|
||||
bail!("Received cancel signal");
|
||||
}
|
||||
|
||||
let to_read = (range.end - range.start).min(buf.len() as u64) as usize;
|
||||
let n = response.read(&mut buf[..to_read]).with_context(|| {
|
||||
format!(
|
||||
"Failed to download {to_read} bytes at offset {}",
|
||||
range.start,
|
||||
)
|
||||
})?;
|
||||
if n == 0 {
|
||||
bail!("Unexpected EOF from server");
|
||||
}
|
||||
|
||||
// This may overlap with another task's write when a range split occurs,
|
||||
// but the same data will be written anyway, so it's not a huge deal.
|
||||
task::block_in_place(|| {
|
||||
file.seek(SeekFrom::Start(range.start))?;
|
||||
file.write_all(&data)
|
||||
})
|
||||
.with_context(|| {
|
||||
file.seek(SeekFrom::Start(range.start))?;
|
||||
file.write_all(&buf[..n]).with_context(|| {
|
||||
format!(
|
||||
"Failed to write {} bytes to output file at offset {}",
|
||||
data.len(),
|
||||
"Failed to write {n} bytes to output file at offset {}",
|
||||
range.start,
|
||||
)
|
||||
})?;
|
||||
|
||||
let consumed = cmp::min(range.end - range.start, data.len() as u64);
|
||||
range.start += consumed;
|
||||
range.start += n as u64;
|
||||
|
||||
// Report progress to the controller.
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let msg = ProgressMessage {
|
||||
task_id,
|
||||
bytes: consumed,
|
||||
resp: tx,
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let msg = Message {
|
||||
id: thread::current().id(),
|
||||
data: MessageData::Progress {
|
||||
bytes: n as u64,
|
||||
resp: tx,
|
||||
},
|
||||
};
|
||||
channel.send(msg).await?;
|
||||
channel.send(msg)?;
|
||||
|
||||
// Get new ending offset from controller.
|
||||
let new_end = rx.await?;
|
||||
let new_end = rx.recv()?;
|
||||
if new_end != range.end {
|
||||
debug_assert!(new_end <= range.end);
|
||||
range.end = new_end;
|
||||
@@ -193,33 +207,37 @@ async fn download_range(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create download task for a byte range. This just calls [`download_range()`]
|
||||
/// and returns a tuple containing the task ID and the result.
|
||||
async fn download_task(
|
||||
task_id: u64,
|
||||
url: String,
|
||||
/// This just calls [`download_range()`] and sends a completion message to the
|
||||
/// channel with the result.
|
||||
fn download_thread(
|
||||
url: &str,
|
||||
file: PSeekFile,
|
||||
initial_range: Range<u64>,
|
||||
channel: mpsc::Sender<ProgressMessage>,
|
||||
) -> (u64, Result<()>) {
|
||||
(
|
||||
task_id,
|
||||
download_range(task_id, &url, file, initial_range, channel).await,
|
||||
)
|
||||
channel: mpsc::Sender<Message>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) {
|
||||
let result = download_range(url, file, initial_range, channel.clone(), cancel_signal);
|
||||
|
||||
channel
|
||||
.send(Message {
|
||||
id: thread::current().id(),
|
||||
data: MessageData::Completion { result },
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Send a HEAD request to get the value of the Content-Length header.
|
||||
async fn get_content_length(url: &str) -> Result<u64> {
|
||||
let response = reqwest::Client::new()
|
||||
.head(url)
|
||||
fn get_content_length(url: &str) -> Result<u64> {
|
||||
let response = attohttpc::head(url)
|
||||
.connect_timeout(TIMEOUT)
|
||||
.read_timeout(TIMEOUT)
|
||||
.send()
|
||||
.await
|
||||
.and_then(|r| r.error_for_status())
|
||||
.context("Failed to send HEAD request to get Content-Length")?;
|
||||
|
||||
response
|
||||
.headers()
|
||||
.get("content-length")
|
||||
.get("Content-Length")
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.and_then(|h| h.parse().ok())
|
||||
.ok_or_else(|| anyhow!("HEAD request did not return a valid Content-Length"))
|
||||
@@ -229,27 +247,26 @@ async fn get_content_length(url: &str) -> Result<u64> {
|
||||
/// returned as an Err. Normal/expected errors and download progress info are
|
||||
/// reported via `display`. Returns the remaining ranges that need to be
|
||||
/// downloaded.
|
||||
async fn download_ranges(
|
||||
fn download_ranges(
|
||||
url: &str,
|
||||
output: &Path,
|
||||
initial_ranges: Option<&[Range<u64>]>,
|
||||
display: &mut dyn ProgressDisplay,
|
||||
max_tasks: usize,
|
||||
max_threads: usize,
|
||||
max_errors: u8,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<Vec<Range<u64>>> {
|
||||
let file_size = get_content_length(url).await?;
|
||||
let file_size = get_content_length(url)?;
|
||||
|
||||
// Open for writing, but without truncation.
|
||||
let file = task::block_in_place(|| {
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.open(output)
|
||||
.map(PSeekFile::new)
|
||||
.with_context(|| format!("Failed to open for writing: {output:?}"))
|
||||
})?;
|
||||
let file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.open(output)
|
||||
.map(PSeekFile::new)
|
||||
.with_context(|| format!("Failed to open for writing: {output:?}"))?;
|
||||
|
||||
task::block_in_place(|| file.set_len(file_size))
|
||||
file.set_len(file_size)
|
||||
.with_context(|| format!("Failed to set file size: {output:?}"))?;
|
||||
|
||||
// Queue of ranges that need to be downloaded.
|
||||
@@ -260,114 +277,101 @@ async fn download_ranges(
|
||||
});
|
||||
// Ranges that have failed.
|
||||
let mut failed = Vec::<Range<u64>>::new();
|
||||
// Ranges for currently running tasks.
|
||||
let mut task_ranges = HashMap::<u64, Range<u64>>::new();
|
||||
// Ranges for currently running threads.
|
||||
let mut thread_ranges = HashMap::<ThreadId, Range<u64>>::new();
|
||||
|
||||
// Overall progress.
|
||||
let mut progress = file_size - remaining.iter().map(|r| r.end - r.start).sum::<u64>();
|
||||
display.progress(progress, file_size);
|
||||
|
||||
let mut tasks = JoinSet::new();
|
||||
let mut next_task_id = 0;
|
||||
let mut error_count = 0u8;
|
||||
// Progress messages from tasks.
|
||||
let (tx, mut rx) = mpsc::channel(max_tasks);
|
||||
thread::scope(|scope| {
|
||||
let mut threads = HashMap::new();
|
||||
let mut error_count = 0u8;
|
||||
// Progress messages from threads.
|
||||
let (tx, rx) = mpsc::channel();
|
||||
|
||||
loop {
|
||||
// Spawn new tasks.
|
||||
while tasks.len() < max_tasks {
|
||||
if remaining.is_empty() && !tasks.is_empty() {
|
||||
// No more ranges to download. Split another task's range.
|
||||
let (_, old_range) = task_ranges
|
||||
.iter_mut()
|
||||
.max_by_key(|(_, r)| r.end - r.start)
|
||||
.unwrap();
|
||||
let size = old_range.end - old_range.start;
|
||||
loop {
|
||||
// Spawn new threads.
|
||||
while !cancel_signal.load(Ordering::SeqCst) && threads.len() < max_threads {
|
||||
if remaining.is_empty() && !threads.is_empty() {
|
||||
// No more ranges to download. Split another thread's range.
|
||||
let (_, old_range) = thread_ranges
|
||||
.iter_mut()
|
||||
.max_by_key(|(_, r)| r.end - r.start)
|
||||
.unwrap();
|
||||
let size = old_range.end - old_range.start;
|
||||
|
||||
if size >= MIN_CHUNK_SIZE {
|
||||
let new_range = old_range.start + size / 2..old_range.end;
|
||||
old_range.end = new_range.start;
|
||||
remaining.push_back(new_range);
|
||||
if size >= MIN_CHUNK_SIZE {
|
||||
let new_range = old_range.start + size / 2..old_range.end;
|
||||
old_range.end = new_range.start;
|
||||
remaining.push_back(new_range);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(thread_range) = remaining.pop_front() {
|
||||
let file_cloned = file.reopen();
|
||||
let thread_range_cloned = thread_range.clone();
|
||||
let tx_cloned = tx.clone();
|
||||
|
||||
let join_handle = scope.spawn(|| {
|
||||
download_thread(
|
||||
url,
|
||||
file_cloned,
|
||||
thread_range_cloned,
|
||||
tx_cloned,
|
||||
cancel_signal,
|
||||
)
|
||||
});
|
||||
|
||||
thread_ranges.insert(join_handle.thread().id(), thread_range);
|
||||
threads.insert(join_handle.thread().id(), join_handle);
|
||||
} else {
|
||||
// No pending ranges and no running threads can be split.
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(task_range) = remaining.pop_front() {
|
||||
tasks.spawn(download_task(
|
||||
next_task_id,
|
||||
url.to_owned(),
|
||||
file.clone(),
|
||||
task_range.clone(),
|
||||
tx.clone(),
|
||||
));
|
||||
|
||||
task_ranges.insert(next_task_id, task_range);
|
||||
next_task_id += 1;
|
||||
} else {
|
||||
// No pending ranges and no running tasks can be split.
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
// Interrupted by user.
|
||||
c = ctrl_c() => {
|
||||
c?;
|
||||
if threads.is_empty() {
|
||||
// Nothing left to do.
|
||||
break;
|
||||
}
|
||||
|
||||
// Received progress notification.
|
||||
msg = rx.recv() => {
|
||||
let msg = msg.unwrap();
|
||||
let Message { id, data } = rx.recv().unwrap();
|
||||
|
||||
progress += msg.bytes;
|
||||
display.progress(progress, file_size);
|
||||
match data {
|
||||
MessageData::Progress { bytes, resp } => {
|
||||
progress += bytes;
|
||||
display.progress(progress, file_size);
|
||||
|
||||
let task_range = task_ranges.get_mut(&msg.task_id).unwrap();
|
||||
task_range.start += msg.bytes;
|
||||
let thread_range = thread_ranges.get_mut(&id).unwrap();
|
||||
thread_range.start += bytes;
|
||||
|
||||
msg.resp.send(task_range.end).unwrap();
|
||||
}
|
||||
resp.send(thread_range.end).unwrap();
|
||||
}
|
||||
MessageData::Completion { result } => {
|
||||
threads.remove(&id).unwrap().join().unwrap();
|
||||
|
||||
// Received completion message.
|
||||
r = tasks.join_next() => {
|
||||
match r {
|
||||
// All tasks exited.
|
||||
None => {
|
||||
break;
|
||||
},
|
||||
let thread_range = thread_ranges.remove(&id).unwrap();
|
||||
|
||||
// Download task panicked.
|
||||
Some(Err(e)) => {
|
||||
return Err(e).context("Unexpected panic in download task");
|
||||
}
|
||||
|
||||
// Task completed successfully.
|
||||
Some(Ok((task_id, Ok(_)))) => {
|
||||
task_ranges.remove(&task_id).unwrap();
|
||||
}
|
||||
|
||||
// Task failed.
|
||||
Some(Ok((task_id, Err(e)))) => {
|
||||
display.error(&format!("[Task#{task_id}] {e}"));
|
||||
if let Err(e) = result {
|
||||
display.error(&format!("[{id:?}] {e:?}"));
|
||||
error_count += 1;
|
||||
|
||||
let range = task_ranges.remove(&task_id).unwrap();
|
||||
|
||||
if error_count < max_errors {
|
||||
remaining.push_back(range);
|
||||
remaining.push_back(thread_range);
|
||||
} else {
|
||||
failed.push(range);
|
||||
failed.push(thread_range);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
display.finish();
|
||||
|
||||
failed.extend(remaining.into_iter());
|
||||
failed.extend(task_ranges.into_values());
|
||||
failed.extend(remaining);
|
||||
failed.extend(thread_ranges.into_values());
|
||||
|
||||
Ok(failed)
|
||||
}
|
||||
@@ -428,6 +432,7 @@ pub fn download(
|
||||
display: &mut dyn ProgressDisplay,
|
||||
max_tasks: usize,
|
||||
max_errors: u8,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
let state_path = state_path(output);
|
||||
let ranges = match read_state(&state_path)? {
|
||||
@@ -435,15 +440,15 @@ pub fn download(
|
||||
None => initial_ranges.map(|r| r.to_vec()),
|
||||
};
|
||||
|
||||
let runtime = Runtime::new()?;
|
||||
let remaining = runtime.block_on(download_ranges(
|
||||
let remaining = download_ranges(
|
||||
url,
|
||||
output,
|
||||
ranges.as_deref(),
|
||||
display,
|
||||
max_tasks,
|
||||
max_errors,
|
||||
))?;
|
||||
cancel_signal,
|
||||
)?;
|
||||
|
||||
if remaining.is_empty() {
|
||||
delete_if_exists(&state_path)?;
|
||||
|
||||
+16
-19
@@ -90,14 +90,14 @@ fn exclusion_to_inclusion(holes: &[Range<u64>], file_range: Range<u64>) -> Resul
|
||||
fn strip_image(
|
||||
input: &Path,
|
||||
output: &Path,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<(Vec<Range<u64>>, [u8; 32])> {
|
||||
println!("Stripping {input:?} to {output:?}");
|
||||
|
||||
let mut raw_reader = File::open(input)
|
||||
.map(PSeekFile::new)
|
||||
.with_context(|| format!("Failed to open for reading: {input:?}"))?;
|
||||
let mut zip_reader = ZipArchive::new(BufReader::new(raw_reader.clone()))
|
||||
let mut zip_reader = ZipArchive::new(BufReader::new(raw_reader.reopen()))
|
||||
.with_context(|| format!("Failed to read zip: {input:?}"))?;
|
||||
let payload_entry = zip_reader
|
||||
.by_name(ota::PATH_PAYLOAD)
|
||||
@@ -107,7 +107,7 @@ fn strip_image(
|
||||
|
||||
// Open the payload data directly.
|
||||
let mut payload_reader = SectionReader::new(
|
||||
BufReader::new(raw_reader.clone()),
|
||||
BufReader::new(raw_reader.reopen()),
|
||||
payload_offset,
|
||||
payload_size,
|
||||
)?;
|
||||
@@ -194,7 +194,7 @@ fn url_filename(url: &str) -> Result<&str> {
|
||||
.ok_or_else(|| anyhow!("Failed to determine filename from URL: {url}"))
|
||||
}
|
||||
|
||||
fn hash_file(path: &Path, cancel_signal: &Arc<AtomicBool>) -> Result<[u8; 32]> {
|
||||
fn hash_file(path: &Path, cancel_signal: &AtomicBool) -> Result<[u8; 32]> {
|
||||
println!("Calculating hash of {path:?}");
|
||||
|
||||
let raw_reader =
|
||||
@@ -211,7 +211,7 @@ fn hash_file(path: &Path, cancel_signal: &Arc<AtomicBool>) -> Result<[u8; 32]> {
|
||||
Ok(digest.as_ref().try_into().unwrap())
|
||||
}
|
||||
|
||||
fn verify_hash(path: &Path, sha256: &[u8; 32], cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
fn verify_hash(path: &Path, sha256: &[u8; 32], cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let digest = hash_file(path, cancel_signal)?;
|
||||
|
||||
if sha256 != digest.as_ref() {
|
||||
@@ -239,7 +239,7 @@ fn download_file(
|
||||
sections: Option<&[Range<u64>]>,
|
||||
path_is_dir: bool,
|
||||
validate: Validate,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<PathBuf> {
|
||||
let path = if path_is_dir {
|
||||
path.join(url_filename(url)?)
|
||||
@@ -270,6 +270,7 @@ fn download_file(
|
||||
&mut display,
|
||||
DOWNLOAD_TASKS,
|
||||
DOWNLOAD_RETRIES,
|
||||
cancel_signal,
|
||||
)?;
|
||||
}
|
||||
|
||||
@@ -284,7 +285,7 @@ fn download_magisk(
|
||||
config: &Config,
|
||||
work_dir: &Path,
|
||||
revalidate: bool,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<PathBuf> {
|
||||
download_file(
|
||||
&work_dir.join("magisk"),
|
||||
@@ -307,7 +308,7 @@ fn download_image(
|
||||
work_dir: &Path,
|
||||
stripped: bool,
|
||||
revalidate: bool,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<PathBuf> {
|
||||
let info = &config.device[device];
|
||||
let mut path = work_dir.join(device);
|
||||
@@ -395,7 +396,7 @@ fn patch_image(
|
||||
input_file: &Path,
|
||||
output_file: &Path,
|
||||
extra_args: &[OsString],
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
cancel_signal: &AtomicBool,
|
||||
) -> Result<()> {
|
||||
println!("Patching {input_file:?}");
|
||||
|
||||
@@ -425,11 +426,7 @@ fn patch_image(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn extract_image(
|
||||
input_file: &Path,
|
||||
output_dir: &Path,
|
||||
cancel_signal: &Arc<AtomicBool>,
|
||||
) -> Result<()> {
|
||||
fn extract_image(input_file: &Path, output_dir: &Path, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
println!("Extracting AVB partitions from {input_file:?}");
|
||||
|
||||
let cli = ExtractCli::try_parse_from([
|
||||
@@ -444,7 +441,7 @@ fn extract_image(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_image(input_file: &Path, cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
fn verify_image(input_file: &Path, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
println!("Verifying signatures in {input_file:?}");
|
||||
|
||||
let (_temp_key_dir, _, key_args) = test_keys()?;
|
||||
@@ -509,7 +506,7 @@ fn filter_devices<'a>(config: &'a Config, cli: &'a DeviceGroup) -> Result<BTreeS
|
||||
Ok(devices)
|
||||
}
|
||||
|
||||
fn strip_subcommand(cli: &StripCli, cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
fn strip_subcommand(cli: &StripCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let (sections, sha256) = strip_image(&cli.input, &cli.output, cancel_signal)?;
|
||||
|
||||
println!("Preserved sections:");
|
||||
@@ -522,7 +519,7 @@ fn strip_subcommand(cli: &StripCli, cancel_signal: &Arc<AtomicBool>) -> Result<(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn add_subcommand(cli: &AddCli, cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
fn add_subcommand(cli: &AddCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let (config, mut document) = config::load_config(&cli.config.config)?;
|
||||
|
||||
let image_dir = cli.config.work_dir.join(&cli.device);
|
||||
@@ -636,7 +633,7 @@ fn add_subcommand(cli: &AddCli, cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn download_subcommand(cli: &DownloadCli, cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
fn download_subcommand(cli: &DownloadCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let (config, _) = config::load_config(&cli.config.config)?;
|
||||
let devices = filter_devices(&config, &cli.device)?;
|
||||
|
||||
@@ -667,7 +664,7 @@ fn download_subcommand(cli: &DownloadCli, cancel_signal: &Arc<AtomicBool>) -> Re
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn test_subcommand(cli: &TestCli, cancel_signal: &Arc<AtomicBool>) -> Result<()> {
|
||||
fn test_subcommand(cli: &TestCli, cancel_signal: &AtomicBool) -> Result<()> {
|
||||
let (config, _) = config::load_config(&cli.config.config)?;
|
||||
let devices = filter_devices(&config, &cli.device)?;
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
id=com.chiller3.avbroot.clearotacerts
|
||||
name=clearotacerts
|
||||
version=v2.0.3
|
||||
versionCode=131075
|
||||
version=v2.1.0
|
||||
versionCode=131328
|
||||
author=chenxiaolong
|
||||
description=Block A/B OTAs by clearing verification certificates
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
id=com.chiller3.avbroot.oemunlockonboot
|
||||
name=oemunlockonboot
|
||||
version=v2.0.3
|
||||
versionCode=131075
|
||||
version=v2.1.0
|
||||
versionCode=131328
|
||||
author=chenxiaolong
|
||||
description=Enable OEM unlocking on every boot
|
||||
|
||||
+5
-22
@@ -20,16 +20,11 @@ use crate::WORKSPACE_DIR;
|
||||
struct LinkRef {
|
||||
link_type: String,
|
||||
number: u32,
|
||||
user: Option<String>,
|
||||
}
|
||||
|
||||
impl fmt::Display for LinkRef {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "[{} #{}", self.link_type, self.number)?;
|
||||
if let Some(u) = &self.user {
|
||||
write!(f, " @{}", u)?;
|
||||
}
|
||||
write!(f, "]")
|
||||
write!(f, "[{} #{}]", self.link_type, self.number)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,7 +50,7 @@ fn check_brackets(line: &str) -> Result<()> {
|
||||
|
||||
fn update_changelog_links(path: &Path, base_url: &str) -> Result<()> {
|
||||
let re_standalone_link = Regex::new(r"\[([^\]]+)\]($|[^\(\[])")?;
|
||||
let re_auto_link = Regex::new(r"^(Issue|PR) #([0-9]+)(?: @([a-zA-Z0-9\-]+))?$")?;
|
||||
let re_auto_link = Regex::new(r"^(Issue|PR) #([0-9]+)?$")?;
|
||||
let mut links = BTreeMap::<LinkRef, String>::new();
|
||||
|
||||
let raw_reader = File::open(path)?;
|
||||
@@ -85,22 +80,11 @@ fn update_changelog_links(path: &Path, base_url: &str) -> Result<()> {
|
||||
let link_ref = captures.get(0).unwrap().as_str();
|
||||
let link_type = captures.get(1).unwrap().as_str();
|
||||
let number: u32 = captures.get(2).unwrap().as_str().parse()?;
|
||||
let user = captures.get(3).map(|c| c.as_str());
|
||||
|
||||
let link = match link_type {
|
||||
"Issue" => {
|
||||
if user.is_some() {
|
||||
bail!("{link_ref} should not have a username");
|
||||
}
|
||||
format!("{base_url}/issues/{number}")
|
||||
}
|
||||
"PR" => {
|
||||
if user.is_none() {
|
||||
bail!("{link_ref} should have a username");
|
||||
}
|
||||
format!("{base_url}/pull/{number}")
|
||||
}
|
||||
t => bail!("Unknown link type: {t:?}"),
|
||||
"Issue" => format!("{base_url}/issues/{number}"),
|
||||
"PR" => format!("{base_url}/pull/{number}"),
|
||||
t => bail!("Unknown link type in {link_ref:?}: {t:?}"),
|
||||
};
|
||||
|
||||
// #0 is used for examples only.
|
||||
@@ -109,7 +93,6 @@ fn update_changelog_links(path: &Path, base_url: &str) -> Result<()> {
|
||||
LinkRef {
|
||||
link_type: link_type.to_owned(),
|
||||
number,
|
||||
user: user.map(|u| u.to_owned()),
|
||||
},
|
||||
link,
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user