Section 12.35

pyelftools

Full name: pyelftools: a coined name from py (for Python), ELF (Executable and Linking Format) and tools; it is not an abbreviation.

Definition

pyelftools is a Python §12.23 library that reads ELF §12.6 (Executable and Linking Format) files, the standard format for programs, libraries and object files on Linux and in most embedded toolchains §12.2, and the DWARF §12.9 (Debugging With Attributed Record Formats) debugging information inside them. It returns a file’s parts as Python objects: its headers; its sections and segments, the regions that divide its bytes; its symbols, which are names with their addresses; and its debugging records. It never loads or runs the program. Eli Bendersky wrote it in pure Python.

The idea

A test script must read a firmware variable named boot_count through a debugger, so it needs the variable’s address and size; another tool must map a crash address to a function and a source line. Both answers are in the ELF file the build produced: in the symbol table §12.8, a list of names with their addresses and sizes, and in the debugging information. pyelftools hands a script these structures without the script decoding the binary format.

An ELF file is a plan, and the memory of the running program is the building made from it. The builder, an operating system’s loader or a microcontroller’s §6.1 startup code, follows only one part of the plan, the program headers. While building, it adds what the plan only describes, such as regions filled with zeros, and settles what the plan leaves open, such as the base address of a position-independent program. Afterwards the running program changes its own memory. pyelftools reads the plan exactly; it cannot see the building. The picture stops at one point: a building is made from one known plan, but nothing in an ELF file shows that the device runs that file and not another.

How it works

An ELF file offers two views of its bytes.

A loader uses only the segment view. A program can run with its section headers stripped out entirely.

Reading a file with pyelftools:

  1. Open the file in binary mode and create elf = ELFFile(f). pyelftools reads each part of the file only when asked, so the file must stay open while its objects are in use.

  2. elf["e_type"] is ET_EXEC for an executable at fixed addresses, ET_DYN for a shared library or a position-independent executable (PIE), whose addresses are offsets from a base chosen at load time, and ET_REL for an object file not yet linked.

  3. elf.iter_sections() and elf.iter_segments() list the sections and the segments. Each is indexed by field name, as in seg["p_vaddr"], and a section’s data() method returns its bytes.

  4. The symbol table section, fetched with elf.get_section_by_name(".symtab"), has a method get_symbol_by_name, which returns a list of the symbols with the given name, or None. Each symbol has a value st_value, an address in a linked file, and a size st_size.

  5. elf.get_dwarf_info() gives the DWARF records: compilation units, one per compiled source file; entries that describe functions, variables and types; and line tables that map addresses to source lines.

  6. A malformed file raises ELFError or another exception.

What happens between the file and the running memory, and so cannot be read from the file alone:

Worked example

A firmware ELF file for a microcontroller whose flash memory starts at address 0x00000000 and whose RAM starts at 0x20000000 has a PT_LOAD segment with these fields:

Its symbol table holds table, with st_value == 0x20000010 and st_size == 16, and counter, with st_value == 0x20000120 and st_size == 4.

table starts 𝟶𝚡𝟸𝟶𝟶𝟶𝟶𝟶𝟷𝟶−𝟶𝚡𝟸𝟶𝟶𝟶𝟶𝟶𝟶𝟶=𝟶𝚡𝟷𝟶\texttt{0x20000010} - \texttt{0x20000000} = \texttt{0x10}, which is 16, bytes into the segment. Its 16 bytes end at offset 16+16=3216 + 16 = 32, below 256, so all of them lie in the part that comes from the file. Its initial values sit in the file at offset 𝟶𝚡𝟿𝟺𝟶𝟶+𝟶𝚡𝟷𝟶=𝟶𝚡𝟿𝟺𝟷𝟶\texttt{0x9400} + \texttt{0x10} = \texttt{0x9410}, in flash at 𝟶𝚡𝟾𝟺𝟶𝟶+𝟶𝚡𝟷𝟶=𝟶𝚡𝟾𝟺𝟷𝟶\texttt{0x8400} + \texttt{0x10} = \texttt{0x8410}, and, once the startup code has copied them, in RAM at 0x20000010: three addresses for one variable.

counter starts 𝟶𝚡𝟷𝟸𝟶=288\texttt{0x120} = 288 bytes into the segment. Since 288≥256288 \ge 256, it lies in the zero-filled part, which runs from 𝟶𝚡𝟸𝟶𝟶𝟶𝟶𝟶𝟶𝟶+𝟶𝚡𝟷𝟶𝟶=𝟶𝚡𝟸𝟶𝟶𝟶𝟶𝟷𝟶𝟶\texttt{0x20000000} + \texttt{0x100} = \texttt{0x20000100} to 𝟶𝚡𝟸𝟶𝟶𝟶𝟶𝟶𝟶𝟶+𝟶𝚡𝟻𝟶𝟶−1=𝟶𝚡𝟸𝟶𝟶𝟶𝟶𝟺𝚏𝚏\texttt{0x20000000} + \texttt{0x500} - 1 = \texttt{0x200004ff}, a region of 1280−256=10241280 - 256 = 1024 bytes. The file holds no bytes for counter. Its value is 0 when the startup code finishes. If the firmware then increments it 37 times, a debugger reading RAM at 0x20000120 finds 37, and the file says nothing about that.

A desktop program meets the base address instead. Suppose main has st_value == 0x1139 in a position-independent executable for Linux on a 64-bit x86 processor. Run under a debugger that turns ASLR off, the program is loaded at the base 0x555555554000, so main sits at 𝟶𝚡𝟻𝟻𝟻𝟻𝟻𝟻𝟻𝟻𝟺𝟶𝟶𝟶+𝟶𝚡𝟷𝟷𝟹𝟿=𝟶𝚡𝟻𝟻𝟻𝟻𝟻𝟻𝟻𝟻𝟻𝟷𝟹𝟿\texttt{0x555555554000} + \texttt{0x1139} = \texttt{0x555555555139}. With ASLR on, the base changes from run to run.

Stated precisely

The System V application binary interface (ABI §12.47), the specification that defines how ELF files are loaded, states the rule for a loadable segment. Let a PT_LOAD entry have file offset oo (p_offset), address vv (p_vaddr), file size ff (p_filesz) and memory size mm (p_memsz), with f≤mf \le m. Let BB be the load bias: 0 for an ET_EXEC file, and for an ET_DYN file the amount by which the loader shifts all addresses. Write mem[x]\mathrm{mem}[x] for the byte at memory address xx and file[y]\mathrm{file}[y] for the byte at file offset yy. When loading is complete, mem[B+v+i]={file[o+i]for 0≤i<f,0for f≤i<m.\mathrm{mem}[B + v + i] = \begin{cases} \mathrm{file}[o + i] & \text{for } 0 \le i < f, \\ 0 & \text{for } f \le i < m. \end{cases} A symbol with value ss in a linked file is at run address B+sB + s.

These equalities hold only under three assumptions.

  1. Identity. The file that was loaded is, byte for byte, the file that was parsed.

  2. A conforming loader. The loader follows the rule. On a microcontroller the flash programmer and the startup code together play that part, and they follow the rule only if the startup code and the linker script §12.5 agree on the addresses.

  3. Nothing has changed the bytes since. Relocations applied by the dynamic linker change the bytes they name, and every write by the program changes memory after it starts. From then on, only the program’s behavior determines what memory holds.

Section headers, symbols and DWARF records describe the program; no loader reads them to decide what goes into memory.

Limits and common mistakes

A successful parse shows that the file is well formed, not that it is authentic or that it is the file on the device. To tie an analysis to the device, compare a cryptographic hash §5.1 of the parsed file with that of the file that was flashed or loaded, or read memory back and compare it with the segment bytes.

Sections can disagree with segments. A stripped file, one from which a tool such as strip removed the symbol table, has no .symtab; some tools also remove the section headers altogether; and a crafted file can carry section headers that describe bytes other than those its segments load. For what actually runs, read the program headers.

Source names and symbols do not match one to one. A function that the compiler inlined, copying its body into each caller, has no address of its own and appears only in DWARF records. After compiler optimization §3.39, DWARF can place a variable in different registers at different addresses, or mark it as optimized out, meaning that no location holds its value at that point.

A file crafted to attack the parser can make pyelftools raise exceptions other than ELFError. A tool that parses untrusted files should catch every exception and limit the work it does per file.

Questions answered

How do parsed metadata and actual loaded memory differ?

Parsed metadata is what an ELF (Executable and Linking Format) file says about a program; loaded memory is what a loader, or a microcontroller’s flash programmer and startup code, built from that file, changed by everything that has run since. A parser such as pyelftools returns the metadata: sections, symbols, debugging records, and the program headers that describe the loadable segments. Five things separate that from memory:

  1. the loader follows only the program headers, never the section headers;

  2. regions such as .bss exist only in memory, as zeros, with no bytes in the file;

  3. a position-independent program is placed at a base address chosen at load time, on Linux at random, and relocation writes final addresses into it;

  4. on a microcontroller, initialized data is stored in flash at one address and copied to RAM at another by startup code;

  5. once the program runs, it changes its own memory.

Finally, nothing in the file shows that it is the file the device runs; that needs a separate comparison, for example of cryptographic hashes.

Related entries: ELF (§12.6), Symbol table (§12.8), Debug information (DWARF) (§12.9), Machine-code proof boundary (§4.48), Program loading: from an ELF file to a running native process (§12.49), Relocation: turning a symbolic reference into exact encoded bits (§12.50). Further reading: [41, 110, 111].