mirror of
https://github.com/morluto/rea.git
synced 2026-11-23 06:55:55 +00:00
* perf(pcap/pwntools): eliminate redundant parsing, linear scans, and quadratic allocations * fix(pcap/pwntools): address review threads on DNS reconciliation, request target cache bound, and dead helpers
505 lines
34 KiB
Python
505 lines
34 KiB
Python
"""Offline adapter to unchanged pwntools 4.15.0; never use libs/maps/libc.
|
|
|
|
Owned request/snapshot/reply paths are supplied by REA. No host target-process launch,
|
|
user configuration initialization, debugger startup, or dependency installation.
|
|
"""
|
|
import base64
|
|
import gc
|
|
import importlib.metadata
|
|
import io
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
|
|
PROFILE = "pwntools@4.15.0;pyelftools@0.33;unicorn@2.1.2"
|
|
PACKAGES = {"pwntools": "4.15.0", "pyelftools": "0.33", "unicorn": "2.1.2"}
|
|
OUTPUT_BYTES = 64 * 1024 * 1024
|
|
# (e_machine, ELF class bits, byte order) -> architecture pwntools must also report.
|
|
PROFILES = {(62, 64, "little"): "amd64", (183, 64, "little"): "aarch64", (3, 32, "little"): "i386",
|
|
(40, 32, "little"): "arm", (8, 32, "little"): "mips", (8, 32, "big"): "mips"}
|
|
PROFILE_SCOPE = ("Layout profile requires ELF64 x86-64, ELF64 AArch64 little-endian, ELF32 i386, "
|
|
"ELF32 ARM little-endian or ELF32 MIPS little- or big-endian objects.")
|
|
|
|
|
|
class LayoutFailure(Exception):
|
|
def __init__(self, reason, message):
|
|
super().__init__(message)
|
|
self.reason = reason
|
|
|
|
|
|
def address(value):
|
|
return "0x0" if value == 0 else hex(value if type(value) is int else int(value))
|
|
|
|
|
|
def file_range(offset, size, length):
|
|
return 0 <= offset <= length and 0 <= size <= length - offset
|
|
|
|
|
|
def location(offset, size, length):
|
|
if not file_range(offset, size, length):
|
|
raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.")
|
|
return {"offset": address(offset), "bytes": address(size)}
|
|
|
|
|
|
def _name_in_validated_table(display, table_start, table_size, offset, content, length, cache=None):
|
|
if not 0 <= offset < table_size:
|
|
raise LayoutFailure("format", f"ELF name offset {offset} lies outside its declared string table of {table_size} bytes at file offset {table_start}.")
|
|
if cache is not None:
|
|
cached = cache.get(offset)
|
|
if cached is not None:
|
|
raw_display, b64, off_hex, bytes_hex = cached
|
|
if display is None:
|
|
if raw_display is None:
|
|
start = table_start + offset
|
|
end = content.find(b"\0", start, table_start + table_size)
|
|
raw_display = content[start:end].decode("utf-8", "replace")
|
|
cache[offset] = (raw_display, b64, off_hex, bytes_hex)
|
|
resolved_display = raw_display
|
|
else:
|
|
resolved_display = display
|
|
return {"display": resolved_display, "bytes_base64": b64,
|
|
"location": {"offset": off_hex, "bytes": bytes_hex}, "unknown_reason": None}
|
|
start = table_start + offset
|
|
limit = table_start + table_size
|
|
end = content.find(b"\0", start, limit)
|
|
if end < 0:
|
|
raise LayoutFailure("format", "ELF name lacks a terminator within its reported string table.")
|
|
raw = content[start:end]
|
|
raw_size = len(raw) + 1
|
|
if not file_range(start, raw_size, length):
|
|
raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.")
|
|
b64 = base64.b64encode(raw).decode("ascii")
|
|
off_hex = address(start)
|
|
bytes_hex = address(raw_size)
|
|
raw_display = raw.decode("utf-8", "replace") if display is None else None
|
|
if cache is not None:
|
|
cache[offset] = (raw_display, b64, off_hex, bytes_hex)
|
|
return {"display": raw_display if display is None else display, "bytes_base64": b64,
|
|
"location": {"offset": off_hex, "bytes": bytes_hex}, "unknown_reason": None}
|
|
|
|
|
|
def inspect_elf(path, cache):
|
|
for package, expected in PACKAGES.items():
|
|
try:
|
|
version = importlib.metadata.version(package)
|
|
except importlib.metadata.PackageNotFoundError as error:
|
|
raise LayoutFailure("unavailable", "Selected Python lacks " + package + " " + expected + ".") from error
|
|
if version != expected:
|
|
raise LayoutFailure("unsupported", "Expected " + package + " " + expected + "; selected Python reports " + version + ".")
|
|
content = path.read_bytes()
|
|
length = len(content)
|
|
if length < 4 or content[:4] != b"\x7fELF":
|
|
raise LayoutFailure("format", "Selected object does not contain an ELF header.")
|
|
if length < 16:
|
|
raise LayoutFailure("format", "Selected ELF identification is truncated.")
|
|
if content[4] not in (1, 2) or content[5] not in (1, 2):
|
|
raise LayoutFailure("unsupported-target", "Selected ELF declares an unknown class or byte order.")
|
|
bits, header_size = (32, 52) if content[4] == 1 else (64, 64)
|
|
order = "little" if content[5] == 1 else "big"
|
|
if length < header_size:
|
|
raise LayoutFailure("format", f"Selected ELF{bits} header is truncated.")
|
|
profile = (int.from_bytes(content[18:20], order), bits, order)
|
|
if profile not in PROFILES:
|
|
raise LayoutFailure("unsupported-target", PROFILE_SCOPE)
|
|
if int.from_bytes(content[16:18], order) not in (1, 2, 3):
|
|
raise LayoutFailure("unsupported-target", "Selected ELF type is outside the EXEC/DYN/REL layout profile; recorded core analysis is separate.")
|
|
from pwnlib.context import context
|
|
with context.local(cache_dir=str(cache), log_level="warning"):
|
|
from elftools.common.exceptions import ELFError
|
|
from elftools.common.utils import struct_parse
|
|
from elftools.elf.elffile import ELFFile
|
|
from pwnlib.elf import ELF
|
|
from pwnlib.elf import elf as upstream_elf
|
|
try:
|
|
headers = ELFFile(io.BytesIO(content))
|
|
section_count = headers.num_sections()
|
|
consumed_strings = set()
|
|
compressed_strtabs = []
|
|
if section_count:
|
|
if headers.header.e_shentsize < headers.structs.Elf_Shdr.sizeof():
|
|
raise LayoutFailure("format", "ELF section-header entry is shorter than the required structure.")
|
|
if not file_range(headers.header.e_shoff, section_count * headers.header.e_shentsize, length):
|
|
raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.")
|
|
# Upstream symbol, relocation and dynamic access reads stored stream
|
|
# bytes, while this profile reports logical names and file coordinates.
|
|
# A string table is read only when it names sections or symbols.
|
|
e_shoff = headers.header.e_shoff
|
|
e_shentsize = headers.header.e_shentsize
|
|
elf_shdr_struct = headers.structs.Elf_Shdr
|
|
stream = headers.stream
|
|
for index in range(section_count):
|
|
raw_header = struct_parse(elf_shdr_struct, stream,
|
|
stream_pos=e_shoff + index * e_shentsize)
|
|
sh_type = raw_header.sh_type
|
|
if raw_header.sh_flags & 0x800:
|
|
if sh_type in ("SHT_SYMTAB", "SHT_DYNSYM", "SHT_REL", "SHT_RELA", "SHT_RELR", "SHT_DYNAMIC"):
|
|
raise LayoutFailure("unsupported-target", f"ELF section {index} ({sh_type}) is SHF_COMPRESSED; logical metadata and its source coordinates are not decoded by this profile.")
|
|
if sh_type == "SHT_STRTAB":
|
|
compressed_strtabs.append(index)
|
|
if sh_type in ("SHT_SYMTAB", "SHT_DYNSYM"):
|
|
consumed_strings.add(raw_header.sh_link)
|
|
segment_count = headers.num_segments()
|
|
if segment_count and not file_range(headers.header.e_phoff, segment_count * headers.header.e_phentsize, length):
|
|
raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.")
|
|
if headers.header.e_shstrndx == 0xffff and section_count == 0:
|
|
raise LayoutFailure("format", "ELF extended section-name index requires a declared section-zero header.")
|
|
raw_name_index = headers.header.e_shstrndx
|
|
if 0xff00 <= raw_name_index < 0xffff:
|
|
raise LayoutFailure("format", f"ELF section-name index {raw_name_index} is reserved and cannot directly reference a section.")
|
|
section_name_index = headers.get_shstrndx()
|
|
if raw_name_index == 0xffff and section_name_index < 0xff00:
|
|
raise LayoutFailure("format", f"ELF SHN_XINDEX resolves to ordinary index {section_name_index}; the escape requires an index at least SHN_LORESERVE (0xff00).")
|
|
if section_name_index != 0:
|
|
if section_name_index >= section_count:
|
|
raise LayoutFailure("format", f"ELF section-name table index {section_name_index} lies outside the declared section count {section_count}.")
|
|
names_header = headers._get_section_header(section_name_index)
|
|
if names_header.sh_type != "SHT_STRTAB":
|
|
raise LayoutFailure("format", f"ELF section-name table {section_name_index} is not SHT_STRTAB.")
|
|
consumed_strings.add(section_name_index)
|
|
for index in compressed_strtabs:
|
|
if index in consumed_strings:
|
|
raise LayoutFailure("unsupported-target", f"ELF section {index} (SHT_STRTAB) is SHF_COMPRESSED; logical metadata and its source coordinates are not decoded by this profile.")
|
|
if section_name_index != 0 and not file_range(names_header.sh_offset, names_header.sh_size, length):
|
|
raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.")
|
|
except (ELFError, ValueError, OverflowError, AssertionError, IndexError) as error:
|
|
raise LayoutFailure("format", str(error)) from error
|
|
class LayoutELF(ELF):
|
|
def search(self, needle, writable=False, executable=False):
|
|
# This adapter exposes structural facts, GOT/PLT and mitigation
|
|
# indicators, not kernel config/version discovery. Upstream's
|
|
# constructor searches virtual memory for those unrelated
|
|
# heuristics, materializing NOBITS tails and interpreting
|
|
# ordinary IKCFG_ST data as a compressed kernel config.
|
|
return iter(())
|
|
|
|
def _populate_kernel_version(self):
|
|
# Kernel banner decoding is outside this report too.
|
|
return None
|
|
|
|
def _populate_plt(self):
|
|
# Upstream emulates each present PLT section (.plt, .plt.got,
|
|
# .plt.sec, .MIPS.stubs) in a new Unicorn instance with a
|
|
# 1 GiB virtual map. Unicorn hook closures keep each instance
|
|
# in a reference cycle, so its map stays reserved until a
|
|
# cyclic collection. Under the selected address-space limit,
|
|
# the third section of a CET x86-64 image then fails
|
|
# upstream's 1 GiB probe, and upstream keeps the truncated map
|
|
# with only a warning. Collect after each section so the limit
|
|
# is charged one emulator at a time. Upstream resolves this
|
|
# module global per section and offers no instance hook
|
|
# between sections, so this is the adapter's one scoped global
|
|
# substitution; finally restores it in this single-request
|
|
# bridge process.
|
|
emulate = upstream_elf.emulate_plt_instructions
|
|
|
|
def emulate_then_release(*args, **kwargs):
|
|
try:
|
|
return emulate(*args, **kwargs)
|
|
finally:
|
|
gc.collect()
|
|
|
|
upstream_elf.emulate_plt_instructions = emulate_then_release
|
|
try:
|
|
return super()._populate_plt()
|
|
finally:
|
|
upstream_elf.emulate_plt_instructions = emulate
|
|
|
|
def _get_section_name(self, header):
|
|
# SHN_UNDEF declares no names; upstream would otherwise read
|
|
# strings at the inactive section-zero offset.
|
|
return "" if section_name_index == 0 else super()._get_section_name(header)
|
|
|
|
# pyelftools 0.33 calls these documented filters internally;
|
|
# pwntools 4.15.0's cached overrides do not accept the argument.
|
|
# Forward the filter on this adapter instance, without modifying
|
|
# either upstream package or process-global methods (the scoped
|
|
# PLT-pass substitution above is the only global exception).
|
|
def iter_segments(self, type=None):
|
|
return (segment for segment in super().iter_segments()
|
|
if type is None or segment.header.p_type == type)
|
|
|
|
def iter_sections(self, type=None):
|
|
return (section for section in super().iter_sections()
|
|
if type is None or section.header.sh_type == type)
|
|
try:
|
|
image = LayoutELF(str(path), checksec=False)
|
|
if (image.arch, image.bits, image.endian) != (PROFILES[profile], bits, order):
|
|
raise LayoutFailure("unsupported-target", PROFILE_SCOPE)
|
|
image_type = image.header.e_type
|
|
if image_type not in ("ET_EXEC", "ET_DYN", "ET_REL"):
|
|
raise LayoutFailure("unsupported-target", "Selected ELF type is outside the EXEC/DYN/REL layout profile; recorded core analysis is separate.")
|
|
all_sections = list(image.iter_sections())
|
|
num_sections = len(all_sections)
|
|
section_is_null = [s.header.sh_type == "SHT_NULL" for s in all_sections]
|
|
is_et_rel = (image_type == "ET_REL")
|
|
shstrings = image.get_section(section_name_index) if all_sections and section_name_index != 0 else None
|
|
shstr_header = getattr(shstrings, "header", None) if shstrings is not None else None
|
|
shstr_valid = shstr_header is not None and shstr_header.sh_type == "SHT_STRTAB"
|
|
if shstr_valid and not file_range(shstr_header.sh_offset, shstr_header.sh_size, length):
|
|
raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.")
|
|
shstr_start = shstr_header.sh_offset if shstr_valid else 0
|
|
shstr_size = shstr_header.sh_size if shstr_valid else 0
|
|
shstr_cache = {} if shstr_valid else None
|
|
|
|
e_shoff = image.header.e_shoff
|
|
e_shentsize = image.header.e_shentsize
|
|
e_shentsize_hex = address(e_shentsize)
|
|
sym_sizeof = image.structs.Elf_Sym.sizeof()
|
|
strtab_caches = {}
|
|
validated_strtabs = set()
|
|
|
|
sections, segments, symbols, relocations, packed_relatives = [], [], [], [], []
|
|
needed, interpreters = [], []
|
|
for index, section in enumerate(all_sections):
|
|
h = section.header
|
|
sh_type = h.sh_type
|
|
backing = sh_type not in ("SHT_NOBITS", "SHT_NULL")
|
|
if backing and not file_range(h.sh_offset, h.sh_size, length):
|
|
raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.")
|
|
hdr_off = e_shoff + index * e_shentsize
|
|
if not file_range(hdr_off, e_shentsize, length):
|
|
raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.")
|
|
if shstrings is None:
|
|
sec_name = {"display": "", "bytes_base64": None, "location": None,
|
|
"unknown_reason": "ELF declares no section-name table (SHN_UNDEF index 0)."}
|
|
elif not shstr_valid:
|
|
sec_name = {"display": section.name, "bytes_base64": None, "location": None,
|
|
"unknown_reason": "Referenced string table could not be resolved."}
|
|
else:
|
|
sec_name = _name_in_validated_table(
|
|
section.name, shstr_start, shstr_size, h.sh_name, content, length, shstr_cache)
|
|
sections.append({
|
|
"index": index, "name": sec_name, "name_offset": address(h.sh_name), "type": sh_type,
|
|
"header_location": {"offset": address(hdr_off), "bytes": e_shentsize_hex},
|
|
"address": address(h.sh_addr), "offset": address(h.sh_offset),
|
|
"size": address(h.sh_size), "alignment": address(h.sh_addralign),
|
|
"flags": address(h.sh_flags), "link": h.sh_link, "info": h.sh_info,
|
|
"entry_size": address(h.sh_entsize), "file_backing": "file" if backing else "none",
|
|
})
|
|
if sh_type in ("SHT_SYMTAB", "SHT_DYNSYM"):
|
|
entsize = h.sh_entsize
|
|
if entsize < sym_sizeof:
|
|
raise LayoutFailure("format", f"ELF symbol entry is smaller than the decoded Elf{bits}_Sym structure.")
|
|
sh_link = h.sh_link
|
|
if sh_link >= num_sections or all_sections[sh_link].header.sh_type != "SHT_STRTAB":
|
|
raise LayoutFailure("format", f"ELF symbol table {index} links to invalid string table {sh_link}.")
|
|
strings_hdr = all_sections[sh_link].header
|
|
str_start = strings_hdr.sh_offset
|
|
str_size = strings_hdr.sh_size
|
|
str_cache = strtab_caches.get(sh_link)
|
|
if str_cache is None:
|
|
str_cache = {}
|
|
strtab_caches[sh_link] = str_cache
|
|
entsize_hex = address(entsize)
|
|
sym_base_off = h.sh_offset
|
|
strtab_checked = sh_link in validated_strtabs
|
|
for entry, symbol in enumerate(section.iter_symbols()):
|
|
if not strtab_checked:
|
|
if not file_range(str_start, str_size, length):
|
|
raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.")
|
|
validated_strtabs.add(sh_link)
|
|
strtab_checked = True
|
|
raw = symbol.entry
|
|
entry_off = sym_base_off + entry * entsize
|
|
if not file_range(entry_off, entsize, length):
|
|
raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.")
|
|
raw_info = raw.st_info
|
|
sym_type = raw_info.type
|
|
shndx = raw.st_shndx
|
|
if sym_type == "STT_FILE":
|
|
meaning = "no-address"
|
|
elif shndx == "SHN_UNDEF":
|
|
meaning = "undefined"
|
|
elif shndx == "SHN_COMMON":
|
|
meaning = "alignment"
|
|
elif shndx == "SHN_ABS":
|
|
meaning = "absolute-value"
|
|
elif not isinstance(shndx, int) or not 0 < shndx < num_sections or shndx >= 0xff00 or section_is_null[shndx]:
|
|
meaning = "unknown-section-index"
|
|
elif is_et_rel:
|
|
meaning = "section-offset"
|
|
elif sym_type == "STT_TLS":
|
|
meaning = "tls-offset"
|
|
else:
|
|
meaning = "linked-virtual-address"
|
|
st_name = raw.st_name
|
|
symbols.append({
|
|
"table_index": index, "entry_index": entry,
|
|
"name": _name_in_validated_table(symbol.name, str_start, str_size, st_name, content, length, str_cache),
|
|
"name_offset": address(st_name),
|
|
"location": {"offset": address(entry_off), "bytes": entsize_hex},
|
|
"value": address(raw.st_value), "value_meaning": meaning,
|
|
"size": address(raw.st_size), "binding": raw_info.bind, "type": sym_type,
|
|
"visibility": raw.st_other.visibility, "section_index": shndx,
|
|
})
|
|
elif sh_type in ("SHT_REL", "SHT_RELA"):
|
|
entsize = h.sh_entsize
|
|
if h.sh_size % entsize != 0:
|
|
raise LayoutFailure(
|
|
"format",
|
|
f"ELF relocation section {index} size is not a multiple of its {entsize}-byte entries.",
|
|
)
|
|
sh_info = h.sh_info
|
|
if is_et_rel and sh_info >= num_sections:
|
|
raise LayoutFailure("format", f"ELF relocation section {index} references missing target section {sh_info}.")
|
|
sh_link = h.sh_link
|
|
symbol_table = None
|
|
if sh_link != 0:
|
|
if sh_link >= num_sections or all_sections[sh_link].header.sh_type not in ("SHT_SYMTAB", "SHT_DYNSYM"):
|
|
raise LayoutFailure("format", f"ELF relocation section {index} links to invalid symbol table {sh_link}.")
|
|
symbol_table = all_sections[sh_link]
|
|
num_symbols = 0 if symbol_table is None else symbol_table.num_symbols()
|
|
entsize_hex = address(entsize)
|
|
rel_base_off = h.sh_offset
|
|
target_unknown_reason = None
|
|
if is_et_rel and (sh_info == 0 or section_is_null[sh_info]):
|
|
target_unknown_reason = "undefined-section-reference" if sh_info == 0 else "inactive-section-header"
|
|
for entry, relocation in enumerate(section.iter_relocations()):
|
|
raw = relocation.entry
|
|
sym_idx = raw.r_info_sym
|
|
if sym_idx != 0 and (symbol_table is None or sym_idx >= num_symbols):
|
|
raise LayoutFailure("format", f"ELF relocation section {index} entry {entry} references missing symbol {sym_idx} in table {sh_link}.")
|
|
entry_off = rel_base_off + entry * entsize
|
|
if not file_range(entry_off, entsize, length):
|
|
raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.")
|
|
offset_hex = address(raw.r_offset)
|
|
if not is_et_rel:
|
|
target = {"kind": "linked-virtual-address", "address": offset_hex}
|
|
elif target_unknown_reason is not None:
|
|
target = {"kind": "unknown-section", "reported_section_index": sh_info,
|
|
"offset": offset_hex, "unknown_reason": target_unknown_reason}
|
|
else:
|
|
target = {"kind": "section-offset", "section_index": sh_info, "offset": offset_hex}
|
|
relocations.append({
|
|
"section_index": index, "entry_index": entry, "reported_offset": offset_hex,
|
|
"target": target,
|
|
"location": {"offset": address(entry_off), "bytes": entsize_hex},
|
|
"type": raw.r_info_type, "symbol_table_index": sh_link, "symbol_index": sym_idx,
|
|
"symbol_reference_meaning": "zero-symbol-value" if sym_idx == 0 else "symbol-table-entry",
|
|
"addend": None if "r_addend" not in raw else str(raw.r_addend),
|
|
})
|
|
elif sh_type == "SHT_RELR":
|
|
packed_relatives.append({
|
|
"section_index": index,
|
|
"location": location(h.sh_offset, h.sh_size, length),
|
|
"encoded_bytes_base64": base64.b64encode(content[h.sh_offset:h.sh_offset + h.sh_size]).decode("ascii"),
|
|
"entries": [{"decoded_index": decoded, "reported_offset": address(relocation.entry.r_offset)} for decoded, relocation in enumerate(section.iter_relocations())],
|
|
"offset_meaning": "unknown" if is_et_rel else "linked-virtual-address",
|
|
"evidence_kind": "derived", "entry_source_locations": None, "addends": None,
|
|
})
|
|
|
|
all_segments = list(image.iter_segments())
|
|
load_headers = [seg.header for seg in all_segments if seg.header.p_type == "PT_LOAD"]
|
|
e_phoff = image.header.e_phoff
|
|
e_phentsize = image.header.e_phentsize
|
|
e_phentsize_hex = address(e_phentsize)
|
|
dyn_tag_size = image.structs.Elf_Dyn.sizeof()
|
|
for index, segment in enumerate(all_segments):
|
|
h = segment.header
|
|
p_type = h.p_type
|
|
backing = p_type != "PT_NULL" and h.p_filesz != 0
|
|
if backing and not file_range(h.p_offset, h.p_filesz, length):
|
|
raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.")
|
|
if p_type == "PT_LOAD" and h.p_memsz < h.p_filesz:
|
|
raise LayoutFailure("format", "ELF load segment memory size is smaller than its file size.")
|
|
phdr_off = e_phoff + index * e_phentsize
|
|
if not file_range(phdr_off, e_phentsize, length):
|
|
raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.")
|
|
segments.append({
|
|
"index": index, "type": p_type, "offset": address(h.p_offset),
|
|
"header_location": {"offset": address(phdr_off), "bytes": e_phentsize_hex},
|
|
"file_size": address(h.p_filesz), "memory_size": address(h.p_memsz),
|
|
"virtual_address": address(h.p_vaddr), "physical_address": address(h.p_paddr),
|
|
"alignment": address(h.p_align), "flags": address(h.p_flags),
|
|
"file_backing": "file" if backing else "none",
|
|
"permissions": None if p_type == "PT_NULL" else {"read": bool(h.p_flags & 4), "write": bool(h.p_flags & 2), "execute": bool(h.p_flags & 1)},
|
|
})
|
|
if p_type == "PT_DYNAMIC":
|
|
dt_strtab = []
|
|
dt_strsz = []
|
|
dt_needed = []
|
|
for tag_index in range(h.p_filesz // dyn_tag_size):
|
|
tag = segment._get_tag(tag_index)
|
|
d_tag = tag.d_tag
|
|
if d_tag == "DT_NULL":
|
|
break
|
|
if d_tag == "DT_STRTAB":
|
|
dt_strtab.append(tag.d_val)
|
|
elif d_tag == "DT_STRSZ":
|
|
dt_strsz.append(tag.d_val)
|
|
elif d_tag == "DT_NEEDED":
|
|
dt_needed.append(tag.d_val)
|
|
else:
|
|
raise LayoutFailure("format", f"ELF dynamic segment {index} has no complete DT_NULL terminator within its reported file range.")
|
|
if dt_needed:
|
|
if not dt_strtab or not dt_strsz:
|
|
raise LayoutFailure("format", "ELF dependency requires DT_STRTAB and DT_STRSZ.")
|
|
if len(dt_strtab) != 1 or len(dt_strsz) != 1:
|
|
raise LayoutFailure("unsupported-target", "ELF dependency string-table tags are ambiguous: " + repr({"DT_STRTAB": dt_strtab, "DT_STRSZ": dt_strsz}))
|
|
dyn_start, dyn_size = dt_strtab[0], dt_strsz[0]
|
|
dynstr_offset = None
|
|
dyn_cache = {}
|
|
for needed_offset in dt_needed:
|
|
if not 0 <= needed_offset < dyn_size:
|
|
raise LayoutFailure("format", f"ELF dependency name offset {needed_offset} lies outside declared DT_STRSZ {dyn_size}.")
|
|
if dynstr_offset is None:
|
|
offsets = {
|
|
lh.p_offset + dyn_start - lh.p_vaddr
|
|
for lh in load_headers
|
|
if dyn_start >= lh.p_vaddr and dyn_start + dyn_size <= lh.p_vaddr + lh.p_filesz
|
|
}
|
|
if len(offsets) != 1:
|
|
raise LayoutFailure("unsupported-target", "Dynamic string table lacks a unique file-backed mapping: " + repr({"DT_STRTAB": dt_strtab, "DT_STRSZ": dt_strsz, "candidate_file_offsets": sorted(offsets)}))
|
|
dynstr_offset = offsets.pop()
|
|
if not file_range(dynstr_offset, dyn_size, length):
|
|
raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.")
|
|
needed.append(_name_in_validated_table(None, dynstr_offset, dyn_size, needed_offset, content, length, dyn_cache))
|
|
elif p_type == "PT_INTERP":
|
|
raw = content[h.p_offset:h.p_offset + h.p_filesz]
|
|
end = raw.find(b"\0")
|
|
if end < 0:
|
|
raise LayoutFailure("format", "ELF interpreter lacks a reported terminator.")
|
|
interp_raw = raw[:end]
|
|
interpreters.append({"display": interp_raw.decode("utf-8", "replace"), "bytes_base64": base64.b64encode(interp_raw).decode("ascii"), "location": location(h.p_offset, end + 1, length), "unknown_reason": None})
|
|
return {
|
|
"format": "elf", "architecture": {"machine": image.header.e_machine, "bits": image.bits, "byte_order": image.endian},
|
|
"image_type": image_type,
|
|
"entry_point": {"reported_value": address(image.header.e_entry), "meaning": "not-applicable" if is_et_rel else "absent" if image.header.e_entry == 0 else "linked-virtual-address", "execution_status": "unknown"},
|
|
"runtime_load_base": None, "sections": sections, "segments": segments, "symbols": symbols, "relocations": relocations,
|
|
"packed_relative_relocations": packed_relatives, "relocation_inventory_completeness": "unknown",
|
|
"linkage": {"needed_libraries": needed, "interpreters": interpreters,
|
|
"got": [{"display_name": name, "address": address(value)} for name, value in image.got.items()],
|
|
"plt": [{"display_name": name, "address": address(value)} for name, value in image.plt.items()],
|
|
"convenience_maps_completeness": "unknown", "runtime_library_paths": None},
|
|
"mitigations": {"evidence_kind": "inferred", "position_independent": image.pie, "nx_indicator": image.nx, "executable_stack_indicator": image.execstack, "stack_canary_indicator": image.canary, "relro": image.relro},
|
|
"limitations": [
|
|
"PT_NULL payload fields are unused and retain their reported numbers without file-byte or permission claims. Zero-file-size segments provide no file bytes.",
|
|
"SHN_XINDEX symbol values remain unresolved in this upstream representation; an external index table does not establish a resolved index in this report.",
|
|
"Reported values preserve linked addresses, section offsets, TLS offsets, alignment and absolute values separately. Runtime load base and library paths are unknown.",
|
|
"Names are display strings plus raw bytes and file ranges where resolvable; section/table/entry indices preserve identity and duplicates. Name ranges include their terminating NUL; raw name bytes exclude it.",
|
|
"Ordinary relocation rows cover REL/RELA. RELR tables retain complete encoded bytes and upstream-decoded offsets as derived evidence; per-offset packed-word locations and implicit addends remain unknown. Relocation inventory completeness is unknown, including other encodings and missing section tables.",
|
|
"Relocation symbol index zero uses a zero symbol value without a table lookup. Positive indices reference validated original symbol-table entries; raw table and symbol indices remain reported.",
|
|
"Relocatable relocation targets with SHN_UNDEF or inactive SHT_NULL headers retain their reported section index/offset as unknown; they do not establish an associated target section.",
|
|
"GOT/PLT are derived upstream convenience maps; PLT inference can emulate selected instructions in Unicorn. They do not establish target runtime behavior; aliases may collapse and warnings may indicate incomplete coverage. Their completeness is unknown.",
|
|
"Mitigations are upstream static heuristics, not runtime protection. ET_DYN does not prove an executable; absent canary symbols do not prove every function unprotected.",
|
|
"Kernel configuration/version discovery is not performed; these memory-content scans do not supply the reported structural, linkage or mitigation facts.",
|
|
"This profile inspects ELF EXEC/DYN/REL layout only. It does not analyze recorded cores, resolve loaded libraries, launch the target as a host process or start a debugger.",
|
|
"Symbol/relocation inventories reflect original section tables. A sectionless image can still report dynamic dependency names; missing tables do not prove absence of dynamic symbols or relocations.",
|
|
*(["Absent section-name table: section-dependent RELRO/canary heuristics may be incomplete; protection coverage is unknown."] if all_sections and section_name_index == 0 else []),
|
|
*(["Sectionless images lack the .dynamic section and symbol tables used by upstream heuristics. RELRO/canary indicators may be incomplete; their values remain reported static candidates, with protection coverage unknown."] if not all_sections else []),
|
|
],
|
|
}
|
|
except LayoutFailure:
|
|
raise
|
|
except (ELFError, ValueError, OverflowError, AssertionError, IndexError) as error:
|
|
raise LayoutFailure("format", "Selected ELF failed unchanged upstream structural parsing: " + str(error)) from error
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
runtime_path = Path(__file__).with_name("decoder_runtime.py")
|
|
runtime = {"__file__": str(runtime_path), "__name__": "rea_decoder_runtime"}
|
|
exec(compile(runtime_path.read_bytes(), str(runtime_path), "exec"), runtime)
|
|
runtime["main"](sys.argv[-1], inspect_elf, LayoutFailure, PROFILE)
|