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