add overflow check for vaddr

This commit is contained in:
mos 2024-04-19 11:23:48 +02:00
parent a1ece95459
commit 767804233f
2 changed files with 13 additions and 7 deletions

View File

@ -12,6 +12,7 @@ pub enum Error {
BadMagic, BadMagic,
BadType, BadType,
BadMachine, BadMachine,
BadAddr,
} }
struct Phdr { struct Phdr {
@ -101,15 +102,19 @@ pub fn load(elf: Vec<u8>, mem: &mut [u8]) -> Result<u32, Error> {
continue; continue;
} }
let vaddr = (phdr.vaddr - RAM_BASE) as usize; if let Some(vaddr) = phdr.vaddr.checked_sub(RAM_BASE) {
let memsz = phdr.memsz as usize; let vaddr = vaddr as usize;
let memsz = phdr.memsz as usize;
let pos = rdr.position(); let pos = rdr.position();
rdr.set_position(phdr.offset as u64); rdr.set_position(phdr.offset as u64);
if rdr.read_exact(&mut mem[vaddr..vaddr + memsz]).is_err() { if rdr.read_exact(&mut mem[vaddr..vaddr + memsz]).is_err() {
return Err(Error::Eof); return Err(Error::Eof);
}
rdr.set_position(pos);
} else {
return Err(Error::BadAddr);
} }
rdr.set_position(pos);
} }
Ok(entry) Ok(entry)

View File

@ -336,6 +336,7 @@ pub fn run(path: String) -> Result<()> {
elf::Error::BadMagic => bail!("bad magic"), elf::Error::BadMagic => bail!("bad magic"),
elf::Error::BadType => bail!("invalid executable"), elf::Error::BadType => bail!("invalid executable"),
elf::Error::BadMachine => bail!("foreign elf architecture"), elf::Error::BadMachine => bail!("foreign elf architecture"),
elf::Error::BadAddr => bail!("bad virt address offset"),
}, },
}; };