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
15.2 KiB263 linesraw
1"""Tests for apps/desktop/scripts/appimage_elf.py (#4337: the bundled ripgrep, a static PIE, crashed in the Linux AppImage).
2
3A static PIE relocates itself at start-up by reading its own `.dynamic` section. linuxdeploy's RPATH rewrite moves that section and fills the old
4place; the program then does not start. The checks here: ELF files built in memory (run everywhere), and, on Linux with gcc and -static-pie, a real
5static PIE that runs, the same file with its `.dynamic` overwritten the way the reporters found it (it must crash at start, and the scan must say so).
6No downloads; nothing of the real install is touched.
7
8    python -m unittest tools.test_appimage_elf
9"""
10from __future__ import annotations
11
12import os
13import shutil
14import struct
15import subprocess
16import sys
17import tempfile
18import unittest
19from pathlib import Path
20
21ROOT = Path(__file__).resolve().parents[1]
22sys.path.insert(0, str(ROOT / "apps" / "desktop" / "scripts"))
23import appimage_elf as E  # noqa: E402
24
25
26def make_static_pie(*, extra_tags=(), rela=True, garbage=False, filler=False, interp=False, loads=2, pie=True, entry=0x1000) -> bytes:
27    """A small ELF64 ET_DYN: PT_LOADs, a PT_DYNAMIC inside the last one, optionally a PT_INTERP. Not runnable, only well formed."""
28    page = 0x1000
29    dyn = [(E.DT_RELA, 0x1100), (E.DT_RELASZ, 48), (E.DT_RELAENT, 24)] if rela else []
30    dyn += ([(E.DT_FLAGS_1, E.DF_1_PIE)] if pie else []) + list(extra_tags) + [(E.DT_NULL, 0)]
31    dyn_bytes = b"".join(struct.pack("<qQ", t, v) for t, v in dyn)
32    if garbage:
33        dyn_bytes = b"Z" * len(dyn_bytes)
34    nph = loads + 1 + (1 if interp else 0)
35    body = bytearray(page * (loads + 1))
36    phdr = []
37    for i in range(loads):
38        phdr.append((E.PT_LOAD, 5 if i == 0 else 6, i * page, i * page, page, page, page))
39    dyn_off = page * loads + 0x40
40    # the last load covers the dynamic section
41    phdr[-1] = (E.PT_LOAD, 6, (loads - 1) * page, (loads - 1) * page, 2 * page, 2 * page, page)
42    phdr.append((E.PT_DYNAMIC, 6, dyn_off, dyn_off, len(dyn_bytes), len(dyn_bytes), 8))
43    if interp:
44        phdr.append((E.PT_INTERP, 4, 0x200, 0x200, 16, 16, 1))
45    body[dyn_off:dyn_off + len(dyn_bytes)] = dyn_bytes
46    if rela:
47        body[0x1100:0x1100 + 48] = (b"Z" * 48) if filler else struct.pack("<QQqQQq", 0x2000, 8, 0x2100, 0x2008, 8, 0x2200)
48    if filler:
49        body[0x300:0x300 + 400] = b"X" * 400
50    head = bytearray(64)
51    head[:4] = b"\x7fELF"
52    head[4], head[5], head[6] = 2, 1, 1
53    struct.pack_into("<HHIQQQIHHHHHH", head, 16, E.ET_DYN, 62, 1, entry, 64, 0, 0, 64, 56, len(phdr), 64, 0, 0)
54    out = bytearray(head)
55    for p_type, flags, off, vaddr, filesz, memsz, align in phdr:
56        out += struct.pack("<IIQQQQQQ", p_type, flags, off, vaddr, vaddr, filesz, memsz, align)
57    data = bytes(out) + bytes(body[len(out):])
58    return data
59
60
61class Synthetic(unittest.TestCase):
62    def test_a_sound_static_pie_has_no_problems(self):
63        self.assertEqual(E.check_static_pie(make_static_pie()), [])
64        self.assertEqual(E.check_static_pie(make_static_pie(loads=3)), [])
65
66    def test_a_filled_dynamic_section_is_reported(self):
67        problems = E.check_static_pie(make_static_pie(garbage=True))
68        self.assertTrue(any("tags that do not exist" in p for p in problems), problems)
69
70    def test_an_added_rpath_on_a_static_pie_is_reported(self):
71        for tag in (E.DT_RPATH, E.DT_RUNPATH):
72            problems = E.check_static_pie(make_static_pie(extra_tags=[(tag, 1)]))
73            self.assertTrue(any("RPATH or RUNPATH" in p for p in problems), problems)
74
75    def test_a_filled_relocation_table_and_filler_runs_are_reported(self):
76        problems = E.check_static_pie(make_static_pie(filler=True))
77        self.assertTrue(any("relocation table is filled" in p for p in problems), problems)
78        self.assertTrue(any("filler bytes" in p for p in problems), problems)
79
80    def test_a_dynamic_segment_outside_the_loaded_segments_is_reported(self):
81        data = bytearray(make_static_pie())
82        # point PT_DYNAMIC's address far outside every PT_LOAD
83        info = E.read_elf(bytes(data))
84        phoff = 64
85        for i, p in enumerate(info["phdrs"]):
86            if p["type"] == E.PT_DYNAMIC:
87                struct.pack_into("<Q", data, phoff + i * 56 + 16, 0x900000)
88        problems = E.check_static_pie(bytes(data))
89        self.assertTrue(any("not inside any loaded segment" in p for p in problems), problems)
90
91    def test_programs_that_are_not_static_pies_are_left_alone(self):
92        self.assertEqual(E.check_static_pie(make_static_pie(garbage=True, interp=True)), [], "a dynamic program with an interpreter")
93        self.assertEqual(E.check_static_pie(b"#!/bin/sh\necho hi\n"), [])
94        self.assertEqual(E.check_static_pie(b"\x7fELF" + b"\x01" * 60), [], "32-bit")
95        self.assertEqual(E.check_static_pie(b""), [])
96        self.assertEqual(E.check_static_pie(b"\x7fELF\x02\x01" + b"\x00" * 100), [], "no program headers: nothing to check")
97
98    def test_a_shared_library_with_no_interpreter_passes_however_it_is_named(self):
99        """Pillow, numpy and sharp ship .so files with an RUNPATH of $ORIGIN, no PT_INTERP and (usually) no entry point: they were flagged as static PIEs."""
100        sonames = [(E.DT_SONAME, 1), (E.DT_RUNPATH, 2)]
101        for lib in (make_static_pie(entry=0, pie=False, extra_tags=sonames),            # the common case: no entry point
102                    make_static_pie(entry=0, pie=False, extra_tags=[(E.DT_RUNPATH, 2)]),  # no SONAME either (a Node .node module)
103                    make_static_pie(entry=0x1000, pie=False, extra_tags=sonames),         # an entry point (libc, ld.so style) but a SONAME and no PIE flag
104                    make_static_pie(entry=0x1000, pie=True, extra_tags=sonames),          # even a stray PIE flag: a SONAME makes it a library
105                    make_static_pie(entry=0, pie=False, garbage=True)):                   # a library with a damaged dynamic section is not this checker's business
106            self.assertEqual(E.check_static_pie(lib), [])
107        self.assertEqual(E.static_pie_kind(make_static_pie(entry=0, pie=False, extra_tags=sonames), E.read_elf(make_static_pie(entry=0, pie=False, extra_tags=sonames))), None)
108
109    def test_a_static_pie_is_told_from_a_library_and_a_damaged_one_is_found(self):
110        good = make_static_pie()
111        self.assertEqual(E.static_pie_kind(good, E.read_elf(good)), "static-pie")
112        self.assertEqual(E.check_static_pie(good), [])
113        bad = make_static_pie(garbage=True)
114        self.assertEqual(E.static_pie_kind(bad, E.read_elf(bad)), "damaged")
115        self.assertTrue(E.check_static_pie(bad))
116        # linuxdeploy's own edit: the section survives (moved) with a RUNPATH added; it is still a static PIE and the RUNPATH gives it away
117        rp = make_static_pie(extra_tags=[(E.DT_RUNPATH, 1)])
118        self.assertEqual(E.static_pie_kind(rp, E.read_elf(rp)), "static-pie")
119        self.assertTrue(any("RPATH or RUNPATH" in p for p in E.check_static_pie(rp)))
120        # no entry point, no PIE flag, not a static PIE: left alone
121        self.assertEqual(E.check_static_pie(make_static_pie(pie=False)), [], "a sound dynamic section with no PIE flag and no SONAME is not a static PIE")
122
123    def test_a_folder_of_libraries_and_one_static_pie(self):
124        with tempfile.TemporaryDirectory() as tmp:
125            for i in range(5):
126                Path(tmp, f"lib{i}.so.1").write_bytes(make_static_pie(entry=0, pie=False, extra_tags=[(E.DT_SONAME, 1), (E.DT_RUNPATH, 2)]))
127            Path(tmp, "something.node").write_bytes(make_static_pie(entry=0, pie=False, extra_tags=[(E.DT_RUNPATH, 2)]))
128            Path(tmp, "rg").write_bytes(make_static_pie())
129            self.assertEqual(E.scan(tmp), {}, "no name rules: only the static PIE is looked at, and it is sound")
130            Path(tmp, "rg").write_bytes(make_static_pie(garbage=True))
131            self.assertEqual(list(E.scan(tmp)), ["rg"])
132
133    def test_a_truncated_file_is_a_report_not_a_crash(self):
134        data = make_static_pie()
135        for cut in (70, 200, 4100, len(data) - 10):
136            E.check_static_pie(data[:cut])
137
138    def test_folder_scan_and_compare(self):
139        with tempfile.TemporaryDirectory() as tmp:
140            staged, packed = Path(tmp, "staged"), Path(tmp, "packed")
141            for base in (staged, packed):
142                (base / "node_modules/@vscode/ripgrep-linux-x64/bin").mkdir(parents=True)
143                (base / "lib").mkdir()
144            good, bad = make_static_pie(), make_static_pie(garbage=True, extra_tags=[(E.DT_RUNPATH, 1)])
145            rg = "node_modules/@vscode/ripgrep-linux-x64/bin/rg"
146            (staged / rg).write_bytes(good)
147            (packed / rg).write_bytes(bad)
148            (staged / "lib/libx.so").write_bytes(good)
149            (packed / "lib/libx.so").write_bytes(good)
150            (staged / "readme.txt").write_text("text")
151            found = E.scan(str(packed))
152            self.assertEqual(list(found), [rg.replace("/", os.sep)])
153            diffs = E.compare(str(staged), str(packed))
154            self.assertEqual(list(diffs), [rg.replace("/", os.sep)])
155            self.assertIn("bytes differ", diffs[rg.replace("/", os.sep)])
156            # the repaired copy passes both
157            (packed / rg).write_bytes(good)
158            self.assertEqual(E.scan(str(packed)), {})
159            self.assertEqual(E.compare(str(staged), str(packed)), {})
160            # a missing file is reported
161            (packed / "lib/libx.so").unlink()
162            self.assertEqual(E.compare(str(staged), str(packed)), {os.path.join("lib", "libx.so"): ["missing"]})
163
164    def test_the_command_line_exit_codes(self):
165        with tempfile.TemporaryDirectory() as tmp:
166            Path(tmp, "rg").write_bytes(make_static_pie())
167            self.assertEqual(E.main(["x", "scan", tmp]), 0)
168            Path(tmp, "rg").write_bytes(make_static_pie(garbage=True))
169            self.assertEqual(E.main(["x", "scan", tmp]), 1)
170            self.assertEqual(E.main(["x"]), 2)
171
172
173@unittest.skipUnless(sys.platform.startswith("linux") and shutil.which("gcc"), "needs Linux and gcc")
174class RealStaticPie(unittest.TestCase):
175    """A real static PIE from gcc: it runs; with its .dynamic filled the way the reports found it, it does not start, and the scan says why."""
176
177    @classmethod
178    def setUpClass(cls):
179        cls.tmp = tempfile.mkdtemp(prefix="strata-elf-")
180        src = Path(cls.tmp, "t.c")
181        src.write_text('#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n'
182                       'static const char *n[]={"alpha","beta","gamma"};\n'
183                       'int main(int c,char**v){char b[256];memset(b,0,sizeof b);for(int i=0;i<3;i++)strcat(b,n[i]);'
184                       'printf("ok %s %d\\n",b,c);void*p=malloc(100000);memcpy(p,b,200);free(p);return 0;}\n')
185        cls.good = Path(cls.tmp, "good")
186        built = subprocess.run(["gcc", "-O2", "-static-pie", str(src), "-o", str(cls.good)], capture_output=True)
187        cls.ok = built.returncode == 0
188
189    @classmethod
190    def tearDownClass(cls):
191        shutil.rmtree(cls.tmp, ignore_errors=True)
192
193    def setUp(self):
194        if not self.ok:
195            self.skipTest("this gcc cannot build a static PIE")
196
197    def test_the_real_program_runs_and_passes(self):
198        out = subprocess.run([str(self.good)], capture_output=True, text=True)
199        self.assertEqual(out.returncode, 0)
200        self.assertIn("ok alphabetagamma", out.stdout)
201        self.assertEqual(E.check_static_pie(self.good.read_bytes()), [])
202
203    def test_a_real_shared_library_with_a_runpath_passes(self):
204        src = Path(self.tmp, "lib.c")
205        src.write_text("int answer(void) { return 42; }" + chr(10))
206        lib = Path(self.tmp, "libanswer.so.1")
207        built = subprocess.run(["gcc", "-shared", "-fPIC", "-O2", "-Wl,-soname,libanswer.so.1", "-Wl,-rpath,$ORIGIN", str(src), "-o", str(lib)], capture_output=True)
208        if built.returncode != 0:
209            self.skipTest("this gcc cannot build a shared library")
210        data = lib.read_bytes()
211        self.assertEqual(E.check_static_pie(data), [], "a real library with RUNPATH $ORIGIN and no interpreter is not a static PIE")
212        self.assertEqual(E.static_pie_kind(data, E.read_elf(data)), None)
213        # and the real static PIE of this class is still told apart and still found when damaged
214        good = self.good.read_bytes()
215        self.assertEqual(E.static_pie_kind(good, E.read_elf(good)), "static-pie")
216
217    def test_a_filled_dynamic_section_does_not_start_and_is_found(self):
218        data = bytearray(self.good.read_bytes())
219        info = E.read_elf(bytes(data))
220        seg = next(p for p in info["phdrs"] if p["type"] == E.PT_DYNAMIC)
221        data[seg["off"]:seg["off"] + seg["filesz"]] = b"Z" * seg["filesz"]
222        bad = Path(self.tmp, "bad")
223        bad.write_bytes(bytes(data))
224        bad.chmod(0o755)
225        run = subprocess.run([str(bad)], capture_output=True)
226        self.assertNotEqual(run.returncode, 0, "a static PIE whose .dynamic is overwritten must not run")
227        self.assertTrue(E.check_static_pie(bytes(data)))
228        self.assertEqual(E.main(["x", "scan", self.tmp]), 1)
229
230    def test_the_repack_script_check_passes_a_sound_bundled_rg_and_stops_a_damaged_one(self):
231        """The shell function of repack-appimage.sh --check, run on a fixture AppDir whose `rg` is a real static PIE."""
232        if sys.platform != "linux" or os.uname().machine != "x86_64" or not shutil.which("bash") or not shutil.which("python3"):
233            self.skipTest("the check runs the bundled rg: x86-64 Linux with bash and python3")
234        script = ROOT / "apps" / "desktop" / "scripts" / "repack-appimage.sh"
235        src = Path(self.tmp, "rg.c")
236        src.write_text(chr(10).join(["#include <stdio.h>", "#include <string.h>",
237                                     'int main(int c, char **v) { for (int i = 1; i < c; i++) if (!strcmp(v[i], "--version")) { puts("ripgrep 0"); return 0; }',
238                                     '  FILE *f = fopen(v[c - 1], "r"); if (!f) return 2; char b[256]; int n = 0; while (fgets(b, 256, f)) if (strstr(b, "needle")) n++;',
239                                     '  printf("%d", n); return 0; }', ""]))
240        lib = Path(self.tmp, "AppDir-lib")
241        rg = lib / "harness/node_modules/@vscode/ripgrep-linux-x64/bin/rg"
242        rg.parent.mkdir(parents=True)
243        built = subprocess.run(["gcc", "-O2", "-static-pie", str(src), "-o", str(rg)], capture_output=True)
244        if built.returncode != 0:
245            self.skipTest("this gcc cannot build a static PIE")
246        snippet = 'source <(sed -n "/^elf_and_rg_check()/,/^}/p" "$SCRIPT"); elf_and_rg_check'
247        env = dict(os.environ, SCRIPT=str(script), LIB=str(lib), HERE=str(script.parent))
248        ok = subprocess.run(["bash", "-c", snippet], env=env, capture_output=True, text=True)
249        self.assertEqual(ok.returncode, 0, ok.stdout + ok.stderr)
250        self.assertIn("bundled rg runs: ok", ok.stdout)
251        data = bytearray(rg.read_bytes())
252        info = E.read_elf(bytes(data))
253        seg = next(p for p in info["phdrs"] if p["type"] == E.PT_DYNAMIC)
254        data[seg["off"]:seg["off"] + seg["filesz"]] = b"Z" * seg["filesz"]
255        rg.write_bytes(bytes(data))
256        bad = subprocess.run(["bash", "-c", snippet], env=env, capture_output=True, text=True)
257        self.assertNotEqual(bad.returncode, 0)
258        self.assertIn("BROKEN", bad.stdout)
259        self.assertIn("does not run", bad.stderr)
260
261
262if __name__ == "__main__":
263    unittest.main()