puffin: Guard puffpatch against corrupt patches

This CL adds some size checks for the incoming patch in puffpatch to detect
corrupt or malicious patches.

BUG=none
TEST=unittests pass

Change-Id: Ibc825f15652970a56dca2144ed39d495e5fb940d
Reviewed-on: https://chromium-review.googlesource.com/763871
Commit-Ready: Amin Hassani <ahassani@chromium.org>
Tested-by: Amin Hassani <ahassani@chromium.org>
Reviewed-by: Ben Chan <benchan@chromium.org>
Reviewed-by: Sen Jiang <senj@chromium.org>
diff --git a/src/puffpatch.cc b/src/puffpatch.cc
index bfaedae..1284196 100644
--- a/src/puffpatch.cc
+++ b/src/puffpatch.cc
@@ -55,6 +55,9 @@
                  size_t* src_puff_size,
                  size_t* dst_puff_size) {
   size_t offset = 0;
+  uint32_t header_size;
+  TEST_AND_RETURN_FALSE(patch_length >= (kMagicLength + sizeof(header_size)));
+
   string patch_magic(reinterpret_cast<const char*>(patch), kMagicLength);
   if (patch_magic != kMagic) {
     LOG(ERROR) << "Magic number for Puffin patch is incorrect: " << patch_magic;
@@ -63,10 +66,10 @@
   offset += kMagicLength;
 
   // Read the header size from big-endian mode.
-  uint32_t header_size;
   memcpy(&header_size, patch + offset, sizeof(header_size));
   header_size = be32toh(header_size);
   offset += sizeof(header_size);
+  TEST_AND_RETURN_FALSE(header_size <= (patch_length - offset));
 
   metadata::PatchHeader header;
   TEST_AND_RETURN_FALSE(header.ParseFromArray(patch + offset, header_size));