kernel_loader: check phdr memory size addition

The mem_offset + phdr.memsz addition is using untrusted input
(phdr.memsz) and can overflow; add an explicit check to avoid panics on
invalid values.

BUG=None
TEST=/usr/libexec/fuzzers/crosvm_zimage_fuzzer in cros_fuzz shell

Change-Id: Ie6f7f27bd00958ff85201cecaa75ce2b19779b8b
Signed-off-by: Daniel Verkamp <dverkamp@chromium.org>
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/crosvm/+/1674664
Tested-by: kokoro <noreply+kokoro@google.com>
Reviewed-by: Dylan Reid <dgreid@chromium.org>
diff --git a/kernel_loader/src/lib.rs b/kernel_loader/src/lib.rs
index 7ff6efa..75828f5 100644
--- a/kernel_loader/src/lib.rs
+++ b/kernel_loader/src/lib.rs
@@ -26,6 +26,7 @@
     InvalidProgramHeaderSize,
     InvalidProgramHeaderOffset,
     InvalidProgramHeaderAddress,
+    InvalidProgramHeaderMemSize,
     ReadElfHeader,
     ReadKernelImage,
     ReadProgramHeader,
@@ -49,6 +50,7 @@
             InvalidProgramHeaderSize => "invalid program header size",
             InvalidProgramHeaderOffset => "invalid program header offset",
             InvalidProgramHeaderAddress => "invalid Program Header Address",
+            InvalidProgramHeaderMemSize => "invalid Program Header memory size",
             ReadElfHeader => "unable to read elf header",
             ReadKernelImage => "unable to read kernel image",
             ReadProgramHeader => "unable to read program header",
@@ -132,7 +134,10 @@
             .read_to_memory(mem_offset, kernel_image, phdr.p_filesz as usize)
             .map_err(|_| Error::ReadKernelImage)?;
 
-        kernel_end = mem_offset.offset() + phdr.p_memsz;
+        kernel_end = mem_offset
+            .offset()
+            .checked_add(phdr.p_memsz)
+            .ok_or(Error::InvalidProgramHeaderMemSize)?;
     }
 
     Ok(kernel_end)