ELF Headers, Sections and Segments
Every Linux executable, shared library, object file and core dump, most Android native code and a lot of firmware use one container format: ELF (Executable and Linkable Format). The first thing any analysis tool does is parse its headers, and the first thing a malformed or hostile file attacks is that parser. Knowing the format byte by byte lets you check what tools tell you, recognise files that have been tampered with, and write your own parsers safely. This lesson parses ELF headers with Python's struct (introduced in Binary Formats with struct) on a file the example builds from scratch, then compares with readelf on a real compiled program.
Definitions
- ELF header (64 bytes for 64-bit files) at offset 0: the magic
7f 45 4c 46(\x7fELF), class (1 = 32-bit, 2 = 64-bit), byte order (1 = little-endian), type (ET_REL1 object file,ET_EXEC2 fixed-address executable,ET_DYN3 shared library or PIE executable,ET_CORE4), machine (62 = x86-64, 183 = AArch64), entry point address, and the offsets and counts of the two header tables. - Program headers (the execution view): segments, what the loader maps into memory.
PT_LOADsegments with permissions (R, W, X),PT_INTERP(path of the dynamic loader),PT_DYNAMIC(dynamic linking table),PT_GNU_STACK(stack permissions: NX),PT_GNU_RELRO(made read-only after relocation). - Section headers (the linking view): sections, named pieces for the linker and tools:
.text(code),.rodata(constants, strings),.data,.bss,.symtab,.dynsym,.plt,.got,.eh_frame, debug sections. - The key fact: the kernel and loader use only the program headers. Section headers are optional at run time; a file with its section table removed or corrupted still runs, while tools that rely on sections get confused.
A minimal ELF, built and parsed in Python
The smallest useful ELF executable needs only the ELF header, one PT_LOAD program header and some code: no sections at all. The example builds one whose code is three instructions (mov edi, 42; mov eax, 60; syscall = exit(42)), then parses it back the way a loader would and checks what a careful parser must check.
import struct
def build_tiny_elf():
code = bytes.fromhex("bf2a000000" "b83c000000" "0f05") # mov edi,42; mov eax,60; syscall
base, ehsize, phsize = 0x400000, 64, 56
entry = base + ehsize + phsize
ident = b"\x7fELF" + bytes([2, 1, 1, 0]) + bytes(8) # 64-bit, little-endian, version 1, SysV
ehdr = ident + struct.pack("<HHIQQQIHHHHHH",
2, 62, 1, # e_type ET_EXEC, e_machine x86-64, e_version
entry, ehsize, 0, # e_entry, e_phoff, e_shoff (no section headers)
0, ehsize, phsize, 1, # e_flags, e_ehsize, e_phentsize, e_phnum
64, 0, 0) # e_shentsize, e_shnum, e_shstrndx
total = ehsize + phsize + len(code)
phdr = struct.pack("<IIQQQQQQ", 1, 5, 0, base, base, total, total, 0x1000) # PT_LOAD, R+X
return ehdr + phdr + code
def parse_elf(data):
if len(data) < 64 or data[:4] != b"\x7fELF":
raise ValueError("not an ELF file")
if data[4] != 2 or data[5] != 1:
raise ValueError("only 64-bit little-endian handled here")
(e_type, e_machine, _, e_entry, e_phoff, e_shoff, _, _, e_phentsize, e_phnum,
_, e_shnum, _) = struct.unpack_from("<HHIQQQIHHHHHH", data, 16)
types = {1: "REL", 2: "EXEC", 3: "DYN", 4: "CORE"}
print(f"type={types.get(e_type, e_type)} machine={e_machine} entry={e_entry:#x}")
print(f"program headers: {e_phnum} x {e_phentsize} bytes at {e_phoff}; section headers: {e_shnum}")
# A parser must never trust counts and offsets: check they fit in the file.
if e_phentsize != 56 or e_phoff + e_phnum * e_phentsize > len(data):
raise ValueError("program header table outside the file")
entry_ok = False
for i in range(e_phnum):
p_type, p_flags, p_off, p_vaddr, _, p_filesz, p_memsz, _ = struct.unpack_from(
"<IIQQQQQQ", data, e_phoff + i * e_phentsize)
perms = ("R" if p_flags & 4 else "-") + ("W" if p_flags & 2 else "-") + ("X" if p_flags & 1 else "-")
print(f" segment {i}: type={p_type} {perms} vaddr={p_vaddr:#x} filesz={p_filesz} memsz={p_memsz}")
if p_type == 1 and p_flags & 1 and p_vaddr <= e_entry < p_vaddr + p_memsz:
entry_ok = True
code = data[p_off + (e_entry - p_vaddr):p_off + p_filesz]
print(f" entry point is in segment {i}; first code bytes: {code[:12].hex(' ')}")
print("entry point in an executable LOAD segment:", entry_ok)
elf = build_tiny_elf()
print(f"file size: {len(elf)} bytes")
parse_elf(elf)
print("--- a hostile header: e_phnum = 65535")
bad = bytearray(elf); struct.pack_into("<H", bad, 56, 65535)
try:
parse_elf(bytes(bad))
except ValueError as e:
print("rejected:", e)file size: 132 bytes
type=EXEC machine=62 entry=0x400078
program headers: 1 x 56 bytes at 64; section headers: 0
segment 0: type=1 R-X vaddr=0x400000 filesz=132 memsz=132
entry point is in segment 0; first code bytes: bf 2a 00 00 00 b8 3c 00 00 00 0f 05
entry point in an executable LOAD segment: True
--- a hostile header: e_phnum = 65535
type=EXEC machine=62 entry=0x400078
program headers: 65535 x 56 bytes at 64; section headers: 0
rejected: program header table outside the file
132 bytes make a complete program. The parser prints what readelf -h and readelf -l print, and it refuses the hostile variant: e_phnum = 65535 would make a naive parser read about 3.7 MB (65535 × 56 bytes) past the end of a 132-byte file. Real-world parser bugs in this place (in loaders, antivirus engines, debuggers and disassemblers) have been exploitable, which is why analysis tools are run in sandboxes too.
The same file and a real program in readelf
The session writes the same 132 bytes with the system's Python, checks them with readelf, and runs the file: the exit status is the 42 from the code. Then it compares a normal GCC executable, whose segments contain many sections.
python3 - <<'PY'
import struct
code = bytes.fromhex("bf2a000000b83c0000000f05")
ehdr = b"\x7fELF" + bytes([2, 1, 1, 0]) + bytes(8) + struct.pack("<HHIQQQIHHHHHH",
2, 62, 1, 0x400078, 64, 0, 0, 64, 56, 1, 64, 0, 0)
phdr = struct.pack("<IIQQQQQQ", 1, 5, 0, 0x400000, 0x400000, 132, 132, 0x1000)
open("tiny", "wb").write(ehdr + phdr + code)
PY
chmod +x tiny
readelf -h tiny | grep -E 'Class|Type|Machine|Entry|Number of (program|section) headers'
readelf -lW tiny | grep -E '^\s+LOAD'
./tiny; echo "exit status: $?"
echo "== a normal gcc executable"
printf 'int main(void){return 0;}\n' > n.c && gcc -O2 n.c -o normal
readelf -hW normal | grep -E 'Type|Number of (program|section) headers'
readelf -lW normal | sed -n '/Section to Segment/,$p' | head -8 Class: ELF64
Type: EXEC (Executable file)
Machine: Advanced Micro Devices X86-64
Entry point address: 0x400078
Number of program headers: 1
Number of section headers: 0
LOAD 0x000000 0x0000000000400000 0x0000000000400000 0x000084 0x000084 R E 0x1000
exit status: 42
== a normal gcc executable
Type: DYN (Position-Independent Executable file)
Number of program headers: 13
Number of section headers: 29
Section to Segment mapping:
Segment Sections...
00
01 .interp
02 .interp .note.gnu.property .note.gnu.build-id .note.ABI-tag .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn
03 .init .plt .plt.got .text .fini
04 .rodata .eh_frame_hdr .eh_frame
05 .init_array .fini_array .dynamic .got .data .bss
readelf agrees with the Python parser on every field. The GCC executable is DYN (a PIE), has more than a dozen program headers and around thirty sections, and the "Section to Segment mapping" shows how sections are grouped: the interpreter path in its own segment, code sections in the executable LOAD, and so on.
How malformed and modified ELF files are detected
- Missing or inconsistent section headers (
e_shnum = 0, or sections that don't match the segments) are normal for hand-made files liketiny, rare for compiler output, and common in packed or deliberately obfuscated binaries. Tools that only read sections (old versions of some disassemblers) show nothing useful. - An entry point outside
.text, in a writable segment, or in the last segment of the file, suggests a packer stub or an injected loader (see Packing). - Writable and executable segments (
RWE) andPT_GNU_STACKwithEmean no NX;checksecandreadelf -lWshow both. - Data after the last segment ("overlay") is not loaded by the kernel; installers and some malware store payloads there.
How parsers are kept safe
- Check every offset and count against the file size before reading, as
parse_elfdoes; reject rather than guess. - Parse untrusted files in a sandbox or with a memory-safe parser (Rust's
goblin, Python'spyelftoolsrun in an isolated process), and fuzz your own parsers (the Security Research course covers fuzzing). - Prefer segments for questions about run-time behaviour, sections for questions about how the file was built.
Pitfalls
DYNis not "a library": PIE executables areET_DYNtoo;readelf -dshowingFLAGS_1 ... PIE, or aPT_INTERPsegment, tells them apart.- Endianness: firmware for big-endian MIPS or PowerPC uses
EI_DATA = 2; use>instructformats for those. - 32-bit ELF has different field sizes (52-byte header, 32-byte program headers).
strip --strip-allremoves.symtabbut keeps the section table; tools such assstripremove the section table too.
Practice
1. A file starts 7f 45 4c 46 01 01 01. What do the fifth and sixth bytes tell you?
Class 1 = 32-bit ELF, data 1 = little-endian. Use the 32-bit layouts.
2. Why does tiny run even though it has no sections?
The kernel's ELF loader reads only the ELF header and the program headers; sections are for linkers and tools.
3. Change p_flags in the Python builder from 5 to 4 (R only). What does the parser report, and what would the kernel do?
The entry point check prints False: the only LOAD segment is not executable. The kernel would map the page without execute permission and the process would crash with a segmentation fault at the first instruction.
Test yourself
Which header table does the Linux loader use to map a program into memory?
- The section headers
- The program headers (segments)
- The symbol table
- The .dynamic section only
An x86-64 PIE executable has which ELF type?
- ET_EXEC
- ET_DYN
- ET_REL
- ET_CORE
Why does parse_elf check e_phoff + e_phnum * e_phentsize against the file size?
- To speed up parsing
- Because a hostile file can claim a table far larger than the file, making a naive parser read out of bounds
- Because readelf requires it
- To compute the entry point
What is e_machine 62?
- AArch64
- x86-64
- RISC-V
- 32-bit x86