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

..--

boot_control/22-Nov-2023-171122

contrib/linux/4.4/22-Nov-2023-1,1051,048

docs/22-Nov-2023-

examples/22-Nov-2023-1,8561,254

libavb/22-Nov-2023-7,4554,383

libavb_ab/22-Nov-2023-926485

libavb_atx/22-Nov-2023-532293

libavb_user/22-Nov-2023-1,007597

test/22-Nov-2023-10,8738,710

tools/avbctl/22-Nov-2023-308223

.clang-formatD22-Nov-2023884 2725

.gitD01-Jan-19700

Android.bpD22-Nov-20235.7 KiB237223

LICENSED22-Nov-20231 KiB2117

MODULE_LICENSE_MITD22-Nov-20230

NOTICED22-Nov-20231 KiB2117

OWNERSD22-Nov-202382 54

PREUPLOAD.cfgD22-Nov-2023138 64

README.mdD22-Nov-202341.3 KiB921743

avbtoolD22-Nov-2023156.5 KiB4,0273,178

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