Skip to content

Commit a44f152

Browse files
likebreathrbradford
andcommitted
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 <[email protected]> Co-authored-by: Rob Bradford <[email protected]>
1 parent 2580d45 commit a44f152

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

src/loader/x86_64/elf/mod.rs

+6-7
Original file line numberDiff line numberDiff line change
@@ -217,8 +217,8 @@ impl KernelLoader for Elf {
217217
.map_err(|_| Error::SeekElfStart)?;
218218

219219
let mut ehdr = elf::Elf64_Ehdr::default();
220-
ehdr.as_bytes()
221-
.read_from(0, kernel_image, mem::size_of::<elf::Elf64_Ehdr>())
220+
kernel_image
221+
.read_exact(ehdr.as_mut_slice())
222222
.map_err(|_| Error::ReadElfHeader)?;
223223

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

249-
let phdr_sz = mem::size_of::<elf::Elf64_Phdr>();
250249
let mut phdrs: Vec<elf::Elf64_Phdr> = vec![];
251250
for _ in 0usize..ehdr.e_phnum as usize {
252251
let mut phdr = elf::Elf64_Phdr::default();
253-
phdr.as_bytes()
254-
.read_from(0, kernel_image, phdr_sz)
252+
kernel_image
253+
.read_exact(phdr.as_mut_slice())
255254
.map_err(|_| Error::ReadProgramHeader)?;
256255
phdrs.push(phdr);
257256
}
@@ -335,8 +334,8 @@ where
335334
let nhdr_sz = mem::size_of::<elf::Elf64_Nhdr>();
336335

337336
while read_size < phdr.p_filesz as usize {
338-
nhdr.as_bytes()
339-
.read_from(0, kernel_image, nhdr_sz)
337+
kernel_image
338+
.read_exact(nhdr.as_mut_slice())
340339
.map_err(|_| Error::ReadNoteHeader)?;
341340

342341
// Check if the note header's name and type match the ones specified by the PVH ABI.

0 commit comments

Comments
 (0)