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