• Home
Name Date Size #Lines LOC

..--

boot_control/03-May-2024-171122

docs/03-May-2024-

examples/03-May-2024-1,8501,248

libavb/03-May-2024-8,2274,858

libavb_ab/03-May-2024-926485

libavb_atx/03-May-2024-727443

libavb_user/03-May-2024-1,016599

test/03-May-2024-14,39811,617

tools/03-May-2024-2,2401,656

.clang-formatD03-May-2024884 2725

.gitignoreD03-May-20249 21

Android.bpD03-May-20248.8 KiB375353

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-202452.9 KiB1,139917

TEST_MAPPINGD03-May-2024128 1110

avbtoolD03-May-2024196.2 KiB4,9263,957

avbtool.pyD03-May-2024196.2 KiB4,9263,957

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    + [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        [--check_at_most_once]
434
435Valid values for `HASH_ALG` above include `sha1`, `sha256`, and `blake2b-256`.
436
437The size of an image with integrity footers can be changed using the
438`resize_image` command:
439
440    $ avbtool resize_image                                                         \
441        --image IMAGE                                                              \
442        --partition_size SIZE
443
444The integrity footer on an image can be removed from an image. The
445hashtree can optionally be kept in place.
446
447    $ avbtool erase_footer --image IMAGE [--keep_hashtree]
448
449For hash- and hashtree-images the vbmeta struct can also be written to
450an external file via the `--output_vbmeta_image` option and one can
451also specify that the vbmeta struct and footer not be added to the
452image being operated on.
453
454The hashtree and FEC data in an image can be zeroed out with the following
455command:
456
457    $ avbtool zero_hashtree --image IMAGE
458
459This is useful for trading compressed image size for having to reculculate the
460hashtree and FEC at runtime. If this is done the hashtree and FEC data is set
461to zero except for the first eight bytes which are set to the magic
462`ZeRoHaSH`. Either the hashtree or FEC data or both may be zeroed this way
463so applications should check for the magic both places. Applications can
464use the magic to detect if recalculation is needed.
465
466To calculate the maximum size of an image that will fit in a partition
467of a given size after having used the `avbtool add_hash_footer` or
468`avbtool add_hashtree_footer` commands on it, use the
469`--calc_max_image_size` option:
470
471    $ avbtool add_hash_footer --partition_size $((10*1024*1024)) \
472        --calc_max_image_size
473    10416128
474
475    $ avbtool add_hashtree_footer --partition_size $((10*1024*1024)) \
476        --calc_max_image_size
477    10330112
478
479To calculate the required libavb version that would be put in the
480vbmeta struct when using `make_vbmeta_image`, `add_hash_footer`, and
481`add_hashtree_footer` commands use the
482`--print_required_libavb_version` option:
483
484    $ avbtool make_vbmeta_image \
485        --algorithm SHA256_RSA2048 --key /path/to/key.pem \
486        --include_descriptors_from_image /path/to/boot.img \
487        --include_descriptors_from_image /path/to/system.img \
488        --print_required_libavb_version
489    1.0
490
491Alternatively, `--no_hashtree` can be used with `avbtool add_hashtree_footer`
492command. If `--no_hashtree` is given, the hashtree blob is omitted and only
493its descriptor is added to the vbmeta struct. The descriptor says the size
494of hashtree is 0, which tells an application the need to recalculate
495hashtree.
496
497The `--signing_helper` option can be used in `make_vbmeta_image`,
498`add_hash_footer` and `add_hashtree_footer` commands to specify any
499external program for signing hashes. The data to sign (including
500padding e.g. PKCS1-v1.5) is fed via `STDIN` and the signed data is
501returned via `STDOUT`. If `--signing_helper` is present in a command
502line, the `--key` option need only contain a public key. Arguments for
503a signing helper are `algorithm` and `public key`. If the signing
504helper exits with a non-zero exit code, it means failure.
505
506Here's an example invocation:
507
508    /path/to/my_signing_program SHA256_RSA2048 /path/to/publickey.pem
509
510The `--signing_helper_with_files` is similar to `--signing_helper`
511except that a temporary file is used to communicate with the helper
512instead of `STDIN` and `STDOUT`. This is useful in situations where
513the signing helper is using code which is outputting diagnostics on
514`STDOUT` instead of `STDERR`. Here's an example invocation
515
516    /path/to/my_signing_program_with_files SHA256_RSA2048 \
517      /path/to/publickey.pem /tmp/path/to/communication_file
518
519where the last positional argument is a file that contains the data to
520sign. The helper should write the signature in this file.
521
522The `append_vbmeta_image` command can be used to append an entire
523vbmeta blob to the end of another image. This is useful for cases when
524not using any vbmeta partitions, for example:
525
526    $ cp boot.img boot-with-vbmeta-appended.img
527    $ avbtool append_vbmeta_image                       \
528        --image boot-with-vbmeta-appended.img           \
529        --partition_size SIZE_OF_BOOT_PARTITION         \
530        --vbmeta_image vbmeta.img
531    $ fastboot flash boot boot-with-vbmeta-appended.img
532
533Information about an image can be obtained using the `info_image` command. The
534output of this command should not be relied on and the way information is
535structured may change.
536
537The `verify_image` command can be used to verify the contents of
538several image files at the same time. When invoked on an image the
539following checks are performed:
540
541* If the image has a VBMeta struct the signature is checked against
542  the embedded public key. If the image doesn't look like `vbmeta.img`
543  then a footer is looked for and used if present.
544
545* If the option `--key` is passed then a `.pem` file is expected and
546  it's checked that the embedded public key in said VBMeta struct
547  matches the given key.
548
549* All descriptors in the VBMeta struct are checked in the following
550  way:
551    + For a hash descriptor the image file corresponding to the
552      partition name is loaded and its digest is checked against that
553      in the descriptor.
554    + For a hashtree descriptor the image file corresponding to the
555      partition name is loaded and the hashtree is calculated and its
556      root digest compared to that in the descriptor.
557    + For a chained partition descriptor its contents is compared
558      against content that needs to be passed in via the
559      `--expected_chain_partition` options. The format for this option
560      is similar to that of the `--chain_partition` option. If there
561      is no `--expected_chain_partition` descriptor for the chain
562      partition descriptor the check fails.
563
564Here's an example for a setup where the digests for `boot.img` and
565`system.img` are stored in `vbmeta.img` which is signed with
566`my_key.pem`. It also checks that the chain partition for partition
567`foobar` uses rollback index 8 and that the public key in AVB format
568matches that of the file `foobar_vendor_key.avbpubkey`:
569
570    $ avbtool verify_image \
571         --image /path/to/vbmeta.img \
572         --key my_key.pem \
573         --expect_chained_partition foobar:8:foobar_vendor_key.avbpubkey
574
575    Verifying image /path/to/vbmeta.img using key at my_key.pem
576    vbmeta: Successfully verified SHA256_RSA4096 vbmeta struct in /path_to/vbmeta.img
577    boot: Successfully verified sha256 hash of /path/to/boot.img for image of 10543104 bytes
578    system: Successfully verified sha1 hashtree of /path/to/system.img for image of 1065213952 bytes
579    foobar: Successfully verified chain partition descriptor matches expected data
580
581In this example the `verify_image` command verifies the files
582`vbmeta.img`, `boot.img`, and `system.img` in the directory
583`/path/to`. The directory and file extension of the given image
584(e.g. `/path/to/vbmeta.img`) is used together with the partition name
585in the descriptor to calculate the filenames of the images holding
586hash and hashtree images.
587
588The `verify_image` command can also be used to check that a custom
589signing helper works as intended.
590
591The `calculate_vbmeta_digest` command can be used to calculate the vbmeta digest
592of several image files at the same time. The result is printed as a hexadecimal
593string either on `STDOUT` or a supplied path (using the `--output` option).
594
595    $ avbtool calculate_vbmeta_digest \
596         --hash_algorithm sha256 \
597         --image /path/to/vbmeta.img
598    a20fdd01a6638c55065fe08497186acde350d6797d59a55d70ffbcf41e95c2f5
599
600In this example the `calculate_vbmeta_digest` command loads the `vbmeta.img`
601file. If this image has one or more chain partition descriptors, the same logic
602as the `verify_image` command is used to load files for these (e.g. it assumes
603the same directory and file extension as the given image). Once all vbmeta
604structs have been loaded, the digest is calculated (using the hash algorithm
605given by the `--hash_algorithm` option) and printed out.
606
607To print hash and hashtree digests embedded in the verified metadata, use the
608`print_partition_digests` command like this:
609
610    $ avbtool print_partition_digests --image /path/to/vbmeta.img
611    system: ddaa513715fd2e22f3c1cea3c1a1f98ccb515fc6
612    boot: 5cba9a418e04b5f9e29ee6a250f6cdbe30c6cec867c59d388f141c3fedcb28c1
613    vendor: 06993a9e85e46e53d3892881bb75eff48ecadaa8
614
615For partitions with hash descriptors, this prints out the digest and for
616partitions with hashtree descriptors the root digest is printed out. Like the
617`calculate_vbmeta_digest` and `verify_image` commands, chain partitions are
618followed. To use JSON for the output, use the `--json` option.
619
620In case you would like to log all command lines for all avbtool invocations for
621debugging integrations with other tooling, you can configure the envirionment
622variable AVB_INVOCATION_LOGFILE with the name of the log file:
623
624    $ export AVB_INVOCATION_LOGFILE='/tmp/avb_invocation.log'
625    $ ./avbtool version
626    $ ./avbtool version
627    $ cat /tmp/avb_invocation.log
628    ./avbtool version
629    ./avbtool version
630
631
632## Build System Integration
633
634In Android, AVB is enabled by the `BOARD_AVB_ENABLE` variable
635
636    BOARD_AVB_ENABLE := true
637
638This will make the build system create `vbmeta.img` which will contain
639a hash descriptor for `boot.img`, a hashtree descriptor for
640`system.img`, a kernel-cmdline descriptor for setting up `dm-verity`
641for `system.img` and append a hash-tree to `system.img`. If the build
642system is set up such that one or many of `vendor.img` / `product.img`
643/ `system_ext.img` / `odm.img` are being built, the hash-tree for each
644of them will also be appended to the image respectively, and their
645hash-tree descriptors will be included into `vbmeta.img` accordingly.
646
647By default, the algorithm `SHA256_RSA4096` is used with a test key
648from the `external/avb/test/data` directory. This can be overriden by
649the `BOARD_AVB_ALGORITHM` and `BOARD_AVB_KEY_PATH` variables to use
650e.g. a 4096-bit RSA key and SHA-512:
651
652    BOARD_AVB_ALGORITHM := SHA512_RSA4096
653    BOARD_AVB_KEY_PATH := /path/to/rsa_key_4096bits.pem
654
655Remember that the public part of this key needs to be available to the
656bootloader of the device expected to verify resulting images. Use
657`avbtool extract_public_key` to extract the key in the expected format
658(`AVB_pk` in the following). If the device is using a different root
659of trust than `AVB_pk` the `--public_key_metadata` option can be used
660to embed a blob (`AVB_pkmd` in the following) that can be used to
661e.g. derive `AVB_pk`. Both `AVB_pk` and `AVB_pkmd` are passed to the
662`validate_vbmeta_public_key()` operation when verifying a slot.
663
664Some devices may support the end-user configuring the root of trust to use, see
665the [Device Specific Notes](#Device-Specific-Notes) section for details.
666
667Devices can be configured to create additional `vbmeta` partitions as
668[chained partitions](#The-VBMeta-struct) in order to update a subset of
669partitions without changing the top-level `vbmeta` partition. For example,
670the following variables create `vbmeta_system.img` as a chained `vbmeta`
671image that contains the hash-tree descriptors for `system.img`, `system_ext.img`
672and `product.img`. `vbmeta_system.img` itself will be signed by the specified
673key and algorithm.
674
675    BOARD_AVB_VBMETA_SYSTEM := system system_ext product
676    BOARD_AVB_VBMETA_SYSTEM_KEY_PATH := external/avb/test/data/testkey_rsa2048.pem
677    BOARD_AVB_VBMETA_SYSTEM_ALGORITHM := SHA256_RSA2048
678    BOARD_AVB_VBMETA_SYSTEM_ROLLBACK_INDEX_LOCATION := 1
679
680Note that the hash-tree descriptors for `system.img`, `system_ext.img` and
681`product.img` will be included only in `vbmeta_system.img`, but not
682`vbmeta.img`. With the above setup, partitions `system.img`, `system_ext.img`,
683`product.img` and `vbmeta_system.img` can be updated independently - but as a
684group - of the rest of the partitions, *or* as part of the traditional updates
685that update all the partitions.
686
687Currently build system supports building chained `vbmeta` images of
688`vbmeta_system.img` (`BOARD_AVB_VBMETA_SYSTEM`) and `vbmeta_vendor.img`
689(`BOARD_AVB_VBMETA_VENDOR`).
690
691To prevent rollback attacks, the rollback index should be increased on
692a regular basis. The rollback index can be set with the
693`BOARD_AVB_ROLLBACK_INDEX` variable:
694
695     BOARD_AVB_ROLLBACK_INDEX := 5
696
697If this is not set, the rollback index defaults to 0.
698
699The variable `BOARD_AVB_MAKE_VBMETA_IMAGE_ARGS` can be used to specify
700additional options passed to `avbtool make_vbmeta_image`. Typical
701options to be used here include `--prop`, `--prop_from_file`,
702`--chain_partition`, `--public_key_metadata`, and `--signing_helper`.
703
704The variable `BOARD_AVB_BOOT_ADD_HASH_FOOTER_ARGS` can be used to
705specify additional options passed to `avbtool add_hash_footer` for
706`boot.img`. Typical options to be used here include `--hash_algorithm`
707and `--salt`.
708
709The variable `BOARD_AVB_SYSTEM_ADD_HASHTREE_FOOTER_ARGS` can be used
710to specify additional options passed to `avbtool add_hashtree_footer`
711for `system.img`. Typical options to be used here include
712`--hash_algorithm`, `--salt`, `--block_size`, and
713`--do_not_generate_fec`.
714
715The variable `BOARD_AVB_VENDOR_ADD_HASHTREE_FOOTER_ARGS` can be used
716to specify additional options passed to `avbtool add_hashtree_footer`
717for `vendor.img`. Typical options to be used here include
718`--hash_algorithm`, `--salt`, `--block_size`, and
719`--do_not_generate_fec`.
720
721The variable `BOARD_AVB_DTBO_ADD_HASH_FOOTER_ARGS` can be used to
722specify additional options passed to `avbtool add_hash_footer` for
723`dtbo.img`. Typical options to be used here include `--hash_algorithm`
724and `--salt`.
725
726Build system variables (such as `PRODUCT_SUPPORTS_VERITY_FEC`) used
727for previous version of Verified Boot in Android are not used in AVB.
728
729A/B related build system variables can be found [here](https://source.android.com/devices/tech/ota/ab_updates#build-variables).
730
731# Device Integration
732
733This section discusses recommendations and best practices for
734integrating `libavb` with a device boot loader. It's important to
735emphasize that these are just recommendations so the use of the word
736`must` should be taken lightly.
737
738Additionally term *HLOS* is used in this chapter to refer to the *High
739Level Operating System*. This obviously includes Android (including
740other form-factors than phones) but could also be other operating
741systems.
742
743## System Dependencies
744
745The `libavb` library is written in a way so it's portable to any
746system with a C99 compiler. It does not require the standard C library
747however the boot loader must implement a simple set of system
748primitives required by `libavb` such as `avb_malloc()`, `avb_free()`,
749and `avb_print()`.
750
751In addition to the system primitives, `libavb` interfaces with the boot
752loader through the supplied `AvbOps` struct. This includes operations
753to read and write data from partitions, read and write rollback
754indexes, check if the public key used to make a signature should be
755accepted, and so on.
756
757## Locked and Unlocked mode
758
759AVB has been designed to support the notion of the device being either
760LOCKED state or UNLOCKED state as used in Android.
761
762In the context of AVB, the LOCKED state means that verification errors
763are fatal whereas in UNLOCKED state they are not. If the device is
764UNLOCKED pass `AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR` flag in
765the `flags` parameter of `avb_slot_verify()` and treat verification
766errors including
767
768* `AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED`
769* `AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION`
770* `AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX`
771
772as non-fatal. If the device is in the LOCKED state, don't pass the
773`AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR` flag in the `flags`
774parameter of `avb_slot_verify()` and only treat
775`AVB_SLOT_VERIFY_RESULT_OK` as non-fatal.
776
777On Android, device state may be altered through the fastboot interface
778using, e.g. `fastboot flashing lock` (to transition to the LOCKED
779state) and `fastboot flashing unlock` (to transition to the UNLOCKED
780state).
781
782The device must only allow state transitions (e.g. from LOCKED to
783UNLOCKED or UNLOCKED to LOCKED) after asserting physical presence of
784the user. If the device has a display and buttons this is typically
785done by showing a dialog and requiring the user to confirm or cancel
786using physical buttons.
787
788All user data must be cleared when transitioning from the LOCKED to
789the UNLOCKED state (including the `userdata` partition and any NVRAM
790spaces). Additionally all `stored_rollback_index[n]` locations must be
791cleared (all elements must be set to zero). Similar action (erasing
792`userdata`, NVRAM spaces, and `stored_rollback_index[n]` locations)
793shall also happening when transitioning from UNLOCKED to LOCKED. If
794the device is required to use full disk encryption, then a less
795intensive wipe is required for UNLOCKED to LOCKED. Depending on the
796device form-factor and intended use, the user should be prompted to
797confirm before any data is erased.
798
799## Tamper-evident Storage
800
801In this document, *tamper-evident* means that it's possible to detect
802if the HLOS has tampered with the data, e.g. if it has been
803overwritten.
804
805Tamper-evident storage must be used for stored rollback indexes, keys
806used for verification, device state (whether the device is LOCKED or
807UNLOCKED), and named persistent values. If tampering has been detected
808the corresponding `AvbOps` operation should fail by e.g. returning
809`AVB_IO_RESULT_ERROR_IO`. It is especially important that verification
810keys cannot be tampered with since they represent the root-of-trust.
811
812If verification keys are mutable they must only be set by the end
813user, e.g. it must never be set at the factory or store or any
814intermediate point before the end user. Additionally, it must only be
815possible to set or clear a key while the device is in the UNLOCKED
816state.
817
818## Named Persistent Values
819
820AVB 1.1 introduces support for named persistent values which must be
821tamper evident and allows AVB to store arbitrary key-value pairs.
822Integrators may limit support for these values to a set of fixed
823well-known names, a maximum value size, and / or a maximum number of
824values.
825
826## Persistent Digests
827
828Using a persistent digest for a partition means the digest (or root
829digest in the case of a hashtree) is not stored in the descriptor but
830is stored in a named persistent value. This allows configuration data
831which may differ from device to device to be verified by AVB. It must
832not be possible to modify the persistent digest when the device is in
833the LOCKED state, except if a digest does not exist it may be initialized.
834
835To specify that a descriptor should use a persistent digest, use the
836`--use_persistent_digest` option for the `add_hash_footer` or
837`add_hashtree_footer` avbtool operations. Then, during verification of
838the descriptor, AVB will look for the digest in the named persistent
839value `avb.persistent_digest.$(partition_name)` instead of in the
840descriptor itself.
841
842For hashtree descriptors using a persistent digest, the digest value
843will be available for substitution into kernel command line descriptors
844using a token of the form `$(AVB_FOO_ROOT_DIGEST)` where 'FOO' is the
845uppercase partition name, in this case for the partition named 'foo'.
846The token will be replaced by the digest in hexadecimal form.
847
848By default, when the `--use_persistent_digest` option is used with
849`add_hash_footer` or `add_hashtree_footer`, avbtool will generate a
850descriptor with no salt rather than the typical default of generating a
851random salt equal to the digest length. This is because the digest
852value is stored in persistent storage and thus cannot change over time.
853An alternative option would be to manually provide a random salt using
854`--salt`, but this salt would need to remain unchanged for the life
855of the device once the persistent digest value was written.
856
857## Updating Stored Rollback Indexes
858
859In order for Rollback Protection to work the bootloader will need to
860update the `stored_rollback_indexes[n]` array on the device prior to
861transferring control to the HLOS. If not using A/B this is
862straightforward - just update it to what's in the AVB metadata for the
863slot before booting. In pseudo-code it would look like this:
864
865```c++
866// The |slot_data| parameter should be the AvbSlotVerifyData returned
867// by avb_slot_verify() for the slot we're about to boot.
868//
869bool update_stored_rollback_indexes_for_slot(AvbOps* ops,
870                                             AvbSlotVerifyData* slot_data) {
871    for (int n = 0; n < AVB_MAX_NUMBER_OF_ROLLBACK_INDEX_LOCATIONS; n++) {
872        uint64_t rollback_index = slot_data->rollback_indexes[n];
873        if (rollback_index > 0) {
874            AvbIOResult io_ret;
875            uint64_t current_stored_rollback_index;
876
877            io_ret = ops->read_rollback_index(ops, n, &current_stored_rollback_index);
878            if (io_ret != AVB_IO_RESULT_OK) {
879                return false;
880            }
881
882            if (rollback_index > current_stored_rollback_index) {
883                io_ret = ops->write_rollback_index(ops, n, rollback_index);
884                if (io_ret != AVB_IO_RESULT_OK) {
885                    return false;
886                }
887            }
888        }
889    }
890    return true;
891}
892```
893
894However if using A/B more care must be taken to still allow the device
895to fall back to the old slot if the update didn't work.
896
897For an HLOS like Android where rollback is only supported if the
898updated OS version is found to not work, `stored_rollback_index[n]`
899should only be updated from slots that are marked as SUCCESSFUL in the
900A/B metadata. The pseudo-code for that is as follows where
901`is_slot_is_marked_as_successful()` comes from the A/B stack in use:
902
903```c++
904if (is_slot_is_marked_as_successful(slot->ab_suffix)) {
905    if (!update_stored_rollback_indexes_for_slot(ops, slot)) {
906        // TODO: handle error.
907    }
908}
909```
910
911This logic should ideally be implemented outside of the HLOS. One
912possible implementation is to update rollback indices in the
913bootloader when booting into a successful slot. This means that
914when booting into a new OS not yet marked as successful, the
915rollback indices would not be updated. The first reboot after the
916slot succeeded would trigger an update of the rollback indices.
917
918For an HLOS where it's possible to roll back to a previous version,
919`stored_rollback_index[n]` should be set to the largest possible value
920allowing all bootable slots to boot. This approach is implemented in
921AVB's experimental (and now deprecated) A/B stack `libavb_ab`, see the
922`avb_ab_flow()` implementation. Note that this requires verifying
923*all* bootable slots at every boot and this may impact boot time.
924
925## Recommended Bootflow
926
927The recommended boot flow for a device using AVB is as follows:
928
929![Recommended AVB boot flow](docs/avb-recommended-boot-flow.png)
930
931Notes:
932
933* The device is expected to search through all A/B slots until it
934  finds a valid OS to boot. Slots that are rejected in the LOCKED
935  state might not be rejected in the UNLOCKED state, (e.g. when
936  UNLOCKED any key can be used and rollback index failures are
937  allowed), so the algorithm used for selecting a slot varies
938  depending on what state the device is in.
939
940* If no valid OS (that is, no bootable A/B slot) can be found, the
941  device cannot boot and has to enter repair mode. It is
942  device-dependent what this looks like.  If the device has a screen
943  it must convey this state to the user.
944
945* If the device is LOCKED, only an OS signed by an embedded
946  verification key (see the previous section) shall be
947  accepted. Additionally, `rollback_index[n]` as stored in the
948  verified image must be greater or equal than what's in
949  `stored_rollback_index[n]` on the device (for all `n`) and the
950  `stored_rollback_index[n]` array is expected to be updated as
951  specified in the previous section.
952    + If the key used for verification was set by the end user, and
953      the device has a screen, it must show a warning with the key
954      fingerprint to convey that the device is booting a custom
955      OS. The warning must be shown for at least 10 seconds before the
956      boot process continues. If the device does not have a screen,
957      other ways must be used to convey that the device is booting a
958      custom OS (lightbars, LEDs, etc.).
959
960* If the device is UNLOCKED, there is no requirement to check the key
961  used to sign the OS nor is there any requirement to check or update
962  rollback `stored_rollback_index[n]` on the device. Because of this
963  the user must always be shown a warning about verification not
964  occurring.
965    + It is device-dependent how this is implemented since it depends
966      on the device form-factor and intended usage. If the device has
967      a screen and buttons (for example if it's a phone) the warning
968      is to be shown for at least 10 seconds before the boot process
969      continues. If the device does not have a screen, other ways must
970      be used to convey that the device is UNLOCKED (lightbars, LEDs,
971      etc.).
972
973### Booting Into Recovery
974
975On Android devices not using A/B, the `recovery` partition usually isn't
976updated along with other partitions and therefore can't be referenced
977from the main `vbmeta` partition.
978
979It's still possible to use AVB to protect this partition (and others)
980by signing these partitions and passing the
981`AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION` flag to `avb_slot_verify()`.
982In this mode, the key used to sign each requested partition is verified
983by the `validate_public_key_for_partition()` operation which is also
984used to return the rollback index location to be used.
985
986## Handling dm-verity Errors
987
988By design, hashtree verification errors are detected by the HLOS and
989not the bootloader. AVB provides a way to specify how the error should
990be handled through the `hashtree_error_mode` parameter in the
991`avb_slot_verify()` function. Possible values include
992
993* `AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE` means that the HLOS
994  will invalidate the current slot and restart. On devices with A/B
995  this would lead to attempting to boot the other slot (if it's marked
996  as bootable) or it could lead to a mode where no OS can be booted
997  (e.g. some form of repair mode). In Linux this requires a kernel
998  built with `CONFIG_DM_VERITY_AVB`.
999
1000* `AVB_HASHTREE_ERROR_MODE_RESTART` means that the OS will restart
1001  without the current slot being invalidated. Be careful using this
1002  mode unconditionally as it may introduce boot loops if the same
1003  hashtree verification error is hit on every boot.
1004
1005* `AVB_HASHTREE_ERROR_MODE_EIO` means that an `EIO` error will be
1006  returned to the application.
1007
1008* `AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO` means that either the **RESTART**
1009  or **EIO** mode is used, depending on state. This mode implements a state
1010  machine whereby **RESTART** is used by default and when the
1011  `AVB_SLOT_VERIFY_FLAGS_RESTART_CAUSED_BY_HASHTREE_CORRUPTION` is passed to
1012  `avb_slot_verify()` the mode transitions to **EIO**. When a new OS has been
1013  detected the device transitions back to the **RESTART** mode.
1014    + To do this persistent storage is needed - specifically this means that the
1015      passed in `AvbOps` will need to have the `read_persistent_value()` and
1016      `write_persistent_value()` operations implemented. The name of the
1017      persistent value used is **avb.managed_verity_mode** and 32 bytes of storage
1018      is needed.
1019
1020* `AVB_HASHTREE_ERROR_MODE_LOGGING` means that errors will be logged
1021   and corrupt data may be returned to applications. This mode should
1022   be used for **ONLY** diagnostics and debugging. It cannot be used
1023   unless verification errors are allowed.
1024
1025* `AVB_HASHTREE_ERROR_MODE_PANIC` means that the OS will **panic** without
1026  the current slot being invalidated. Be careful using this mode as it may
1027  introduce boot panic if the same hashtree verification error is hit on
1028  every boot. This mode is available since: 1.7.0 (kernel 5.9)
1029
1030The value passed in `hashtree_error_mode` is essentially just passed on through
1031to the HLOS through the the `androidboot.veritymode`,
1032`androidboot.veritymode.managed`, and `androidboot.vbmeta.invalidate_on_error`
1033kernel command-line parameters in the following way:
1034
1035|      | `androidboot.veritymode` | `androidboot.veritymode.managed` | `androidboot.vbmeta.invalidate_on_error` |
1036|------|:------------------------:|:--------------------------------:|:----------------------------------------:|
1037| `AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE` | **enforcing** | (unset) | **yes** |
1038| `AVB_HASHTREE_ERROR_MODE_RESTART` | **enforcing** | (unset) | (unset) |
1039| `AVB_HASHTREE_ERROR_MODE_EIO` | **eio** | (unset) | (unset) |
1040| `AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO` | **eio** or **enforcing** | **yes** | (unset) |
1041| `AVB_HASHTREE_ERROR_MODE_LOGGING` | **ignore_corruption** | (unset) | (unset) |
1042| `AVB_HASHTREE_ERROR_MODE_PANIC` | **panicking** | (unset) | (unset) |
1043
1044The only exception to this table is that if the
1045`AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED` flag is set in the top-level vbmeta,
1046then `androidboot.veritymode` is set to **disabled** and
1047`androidboot.veritymode.managed` and `androidboot.vbmeta.invalidate_on_error`
1048are unset.
1049
1050The different values of `hashtree_error_mode` parameter in the `avb_slot_verify()`
1051function can be categorized into three groups:
1052
1053* `AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE`, which needs `CONFIG_DM_VERITY_AVB`
1054  in the kernel config for the kernel to invalidate the current slot and
1055  restart. This is kept here for legacy Android Things devices and is not
1056  recommended for other device form factors.
1057
1058* The bootloader handles the switch between `AVB_HASHTREE_ERROR_MODE_RESTART`
1059  and `AVB_HASHTREE_ERROR_MODE_EIO`. This would need a persistent storage on the
1060  device to store the vbmeta digest, so the bootloader can detect if a device
1061  ever gets an update or not. Once the new OS is installed and if the device is
1062  in **EIO** mode, the bootloader should switch back to **RESTART** mode.
1063
1064* `AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO`: `libavb` helps the
1065  bootloader manage **EIO**/**RESTART** state transition. The bootloader needs
1066  to implement the callbacks of `AvbOps->read_persistent_value()` and
1067  `AvbOps->write_persistent_value()` for `libavb` to store the vbmeta digest to
1068  detect whether a new OS is installed.
1069
1070### Which mode should I use for my device?
1071
1072This depends entirely on the device, how the device is intended to be
1073used, and the desired user experience.
1074
1075For Android devices the `AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO` mode
1076should 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.
1077
1078If the device doesn't have a screen or if the HLOS supports multiple bootable
1079slots simultaneously it may make more sense to just use
1080`AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE`.
1081
1082## Android Specific Integration
1083
1084On Android, the boot loader must set the
1085`androidboot.verifiedbootstate` parameter on the kernel command-line
1086to indicate the boot state. It shall use the following values:
1087
1088* **green**: If in LOCKED state and the key used for verification was not set by the end user.
1089* **yellow**: If in LOCKED state and the key used for verification was set by the end user.
1090* **orange**: If in the UNLOCKED state.
1091
1092## Device Specific Notes
1093
1094This section contains information about how AVB is integrated into specific
1095devices. This is not an exhaustive list.
1096
1097### Pixel 2 and later
1098
1099On the Pixel 2, Pixel 2 XL and later Pixel models, the boot loader supports a
1100virtual partition with the name `avb_custom_key`. Flashing and erasing this
1101partition only works in the UNLOCKED state. Setting the custom key is done like
1102this:
1103
1104    avbtool extract_public_key --key key.pem --output pkmd.bin
1105    fastboot flash avb_custom_key pkmd.bin
1106
1107Erasing the key is done by erasing the virtual partition:
1108
1109    fastboot erase avb_custom_key
1110
1111When the custom key is set and the device is in the LOCKED state it will boot
1112images signed with both the built-in key as well as the custom key. All other
1113security features (including rollback-protection) are in effect, e.g. the
1114**only** difference is the root of trust to use.
1115
1116When booting an image signed with a custom key, a yellow screen will be shown as
1117part of the boot process to remind the user that the custom key is in use.
1118
1119# Version History
1120
1121### Version 1.2
1122
1123Version 1.2 adds support for the following:
1124* `rollback_index_location` field of the main vbmeta header.
1125* `check_at_most_once` parameter of dm-verity in a hashtree descriptor.
1126
1127### Version 1.1
1128
1129Version 1.1 adds support for the following:
1130
1131* A 32-bit `flags` element is added to hash and hashtree descriptors.
1132* Support for partitions which don't use [A/B](#A_B-Support).
1133* Tamper-evident [named persistent values](#Named-Persistent-Values).
1134* [Persistent digests](#Persistent-Digests) for hash or hashtree descriptors.
1135
1136### Version 1.0
1137
1138All features not explicitly listed under a later version are supported by 1.0.
1139