• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..--

boot_control/23-Nov-2023-171122

docs/23-Nov-2023-

examples/23-Nov-2023-1,8501,248

libavb/23-Nov-2023-8,2224,855

libavb_ab/23-Nov-2023-926485

libavb_aftl/23-Nov-2023-2,1471,445

libavb_atx/23-Nov-2023-727443

libavb_user/23-Nov-2023-1,016599

proto/23-Nov-2023-2,1411,864

test/23-Nov-2023-15,17512,175

tools/23-Nov-2023-1,3831,017

.clang-formatD23-Nov-2023884 2725

.gitignoreD23-Nov-20239 21

Android.bpD23-Nov-202311.6 KiB514487

LICENSED23-Nov-20233.2 KiB6452

METADATAD23-Nov-202339 43

MODULE_LICENSE_APACHE2D23-Nov-20230

MODULE_LICENSE_BSDD23-Nov-20230

MODULE_LICENSE_MITD23-Nov-20230

OWNERSD23-Nov-2023114 76

PREUPLOAD.cfgD23-Nov-2023165 86

README.mdD23-Nov-202352.3 KiB1,129908

TEST_MAPPINGD23-Nov-2023128 1110

aftltoolD23-Nov-202381.9 KiB2,2551,797

aftltool.pyD23-Nov-202381.9 KiB2,2551,797

aftltool_integration_test.pyD23-Nov-20233.1 KiB8344

aftltool_test.pyD23-Nov-202362.3 KiB1,6101,173

avbtoolD23-Nov-2023194.1 KiB4,8783,916

avbtool.pyD23-Nov-2023194.1 KiB4,8783,916

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