• Home
Name Date Size #Lines LOC

..--

boot_control/03-May-2024-171122

contrib/linux/4.4/03-May-2024-1,1051,048

docs/03-May-2024-

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

libavb/03-May-2024-8,0364,781

libavb_ab/03-May-2024-926485

libavb_aftl/03-May-2024-1,7481,143

libavb_atx/03-May-2024-727443

libavb_user/03-May-2024-1,016599

proto/03-May-2024-3,6063,137

test/03-May-2024-14,48611,647

tools/03-May-2024-1,3731,008

.clang-formatD03-May-2024884 2725

.gitignoreD03-May-20249 21

Android.bpD03-May-20248.7 KiB388366

LICENSED03-May-20241 KiB2117

MODULE_LICENSE_MITD03-May-20240

NOTICED03-May-20241 KiB2117

OWNERSD03-May-2024121 76

PREUPLOAD.cfgD03-May-2024152 75

README.mdD03-May-202449 KiB1,061857

TEST_MAPPINGD03-May-2024158 1312

aftltoolD03-May-202471.9 KiB1,9001,515

aftltool.pyD03-May-202471.9 KiB1,9001,515

aftltool_integration_test.pyD03-May-20243 KiB8041

aftltool_test.pyD03-May-202459.2 KiB1,5381,104

avbtoolD03-May-2024182.8 KiB4,6493,703

avbtool.pyD03-May-2024182.8 KiB4,6493,703

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