#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Linkage {
Static,
Musl,
Glibc,
Other(String),
}
impl Linkage {
pub fn as_str(&self) -> &str {
match self {
Linkage::Static => "static",
Linkage::Musl => "musl",
Linkage::Glibc => "glibc",
Linkage::Other(interp) => interp,
}
}
}
fn u16_at(b: &[u8], off: usize, little: bool) -> Option<u16> {
let raw: [u8; 2] = b.get(off..off.checked_add(2)?)?.try_into().ok()?;
Some(if little {
u16::from_le_bytes(raw)
} else {
u16::from_be_bytes(raw)
})
}
fn u64_at(b: &[u8], off: usize, little: bool) -> Option<u64> {
let raw: [u8; 8] = b.get(off..off.checked_add(8)?)?.try_into().ok()?;
Some(if little {
u64::from_le_bytes(raw)
} else {
u64::from_be_bytes(raw)
})
}
pub fn linkage(bytes: &[u8]) -> Option<Linkage> {
const ELF_CLASS64: u8 = 2;
const PT_INTERP: u32 = 3;
if !bytes.starts_with(&[0x7F, b'E', b'L', b'F']) {
return None;
}
if *bytes.get(4)? != ELF_CLASS64 {
return None;
}
let little = *bytes.get(5)? == 1;
let e_phoff = u64_at(bytes, 32, little)?;
let e_phentsize = u16_at(bytes, 54, little)? as usize;
let e_phnum = u16_at(bytes, 56, little)? as usize;
if e_phentsize < 56 {
return None;
}
let phoff = usize::try_from(e_phoff).ok()?;
for i in 0..e_phnum {
let entry = phoff.checked_add(i.checked_mul(e_phentsize)?)?;
let p_type = {
let raw: [u8; 4] = bytes.get(entry..entry.checked_add(4)?)?.try_into().ok()?;
if little {
u32::from_le_bytes(raw)
} else {
u32::from_be_bytes(raw)
}
};
if p_type != PT_INTERP {
continue;
}
let p_offset = usize::try_from(u64_at(bytes, entry.checked_add(8)?, little)?).ok()?;
let p_filesz = usize::try_from(u64_at(bytes, entry.checked_add(32)?, little)?).ok()?;
let raw = bytes.get(p_offset..p_offset.checked_add(p_filesz)?)?;
let text = raw.split(|b| *b == 0).next().unwrap_or(raw);
let interp = String::from_utf8_lossy(text).into_owned();
return Some(if interp.contains("ld-musl") {
Linkage::Musl
} else if interp.contains("ld-linux") || interp.contains("ld.so") {
Linkage::Glibc
} else {
Linkage::Other(interp)
});
}
Some(Linkage::Static)
}
#[cfg(test)]
mod tests {
use super::{Linkage, linkage};
#[test]
fn real_release_binaries_report_the_libc_they_actually_need() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/libc");
for (name, want) in [
("ordeal-musl.elfhead", Linkage::Static),
("ordeal-gnu.elfhead", Linkage::Glibc),
] {
let path = dir.join(name);
let bytes = std::fs::read(&path)
.unwrap_or_else(|e| panic!("fixture {} is required: {e}", path.display()));
assert_eq!(
linkage(&bytes).as_ref(),
Some(&want),
"{name}: measured the wrong floor"
);
}
}
#[test]
fn an_unmeasurable_payload_is_not_reported_as_static() {
assert_eq!(linkage(b"#!/bin/sh\necho hi\n"), None, "a script");
assert_eq!(linkage(b""), None, "empty");
assert_eq!(linkage(b"\x7fELF"), None, "truncated before EI_CLASS");
let mut elf32 = vec![0x7F, b'E', b'L', b'F', 1, 1];
elf32.resize(128, 0);
assert_eq!(linkage(&elf32), None, "ELF32");
}
#[test]
fn a_program_header_larger_than_the_minimum_is_still_measured() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/libc");
let real = std::fs::read(dir.join("ordeal-gnu.elfhead")).expect("fixture");
assert_eq!(
linkage(&real),
Some(Linkage::Glibc),
"the unmodified fixture must measure, or this test proves nothing"
);
let phoff = u64::from_le_bytes(real[32..40].try_into().unwrap()) as usize;
let phentsize = u16::from_le_bytes(real[54..56].try_into().unwrap()) as usize;
let phnum = u16::from_le_bytes(real[56..58].try_into().unwrap()) as usize;
assert_eq!(phentsize, 56, "fixture assumption: the ELF64 minimum");
const WIDE: usize = 64;
let mut wide = real.clone();
let new_phoff = wide.len();
for i in 0..phnum {
let entry = &real[phoff + i * phentsize..phoff + (i + 1) * phentsize];
wide.extend_from_slice(entry);
wide.extend_from_slice(&[0u8; WIDE - 56]);
}
wide[32..40].copy_from_slice(&(new_phoff as u64).to_le_bytes());
wide[54..56].copy_from_slice(&(WIDE as u16).to_le_bytes());
assert_eq!(
linkage(&wide),
Some(Linkage::Glibc),
"a 64-byte program header entry is legal and must still be read"
);
}
#[test]
fn a_program_header_too_small_to_hold_one_is_not_measured() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/libc");
let mut bytes = std::fs::read(dir.join("ordeal-gnu.elfhead")).expect("fixture");
bytes[54..56].copy_from_slice(&32u16.to_le_bytes());
assert_eq!(
linkage(&bytes),
None,
"a 32-byte program header cannot hold an ELF64 one"
);
}
#[test]
fn an_unrecognised_interpreter_is_recorded_verbatim_not_rounded() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/libc");
let mut bytes = std::fs::read(dir.join("ordeal-gnu.elfhead")).expect("fixture");
let gnu = b"/lib64/ld-linux-x86-64.so.2";
let at = bytes
.windows(gnu.len())
.position(|w| w == gnu)
.expect("the real fixture names the glibc interpreter");
let odd = b"/opt/acme/ld-acme-x86_64.so";
assert_eq!(odd.len(), gnu.len());
bytes[at..at + odd.len()].copy_from_slice(odd);
match linkage(&bytes) {
Some(Linkage::Other(interp)) => assert_eq!(
interp, "/opt/acme/ld-acme-x86_64.so",
"the interpreter must be recorded exactly as the ELF names it"
),
other => panic!(
"an unrecognised interpreter was rounded to {other:?} — a signed \
claim about a libc nobody measured"
),
}
assert_eq!(
Linkage::Other("/opt/acme/ld-acme-x86_64.so".into()).as_str(),
"/opt/acme/ld-acme-x86_64.so"
);
}
#[test]
fn a_musl_interpreter_is_not_rounded_to_glibc() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/libc");
let mut bytes = std::fs::read(dir.join("ordeal-gnu.elfhead")).expect("fixture");
let gnu = b"/lib64/ld-linux-x86-64.so.2";
let at = bytes
.windows(gnu.len())
.position(|w| w == gnu)
.expect("the real fixture names the glibc interpreter");
let musl = b"/lib/ld-musl-x86_64.so.1\0\0\0";
assert_eq!(
musl.len(),
gnu.len(),
"same length keeps every offset valid"
);
bytes[at..at + musl.len()].copy_from_slice(musl);
assert_eq!(linkage(&bytes), Some(Linkage::Musl));
}
}