From a44f152da4f38c538ed492b1efa8515be2047db2 Mon Sep 17 00:00:00 2001 From: Bo Chen Date: Mon, 5 Dec 2022 20:44:21 -0800 Subject: [PATCH] loader: x86_64: elf: Avoid reading beyond file end The ELF header contains offsets that the loader uses to find other structures. If those offsets are beyond the end of the file (or would go past the end of the file) it is essential to error out when attempting to read those. Using `Read::read_exact()` permits this. Signed-off-by: Bo Chen Co-authored-by: Rob Bradford --- src/loader/x86_64/elf/mod.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/loader/x86_64/elf/mod.rs b/src/loader/x86_64/elf/mod.rs index 277cea55..10aa737f 100644 --- a/src/loader/x86_64/elf/mod.rs +++ b/src/loader/x86_64/elf/mod.rs @@ -217,8 +217,8 @@ impl KernelLoader for Elf { .map_err(|_| Error::SeekElfStart)?; let mut ehdr = elf::Elf64_Ehdr::default(); - ehdr.as_bytes() - .read_from(0, kernel_image, mem::size_of::()) + kernel_image + .read_exact(ehdr.as_mut_slice()) .map_err(|_| Error::ReadElfHeader)?; // Sanity checks. @@ -246,12 +246,11 @@ impl KernelLoader for Elf { .seek(SeekFrom::Start(ehdr.e_phoff)) .map_err(|_| Error::SeekProgramHeader)?; - let phdr_sz = mem::size_of::(); let mut phdrs: Vec = vec![]; for _ in 0usize..ehdr.e_phnum as usize { let mut phdr = elf::Elf64_Phdr::default(); - phdr.as_bytes() - .read_from(0, kernel_image, phdr_sz) + kernel_image + .read_exact(phdr.as_mut_slice()) .map_err(|_| Error::ReadProgramHeader)?; phdrs.push(phdr); } @@ -335,8 +334,8 @@ where let nhdr_sz = mem::size_of::(); while read_size < phdr.p_filesz as usize { - nhdr.as_bytes() - .read_from(0, kernel_image, nhdr_sz) + kernel_image + .read_exact(nhdr.as_mut_slice()) .map_err(|_| Error::ReadNoteHeader)?; // Check if the note header's name and type match the ones specified by the PVH ABI.