okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2b8179f3e
main
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 11appimage_elf.py scan <folder> every static PIE under <folder> must have a sound .dynamic (exit 1 if not) 12appimage_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.""" 34return 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.""" 39if len (data )< 64 or data [:4 ]!= b"\x7fELF" or data [4 ]!= 2 or data [5 ]!= 1 : 40return None 41e_type = struct .unpack_from ("<H" ,data ,16 )[0 ] 42e_entry = struct .unpack_from ("<Q" ,data ,0x18 )[0 ] 43phoff = struct .unpack_from ("<Q" ,data ,0x20 )[0 ] 44phentsize ,phnum = struct .unpack_from ("<HH" ,data ,0x36 ) 45if phentsize < 56 or phoff + phentsize * phnum > len (data ): 46return {"type" :e_type ,"entry" :e_entry ,"phdrs" : [],"broken" :"the program header table is outside the file" } 47phdrs = [] 48for i in range (phnum ): 49p_type ,flags ,off ,vaddr ,_paddr ,filesz ,memsz ,align = struct .unpack_from ("<IIQQQQQQ" ,data ,phoff + i * phentsize ) 50phdrs .append ({"type" :p_type ,"flags" :flags ,"off" :off ,"vaddr" :vaddr ,"filesz" :filesz ,"memsz" :memsz ,"align" :align }) 51return {"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. 56A 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) 57have a readable dynamic section and are told apart by it (static_pie_kind). The test uses nothing the damage we look for can erase.""" 58return 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: 64shared libraries, which carry a DT_SONAME and no DF_1_PIE, and programs that are not static PIEs.""" 65if not is_pie_candidate (info ): 66return None 67entries ,why = dynamic_entries (data ,info ) 68if why or any (not _known_tag (t )for t ,_ in entries ): 69return "damaged" 70tags = {t :v for t ,v in entries } 71if DT_SONAME in tags : 72return None 73return "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.""" 78return 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.""" 83for p in info ["phdrs" ]: 84if p ["type" ]== PT_LOAD and p ["vaddr" ]<= vaddr and vaddr + size <= p ["vaddr" ]+ p ["filesz" ]: 85return p ["off" ]+ (vaddr - p ["vaddr" ]) 86return 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.""" 91seg = next (p for p in info ["phdrs" ]if p ["type" ]== PT_DYNAMIC ) 92if seg ["off" ]+ seg ["filesz" ]> len (data ): 93return [],"the dynamic segment is outside the file" 94out = [] 95for at in range (seg ["off" ],seg ["off" ]+ seg ["filesz" ]- 15 ,16 ): 96tag ,val = struct .unpack_from ("<qQ" ,data ,at ) 97if tag == DT_NULL : 98return out ,None 99out .append ((tag ,val )) 100return out ,"the dynamic segment does not end with DT_NULL" 101 102 103def _longest_filler (data ,start ,end ): 104best = run = 0 105prev = None 106for b in data [start :end ]: 107run = run + 1 if b == prev and b in FILLERS else (1 if b in FILLERS else 0 ) 108prev = b 109best = max (best ,run ) 110return 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.""" 115info = read_elf (data ) 116if static_pie_kind (data ,info )is None : 117return [] 118problems = [] 119seg = next (p for p in info ["phdrs" ]if p ["type" ]== PT_DYNAMIC ) 120if _mapped (info ,seg ["vaddr" ],max (seg ["filesz" ],1 ))is None : 121problems .append ("the dynamic segment is not inside any loaded segment" ) 122entries ,why = dynamic_entries (data ,info ) 123if why : 124problems .append (why ) 125bad = [t for t ,_ in entries if not _known_tag (t )] 126if bad : 127problems .append (f" { len ( bad ) } dynamic entries have tags that do not exist (first { bad [ 0 ]:#x } ): the section is overwritten" ) 128if any (t in (DT_RPATH ,DT_RUNPATH )for t ,_ in entries ): 129problems .append ("a static PIE has an RPATH or RUNPATH: something rewrote it after it was linked" ) 130values = dict (entries ) 131if DT_RELA in values : 132size = values .get (DT_RELASZ ,0 ) 133at = _mapped (info ,values [DT_RELA ],max (size ,1 )) 134if size == 0 or at is None : 135problems .append ("the relocation table named by DT_RELA is empty or outside the loaded segments" ) 136elif _longest_filler (data ,at ,at + size )>= min (RUN ,size ): 137problems .append ("the relocation table is filled with one byte" ) 138for p in info ["phdrs" ]: 139if p ["type" ]== PT_LOAD and _longest_filler (data ,p ["off" ],p ["off" ]+ p ["filesz" ])>= RUN : 140problems .append (f" { RUN } or more filler bytes (0x5A or 0x58) in a row inside a loaded segment" ) 141break 142return 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.""" 147a ,b = read_elf (staged ),read_elf (packaged ) 148if not a or not b : 149return []if staged == packaged else ["one of the two is not an ELF64 file" ] 150out = [] 151ta ,tb = [p ["type" ]for p in a ["phdrs" ]], [p ["type" ]for p in b ["phdrs" ]] 152if ta != tb : 153out .append (f"program headers { len ( ta ) } -> { len ( tb ) } ( { ta . count ( PT_LOAD ) } -> { tb . count ( PT_LOAD ) } loaded segments)" ) 154if is_pie_candidate (a )and is_pie_candidate (b ): 155da ,_ = dynamic_entries (staged ,a ) 156db ,_ = dynamic_entries (packaged ,b ) 157if da != db : 158out .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 "" )) 159return out 160 161 162def _files (folder ): 163for base ,dirs ,names in os .walk (folder ): 164dirs .sort () 165for name in sorted (names ): 166path = os .path .join (base ,name ) 167if os .path .islink (path )or not os .path .isfile (path ): 168continue 169yield path 170 171 172def scan (folder ): 173"""{relative path: problems} for every static PIE under `folder` that has any.""" 174found = {} 175for path in _files (folder ): 176try : 177with open (path ,"rb" )as f : 178head = f .read (4 ) 179if head != b"\x7fELF" : 180continue 181data = head + f .read () 182except OSError : 183continue 184problems = check_static_pie (data ) 185if problems : 186found [os .path .relpath (path ,folder )]= problems 187return found 188 189 190def compare (staged_folder ,folder ): 191"""{relative path: sentences} for every staged ELF file that is missing or differs in `folder`.""" 192found = {} 193for path in _files (staged_folder ): 194rel = os .path .relpath (path ,staged_folder ) 195with open (path ,"rb" )as f : 196want = f .read () 197if want [:4 ]!= b"\x7fELF" : 198continue 199other = os .path .join (folder ,rel ) 200if not os .path .isfile (other ): 201found [rel ]= ["missing" ] 202continue 203with open (other ,"rb" )as f : 204have = f .read () 205if have != want : 206found [rel ]= ["bytes differ" ]+ elf_differences (want ,have ) 207return found 208 209 210def main (argv ): 211if len (argv )>= 3 and argv [1 ]== "scan" : 212bad = scan (argv [2 ]) 213for rel ,problems in bad .items (): 214f"BROKEN { rel } : " + "; " .join (problems )) 215f" { len ( bad ) } static PIE file(s) with a damaged dynamic section" ) 216return 1 if bad else 0 217if len (argv )>= 4 and argv [1 ]== "compare" : 218bad = compare (argv [2 ],argv [3 ]) 219for rel ,why in bad .items (): 220f"DIFFERS { rel } : " + "; " .join (why )) 221f" { len ( bad ) } ELF file(s) differ from what was staged" ) 222return 1 if bad else 0 223__doc__ ) 224return 2 225 226 227if __name__ == "__main__" : 228sys .exit (main (sys .argv ))