The ELF parser in gprof(1) trusts several header fields from the
input file without validation against the file size.
At elf.c:77, e_shoff is used as an offset into the mmap'd file
without checking it fits within the file:
shdrs = (const Elf_Shdr *)(base + h.e_shoff);
At line 86, sh_link indexes the section header table without a
bounds check:
sh_strtab = &shdrs[sh_symtab->sh_link];
At line 89, sh_entsize is used as a divisor without checking
for zero:
symtabct = sh_symtab->sh_size / sh_symtab->sh_entsize;
A 64-byte corrupted ELF file triggers SIGSEGV at line 86.
Confirmed on OpenBSD 7.8/arm64:
#0 getnfile at elf.c:86
Fix: validate e_shoff and section count against file size,
sh_link against e_shnum, sh_offset against file size, and
sh_entsize for zero before use.
All 5 SIGSEGV crash inputs handled cleanly after the fix
(3 caught by section header offset check, 2 by string table
link check).
Found by AFL++ fuzzing.
Index: usr.bin/gprof/elf.c
===================================================================
RCS file: /cvs/src/usr.bin/gprof/elf.c,v
retrieving revision 1.17
diff -u -p -r1.17 elf.c
--- usr.bin/gprof/elf.c 25 Nov 2023 01:26:32 -0000 1.17
+++ usr.bin/gprof/elf.c
@@ -74,6 +74,10 @@ getnfile(const char *filename, char ***d
close(fd);
base = (const char *)mapbase;
+
+ if (h.e_shoff >= s.st_size ||
+ h.e_shoff + (off_t)h.e_shnum * sizeof(Elf_Shdr) > s.st_size)
+ errx(1, "%s: bad section header offset", filename);
shdrs = (const Elf_Shdr *)(base + h.e_shoff);
/* Find the symbol table and associated string table section. */
@@ -83,8 +87,14 @@ getnfile(const char *filename, char ***d
if (i == h.e_shnum)
errx(1, "%s has no symbol table", filename);
sh_symtab = &shdrs[i];
+ if (sh_symtab->sh_link >= h.e_shnum)
+ errx(1, "%s: bad string table link", filename);
sh_strtab = &shdrs[sh_symtab->sh_link];
+ if (sh_symtab->sh_offset >= s.st_size ||
+ sh_symtab->sh_entsize == 0 ||
+ sh_strtab->sh_offset >= s.st_size)
+ errx(1, "%s: bad symbol table", filename);
symtab = (const Elf_Sym *)(base + sh_symtab->sh_offset);
symtabct = sh_symtab->sh_size / sh_symtab->sh_entsize;
strtab = (const char *)(base + sh_strtab->sh_offset);