diff --git a/Cargo.lock b/Cargo.lock index 9d0c90324..3c3a80f8b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1475,6 +1475,7 @@ dependencies = [ "elf", "fspy_nostd", "linux-raw-sys 0.12.1", + "syscalls", "tempfile", ] diff --git a/crates/fspy_elf_loader/Cargo.toml b/crates/fspy_elf_loader/Cargo.toml index 154943b2f..692fb4bd1 100644 --- a/crates/fspy_elf_loader/Cargo.toml +++ b/crates/fspy_elf_loader/Cargo.toml @@ -1,6 +1,7 @@ [package] name = "fspy_elf_loader" version = "0.1.0" +links = "fspy_elf_loader" authors.workspace = true edition.workspace = true license.workspace = true @@ -10,7 +11,8 @@ rust-version.workspace = true [target.'cfg(any(target_os = "linux", target_os = "none"))'.dependencies] elf = { workspace = true } fspy_nostd = { workspace = true } -linux-raw-sys = { workspace = true, features = ["auxvec", "no_std"] } +linux-raw-sys = { workspace = true, features = ["auxvec", "general", "no_std", "prctl"] } +syscalls = { workspace = true } [target.'cfg(target_os = "linux")'.dev-dependencies] tempfile = { workspace = true } diff --git a/crates/fspy_elf_loader/build.rs b/crates/fspy_elf_loader/build.rs new file mode 100644 index 000000000..e9ea72a63 --- /dev/null +++ b/crates/fspy_elf_loader/build.rs @@ -0,0 +1,16 @@ +fn main() { + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("none") { + // Leave the low 4 GiB available while staying in application regions + // of the current LLVM Linux ASan and C/C++ TSan layouts. AArch64's + // base also fits smaller virtual address spaces, including 39-bit. + // Older AArch64 TSan runtimes can reject 8 GiB; see the README. + // This is a placement convention; fixed targets can still overlap it. + let image_base = match std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() { + Ok("x86_64") => "--image-base=0x550000000000", // 85 TiB + Ok("aarch64") => "--image-base=0x200000000", // 8 GiB + _ => panic!("unsupported launcher architecture"), + }; + // Fixed linking resolves pointers without a startup self-relocator. + println!("cargo::metadata=link_args=--no-pie {image_base}"); + } +} diff --git a/crates/fspy_elf_loader/src/image.rs b/crates/fspy_elf_loader/src/image.rs index d5c844d75..999f783ca 100644 --- a/crates/fspy_elf_loader/src/image.rs +++ b/crates/fspy_elf_loader/src/image.rs @@ -17,11 +17,11 @@ use elf::{ segment::{ProgramHeader, SegmentTable}, }; use fspy_nostd::{ - CStr, Fat, OwnedFd, fs, + BorrowedFd, CStr, Error, Fat, Result, fs, mm::{self, MapFlags, MprotectFlags, ProtFlags}, }; -use crate::mapping::{Mapping, add, align_up, sub, word}; +use crate::mapping::{Mapping, add, align_up, sub, try_align_up, word}; #[cfg(test)] mod tests; @@ -35,13 +35,22 @@ const MACHINE: u16 = abi::EM_AARCH64; const MACHINE: u16 = abi::EM_X86_64; /// A temporary read-only view used to parse file offsets, not to execute code. -pub struct File { - fd: OwnedFd, +pub struct File<'fd> { + fd: BorrowedFd<'fd>, view: Mapping, header: FileHeader, headers: Range, } +/// Validated page-rounded address span and metadata for an ELF image. +#[derive(Clone, Copy, Debug)] +pub struct ValidatedLayout { + pub low: usize, + pub span: usize, + pub alignment: usize, + pub has_phdr: bool, +} + /// The final memory layout, with addresses the target can use at runtime. pub struct Image { mapping: Mapping, @@ -64,41 +73,57 @@ impl Image { } } -impl File { - pub fn new(fd: OwnedFd) -> Self { - let len = usize::try_from(fs::fstat(fd.as_fd()).expect("cannot stat ELF").st_size) - .expect("invalid ELF file size"); - assert!(len >= EHDR_SIZE, "truncated ELF header"); - let view = Mapping::file(fd.as_fd(), len); +impl<'fd> File<'fd> { + /// Parses and validates the ELF64 header and program-header table bounds + /// without taking ownership of `fd`. + pub fn open(fd: BorrowedFd<'fd>) -> Result { + let meta = fs::fstat(fd)?; + if !meta.is_regular_file() { + return Err(Error::ACCES); + } + let len = usize::try_from(meta.st_size).map_err(|_| Error::NOEXEC)?; + if len < EHDR_SIZE { + return Err(Error::NOEXEC); + } + let view = Mapping::try_file(fd, len)?; // SAFETY: this is the unchanged, read-only file view. let bytes = unsafe { view.bytes() }; // The 16-byte identity tells us how to decode the rest of the 64-byte // ELF64 header. Section headers describe linker/debugger information; // loading these images needs only the separate program-header table. - let ident = file::parse_ident::(&bytes[..16]).expect("invalid ELF identity"); - assert_eq!(ident.1, Class::ELF64, "only ELF64 is supported"); + let ident = file::parse_ident::(&bytes[..16]).map_err(|_| Error::NOEXEC)?; + if ident.1 != Class::ELF64 { + return Err(Error::NOEXEC); + } let header = - FileHeader::parse_tail(ident, &bytes[16..EHDR_SIZE]).expect("invalid ELF header"); - assert_eq!(header.e_machine, MACHINE, "ELF architecture mismatch"); + FileHeader::parse_tail(ident, &bytes[16..EHDR_SIZE]).map_err(|_| Error::NOEXEC)?; + if header.e_machine != MACHINE { + return Err(Error::NOEXEC); + } // ET_DYN permits a load bias chosen for the available address space. // Position-independent executables (PIE) and their interpreters use it. // ET_EXEC instead uses its declared addresses with no load bias. - assert!( - matches!(header.e_type, abi::ET_DYN | abi::ET_EXEC), - "only ET_DYN and ET_EXEC images are supported" - ); - assert_eq!(header.version, u32::from(abi::EV_CURRENT), "invalid ELF version"); - assert_eq!(usize::from(header.e_phentsize), PHDR_SIZE, "invalid program-header size"); - // 0xffff is an escape to a count stored in section metadata. This MVP - // accepts only counts carried in the ELF header itself. - assert!( - header.e_phnum != 0 && header.e_phnum != 0xffff, - "unsupported program-header count" - ); - let start = word(header.e_phoff); - let end = add(start, usize::from(header.e_phnum) * PHDR_SIZE); - assert!(bytes.get(start..end).is_some(), "truncated program headers"); - Self { fd, view, header, headers: start..end } + if !matches!(header.e_type, abi::ET_DYN | abi::ET_EXEC) { + return Err(Error::NOEXEC); + } + if header.version != u32::from(abi::EV_CURRENT) { + return Err(Error::NOEXEC); + } + if usize::from(header.e_phentsize) != PHDR_SIZE { + return Err(Error::NOEXEC); + } + // 0xffff is an escape to a count stored in section metadata. We accept + // only counts carried in the ELF header itself. + if header.e_phnum == 0 || header.e_phnum == 0xffff { + return Err(Error::NOEXEC); + } + let start = usize::try_from(header.e_phoff).map_err(|_| Error::NOEXEC)?; + let table_len = usize::from(header.e_phnum).checked_mul(PHDR_SIZE).ok_or(Error::NOEXEC)?; + let end = start.checked_add(table_len).ok_or(Error::NOEXEC)?; + if bytes.get(start..end).is_none() { + return Err(Error::NOEXEC); + } + Ok(Self { fd, view, header, headers: start..end }) } fn segments(&self) -> SegmentTable<'_, LittleEndian> { @@ -114,96 +139,151 @@ impl File { self.header.e_type == abi::ET_DYN } - pub fn interpreter(&self) -> Option> { + pub fn interpreter(&self) -> Result>> { let mut result = None; for segment in self.segments().iter() { if segment.p_type == abi::PT_INTERP { - assert!(result.is_none(), "multiple PT_INTERP entries"); - let start = word(segment.p_offset); - let end = add(start, word(segment.p_filesz)); + if result.is_some() { + return Err(Error::NOEXEC); + } + let start = usize::try_from(segment.p_offset).map_err(|_| Error::NOEXEC)?; + let len = usize::try_from(segment.p_filesz).map_err(|_| Error::NOEXEC)?; + let end = start.checked_add(len).ok_or(Error::NOEXEC)?; // SAFETY: the file remains unchanged and mapped read-only. - let bytes = - unsafe { self.view.bytes() }.get(start..end).expect("truncated PT_INTERP"); + let bytes = unsafe { self.view.bytes() }.get(start..end).ok_or(Error::NOEXEC)?; // Linux requires only that the last byte is NUL, then treats // the slice as a C string. Linkers may pad with extra NULs. - assert!(bytes.last() == Some(&0), "unterminated PT_INTERP"); - let len = bytes.iter().position(|byte| *byte == 0).unwrap() + 1; - let path = - CStr::from_units_with_nul(&bytes[..len]).expect("invalid PT_INTERP path"); - assert!(!path.as_units().is_empty(), "empty PT_INTERP path"); + if bytes.last() != Some(&0) { + return Err(Error::NOEXEC); + } + let nul_len = bytes.iter().position(|byte| *byte == 0).ok_or(Error::NOEXEC)? + 1; + let path = CStr::from_units_with_nul(&bytes[..nul_len]).ok_or(Error::NOEXEC)?; + if path.as_units().is_empty() { + return Err(Error::NOEXEC); + } result = Some(path); } } - result + Ok(result) } - fn assert_disjoint_load(&self, index: usize, start: usize, end: usize) { + fn check_disjoint_load(&self, index: usize, start: usize, end: usize) -> Result<()> { for (other_index, other) in self.segments().iter().enumerate() { if other_index > index && other.p_type == abi::PT_LOAD && other.p_memsz != 0 { - let other_start = word(other.p_vaddr); - let other_end = add(other_start, word(other.p_memsz)); - assert!(end <= other_start || other_end <= start, "overlapping ELF segments"); + let other_start = usize::try_from(other.p_vaddr).map_err(|_| Error::NOEXEC)?; + let other_memsz = usize::try_from(other.p_memsz).map_err(|_| Error::NOEXEC)?; + let other_end = other_start.checked_add(other_memsz).ok_or(Error::NOEXEC)?; + if !(end <= other_start || other_end <= start) { + return Err(Error::NOEXEC); + } } } + Ok(()) } - pub fn map(&self, page: usize) -> Image { - // First validate the segments and find their page-rounded span. - // mmap operates on whole pages, even when ELF segments do not. + /// Validates all program headers (`PT_GNU_STACK`, `PT_LOAD` bounds, + /// disjointness, alignment, page congruence, entry point, and `AT_PHDR` + /// coverage) without mapping any execution segments. + pub fn validate_segments(&self, page: usize) -> Result { + if !page.is_power_of_two() { + return Err(Error::INVAL); + } let mut low = usize::MAX; - let mut high = 0; + let mut high = 0_usize; let mut alignment = page; + let mut has_phdr = false; + let mut executable_entry = false; + for (index, segment) in self.segments().iter().enumerate() { - if segment.p_type == abi::PT_GNU_STACK { - assert!(segment.p_flags & abi::PF_X == 0, "executable stacks are unsupported"); + if segment.p_type == abi::PT_GNU_STACK && (segment.p_flags & abi::PF_X) != 0 { + return Err(Error::NOEXEC); } if segment.p_type == abi::PT_LOAD { - let start = word(segment.p_vaddr); - let end = add(start, word(segment.p_memsz)); - let file_end = add(word(segment.p_offset), word(segment.p_filesz)); - assert!(segment.p_filesz <= segment.p_memsz, "ELF filesz exceeds memsz"); - assert!(file_end <= self.view.len, "truncated ELF segment"); + let start = usize::try_from(segment.p_vaddr).map_err(|_| Error::NOEXEC)?; + let memsz = usize::try_from(segment.p_memsz).map_err(|_| Error::NOEXEC)?; + let filesz = usize::try_from(segment.p_filesz).map_err(|_| Error::NOEXEC)?; + let offset = usize::try_from(segment.p_offset).map_err(|_| Error::NOEXEC)?; + let end = start.checked_add(memsz).ok_or(Error::NOEXEC)?; + let file_end = offset.checked_add(filesz).ok_or(Error::NOEXEC)?; + if segment.p_filesz > segment.p_memsz || file_end > self.view.len { + return Err(Error::NOEXEC); + } // Byte ranges must not overlap. Header order need not match // vaddr order; mapping below still walks headers so a later // MAP_FIXED can share a page with an earlier load. if segment.p_memsz != 0 { - self.assert_disjoint_load(index, start, end); - low = low.min(start & !sub(page, 1)); - high = high.max(align_up(end, page)); + self.check_disjoint_load(index, start, end)?; + low = low.min(start & !(page - 1)); + let aligned_end = try_align_up(end, page).ok_or(Error::NOEXEC)?; + high = high.max(aligned_end); + if self.headers.start >= offset && self.headers.end <= file_end { + has_phdr = true; + } + let entry_end = + segment.p_vaddr.checked_add(segment.p_memsz).ok_or(Error::NOEXEC)?; + executable_entry |= (segment.p_flags & abi::PF_X) != 0 + && self.header.e_entry >= segment.p_vaddr + && self.header.e_entry < entry_end; } // ELF treats alignment 0 and 1 as no extra constraint. File // and memory offsets must agree within a page for mmap; like // Linux binfmt_elf, do not reject binaries (e.g. patchelf // output) that are page-congruent but incongruent mod p_align. - let align = word(segment.p_align).max(1); - assert!(align.is_power_of_two(), "invalid segment alignment"); - assert_eq!( - start % page, - word(segment.p_offset) % page, - "incongruent ELF page offsets" - ); + let align = usize::try_from(segment.p_align).map_err(|_| Error::NOEXEC)?.max(1); + if !align.is_power_of_two() { + return Err(Error::NOEXEC); + } + if start % page != offset % page { + return Err(Error::NOEXEC); + } alignment = alignment.max(align); } } - let span = high.checked_sub(low).expect("ELF has no loadable memory"); + + let span = high.checked_sub(low).ok_or(Error::NOEXEC)?; + if span == 0 || isize::try_from(span).is_err() { + return Err(Error::NOEXEC); + } + if self.header.e_type == abi::ET_DYN { + let reserved = span.checked_add(alignment).ok_or(Error::NOEXEC)?; + if isize::try_from(reserved).is_err() { + return Err(Error::NOEXEC); + } + } + if !executable_entry { + return Err(Error::NOEXEC); + } + Ok(ValidatedLayout { low, span, alignment, has_phdr }) + } + + pub fn map(&self, page: usize, layout: &ValidatedLayout) -> Image { // Reserve the whole image, including holes, before replacing pages // with MAP_FIXED. That flag discards existing mappings at its address; // restricting it to our reservation protects the loader and old stack. let (mapping, bias) = if self.header.e_type == abi::ET_EXEC { // Fixed-address executables cannot move. Refuse collisions rather // than replacing resident loader code or other process state. - (Mapping::reserve_at(low, span), 0) + (Mapping::reserve_at(layout.low, layout.span), 0) } else { - // Extra space aligns the bias even when p_align exceeds a page. - let mapping = Mapping::reserve(add(span, alignment)); + // Extra space aligns the load bias even when `p_align` exceeds a + // page or `layout.low > base`. Compute `mapped_low` inside the + // reservation with `mapped_low % alignment == layout.low % alignment` + // so `bias = mapped_low.wrapping_sub(layout.low)` is aligned to + // `layout.alignment` and never underflows. + let mapping = Mapping::reserve(add(layout.span, layout.alignment)); let base = mapping.ptr.as_ptr().expose_provenance(); - let bias = - align_up(base.checked_sub(low).expect("unsupported ELF address range"), alignment); - assert!(add(bias, high) <= add(base, mapping.len), "ELF exceeds reservation"); + let desired_mod = layout.low % layout.alignment; + let cur_mod = base % layout.alignment; + let delta = (desired_mod + layout.alignment - cur_mod) % layout.alignment; + let mapped_low = add(base, delta); + let bias = mapped_low.wrapping_sub(layout.low); + assert!( + add(mapped_low, layout.span) <= add(base, mapping.len), + "ELF exceeds reservation" + ); (mapping, bias) }; let mut phdr = None; - let mut executable_entry = false; // All segments share one bias, preserving their relative addresses. // The executable and interpreter each get their own reservation/bias. for segment in @@ -217,33 +297,25 @@ impl File { && self.headers.end <= add(file_start, word(segment.p_filesz)) { phdr = Some(add( - add(bias, word(segment.p_vaddr)), + bias.wrapping_add(word(segment.p_vaddr)), sub(self.headers.start, file_start), )); } - executable_entry |= segment.p_flags & abi::PF_X != 0 - && self.header.e_entry >= segment.p_vaddr - && self.header.e_entry - < segment - .p_vaddr - .checked_add(segment.p_memsz) - .expect("ELF entry range overflow"); // SAFETY: validation and reservation cover every page this // segment replaces. No references to those pages exist yet. unsafe { self.map_segment(segment, bias, page) }; } - assert!(executable_entry, "ELF entry is not in an executable segment"); Image { mapping, bias, - entry: add(bias, word(self.header.e_entry)), + entry: bias.wrapping_add(word(self.header.e_entry)), phdr, phnum: usize::from(self.header.e_phnum), } } unsafe fn map_segment(&self, segment: ProgramHeader, bias: usize, page: usize) { - let start = add(bias, word(segment.p_vaddr)); + let start = bias.wrapping_add(word(segment.p_vaddr)); let end = add(start, word(segment.p_memsz)); let file_end = add(start, word(segment.p_filesz)); let page_start = start & !sub(page, 1); @@ -275,7 +347,7 @@ impl File { file_len, protection, fixed, - self.fd.as_fd(), + self.fd, segment.p_offset & !u64::try_from(sub(page, 1)).unwrap(), ) } @@ -295,7 +367,7 @@ impl File { let mut zero_end = align_up(file_end, page); for other in self.segments().iter() { if other.p_type == abi::PT_LOAD && other.p_memsz != 0 { - let other_start = add(bias, word(other.p_vaddr)); + let other_start = bias.wrapping_add(word(other.p_vaddr)); if other_start >= end && other_start < zero_end { zero_end = other_start; } @@ -352,3 +424,28 @@ impl File { } } } + +/// Validates an executable descriptor and its `PT_INTERP` (if present) using +/// the same rules as [`crate::exec_elf`], without mapping execution segments or +/// closing `fd`. +pub fn validate_exec_fd(fd: BorrowedFd<'_>, page: usize) -> Result<()> { + let executable = File::open(fd)?; + let layout = executable.validate_segments(page)?; + if !layout.has_phdr { + return Err(Error::NOEXEC); + } + if let Some(interp_path) = executable.interpreter()? { + let interp_fd = fs::openat( + fspy_nostd::CWD, + interp_path, + fs::OFlags::RDONLY | fs::OFlags::CLOEXEC, + fs::Mode::empty(), + )?; + let interp = File::open(interp_fd.as_fd())?; + if !interp.is_dynamic() || interp.interpreter()?.is_some() { + return Err(Error::NOEXEC); + } + let _ = interp.validate_segments(page)?; + } + Ok(()) +} diff --git a/crates/fspy_elf_loader/src/image/tests.rs b/crates/fspy_elf_loader/src/image/tests.rs index 42d0d5673..059a058f9 100644 --- a/crates/fspy_elf_loader/src/image/tests.rs +++ b/crates/fspy_elf_loader/src/image/tests.rs @@ -1,3 +1,5 @@ +use fspy_nostd::OwnedFd; + use super::*; #[test] @@ -192,40 +194,166 @@ fn accepts_page_congruent_segment_incongruent_with_large_p_align() { } #[test] -#[should_panic(expected = "overlapping ELF segments")] fn rejects_overlapping_load_segments() { let page = fspy_nostd::param::page_size(); let mut bytes = std::vec![0xa5; 2 * page]; write_header(&mut bytes, 2, 0x80); load(&mut bytes, 0, 0, 0x200, 0x200, abi::PF_R | abi::PF_X, page); load(&mut bytes, 1, 0x100, 0x200, 0x200, abi::PF_R | abi::PF_W, page); - map_bytes(&bytes); + let fd = open_bytes(&bytes); + let file = File::open(fd.as_fd()).unwrap(); + assert_eq!(file.validate_segments(page).unwrap_err(), Error::NOEXEC); } #[test] fn reports_no_interpreter_when_pt_interp_is_absent() { let page = fspy_nostd::param::page_size(); - let file = File::new(open_bytes(&fixture(page, 0x180, abi::PF_R | abi::PF_W))); - assert!(file.interpreter().is_none()); + let fd = open_bytes(&fixture(page, 0x180, abi::PF_R | abi::PF_W)); + let file = File::open(fd.as_fd()).unwrap(); + assert!(file.interpreter().unwrap().is_none()); } #[test] fn accepts_pt_interp_padded_with_extra_nuls() { - let file = File::new(open_bytes(&interp_image(b"ld.so\0\0\0"))); - let path = file.interpreter().unwrap(); + let fd = open_bytes(&interp_image(b"ld.so\0\0\0")); + let file = File::open(fd.as_fd()).unwrap(); + let path = file.interpreter().unwrap().unwrap(); assert_eq!(path.as_units(), b"ld.so"); } #[test] -#[should_panic(expected = "unterminated PT_INTERP")] -fn rejects_unterminated_pt_interp() { - let _ = File::new(open_bytes(&interp_image(b"ld.so"))).interpreter(); +fn rejects_unterminated_and_empty_pt_interp() { + let fd_unterm = open_bytes(&interp_image(b"ld.so")); + assert_eq!(File::open(fd_unterm.as_fd()).unwrap().interpreter().err(), Some(Error::NOEXEC)); + + let fd_empty = open_bytes(&interp_image(b"\0\0\0")); + assert_eq!(File::open(fd_empty.as_fd()).unwrap().interpreter().err(), Some(Error::NOEXEC)); } #[test] -#[should_panic(expected = "empty PT_INTERP path")] -fn rejects_empty_pt_interp() { - let _ = File::new(open_bytes(&interp_image(b"\0\0\0"))).interpreter(); +fn validate_exec_checks_valid_and_invalid_images_without_closing_fd() { + let page = fspy_nostd::param::page_size(); + + // Valid ET_DYN (PIE) image. + let valid_pie = open_bytes(&fixture(page, 0x180, abi::PF_R | abi::PF_W)); + assert_eq!(crate::validate_exec(valid_pie.as_fd()), Ok(())); + // Verify `fd` was NOT closed by `validate_exec`. + assert!(fs::fstat(valid_pie.as_fd()).is_ok()); + + // Valid ET_EXEC image. + let mut exec_bytes = fixture(page, 0x180, abi::PF_R | abi::PF_W); + exec_bytes[16..18].copy_from_slice(&abi::ET_EXEC.to_le_bytes()); + let valid_exec = open_bytes(&exec_bytes); + assert_eq!(crate::validate_exec(valid_exec.as_fd()), Ok(())); + assert!(fs::fstat(valid_exec.as_fd()).is_ok()); + + // Non-ELF -> NOEXEC, fd stays open. + let non_elf = open_bytes(b"#!/bin/sh\necho hi\n"); + assert_eq!(crate::validate_exec(non_elf.as_fd()), Err(Error::NOEXEC)); + assert!(fs::fstat(non_elf.as_fd()).is_ok()); + + // Truncated ELF header -> NOEXEC. + let truncated = open_bytes(&exec_bytes[..32]); + assert_eq!(crate::validate_exec(truncated.as_fd()), Err(Error::NOEXEC)); + + // Wrong architecture -> NOEXEC. + let mut bad_arch = fixture(page, 0x180, abi::PF_R | abi::PF_W); + bad_arch[18..20].copy_from_slice(&0_u16.to_le_bytes()); + let bad_arch_fd = open_bytes(&bad_arch); + assert_eq!(crate::validate_exec(bad_arch_fd.as_fd()), Err(Error::NOEXEC)); + + // Executable PT_GNU_STACK -> NOEXEC. + let mut exec_stack = std::vec![0; 2 * page]; + write_header(&mut exec_stack, 2, 0x200); + load(&mut exec_stack, 0, 0, page, page, abi::PF_R | abi::PF_X, page); + Phdr { + p_type: abi::PT_GNU_STACK, + p_flags: abi::PF_R | abi::PF_W | abi::PF_X, + p_offset: 0, + p_vaddr: 0, + p_filesz: 0, + p_memsz: 0, + p_align: 16, + } + .write_to(&mut exec_stack, 1); + let exec_stack_fd = open_bytes(&exec_stack); + assert_eq!(crate::validate_exec(exec_stack_fd.as_fd()), Err(Error::NOEXEC)); + + // Missing PT_INTERP -> NOENT. + let missing_interp_path = b"/nonexistent-fspy-interp-for-test\0"; + let mut missing_interp = std::vec![0; 2 * page]; + write_header(&mut missing_interp, 2, 0x200); + load(&mut missing_interp, 0, 0, page, page, abi::PF_R | abi::PF_X, page); + let path_off = page - missing_interp_path.len(); + missing_interp[path_off..page].copy_from_slice(missing_interp_path); + Phdr { + p_type: abi::PT_INTERP, + p_flags: abi::PF_R, + p_offset: u64::try_from(path_off).unwrap(), + p_vaddr: u64::try_from(path_off).unwrap(), + p_filesz: u64::try_from(missing_interp_path.len()).unwrap(), + p_memsz: u64::try_from(missing_interp_path.len()).unwrap(), + p_align: 1, + } + .write_to(&mut missing_interp, 1); + let missing_interp_fd = open_bytes(&missing_interp); + assert_eq!(crate::validate_exec(missing_interp_fd.as_fd()), Err(Error::NOENT)); + assert!(fs::fstat(missing_interp_fd.as_fd()).is_ok()); + + // Valid PT_INTERP pointing to a valid ET_DYN interpreter succeeds; pointing + // to an ET_EXEC interpreter fails with NOEXEC. + let dyn_interp_file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(dyn_interp_file.path(), fixture(page, 0x180, abi::PF_R | abi::PF_W)).unwrap(); + let dyn_interp_path = + std::ffi::CString::new(dyn_interp_file.path().as_os_str().as_encoded_bytes()).unwrap(); + let mut with_valid_interp = std::vec![0; 2 * page]; + write_header(&mut with_valid_interp, 2, 0x200); + load(&mut with_valid_interp, 0, 0, page, page, abi::PF_R | abi::PF_X, page); + let pbytes = dyn_interp_path.as_bytes_with_nul(); + let p_off = page - pbytes.len(); + with_valid_interp[p_off..page].copy_from_slice(pbytes); + Phdr { + p_type: abi::PT_INTERP, + p_flags: abi::PF_R, + p_offset: u64::try_from(p_off).unwrap(), + p_vaddr: u64::try_from(p_off).unwrap(), + p_filesz: u64::try_from(pbytes.len()).unwrap(), + p_memsz: u64::try_from(pbytes.len()).unwrap(), + p_align: 1, + } + .write_to(&mut with_valid_interp, 1); + let valid_dyn_fd = open_bytes(&with_valid_interp); + assert_eq!(crate::validate_exec(valid_dyn_fd.as_fd()), Ok(())); + + // Overwrite interpreter with ET_EXEC -> validate_exec rejects with NOEXEC. + std::fs::write(dyn_interp_file.path(), &exec_bytes).unwrap(); + assert_eq!(crate::validate_exec(valid_dyn_fd.as_fd()), Err(Error::NOEXEC)); +} + +#[test] +fn maps_et_dyn_with_high_nonzero_p_vaddr_without_underflow() { + let page = fspy_nostd::param::page_size(); + let high_vaddr = 0x7000_0000_0000_u64; + let mut bytes = std::vec![0x3c; 2 * page]; + write_header(&mut bytes, 1, high_vaddr + 0x200); + Phdr { + p_type: abi::PT_LOAD, + p_flags: abi::PF_R | abi::PF_X, + p_offset: 0, + p_vaddr: high_vaddr, + p_filesz: u64::try_from(page + 0x100).unwrap(), + p_memsz: u64::try_from(page + 0x100).unwrap(), + p_align: u64::try_from(page).unwrap(), + } + .write_to(&mut bytes, 0); + + let file = open_bytes(&bytes); + let parsed = File::open(file.as_fd()).unwrap(); + let layout = parsed.validate_segments(page).unwrap(); + let image = parsed.map(page, &layout); + let mapped_base = image.bias.wrapping_add(layout.low); + assert_eq!(image.entry, mapped_base + 0x200); + assert_eq!(image.phdr, Some(mapped_base + EHDR_SIZE)); } fn fixture(page: usize, memory_size: usize, flags: u32) -> std::vec::Vec { @@ -318,7 +446,11 @@ fn load( } fn map_bytes(bytes: &[u8]) -> Image { - File::new(open_bytes(bytes)).map(fspy_nostd::param::page_size()) + let page = fspy_nostd::param::page_size(); + let fd = open_bytes(bytes); + let file = File::open(fd.as_fd()).unwrap(); + let layout = file.validate_segments(page).unwrap(); + file.map(page, &layout) } fn open_bytes(bytes: &[u8]) -> OwnedFd { diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index 8125f6919..125ec3289 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -19,27 +19,44 @@ #[cfg(test)] extern crate std; -use fspy_nostd::{CStr, OwnedFd, Thin, env::AuxEntry}; -use linux_raw_sys::auxvec::AT_PAGESZ; +use fspy_nostd::{BorrowedFd, CStr, OwnedFd, Result, Thin, env::AuxEntry}; +use linux_raw_sys::{auxvec::AT_PAGESZ, prctl::PR_SET_NAME}; +use syscalls::Sysno; mod image; mod mapping; mod stack; +/// Validates that `fd` refers to a loadable ELF64 executable (and, if present, +/// a valid `PT_INTERP` dynamic interpreter) without mapping execution segments, +/// mutating process state, or closing `fd`. +/// +/// # Errors +/// +/// Returns [`fspy_nostd::Error::NOEXEC`] for malformed or unsupported ELF +/// images (including wrong architecture, non-ELF64, executable `PT_GNU_STACK`, +/// fixed-address `PT_INTERP`, or nested `PT_INTERP`), or the underlying OS +/// error if `fd` or its `PT_INTERP` cannot be inspected or opened. +pub fn validate_exec(fd: BorrowedFd<'_>) -> Result<()> { + image::validate_exec_fd(fd, fspy_nostd::param::page_size()) +} + /// Loads an ELF executable into the current process and enters it. /// /// Takes ownership of a private executable descriptor and closes it after -/// mapping. Loads the executable and, when present, its `PT_INTERP`. Builds an -/// initial stack and transfers control to the interpreter, or to the -/// executable when there is no interpreter. +/// mapping. Loads the executable and, when present, its `PT_INTERP`. Sets the +/// process name (`PR_SET_NAME`) to the basename of `execfn`, sizes the new +/// stack from `RLIMIT_STACK` (clamped to `[8 MiB, 64 MiB]`), builds an initial +/// stack, and transfers control to the interpreter, or to the executable when +/// there is no interpreter. /// -/// `execfn` is the original execution name used for `AT_EXECFN`; it need not -/// match `argv[0]`. Arguments and environment entries are copied to the new -/// stack. `inherited_auxv` borrows entries from the loader's original kernel -/// stack, excluding `AT_NULL`. Its `AT_PAGESZ` supplies the page size used for -/// mapping. Image-specific entries are replaced, reusable entries are -/// preserved, and referenced data is copied where needed. The resulting -/// vector ends with `AT_NULL`. +/// `execfn` is the original execution name used for `AT_EXECFN` and +/// `PR_SET_NAME`; it need not match `argv[0]`. Arguments and environment +/// entries are copied to the new stack. `inherited_auxv` borrows entries from +/// the loader's original kernel stack, excluding `AT_NULL`. Its `AT_PAGESZ` +/// supplies the page size used for mapping. Image-specific entries are +/// replaced, reusable entries are preserved, and referenced data is copied +/// where needed. The resulting vector ends with `AT_NULL`. /// /// Path resolution, shebang handling, and execution-policy checks belong to /// the caller. This function does not perform kernel exec cleanup: installed @@ -51,10 +68,9 @@ mod stack; /// x86-64, with a non-executable stack. Both PIE (`ET_DYN`) and fixed-address /// (`ET_EXEC`) images are supported, with or without `PT_INTERP`. /// Fixed-address images must not overlap any existing process mappings. -/// The new stack has a fixed 8 MiB capacity and a guard page. Existing loader -/// mappings, the old stack, and kernel process metadata (including `/proc` -/// identity and `brk`) are retained. This does not emulate a complete exec. -/// Processor-specific GNU properties are not applied. +/// Existing loader mappings, the old stack, and kernel process metadata +/// (including `/proc` identity and `brk`) are retained. This does not emulate +/// a complete exec. Processor-specific GNU properties are not applied. /// /// # Safety /// @@ -87,25 +103,39 @@ pub unsafe fn exec_elf<'a>( .expect("missing AT_PAGESZ") .value; assert!(page_size.is_power_of_two(), "invalid AT_PAGESZ"); - let executable = image::File::new(elf_file); + + let executable = image::File::open(elf_file.as_fd()).expect("invalid ELF executable"); + let executable_layout = + executable.validate_segments(page_size).expect("invalid ELF executable segments"); + assert!(executable_layout.has_phdr, "program headers are not mapped by PT_LOAD"); + // PT_INTERP names a second ELF file. Loading it here lets us delegate // dynamic linking and libc startup to the program's own interpreter. // Static and static-PIE images omit it; the executable is the startup image. - let interpreter = executable.interpreter().map(|path| { - let fd = fspy_nostd::fs::openat( + let interp_path = executable.interpreter().expect("invalid PT_INTERP"); + let interp_fd = interp_path.map(|path| { + fspy_nostd::fs::openat( fspy_nostd::CWD, path, fspy_nostd::fs::OFlags::RDONLY | fspy_nostd::fs::OFlags::CLOEXEC, fspy_nostd::fs::Mode::empty(), ) - .expect("cannot open ELF interpreter"); - let file = image::File::new(fd); + .expect("cannot open ELF interpreter") + }); + let interpreter = interp_fd.as_ref().map(|fd| { + let file = image::File::open(fd.as_fd()).expect("invalid ELF interpreter"); assert!(file.is_dynamic(), "fixed-address PT_INTERP is unsupported"); - assert!(file.interpreter().is_none(), "nested PT_INTERP is unsupported"); - file + assert!( + file.interpreter().expect("invalid nested PT_INTERP").is_none(), + "nested PT_INTERP is unsupported" + ); + let layout = file.validate_segments(page_size).expect("invalid ELF interpreter segments"); + (file, layout) }); - let executable_image = executable.map(page_size); - let interpreter_image = interpreter.as_ref().map(|file| file.map(page_size)); + + let executable_image = executable.map(page_size, &executable_layout); + let interpreter_image = interpreter.as_ref().map(|(file, layout)| file.map(page_size, layout)); + // SAFETY: the caller supplies live auxiliary payloads from this process. let stack = unsafe { stack::build( @@ -118,15 +148,22 @@ pub unsafe fn exec_elf<'a>( page_size, ) }; + + // Match kernel execve's `/proc/self/comm` basename update. + set_process_name(execfn); + // With PT_INTERP, the interpreter runs first even though AT_ENTRY points // at the executable. It uses that value to hand off after linking. // Without PT_INTERP, AT_BASE is 0 and the executable's e_entry starts. let entry = interpreter_image.as_ref().map_or(executable_image.entry, |image| image.entry); + // File mappings keep their backing storage alive after close. Release // only our parsing views and descriptors, then retain the execution maps // so Rust destructors cannot unmap code the target is about to use. drop(interpreter); + drop(interp_fd); drop(executable); + drop(elf_file); executable_image.retain(); if let Some(image) = interpreter_image { image.retain(); @@ -136,6 +173,18 @@ pub unsafe fn exec_elf<'a>( unsafe { enter(entry, stack) } } +/// Sets `/proc/self/comm` via `prctl(PR_SET_NAME)` to the basename of `execfn` +/// truncated to 15 bytes + NUL. +fn set_process_name(execfn: CStr<'_, Thin>) { + let bytes = execfn.count().as_units(); + let basename = bytes.rsplit(|&b| b == b'/').next().unwrap_or(bytes); + let mut comm = [0_u8; 16]; + let len = basename.len().min(15); + comm[..len].copy_from_slice(&basename[..len]); + // SAFETY: `PR_SET_NAME` reads a NUL-terminated buffer of up to 16 bytes. + let _ = unsafe { syscalls::syscall!(Sysno::prctl, PR_SET_NAME, comm.as_ptr(), 0, 0, 0) }; +} + // No Rust code may execute after replacing SP. The dynamic interpreter is // entered like a program, not called like a function with a return address. // #[naked] prevents a compiler-generated stack frame. Each stub starts with diff --git a/crates/fspy_elf_loader/src/mapping.rs b/crates/fspy_elf_loader/src/mapping.rs index 9d63f8d0e..277d6933a 100644 --- a/crates/fspy_elf_loader/src/mapping.rs +++ b/crates/fspy_elf_loader/src/mapping.rs @@ -1,7 +1,7 @@ use core::{ptr, ptr::NonNull, slice}; use fspy_nostd::{ - BorrowedFd, + BorrowedFd, Error, Result, mm::{self, MapFlags, ProtFlags}, }; @@ -19,6 +19,17 @@ pub const fn align_up(value: usize, alignment: usize) -> usize { add(value, mask) & !mask } +pub const fn try_align_up(value: usize, alignment: usize) -> Option { + if !alignment.is_power_of_two() { + return None; + } + let mask = alignment - 1; + match value.checked_add(mask) { + Some(sum) => Some(sum & !mask), + None => None, + } +} + pub fn word(value: u64) -> usize { usize::try_from(value).expect("ELF value exceeds native word") } @@ -72,16 +83,23 @@ impl Mapping { mapping } - pub fn file(fd: BorrowedFd<'_>, len: usize) -> Self { - Self::check_len(len); + pub fn try_file(fd: BorrowedFd<'_>, len: usize) -> Result { + if len == 0 || isize::try_from(len).is_err() { + return Err(Error::NOEXEC); + } // One contiguous view makes file-offset parsing possible. This is // separate from the segments mapped at their final execution addresses. // SAFETY: private read-only view at a kernel-selected address. The - // exec_elf contract keeps the file unchanged while this view is used. + // caller keeps the file unchanged while this view is used. let ptr = - unsafe { mm::mmap(ptr::null_mut(), len, ProtFlags::READ, MapFlags::PRIVATE, fd, 0) } - .expect("cannot map ELF metadata"); - Self::new(ptr.cast(), len) + unsafe { mm::mmap(ptr::null_mut(), len, ProtFlags::READ, MapFlags::PRIVATE, fd, 0) }?; + let Some(ptr) = NonNull::new(ptr.cast()) else { + // SAFETY: this successful mapping is owned here, but address zero + // cannot back Rust references, so release it before failing. + let _ = unsafe { mm::munmap(ptr, len) }; + return Err(Error::NOMEM); + }; + Ok(Self { ptr, len }) } fn check_len(len: usize) { diff --git a/crates/fspy_elf_loader/src/stack.rs b/crates/fspy_elf_loader/src/stack.rs index 67752906d..d44d92a77 100644 --- a/crates/fspy_elf_loader/src/stack.rs +++ b/crates/fspy_elf_loader/src/stack.rs @@ -14,7 +14,7 @@ //! layout. This consumes iterators once without any heap allocator. use core::{ - mem::{align_of, size_of}, + mem::{MaybeUninit, align_of, size_of}, ptr, }; @@ -23,21 +23,65 @@ use fspy_nostd::{ env::AuxEntry, mm::{self, MprotectFlags}, }; -use linux_raw_sys::auxvec as abi; +use linux_raw_sys::{ + auxvec as abi, + general::{RLIM_INFINITY, RLIMIT_STACK, rlimit64}, +}; +use syscalls::Sysno; use crate::{ image::{Image, PHDR_SIZE}, - mapping::{Mapping, add, sub}, + mapping::{Mapping, add, align_up, sub}, }; -// Includes startup data and room for the target's downward-growing call stack. -// This MVP uses a fixed mapping rather than Linux's growable initial stack. -const CAPACITY: usize = 8 * 1024 * 1024; +// Clamp target stack capacity derived from `RLIMIT_STACK` to `[8 MiB, 64 MiB]`. +const MIN_CAPACITY: usize = 8 * 1024 * 1024; +const MAX_CAPACITY: usize = 64 * 1024 * 1024; // Reserve at least 64 KiB below the initial SP above the guard page so a huge // argv/envp fails loudly during loading instead of immediately SIGSEGVing at // process entry. const MIN_STACK_HEADROOM: usize = 64 * 1024; +const RLIM_INFINITY_U64: u64 = (RLIM_INFINITY as i64).cast_unsigned(); + +/// Computes the target stack capacity from an `RLIMIT_STACK` soft limit, +/// treating `RLIM_INFINITY` as 64 MiB, rounding up to `page`, and clamping to +/// `[8 MiB, 64 MiB]`. +const fn clamp_stack_capacity(rlim_cur: u64, page: usize) -> usize { + if rlim_cur == RLIM_INFINITY_U64 { + return MAX_CAPACITY; + } + if rlim_cur >= MAX_CAPACITY as u64 { + return MAX_CAPACITY; + } + #[expect(clippy::cast_possible_truncation, reason = "bounded by MAX_CAPACITY above")] + let raw = rlim_cur as usize; + if raw <= MIN_CAPACITY { + return MIN_CAPACITY; + } + let aligned = align_up(raw, page); + if aligned > MAX_CAPACITY { MAX_CAPACITY } else { aligned } +} + +/// Queries the current process's `RLIMIT_STACK` soft limit via `prlimit64` and +/// returns the clamped stack capacity, falling back to 8 MiB on error. +fn query_stack_capacity(page: usize) -> usize { + let mut rlim = MaybeUninit::::zeroed(); + // SAFETY: `pid = 0` queries the calling process, `new_limit` is NULL, and + // `rlim` points to writable `rlimit64` storage. + let res = unsafe { + syscalls::syscall!(Sysno::prlimit64, 0_usize, RLIMIT_STACK, 0_usize, rlim.as_mut_ptr()) + }; + match res { + Ok(_) => { + // SAFETY: a successful `prlimit64` initialized `rlim`. + let rlim = unsafe { rlim.assume_init() }; + clamp_stack_capacity(rlim.rlim_cur, page) + } + Err(_) => MIN_CAPACITY, + } +} + struct Builder { mapping: Mapping, // Offsets from mapping.ptr: first usable byte, staged word count, and payload start. @@ -48,8 +92,14 @@ struct Builder { impl Builder { fn new(page: usize) -> Self { + let capacity = query_stack_capacity(page); + Self::with_capacity(page, capacity) + } + + fn with_capacity(page: usize, capacity: usize) -> Self { assert!(page.is_multiple_of(align_of::()), "invalid page size"); - let mapping = Mapping::reserve(add(CAPACITY, page)); + assert!(capacity.is_multiple_of(page), "stack capacity must be page-aligned"); + let mapping = Mapping::reserve(add(capacity, page)); // Keep the low page inaccessible so an overflow reaching it faults // instead of writing into a neighboring mapping. // SAFETY: the first page remains a guard; the remaining pages are @@ -57,7 +107,7 @@ impl Builder { unsafe { mm::mprotect( mapping.ptr.as_ptr().add(page).cast(), - CAPACITY, + capacity, MprotectFlags::READ | MprotectFlags::WRITE, ) } @@ -258,6 +308,19 @@ mod tests { use super::*; + #[test] + fn clamp_stack_capacity_bounds_and_aligns_rlimit_values() { + let page = 4096; + assert_eq!(clamp_stack_capacity(0, page), MIN_CAPACITY); + assert_eq!(clamp_stack_capacity(1024 * 1024, page), MIN_CAPACITY); + assert_eq!(clamp_stack_capacity(MIN_CAPACITY as u64, page), MIN_CAPACITY); + assert_eq!(clamp_stack_capacity(MIN_CAPACITY as u64 + 1, page), MIN_CAPACITY + page); + assert_eq!(clamp_stack_capacity(16 * 1024 * 1024, page), 16 * 1024 * 1024); + assert_eq!(clamp_stack_capacity(MAX_CAPACITY as u64, page), MAX_CAPACITY); + assert_eq!(clamp_stack_capacity(128 * 1024 * 1024, page), MAX_CAPACITY); + assert_eq!(clamp_stack_capacity(RLIM_INFINITY_U64, page), MAX_CAPACITY); + } + #[test] fn args_and_envs_are_contiguous_in_forward_order() { let args = [c"program", c"", c"\xff", c"longer-argument"]; @@ -265,7 +328,7 @@ mod tests { let page = fspy_nostd::param::page_size(); for argc in 0..=args.len() { for envc in 0..=envs.len() { - let mut builder = Builder::new(page); + let mut builder = Builder::with_capacity(page, MIN_CAPACITY); let thin = |value: &'static core::ffi::CStr| { CStr::from_units_with_nul(value.to_bytes_with_nul()).unwrap().as_thin() }; @@ -353,8 +416,8 @@ mod tests { #[should_panic(expected = "initial stack exceeds capacity")] fn rejects_stack_without_call_headroom() { let page = fspy_nostd::param::page_size(); - let mut builder = Builder::new(page); - let huge = std::vec![b'x'; CAPACITY - MIN_STACK_HEADROOM / 2]; + let mut builder = Builder::with_capacity(page, MIN_CAPACITY); + let huge = std::vec![b'x'; MIN_CAPACITY - MIN_STACK_HEADROOM / 2]; let _ = builder.copy(&huge); let _ = builder.finish(); } diff --git a/crates/fspy_elf_loader_test_launcher/build.rs b/crates/fspy_elf_loader_test_launcher/build.rs index 99b5bec3c..3ef51502e 100644 --- a/crates/fspy_elf_loader_test_launcher/build.rs +++ b/crates/fspy_elf_loader_test_launcher/build.rs @@ -1,17 +1,6 @@ fn main() { - if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("none") { - // Leave the low 4 GiB available while staying in application regions - // of the current LLVM Linux ASan and C/C++ TSan layouts. AArch64's - // base also fits smaller virtual address spaces, including 39-bit. - // Older AArch64 TSan runtimes can reject 8 GiB; see the README. - // This is a placement convention; fixed targets can still overlap it. - let image_base = match std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() { - Ok("x86_64") => "--image-base=0x550000000000", // 85 TiB - Ok("aarch64") => "--image-base=0x200000000", // 8 GiB - _ => panic!("unsupported launcher architecture"), - }; - // Fixed linking resolves pointers without a startup self-relocator. - for argument in ["--no-pie", image_base] { + if let Ok(link_args) = std::env::var("DEP_FSPY_ELF_LOADER_LINK_ARGS") { + for argument in link_args.split_whitespace() { println!("cargo::rustc-link-arg={argument}"); } }