okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2b8179f3e
main
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 8python -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.""" 28page = 0x1000 29dyn = [(E .DT_RELA ,0x1100 ), (E .DT_RELASZ ,48 ), (E .DT_RELAENT ,24 )]if rela else [] 30dyn += ([(E .DT_FLAGS_1 ,E .DF_1_PIE )]if pie else [])+ list (extra_tags )+ [(E .DT_NULL ,0 )] 31dyn_bytes = b"" .join (struct .pack ("<qQ" ,t ,v )for t ,v in dyn ) 32if garbage : 33dyn_bytes = b"Z" * len (dyn_bytes ) 34nph = loads + 1 + (1 if interp else 0 ) 35body = bytearray (page * (loads + 1 )) 36phdr = [] 37for i in range (loads ): 38phdr .append ((E .PT_LOAD ,5 if i == 0 else 6 ,i * page ,i * page ,page ,page ,page )) 39dyn_off = page * loads + 0x40 40# the last load covers the dynamic section 41phdr [- 1 ]= (E .PT_LOAD ,6 , (loads - 1 )* page , (loads - 1 )* page ,2 * page ,2 * page ,page ) 42phdr .append ((E .PT_DYNAMIC ,6 ,dyn_off ,dyn_off ,len (dyn_bytes ),len (dyn_bytes ),8 )) 43if interp : 44phdr .append ((E .PT_INTERP ,4 ,0x200 ,0x200 ,16 ,16 ,1 )) 45body [dyn_off :dyn_off + len (dyn_bytes )]= dyn_bytes 46if rela : 47body [0x1100 :0x1100 + 48 ]= (b"Z" * 48 )if filler else struct .pack ("<QQqQQq" ,0x2000 ,8 ,0x2100 ,0x2008 ,8 ,0x2200 ) 48if filler : 49body [0x300 :0x300 + 400 ]= b"X" * 400 50head = bytearray (64 ) 51head [:4 ]= b"\x7fELF" 52head [4 ],head [5 ],head [6 ]= 2 ,1 ,1 53struct .pack_into ("<HHIQQQIHHHHHH" ,head ,16 ,E .ET_DYN ,62 ,1 ,entry ,64 ,0 ,0 ,64 ,56 ,len (phdr ),64 ,0 ,0 ) 54out = bytearray (head ) 55for p_type ,flags ,off ,vaddr ,filesz ,memsz ,align in phdr : 56out += struct .pack ("<IIQQQQQQ" ,p_type ,flags ,off ,vaddr ,vaddr ,filesz ,memsz ,align ) 57data = bytes (out )+ bytes (body [len (out ):]) 58return data 59 60 61class Synthetic (unittest .TestCase ): 62def test_a_sound_static_pie_has_no_problems (self ): 63self .assertEqual (E .check_static_pie (make_static_pie ()), []) 64self .assertEqual (E .check_static_pie (make_static_pie (loads = 3 )), []) 65 66def test_a_filled_dynamic_section_is_reported (self ): 67problems = E .check_static_pie (make_static_pie (garbage = True )) 68self .assertTrue (any ("tags that do not exist" in p for p in problems ),problems ) 69 70def test_an_added_rpath_on_a_static_pie_is_reported (self ): 71for tag in (E .DT_RPATH ,E .DT_RUNPATH ): 72problems = E .check_static_pie (make_static_pie (extra_tags = [(tag ,1 )])) 73self .assertTrue (any ("RPATH or RUNPATH" in p for p in problems ),problems ) 74 75def test_a_filled_relocation_table_and_filler_runs_are_reported (self ): 76problems = E .check_static_pie (make_static_pie (filler = True )) 77self .assertTrue (any ("relocation table is filled" in p for p in problems ),problems ) 78self .assertTrue (any ("filler bytes" in p for p in problems ),problems ) 79 80def test_a_dynamic_segment_outside_the_loaded_segments_is_reported (self ): 81data = bytearray (make_static_pie ()) 82# point PT_DYNAMIC's address far outside every PT_LOAD 83info = E .read_elf (bytes (data )) 84phoff = 64 85for i ,p in enumerate (info ["phdrs" ]): 86if p ["type" ]== E .PT_DYNAMIC : 87struct .pack_into ("<Q" ,data ,phoff + i * 56 + 16 ,0x900000 ) 88problems = E .check_static_pie (bytes (data )) 89self .assertTrue (any ("not inside any loaded segment" in p for p in problems ),problems ) 90 91def test_programs_that_are_not_static_pies_are_left_alone (self ): 92self .assertEqual (E .check_static_pie (make_static_pie (garbage = True ,interp = True )), [],"a dynamic program with an interpreter" ) 93self .assertEqual (E .check_static_pie (b"#!/bin/sh\necho hi\n" ), []) 94self .assertEqual (E .check_static_pie (b"\x7fELF" + b"\x01" * 60 ), [],"32-bit" ) 95self .assertEqual (E .check_static_pie (b"" ), []) 96self .assertEqual (E .check_static_pie (b"\x7fELF\x02\x01" + b"\x00" * 100 ), [],"no program headers: nothing to check" ) 97 98def 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.""" 100sonames = [(E .DT_SONAME ,1 ), (E .DT_RUNPATH ,2 )] 101for lib in (make_static_pie (entry = 0 ,pie = False ,extra_tags = sonames ),# the common case: no entry point 102make_static_pie (entry = 0 ,pie = False ,extra_tags = [(E .DT_RUNPATH ,2 )]),# no SONAME either (a Node .node module) 103make_static_pie (entry = 0x1000 ,pie = False ,extra_tags = sonames ),# an entry point (libc, ld.so style) but a SONAME and no PIE flag 104make_static_pie (entry = 0x1000 ,pie = True ,extra_tags = sonames ),# even a stray PIE flag: a SONAME makes it a library 105make_static_pie (entry = 0 ,pie = False ,garbage = True )):# a library with a damaged dynamic section is not this checker's business 106self .assertEqual (E .check_static_pie (lib ), []) 107self .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 109def test_a_static_pie_is_told_from_a_library_and_a_damaged_one_is_found (self ): 110good = make_static_pie () 111self .assertEqual (E .static_pie_kind (good ,E .read_elf (good )),"static-pie" ) 112self .assertEqual (E .check_static_pie (good ), []) 113bad = make_static_pie (garbage = True ) 114self .assertEqual (E .static_pie_kind (bad ,E .read_elf (bad )),"damaged" ) 115self .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 117rp = make_static_pie (extra_tags = [(E .DT_RUNPATH ,1 )]) 118self .assertEqual (E .static_pie_kind (rp ,E .read_elf (rp )),"static-pie" ) 119self .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 121self .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 123def test_a_folder_of_libraries_and_one_static_pie (self ): 124with tempfile .TemporaryDirectory ()as tmp : 125for i in range (5 ): 126Path (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 )])) 127Path (tmp ,"something.node" ).write_bytes (make_static_pie (entry = 0 ,pie = False ,extra_tags = [(E .DT_RUNPATH ,2 )])) 128Path (tmp ,"rg" ).write_bytes (make_static_pie ()) 129self .assertEqual (E .scan (tmp ), {},"no name rules: only the static PIE is looked at, and it is sound" ) 130Path (tmp ,"rg" ).write_bytes (make_static_pie (garbage = True )) 131self .assertEqual (list (E .scan (tmp )), ["rg" ]) 132 133def test_a_truncated_file_is_a_report_not_a_crash (self ): 134data = make_static_pie () 135for cut in (70 ,200 ,4100 ,len (data )- 10 ): 136E .check_static_pie (data [:cut ]) 137 138def test_folder_scan_and_compare (self ): 139with tempfile .TemporaryDirectory ()as tmp : 140staged ,packed = Path (tmp ,"staged" ),Path (tmp ,"packed" ) 141for base in (staged ,packed ): 142 (base / "node_modules/@vscode/ripgrep-linux-x64/bin" ).mkdir (parents = True ) 143 (base / "lib" ).mkdir () 144good ,bad = make_static_pie (),make_static_pie (garbage = True ,extra_tags = [(E .DT_RUNPATH ,1 )]) 145rg = "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" ) 151found = E .scan (str (packed )) 152self .assertEqual (list (found ), [rg .replace ("/" ,os .sep )]) 153diffs = E .compare (str (staged ),str (packed )) 154self .assertEqual (list (diffs ), [rg .replace ("/" ,os .sep )]) 155self .assertIn ("bytes differ" ,diffs [rg .replace ("/" ,os .sep )]) 156# the repaired copy passes both 157 (packed / rg ).write_bytes (good ) 158self .assertEqual (E .scan (str (packed )), {}) 159self .assertEqual (E .compare (str (staged ),str (packed )), {}) 160# a missing file is reported 161 (packed / "lib/libx.so" ).unlink () 162self .assertEqual (E .compare (str (staged ),str (packed )), {os .path .join ("lib" ,"libx.so" ): ["missing" ]}) 163 164def test_the_command_line_exit_codes (self ): 165with tempfile .TemporaryDirectory ()as tmp : 166Path (tmp ,"rg" ).write_bytes (make_static_pie ()) 167self .assertEqual (E .main (["x" ,"scan" ,tmp ]),0 ) 168Path (tmp ,"rg" ).write_bytes (make_static_pie (garbage = True )) 169self .assertEqual (E .main (["x" ,"scan" ,tmp ]),1 ) 170self .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 178def setUpClass (cls ): 179cls .tmp = tempfile .mkdtemp (prefix = "strata-elf-" ) 180src = Path (cls .tmp ,"t.c" ) 181src .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' ) 185cls .good = Path (cls .tmp ,"good" ) 186built = subprocess .run (["gcc" ,"-O2" ,"-static-pie" ,str (src ),"-o" ,str (cls .good )],capture_output = True ) 187cls .ok = built .returncode == 0 188 189@classmethod 190def tearDownClass (cls ): 191shutil .rmtree (cls .tmp ,ignore_errors = True ) 192 193def setUp (self ): 194if not self .ok : 195self .skipTest ("this gcc cannot build a static PIE" ) 196 197def test_the_real_program_runs_and_passes (self ): 198out = subprocess .run ([str (self .good )],capture_output = True ,text = True ) 199self .assertEqual (out .returncode ,0 ) 200self .assertIn ("ok alphabetagamma" ,out .stdout ) 201self .assertEqual (E .check_static_pie (self .good .read_bytes ()), []) 202 203def test_a_real_shared_library_with_a_runpath_passes (self ): 204src = Path (self .tmp ,"lib.c" ) 205src .write_text ("int answer(void) { return 42; }" + chr (10 )) 206lib = Path (self .tmp ,"libanswer.so.1" ) 207built = subprocess .run (["gcc" ,"-shared" ,"-fPIC" ,"-O2" ,"-Wl,-soname,libanswer.so.1" ,"-Wl,-rpath,$ORIGIN" ,str (src ),"-o" ,str (lib )],capture_output = True ) 208if built .returncode != 0 : 209self .skipTest ("this gcc cannot build a shared library" ) 210data = lib .read_bytes () 211self .assertEqual (E .check_static_pie (data ), [],"a real library with RUNPATH $ORIGIN and no interpreter is not a static PIE" ) 212self .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 214good = self .good .read_bytes () 215self .assertEqual (E .static_pie_kind (good ,E .read_elf (good )),"static-pie" ) 216 217def test_a_filled_dynamic_section_does_not_start_and_is_found (self ): 218data = bytearray (self .good .read_bytes ()) 219info = E .read_elf (bytes (data )) 220seg = next (p for p in info ["phdrs" ]if p ["type" ]== E .PT_DYNAMIC ) 221data [seg ["off" ]:seg ["off" ]+ seg ["filesz" ]]= b"Z" * seg ["filesz" ] 222bad = Path (self .tmp ,"bad" ) 223bad .write_bytes (bytes (data )) 224bad .chmod (0o755 ) 225run = subprocess .run ([str (bad )],capture_output = True ) 226self .assertNotEqual (run .returncode ,0 ,"a static PIE whose .dynamic is overwritten must not run" ) 227self .assertTrue (E .check_static_pie (bytes (data ))) 228self .assertEqual (E .main (["x" ,"scan" ,self .tmp ]),1 ) 229 230def 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.""" 232if sys .platform != "linux" or os .uname ().machine != "x86_64" or not shutil .which ("bash" )or not shutil .which ("python3" ): 233self .skipTest ("the check runs the bundled rg: x86-64 Linux with bash and python3" ) 234script = ROOT / "apps" / "desktop" / "scripts" / "repack-appimage.sh" 235src = Path (self .tmp ,"rg.c" ) 236src .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; }' ,"" ])) 240lib = Path (self .tmp ,"AppDir-lib" ) 241rg = lib / "harness/node_modules/@vscode/ripgrep-linux-x64/bin/rg" 242rg .parent .mkdir (parents = True ) 243built = subprocess .run (["gcc" ,"-O2" ,"-static-pie" ,str (src ),"-o" ,str (rg )],capture_output = True ) 244if built .returncode != 0 : 245self .skipTest ("this gcc cannot build a static PIE" ) 246snippet = 'source <(sed -n "/^elf_and_rg_check()/,/^}/p" "$SCRIPT"); elf_and_rg_check' 247env = dict (os .environ ,SCRIPT = str (script ),LIB = str (lib ),HERE = str (script .parent )) 248ok = subprocess .run (["bash" ,"-c" ,snippet ],env = env ,capture_output = True ,text = True ) 249self .assertEqual (ok .returncode ,0 ,ok .stdout + ok .stderr ) 250self .assertIn ("bundled rg runs: ok" ,ok .stdout ) 251data = bytearray (rg .read_bytes ()) 252info = E .read_elf (bytes (data )) 253seg = next (p for p in info ["phdrs" ]if p ["type" ]== E .PT_DYNAMIC ) 254data [seg ["off" ]:seg ["off" ]+ seg ["filesz" ]]= b"Z" * seg ["filesz" ] 255rg .write_bytes (bytes (data )) 256bad = subprocess .run (["bash" ,"-c" ,snippet ],env = env ,capture_output = True ,text = True ) 257self .assertNotEqual (bad .returncode ,0 ) 258self .assertIn ("BROKEN" ,bad .stdout ) 259self .assertIn ("does not run" ,bad .stderr ) 260 261 262if __name__ == "__main__" : 263unittest .main ()