okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-int ce4197ce8 (AppImage ELF check: an ELF test instead of 'every ET_DYN is a static PIE', #4337) into f-0211-rc2b8179f3e

main
10.7 KiB228 linesraw
1#!/usr/bin/env python3
2"""Is every static-PIE program inside an AppImage still the program it was staged as? (#4337)
3
4Why: the bundled ripgrep (`harness/node_modules/@vscode/ripgrep-linux-x64/bin/rg`) is a statically linked PIE. Such a program relocates itself at
5start-up by reading its own `.dynamic` section through a fixed offset in its code. linuxdeploy, which Tauri runs over the AppDir, treats every ELF file
6as a library to fix up and rewrites its RPATH; for a static PIE that moves `.dynamic` to a new segment and leaves the old place filled with a filler
7byte, so the start-up code reads garbage. Reporters on #4337 see the same crash offset in every run (`rg + 0x3ffcf1`) and filler bytes (0x5A) where
8`.rela.dyn` and `.dynamic` were. A static PIE whose `.dynamic` is filled does not start: tools/test_appimage_elf.py shows that on a real one.
9apps/desktop/scripts/repack-appimage.sh puts the staged bytes back; this file is the check that says whether it did.
10
11    appimage_elf.py scan <folder>                      every static PIE under <folder> must have a sound .dynamic (exit 1 if not)
12    appimage_elf.py compare <staged-folder> <folder>   the same files, byte for byte, plus what differs in their ELF headers
13
14What is checked: only static PIE programs. A shared library (.so, Python's and Node's native modules, Pillow, numpy, sharp) is not one, however it is
15named: it has no entry point, or a DT_SONAME and no DF_1_PIE flag, and its RPATH/RUNPATH is normal. A static PIE is an ET_DYN with no interpreter, an entry
16point, and DF_1_PIE in DT_FLAGS_1; one whose .dynamic cannot be read at all (overwritten) is reported as damaged, since the overwrite takes the flags too.
17
18Standard library only; reads ELF64 little endian (x86-64 and arm64), anything else is ignored.
19"""
20import os
21import struct
22import sys
23
24ET_DYN = 3
25PT_LOAD, PT_DYNAMIC, PT_INTERP = 1, 2, 3
26DT_NULL, DT_NEEDED, DT_RELA, DT_RELASZ, DT_RELAENT, DT_SONAME, DT_RPATH, DT_RUNPATH = 0, 1, 7, 8, 9, 14, 15, 29
27DT_FLAGS_1, DF_1_PIE = 0x6FFFFFFB, 0x08000000
28FILLERS = (0x5A, 0x58)           # 'Z' (what the reports found) and 'X' (what patchelf documents)
29RUN = 128                        # that many equal filler bytes in a row is not code or data
30
31
32def _known_tag(tag):
33    """The dynamic tags the ELF specification and the GNU and processor ranges define: anything else is garbage."""
34    return 0 <= tag <= 0x22 or 0x6000000D <= tag <= 0x6FFFFFFF or 0x70000000 <= tag <= 0x7FFFFFFF
35
36
37def read_elf(data):
38    """The facts about an ELF64 little-endian file, or None when it is not one."""
39    if len(data) < 64 or data[:4] != b"\x7fELF" or data[4] != 2 or data[5] != 1:
40        return None
41    e_type = struct.unpack_from("<H", data, 16)[0]
42    e_entry = struct.unpack_from("<Q", data, 0x18)[0]
43    phoff = struct.unpack_from("<Q", data, 0x20)[0]
44    phentsize, phnum = struct.unpack_from("<HH", data, 0x36)
45    if phentsize < 56 or phoff + phentsize * phnum > len(data):
46        return {"type": e_type, "entry": e_entry, "phdrs": [], "broken": "the program header table is outside the file"}
47    phdrs = []
48    for i in range(phnum):
49        p_type, flags, off, vaddr, _paddr, filesz, memsz, align = struct.unpack_from("<IIQQQQQQ", data, phoff + i * phentsize)
50        phdrs.append({"type": p_type, "flags": flags, "off": off, "vaddr": vaddr, "filesz": filesz, "memsz": memsz, "align": align})
51    return {"type": e_type, "entry": e_entry, "phdrs": phdrs, "broken": None}
52
53
54def is_pie_candidate(info):
55    """An ET_DYN with no interpreter, a dynamic segment and an entry point: what a static PIE looks like from outside the dynamic section.
56    A shared library normally has no entry point (e_entry 0) and is not a candidate; the few that do (the C library itself, the dynamic loader)
57    have a readable dynamic section and are told apart by it (static_pie_kind). The test uses nothing the damage we look for can erase."""
58    return bool(info) and info["type"] == ET_DYN and not info["broken"] and info.get("entry", 0) != 0         and not any(p["type"] == PT_INTERP for p in info["phdrs"]) and any(p["type"] == PT_DYNAMIC for p in info["phdrs"])
59
60
61def static_pie_kind(data, info):
62    """'static-pie' for a sound static PIE (DT_FLAGS_1 has DF_1_PIE, no DT_SONAME), 'damaged' for a candidate whose dynamic section cannot be read
63    (a static PIE with an overwritten .dynamic loses its flags with it, so unreadable is treated as damaged), None for everything else:
64    shared libraries, which carry a DT_SONAME and no DF_1_PIE, and programs that are not static PIEs."""
65    if not is_pie_candidate(info):
66        return None
67    entries, why = dynamic_entries(data, info)
68    if why or any(not _known_tag(t) for t, _ in entries):
69        return "damaged"
70    tags = {t: v for t, v in entries}
71    if DT_SONAME in tags:
72        return None
73    return "static-pie" if tags.get(DT_FLAGS_1, 0) & DF_1_PIE else None
74
75
76def is_static_pie(info):
77    """Kept for callers: a candidate. check_static_pie decides with static_pie_kind."""
78    return is_pie_candidate(info)
79
80
81def _mapped(info, vaddr, size):
82    """The file offset of [vaddr, vaddr+size) when one PT_LOAD maps all of it from the file, else None."""
83    for p in info["phdrs"]:
84        if p["type"] == PT_LOAD and p["vaddr"] <= vaddr and vaddr + size <= p["vaddr"] + p["filesz"]:
85            return p["off"] + (vaddr - p["vaddr"])
86    return None
87
88
89def dynamic_entries(data, info):
90    """(tag, value) pairs of the PT_DYNAMIC segment up to DT_NULL, and the problem if it does not end properly."""
91    seg = next(p for p in info["phdrs"] if p["type"] == PT_DYNAMIC)
92    if seg["off"] + seg["filesz"] > len(data):
93        return [], "the dynamic segment is outside the file"
94    out = []
95    for at in range(seg["off"], seg["off"] + seg["filesz"] - 15, 16):
96        tag, val = struct.unpack_from("<qQ", data, at)
97        if tag == DT_NULL:
98            return out, None
99        out.append((tag, val))
100    return out, "the dynamic segment does not end with DT_NULL"
101
102
103def _longest_filler(data, start, end):
104    best = run = 0
105    prev = None
106    for b in data[start:end]:
107        run = run + 1 if b == prev and b in FILLERS else (1 if b in FILLERS else 0)
108        prev = b
109        best = max(best, run)
110    return best
111
112
113def check_static_pie(data):
114    """The problems of one file (a list of sentences); empty for a sound static PIE and for anything that is not one."""
115    info = read_elf(data)
116    if static_pie_kind(data, info) is None:
117        return []
118    problems = []
119    seg = next(p for p in info["phdrs"] if p["type"] == PT_DYNAMIC)
120    if _mapped(info, seg["vaddr"], max(seg["filesz"], 1)) is None:
121        problems.append("the dynamic segment is not inside any loaded segment")
122    entries, why = dynamic_entries(data, info)
123    if why:
124        problems.append(why)
125    bad = [t for t, _ in entries if not _known_tag(t)]
126    if bad:
127        problems.append(f"{len(bad)} dynamic entries have tags that do not exist (first {bad[0]:#x}): the section is overwritten")
128    if any(t in (DT_RPATH, DT_RUNPATH) for t, _ in entries):
129        problems.append("a static PIE has an RPATH or RUNPATH: something rewrote it after it was linked")
130    values = dict(entries)
131    if DT_RELA in values:
132        size = values.get(DT_RELASZ, 0)
133        at = _mapped(info, values[DT_RELA], max(size, 1))
134        if size == 0 or at is None:
135            problems.append("the relocation table named by DT_RELA is empty or outside the loaded segments")
136        elif _longest_filler(data, at, at + size) >= min(RUN, size):
137            problems.append("the relocation table is filled with one byte")
138    for p in info["phdrs"]:
139        if p["type"] == PT_LOAD and _longest_filler(data, p["off"], p["off"] + p["filesz"]) >= RUN:
140            problems.append(f"{RUN} or more filler bytes (0x5A or 0x58) in a row inside a loaded segment")
141            break
142    return problems
143
144
145def elf_differences(staged, packaged):
146    """What differs between two builds of one program in the parts that matter for start-up: for the report."""
147    a, b = read_elf(staged), read_elf(packaged)
148    if not a or not b:
149        return [] if staged == packaged else ["one of the two is not an ELF64 file"]
150    out = []
151    ta, tb = [p["type"] for p in a["phdrs"]], [p["type"] for p in b["phdrs"]]
152    if ta != tb:
153        out.append(f"program headers {len(ta)} -> {len(tb)} ({ta.count(PT_LOAD)} -> {tb.count(PT_LOAD)} loaded segments)")
154    if is_pie_candidate(a) and is_pie_candidate(b):
155        da, _ = dynamic_entries(staged, a)
156        db, _ = dynamic_entries(packaged, b)
157        if da != db:
158            out.append(f"dynamic section: {len(da)} -> {len(db)} entries" + ("; an RPATH/RUNPATH was added" if any(t in (DT_RPATH, DT_RUNPATH) for t, _ in db) and not any(t in (DT_RPATH, DT_RUNPATH) for t, _ in da) else ""))
159    return out
160
161
162def _files(folder):
163    for base, dirs, names in os.walk(folder):
164        dirs.sort()
165        for name in sorted(names):
166            path = os.path.join(base, name)
167            if os.path.islink(path) or not os.path.isfile(path):
168                continue
169            yield path
170
171
172def scan(folder):
173    """{relative path: problems} for every static PIE under `folder` that has any."""
174    found = {}
175    for path in _files(folder):
176        try:
177            with open(path, "rb") as f:
178                head = f.read(4)
179                if head != b"\x7fELF":
180                    continue
181                data = head + f.read()
182        except OSError:
183            continue
184        problems = check_static_pie(data)
185        if problems:
186            found[os.path.relpath(path, folder)] = problems
187    return found
188
189
190def compare(staged_folder, folder):
191    """{relative path: sentences} for every staged ELF file that is missing or differs in `folder`."""
192    found = {}
193    for path in _files(staged_folder):
194        rel = os.path.relpath(path, staged_folder)
195        with open(path, "rb") as f:
196            want = f.read()
197        if want[:4] != b"\x7fELF":
198            continue
199        other = os.path.join(folder, rel)
200        if not os.path.isfile(other):
201            found[rel] = ["missing"]
202            continue
203        with open(other, "rb") as f:
204            have = f.read()
205        if have != want:
206            found[rel] = ["bytes differ"] + elf_differences(want, have)
207    return found
208
209
210def main(argv):
211    if len(argv) >= 3 and argv[1] == "scan":
212        bad = scan(argv[2])
213        for rel, problems in bad.items():
214            print(f"BROKEN {rel}: " + "; ".join(problems))
215        print(f"{len(bad)} static PIE file(s) with a damaged dynamic section")
216        return 1 if bad else 0
217    if len(argv) >= 4 and argv[1] == "compare":
218        bad = compare(argv[2], argv[3])
219        for rel, why in bad.items():
220            print(f"DIFFERS {rel}: " + "; ".join(why))
221        print(f"{len(bad)} ELF file(s) differ from what was staged")
222        return 1 if bad else 0
223    print(__doc__)
224    return 2
225
226
227if __name__ == "__main__":
228    sys.exit(main(sys.argv))