Fix a bug that would cause OoB memory read.

The magic number in avb_vbmeta_image_verify is checked before the
length is checked, thus if the structure size is less than the magic
number length, OoB memory would be read. This bug is found by running
a fuzz test that gives empty input to this function.

Tests: Added unit test.
Bug: b/133164384
Change-Id: Ib443ea5ee896a8b16fab9fb925637c5f58cc61e5
diff --git a/libavb/avb_vbmeta_image.c b/libavb/avb_vbmeta_image.c
index 21bbf92..b1879f6 100644
--- a/libavb/avb_vbmeta_image.c
+++ b/libavb/avb_vbmeta_image.c
@@ -54,17 +54,18 @@
     *out_public_key_length = 0;
   }
 
+  /* Before we byteswap or compare Magic, ensure length is long enough. */
+  if (length < sizeof(AvbVBMetaImageHeader)) {
+    avb_error("Length is smaller than header.\n");
+    goto out;
+  }
+
   /* Ensure magic is correct. */
   if (avb_safe_memcmp(data, AVB_MAGIC, AVB_MAGIC_LEN) != 0) {
     avb_error("Magic is incorrect.\n");
     goto out;
   }
 
-  /* Before we byteswap, ensure length is long enough. */
-  if (length < sizeof(AvbVBMetaImageHeader)) {
-    avb_error("Length is smaller than header.\n");
-    goto out;
-  }
   avb_vbmeta_image_header_to_host_byte_order((const AvbVBMetaImageHeader*)data,
                                              &h);
 
diff --git a/test/avb_vbmeta_image_unittest.cc b/test/avb_vbmeta_image_unittest.cc
index 5403cd2..9343eaf 100644
--- a/test/avb_vbmeta_image_unittest.cc
+++ b/test/avb_vbmeta_image_unittest.cc
@@ -404,6 +404,13 @@
                 vbmeta_image_.data(), vbmeta_image_.size(), NULL, NULL));
 }
 
+TEST_F(VerifyTest, VbmetaImageSmallerThanMagic) {
+  uint8_t vbmeta_onebyte[1] = {0};
+  EXPECT_EQ(AVB_VBMETA_VERIFY_RESULT_INVALID_VBMETA_HEADER,
+            avb_vbmeta_image_verify(
+                vbmeta_onebyte, 1, NULL, NULL));
+}
+
 bool VerifyTest::test_modification(AvbVBMetaVerifyResult expected_result,
                                    size_t offset,
                                    size_t length) {