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