Static ELF64 ABI and hardening gating in zero-dependency Rust

Linux release binaries break on customer hosts in quiet, repeatable ways. A runner image upgrades from Ubuntu 22.04 to 24.04, and one call to strtol or arc4random silently pulls in __isoc23_strtol@GLIBC_2.38, GLIBCXX_3.4.32, or GLIBC_ABI_DT_RELR (-z pack-relative-relocs). The binary builds cleanly, passes every unit test on the CI runner, and then dies at process startup on RHEL 8 or Debian 11 before main() executes.

Security controls regress the same way. A CMake flag refactor drops -fPIE, downgrades PT_GNU_RELRO from full to partial by losing DT_BIND_NOW, leaks a build-machine DT_RUNPATH or empty : current-directory search entry, introduces DT_TEXTREL, or strips Intel CET and ARM64 BTI/PAC PT_GNU_PROPERTY notes. I built bincompat in zero-dependency safe Rust (#![forbid(unsafe_code)]) to parse ELF64 binaries directly, fail CI with exact offending symbols and rule IDs, and diff releases before shipping. You can test the policy engine live in the interactive bincompat policy simulator.

1. Streaming ELF64 reads and PT_DYNAMIC fallback when sections are stripped

Early versions read the entire binary into a Vec<u8> and relied on section headers (SHT_DYNAMIC, SHT_DYNSYM, SHT_GNU_VERSYM, SHT_GNU_VERNEED). Both assumptions fail in production: large release artifacts waste memory when only small metadata tables are needed, and packed or stripped binaries can set e_shoff == 0 and e_shnum == 0 while remaining completely valid ELF executables for the Linux kernel and dynamic linker.

In src/elf.rs, analyze_file() now uses targeted File seeks and read_exact() calls bounded against file length before any allocation, resolves extended program header counts (PN_XNUM, e_phnum == 0xffff) from section 0 sh_info, caches linked SHT_STRTAB slices, and skips SHT_SYMTAB when stack canary symbols are already found in .dynsym.

When section headers are absent, parse_pt_dynamic_fallback() switches to program headers alone. Every virtual address discovered in PT_DYNAMIC (DT_STRTAB, DT_SYMTAB, DT_HASH, DT_GNU_HASH, DT_VERSYM, DT_VERNEED) passes through checked PT_LOAD translation in vaddr_to_file_offset():

fn vaddr_to_file_offset(loads: &[LoadSegment], vaddr: u64, file_len: u64) -> Option<(u64, u64)> {
    for seg in loads {
        if vaddr >= seg.p_vaddr {
            let delta = vaddr - seg.p_vaddr;
            if delta < seg.p_filesz {
                let file_off = seg.p_offset.checked_add(delta)?;
                let seg_end = seg.p_offset.checked_add(seg.p_filesz)?.min(file_len);
                if file_off < seg_end {
                    return Some((file_off, seg_end - file_off));
                }
            }
        }
    }
    None
}

The trickiest part of section-less parsing is determining how many symbols live in DT_SYMTAB, because ELF stores no DT_SYMSZ dynamic tag. bincompat recovers the symbol count from SysV DT_HASH (reading the 4-byte nchain field at offset 4) or, when only GNU hashing is present, parses DT_GNU_HASH (nbuckets, symoffset, bloom_size * 8 bytes, maximum bucket index, and a bounded chain walk ending at bit 0). Both paths clamp the resulting count against sym_avail / stride so crafted binaries with an inflated DT_VERNEEDNUM or out-of-range DT_STRTAB return typed CorruptDynamic or CorruptVerneed errors instead of hanging or allocating gigabytes.

2. Parsing DT_VERNEED, hidden version bits, and repeated DT_RPATH entries

Knowing a binary requires GLIBC_2.38 is half the debugging loop; knowing which imported symbols dragged that tag in is what lets an engineer fix the build. bincompat walks Elf64_Verneed (checking vn_version == 1, vn_cnt, vn_file, vn_aux, and vn_next) and nested Elf64_Vernaux entries (vna_other, vna_name, vna_next) while tracking visited offsets in two BTreeSets to reject cycles and duplicate vna_other indices.

To attribute symbols back to each tag, attribute_dynsym_versions_slice() reads the matching 16-bit entry from SHT_GNU_VERSYM (or DT_VERSYM) and masks off the 0x8000 hidden-version bit (VERSYM_VERSION_MASK = 0x7fff). Ignoring that bit silently drops hidden default version references. Every non-zero undefined symbol in .dynsym maps straight to its exact (library, raw_tag) requirement, verified against live readelf -d, readelf -V, and readelf --dyn-syms output on /usr/bin/env, /usr/bin/ls, and compiled g++ binaries.

Dynamic search paths had their own subtle edge case. A binary linked with multiple flags can contain more than one DT_RPATH (tag 15) or DT_RUNPATH (tag 29) entry. Overwriting the stored string with the last tag hides earlier paths, including an empty segment that ld.so treats as the current working directory. parse_dynamic_section() now concatenates repeated entries in order with : via append_search_path(), preserving empty segments so both check --forbid-rpath and diff catch them reliably.

3. Parsing PT_GNU_PROPERTY and .note.gnu.property notes

Modern Linux toolchains record hardware control-flow enforcement and x86-64 microarchitecture floor bits inside PT_GNU_PROPERTY (program header type 0x6474e553) and .note.gnu.property sections using ELF note type NT_GNU_PROPERTY_TYPE_0 (5) under owner "GNU". parse_gnu_property_notes() walks 12-byte note headers (n_namesz, n_descsz, n_type) aligned to p_align or sh_addralign, then parses 8-byte-aligned property descriptors (pr_type, pr_datasz, payload) with checked arithmetic on every step:

Descriptor constant Hex ID Decoded bits Policy gate
GNU_PROPERTY_X86_FEATURE_1_AND 0xc0000002 IBT (0x1), SHSTK (0x2) BC013 (--require-cet)
GNU_PROPERTY_AARCH64_FEATURE_1_AND 0xc0000000 BTI (0x1), PAC (0x2) BC014 (--require-bti), BC015 (--require-pac)
GNU_PROPERTY_X86_ISA_1_NEEDED 0xc0008002 x86-64 baseline, v2, v3, v4 level bits BC016 (--max-x86-isa), BC107 (diff)

Reading PT_GNU_PROPERTY first keeps CET, BTI, PAC, and ISA level checks working on stripped binaries with e_shoff == 0, while falling back to .note.gnu.property covers relocatable ET_REL object files that lack program headers. Ground-truth integration tests in tests/readelf_ground_truth.rs cross-check every parsed flag and ISA level directly against live readelf -n output on /usr/bin/env, /usr/bin/ls, and /usr/bin/gcc.

4. Policy rules (BC001 to BC016), diff rules (BC101 to BC107), DSO export ABI rules (BC201 to BC203), and CI outputs

bincompat separates binary inspection from policy evaluation so the same 26 rules run identically from CLI flags, a zero-dependency TOML config file (-c bincompat.toml, with deterministic precedence config target -> config overrides -> CLI --target -> CLI explicit overrides), recursive non-symlink directory walks (-r), transitive dependency-tree gating (check --tree), exported-symbol inspection (bincompat exports), or build-to-build comparisons (bincompat diff). Version comparisons normalize trailing zeros numerically (2.9 < 2.28, 2.3 == 2.3.0) across 14 built-in glibc distro baselines (centos-7 through ubuntu-26.04) plus alpine (musl).

Rule ID Command SARIF rule name Condition flagged
BC001 check SymbolVersionExceeded Imported GLIBC, GLIBCXX, or custom version tag exceeds floor
BC002 check ForbiddenAbiTag Forbidden non-numeric ABI tag such as GLIBC_ABI_DT_RELR or DT_RELR
BC003 check ForbiddenRpath DT_RPATH or DT_RUNPATH entry present (including repeated entries)
BC004 to BC007 check MissingPie / InsufficientRelro / MissingNx / MissingStackCanary Missing PIE, insufficient RELRO, executable stack, or absent stack canary
BC008 check IncompatibleLibc Dynamic musl binary checked against glibc target, or glibc binary on alpine
BC009, BC010 check ForbiddenNeededLibrary / DisallowedNeededLibrary DT_NEEDED matches --forbid-needed or falls outside --allow-needed
BC011, BC012 check MissingFortify / ForbiddenTextrel Dynamic glibc binary lacks __*_chk fortify imports, or contains DT_TEXTREL
BC013 to BC016 check MissingCet / MissingBti / MissingPac / X86IsaNoteExceeded Missing x86-64 CET, ARM64 BTI/PAC, or exceeded x86-64 ISA property note
BC101 to BC107 diff AddedNeededLibrary .. X86IsaNoteBumped New DT_NEEDED, raised version floor, new ABI tag/RPATH, weakened hardening, changed PT_INTERP, or raised x86-64 ISA note
BC201 to BC203 diff / exports RemovedExportedSymbol / VerdefChanged / ExportAbiChanged Removed exported DSO symbol, removed or altered DT_VERDEF node or parent chain, or incompatible symbol type, visibility, or @@VER to @VER demotion

Every subcommand renders deterministic Text, JSON, Markdown, HTML, SARIF 2.1.0 (with invocations and RFC 3986 URI normalization for GitHub Code Scanning), or native --format github annotations, exiting 0 on pass, 1 on violation or regression, and 2 on I/O or malformed ELF input. Want to experiment with distro targets, hardening toggles, dependency trees, DSO export diffs, and SARIF output in the browser? Open the bincompat ELF policy simulator on the homepage.

5. Reproduce locally

brew install alexander-src/tap/bincompat

# Scan a system binary or recursive release directory
bincompat scan /usr/bin/env
bincompat scan -r ./dist --format=json

# Gate against RHEL 8 (manylinux_2_28) and upload SARIF 2.1.0
bincompat check ./build/app \
  --target=rhel-8 \
  --forbid-rpath --forbid-textrel \
  --require-hardening --require-fortify \
  --format=sarif -o bincompat.sarif

# Fail CI if a candidate release raises symbol floors or drops hardening
bincompat diff ./releases/prev/app ./build/app --quiet

Limitations