Перейти к основному содержимому
ELF & PE Binary Formats: Headers, Sections & Imports
Урок 3 из 11

ELF & PE Binary Formats: Headers, Sections & Imports

Navigate ELF and PE headers, sections, segments, and import tables using readelf, pefile, and DIE to locate code, embedded resources, and packing indicators.

Средний 26 мин Реверс-инжиниринг
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.
Только в разрешённой среде — Описанные здесь приёмы применяются только в учебных лабораториях и в системах, которые принадлежат вам или на которые есть письменное разрешение.

Цели обучения

  • Explain the difference between ELF sections used for linking and segments used by the OS loader
  • Trace the Windows PE header chain from the DOS MZ header and e_lfanew to the Optional Header and sections
  • Convert between a PE Relative Virtual Address (RVA) and a raw file offset
  • Identify suspicious imports, custom sections, and high-entropy regions using readelf, pefile, and DIE

Рекомендуется заранее: CPU Registers, Memory Addressing & Calling ConventionsAssembly Basics: x86/x64 & ARM Control Flow

#Why this matters

Before you read a single assembly instruction in objdump or Ghidra, you need to know how the operating system parses and loads the executable file. Knowing where executable code sits, where read-only strings or resources live, and which OS APIs a program imports saves hours of blind searching.

On Linux and Android, executables use ELF (Executable and Linkable Format). On Windows, they use PE (Portable Executable). Both containers solve the same problem with slightly different structures.

#ELF anatomy: headers, segments, and sections

Every valid ELF file begins with the 4-byte magic sequence 7f 45 4c 46 (\x7fELF). The ELF header specifies the target architecture (e_machine, e.g., EM_X86_64), the entry point (e_entry), and e_type (ET_EXEC for fixed-address executables or ET_DYN for shared libraries and Position-Independent Executables, PIE).

ELF separates two views of the binary:

  • Segments (Program Headers, readelf -l) are required at runtime. PT_LOAD segments tell the kernel which byte ranges to map into memory with Read (R), Write (W), and Execute (E) permissions, while PT_INTERP names the dynamic linker.
  • Sections (Section Headers, readelf -S) help linkers and analysts. Common sections include .text (machine code), .rodata (read-only constants and strings), .data (writable globals), .bss (zero-initialized data occupying zero bytes on disk), and .dynsym (imported/exported dynamic symbols). Running strip removes .symtab, yet .dynsym stays intact so dynamic linking still works.

#PE anatomy: headers, RVAs, and imports

A Windows PE file begins with a legacy DOS header starting with MZ (4d 5a). At file offset 0x3c, the 32-bit field e_lfanew points to the PE\0\0 (50 45 00 00) signature, followed by:

  1. COFF File Header: Machine (0x8664 for x64, 0x014c for x86), NumberOfSections, and TimeDateStamp.
  2. Optional Header: AddressOfEntryPoint, ImageBase, FileAlignment (often 0x200 on disk), SectionAlignment (often 0x1000 in memory), and Data Directories pointing to imports, exports, and resources.
  3. Section Table: .text (code), .rdata (read-only data and imports), .data (globals), .rsrc (icons, manifests, or embedded payloads), and .reloc (relocation entries).
  1. 1DOS MZ Header (4d 5a)e_lfanew at 0x3c points to PE signature
  2. 2PE\0\0 + COFF HeaderMachine architecture and section count
  3. 3Optional HeaderImageBase, EntryPoint RVA, Data Directories
  4. 4Section Headers.text, .rdata, .data, .rsrc mappings

Because disk alignment differs from memory alignment, a Relative Virtual Address (RVA) (offset from ImageBase in memory) rarely equals the raw file offset. To convert an RVA inside a section: FileOffset = PointerToRawData + (RVA - VirtualAddress).

Purpose ELF PE
Magic bytes \x7fELF (7f 45 4c 46) MZ (4d 5a) then PE\0\0
Executable code .text .text
Read-only strings .rodata .rdata
Embedded assets Custom sections / .rodata .rsrc
Dynamic imports .dynsym, .plt, .got Import Directory / IAT

#Inspecting sections, imports, and entropy

Using readelf on Linux, pefile in Python, and Detect It Easy (DIE) gives a fast static profile before disassembly:

Checking ELF sections and parsing a PE sample with pefile
$ readelf -S ./lab_chal | grep -E "\.text|\.rodata|\.secret"
  [14] .text             PROGBITS         0000000000001060  00001060
  [16] .rodata           PROGBITS         0000000000002000  00002000
  [25] .secret           PROGBITS         0000000000004020  00003020
$ python3 -c "import pefile; pe=pefile.PE('sample.exe'); print([(s.Name.decode().strip('\x00'), hex(s.Misc_VirtualSize), hex(s.SizeOfRawData), round(s.get_entropy(),2)) for s in pe.sections])"
[('.text', '0x1240', '0x1400', 6.12), ('.rdata', '0x680', '0x800', 4.91), ('.rsrc', '0x4200', '0x4200', 7.91)]

Notice .rsrc has an entropy of 7.91 out of 8.0: compiled code typically scores 5.5-6.6, while values above 7.5 suggest encrypted, compressed, or packed blobs. Similarly, a section with SizeOfRawData = 0 and a large VirtualSize is a classic packer signature (an empty buffer allocated for unpacking at runtime).

#Common mistakes

  • Treating an RVA as a file offset. Always subtract the section's VirtualAddress and add PointerToRawData before slicing a PE file on disk.
  • Trusting section names blindly. Packers rename .text to anything they choose; inspect PT_LOAD / section permission flags (X or IMAGE_SCN_MEM_EXECUTE) and where EntryPoint lands instead.
  • Assuming strip removes all symbols. Stripping deletes .symtab, but .dynsym remains readable via readelf --dyn-syms because the OS dynamic linker needs those names.
  • Running strings and stopping there. Embedded config or flags often live inside .rsrc resources or non-default sections encoded or XORed at rest.

#Summary

ELF and PE headers tell the OS loader how to map code, data, and external libraries into virtual memory. Distinguishing ELF segments from sections, navigating PE headers from MZ and e_lfanew to sections and imports, and converting between RVAs and file offsets let you pinpoint where logic and hidden payloads reside. Checking section sizes, imports, and entropy in readelf, pefile, and DIE reveals packers and custom data before you even start disassembling.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания