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