Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Find strings in ELF files with no section headers, read from their loaded segments (#491)

Bently2c7a311dfdba
diff --git a/crates/disasm/src/program.rs b/crates/disasm/src/program.rs
index a28e11cd..146897e3 100644
--- a/crates/disasm/src/program.rs
+++ b/crates/disasm/src/program.rs
@@ -695,25 +695,35 @@ fn collect_strings(img: &Image, limits: &Limits) -> Vec<ProgString> {
let mut out = Vec::new();
let raw = matches!(bin.format, Format::Raw | Format::DosCom | Format::DosMz);
let mut budget = limits.max_data_scan;
- for s in &bin.sections {
+ // (name, address, file offset, bytes in the file) of each region to read strings from.
+ let regions: Vec<(&str, u64, Option<u64>, u64)> = if bin.sections.is_empty() {
+ // No section headers (firmware, or headers removed): every loaded segment, code ones too,
+ // as for a raw image, because read-only data often shares the code's segment then.
+ // Bytes past the segment's size in memory are not mapped, so they are not read.
+ bin.segments.iter().map(|g| (g.name.as_str(), g.addr, Some(g.file_offset), g.file_size.min(g.size))).filter(|&(_, _, _, n)| n > 0).collect()
+ } else {
+ bin.sections
+ .iter()
+ .filter(|s| !((s.exec && !raw) || !s.alloc || matches!(s.kind, "debug" | "bss")))
+ .map(|s| (s.name.as_str(), s.addr, s.file_offset, s.file_size))
+ .collect()
+ };
+ for (name, addr, file_offset, file_size) in regions {
if out.len() >= limits.max_strings || budget == 0 {
break;
}
- if (s.exec && !raw) || !s.alloc || matches!(s.kind, "debug" | "bss") {
- continue;
- }
- let Some(off) = s.file_offset.and_then(|o| usize::try_from(o).ok()) else { continue };
- let n = usize::try_from(s.file_size).unwrap_or(0).min(budget);
+ let Some(off) = file_offset.and_then(|o| usize::try_from(o).ok()) else { continue };
+ let n = usize::try_from(file_size).unwrap_or(0).min(budget);
budget -= n;
let Some(bytes) = img.data.get(off..off.saturating_add(n).min(img.data.len())) else { continue };
for f in craft_anything_formats::strings::extract(bytes, 0, limits.string_min_len, limits.max_strings - out.len()) {
out.push(ProgString {
- addr: s.addr.wrapping_add(f.offset),
+ addr: addr.wrapping_add(f.offset),
file_offset: off as u64 + f.offset,
byte_len: f.byte_len,
encoding: f.encoding,
text: f.text,
- section: s.name.clone(),
+ section: name.to_string(),
});
}
}
@@ -1372,6 +1382,36 @@ mod tests {
}
}
+ #[test]
+ fn strings_are_found_in_the_segments_when_there_are_no_sections() {
+ let (mut elf, l) = tk::elf64(tk::ElfArch::X86_64, false);
+ let (_, sectioned) = analyze(elf.clone());
+ let hello = |p: &Program| p.strings.iter().find(|s| s.text == "Hello, Craft!").map(|s| (s.addr, s.file_offset));
+ assert_eq!(hello(&sectioned), Some((l.rodata_va, l.rodata_va - tk::ELF_BASE)));
+ // Remove the section header table: offset, count and name-table index.
+ elf[40..48].fill(0);
+ elf[60..64].fill(0);
+ let (img, p) = analyze(elf.clone());
+ assert!(img.bin.sections.is_empty());
+ assert_eq!(hello(&p), hello(&sectioned), "the same string at the same address");
+ let s = p.strings.iter().find(|s| s.text == "Hello, Craft!").unwrap();
+ assert!(img.bin.segments.iter().any(|g| g.name == s.section), "named after its segment: {}", s.section);
+ // A code segment that claims more file bytes than the file has, and than it has in memory:
+ // only the bytes it maps are read. Its header is the second one; the first is PT_INTERP.
+ let phoff = usize::try_from(u64::from_le_bytes(elf[32..40].try_into().unwrap())).unwrap();
+ let load = phoff + 56;
+ assert_eq!(elf[load..load + 4], [1, 0, 0, 0], "PT_LOAD");
+ elf[load + 32..load + 40].copy_from_slice(&u64::MAX.to_le_bytes());
+ let (img, p) = analyze(elf);
+ let code = img.bin.segments.iter().find(|g| g.exec).unwrap();
+ assert!(code.file_size > code.size, "file size {} is clamped to the file, not to memory {}", code.file_size, code.size);
+ assert_eq!(hello(&p), hello(&sectioned));
+ for s in &p.strings {
+ let g = img.bin.segments.iter().find(|g| g.name == s.section).unwrap();
+ assert!(s.addr >= g.addr && s.addr + s.byte_len <= g.addr + g.size, "{s:?} is inside {} as mapped", g.name);
+ }
+ }
+
#[test]
fn the_prologue_scan_walks_executable_segments_when_there_are_no_sections() {
let (mut elf, l) = tk::elf64(tk::ElfArch::X86_64, false);