• Home
Name Date Size #Lines LOC

..--

boot_control/03-May-2024-171122

docs/03-May-2024-

examples/03-May-2024-1,8481,246

libavb/03-May-2024-8,2334,845

libavb_ab/03-May-2024-922481

libavb_atx/03-May-2024-727443

libavb_user/03-May-2024-1,002585

test/03-May-2024-14,46711,668

tools/03-May-2024-2,2261,645

.clang-formatD03-May-2024884 2725

.gitignoreD03-May-20249 21

Android.bpD03-May-20249.3 KiB397372

LICENSED03-May-20243.2 KiB6452

METADATAD03-May-202439 43

MODULE_LICENSE_APACHE2D03-May-20240

MODULE_LICENSE_BSDD03-May-20240

MODULE_LICENSE_MITD03-May-20240

OWNERSD03-May-2024119 76

PREUPLOAD.cfgD03-May-2024165 86

README.mdD03-May-202454.1 KiB1,169941

TEST_MAPPINGD03-May-2024128 1110

avbtool.pyD03-May-2024196.7 KiB4,9363,963

pylintrcD03-May-202414.2 KiB490364

README.md

1# Android Verified Boot 2.0
2---
3
4This repository contains tools and libraries for working with Android
5Verified Boot 2.0. Usually AVB is used to refer to this codebase.
6
7# Table of Contents
8
9* [What is it?](#What-is-it)
10    + [The VBMeta struct](#The-VBMeta-struct)
11    + [Rollback Protection](#Rollback-Protection)
12    + [A/B Support](#A_B-Support)
13    + [The VBMeta Digest](#The-VBMeta-Digest)
14* [Tools and Libraries](#Tools-and-Libraries)
15    + [avbtool and libavb](#avbtool-and-libavb)
16    + [Files and Directories](#Files-and-Directories)
17    + [Portability](#Portability)
18    + [Versioning and Compatibility](#Versioning-and-Compatibility)
19    + [Adding New Features](#Adding-New-Features)
20    + [Using avbtool](#Using-avbtool)
21    + [Build System Integration](#Build-System-Integration)
22* [Device Integration](#Device-Integration)
23    + [System Dependencies](#System-Dependencies)
24    + [Locked and Unlocked mode](#Locked-and-Unlocked-mode)
25    + [Tamper-evident Storage](#Tamper_evident-Storage)
26    + [Named Persistent Values](#Named-Persistent-Values)
27    + [Persistent Digests](#Persistent-Digests)
28    + [Updating Stored Rollback Indexes](#Updating-Stored-Rollback-Indexes)
29    + [Recommended Bootflow](#Recommended-Bootflow)
30      + [Booting Into Recovery](#Booting-Into-Recovery)
31    + [Handling dm-verity Errors](#Handling-dm_verity-Errors)
32    + [Android Specific Integration](#Android-Specific-Integration)
33    + [GKI 2.0 Integration](#GKI-2_0-Integration)
34    + [Device Specific Notes](#Device-Specific-Notes)
35* [Version History](#Version-History)
36
37# What is it?
38
39Verified boot is the process of assuring the end user of the integrity
40of the software running on a device. It typically starts with a
41read-only portion of the device firmware which loads code and executes
42it only after cryptographically verifying that the code is authentic
43and doesn't have any known security flaws. AVB is one implementation
44of verified boot.
45
46## The VBMeta struct
47
48The central data structure used in AVB is the VBMeta struct. This data
49structure contains a number of descriptors (and other metadata) and
50all of this data is cryptographically signed. Descriptors are used for
51image hashes, image hashtree metadata, and so-called *chained
52partitions*. A simple example is the following:
53
54![AVB with boot, system, and vendor](docs/avb-integrity-data-in-vbmeta.png)
55
56where the `vbmeta` partition holds the hash for the `boot` partition
57in a hash descriptor. For the `system` and `vendor` partitions a
58hashtree follows the filesystem data and the `vbmeta` partition holds
59the root hash, salt, and offset of the hashtree in hashtree
60descriptors. Because the VBMeta struct in the `vbmeta` partition is
61cryptographically signed, the boot loader can check the signature and
62verify it was made by the owner of `key0` (by e.g. embedding the
63public part of `key0`) and thereby trust the hashes used for `boot`,
64`system`, and `vendor`.
65
66A chained partition descriptor is used to delegate authority - it
67contains the name of the partition where authority is delegated as
68well as the public key that is trusted for signatures on this
69particular partition. As an example, consider the following setup:
70
71![AVB with a chained partition](docs/avb-chained-partition.png)
72
73In this setup the `xyz` partition has a hashtree for
74integrity-checking. Following the hashtree is a VBMeta struct which
75contains the hashtree descriptor with hashtree metadata (root hash,
76salt, offset, etc.) and this struct is signed with `key1`. Finally, at
77the end of the partition is a footer which has the offset of the
78VBMeta struct.
79
80This setup allows the bootloader to use the chain partition descriptor
81to find the footer at the end of the partition (using the name in the
82chain partition descriptor) which in turns helps locate the VBMeta
83struct and verify that it was signed by `key1` (using `key1_pub` stored in the
84chain partition descriptor). Crucially, because there's a footer with
85the offset, the `xyz` partition can be updated without the `vbmeta`
86partition needing any changes.
87
88The VBMeta struct is flexible enough to allow hash descriptors and hashtree
89descriptors for any partition to live in the `vbmeta` partition, the partition
90that they are used to integrity check (via a chain partition descriptor), or any
91other partition (via a chain partition descriptor). This allows for a wide range
92of organizational and trust relationships.
93
94Chained partitions need not use a footer - it is permissible to have a chained
95partition point to a partition where the VBMeta struct is at the beginning
96(e.g. just like the `vbmeta` partition). This is useful for use-cases where all
97hash- and hashtree-descriptors for the partitions owned by an entire
98organization are stored in a dedicated partition, for example `vbmeta_google`.
99In this example the hashtree descriptor for `system` is in the `vbmeta_google`
100partition meaning that the bootloader doesn't need to access the `system`
101partition at all which is helpful if the `system` partition is managed as a
102logical partition (via e.g. [LVM
103techniques](https://en.wikipedia.org/wiki/Logical_volume_management) or
104similar).
105
106## Rollback Protection
107
108AVB includes Rollback Protection which is used to protect against
109known security flaws. Each VBMeta struct has a *rollback index* baked
110into it like the following:
111
112![AVB rollback indexes](docs/avb-rollback-indexes.png)
113
114These numbers are referred to as `rollback_index[n]` and are increased
115for each image as security flaws are discovered and
116fixed. Additionally the device stores the last seen rollback index in
117tamper-evident storage:
118
119![AVB stored rollback indexes](docs/avb-stored-rollback-indexes.png)
120
121and these are referred to as `stored_rollback_index[n]`.
122
123Rollback protection is having the device reject an image unless
124`rollback_index[n]` >= `stored_rollback_index[n]` for all `n`, and
125having the device increase `stored_rollback_index[n]` over
126time. Exactly how this is done is discussed in
127the
128[Updating Stored Rollback Indexes](#Updating-Stored-Rollback-Indexes)
129section.
130
131## A/B Support
132
133AVB has been designed to work with A/B by requiring that the A/B
134suffix is never used in any partition names stored in
135descriptors. Here's an example with two slots:
136
137![AVB with A/B partitions](docs/avb-ab-partitions.png)
138
139Note how the rollback indexes differ between slots - for slot A the
140rollback indexes are `[42, 101]` and for slot B they are `[43, 103]`.
141
142In version 1.1 or later, avbtool supports `--do_not_use_ab` for
143`add_hash_footer` and `add_hashtree_footer` operations. This makes it
144possible to work with a partition that does not use A/B and should
145never have the prefix. This corresponds to the
146`AVB_HASH[TREE]_DESCRIPTOR_FLAGS_DO_NOT_USE_AB` flags.
147
148## The VBMeta Digest
149
150The VBMeta digest is a digest over all VBMeta structs including the root struct
151(e.g. in the `vbmeta` partition) and all VBMeta structs in chained
152partitions. This digest can be calculated at build time using `avbtool
153calculate_vbmeta_digest` and also at runtime using the
154`avb_slot_verify_data_calculate_vbmeta_digest()` function. It is also set on the
155kernel command-line as `androidboot.vbmeta.digest`, see the `avb_slot_verify()`
156documentation for exact details.
157
158This digest can be used together with `libavb` in userspace inside the loaded
159operating system to verify authenticity of the loaded vbmeta structs. This is
160useful if the root-of-trust and/or stored rollback indexes are only available
161while running in the boot loader.
162
163Additionally, if the VBMeta digest is included in [hardware-backed attestation
164data](https://developer.android.com/training/articles/security-key-attestation)
165a relying party can extract the digest and compare it with list of digests for
166known good operating systems which, if found, provides additional assurance
167about the device the application is running on.
168
169For [factory images of Pixel 3 and later
170devices](https://developers.google.com/android/images), the
171`pixel_factory_image_verify.py` located in `tools/transparency` is a convenience
172tool for downloading, verifying and calcuating VBMeta Digests.
173
174    $ pixel_factory_image_verify.py https://dl.google.com/dl/android/aosp/image.zip
175    Fetching file from: https://dl.google.com/dl/android/aosp/image.zip
176    Successfully downloaded file.
177    Successfully unpacked factory image.
178    Successfully unpacked factory image partitions.
179    Successfully verified VBmeta.
180    Successfully calculated VBMeta Digest.
181    The VBMeta Digest for factory image is: 1f329b20a2dd69425e7a29566ca870dad51d2c579311992d41c9ba9ba05e170e
182
183If the given argument is not an URL it considered to be a local file:
184
185    $ pixel_factory_image_verify.py image.zip
186
187# Tools and Libraries
188
189This section contains information about the tools and libraries
190included in AVB.
191
192## avbtool and libavb
193
194The main job of `avbtool` is to create `vbmeta.img` which is the
195top-level object for verified boot. This image is designed to go into
196the `vbmeta` partition (or, if using A/B, the slot in question
197e.g. `vbmeta_a` or `vbmeta_b`) and be of minimal size (for out-of-band
198updates). The vbmeta image is cryptographically signed and contains
199verification data (e.g. cryptographic digests) for verifying
200`boot.img`, `system.img`, and other partitions/images.
201
202The vbmeta image can also contain references to other partitions where
203verification data is stored as well as a public key indicating who
204should sign the verification data. This indirection provides
205delegation, that is, it allows a 3rd party to control content on a
206given partition by including their public key in `vbmeta.img`. By
207design, this authority can be easily revoked by simply updating
208`vbmeta.img` with new descriptors for the partition in question.
209
210Storing signed verification data on other images - for example
211`boot.img` and `system.img` - is also done with `avbtool`.
212
213The minimum requirement for running `avbtool` is to either have
214Python 3.5 installed or build the avbtool with the embedded launcher
215using `m avbtool` and then run it out of the build artifact directory:
216`out/soong/host/linux-x86/bin/avbtool`
217
218In addition to `avbtool`, a library - `libavb` - is provided. This
219library performs all verification on the device side e.g. it starts by
220loading the `vbmeta` partition, checks the signature, and then goes on
221to load the `boot` partition for verification. This library is
222intended to be used in both boot loaders and inside Android. It has a
223simple abstraction for system dependencies (see `avb_sysdeps.h`) as
224well as operations that the boot loader or OS is expected to implement
225(see `avb_ops.h`). The main entry point for verification is
226`avb_slot_verify()`.
227
228Android Things has specific requirements and validation logic for the
229vbmeta public key. An extension is provided in `libavb_atx` which
230performs this validation as an implementation of `libavb`'s public key
231validation operation (see `avb_validate_vbmeta_public_key()` in
232`avb_ops.h`).
233
234## Files and Directories
235
236* `libavb/`
237    + An implementation of image verification. This code is designed
238      to be highly portable so it can be used in as many contexts as
239      possible. This code requires a C99-compliant C compiler. Part of
240      this code is considered internal to the implementation and
241      should not be used outside it. For example, this applies to the
242      `avb_rsa.[ch]` and `avb_sha.[ch]` files. System dependencies
243      expected to be provided by the platform is defined in
244      `avb_sysdeps.h`. If the platform provides the standard C runtime
245      `avb_sysdeps_posix.c` can be used.
246* `libavb_atx/`
247    + An Android Things Extension for validating public key metadata.
248* `libavb_user/`
249    + Contains an `AvbOps` implementation suitable for use in Android
250      userspace. This is used in `boot_control.avb` and `avbctl`.
251* `libavb_ab/`
252    + An experimental A/B implementation for use in boot loaders and
253      AVB examples. **NOTE**: This code is *DEPRECATED* and you must
254      define `AVB_AB_I_UNDERSTAND_LIBAVB_AB_IS_DEPRECATED` to use
255      it. The code will be removed Jun 1 2018.
256* `boot_control/`
257    + An implementation of the Android `boot_control` HAL for use with
258      boot loaders using the experimental `libavb_ab` A/B stack.
259      **NOTE**: This code is *DEPRECATED* and will be removed Jun 1
260      2018.
261* `Android.bp`
262    + Build instructions for building `libavb` (a static library for use
263      on the device), host-side libraries (for unit tests), and unit
264      tests.
265* `avbtool`
266    + A tool written in Python for working with images related to
267      verified boot.
268* `test/`
269    + Unit tests for `abvtool`, `libavb`, `libavb_ab`, and
270      `libavb_atx`.
271* `tools/avbctl/`
272    + Contains the source-code for a tool that can be used to control
273      AVB at runtime in Android.
274* `examples/uefi/`
275    + Contains the source-code for a UEFI-based boot-loader utilizing
276      `libavb/` and `libavb_ab/`.
277* `examples/things/`
278    + Contains the source-code for a slot verification suitable for Android
279      Things.
280* `README.md`
281    + This file.
282* `docs/`
283    + Contains documentation files.
284
285## Portability
286
287The `libavb` code is intended to be used in bootloaders in devices
288that will load Android or other operating systems. The suggested
289approach is to copy the appropriate header and C files mentioned in
290the previous section into the boot loader and integrate as
291appropriate.
292
293As the `libavb/` codebase will evolve over time integration should be
294as non-invasive as possible. The intention is to keep the API of the
295library stable however it will be broken if necessary. As for
296portability, the library is intended to be highly portable, work on
297both little- and big-endian architectures and 32- and 64-bit. It's
298also intended to work in non-standard environments without the
299standard C library and runtime.
300
301If the `AVB_ENABLE_DEBUG` preprocessor symbol is set, the code will
302include useful debug information and run-time checks. Production
303builds should not use this. The preprocessor symbol `AVB_COMPILATION`
304should be set only when compiling the libraries. The code must be
305compiled into a separate library.
306
307Applications using the compiled `libavb` library must only include the
308`libavb/libavb.h` file (which will include all public interfaces) and
309must not have the `AVB_COMPILATION` preprocessor symbol set. This is
310to ensure that internal code that may be change in the future (for
311example `avb_sha.[ch]` and `avb_rsa.[ch]`) will not be visible to
312application code.
313
314## Versioning and Compatibility
315
316AVB uses a version number with three fields - the major, minor, and
317sub version. Here's an example version number
318
319                         1.4.3
320                         ^ ^ ^
321                         | | |
322    the major version ---+ | |
323    the minor version -----+ |
324      the sub version -------+
325
326The major version number is bumped only if compatibility is broken,
327e.g. a struct field has been removed or changed. The minor version
328number is bumped only if a new feature is introduced, for example a
329new algorithm or descriptor has been added. The sub version number is
330bumped when bugs are fixed or other changes not affecting
331compatibility are made.
332
333The `AvbVBMetaImageHeader` struct (as defined in the
334`avb_vbmeta_image.h`) carries the major and minor version number of
335`libavb` required to verify the struct in question. This is stored in
336the `required_libavb_version_major` and
337`required_libavb_version_minor` fields. Additionally this struct
338contains a textual field with the version of `avbtool` used to create
339the struct, for example "avbtool 1.4.3" or "avbtool 1.4.3 some_board
340Git-4589fbec".
341
342Note that it's entirely possible to have a `AvbVBMetaImageHeader`
343struct with
344
345    required_libavb_version_major = 1
346    required_libavb_version_minor = 0
347    avbtool_release_string = "avbtool 1.4.3"
348
349if, for example, creating an image that does not use any features
350added after AVB version 1.0.
351
352## Adding New Features
353
354If adding a new feature for example a new algorithm or a new
355descriptor then `AVB_VERSION_MINOR` in `avb_version.h` and `avbtool`
356must be bumped and `AVB_VERSION_SUB` should be set to zero.
357
358Unit tests **MUST** be added to check that
359
360* The feature is used if - and only if - suitable commands/options are
361  passed to `avbtool`.
362* The `required_version_minor` field is set to the bumped value if -
363  and only if - the feature is used. Also add tests to check that the
364  correct value is output when `--print_required_libavb_version` is
365  used.
366
367If `AVB_VERSION_MINOR` has already been bumped since the last release
368there is obviously no need to bump it again.
369
370## Using avbtool
371
372The content for the vbmeta partition can be generated as follows:
373
374    $ avbtool make_vbmeta_image                                                    \
375        [--output OUTPUT]                                                          \
376        [--algorithm ALGORITHM] [--key /path/to/key_used_for_signing_or_pub_key]   \
377        [--public_key_metadata /path/to/pkmd.bin]                                  \
378        [--rollback_index NUMBER] [--rollback_index_location NUMBER]               \
379        [--include_descriptors_from_image /path/to/image.bin]                      \
380        [--setup_rootfs_from_kernel /path/to/image.bin]                            \
381        [--chain_partition part_name:rollback_index_location:/path/to/key1.bin]    \
382        [--signing_helper /path/to/external/signer]                                \
383        [--signing_helper_with_files /path/to/external/signer_with_files]          \
384        [--print_required_libavb_version]                                          \
385        [--append_to_release_string STR]
386
387An integrity footer containing the hash for an entire partition can be
388added to an existing image as follows:
389
390    $ avbtool add_hash_footer                                                      \
391        --partition_name PARTNAME --partition_size SIZE                            \
392        [--image IMAGE]                                                            \
393        [--algorithm ALGORITHM] [--key /path/to/key_used_for_signing_or_pub_key]   \
394        [--public_key_metadata /path/to/pkmd.bin]                                  \
395        [--rollback_index NUMBER] [--rollback_index_location NUMBER]               \
396        [--hash_algorithm HASH_ALG] [--salt HEX]                                   \
397        [--include_descriptors_from_image /path/to/image.bin]                      \
398        [--setup_rootfs_from_kernel /path/to/image.bin]                            \
399        [--output_vbmeta_image OUTPUT_IMAGE] [--do_not_append_vbmeta_image]        \
400        [--signing_helper /path/to/external/signer]                                \
401        [--signing_helper_with_files /path/to/external/signer_with_files]          \
402        [--print_required_libavb_version]                                          \
403        [--append_to_release_string STR]                                           \
404        [--calc_max_image_size]                                                    \
405        [--do_not_use_ab]                                                          \
406        [--use_persistent_digest]
407
408Valid values for `HASH_ALG` above include `sha1` and `sha256`.
409
410An integrity footer containing the root digest and salt for a hashtree
411for a partition can be added to an existing image as follows. The
412hashtree is also appended to the image.
413
414    $ avbtool add_hashtree_footer                                                  \
415        --partition_name PARTNAME --partition_size SIZE                            \
416        [--image IMAGE]                                                            \
417        [--algorithm ALGORITHM] [--key /path/to/key_used_for_signing_or_pub_key]   \
418        [--public_key_metadata /path/to/pkmd.bin]                                  \
419        [--rollback_index NUMBER] [--rollback_index_location NUMBER]               \
420        [--hash_algorithm HASH_ALG] [--salt HEX] [--block_size SIZE]               \
421        [--include_descriptors_from_image /path/to/image.bin]                      \
422        [--setup_rootfs_from_kernel /path/to/image.bin]                            \
423        [--setup_as_rootfs_from_kernel]                                            \
424        [--output_vbmeta_image OUTPUT_IMAGE] [--do_not_append_vbmeta_image]        \
425        [--do_not_generate_fec] [--fec_num_roots FEC_NUM_ROOTS]                    \
426        [--signing_helper /path/to/external/signer]                                \
427        [--signing_helper_with_files /path/to/external/signer_with_files]          \
428        [--print_required_libavb_version]                                          \
429        [--append_to_release_string STR]                                           \
430        [--calc_max_image_size]                                                    \
431        [--do_not_use_ab]                                                          \
432        [--no_hashtree]                                                            \
433        [--use_persistent_digest]                                                  \
434        [--check_at_most_once]
435
436Valid values for `HASH_ALG` above include `sha1`, `sha256`, and `blake2b-256`.
437
438The size of an image with integrity footers can be changed using the
439`resize_image` command:
440
441    $ avbtool resize_image                                                         \
442        --image IMAGE                                                              \
443        --partition_size SIZE
444
445The integrity footer on an image can be removed from an image. The
446hashtree can optionally be kept in place.
447
448    $ avbtool erase_footer --image IMAGE [--keep_hashtree]
449
450For hash- and hashtree-images the vbmeta struct can also be written to
451an external file via the `--output_vbmeta_image` option and one can
452also specify that the vbmeta struct and footer not be added to the
453image being operated on.
454
455The hashtree and FEC data in an image can be zeroed out with the following
456command:
457
458    $ avbtool zero_hashtree --image IMAGE
459
460This is useful for trading compressed image size for having to reculculate the
461hashtree and FEC at runtime. If this is done the hashtree and FEC data is set
462to zero except for the first eight bytes which are set to the magic
463`ZeRoHaSH`. Either the hashtree or FEC data or both may be zeroed this way
464so applications should check for the magic both places. Applications can
465use the magic to detect if recalculation is needed.
466
467To calculate the maximum size of an image that will fit in a partition
468of a given size after having used the `avbtool add_hash_footer` or
469`avbtool add_hashtree_footer` commands on it, use the
470`--calc_max_image_size` option:
471
472    $ avbtool add_hash_footer --partition_size $((10*1024*1024)) \
473        --calc_max_image_size
474    10416128
475
476    $ avbtool add_hashtree_footer --partition_size $((10*1024*1024)) \
477        --calc_max_image_size
478    10330112
479
480To calculate the required libavb version that would be put in the
481vbmeta struct when using `make_vbmeta_image`, `add_hash_footer`, and
482`add_hashtree_footer` commands use the
483`--print_required_libavb_version` option:
484
485    $ avbtool make_vbmeta_image \
486        --algorithm SHA256_RSA2048 --key /path/to/key.pem \
487        --include_descriptors_from_image /path/to/boot.img \
488        --include_descriptors_from_image /path/to/system.img \
489        --print_required_libavb_version
490    1.0
491
492Alternatively, `--no_hashtree` can be used with `avbtool add_hashtree_footer`
493command. If `--no_hashtree` is given, the hashtree blob is omitted and only
494its descriptor is added to the vbmeta struct. The descriptor says the size
495of hashtree is 0, which tells an application the need to recalculate
496hashtree.
497
498The `--signing_helper` option can be used in `make_vbmeta_image`,
499`add_hash_footer` and `add_hashtree_footer` commands to specify any
500external program for signing hashes. The data to sign (including
501padding e.g. PKCS1-v1.5) is fed via `STDIN` and the signed data is
502returned via `STDOUT`. If `--signing_helper` is present in a command
503line, the `--key` option need only contain a public key. Arguments for
504a signing helper are `algorithm` and `public key`. If the signing
505helper exits with a non-zero exit code, it means failure.
506
507Here's an example invocation:
508
509    /path/to/my_signing_program SHA256_RSA2048 /path/to/publickey.pem
510
511The `--signing_helper_with_files` is similar to `--signing_helper`
512except that a temporary file is used to communicate with the helper
513instead of `STDIN` and `STDOUT`. This is useful in situations where
514the signing helper is using code which is outputting diagnostics on
515`STDOUT` instead of `STDERR`. Here's an example invocation
516
517    /path/to/my_signing_program_with_files SHA256_RSA2048 \
518      /path/to/publickey.pem /tmp/path/to/communication_file
519
520where the last positional argument is a file that contains the data to
521sign. The helper should write the signature in this file.
522
523The `append_vbmeta_image` command can be used to append an entire
524vbmeta blob to the end of another image. This is useful for cases when
525not using any vbmeta partitions, for example:
526
527    $ cp boot.img boot-with-vbmeta-appended.img
528    $ avbtool append_vbmeta_image                       \
529        --image boot-with-vbmeta-appended.img           \
530        --partition_size SIZE_OF_BOOT_PARTITION         \
531        --vbmeta_image vbmeta.img
532    $ fastboot flash boot boot-with-vbmeta-appended.img
533
534Information about an image can be obtained using the `info_image` command. The
535output of this command should not be relied on and the way information is
536structured may change.
537
538The `verify_image` command can be used to verify the contents of
539several image files at the same time. When invoked on an image the
540following checks are performed:
541
542* If the image has a VBMeta struct the signature is checked against
543  the embedded public key. If the image doesn't look like `vbmeta.img`
544  then a footer is looked for and used if present.
545
546* If the option `--key` is passed then a `.pem` file is expected and
547  it's checked that the embedded public key in said VBMeta struct
548  matches the given key.
549
550* All descriptors in the VBMeta struct are checked in the following
551  way:
552    + For a hash descriptor the image file corresponding to the
553      partition name is loaded and its digest is checked against that
554      in the descriptor.
555    + For a hashtree descriptor the image file corresponding to the
556      partition name is loaded and the hashtree is calculated and its
557      root digest compared to that in the descriptor.
558    + For a chained partition descriptor its contents is compared
559      against content that needs to be passed in via the
560      `--expected_chain_partition` options. The format for this option
561      is similar to that of the `--chain_partition` option. If there
562      is no `--expected_chain_partition` descriptor for the chain
563      partition descriptor the check fails.
564
565Here's an example for a setup where the digests for `boot.img` and
566`system.img` are stored in `vbmeta.img` which is signed with
567`my_key.pem`. It also checks that the chain partition for partition
568`foobar` uses rollback index 8 and that the public key in AVB format
569matches that of the file `foobar_vendor_key.avbpubkey`:
570
571    $ avbtool verify_image \
572         --image /path/to/vbmeta.img \
573         --key my_key.pem \
574         --expect_chained_partition foobar:8:foobar_vendor_key.avbpubkey
575
576    Verifying image /path/to/vbmeta.img using key at my_key.pem
577    vbmeta: Successfully verified SHA256_RSA4096 vbmeta struct in /path_to/vbmeta.img
578    boot: Successfully verified sha256 hash of /path/to/boot.img for image of 10543104 bytes
579    system: Successfully verified sha1 hashtree of /path/to/system.img for image of 1065213952 bytes
580    foobar: Successfully verified chain partition descriptor matches expected data
581
582In this example the `verify_image` command verifies the files
583`vbmeta.img`, `boot.img`, and `system.img` in the directory
584`/path/to`. The directory and file extension of the given image
585(e.g. `/path/to/vbmeta.img`) is used together with the partition name
586in the descriptor to calculate the filenames of the images holding
587hash and hashtree images.
588
589The `verify_image` command can also be used to check that a custom
590signing helper works as intended.
591
592The `calculate_vbmeta_digest` command can be used to calculate the vbmeta digest
593of several image files at the same time. The result is printed as a hexadecimal
594string either on `STDOUT` or a supplied path (using the `--output` option).
595
596    $ avbtool calculate_vbmeta_digest \
597         --hash_algorithm sha256 \
598         --image /path/to/vbmeta.img
599    a20fdd01a6638c55065fe08497186acde350d6797d59a55d70ffbcf41e95c2f5
600
601In this example the `calculate_vbmeta_digest` command loads the `vbmeta.img`
602file. If this image has one or more chain partition descriptors, the same logic
603as the `verify_image` command is used to load files for these (e.g. it assumes
604the same directory and file extension as the given image). Once all vbmeta
605structs have been loaded, the digest is calculated (using the hash algorithm
606given by the `--hash_algorithm` option) and printed out.
607
608To print hash and hashtree digests embedded in the verified metadata, use the
609`print_partition_digests` command like this:
610
611    $ avbtool print_partition_digests --image /path/to/vbmeta.img
612    system: ddaa513715fd2e22f3c1cea3c1a1f98ccb515fc6
613    boot: 5cba9a418e04b5f9e29ee6a250f6cdbe30c6cec867c59d388f141c3fedcb28c1
614    vendor: 06993a9e85e46e53d3892881bb75eff48ecadaa8
615
616For partitions with hash descriptors, this prints out the digest and for
617partitions with hashtree descriptors the root digest is printed out. Like the
618`calculate_vbmeta_digest` and `verify_image` commands, chain partitions are
619followed. To use JSON for the output, use the `--json` option.
620
621In case you would like to log all command lines for all avbtool invocations for
622debugging integrations with other tooling, you can configure the envirionment
623variable AVB_INVOCATION_LOGFILE with the name of the log file:
624
625    $ export AVB_INVOCATION_LOGFILE='/tmp/avb_invocation.log'
626    $ ./avbtool.py version
627    $ ./avbtool.py version
628    $ cat /tmp/avb_invocation.log
629    ./avbtool.py version
630    ./avbtool.py version
631
632
633## Build System Integration
634
635In Android, AVB is enabled by the `BOARD_AVB_ENABLE` variable
636
637    BOARD_AVB_ENABLE := true
638
639This will make the build system create `vbmeta.img` which will contain
640a hash descriptor for `boot.img`, a hashtree descriptor for
641`system.img`, a kernel-cmdline descriptor for setting up `dm-verity`
642for `system.img` and append a hash-tree to `system.img`. If the build
643system is set up such that one or many of `vendor.img` / `product.img`
644/ `system_ext.img` / `odm.img` are being built, the hash-tree for each
645of them will also be appended to the image respectively, and their
646hash-tree descriptors will be included into `vbmeta.img` accordingly.
647
648By default, the algorithm `SHA256_RSA4096` is used with a test key
649from the `external/avb/test/data` directory. This can be overriden by
650the `BOARD_AVB_ALGORITHM` and `BOARD_AVB_KEY_PATH` variables to use
651e.g. a 4096-bit RSA key and SHA-512:
652
653    BOARD_AVB_ALGORITHM := SHA512_RSA4096
654    BOARD_AVB_KEY_PATH := /path/to/rsa_key_4096bits.pem
655
656Remember that the public part of this key needs to be available to the
657bootloader of the device expected to verify resulting images. Use
658`avbtool extract_public_key` to extract the key in the expected format
659(`AVB_pk` in the following). If the device is using a different root
660of trust than `AVB_pk` the `--public_key_metadata` option can be used
661to embed a blob (`AVB_pkmd` in the following) that can be used to
662e.g. derive `AVB_pk`. Both `AVB_pk` and `AVB_pkmd` are passed to the
663`validate_vbmeta_public_key()` operation when verifying a slot.
664
665Some devices may support the end-user configuring the root of trust to use, see
666the [Device Specific Notes](#Device-Specific-Notes) section for details.
667
668Devices can be configured to create additional `vbmeta` partitions as
669[chained partitions](#The-VBMeta-struct) in order to update a subset of
670partitions without changing the top-level `vbmeta` partition. For example,
671the following variables create `vbmeta_system.img` as a chained `vbmeta`
672image that contains the hash-tree descriptors for `system.img`, `system_ext.img`
673and `product.img`. `vbmeta_system.img` itself will be signed by the specified
674key and algorithm.
675
676    BOARD_AVB_VBMETA_SYSTEM := system system_ext product
677    BOARD_AVB_VBMETA_SYSTEM_KEY_PATH := external/avb/test/data/testkey_rsa2048.pem
678    BOARD_AVB_VBMETA_SYSTEM_ALGORITHM := SHA256_RSA2048
679    BOARD_AVB_VBMETA_SYSTEM_ROLLBACK_INDEX_LOCATION := 1
680
681Note that the hash-tree descriptors for `system.img`, `system_ext.img` and
682`product.img` will be included only in `vbmeta_system.img`, but not
683`vbmeta.img`. With the above setup, partitions `system.img`, `system_ext.img`,
684`product.img` and `vbmeta_system.img` can be updated independently - but as a
685group - of the rest of the partitions, *or* as part of the traditional updates
686that update all the partitions.
687
688Currently build system supports building chained `vbmeta` images of
689`vbmeta_system.img` (`BOARD_AVB_VBMETA_SYSTEM`) and `vbmeta_vendor.img`
690(`BOARD_AVB_VBMETA_VENDOR`).
691
692To prevent rollback attacks, the rollback index should be increased on
693a regular basis. The rollback index can be set with the
694`BOARD_AVB_ROLLBACK_INDEX` variable:
695
696     BOARD_AVB_ROLLBACK_INDEX := 5
697
698If this is not set, the rollback index defaults to 0.
699
700The variable `BOARD_AVB_MAKE_VBMETA_IMAGE_ARGS` can be used to specify
701additional options passed to `avbtool make_vbmeta_image`. Typical
702options to be used here include `--prop`, `--prop_from_file`,
703`--chain_partition`, `--public_key_metadata`, and `--signing_helper`.
704
705The variable `BOARD_AVB_BOOT_ADD_HASH_FOOTER_ARGS` can be used to
706specify additional options passed to `avbtool add_hash_footer` for
707`boot.img`. Typical options to be used here include `--hash_algorithm`
708and `--salt`.
709
710The variable `BOARD_AVB_SYSTEM_ADD_HASHTREE_FOOTER_ARGS` can be used
711to specify additional options passed to `avbtool add_hashtree_footer`
712for `system.img`. Typical options to be used here include
713`--hash_algorithm`, `--salt`, `--block_size`, and
714`--do_not_generate_fec`.
715
716The variable `BOARD_AVB_VENDOR_ADD_HASHTREE_FOOTER_ARGS` can be used
717to specify additional options passed to `avbtool add_hashtree_footer`
718for `vendor.img`. Typical options to be used here include
719`--hash_algorithm`, `--salt`, `--block_size`, and
720`--do_not_generate_fec`.
721
722The variable `BOARD_AVB_DTBO_ADD_HASH_FOOTER_ARGS` can be used to
723specify additional options passed to `avbtool add_hash_footer` for
724`dtbo.img`. Typical options to be used here include `--hash_algorithm`
725and `--salt`.
726
727Build system variables (such as `PRODUCT_SUPPORTS_VERITY_FEC`) used
728for previous version of Verified Boot in Android are not used in AVB.
729
730A/B related build system variables can be found [here](https://source.android.com/devices/tech/ota/ab_updates#build-variables).
731
732# Device Integration
733
734This section discusses recommendations and best practices for
735integrating `libavb` with a device boot loader. It's important to
736emphasize that these are just recommendations so the use of the word
737`must` should be taken lightly.
738
739Additionally term *HLOS* is used in this chapter to refer to the *High
740Level Operating System*. This obviously includes Android (including
741other form-factors than phones) but could also be other operating
742systems.
743
744## System Dependencies
745
746The `libavb` library is written in a way so it's portable to any
747system with a C99 compiler. It does not require the standard C library
748however the boot loader must implement a simple set of system
749primitives required by `libavb` such as `avb_malloc()`, `avb_free()`,
750and `avb_print()`.
751
752In addition to the system primitives, `libavb` interfaces with the boot
753loader through the supplied `AvbOps` struct. This includes operations
754to read and write data from partitions, read and write rollback
755indexes, check if the public key used to make a signature should be
756accepted, and so on.
757
758## Locked and Unlocked mode
759
760AVB has been designed to support the notion of the device being either
761LOCKED state or UNLOCKED state as used in Android.
762
763In the context of AVB, the LOCKED state means that verification errors
764are fatal whereas in UNLOCKED state they are not. If the device is
765UNLOCKED pass `AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR` flag in
766the `flags` parameter of `avb_slot_verify()` and treat verification
767errors including
768
769* `AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED`
770* `AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION`
771* `AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX`
772
773as non-fatal. If the device is in the LOCKED state, don't pass the
774`AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR` flag in the `flags`
775parameter of `avb_slot_verify()` and only treat
776`AVB_SLOT_VERIFY_RESULT_OK` as non-fatal.
777
778On Android, device state may be altered through the fastboot interface
779using, e.g. `fastboot flashing lock` (to transition to the LOCKED
780state) and `fastboot flashing unlock` (to transition to the UNLOCKED
781state).
782
783The device must only allow state transitions (e.g. from LOCKED to
784UNLOCKED or UNLOCKED to LOCKED) after asserting physical presence of
785the user. If the device has a display and buttons this is typically
786done by showing a dialog and requiring the user to confirm or cancel
787using physical buttons.
788
789All user data must be cleared when transitioning from the LOCKED to
790the UNLOCKED state (including the `userdata` partition and any NVRAM
791spaces). Additionally all `stored_rollback_index[n]` locations must be
792cleared (all elements must be set to zero). Similar action (erasing
793`userdata`, NVRAM spaces, and `stored_rollback_index[n]` locations)
794shall also happening when transitioning from UNLOCKED to LOCKED. If
795the device is required to use full disk encryption, then a less
796intensive wipe is required for UNLOCKED to LOCKED. Depending on the
797device form-factor and intended use, the user should be prompted to
798confirm before any data is erased.
799
800## Tamper-evident Storage
801
802In this document, *tamper-evident* means that it's possible to detect
803if the HLOS has tampered with the data, e.g. if it has been
804overwritten.
805
806Tamper-evident storage must be used for stored rollback indexes, keys
807used for verification, device state (whether the device is LOCKED or
808UNLOCKED), and named persistent values. If tampering has been detected
809the corresponding `AvbOps` operation should fail by e.g. returning
810`AVB_IO_RESULT_ERROR_IO`. It is especially important that verification
811keys cannot be tampered with since they represent the root-of-trust.
812
813If verification keys are mutable they must only be set by the end
814user, e.g. it must never be set at the factory or store or any
815intermediate point before the end user. Additionally, it must only be
816possible to set or clear a key while the device is in the UNLOCKED
817state.
818
819## Named Persistent Values
820
821AVB 1.1 introduces support for named persistent values which must be
822tamper evident and allows AVB to store arbitrary key-value pairs.
823Integrators may limit support for these values to a set of fixed
824well-known names, a maximum value size, and / or a maximum number of
825values.
826
827## Persistent Digests
828
829Using a persistent digest for a partition means the digest (or root
830digest in the case of a hashtree) is not stored in the descriptor but
831is stored in a named persistent value. This allows configuration data
832which may differ from device to device to be verified by AVB. It must
833not be possible to modify the persistent digest when the device is in
834the LOCKED state, except if a digest does not exist it may be initialized.
835
836To specify that a descriptor should use a persistent digest, use the
837`--use_persistent_digest` option for the `add_hash_footer` or
838`add_hashtree_footer` avbtool operations. Then, during verification of
839the descriptor, AVB will look for the digest in the named persistent
840value `avb.persistent_digest.$(partition_name)` instead of in the
841descriptor itself.
842
843For hashtree descriptors using a persistent digest, the digest value
844will be available for substitution into kernel command line descriptors
845using a token of the form `$(AVB_FOO_ROOT_DIGEST)` where 'FOO' is the
846uppercase partition name, in this case for the partition named 'foo'.
847The token will be replaced by the digest in hexadecimal form.
848
849By default, when the `--use_persistent_digest` option is used with
850`add_hash_footer` or `add_hashtree_footer`, avbtool will generate a
851descriptor with no salt rather than the typical default of generating a
852random salt equal to the digest length. This is because the digest
853value is stored in persistent storage and thus cannot change over time.
854An alternative option would be to manually provide a random salt using
855`--salt`, but this salt would need to remain unchanged for the life
856of the device once the persistent digest value was written.
857
858## Updating Stored Rollback Indexes
859
860In order for Rollback Protection to work the bootloader will need to
861update the `stored_rollback_indexes[n]` array on the device prior to
862transferring control to the HLOS. If not using A/B this is
863straightforward - just update it to what's in the AVB metadata for the
864slot before booting. In pseudo-code it would look like this:
865
866```c++
867// The |slot_data| parameter should be the AvbSlotVerifyData returned
868// by avb_slot_verify() for the slot we're about to boot.
869//
870bool update_stored_rollback_indexes_for_slot(AvbOps* ops,
871                                             AvbSlotVerifyData* slot_data) {
872    for (int n = 0; n < AVB_MAX_NUMBER_OF_ROLLBACK_INDEX_LOCATIONS; n++) {
873        uint64_t rollback_index = slot_data->rollback_indexes[n];
874        if (rollback_index > 0) {
875            AvbIOResult io_ret;
876            uint64_t current_stored_rollback_index;
877
878            io_ret = ops->read_rollback_index(ops, n, &current_stored_rollback_index);
879            if (io_ret != AVB_IO_RESULT_OK) {
880                return false;
881            }
882
883            if (rollback_index > current_stored_rollback_index) {
884                io_ret = ops->write_rollback_index(ops, n, rollback_index);
885                if (io_ret != AVB_IO_RESULT_OK) {
886                    return false;
887                }
888            }
889        }
890    }
891    return true;
892}
893```
894
895However if using A/B more care must be taken to still allow the device
896to fall back to the old slot if the update didn't work.
897
898For an HLOS like Android where rollback is only supported if the
899updated OS version is found to not work, `stored_rollback_index[n]`
900should only be updated from slots that are marked as SUCCESSFUL in the
901A/B metadata. The pseudo-code for that is as follows where
902`is_slot_is_marked_as_successful()` comes from the A/B stack in use:
903
904```c++
905if (is_slot_is_marked_as_successful(slot->ab_suffix)) {
906    if (!update_stored_rollback_indexes_for_slot(ops, slot)) {
907        // TODO: handle error.
908    }
909}
910```
911
912This logic should ideally be implemented outside of the HLOS. One
913possible implementation is to update rollback indices in the
914bootloader when booting into a successful slot. This means that
915when booting into a new OS not yet marked as successful, the
916rollback indices would not be updated. The first reboot after the
917slot succeeded would trigger an update of the rollback indices.
918
919For an HLOS where it's possible to roll back to a previous version,
920`stored_rollback_index[n]` should be set to the largest possible value
921allowing all bootable slots to boot. This approach is implemented in
922AVB's experimental (and now deprecated) A/B stack `libavb_ab`, see the
923`avb_ab_flow()` implementation. Note that this requires verifying
924*all* bootable slots at every boot and this may impact boot time.
925
926## Recommended Bootflow
927
928The recommended boot flow for a device using AVB is as follows:
929
930![Recommended AVB boot flow](docs/avb-recommended-boot-flow.png)
931
932Notes:
933
934* The device is expected to search through all A/B slots until it
935  finds a valid OS to boot. Slots that are rejected in the LOCKED
936  state might not be rejected in the UNLOCKED state, (e.g. when
937  UNLOCKED any key can be used and rollback index failures are
938  allowed), so the algorithm used for selecting a slot varies
939  depending on what state the device is in.
940
941* If no valid OS (that is, no bootable A/B slot) can be found, the
942  device cannot boot and has to enter repair mode. It is
943  device-dependent what this looks like.  If the device has a screen
944  it must convey this state to the user.
945
946* If the device is LOCKED, only an OS signed by an embedded
947  verification key (see the previous section) shall be
948  accepted. Additionally, `rollback_index[n]` as stored in the
949  verified image must be greater or equal than what's in
950  `stored_rollback_index[n]` on the device (for all `n`) and the
951  `stored_rollback_index[n]` array is expected to be updated as
952  specified in the previous section.
953    + If the key used for verification was set by the end user, and
954      the device has a screen, it must show a warning with the key
955      fingerprint to convey that the device is booting a custom
956      OS. The warning must be shown for at least 10 seconds before the
957      boot process continues. If the device does not have a screen,
958      other ways must be used to convey that the device is booting a
959      custom OS (lightbars, LEDs, etc.).
960
961* If the device is UNLOCKED, there is no requirement to check the key
962  used to sign the OS nor is there any requirement to check or update
963  rollback `stored_rollback_index[n]` on the device. Because of this
964  the user must always be shown a warning about verification not
965  occurring.
966    + It is device-dependent how this is implemented since it depends
967      on the device form-factor and intended usage. If the device has
968      a screen and buttons (for example if it's a phone) the warning
969      is to be shown for at least 10 seconds before the boot process
970      continues. If the device does not have a screen, other ways must
971      be used to convey that the device is UNLOCKED (lightbars, LEDs,
972      etc.).
973
974### Booting Into Recovery
975
976On Android devices not using A/B, the `recovery` partition usually isn't
977updated along with other partitions and therefore can't be referenced
978from the main `vbmeta` partition.
979
980It's still possible to use AVB to protect this partition (and others)
981by signing these partitions and passing the
982`AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION` flag to `avb_slot_verify()`.
983In this mode, the key used to sign each requested partition is verified
984by the `validate_public_key_for_partition()` operation which is also
985used to return the rollback index location to be used.
986
987## Handling dm-verity Errors
988
989By design, hashtree verification errors are detected by the HLOS and
990not the bootloader. AVB provides a way to specify how the error should
991be handled through the `hashtree_error_mode` parameter in the
992`avb_slot_verify()` function. Possible values include
993
994* `AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE` means that the HLOS
995  will invalidate the current slot and restart. On devices with A/B
996  this would lead to attempting to boot the other slot (if it's marked
997  as bootable) or it could lead to a mode where no OS can be booted
998  (e.g. some form of repair mode). In Linux this requires a kernel
999  built with `CONFIG_DM_VERITY_AVB`.
1000
1001* `AVB_HASHTREE_ERROR_MODE_RESTART` means that the OS will restart
1002  without the current slot being invalidated. Be careful using this
1003  mode unconditionally as it may introduce boot loops if the same
1004  hashtree verification error is hit on every boot.
1005
1006* `AVB_HASHTREE_ERROR_MODE_EIO` means that an `EIO` error will be
1007  returned to the application.
1008
1009* `AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO` means that either the **RESTART**
1010  or **EIO** mode is used, depending on state. This mode implements a state
1011  machine whereby **RESTART** is used by default and when the
1012  `AVB_SLOT_VERIFY_FLAGS_RESTART_CAUSED_BY_HASHTREE_CORRUPTION` is passed to
1013  `avb_slot_verify()` the mode transitions to **EIO**. When a new OS has been
1014  detected the device transitions back to the **RESTART** mode.
1015    + To do this persistent storage is needed - specifically this means that the
1016      passed in `AvbOps` will need to have the `read_persistent_value()` and
1017      `write_persistent_value()` operations implemented. The name of the
1018      persistent value used is **avb.managed_verity_mode** and 32 bytes of storage
1019      is needed.
1020
1021* `AVB_HASHTREE_ERROR_MODE_LOGGING` means that errors will be logged
1022   and corrupt data may be returned to applications. This mode should
1023   be used for **ONLY** diagnostics and debugging. It cannot be used
1024   unless verification errors are allowed.
1025
1026* `AVB_HASHTREE_ERROR_MODE_PANIC` means that the OS will **panic** without
1027  the current slot being invalidated. Be careful using this mode as it may
1028  introduce boot panic if the same hashtree verification error is hit on
1029  every boot. This mode is available since: 1.7.0 (kernel 5.9)
1030
1031The value passed in `hashtree_error_mode` is essentially just passed on through
1032to the HLOS through the the `androidboot.veritymode`,
1033`androidboot.veritymode.managed`, and `androidboot.vbmeta.invalidate_on_error`
1034kernel command-line parameters in the following way:
1035
1036|      | `androidboot.veritymode` | `androidboot.veritymode.managed` | `androidboot.vbmeta.invalidate_on_error` |
1037|------|:------------------------:|:--------------------------------:|:----------------------------------------:|
1038| `AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE` | **enforcing** | (unset) | **yes** |
1039| `AVB_HASHTREE_ERROR_MODE_RESTART` | **enforcing** | (unset) | (unset) |
1040| `AVB_HASHTREE_ERROR_MODE_EIO` | **eio** | (unset) | (unset) |
1041| `AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO` | **eio** or **enforcing** | **yes** | (unset) |
1042| `AVB_HASHTREE_ERROR_MODE_LOGGING` | **ignore_corruption** | (unset) | (unset) |
1043| `AVB_HASHTREE_ERROR_MODE_PANIC` | **panicking** | (unset) | (unset) |
1044
1045The only exception to this table is that if the
1046`AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED` flag is set in the top-level vbmeta,
1047then `androidboot.veritymode` is set to **disabled** and
1048`androidboot.veritymode.managed` and `androidboot.vbmeta.invalidate_on_error`
1049are unset.
1050
1051The different values of `hashtree_error_mode` parameter in the `avb_slot_verify()`
1052function can be categorized into three groups:
1053
1054* `AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE`, which needs `CONFIG_DM_VERITY_AVB`
1055  in the kernel config for the kernel to invalidate the current slot and
1056  restart. This is kept here for legacy Android Things devices and is not
1057  recommended for other device form factors.
1058
1059* The bootloader handles the switch between `AVB_HASHTREE_ERROR_MODE_RESTART`
1060  and `AVB_HASHTREE_ERROR_MODE_EIO`. This would need a persistent storage on the
1061  device to store the vbmeta digest, so the bootloader can detect if a device
1062  ever gets an update or not. Once the new OS is installed and if the device is
1063  in **EIO** mode, the bootloader should switch back to **RESTART** mode.
1064
1065* `AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO`: `libavb` helps the
1066  bootloader manage **EIO**/**RESTART** state transition. The bootloader needs
1067  to implement the callbacks of `AvbOps->read_persistent_value()` and
1068  `AvbOps->write_persistent_value()` for `libavb` to store the vbmeta digest to
1069  detect whether a new OS is installed.
1070
1071### Which mode should I use for my device?
1072
1073This depends entirely on the device, how the device is intended to be
1074used, and the desired user experience.
1075
1076For Android devices the `AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO` mode
1077should be used. Also see the [Boot Flow section on source.android.com](https://source.android.com/security/verifiedboot/boot-flow) for the kind of UX and UI the boot loader should implement.
1078
1079If the device doesn't have a screen or if the HLOS supports multiple bootable
1080slots simultaneously it may make more sense to just use
1081`AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE`.
1082
1083## Android Specific Integration
1084
1085On Android, the boot loader must set the
1086`androidboot.verifiedbootstate` parameter on the kernel command-line
1087to indicate the boot state. It shall use the following values:
1088
1089* **green**: If in LOCKED state and the key used for verification was not set by the end user.
1090* **yellow**: If in LOCKED state and the key used for verification was set by the end user.
1091* **orange**: If in the UNLOCKED state.
1092
1093## GKI 2.0 Integration
1094
1095Starting from Android 12, devices launching with kernel version 5.10 or higher
1096must ship with the GKI kernel. See [GKI 2.0](https://source.android.com/devices/architecture/kernel/generic-kernel-image#gki2)
1097for details.
1098
1099While incorporating a certified GKI `boot.img` into a device codebase, the
1100following board variables should be configured. The setting shown below is just
1101an example to be adjusted per device.
1102
1103```
1104# Uses a prebuilt boot.img
1105TARGET_NO_KERNEL := true
1106BOARD_PREBUILT_BOOTIMAGE := device/${company}/${board}/boot.img
1107
1108# Enables chained vbmeta for the boot.img so it can be updated independently,
1109# without updating the vbmeta.img. The following configs are optional.
1110# When they're absent, the hash of the boot.img will be stored then signed in
1111# the vbmeta.img.
1112BOARD_AVB_BOOT_KEY_PATH := external/avb/test/data/testkey_rsa4096.pem
1113BOARD_AVB_BOOT_ALGORITHM := SHA256_RSA4096
1114BOARD_AVB_BOOT_ROLLBACK_INDEX := $(PLATFORM_SECURITY_PATCH_TIMESTAMP)
1115BOARD_AVB_BOOT_ROLLBACK_INDEX_LOCATION := 2
1116```
1117
1118**NOTE**: The certified GKI `boot.img` isn't signed for verified boot.
1119A device-specific verified boot chain should still be configured for a prebuilt
1120GKI `boot.img`.
1121
1122## Device Specific Notes
1123
1124This section contains information about how AVB is integrated into specific
1125devices. This is not an exhaustive list.
1126
1127### Pixel 2 and later
1128
1129On the Pixel 2, Pixel 2 XL and later Pixel models, the boot loader supports a
1130virtual partition with the name `avb_custom_key`. Flashing and erasing this
1131partition only works in the UNLOCKED state. Setting the custom key is done like
1132this:
1133
1134    avbtool extract_public_key --key key.pem --output pkmd.bin
1135    fastboot flash avb_custom_key pkmd.bin
1136
1137Erasing the key is done by erasing the virtual partition:
1138
1139    fastboot erase avb_custom_key
1140
1141When the custom key is set and the device is in the LOCKED state it will boot
1142images signed with both the built-in key as well as the custom key. All other
1143security features (including rollback-protection) are in effect, e.g. the
1144**only** difference is the root of trust to use.
1145
1146When booting an image signed with a custom key, a yellow screen will be shown as
1147part of the boot process to remind the user that the custom key is in use.
1148
1149# Version History
1150
1151### Version 1.2
1152
1153Version 1.2 adds support for the following:
1154* `rollback_index_location` field of the main vbmeta header.
1155* `check_at_most_once` parameter of dm-verity in a hashtree descriptor.
1156
1157### Version 1.1
1158
1159Version 1.1 adds support for the following:
1160
1161* A 32-bit `flags` element is added to hash and hashtree descriptors.
1162* Support for partitions which don't use [A/B](#A_B-Support).
1163* Tamper-evident [named persistent values](#Named-Persistent-Values).
1164* [Persistent digests](#Persistent-Digests) for hash or hashtree descriptors.
1165
1166### Version 1.0
1167
1168All features not explicitly listed under a later version are supported by 1.0.
1169