Skip to content

Commit

Permalink
loader: x86_64: elf: Avoid reading beyond file end
Browse files Browse the repository at this point in the history
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 <chen.bo@intel.com>
Co-authored-by: Rob Bradford <robert.bradford@intel.com>
  • Loading branch information
likebreath and rbradford committed Dec 6, 2022
1 parent 2580d45 commit a44f152
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions src/loader/x86_64/elf/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<elf::Elf64_Ehdr>())
kernel_image
.read_exact(ehdr.as_mut_slice())
.map_err(|_| Error::ReadElfHeader)?;

// Sanity checks.
Expand Down Expand Up @@ -246,12 +246,11 @@ impl KernelLoader for Elf {
.seek(SeekFrom::Start(ehdr.e_phoff))
.map_err(|_| Error::SeekProgramHeader)?;

let phdr_sz = mem::size_of::<elf::Elf64_Phdr>();
let mut phdrs: Vec<elf::Elf64_Phdr> = 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);
}
Expand Down Expand Up @@ -335,8 +334,8 @@ where
let nhdr_sz = mem::size_of::<elf::Elf64_Nhdr>();

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.
Expand Down

0 comments on commit a44f152

Please sign in to comment.