diff --git a/Cargo.lock b/Cargo.lock index 9d0c90324..7843c433c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1475,6 +1475,7 @@ dependencies = [ "elf", "fspy_nostd", "linux-raw-sys 0.12.1", + "syscalls", "tempfile", ] @@ -1491,6 +1492,7 @@ name = "fspy_elf_loader_tests" version = "0.0.0" dependencies = [ "elf", + "fspy_elf_loader", "fspy_elf_loader_test_launcher", "libc", "ntest", diff --git a/Cargo.toml b/Cargo.toml index ce4b0b9de..20f0880b2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -200,6 +200,7 @@ xxhash-rust = "0.8.15" ntest = "0.9.5" terminal_size = "0.4" zstd = "0.14" +fspy_elf_loader = { path = "crates/fspy_elf_loader" } [workspace.metadata.cargo-shear] ignored = [ diff --git a/crates/fspy_elf_loader/Cargo.toml b/crates/fspy_elf_loader/Cargo.toml index 154943b2f..046b3408a 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", "errno", "general", "no_std", "prctl"] } +syscalls = { workspace = true } [target.'cfg(target_os = "linux")'.dev-dependencies] tempfile = { workspace = true } diff --git a/crates/fspy_elf_loader/README.md b/crates/fspy_elf_loader/README.md index f245f2ff1..c18fa8c57 100644 --- a/crates/fspy_elf_loader/README.md +++ b/crates/fspy_elf_loader/README.md @@ -18,8 +18,9 @@ the kernel will not, once it never sees the target. ## Support -Native little-endian ELF64 on x86-64 and AArch64. `PT_GNU_STACK` must be -non-executable. `ET_EXEC` that overlaps any retained mapping is rejected. +Native little-endian ELF64 on x86-64 and AArch64. An executable `PT_GNU_STACK` +maps the stack executable, as Linux does. `ET_EXEC` that overlaps any retained +mapping is rejected. | | `PT_INTERP` | no `PT_INTERP` | | --------- | ------------------------------------------------- | -------------------------------------------------- | diff --git a/crates/fspy_elf_loader/build.rs b/crates/fspy_elf_loader/build.rs new file mode 100644 index 000000000..b995e7df8 --- /dev/null +++ b/crates/fspy_elf_loader/build.rs @@ -0,0 +1,20 @@ +include!("src/launcher_region.rs"); + +fn main() { + println!("cargo::rerun-if-changed=build.rs"); + println!("cargo::rerun-if-changed=src/launcher_region.rs"); + 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") => LAUNCHER_REGION_X86_64.0, // 85 TiB + Ok("aarch64") => LAUNCHER_REGION_AARCH64.0, // 8 GiB + _ => panic!("unsupported launcher architecture"), + }; + // Fixed linking resolves pointers without a startup self-relocator. + println!("cargo::metadata=link_args=--no-pie --image-base={image_base:#x}"); + } +} diff --git a/crates/fspy_elf_loader/src/image.rs b/crates/fspy_elf_loader/src/image.rs index d5c844d75..f4c37d0d7 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,22 +35,34 @@ 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, + /// The last `PT_GNU_STACK` asks for an executable stack (`PF_X`). + pub exec_stack: bool, +} + /// The final memory layout, with addresses the target can use at runtime. pub struct Image { mapping: Mapping, /// Add this load bias to an ELF virtual address to get its runtime address. pub bias: usize, pub entry: usize, - /// Address of the program-header table inside the mapped image, if present. - pub phdr: Option, + /// Address of the program-header table inside the mapped image (`AT_PHDR`). + pub phdr: usize, pub phnum: usize, + /// The image's `PT_GNU_STACK` asks for an executable stack. + pub exec_stack: bool, } impl Image { @@ -60,45 +72,73 @@ impl Image { #[cfg(test)] pub fn test_stub(page: usize) -> Self { - Self { mapping: Mapping::reserve(page), bias: 0, entry: 0x1000, phdr: Some(0x40), phnum: 1 } + Self { + mapping: Mapping::reserve(page), + bias: 0, + entry: 0x1000, + phdr: 0x40, + phnum: 1, + exec_stack: false, + } } } -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"); + // + // Linux `fs/binfmt_elf.c` does not check `e_ident[EI_VERSION]` or + // `e_version`, while `elf::file::parse_ident` rejects non-`EV_CURRENT`. + // Normalize `EI_VERSION` on a local copy while keeping the magic, + // class, and endianness checks. + let mut ident_buf = [0_u8; 16]; + ident_buf.copy_from_slice(&bytes[..16]); + ident_buf[abi::EI_VERSION] = abi::EV_CURRENT; + let ident = file::parse_ident::(&ident_buf).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 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> { @@ -110,140 +150,187 @@ impl File { ) } - pub const fn is_dynamic(&self) -> bool { - self.header.e_type == abi::ET_DYN - } - - pub fn interpreter(&self) -> Option> { - let mut result = None; + /// Returns the first `PT_INTERP` path; like Linux, later ones are ignored. + pub fn interpreter(&self) -> Result>> { 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)); + 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"); - result = Some(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); + } + return Ok(Some(path)); } } - result + Ok(None) } - fn assert_disjoint_load(&self, index: usize, start: usize, end: usize) { - 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"); - } + /// Validates the `PT_LOAD` headers (bounds, page congruence, and entry + /// point) and records `PT_GNU_STACK`, without mapping any execution + /// segments. Like Linux `binfmt_elf`, overlapping loads, non-power-of-two + /// `p_align`, and an executable stack are accepted. + pub fn validate_segments(&self, page: usize) -> Result { + if !page.is_power_of_two() { + return Err(Error::INVAL); } - } - - 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. let mut low = usize::MAX; - let mut high = 0; + let mut high = 0_usize; let mut alignment = page; - for (index, segment) in self.segments().iter().enumerate() { + let mut exec_stack = false; + let mut executable_entry = false; + + for segment in self.segments().iter() { if segment.p_type == abi::PT_GNU_STACK { - assert!(segment.p_flags & abi::PF_X == 0, "executable stacks are unsupported"); + exec_stack = (segment.p_flags & abi::PF_X) != 0; } 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"); - // 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. + 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); + } + // Header order need not match vaddr order; mapping below walks + // headers so a later MAP_FIXED wins where loads share pages. 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)); + low = low.min(start & !(page - 1)); + let aligned_end = try_align_up(end, page).ok_or(Error::NOEXEC)?; + high = high.max(aligned_end); + 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, and + // Linux ignores a non-power-of-two `p_align`. 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 = usize::try_from(segment.p_align).map_err(|_| Error::NOEXEC)?; + if start % page != offset % page { + return Err(Error::NOEXEC); + } + if align.is_power_of_two() { + alignment = alignment.max(align); } - // 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" - ); - 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_EXEC && low == 0 { + 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, exec_stack }) + } + + /// Rejects fixed-address (`ET_EXEC`) images whose page-rounded span + /// intersects [`crate::LAUNCHER_REGION`]. + /// + /// Returns `EEXIST` rather than `ENOEXEC` so `execvp`/`posix_spawnp`/shells + /// do not fall back to interpreting the ELF binary with `/bin/sh`. + pub(crate) const fn reject_launcher_region_overlap( + &self, + layout: &ValidatedLayout, + ) -> Result<()> { + if self.header.e_type == abi::ET_EXEC { + let (region_base, region_limit) = crate::LAUNCHER_REGION; + if layout.low < region_limit && layout.low.saturating_add(layout.span) > region_base { + return Err(Error::from_raw_os_error(linux_raw_sys::errno::EEXIST.cast_signed())); + } + } + Ok(()) + } + + 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) + self.reject_launcher_region_overlap(layout) + .expect("cannot reserve fixed ELF address range"); + (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; + // Like Linux, AT_PHDR is the table's address in the LOAD whose file + // bytes contain the program-header table, or the load bias when no LOAD + // does. This also works when the ELF has no explicit PT_PHDR header. + let mut phdr = bias; // All segments share one bias, preserving their relative addresses. // The executable and interpreter each get their own reservation/bias. for segment in self.segments().iter().filter(|ph| ph.p_type == abi::PT_LOAD && ph.p_memsz != 0) { let file_start = word(segment.p_offset); - // AT_PHDR must point into the final image, not our temporary file - // view. Find the LOAD covering the table and translate its offset. - // This also works when the ELF has no explicit PT_PHDR header. - if self.headers.start >= file_start - && self.headers.end <= add(file_start, word(segment.p_filesz)) + if let Some(file_end) = file_start.checked_add(word(segment.p_filesz)) + && self.headers.start >= file_start + && self.headers.end <= file_end { - phdr = Some(add( - add(bias, word(segment.p_vaddr)), + phdr = add( + 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), + exec_stack: layout.exec_stack, } } 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 +362,7 @@ impl File { file_len, protection, fixed, - self.fd.as_fd(), + self.fd, segment.p_offset & !u64::try_from(sub(page, 1)).unwrap(), ) } @@ -295,8 +382,9 @@ 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)); - if other_start >= end && other_start < zero_end { + let other_start = bias.wrapping_add(word(other.p_vaddr)); + if other_start > start && other_start >= file_end && other_start < zero_end + { zero_end = other_start; } } @@ -352,3 +440,26 @@ 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)?; + executable.reject_launcher_region_overlap(&layout)?; + 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(), + )?; + // Like Linux, accept an ET_EXEC interpreter and ignore its own + // PT_INTERP and PT_GNU_STACK. + let interp = File::open(interp_fd.as_fd())?; + let interp_layout = interp.validate_segments(page)?; + interp.reject_launcher_region_overlap(&interp_layout)?; + } + Ok(()) +} diff --git a/crates/fspy_elf_loader/src/image/tests.rs b/crates/fspy_elf_loader/src/image/tests.rs index 42d0d5673..746ea6dd9 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] @@ -17,7 +19,7 @@ fn check_bss(page: usize, flags: u32, expected_protection: &str) { let bytes = fixture(page, memory_size, flags); let image = map_bytes(&bytes); assert_eq!(image.bias % (2 * page), 0); - assert_eq!(image.phdr, Some(image.bias + EHDR_SIZE)); + assert_eq!(image.phdr, image.bias + EHDR_SIZE); let maps = std::fs::read_to_string("/proc/self/maps").unwrap(); let protection = |address| { maps.lines() @@ -118,6 +120,61 @@ fn unordered_shared_page_does_not_wipe_higher_segment() { } } +#[test] +fn padzero_clamps_to_higher_segment_overlapping_bss() { + let page = fspy_nostd::param::page_size(); + let mut bytes = std::vec![0xa5; 3 * page]; + write_header(&mut bytes, 3, 0x200); + load(&mut bytes, 0, 0, page, page, abi::PF_R | abi::PF_X, page); + // Higher vaddr first at page + 0x300; lower vaddr second at page + 0x100 + // with filesz = 0x100 (file_end = page + 0x200) and memsz = 0x300 + // (end = page + 0x400 > other_start). + load(&mut bytes, 1, page + 0x300, 0x100, 0x100, abi::PF_R | abi::PF_W, page); + load(&mut bytes, 2, page + 0x100, 0x100, 0x300, abi::PF_R | abi::PF_W, page); + bytes[page + 0x300] = 0x11; + bytes[page + 0x100] = 0x22; + let image = map_bytes(&bytes); + // SAFETY: both segments on the shared page are mapped readable. + unsafe { + assert_eq!(ptr::with_exposed_provenance::(image.bias + page + 0x100).read(), 0x22); + let bss = core::slice::from_raw_parts( + ptr::with_exposed_provenance::(image.bias + page + 0x200), + 0x100, + ); + assert!(bss.iter().all(|byte| *byte == 0)); + assert_eq!( + ptr::with_exposed_provenance::(image.bias + page + 0x300).read(), + 0x11, + "padzero must clamp at other_start >= file_end even when other_start < end" + ); + } +} + +#[test] +fn at_phdr_requires_full_program_header_table_within_p_filesz() { + let page = fspy_nostd::param::page_size(); + let table_end = EHDR_SIZE + 2 * PHDR_SIZE; + + // p_filesz covers e_phoff (headers.start) but ends inside the second Phdr. + let mut partial = std::vec![0; 2 * page]; + write_header(&mut partial, 2, 0x200); + load(&mut partial, 0, 0, table_end - 1, page, abi::PF_R | abi::PF_X, page); + load(&mut partial, 1, page, 0x40, 0x40, abi::PF_R | abi::PF_W, page); + let partial_image = map_bytes(&partial); + assert_eq!( + partial_image.phdr, partial_image.bias, + "AT_PHDR must not point to a program-header table partially past p_filesz" + ); + + // Exact boundary: p_filesz == headers.end maps the entire table. + let mut exact = std::vec![0; 2 * page]; + write_header(&mut exact, 2, 0x200); + load(&mut exact, 0, 0, table_end, page, abi::PF_R | abi::PF_X, page); + load(&mut exact, 1, page, 0x40, 0x40, abi::PF_R | abi::PF_W, page); + let exact_image = map_bytes(&exact); + assert_eq!(exact_image.phdr, exact_image.bias + EHDR_SIZE); +} + #[test] fn preserves_previous_load_when_bss_only_starts_mid_page() { let page = fspy_nostd::param::page_size(); @@ -192,40 +249,279 @@ fn accepts_page_congruent_segment_incongruent_with_large_p_align() { } #[test] -#[should_panic(expected = "overlapping ELF segments")] -fn rejects_overlapping_load_segments() { +fn reports_no_interpreter_when_pt_interp_is_absent() { 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(&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 reports_no_interpreter_when_pt_interp_is_absent() { +fn accepts_pt_interp_padded_with_extra_nuls() { + 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] +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] +fn validate_exec_checks_valid_and_invalid_images_without_closing_fd() { 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()); + + // 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 at a non-zero fixed load address. + let exec_base = 0x40_0000_u64; + let mut exec_bytes = std::vec![0xa5; 2 * page]; + write_header(&mut exec_bytes, 1, exec_base + 0x200); + exec_bytes[16..18].copy_from_slice(&abi::ET_EXEC.to_le_bytes()); + Phdr { + p_type: abi::PT_LOAD, + p_flags: abi::PF_R | abi::PF_X, + p_offset: 0, + p_vaddr: exec_base, + 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 exec_bytes, 0); + 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()); + + // Zero-address ET_EXEC image -> NOEXEC (cannot reserve address 0). + let mut zero_exec_bytes = fixture(page, 0x180, abi::PF_R | abi::PF_W); + zero_exec_bytes[16..18].copy_from_slice(&abi::ET_EXEC.to_le_bytes()); + let zero_exec = open_bytes(&zero_exec_bytes); + assert_eq!(crate::validate_exec(zero_exec.as_fd()), Err(Error::NOEXEC)); + + // 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 is accepted, as Linux does, and recorded. + 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()), Ok(())); + let exec_stack_file = File::open(exec_stack_fd.as_fd()).unwrap(); + assert!(exec_stack_file.validate_segments(page).unwrap().exec_stack); + + // 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 or (as Linux allows) ET_EXEC + // interpreter succeeds. + 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(())); + + std::fs::write(dyn_interp_file.path(), &exec_bytes).unwrap(); + assert_eq!(crate::validate_exec(valid_dyn_fd.as_fd()), Ok(())); } #[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(); - assert_eq!(path.as_units(), b"ld.so"); +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, mapped_base + EHDR_SIZE); } #[test] -#[should_panic(expected = "unterminated PT_INTERP")] -fn rejects_unterminated_pt_interp() { - let _ = File::new(open_bytes(&interp_image(b"ld.so"))).interpreter(); +fn accepts_non_ev_current_ident_and_header_versions() { + let page = fspy_nostd::param::page_size(); + for (ei_version, e_version) in [(0_u8, 0_u32), (0, 1), (1, 0), (2, 2), (2, 0)] { + let mut bytes = fixture(page, 0x180, abi::PF_R | abi::PF_W); + bytes[abi::EI_VERSION] = ei_version; + bytes[20..24].copy_from_slice(&e_version.to_le_bytes()); + + let fd = open_bytes(&bytes); + let parsed = File::open(fd.as_fd()).expect("non-EV_CURRENT ELF should open"); + let _layout = parsed.validate_segments(page).expect("non-EV_CURRENT ELF should validate"); + assert_eq!(crate::validate_exec(fd.as_fd()), Ok(())); + } + + // Magic, ELF64 class, and little-endian data checks must still reject invalid images. + for (offset, bad_byte) in + [(0_usize, 0x00_u8), (abi::EI_CLASS, abi::ELFCLASS32), (abi::EI_DATA, abi::ELFDATA2MSB)] + { + let mut bytes = fixture(page, 0x180, abi::PF_R | abi::PF_W); + bytes[offset] = bad_byte; + let fd = open_bytes(&bytes); + assert_eq!(File::open(fd.as_fd()).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_rejects_et_exec_overlapping_launcher_region_with_eexist() { + let page = fspy_nostd::param::page_size(); + let eexist = Error::from_raw_os_error(linux_raw_sys::errno::EEXIST.cast_signed()); + let (region_base, region_limit) = crate::LAUNCHER_REGION; + + let make_et_exec = |vaddr: usize, memsz: usize| { + let mut bytes = std::vec![0xa5; 2 * page]; + let vaddr_u64 = u64::try_from(vaddr).unwrap(); + write_header(&mut bytes, 1, vaddr_u64 + 0x200); + bytes[16..18].copy_from_slice(&abi::ET_EXEC.to_le_bytes()); + Phdr { + p_type: abi::PT_LOAD, + p_flags: abi::PF_R | abi::PF_X, + p_offset: 0, + p_vaddr: vaddr_u64, + p_filesz: u64::try_from(page).unwrap(), + p_memsz: u64::try_from(memsz).unwrap(), + p_align: u64::try_from(page).unwrap(), + } + .write_to(&mut bytes, 0); + bytes + }; + + // 1. Segment strictly inside LAUNCHER_REGION -> EEXIST. + let inside = open_bytes(&make_et_exec(region_base + 4 * page, 2 * page)); + assert_eq!(crate::validate_exec(inside.as_fd()), Err(eexist)); + + // 2a. Segment straddling the lower boundary of LAUNCHER_REGION -> EEXIST. + let straddle_low = open_bytes(&make_et_exec(region_base - page, 2 * page)); + assert_eq!(crate::validate_exec(straddle_low.as_fd()), Err(eexist)); + + // 2b. Segment straddling the upper boundary of LAUNCHER_REGION -> EEXIST. + let straddle_high = open_bytes(&make_et_exec(region_limit - page, 2 * page)); + assert_eq!(crate::validate_exec(straddle_high.as_fd()), Err(eexist)); + + // 3. Segment fully containing LAUNCHER_REGION -> EEXIST. + let containing = + open_bytes(&make_et_exec(region_base - page, (region_limit - region_base) + 2 * page)); + assert_eq!(crate::validate_exec(containing.as_fd()), Err(eexist)); + + // 4. PIE executable with a fixed-address (ET_EXEC) PT_INTERP overlapping + // LAUNCHER_REGION -> EEXIST. + let interp_file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(interp_file.path(), make_et_exec(region_base + 2 * page, page)).unwrap(); + let interp_path = + std::ffi::CString::new(interp_file.path().as_os_str().as_encoded_bytes()).unwrap(); + let mut pie_with_bad_interp = std::vec![0; 2 * page]; + write_header(&mut pie_with_bad_interp, 2, 0x200); + load(&mut pie_with_bad_interp, 0, 0, page, page, abi::PF_R | abi::PF_X, page); + let pbytes = interp_path.as_bytes_with_nul(); + let p_off = page - pbytes.len(); + pie_with_bad_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 pie_with_bad_interp, 1); + let pie_fd = open_bytes(&pie_with_bad_interp); + assert_eq!(crate::validate_exec(pie_fd.as_fd()), Err(eexist)); + + // 5. Normal ET_EXEC outside LAUNCHER_REGION (and adjacent non-overlapping + // boundaries) -> Ok(()). + for (vaddr, memsz) in + [(0x40_0000_usize, 2 * page), (region_base - 2 * page, 2 * page), (region_limit, 2 * page)] + { + let ok_fd = open_bytes(&make_et_exec(vaddr, memsz)); + assert_eq!( + crate::validate_exec(ok_fd.as_fd()), + Ok(()), + "non-overlapping ET_EXEC at {vaddr:#x}..{:#x} should validate", + vaddr + memsz + ); + } } fn fixture(page: usize, memory_size: usize, flags: u32) -> std::vec::Vec { @@ -318,7 +614,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/launcher_region.rs b/crates/fspy_elf_loader/src/launcher_region.rs new file mode 100644 index 000000000..720366afe --- /dev/null +++ b/crates/fspy_elf_loader/src/launcher_region.rs @@ -0,0 +1,7 @@ +/// Reserved fixed-address region `(base, limit)` for the freestanding x86-64 +/// launcher, inside LLVM's Linux `ASan` and C/C++ `TSan` 85–90 TiB application range. +pub const LAUNCHER_REGION_X86_64: (u64, u64) = (0x5500_0000_0000, 0x5a00_0000_0000); + +/// Reserved fixed-address region `(base, limit)` for the freestanding `AArch64` +/// launcher, inside 39-bit virtual address space and `TSan`'s low 20 GiB range. +pub const LAUNCHER_REGION_AARCH64: (u64, u64) = (0x0002_0000_0000, 0x0005_0000_0000); diff --git a/crates/fspy_elf_loader/src/lib.rs b/crates/fspy_elf_loader/src/lib.rs index 8125f6919..9a7663fae 100644 --- a/crates/fspy_elf_loader/src/lib.rs +++ b/crates/fspy_elf_loader/src/lib.rs @@ -13,33 +13,73 @@ //! We implement the mapping, stack, and entry steps after the kernel has //! already executed our freestanding loader. We leave its mappings and signal //! handlers in place. Calling another kernel exec here would discard them. -#![cfg(any(target_os = "linux", target_os = "none"))] #![no_std] -#[cfg(test)] +#[cfg(all(test, target_os = "linux"))] extern crate std; -use fspy_nostd::{CStr, OwnedFd, Thin, env::AuxEntry}; -use linux_raw_sys::auxvec::AT_PAGESZ; +mod launcher_region; +pub use launcher_region::{LAUNCHER_REGION_AARCH64, LAUNCHER_REGION_X86_64}; +/// Reserved fixed-address region `(base, limit)` for the current architecture's +/// freestanding launcher. +#[cfg(all(any(target_os = "linux", target_os = "none"), target_arch = "x86_64"))] +#[expect(clippy::cast_possible_truncation, reason = "x86_64 has 64-bit usize")] +pub const LAUNCHER_REGION: (usize, usize) = + (LAUNCHER_REGION_X86_64.0 as usize, LAUNCHER_REGION_X86_64.1 as usize); + +/// Reserved fixed-address region `(base, limit)` for the current architecture's +/// freestanding launcher. +#[cfg(all(any(target_os = "linux", target_os = "none"), target_arch = "aarch64"))] +#[expect(clippy::cast_possible_truncation, reason = "aarch64 has 64-bit usize")] +pub const LAUNCHER_REGION: (usize, usize) = + (LAUNCHER_REGION_AARCH64.0 as usize, LAUNCHER_REGION_AARCH64.1 as usize); + +#[cfg(any(target_os = "linux", target_os = "none"))] +use fspy_nostd::{BorrowedFd, CStr, OwnedFd, Result, Thin, env::AuxEntry}; +#[cfg(any(target_os = "linux", target_os = "none"))] +use linux_raw_sys::{auxvec::AT_PAGESZ, prctl::PR_SET_NAME}; +#[cfg(any(target_os = "linux", target_os = "none"))] +use syscalls::Sysno; + +#[cfg(any(target_os = "linux", target_os = "none"))] mod image; +#[cfg(any(target_os = "linux", target_os = "none"))] mod mapping; +#[cfg(any(target_os = "linux", target_os = "none"))] 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 (such as wrong architecture or non-ELF64), `EEXIST` if a fixed-address +/// (`ET_EXEC`) executable or interpreter overlaps [`LAUNCHER_REGION`], or the +/// underlying OS error if `fd` or its `PT_INTERP` cannot be inspected or opened. +#[cfg(any(target_os = "linux", target_os = "none"))] +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 @@ -48,13 +88,12 @@ mod stack; /// that executed the loader. /// /// Currently supports native little-endian ELF64 executables on `AArch64` and -/// x86-64, with a non-executable stack. Both PIE (`ET_DYN`) and fixed-address +/// x86-64. 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 /// @@ -74,6 +113,7 @@ mod stack; /// or malformed image, runs out of stack capacity, or fails to map or open a /// file. The freestanding panic handler must terminate the process. Faults /// after entering the interpreter or executable are not converted into panics. +#[cfg(any(target_os = "linux", target_os = "none"))] pub unsafe fn exec_elf<'a>( elf_file: OwnedFd, execfn: CStr<'a, Thin>, @@ -87,25 +127,33 @@ 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"); + // 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); - assert!(file.is_dynamic(), "fixed-address PT_INTERP is unsupported"); - assert!(file.interpreter().is_none(), "nested PT_INTERP is unsupported"); - file + .expect("cannot open ELF interpreter") }); - let executable_image = executable.map(page_size); - let interpreter_image = interpreter.as_ref().map(|file| file.map(page_size)); + let interpreter = interp_fd.as_ref().map(|fd| { + let file = image::File::open(fd.as_fd()).expect("invalid ELF interpreter"); + let layout = file.validate_segments(page_size).expect("invalid ELF interpreter segments"); + (file, layout) + }); + + 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 +166,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,12 +191,25 @@ 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. +#[cfg(any(target_os = "linux", target_os = "none"))] +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 // C function arguments in registers, installs the process-entry stack, and // jumps. A normal call would put an unwanted return address on x86-64's stack. -#[cfg(target_arch = "aarch64")] +#[cfg(all(any(target_os = "linux", target_os = "none"), target_arch = "aarch64"))] #[unsafe(naked)] unsafe extern "C" fn enter(_entry: usize, _stack: *mut usize) -> ! { // X0 holds entry and X1 holds the new SP. Match Linux start_thread by @@ -183,7 +251,7 @@ unsafe extern "C" fn enter(_entry: usize, _stack: *mut usize) -> ! { ); } -#[cfg(target_arch = "x86_64")] +#[cfg(all(any(target_os = "linux", target_os = "none"), target_arch = "x86_64"))] #[unsafe(naked)] unsafe extern "C" fn enter(_entry: usize, _stack: *mut usize) -> ! { // RDI holds entry and RSI holds the new RSP. RDX is the optional diff --git a/crates/fspy_elf_loader/src/mapping.rs b/crates/fspy_elf_loader/src/mapping.rs index 9d63f8d0e..e732ba1bf 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") } @@ -47,6 +58,7 @@ impl Mapping { pub fn reserve_at(address: usize, len: usize) -> Self { Self::check_len(len); + assert!(address != 0, "cannot reserve fixed ELF address range at address zero"); // Reserve the complete fixed-address image before replacing any of // its pages. A collision with the loader, stack, or another mapping // must fail without changing that mapping. @@ -72,30 +84,35 @@ 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) }?; + Self::try_new(ptr.cast(), len) } fn check_len(len: usize) { assert!(len != 0 && isize::try_from(len).is_ok(), "invalid mapping length"); } - fn new(ptr: *mut u8, len: usize) -> Self { + fn try_new(ptr: *mut u8, len: usize) -> Result { let Some(ptr) = NonNull::new(ptr) 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.cast(), len) }; - panic!("mapping returned address zero"); + return Err(Error::NOMEM); }; - Self { ptr, len } + Ok(Self { ptr, len }) + } + + fn new(ptr: *mut u8, len: usize) -> Self { + Self::try_new(ptr, len).expect("mmap returned address zero") } /// Only called on immutable, fully readable file mappings. diff --git a/crates/fspy_elf_loader/src/stack.rs b/crates/fspy_elf_loader/src/stack.rs index 67752906d..697183abe 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,68 @@ use fspy_nostd::{ env::AuxEntry, mm::{self, MprotectFlags}, }; -use linux_raw_sys::auxvec as abi; +use linux_raw_sys::{ + auxvec as abi, + general::{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; +// Linux `RLIM64_INFINITY` (`~0ULL`) for `rlimit64::rlim_cur`. +// `linux_raw_sys::general::RLIM_INFINITY` is typed as `i32 = -1`, so use +// `u64::MAX` directly without relying on sign-extension casts. +const RLIM64_INFINITY_U64: u64 = u64::MAX; + +/// Computes the target stack capacity from an `RLIMIT_STACK` soft limit, +/// treating `RLIM64_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 == RLIM64_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. @@ -47,21 +94,27 @@ struct Builder { } impl Builder { - fn new(page: usize) -> Self { + fn new(page: usize, exec_stack: bool) -> Self { + let capacity = query_stack_capacity(page); + Self::with_capacity(page, capacity, exec_stack) + } + + /// Maps the stack read-write, plus execute when the executable's + /// `PT_GNU_STACK` asks for it, as Linux does. + fn with_capacity(page: usize, capacity: usize, exec_stack: bool) -> 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)); + let mut protection = MprotectFlags::READ | MprotectFlags::WRITE; + if exec_stack { + protection |= MprotectFlags::EXEC; + } // 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 // exclusively owned and do not have live references. - unsafe { - mm::mprotect( - mapping.ptr.as_ptr().add(page).cast(), - CAPACITY, - MprotectFlags::READ | MprotectFlags::WRITE, - ) - } - .expect("cannot map target stack"); + unsafe { mm::mprotect(mapping.ptr.as_ptr().add(page).cast(), capacity, protection) } + .expect("cannot map target stack"); Self { strings: mapping.len, mapping, start: page, word_count: 0 } } @@ -191,7 +244,7 @@ pub unsafe fn build<'a>( interpreter: Option<&Image>, page: usize, ) -> *mut usize { - let mut stack = Builder::new(page); + let mut stack = Builder::new(page, image.exec_stack); stack.args_envs(argv, envp); for mut entry in inherited { let Ok(key) = u32::try_from(entry.key) else { @@ -238,7 +291,7 @@ pub unsafe fn build<'a>( // PHDR/PHENT/PHNUM locate and size the executable's header table; ENTRY // is its startup address. With PT_INTERP we enter the interpreter first // and BASE is that image's load bias. Without one, BASE is 0 as on Linux. - stack.aux(abi::AT_PHDR, image.phdr.expect("program headers are not mapped by PT_LOAD")); + stack.aux(abi::AT_PHDR, image.phdr); stack.aux(abi::AT_PHENT, PHDR_SIZE); stack.aux(abi::AT_PHNUM, image.phnum); stack.aux(abi::AT_ENTRY, image.entry); @@ -258,6 +311,40 @@ 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(RLIM64_INFINITY_U64, page), MAX_CAPACITY); + } + + #[test] + fn maps_the_stack_executable_only_when_asked() { + let page = fspy_nostd::param::page_size(); + for (exec_stack, expected) in [(false, "rw-p"), (true, "rwxp")] { + let builder = Builder::with_capacity(page, MIN_CAPACITY, exec_stack); + let usable = builder.mapping.ptr.as_ptr().addr() + page; + let maps = std::fs::read_to_string("/proc/self/maps").unwrap(); + let protection = maps + .lines() + .find_map(|line| { + let mut fields = line.split_whitespace(); + let (start, end) = fields.next()?.split_once('-')?; + let range = usize::from_str_radix(start, 16).ok()? + ..usize::from_str_radix(end, 16).ok()?; + range.contains(&usable).then(|| fields.next().unwrap()) + }) + .unwrap(); + assert_eq!(protection, expected); + } + } + #[test] fn args_and_envs_are_contiguous_in_forward_order() { let args = [c"program", c"", c"\xff", c"longer-argument"]; @@ -265,7 +352,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, false); let thin = |value: &'static core::ffi::CStr| { CStr::from_units_with_nul(value.to_bytes_with_nul()).unwrap().as_thin() }; @@ -353,8 +440,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, false); + 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}"); } } diff --git a/crates/fspy_elf_loader_tests/Cargo.toml b/crates/fspy_elf_loader_tests/Cargo.toml index 0e7c174bb..81f7b8dde 100644 --- a/crates/fspy_elf_loader_tests/Cargo.toml +++ b/crates/fspy_elf_loader_tests/Cargo.toml @@ -9,6 +9,7 @@ rust-version.workspace = true [dev-dependencies] elf = { workspace = true } +fspy_elf_loader = { workspace = true } [target.'cfg(target_os = "linux")'.dev-dependencies] libc = { workspace = true } diff --git a/crates/fspy_elf_loader_tests/fixtures/runtime.c b/crates/fspy_elf_loader_tests/fixtures/runtime.c index 167282321..11de28fdb 100644 --- a/crates/fspy_elf_loader_tests/fixtures/runtime.c +++ b/crates/fspy_elf_loader_tests/fixtures/runtime.c @@ -3,8 +3,10 @@ * * Protocol: argv[0]="custom-argv-zero", argv[1]="", argv[2]=0xff, * EMPTY="", BYTES=0xff, FIXTURE_IMAGE=AT_EXECFN, stdout "runtime-ok\n", - * exit 37. Set EXPECT_INTERPRETER=1 when PT_INTERP is present (AT_BASE != 0) - * and EXPECT_FIXED_ADDRESS=1 for ET_EXEC images (load bias == 0). + * exit 37. Set EXPECT_INTERPRETER=1 when PT_INTERP is present (AT_BASE != 0), + * EXPECT_FIXED_ADDRESS=1 for ET_EXEC images (load bias == 0), + * EXPECT_ALIGNED_RANDOM=1 when AT_RANDOM must be 16-byte aligned (exec_elf), + * and EXPECT_EXEC_STACK=1 when /proc/self/maps must show an rwxp stack. */ #define _GNU_SOURCE @@ -13,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -72,7 +75,7 @@ static unsigned long load_bias(unsigned long at_phdr, unsigned long phnum, const return 0; } -int main(int argc, char **argv) { +int main(int argc, char **argv, char **envp) { unsigned long i; pthread_t thread; int started = 0; @@ -98,6 +101,24 @@ int main(int argc, char **argv) { if ((unsigned char)argv[2][0] != 0xff || argv[2][1] != '\0') { fail("argv2"); } + { + /* Verify Linux's ascending, contiguous argv + envp string layout. */ + const char *prev_end = NULL; + int arg_i; + size_t env_i; + for (arg_i = 0; arg_i < argc; arg_i++) { + if (prev_end != NULL && argv[arg_i] != prev_end) { + fail("argv contiguity"); + } + prev_end = argv[arg_i] + strlen(argv[arg_i]) + 1; + } + for (env_i = 0; envp[env_i] != NULL; env_i++) { + if (prev_end != NULL && envp[env_i] != prev_end) { + fail("envp contiguity"); + } + prev_end = envp[env_i] + strlen(envp[env_i]) + 1; + } + } if (getenv("EMPTY") == NULL || getenv("EMPTY")[0] != '\0') { fail("EMPTY"); } @@ -193,6 +214,9 @@ int main(int argc, char **argv) { if (random == NULL) { fail("AT_RANDOM"); } + if (getenv("EXPECT_ALIGNED_RANDOM") != NULL && ((uintptr_t)random % 16) != 0) { + fail("AT_RANDOM alignment"); + } for (i = 0; i < 16; i++) { if (random[i] != 0) { nonzero = 1; @@ -202,6 +226,64 @@ int main(int argc, char **argv) { fail("AT_RANDOM zero"); } } + { + const char *platform = (const char *)getauxval(AT_PLATFORM); + if (platform != NULL) { +#if defined(__x86_64__) + if (strcmp(platform, "x86_64") != 0) { + fail("AT_PLATFORM"); + } +#elif defined(__aarch64__) + if (strcmp(platform, "aarch64") != 0) { + fail("AT_PLATFORM"); + } +#else + if (platform[0] == '\0') { + fail("AT_PLATFORM empty"); + } +#endif + } + } +#ifdef AT_BASE_PLATFORM + { + const char *base_platform = (const char *)getauxval(AT_BASE_PLATFORM); + if (base_platform != NULL && base_platform[0] == '\0') { + fail("AT_BASE_PLATFORM empty"); + } + } +#endif + if (getenv("EXPECT_EXEC_STACK") != NULL) { + volatile int stack_marker = 0; + unsigned long stack_addr = (unsigned long)(uintptr_t)&stack_marker; + FILE *maps = fopen("/proc/self/maps", "r"); + char line[512]; + int found_stack = 0; + if (maps == NULL) { + fail("fopen /proc/self/maps"); + } + while (fgets(line, sizeof line, maps) != NULL) { + unsigned long start = 0; + unsigned long end = 0; + char perms[8]; + if (sscanf(line, "%lx-%lx %7s", &start, &end, perms) == 3) { + if (stack_addr >= start && stack_addr < end) { + if (strcmp(perms, "rwxp") != 0) { + fail("stack not rwxp"); + } + found_stack = 1; + break; + } + } + if (strchr(line, '\n') == NULL) { + int ch; + while ((ch = fgetc(maps)) != '\n' && ch != EOF) {} + } + } + fclose(maps); + if (!found_stack) { + fail("stack mapping not found"); + } + } { DIR *dir = opendir("/proc/self/fd"); diff --git a/crates/fspy_elf_loader_tests/tests/exec_elf.rs b/crates/fspy_elf_loader_tests/tests/exec_elf.rs index 47f5e14a1..5f9ada6e3 100644 --- a/crates/fspy_elf_loader_tests/tests/exec_elf.rs +++ b/crates/fspy_elf_loader_tests/tests/exec_elf.rs @@ -67,6 +67,7 @@ fn run_loaded_fixture(fixture: &str, interpreter: bool, fixed_address: bool) -> let mut command = launcher(); command.args([fixture, "custom-argv-zero"]); configure_runtime_fixture(&mut command, fixture, interpreter, fixed_address); + command.env("EXPECT_ALIGNED_RANDOM", "1"); output(command) } @@ -176,28 +177,67 @@ fn node_runs_javascript() { #[timeout(10_000)] fn rejects_malformed_images() { let base = std::fs::read(FIXTURE_DYN_PIE).unwrap(); + let mut bad_magic = base.clone(); + bad_magic[0..4].copy_from_slice(b"NOPE"); + let mut elf32 = base.clone(); + elf32[elf::abi::EI_CLASS] = elf::abi::ELFCLASS32; let mut overflow = base.clone(); write_u64(&mut overflow, offset_of!(libc::Elf64_Ehdr, e_phoff), u64::MAX); let mut wrong_machine = base.clone(); write_u16(&mut wrong_machine, offset_of!(libc::Elf64_Ehdr, e_machine), 0); let mut unsupported_type = base.clone(); write_u16(&mut unsupported_type, offset_of!(libc::Elf64_Ehdr, e_type), elf::abi::ET_REL); + let mut entry_outside_exec = base.clone(); + write_u64(&mut entry_outside_exec, offset_of!(libc::Elf64_Ehdr, e_entry), u64::MAX - 0x100); let parsed = elf::ElfBytes::::minimal_parse(&base).unwrap(); - let load = - parsed.segments().unwrap().iter().position(|ph| ph.p_type == elf::abi::PT_LOAD).unwrap(); + let segments: Vec<_> = parsed.segments().unwrap().iter().collect(); + let load = segments.iter().position(|ph| ph.p_type == elf::abi::PT_LOAD).unwrap(); let phdr = usize::try_from(parsed.ehdr.e_phoff).unwrap() + load * size_of::(); let mut invalid_size = base.clone(); write_u64(&mut invalid_size, phdr + offset_of!(libc::Elf64_Phdr, p_filesz), u64::MAX); - let mut invalid_alignment = base.clone(); - write_u64(&mut invalid_alignment, phdr + offset_of!(libc::Elf64_Phdr, p_align), 3); + let mut incongruent_load = base.clone(); + write_u64( + &mut incongruent_load, + phdr + offset_of!(libc::Elf64_Phdr, p_vaddr), + segments[load].p_vaddr + 1, + ); + + let interp_index = segments + .iter() + .position(|ph| ph.p_type == elf::abi::PT_INTERP) + .expect("FIXTURE_DYN_PIE has PT_INTERP"); + let interp_phdr = usize::try_from(parsed.ehdr.e_phoff).unwrap() + + interp_index * size_of::(); + let with_interp = |path_with_nul: &[u8]| { + let mut bytes = base.clone(); + let offset = u64::try_from(bytes.len()).unwrap(); + let len = u64::try_from(path_with_nul.len()).unwrap(); + bytes.extend_from_slice(path_with_nul); + write_u64(&mut bytes, interp_phdr + offset_of!(libc::Elf64_Phdr, p_offset), offset); + write_u64(&mut bytes, interp_phdr + offset_of!(libc::Elf64_Phdr, p_filesz), len); + write_u64(&mut bytes, interp_phdr + offset_of!(libc::Elf64_Phdr, p_memsz), len); + bytes + }; + let missing_interp = with_interp(b"/nonexistent-interp\0"); + let corrupt_interp_file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(corrupt_interp_file.path(), b"not an ELF interpreter").unwrap(); + let mut corrupt_interp_path = corrupt_interp_file.path().as_os_str().as_bytes().to_vec(); + corrupt_interp_path.push(0); + let corrupt_interp = with_interp(&corrupt_interp_path); + for (case, bytes) in [ ("truncated header", b"not ELF".to_vec()), + ("bad magic (>= 64 bytes)", bad_magic), + ("ELF32 header", elf32), ("truncated program headers", base[..size_of::()].to_vec()), ("overflowing program-header offset", overflow), ("wrong architecture", wrong_machine), ("unsupported type", unsupported_type), ("invalid size", invalid_size), - ("invalid alignment", invalid_alignment), + ("e_entry outside PF_X", entry_outside_exec), + ("non-page-congruent PT_LOAD", incongruent_load), + ("missing PT_INTERP", missing_interp), + ("corrupt PT_INTERP", corrupt_interp), ] { let file = tempfile::NamedTempFile::new().unwrap(); std::fs::write(file.path(), bytes).unwrap(); @@ -212,6 +252,37 @@ fn rejects_malformed_images() { } } +#[test] +#[timeout(10_000)] +fn runs_images_with_an_executable_stack() { + // Like Linux, an executable PT_GNU_STACK maps the stack executable rather + // than rejecting the image (e.g. objects built without `.note.GNU-stack`). + let mut bytes = std::fs::read(FIXTURE_DYN_PIE).unwrap(); + let parsed = elf::ElfBytes::::minimal_parse(&bytes).unwrap(); + let stack = parsed + .segments() + .unwrap() + .iter() + .position(|ph| ph.p_type == elf::abi::PT_GNU_STACK) + .expect("fixture has PT_GNU_STACK"); + let phdr = + usize::try_from(parsed.ehdr.e_phoff).unwrap() + stack * size_of::(); + let flags = phdr + offset_of!(libc::Elf64_Phdr, p_flags); + let value = u32::from_le_bytes(bytes[flags..flags + 4].try_into().unwrap()) | elf::abi::PF_X; + bytes[flags..flags + 4].copy_from_slice(&value.to_le_bytes()); + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), bytes).unwrap(); + let fixture = file.path().to_str().unwrap(); + let mut command = launcher(); + command.args([fixture, "custom-argv-zero"]); + configure_runtime_fixture(&mut command, fixture, true, false); + command.env("EXPECT_ALIGNED_RANDOM", "1").env("EXPECT_EXEC_STACK", "1"); + let output = output(command); + assert_eq!(output.status.code(), Some(37), "{output:?}"); + assert_eq!(output.stdout, b"runtime-ok\n"); + assert!(output.stderr.is_empty(), "{output:?}"); +} + #[test] #[timeout(10_000)] fn does_not_require_section_headers() { diff --git a/crates/fspy_elf_loader_tests/tests/launcher_image.rs b/crates/fspy_elf_loader_tests/tests/launcher_image.rs index 036fd7e5e..91051b765 100644 --- a/crates/fspy_elf_loader_tests/tests/launcher_image.rs +++ b/crates/fspy_elf_loader_tests/tests/launcher_image.rs @@ -15,8 +15,8 @@ fn launcher_uses_high_fixed_addresses_without_runtime_relocations() { // Keep the entire image inside a sanitizer application region: x86-64 // C/C++ TSan's 85–90 TiB region, or AArch64 39-bit TSan's low 20 GiB. let (base, limit) = match image.ehdr.e_machine { - abi::EM_X86_64 => (0x5500_0000_0000, 0x5a00_0000_0000), - abi::EM_AARCH64 => (0x0002_0000_0000, 0x0005_0000_0000), + abi::EM_X86_64 => fspy_elf_loader::LAUNCHER_REGION_X86_64, + abi::EM_AARCH64 => fspy_elf_loader::LAUNCHER_REGION_AARCH64, machine => panic!("unsupported launcher machine: {machine}"), }; let segments: Vec<_> = image.segments().unwrap().iter().collect();