• 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-7,8334,647

libavb_ab/03-May-2024-926485

libavb_atx/03-May-2024-727443

libavb_user/03-May-2024-1,016599

test/03-May-2024-13,15010,571

tools/03-May-2024-957700

.clang-formatD03-May-2024884 2725

Android.bpD03-May-20246.3 KiB264248

LICENSED03-May-20241 KiB2117

MODULE_LICENSE_MITD03-May-20240

NOTICED03-May-20241 KiB2117

OWNERSD03-May-202482 54

PREUPLOAD.cfgD03-May-2024138 64

README.mdD03-May-202446.7 KiB1,010817

TEST_MAPPINGD03-May-202495 98

avbtoolD03-May-2024174.6 KiB4,4203,516

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