• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright (C) 2016 The Android Open Source Project
4  */
5 
6 #include "avb_slot_verify.h"
7 #include "avb_chain_partition_descriptor.h"
8 #include "avb_cmdline.h"
9 #include "avb_footer.h"
10 #include "avb_hash_descriptor.h"
11 #include "avb_hashtree_descriptor.h"
12 #include "avb_kernel_cmdline_descriptor.h"
13 #include "avb_sha.h"
14 #include "avb_util.h"
15 #include "avb_vbmeta_image.h"
16 #include "avb_version.h"
17 
18 /* Maximum number of partitions that can be loaded with avb_slot_verify(). */
19 #define MAX_NUMBER_OF_LOADED_PARTITIONS 32
20 
21 /* Maximum number of vbmeta images that can be loaded with avb_slot_verify(). */
22 #define MAX_NUMBER_OF_VBMETA_IMAGES 32
23 
24 /* Maximum size of a vbmeta image - 64 KiB. */
25 #define VBMETA_MAX_SIZE (64 * 1024)
26 
27 static AvbSlotVerifyResult initialize_persistent_digest(
28     AvbOps* ops,
29     const char* part_name,
30     const char* persistent_value_name,
31     size_t digest_size,
32     const uint8_t* initial_digest,
33     uint8_t* out_digest);
34 
35 /* Helper function to see if we should continue with verification in
36  * allow_verification_error=true mode if something goes wrong. See the
37  * comments for the avb_slot_verify() function for more information.
38  */
result_should_continue(AvbSlotVerifyResult result)39 static inline bool result_should_continue(AvbSlotVerifyResult result) {
40   switch (result) {
41     case AVB_SLOT_VERIFY_RESULT_ERROR_OOM:
42     case AVB_SLOT_VERIFY_RESULT_ERROR_IO:
43     case AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA:
44     case AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION:
45     case AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT:
46       return false;
47 
48     case AVB_SLOT_VERIFY_RESULT_OK:
49     case AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION:
50     case AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX:
51     case AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED:
52       return true;
53   }
54 
55   return false;
56 }
57 
load_full_partition(AvbOps * ops,const char * part_name,uint64_t image_size,uint8_t ** out_image_buf,bool * out_image_preloaded)58 static AvbSlotVerifyResult load_full_partition(AvbOps* ops,
59                                                const char* part_name,
60                                                uint64_t image_size,
61                                                uint8_t** out_image_buf,
62                                                bool* out_image_preloaded) {
63   size_t part_num_read;
64   AvbIOResult io_ret;
65 
66   /* Make sure that we do not overwrite existing data. */
67   avb_assert(*out_image_buf == NULL);
68   avb_assert(!*out_image_preloaded);
69 
70   /* We are going to implicitly cast image_size from uint64_t to size_t in the
71    * following code, so we need to make sure that the cast is safe. */
72   if (image_size != (size_t)(image_size)) {
73     avb_errorv(part_name, ": Partition size too large to load.\n", NULL);
74     return AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
75   }
76 
77   /* Try use a preloaded one. */
78   if (ops->get_preloaded_partition != NULL) {
79     io_ret = ops->get_preloaded_partition(
80         ops, part_name, image_size, out_image_buf, &part_num_read);
81     if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
82       return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
83     } else if (io_ret != AVB_IO_RESULT_OK) {
84       avb_errorv(part_name, ": Error loading data from partition.\n", NULL);
85       return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
86     }
87 
88     if (*out_image_buf != NULL) {
89       if (part_num_read != image_size) {
90         avb_errorv(part_name, ": Read incorrect number of bytes.\n", NULL);
91         return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
92       }
93       *out_image_preloaded = true;
94     }
95   }
96 
97   /* Allocate and copy the partition. */
98   if (!*out_image_preloaded) {
99     *out_image_buf = avb_malloc(image_size);
100     if (*out_image_buf == NULL) {
101       return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
102     }
103 
104     io_ret = ops->read_from_partition(ops,
105                                       part_name,
106                                       0 /* offset */,
107                                       image_size,
108                                       *out_image_buf,
109                                       &part_num_read);
110     if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
111       return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
112     } else if (io_ret != AVB_IO_RESULT_OK) {
113       avb_errorv(part_name, ": Error loading data from partition.\n", NULL);
114       return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
115     }
116     if (part_num_read != image_size) {
117       avb_errorv(part_name, ": Read incorrect number of bytes.\n", NULL);
118       return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
119     }
120   }
121 
122   return AVB_SLOT_VERIFY_RESULT_OK;
123 }
124 
125 /* Reads a persistent digest stored as a named persistent value corresponding to
126  * the given |part_name|. The value is returned in |out_digest| which must point
127  * to |expected_digest_size| bytes. If there is no digest stored for |part_name|
128  * it can be initialized by providing a non-NULL |initial_digest| of length
129  * |expected_digest_size|. This automatic initialization will only occur if the
130  * device is currently locked. The |initial_digest| may be NULL.
131  *
132  * Returns AVB_SLOT_VERIFY_RESULT_OK on success, otherwise returns an
133  * AVB_SLOT_VERIFY_RESULT_ERROR_* error code.
134  *
135  * If the value does not exist, is not supported, or is not populated, and
136  * |initial_digest| is NULL, returns
137  * AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA. If |expected_digest_size| does
138  * not match the stored digest size, also returns
139  * AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA.
140  */
read_persistent_digest(AvbOps * ops,const char * part_name,size_t expected_digest_size,const uint8_t * initial_digest,uint8_t * out_digest)141 static AvbSlotVerifyResult read_persistent_digest(AvbOps* ops,
142                                                   const char* part_name,
143                                                   size_t expected_digest_size,
144                                                   const uint8_t* initial_digest,
145                                                   uint8_t* out_digest) {
146   char* persistent_value_name = NULL;
147   AvbIOResult io_ret = AVB_IO_RESULT_OK;
148   size_t stored_digest_size = 0;
149 
150   if (ops->read_persistent_value == NULL) {
151     avb_errorv(part_name, ": Persistent values are not implemented.\n", NULL);
152     return AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
153   }
154   persistent_value_name =
155       avb_strdupv(AVB_NPV_PERSISTENT_DIGEST_PREFIX, part_name, NULL);
156   if (persistent_value_name == NULL) {
157     return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
158   }
159 
160   io_ret = ops->read_persistent_value(ops,
161                                       persistent_value_name,
162                                       expected_digest_size,
163                                       out_digest,
164                                       &stored_digest_size);
165 
166   // If no such named persistent value exists and an initial digest value was
167   // given, initialize the named persistent value with the given digest. If
168   // initialized successfully, this will recurse into this function but with a
169   // NULL initial_digest.
170   if (io_ret == AVB_IO_RESULT_ERROR_NO_SUCH_VALUE && initial_digest) {
171     AvbSlotVerifyResult ret =
172         initialize_persistent_digest(ops,
173                                      part_name,
174                                      persistent_value_name,
175                                      expected_digest_size,
176                                      initial_digest,
177                                      out_digest);
178     avb_free(persistent_value_name);
179     return ret;
180   }
181   avb_free(persistent_value_name);
182 
183   if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
184     return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
185   } else if (io_ret == AVB_IO_RESULT_ERROR_NO_SUCH_VALUE) {
186     // Treat a missing persistent value as a verification error, which is
187     // ignoreable, rather than a metadata error which is not.
188     avb_errorv(part_name, ": Persistent digest does not exist.\n", NULL);
189     return AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION;
190   } else if (io_ret == AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE ||
191              io_ret == AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE) {
192     avb_errorv(
193         part_name, ": Persistent digest is not of expected size.\n", NULL);
194     return AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
195   } else if (io_ret != AVB_IO_RESULT_OK) {
196     avb_errorv(part_name, ": Error reading persistent digest.\n", NULL);
197     return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
198   } else if (expected_digest_size != stored_digest_size) {
199     avb_errorv(
200         part_name, ": Persistent digest is not of expected size.\n", NULL);
201     return AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
202   }
203   return AVB_SLOT_VERIFY_RESULT_OK;
204 }
205 
initialize_persistent_digest(AvbOps * ops,const char * part_name,const char * persistent_value_name,size_t digest_size,const uint8_t * initial_digest,uint8_t * out_digest)206 static AvbSlotVerifyResult initialize_persistent_digest(
207     AvbOps* ops,
208     const char* part_name,
209     const char* persistent_value_name,
210     size_t digest_size,
211     const uint8_t* initial_digest,
212     uint8_t* out_digest) {
213   AvbSlotVerifyResult ret;
214   AvbIOResult io_ret = AVB_IO_RESULT_OK;
215   bool is_device_unlocked = true;
216 
217   io_ret = ops->read_is_device_unlocked(ops, &is_device_unlocked);
218   if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
219     return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
220   } else if (io_ret != AVB_IO_RESULT_OK) {
221     avb_error("Error getting device lock state.\n");
222     return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
223   }
224 
225   if (is_device_unlocked) {
226     avb_debugv(part_name,
227                ": Digest does not exist, device unlocked so not initializing "
228                "digest.\n",
229                NULL);
230     return AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION;
231   }
232 
233   // Device locked; initialize digest with given initial value.
234   avb_debugv(part_name,
235              ": Digest does not exist, initializing persistent digest.\n",
236              NULL);
237   io_ret = ops->write_persistent_value(
238       ops, persistent_value_name, digest_size, initial_digest);
239   if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
240     return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
241   } else if (io_ret != AVB_IO_RESULT_OK) {
242     avb_errorv(part_name, ": Error initializing persistent digest.\n", NULL);
243     return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
244   }
245 
246   // To ensure that the digest value was written successfully - and avoid a
247   // scenario where the digest is simply 'initialized' on every verify - recurse
248   // into read_persistent_digest to read back the written value. The NULL
249   // initial_digest ensures that this will not recurse again.
250   ret = read_persistent_digest(ops, part_name, digest_size, NULL, out_digest);
251   if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
252     avb_errorv(part_name,
253                ": Reading back initialized persistent digest failed!\n",
254                NULL);
255   }
256   return ret;
257 }
258 
load_and_verify_hash_partition(AvbOps * ops,const char * const * requested_partitions,const char * ab_suffix,bool allow_verification_error,const AvbDescriptor * descriptor,AvbSlotVerifyData * slot_data)259 static AvbSlotVerifyResult load_and_verify_hash_partition(
260     AvbOps* ops,
261     const char* const* requested_partitions,
262     const char* ab_suffix,
263     bool allow_verification_error,
264     const AvbDescriptor* descriptor,
265     AvbSlotVerifyData* slot_data) {
266   AvbHashDescriptor hash_desc;
267   const uint8_t* desc_partition_name = NULL;
268   const uint8_t* desc_salt;
269   const uint8_t* desc_digest;
270   char part_name[AVB_PART_NAME_MAX_SIZE];
271   AvbSlotVerifyResult ret;
272   AvbIOResult io_ret;
273   uint8_t* image_buf = NULL;
274   bool image_preloaded = false;
275   uint8_t* digest;
276   size_t digest_len;
277   const char* found;
278   uint64_t image_size;
279   size_t expected_digest_len = 0;
280   uint8_t expected_digest_buf[AVB_SHA512_DIGEST_SIZE];
281   const uint8_t* expected_digest = NULL;
282 
283   if (!avb_hash_descriptor_validate_and_byteswap(
284           (const AvbHashDescriptor*)descriptor, &hash_desc)) {
285     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
286     goto out;
287   }
288 
289   desc_partition_name =
290       ((const uint8_t*)descriptor) + sizeof(AvbHashDescriptor);
291   desc_salt = desc_partition_name + hash_desc.partition_name_len;
292   desc_digest = desc_salt + hash_desc.salt_len;
293 
294   if (!avb_validate_utf8(desc_partition_name, hash_desc.partition_name_len)) {
295     avb_error("Partition name is not valid UTF-8.\n");
296     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
297     goto out;
298   }
299 
300   /* Don't bother loading or validating unless the partition was
301    * requested in the first place.
302    */
303   found = avb_strv_find_str(requested_partitions,
304                             (const char*)desc_partition_name,
305                             hash_desc.partition_name_len);
306   if (found == NULL) {
307     ret = AVB_SLOT_VERIFY_RESULT_OK;
308     goto out;
309   }
310 
311   if ((hash_desc.flags & AVB_HASH_DESCRIPTOR_FLAGS_DO_NOT_USE_AB) != 0) {
312     /* No ab_suffix, just copy the partition name as is. */
313     if (hash_desc.partition_name_len >= AVB_PART_NAME_MAX_SIZE) {
314       avb_error("Partition name does not fit.\n");
315       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
316       goto out;
317     }
318     avb_memcpy(part_name, desc_partition_name, hash_desc.partition_name_len);
319     part_name[hash_desc.partition_name_len] = '\0';
320   } else if (hash_desc.digest_len == 0 && avb_strlen(ab_suffix) != 0) {
321     /* No ab_suffix allowed for partitions without a digest in the descriptor
322      * because these partitions hold data unique to this device and are not
323      * updated using an A/B scheme.
324      */
325     avb_error("Cannot use A/B with a persistent digest.\n");
326     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
327     goto out;
328   } else {
329     /* Add ab_suffix to the partition name. */
330     if (!avb_str_concat(part_name,
331                         sizeof part_name,
332                         (const char*)desc_partition_name,
333                         hash_desc.partition_name_len,
334                         ab_suffix,
335                         avb_strlen(ab_suffix))) {
336       avb_error("Partition name and suffix does not fit.\n");
337       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
338       goto out;
339     }
340   }
341 
342   /* If we're allowing verification errors then hash_desc.image_size
343    * may no longer match what's in the partition... so in this case
344    * just load the entire partition.
345    *
346    * For example, this can happen if a developer does 'fastboot flash
347    * boot /path/to/new/and/bigger/boot.img'. We want this to work
348    * since it's such a common workflow.
349    */
350   image_size = hash_desc.image_size;
351   if (allow_verification_error) {
352     io_ret = ops->get_size_of_partition(ops, part_name, &image_size);
353     if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
354       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
355       goto out;
356     } else if (io_ret != AVB_IO_RESULT_OK) {
357       avb_errorv(part_name, ": Error determining partition size.\n", NULL);
358       ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
359       goto out;
360     }
361     avb_debugv(part_name, ": Loading entire partition.\n", NULL);
362   }
363 
364   ret = load_full_partition(
365       ops, part_name, image_size, &image_buf, &image_preloaded);
366   if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
367     goto out;
368   }
369   // Although only one of the type might be used, we have to defined the
370   // structure here so that they would live outside the 'if/else' scope to be
371   // used later.
372   AvbSHA256Ctx sha256_ctx;
373   AvbSHA512Ctx sha512_ctx;
374   size_t image_size_to_hash = hash_desc.image_size;
375   // If we allow verification error and the whole partition is smaller than
376   // image size in hash descriptor, we just hash the whole partition.
377   if (image_size_to_hash > image_size) {
378     image_size_to_hash = image_size;
379   }
380   if (avb_strcmp((const char*)hash_desc.hash_algorithm, "sha256") == 0) {
381     avb_sha256_init(&sha256_ctx);
382     avb_sha256_update(&sha256_ctx, desc_salt, hash_desc.salt_len);
383     avb_sha256_update(&sha256_ctx, image_buf, image_size_to_hash);
384     digest = avb_sha256_final(&sha256_ctx);
385     digest_len = AVB_SHA256_DIGEST_SIZE;
386   } else if (avb_strcmp((const char*)hash_desc.hash_algorithm, "sha512") == 0) {
387     avb_sha512_init(&sha512_ctx);
388     avb_sha512_update(&sha512_ctx, desc_salt, hash_desc.salt_len);
389     avb_sha512_update(&sha512_ctx, image_buf, image_size_to_hash);
390     digest = avb_sha512_final(&sha512_ctx);
391     digest_len = AVB_SHA512_DIGEST_SIZE;
392   } else {
393     avb_errorv(part_name, ": Unsupported hash algorithm.\n", NULL);
394     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
395     goto out;
396   }
397 
398   if (hash_desc.digest_len == 0) {
399     /* Expect a match to a persistent digest. */
400     avb_debugv(part_name, ": No digest, using persistent digest.\n", NULL);
401     expected_digest_len = digest_len;
402     expected_digest = expected_digest_buf;
403     avb_assert(expected_digest_len <= sizeof(expected_digest_buf));
404     /* Pass |digest| as the |initial_digest| so devices not yet initialized get
405      * initialized to the current partition digest.
406      */
407     ret = read_persistent_digest(
408         ops, part_name, digest_len, digest, expected_digest_buf);
409     if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
410       goto out;
411     }
412   } else {
413     /* Expect a match to the digest in the descriptor. */
414     expected_digest_len = hash_desc.digest_len;
415     expected_digest = desc_digest;
416   }
417 
418   if (digest_len != expected_digest_len) {
419     avb_errorv(
420         part_name, ": Digest in descriptor not of expected size.\n", NULL);
421     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
422     goto out;
423   }
424 
425   if (avb_safe_memcmp(digest, expected_digest, digest_len) != 0) {
426     avb_errorv(part_name,
427                ": Hash of data does not match digest in descriptor.\n",
428                NULL);
429     ret = AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION;
430     goto out;
431   }
432 
433   ret = AVB_SLOT_VERIFY_RESULT_OK;
434 
435 out:
436 
437   /* If it worked and something was loaded, copy to slot_data. */
438   if ((ret == AVB_SLOT_VERIFY_RESULT_OK || result_should_continue(ret)) &&
439       image_buf != NULL) {
440     AvbPartitionData* loaded_partition;
441     if (slot_data->num_loaded_partitions == MAX_NUMBER_OF_LOADED_PARTITIONS) {
442       avb_errorv(part_name, ": Too many loaded partitions.\n", NULL);
443       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
444       goto fail;
445     }
446     loaded_partition =
447         &slot_data->loaded_partitions[slot_data->num_loaded_partitions++];
448     loaded_partition->partition_name = avb_strdup(found);
449     loaded_partition->data_size = image_size;
450     loaded_partition->data = image_buf;
451     loaded_partition->preloaded = image_preloaded;
452     image_buf = NULL;
453   }
454 
455 fail:
456   if (image_buf != NULL && !image_preloaded) {
457     avb_free(image_buf);
458   }
459   return ret;
460 }
461 
load_requested_partitions(AvbOps * ops,const char * const * requested_partitions,const char * ab_suffix,AvbSlotVerifyData * slot_data)462 static AvbSlotVerifyResult load_requested_partitions(
463     AvbOps* ops,
464     const char* const* requested_partitions,
465     const char* ab_suffix,
466     AvbSlotVerifyData* slot_data) {
467   AvbSlotVerifyResult ret;
468   uint8_t* image_buf = NULL;
469   bool image_preloaded = false;
470   size_t n;
471 
472   for (n = 0; requested_partitions[n] != NULL; n++) {
473     char part_name[AVB_PART_NAME_MAX_SIZE];
474     AvbIOResult io_ret;
475     uint64_t image_size;
476     AvbPartitionData* loaded_partition;
477 
478     if (!avb_str_concat(part_name,
479                         sizeof part_name,
480                         requested_partitions[n],
481                         avb_strlen(requested_partitions[n]),
482                         ab_suffix,
483                         avb_strlen(ab_suffix))) {
484       avb_error("Partition name and suffix does not fit.\n");
485       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
486       goto out;
487     }
488 
489     io_ret = ops->get_size_of_partition(ops, part_name, &image_size);
490     if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
491       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
492       goto out;
493     } else if (io_ret != AVB_IO_RESULT_OK) {
494       avb_errorv(part_name, ": Error determining partition size.\n", NULL);
495       ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
496       goto out;
497     }
498     avb_debugv(part_name, ": Loading entire partition.\n", NULL);
499 
500     ret = load_full_partition(
501         ops, part_name, image_size, &image_buf, &image_preloaded);
502     if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
503       goto out;
504     }
505 
506     /* Move to slot_data. */
507     if (slot_data->num_loaded_partitions == MAX_NUMBER_OF_LOADED_PARTITIONS) {
508       avb_errorv(part_name, ": Too many loaded partitions.\n", NULL);
509       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
510       goto out;
511     }
512     loaded_partition =
513         &slot_data->loaded_partitions[slot_data->num_loaded_partitions++];
514     loaded_partition->partition_name = avb_strdup(requested_partitions[n]);
515     if (loaded_partition->partition_name == NULL) {
516       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
517       goto out;
518     }
519     loaded_partition->data_size = image_size;
520     loaded_partition->data = image_buf; /* Transferring the owner. */
521     loaded_partition->preloaded = image_preloaded;
522     image_buf = NULL;
523     image_preloaded = false;
524   }
525 
526   ret = AVB_SLOT_VERIFY_RESULT_OK;
527 
528 out:
529   /* Free the current buffer if any. */
530   if (image_buf != NULL && !image_preloaded) {
531     avb_free(image_buf);
532   }
533   /* Buffers that are already saved in slot_data will be handled by the caller
534    * even on failure. */
535   return ret;
536 }
537 
load_and_verify_vbmeta(AvbOps * ops,const char * const * requested_partitions,const char * ab_suffix,AvbSlotVerifyFlags flags,bool allow_verification_error,AvbVBMetaImageFlags toplevel_vbmeta_flags,int rollback_index_location,const char * partition_name,size_t partition_name_len,const uint8_t * expected_public_key,size_t expected_public_key_length,AvbSlotVerifyData * slot_data,AvbAlgorithmType * out_algorithm_type,AvbCmdlineSubstList * out_additional_cmdline_subst)538 static AvbSlotVerifyResult load_and_verify_vbmeta(
539     AvbOps* ops,
540     const char* const* requested_partitions,
541     const char* ab_suffix,
542     AvbSlotVerifyFlags flags,
543     bool allow_verification_error,
544     AvbVBMetaImageFlags toplevel_vbmeta_flags,
545     int rollback_index_location,
546     const char* partition_name,
547     size_t partition_name_len,
548     const uint8_t* expected_public_key,
549     size_t expected_public_key_length,
550     AvbSlotVerifyData* slot_data,
551     AvbAlgorithmType* out_algorithm_type,
552     AvbCmdlineSubstList* out_additional_cmdline_subst) {
553   char full_partition_name[AVB_PART_NAME_MAX_SIZE];
554   AvbSlotVerifyResult ret;
555   AvbIOResult io_ret;
556   size_t vbmeta_offset;
557   size_t vbmeta_size;
558   uint8_t* vbmeta_buf = NULL;
559   size_t vbmeta_num_read;
560   AvbVBMetaVerifyResult vbmeta_ret;
561   const uint8_t* pk_data;
562   size_t pk_len;
563   AvbVBMetaImageHeader vbmeta_header;
564   uint64_t stored_rollback_index;
565   const AvbDescriptor** descriptors = NULL;
566   size_t num_descriptors;
567   size_t n;
568   bool is_main_vbmeta;
569   bool look_for_vbmeta_footer;
570   AvbVBMetaData* vbmeta_image_data = NULL;
571 
572   ret = AVB_SLOT_VERIFY_RESULT_OK;
573 
574   avb_assert(slot_data != NULL);
575 
576   /* Since we allow top-level vbmeta in 'boot', use
577    * rollback_index_location to determine whether we're the main
578    * vbmeta struct.
579    */
580   is_main_vbmeta = false;
581   if (rollback_index_location == 0) {
582     if ((flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION) == 0) {
583       is_main_vbmeta = true;
584     }
585   }
586 
587   /* Don't use footers for vbmeta partitions ('vbmeta' or
588    * 'vbmeta_<partition_name>').
589    */
590   look_for_vbmeta_footer = true;
591   if (avb_strncmp(partition_name, "vbmeta", avb_strlen("vbmeta")) == 0) {
592     look_for_vbmeta_footer = false;
593   }
594 
595   if (!avb_validate_utf8((const uint8_t*)partition_name, partition_name_len)) {
596     avb_error("Partition name is not valid UTF-8.\n");
597     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
598     goto out;
599   }
600 
601   /* Construct full partition name e.g. system_a. */
602   if (!avb_str_concat(full_partition_name,
603                       sizeof full_partition_name,
604                       partition_name,
605                       partition_name_len,
606                       ab_suffix,
607                       avb_strlen(ab_suffix))) {
608     avb_error("Partition name and suffix does not fit.\n");
609     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
610     goto out;
611   }
612 
613   /* If we're loading from the main vbmeta partition, the vbmeta struct is in
614    * the beginning. Otherwise we may have to locate it via a footer... if no
615    * footer is found, we look in the beginning to support e.g. vbmeta_<org>
616    * partitions holding data for e.g. super partitions (b/80195851 for
617    * rationale).
618    */
619   vbmeta_offset = 0;
620   vbmeta_size = VBMETA_MAX_SIZE;
621   if (look_for_vbmeta_footer) {
622     uint8_t footer_buf[AVB_FOOTER_SIZE];
623     size_t footer_num_read;
624     AvbFooter footer;
625 
626     io_ret = ops->read_from_partition(ops,
627                                       full_partition_name,
628                                       -AVB_FOOTER_SIZE,
629                                       AVB_FOOTER_SIZE,
630                                       footer_buf,
631                                       &footer_num_read);
632     if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
633       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
634       goto out;
635     } else if (io_ret != AVB_IO_RESULT_OK) {
636       avb_errorv(full_partition_name, ": Error loading footer.\n", NULL);
637       ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
638       goto out;
639     }
640     avb_assert(footer_num_read == AVB_FOOTER_SIZE);
641 
642     if (!avb_footer_validate_and_byteswap((const AvbFooter*)footer_buf,
643                                           &footer)) {
644       avb_debugv(full_partition_name, ": No footer detected.\n", NULL);
645     } else {
646       /* Basic footer sanity check since the data is untrusted. */
647       if (footer.vbmeta_size > VBMETA_MAX_SIZE) {
648         avb_errorv(
649             full_partition_name, ": Invalid vbmeta size in footer.\n", NULL);
650       } else {
651         vbmeta_offset = footer.vbmeta_offset;
652         vbmeta_size = footer.vbmeta_size;
653       }
654     }
655   }
656 
657   vbmeta_buf = avb_malloc(vbmeta_size);
658   if (vbmeta_buf == NULL) {
659     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
660     goto out;
661   }
662 
663   if (vbmeta_offset != 0) {
664     avb_debugv("Loading vbmeta struct in footer from partition '",
665                full_partition_name,
666                "'.\n",
667                NULL);
668   } else {
669     avb_debugv("Loading vbmeta struct from partition '",
670                full_partition_name,
671                "'.\n",
672                NULL);
673   }
674 
675   io_ret = ops->read_from_partition(ops,
676                                     full_partition_name,
677                                     vbmeta_offset,
678                                     vbmeta_size,
679                                     vbmeta_buf,
680                                     &vbmeta_num_read);
681   if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
682     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
683     goto out;
684   } else if (io_ret != AVB_IO_RESULT_OK) {
685     /* If we're looking for 'vbmeta' but there is no such partition,
686      * go try to get it from the boot partition instead.
687      */
688     if (is_main_vbmeta && io_ret == AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION &&
689         !look_for_vbmeta_footer) {
690       avb_debugv(full_partition_name,
691                  ": No such partition. Trying 'boot' instead.\n",
692                  NULL);
693       ret = load_and_verify_vbmeta(ops,
694                                    requested_partitions,
695                                    ab_suffix,
696                                    flags,
697                                    allow_verification_error,
698                                    0 /* toplevel_vbmeta_flags */,
699                                    0 /* rollback_index_location */,
700                                    "boot",
701                                    avb_strlen("boot"),
702                                    NULL /* expected_public_key */,
703                                    0 /* expected_public_key_length */,
704                                    slot_data,
705                                    out_algorithm_type,
706                                    out_additional_cmdline_subst);
707       goto out;
708     } else {
709       avb_errorv(full_partition_name, ": Error loading vbmeta data.\n", NULL);
710       ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
711       goto out;
712     }
713   }
714   avb_assert(vbmeta_num_read <= vbmeta_size);
715 
716   /* Check if the image is properly signed and get the public key used
717    * to sign the image.
718    */
719   vbmeta_ret =
720       avb_vbmeta_image_verify(vbmeta_buf, vbmeta_num_read, &pk_data, &pk_len);
721   switch (vbmeta_ret) {
722     case AVB_VBMETA_VERIFY_RESULT_OK:
723       avb_assert(pk_data != NULL && pk_len > 0);
724       break;
725 
726     case AVB_VBMETA_VERIFY_RESULT_OK_NOT_SIGNED:
727     case AVB_VBMETA_VERIFY_RESULT_HASH_MISMATCH:
728     case AVB_VBMETA_VERIFY_RESULT_SIGNATURE_MISMATCH:
729       ret = AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION;
730       avb_errorv(full_partition_name,
731                  ": Error verifying vbmeta image: ",
732                  avb_vbmeta_verify_result_to_string(vbmeta_ret),
733                  "\n",
734                  NULL);
735       if (!allow_verification_error) {
736         goto out;
737       }
738       break;
739 
740     case AVB_VBMETA_VERIFY_RESULT_INVALID_VBMETA_HEADER:
741       /* No way to continue this case. */
742       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
743       avb_errorv(full_partition_name,
744                  ": Error verifying vbmeta image: invalid vbmeta header\n",
745                  NULL);
746       goto out;
747 
748     case AVB_VBMETA_VERIFY_RESULT_UNSUPPORTED_VERSION:
749       /* No way to continue this case. */
750       ret = AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION;
751       avb_errorv(full_partition_name,
752                  ": Error verifying vbmeta image: unsupported AVB version\n",
753                  NULL);
754       goto out;
755   }
756 
757   /* Byteswap the header. */
758   avb_vbmeta_image_header_to_host_byte_order((AvbVBMetaImageHeader*)vbmeta_buf,
759                                              &vbmeta_header);
760 
761   /* If we're the toplevel, assign flags so they'll be passed down. */
762   if (is_main_vbmeta) {
763     toplevel_vbmeta_flags = (AvbVBMetaImageFlags)vbmeta_header.flags;
764   } else {
765     if (vbmeta_header.flags != 0) {
766       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
767       avb_errorv(full_partition_name,
768                  ": chained vbmeta image has non-zero flags\n",
769                  NULL);
770       goto out;
771     }
772   }
773 
774   uint32_t rollback_index_location_to_use = rollback_index_location;
775 
776   /* Check if key used to make signature matches what is expected. */
777   if (pk_data != NULL) {
778     if (expected_public_key != NULL) {
779       avb_assert(!is_main_vbmeta);
780       if (expected_public_key_length != pk_len ||
781           avb_safe_memcmp(expected_public_key, pk_data, pk_len) != 0) {
782         avb_errorv(full_partition_name,
783                    ": Public key used to sign data does not match key in chain "
784                    "partition descriptor.\n",
785                    NULL);
786         ret = AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED;
787         if (!allow_verification_error) {
788           goto out;
789         }
790       }
791     } else {
792       bool key_is_trusted = false;
793       const uint8_t* pk_metadata = NULL;
794       size_t pk_metadata_len = 0;
795 
796       if (vbmeta_header.public_key_metadata_size > 0) {
797         pk_metadata = vbmeta_buf + sizeof(AvbVBMetaImageHeader) +
798                       vbmeta_header.authentication_data_block_size +
799                       vbmeta_header.public_key_metadata_offset;
800         pk_metadata_len = vbmeta_header.public_key_metadata_size;
801       }
802 
803       // If we're not using a vbmeta partition, need to use another AvbOps...
804       if (flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION) {
805         io_ret = ops->validate_public_key_for_partition(
806             ops,
807             full_partition_name,
808             pk_data,
809             pk_len,
810             pk_metadata,
811             pk_metadata_len,
812             &key_is_trusted,
813             &rollback_index_location_to_use);
814       } else {
815         avb_assert(is_main_vbmeta);
816         io_ret = ops->validate_vbmeta_public_key(ops,
817                                                  pk_data,
818                                                  pk_len,
819                                                  pk_metadata,
820                                                  pk_metadata_len,
821                                                  &key_is_trusted);
822       }
823 
824       if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
825         ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
826         goto out;
827       } else if (io_ret != AVB_IO_RESULT_OK) {
828         avb_errorv(full_partition_name,
829                    ": Error while checking public key used to sign data.\n",
830                    NULL);
831         ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
832         goto out;
833       }
834       if (!key_is_trusted) {
835         avb_errorv(full_partition_name,
836                    ": Public key used to sign data rejected.\n",
837                    NULL);
838         ret = AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED;
839         if (!allow_verification_error) {
840           goto out;
841         }
842       }
843     }
844   }
845 
846   /* Check rollback index. */
847   io_ret = ops->read_rollback_index(
848       ops, rollback_index_location_to_use, &stored_rollback_index);
849   if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
850     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
851     goto out;
852   } else if (io_ret != AVB_IO_RESULT_OK) {
853     avb_errorv(full_partition_name,
854                ": Error getting rollback index for location.\n",
855                NULL);
856     ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
857     goto out;
858   }
859   if (vbmeta_header.rollback_index < stored_rollback_index) {
860     avb_errorv(
861         full_partition_name,
862         ": Image rollback index is less than the stored rollback index.\n",
863         NULL);
864     ret = AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX;
865     if (!allow_verification_error) {
866       goto out;
867     }
868   }
869 
870   /* Copy vbmeta to vbmeta_images before recursing. */
871   if (is_main_vbmeta) {
872     avb_assert(slot_data->num_vbmeta_images == 0);
873   } else {
874     if (!(flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION)) {
875       avb_assert(slot_data->num_vbmeta_images > 0);
876     }
877   }
878   if (slot_data->num_vbmeta_images == MAX_NUMBER_OF_VBMETA_IMAGES) {
879     avb_errorv(full_partition_name, ": Too many vbmeta images.\n", NULL);
880     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
881     goto out;
882   }
883   vbmeta_image_data = &slot_data->vbmeta_images[slot_data->num_vbmeta_images++];
884   vbmeta_image_data->partition_name = avb_strdup(partition_name);
885   vbmeta_image_data->vbmeta_data = vbmeta_buf;
886   /* Note that |vbmeta_buf| is actually |vbmeta_num_read| bytes long
887    * and this includes data past the end of the image. Pass the
888    * actual size of the vbmeta image. Also, no need to use
889    * avb_safe_add() since the header has already been verified.
890    */
891   vbmeta_image_data->vbmeta_size =
892       sizeof(AvbVBMetaImageHeader) +
893       vbmeta_header.authentication_data_block_size +
894       vbmeta_header.auxiliary_data_block_size;
895   vbmeta_image_data->verify_result = vbmeta_ret;
896 
897   /* If verification has been disabled by setting a bit in the image,
898    * we're done... except that we need to load the entirety of the
899    * requested partitions.
900    */
901   if (vbmeta_header.flags & AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED) {
902     AvbSlotVerifyResult sub_ret;
903     avb_debugv(
904         full_partition_name, ": VERIFICATION_DISABLED bit is set.\n", NULL);
905     /* If load_requested_partitions() fail it is always a fatal
906      * failure (e.g. ERROR_INVALID_ARGUMENT, ERROR_OOM, etc.) rather
907      * than recoverable (e.g. one where result_should_continue()
908      * returns true) and we want to convey that error.
909      */
910     sub_ret = load_requested_partitions(
911         ops, requested_partitions, ab_suffix, slot_data);
912     if (sub_ret != AVB_SLOT_VERIFY_RESULT_OK) {
913       ret = sub_ret;
914     }
915     goto out;
916   }
917 
918   /* Now go through all descriptors and take the appropriate action:
919    *
920    * - hash descriptor: Load data from partition, calculate hash, and
921    *   checks that it matches what's in the hash descriptor.
922    *
923    * - hashtree descriptor: Do nothing since verification happens
924    *   on-the-fly from within the OS. (Unless the descriptor uses a
925    *   persistent digest, in which case we need to find it).
926    *
927    * - chained partition descriptor: Load the footer, load the vbmeta
928    *   image, verify vbmeta image (includes rollback checks, hash
929    *   checks, bail on chained partitions).
930    */
931   descriptors =
932       avb_descriptor_get_all(vbmeta_buf, vbmeta_num_read, &num_descriptors);
933   for (n = 0; n < num_descriptors; n++) {
934     AvbDescriptor desc;
935 
936     if (!avb_descriptor_validate_and_byteswap(descriptors[n], &desc)) {
937       avb_errorv(full_partition_name, ": Descriptor is invalid.\n", NULL);
938       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
939       goto out;
940     }
941 
942     switch (desc.tag) {
943       case AVB_DESCRIPTOR_TAG_HASH: {
944         AvbSlotVerifyResult sub_ret;
945         sub_ret = load_and_verify_hash_partition(ops,
946                                                  requested_partitions,
947                                                  ab_suffix,
948                                                  allow_verification_error,
949                                                  descriptors[n],
950                                                  slot_data);
951         if (sub_ret != AVB_SLOT_VERIFY_RESULT_OK) {
952           ret = sub_ret;
953           if (!allow_verification_error || !result_should_continue(ret)) {
954             goto out;
955           }
956         }
957       } break;
958 
959       case AVB_DESCRIPTOR_TAG_CHAIN_PARTITION: {
960         AvbSlotVerifyResult sub_ret;
961         AvbChainPartitionDescriptor chain_desc;
962         const uint8_t* chain_partition_name;
963         const uint8_t* chain_public_key;
964 
965         /* Only allow CHAIN_PARTITION descriptors in the main vbmeta image. */
966         if (!is_main_vbmeta) {
967           avb_errorv(full_partition_name,
968                      ": Encountered chain descriptor not in main image.\n",
969                      NULL);
970           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
971           goto out;
972         }
973 
974         if (!avb_chain_partition_descriptor_validate_and_byteswap(
975                 (AvbChainPartitionDescriptor*)descriptors[n], &chain_desc)) {
976           avb_errorv(full_partition_name,
977                      ": Chain partition descriptor is invalid.\n",
978                      NULL);
979           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
980           goto out;
981         }
982 
983         if (chain_desc.rollback_index_location == 0) {
984           avb_errorv(full_partition_name,
985                      ": Chain partition has invalid "
986                      "rollback_index_location field.\n",
987                      NULL);
988           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
989           goto out;
990         }
991 
992         chain_partition_name = ((const uint8_t*)descriptors[n]) +
993                                sizeof(AvbChainPartitionDescriptor);
994         chain_public_key = chain_partition_name + chain_desc.partition_name_len;
995 
996         sub_ret =
997             load_and_verify_vbmeta(ops,
998                                    requested_partitions,
999                                    ab_suffix,
1000                                    flags,
1001                                    allow_verification_error,
1002                                    toplevel_vbmeta_flags,
1003                                    chain_desc.rollback_index_location,
1004                                    (const char*)chain_partition_name,
1005                                    chain_desc.partition_name_len,
1006                                    chain_public_key,
1007                                    chain_desc.public_key_len,
1008                                    slot_data,
1009                                    NULL, /* out_algorithm_type */
1010                                    NULL /* out_additional_cmdline_subst */);
1011         if (sub_ret != AVB_SLOT_VERIFY_RESULT_OK) {
1012           ret = sub_ret;
1013           if (!result_should_continue(ret)) {
1014             goto out;
1015           }
1016         }
1017       } break;
1018 
1019       case AVB_DESCRIPTOR_TAG_KERNEL_CMDLINE: {
1020         const uint8_t* kernel_cmdline;
1021         AvbKernelCmdlineDescriptor kernel_cmdline_desc;
1022         bool apply_cmdline;
1023 
1024         if (!avb_kernel_cmdline_descriptor_validate_and_byteswap(
1025                 (AvbKernelCmdlineDescriptor*)descriptors[n],
1026                 &kernel_cmdline_desc)) {
1027           avb_errorv(full_partition_name,
1028                      ": Kernel cmdline descriptor is invalid.\n",
1029                      NULL);
1030           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1031           goto out;
1032         }
1033 
1034         kernel_cmdline = ((const uint8_t*)descriptors[n]) +
1035                          sizeof(AvbKernelCmdlineDescriptor);
1036 
1037         if (!avb_validate_utf8(kernel_cmdline,
1038                                kernel_cmdline_desc.kernel_cmdline_length)) {
1039           avb_errorv(full_partition_name,
1040                      ": Kernel cmdline is not valid UTF-8.\n",
1041                      NULL);
1042           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1043           goto out;
1044         }
1045 
1046         /* Compare the flags for top-level VBMeta struct with flags in
1047          * the command-line descriptor so command-line snippets only
1048          * intended for a certain mode (dm-verity enabled/disabled)
1049          * are skipped if applicable.
1050          */
1051         apply_cmdline = true;
1052         if (toplevel_vbmeta_flags & AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED) {
1053           if (kernel_cmdline_desc.flags &
1054               AVB_KERNEL_CMDLINE_FLAGS_USE_ONLY_IF_HASHTREE_NOT_DISABLED) {
1055             apply_cmdline = false;
1056           }
1057         } else {
1058           if (kernel_cmdline_desc.flags &
1059               AVB_KERNEL_CMDLINE_FLAGS_USE_ONLY_IF_HASHTREE_DISABLED) {
1060             apply_cmdline = false;
1061           }
1062         }
1063 
1064         if (apply_cmdline) {
1065           if (slot_data->cmdline == NULL) {
1066             slot_data->cmdline =
1067                 avb_calloc(kernel_cmdline_desc.kernel_cmdline_length + 1);
1068             if (slot_data->cmdline == NULL) {
1069               ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1070               goto out;
1071             }
1072             avb_memcpy(slot_data->cmdline,
1073                        kernel_cmdline,
1074                        kernel_cmdline_desc.kernel_cmdline_length);
1075           } else {
1076             /* new cmdline is: <existing_cmdline> + ' ' + <newcmdline> + '\0' */
1077             size_t orig_size = avb_strlen(slot_data->cmdline);
1078             size_t new_size =
1079                 orig_size + 1 + kernel_cmdline_desc.kernel_cmdline_length + 1;
1080             char* new_cmdline = avb_calloc(new_size);
1081             if (new_cmdline == NULL) {
1082               ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1083               goto out;
1084             }
1085             avb_memcpy(new_cmdline, slot_data->cmdline, orig_size);
1086             new_cmdline[orig_size] = ' ';
1087             avb_memcpy(new_cmdline + orig_size + 1,
1088                        kernel_cmdline,
1089                        kernel_cmdline_desc.kernel_cmdline_length);
1090             avb_free(slot_data->cmdline);
1091             slot_data->cmdline = new_cmdline;
1092           }
1093         }
1094       } break;
1095 
1096       case AVB_DESCRIPTOR_TAG_HASHTREE: {
1097         AvbHashtreeDescriptor hashtree_desc;
1098 
1099         if (!avb_hashtree_descriptor_validate_and_byteswap(
1100                 (AvbHashtreeDescriptor*)descriptors[n], &hashtree_desc)) {
1101           avb_errorv(
1102               full_partition_name, ": Hashtree descriptor is invalid.\n", NULL);
1103           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1104           goto out;
1105         }
1106 
1107         /* We only need to continue when there is no digest in the descriptor.
1108          * This is because the only processing here is to find the digest and
1109          * make it available on the kernel command line.
1110          */
1111         if (hashtree_desc.root_digest_len == 0) {
1112           char part_name[AVB_PART_NAME_MAX_SIZE];
1113           size_t digest_len = 0;
1114           uint8_t digest_buf[AVB_SHA512_DIGEST_SIZE];
1115           const uint8_t* desc_partition_name =
1116               ((const uint8_t*)descriptors[n]) + sizeof(AvbHashtreeDescriptor);
1117 
1118           if (!avb_validate_utf8(desc_partition_name,
1119                                  hashtree_desc.partition_name_len)) {
1120             avb_error("Partition name is not valid UTF-8.\n");
1121             ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1122             goto out;
1123           }
1124 
1125           /* No ab_suffix for partitions without a digest in the descriptor
1126            * because these partitions hold data unique to this device and are
1127            * not updated using an A/B scheme.
1128            */
1129           if ((hashtree_desc.flags &
1130                AVB_HASHTREE_DESCRIPTOR_FLAGS_DO_NOT_USE_AB) == 0 &&
1131               avb_strlen(ab_suffix) != 0) {
1132             avb_error("Cannot use A/B with a persistent root digest.\n");
1133             ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1134             goto out;
1135           }
1136           if (hashtree_desc.partition_name_len >= AVB_PART_NAME_MAX_SIZE) {
1137             avb_error("Partition name does not fit.\n");
1138             ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1139             goto out;
1140           }
1141           avb_memcpy(
1142               part_name, desc_partition_name, hashtree_desc.partition_name_len);
1143           part_name[hashtree_desc.partition_name_len] = '\0';
1144 
1145           /* Determine the expected digest size from the hash algorithm. */
1146           if (avb_strcmp((const char*)hashtree_desc.hash_algorithm, "sha1") ==
1147               0) {
1148             digest_len = AVB_SHA1_DIGEST_SIZE;
1149           } else if (avb_strcmp((const char*)hashtree_desc.hash_algorithm,
1150                                 "sha256") == 0) {
1151             digest_len = AVB_SHA256_DIGEST_SIZE;
1152           } else if (avb_strcmp((const char*)hashtree_desc.hash_algorithm,
1153                                 "sha512") == 0) {
1154             digest_len = AVB_SHA512_DIGEST_SIZE;
1155           } else {
1156             avb_errorv(part_name, ": Unsupported hash algorithm.\n", NULL);
1157             ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1158             goto out;
1159           }
1160 
1161           ret = read_persistent_digest(ops,
1162                                        part_name,
1163                                        digest_len,
1164                                        NULL /* initial_digest */,
1165                                        digest_buf);
1166           if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
1167             goto out;
1168           }
1169 
1170           if (out_additional_cmdline_subst) {
1171             ret =
1172                 avb_add_root_digest_substitution(part_name,
1173                                                  digest_buf,
1174                                                  digest_len,
1175                                                  out_additional_cmdline_subst);
1176             if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
1177               goto out;
1178             }
1179           }
1180         }
1181       } break;
1182 
1183       case AVB_DESCRIPTOR_TAG_PROPERTY:
1184         /* Do nothing. */
1185         break;
1186     }
1187   }
1188 
1189   if (rollback_index_location < 0 ||
1190       rollback_index_location >= AVB_MAX_NUMBER_OF_ROLLBACK_INDEX_LOCATIONS) {
1191     avb_errorv(
1192         full_partition_name, ": Invalid rollback_index_location.\n", NULL);
1193     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1194     goto out;
1195   }
1196 
1197   slot_data->rollback_indexes[rollback_index_location] =
1198       vbmeta_header.rollback_index;
1199 
1200   if (out_algorithm_type != NULL) {
1201     *out_algorithm_type = (AvbAlgorithmType)vbmeta_header.algorithm_type;
1202   }
1203 
1204 out:
1205   /* If |vbmeta_image_data| isn't NULL it means that it adopted
1206    * |vbmeta_buf| so in that case don't free it here.
1207    */
1208   if (vbmeta_image_data == NULL) {
1209     if (vbmeta_buf != NULL) {
1210       avb_free(vbmeta_buf);
1211     }
1212   }
1213   if (descriptors != NULL) {
1214     avb_free(descriptors);
1215   }
1216   return ret;
1217 }
1218 
avb_manage_hashtree_error_mode(AvbOps * ops,AvbSlotVerifyFlags flags,AvbSlotVerifyData * data,AvbHashtreeErrorMode * out_hashtree_error_mode)1219 static AvbIOResult avb_manage_hashtree_error_mode(
1220     AvbOps* ops,
1221     AvbSlotVerifyFlags flags,
1222     AvbSlotVerifyData* data,
1223     AvbHashtreeErrorMode* out_hashtree_error_mode) {
1224   AvbHashtreeErrorMode ret = AVB_HASHTREE_ERROR_MODE_RESTART;
1225   AvbIOResult io_ret = AVB_IO_RESULT_OK;
1226   uint8_t vbmeta_digest_sha256[AVB_SHA256_DIGEST_SIZE];
1227   uint8_t stored_vbmeta_digest_sha256[AVB_SHA256_DIGEST_SIZE];
1228   size_t num_bytes_read;
1229 
1230   avb_assert(out_hashtree_error_mode != NULL);
1231   avb_assert(ops->read_persistent_value != NULL);
1232   avb_assert(ops->write_persistent_value != NULL);
1233 
1234   // If we're rebooting because of dm-verity corruption, make a note of
1235   // the vbmeta hash so we can stay in 'eio' mode until things change.
1236   if (flags & AVB_SLOT_VERIFY_FLAGS_RESTART_CAUSED_BY_HASHTREE_CORRUPTION) {
1237     avb_debug(
1238         "Rebooting because of dm-verity corruption - "
1239         "recording OS instance and using 'eio' mode.\n");
1240     avb_slot_verify_data_calculate_vbmeta_digest(
1241         data, AVB_DIGEST_TYPE_SHA256, vbmeta_digest_sha256);
1242     io_ret = ops->write_persistent_value(ops,
1243                                          AVB_NPV_MANAGED_VERITY_MODE,
1244                                          AVB_SHA256_DIGEST_SIZE,
1245                                          vbmeta_digest_sha256);
1246     if (io_ret != AVB_IO_RESULT_OK) {
1247       avb_error("Error writing to " AVB_NPV_MANAGED_VERITY_MODE ".\n");
1248       goto out;
1249     }
1250     ret = AVB_HASHTREE_ERROR_MODE_EIO;
1251     io_ret = AVB_IO_RESULT_OK;
1252     goto out;
1253   }
1254 
1255   // See if we're in 'eio' mode.
1256   io_ret = ops->read_persistent_value(ops,
1257                                       AVB_NPV_MANAGED_VERITY_MODE,
1258                                       AVB_SHA256_DIGEST_SIZE,
1259                                       stored_vbmeta_digest_sha256,
1260                                       &num_bytes_read);
1261   if (io_ret == AVB_IO_RESULT_ERROR_NO_SUCH_VALUE ||
1262       (io_ret == AVB_IO_RESULT_OK && num_bytes_read == 0)) {
1263     // This is the usual case ('eio' mode not set).
1264     avb_debug("No dm-verity corruption - using in 'restart' mode.\n");
1265     ret = AVB_HASHTREE_ERROR_MODE_RESTART;
1266     io_ret = AVB_IO_RESULT_OK;
1267     goto out;
1268   } else if (io_ret != AVB_IO_RESULT_OK) {
1269     avb_error("Error reading from " AVB_NPV_MANAGED_VERITY_MODE ".\n");
1270     goto out;
1271   }
1272   if (num_bytes_read != AVB_SHA256_DIGEST_SIZE) {
1273     avb_error(
1274         "Unexpected number of bytes read from " AVB_NPV_MANAGED_VERITY_MODE
1275         ".\n");
1276     io_ret = AVB_IO_RESULT_ERROR_IO;
1277     goto out;
1278   }
1279 
1280   // OK, so we're currently in 'eio' mode and the vbmeta digest of the OS
1281   // that caused this is in |stored_vbmeta_digest_sha256| ... now see if
1282   // the OS we're dealing with now is the same.
1283   avb_slot_verify_data_calculate_vbmeta_digest(
1284       data, AVB_DIGEST_TYPE_SHA256, vbmeta_digest_sha256);
1285   if (avb_memcmp(vbmeta_digest_sha256,
1286                  stored_vbmeta_digest_sha256,
1287                  AVB_SHA256_DIGEST_SIZE) == 0) {
1288     // It's the same so we're still in 'eio' mode.
1289     avb_debug("Same OS instance detected - staying in 'eio' mode.\n");
1290     ret = AVB_HASHTREE_ERROR_MODE_EIO;
1291     io_ret = AVB_IO_RESULT_OK;
1292   } else {
1293     // It did change!
1294     avb_debug(
1295         "New OS instance detected - changing from 'eio' to 'restart' mode.\n");
1296     io_ret =
1297         ops->write_persistent_value(ops,
1298                                     AVB_NPV_MANAGED_VERITY_MODE,
1299                                     0,  // This clears the persistent property.
1300                                     vbmeta_digest_sha256);
1301     if (io_ret != AVB_IO_RESULT_OK) {
1302       avb_error("Error clearing " AVB_NPV_MANAGED_VERITY_MODE ".\n");
1303       goto out;
1304     }
1305     ret = AVB_HASHTREE_ERROR_MODE_RESTART;
1306     io_ret = AVB_IO_RESULT_OK;
1307   }
1308 
1309 out:
1310   *out_hashtree_error_mode = ret;
1311   return io_ret;
1312 }
1313 
has_system_partition(AvbOps * ops,const char * ab_suffix)1314 static bool has_system_partition(AvbOps* ops, const char* ab_suffix) {
1315   char part_name[AVB_PART_NAME_MAX_SIZE];
1316   char* system_part_name = "system";
1317   char guid_buf[37];
1318   AvbIOResult io_ret;
1319 
1320   if (!avb_str_concat(part_name,
1321                       sizeof part_name,
1322                       system_part_name,
1323                       avb_strlen(system_part_name),
1324                       ab_suffix,
1325                       avb_strlen(ab_suffix))) {
1326     avb_error("System partition name and suffix does not fit.\n");
1327     return false;
1328   }
1329 
1330   io_ret = ops->get_unique_guid_for_partition(
1331       ops, part_name, guid_buf, sizeof guid_buf);
1332   if (io_ret == AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION) {
1333     avb_debug("No system partition.\n");
1334     return false;
1335   } else if (io_ret != AVB_IO_RESULT_OK) {
1336     avb_error("Error getting unique GUID for system partition.\n");
1337     return false;
1338   }
1339 
1340   return true;
1341 }
1342 
avb_slot_verify(AvbOps * ops,const char * const * requested_partitions,const char * ab_suffix,AvbSlotVerifyFlags flags,AvbHashtreeErrorMode hashtree_error_mode,AvbSlotVerifyData ** out_data)1343 AvbSlotVerifyResult avb_slot_verify(AvbOps* ops,
1344                                     const char* const* requested_partitions,
1345                                     const char* ab_suffix,
1346                                     AvbSlotVerifyFlags flags,
1347                                     AvbHashtreeErrorMode hashtree_error_mode,
1348                                     AvbSlotVerifyData** out_data) {
1349   AvbSlotVerifyResult ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT;
1350   AvbSlotVerifyData* slot_data = NULL;
1351   AvbAlgorithmType algorithm_type = AVB_ALGORITHM_TYPE_NONE;
1352   bool using_boot_for_vbmeta = false;
1353   AvbVBMetaImageHeader toplevel_vbmeta;
1354   bool allow_verification_error =
1355       (flags & AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR);
1356   AvbCmdlineSubstList* additional_cmdline_subst = NULL;
1357 
1358   /* Fail early if we're missing the AvbOps needed for slot verification. */
1359   avb_assert(ops->read_is_device_unlocked != NULL);
1360   avb_assert(ops->read_from_partition != NULL);
1361   avb_assert(ops->get_size_of_partition != NULL);
1362   avb_assert(ops->read_rollback_index != NULL);
1363   avb_assert(ops->get_unique_guid_for_partition != NULL);
1364 
1365   if (out_data != NULL) {
1366     *out_data = NULL;
1367   }
1368 
1369   /* Allowing dm-verity errors defeats the purpose of verified boot so
1370    * only allow this if set up to allow verification errors
1371    * (e.g. typically only UNLOCKED mode).
1372    */
1373   if (hashtree_error_mode == AVB_HASHTREE_ERROR_MODE_LOGGING &&
1374       !allow_verification_error) {
1375     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT;
1376     goto fail;
1377   }
1378 
1379   /* Make sure passed-in AvbOps support persistent values if
1380    * asking for libavb to manage verity state.
1381    */
1382   if (hashtree_error_mode == AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO) {
1383     if (ops->read_persistent_value == NULL ||
1384         ops->write_persistent_value == NULL) {
1385       avb_error(
1386           "Persistent values required for "
1387           "AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO "
1388           "but are not implemented in given AvbOps.\n");
1389       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT;
1390       goto fail;
1391     }
1392   }
1393 
1394   /* Make sure passed-in AvbOps support verifying public keys and getting
1395    * rollback index location if not using a vbmeta partition.
1396    */
1397   if (flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION) {
1398     if (ops->validate_public_key_for_partition == NULL) {
1399       avb_error(
1400           "AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION was passed but the "
1401           "validate_public_key_for_partition() operation isn't implemented.\n");
1402       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT;
1403       goto fail;
1404     }
1405   } else {
1406     avb_assert(ops->validate_vbmeta_public_key != NULL);
1407   }
1408 
1409   slot_data = avb_calloc(sizeof(AvbSlotVerifyData));
1410   if (slot_data == NULL) {
1411     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1412     goto fail;
1413   }
1414   slot_data->vbmeta_images =
1415       avb_calloc(sizeof(AvbVBMetaData) * MAX_NUMBER_OF_VBMETA_IMAGES);
1416   if (slot_data->vbmeta_images == NULL) {
1417     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1418     goto fail;
1419   }
1420   slot_data->loaded_partitions =
1421       avb_calloc(sizeof(AvbPartitionData) * MAX_NUMBER_OF_LOADED_PARTITIONS);
1422   if (slot_data->loaded_partitions == NULL) {
1423     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1424     goto fail;
1425   }
1426 
1427   additional_cmdline_subst = avb_new_cmdline_subst_list();
1428   if (additional_cmdline_subst == NULL) {
1429     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1430     goto fail;
1431   }
1432 
1433   if (flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION) {
1434     if (requested_partitions == NULL || requested_partitions[0] == NULL) {
1435       avb_fatal(
1436           "Requested partitions cannot be empty when using "
1437           "AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION");
1438       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT;
1439       goto fail;
1440     }
1441 
1442     /* No vbmeta partition, go through each of the requested partitions... */
1443     for (size_t n = 0; requested_partitions[n] != NULL; n++) {
1444       ret = load_and_verify_vbmeta(ops,
1445                                    requested_partitions,
1446                                    ab_suffix,
1447                                    flags,
1448                                    allow_verification_error,
1449                                    0 /* toplevel_vbmeta_flags */,
1450                                    0 /* rollback_index_location */,
1451                                    requested_partitions[n],
1452                                    avb_strlen(requested_partitions[n]),
1453                                    NULL /* expected_public_key */,
1454                                    0 /* expected_public_key_length */,
1455                                    slot_data,
1456                                    &algorithm_type,
1457                                    additional_cmdline_subst);
1458       if (!allow_verification_error && ret != AVB_SLOT_VERIFY_RESULT_OK) {
1459         goto fail;
1460       }
1461     }
1462 
1463   } else {
1464     /* Usual path, load "vbmeta"... */
1465     ret = load_and_verify_vbmeta(ops,
1466                                  requested_partitions,
1467                                  ab_suffix,
1468                                  flags,
1469                                  allow_verification_error,
1470                                  0 /* toplevel_vbmeta_flags */,
1471                                  0 /* rollback_index_location */,
1472                                  "vbmeta",
1473                                  avb_strlen("vbmeta"),
1474                                  NULL /* expected_public_key */,
1475                                  0 /* expected_public_key_length */,
1476                                  slot_data,
1477                                  &algorithm_type,
1478                                  additional_cmdline_subst);
1479     if (!allow_verification_error && ret != AVB_SLOT_VERIFY_RESULT_OK) {
1480       goto fail;
1481     }
1482   }
1483 
1484   if (!result_should_continue(ret)) {
1485     goto fail;
1486   }
1487 
1488   /* If things check out, mangle the kernel command-line as needed. */
1489   if (!(flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION)) {
1490     if (avb_strcmp(slot_data->vbmeta_images[0].partition_name, "vbmeta") != 0) {
1491       avb_assert(
1492           avb_strcmp(slot_data->vbmeta_images[0].partition_name, "boot") == 0);
1493       using_boot_for_vbmeta = true;
1494     }
1495   }
1496 
1497   /* Byteswap top-level vbmeta header since we'll need it below. */
1498   avb_vbmeta_image_header_to_host_byte_order(
1499       (const AvbVBMetaImageHeader*)slot_data->vbmeta_images[0].vbmeta_data,
1500       &toplevel_vbmeta);
1501 
1502   /* Fill in |ab_suffix| field. */
1503   slot_data->ab_suffix = avb_strdup(ab_suffix);
1504   if (slot_data->ab_suffix == NULL) {
1505     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1506     goto fail;
1507   }
1508 
1509   /* If verification is disabled, we are done ... we specifically
1510    * don't want to add any androidboot.* options since verification
1511    * is disabled.
1512    */
1513   if (toplevel_vbmeta.flags & AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED) {
1514     /* Since verification is disabled we didn't process any
1515      * descriptors and thus there's no cmdline... so set root= such
1516      * that the system partition is mounted.
1517      */
1518     avb_assert(slot_data->cmdline == NULL);
1519     // Devices with dynamic partitions won't have system partition.
1520     // Instead, it has a large super partition to accommodate *.img files.
1521     // See b/119551429 for details.
1522     if (has_system_partition(ops, ab_suffix)) {
1523       slot_data->cmdline =
1524           avb_strdup("root=PARTUUID=$(ANDROID_SYSTEM_PARTUUID)");
1525     } else {
1526       // The |cmdline| field should be a NUL-terminated string.
1527       slot_data->cmdline = avb_strdup("");
1528     }
1529     if (slot_data->cmdline == NULL) {
1530       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1531       goto fail;
1532     }
1533   } else {
1534     /* If requested, manage dm-verity mode... */
1535     AvbHashtreeErrorMode resolved_hashtree_error_mode = hashtree_error_mode;
1536     if (hashtree_error_mode ==
1537         AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO) {
1538       AvbIOResult io_ret;
1539       io_ret = avb_manage_hashtree_error_mode(
1540           ops, flags, slot_data, &resolved_hashtree_error_mode);
1541       if (io_ret != AVB_IO_RESULT_OK) {
1542         ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
1543         if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
1544           ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1545         }
1546         goto fail;
1547       }
1548     }
1549     slot_data->resolved_hashtree_error_mode = resolved_hashtree_error_mode;
1550 
1551     /* Add options... */
1552     AvbSlotVerifyResult sub_ret;
1553     sub_ret = avb_append_options(ops,
1554                                  flags,
1555                                  slot_data,
1556                                  &toplevel_vbmeta,
1557                                  algorithm_type,
1558                                  hashtree_error_mode,
1559                                  resolved_hashtree_error_mode);
1560     if (sub_ret != AVB_SLOT_VERIFY_RESULT_OK) {
1561       ret = sub_ret;
1562       goto fail;
1563     }
1564   }
1565 
1566   /* Substitute $(ANDROID_SYSTEM_PARTUUID) and friends. */
1567   if (slot_data->cmdline != NULL && avb_strlen(slot_data->cmdline) != 0) {
1568     char* new_cmdline;
1569     new_cmdline = avb_sub_cmdline(ops,
1570                                   slot_data->cmdline,
1571                                   ab_suffix,
1572                                   using_boot_for_vbmeta,
1573                                   additional_cmdline_subst);
1574     if (new_cmdline != slot_data->cmdline) {
1575       if (new_cmdline == NULL) {
1576         ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1577         goto fail;
1578       }
1579       avb_free(slot_data->cmdline);
1580       slot_data->cmdline = new_cmdline;
1581     }
1582   }
1583 
1584   if (out_data != NULL) {
1585     *out_data = slot_data;
1586   } else {
1587     avb_slot_verify_data_free(slot_data);
1588   }
1589 
1590   avb_free_cmdline_subst_list(additional_cmdline_subst);
1591   additional_cmdline_subst = NULL;
1592 
1593   if (!allow_verification_error) {
1594     avb_assert(ret == AVB_SLOT_VERIFY_RESULT_OK);
1595   }
1596 
1597   return ret;
1598 
1599 fail:
1600   if (slot_data != NULL) {
1601     avb_slot_verify_data_free(slot_data);
1602   }
1603   if (additional_cmdline_subst != NULL) {
1604     avb_free_cmdline_subst_list(additional_cmdline_subst);
1605   }
1606   return ret;
1607 }
1608 
avb_slot_verify_data_free(AvbSlotVerifyData * data)1609 void avb_slot_verify_data_free(AvbSlotVerifyData* data) {
1610   if (data->ab_suffix != NULL) {
1611     avb_free(data->ab_suffix);
1612   }
1613   if (data->cmdline != NULL) {
1614     avb_free(data->cmdline);
1615   }
1616   if (data->vbmeta_images != NULL) {
1617     size_t n;
1618     for (n = 0; n < data->num_vbmeta_images; n++) {
1619       AvbVBMetaData* vbmeta_image = &data->vbmeta_images[n];
1620       if (vbmeta_image->partition_name != NULL) {
1621         avb_free(vbmeta_image->partition_name);
1622       }
1623       if (vbmeta_image->vbmeta_data != NULL) {
1624         avb_free(vbmeta_image->vbmeta_data);
1625       }
1626     }
1627     avb_free(data->vbmeta_images);
1628   }
1629   if (data->loaded_partitions != NULL) {
1630     size_t n;
1631     for (n = 0; n < data->num_loaded_partitions; n++) {
1632       AvbPartitionData* loaded_partition = &data->loaded_partitions[n];
1633       if (loaded_partition->partition_name != NULL) {
1634         avb_free(loaded_partition->partition_name);
1635       }
1636       if (loaded_partition->data != NULL && !loaded_partition->preloaded) {
1637         avb_free(loaded_partition->data);
1638       }
1639     }
1640     avb_free(data->loaded_partitions);
1641   }
1642   avb_free(data);
1643 }
1644 
avb_slot_verify_result_to_string(AvbSlotVerifyResult result)1645 const char* avb_slot_verify_result_to_string(AvbSlotVerifyResult result) {
1646   const char* ret = NULL;
1647 
1648   switch (result) {
1649     case AVB_SLOT_VERIFY_RESULT_OK:
1650       ret = "OK";
1651       break;
1652     case AVB_SLOT_VERIFY_RESULT_ERROR_OOM:
1653       ret = "ERROR_OOM";
1654       break;
1655     case AVB_SLOT_VERIFY_RESULT_ERROR_IO:
1656       ret = "ERROR_IO";
1657       break;
1658     case AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION:
1659       ret = "ERROR_VERIFICATION";
1660       break;
1661     case AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX:
1662       ret = "ERROR_ROLLBACK_INDEX";
1663       break;
1664     case AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED:
1665       ret = "ERROR_PUBLIC_KEY_REJECTED";
1666       break;
1667     case AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA:
1668       ret = "ERROR_INVALID_METADATA";
1669       break;
1670     case AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION:
1671       ret = "ERROR_UNSUPPORTED_VERSION";
1672       break;
1673     case AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT:
1674       ret = "ERROR_INVALID_ARGUMENT";
1675       break;
1676       /* Do not add a 'default:' case here because of -Wswitch. */
1677   }
1678 
1679   if (ret == NULL) {
1680     avb_error("Unknown AvbSlotVerifyResult value.\n");
1681     ret = "(unknown)";
1682   }
1683 
1684   return ret;
1685 }
1686 
avb_slot_verify_data_calculate_vbmeta_digest(AvbSlotVerifyData * data,AvbDigestType digest_type,uint8_t * out_digest)1687 void avb_slot_verify_data_calculate_vbmeta_digest(AvbSlotVerifyData* data,
1688                                                   AvbDigestType digest_type,
1689                                                   uint8_t* out_digest) {
1690   bool ret = false;
1691   size_t n;
1692 
1693   switch (digest_type) {
1694     case AVB_DIGEST_TYPE_SHA256: {
1695       AvbSHA256Ctx ctx;
1696       avb_sha256_init(&ctx);
1697       for (n = 0; n < data->num_vbmeta_images; n++) {
1698         avb_sha256_update(&ctx,
1699                           data->vbmeta_images[n].vbmeta_data,
1700                           data->vbmeta_images[n].vbmeta_size);
1701       }
1702       avb_memcpy(out_digest, avb_sha256_final(&ctx), AVB_SHA256_DIGEST_SIZE);
1703       ret = true;
1704     } break;
1705 
1706     case AVB_DIGEST_TYPE_SHA512: {
1707       AvbSHA512Ctx ctx;
1708       avb_sha512_init(&ctx);
1709       for (n = 0; n < data->num_vbmeta_images; n++) {
1710         avb_sha512_update(&ctx,
1711                           data->vbmeta_images[n].vbmeta_data,
1712                           data->vbmeta_images[n].vbmeta_size);
1713       }
1714       avb_memcpy(out_digest, avb_sha512_final(&ctx), AVB_SHA512_DIGEST_SIZE);
1715       ret = true;
1716     } break;
1717 
1718       /* Do not add a 'default:' case here because of -Wswitch. */
1719   }
1720 
1721   if (!ret) {
1722     avb_fatal("Unknown digest type");
1723   }
1724 }
1725