add_new_section_symbols() sizes its symndx_map VLA as sh_size / sh_entsize - 1 elements. libelf bounds symbol accesses by sh_size divided by the size of one symbol, and gelf_getsymshndx() rejects only indices past that bound. When the stripped file's SHT_SYMTAB has an sh_entsize larger than the symbol size, the VLA is smaller than the number of symbols libelf accepts. A leading run of STT_SECTION symbols then makes the loop write symndx_map[i - 1] past the end of the array, on the stack.
With AddressSanitizer this shows as a dynamic-stack-buffer-overflow, WRITE of size 8, at unstrip.c in add_new_section_symbols. It is reached by an ET_REL stripped file with sh_entsize 48 and 501 or more sections, and by the four-section file in the new test. Add valid_symtab_entsize () and use it where unstrip derives a symbol count from sh_entsize: the stripped SYMTAB and DYNSYM copy loop, and the merge path for the stripped and unstripped SYMTAB. A symbol table whose sh_entsize is not the symbol size is malformed, and is now rejected. This extends the sh_size < sh_entsize check of commit 364419bc. Symbol tables with the usual entsize are not affected. add_new_section_symbols() also refuses an old_shnum larger than nsym before it writes symndx_map, as defense in depth. The entsize check makes that case unreachable from input, but the bound stays next to the array it protects. Related: PR tools/34705. * src/unstrip.c (valid_symtab_entsize): New function. (add_new_section_symbols): Reject old_shnum larger than nsym. (copy_elided_sections): Use valid_symtab_entsize for the stripped SYMTAB and DYNSYM copy loop, and for the stripped and unstripped SYMTAB merge. * tests/run-unstrip-symtab-entsize.sh: New test script. * tests/testfile-unstrip-symtab2.stripped.bz2: New test file. * tests/testfile-unstrip-symtab2.debug.bz2: Likewise. * tests/Makefile.am (TESTS): Add run-unstrip-symtab-entsize.sh. (EXTRA_DIST): Add new test script and bz2 files. Signed-off-by: vivekjha <[email protected]>
0001-unstrip-reject-SYMTAB-sh_entsize-that-is-not-the-sym.patch
Description: Binary data
