git: 4b1963dbb36f - main - link_elf_obj: validate section name offsets

From: Mark Johnston <markj_at_FreeBSD.org>
Date: Mon, 09 Nov 2026 23:43:35 UTC
The branch main has been updated by markj:

URL: https://cgit.FreeBSD.org/src/commit/?id=4b1963dbb36f9928097a6f26cf3aaff88573b77d

commit 4b1963dbb36f9928097a6f26cf3aaff88573b77d
Author:     Osvaldo Janeri Filho <ojanerif@amd.com>
AuthorDate: 2026-11-09 23:18:58 +0000
Commit:     Mark Johnston <markj@FreeBSD.org>
CommitDate: 2026-11-09 23:43:17 +0000

    link_elf_obj: validate section name offsets
    
    A section name offset (sh_name) indexes the section name string table
    without being checked against shstrcnt, and the result is passed to
    strcmp(), so a corrupt object causes an out-of-bounds read.  Check that
    the table is NUL-terminated and that every sh_name lies within it, in
    both the preload and file paths, and reject the object with ENOEXEC.
    
    Reviewed by:    kib
    MFC after:      1 week
    Differential Revision:  https://reviews.freebsd.org/D61338
---
 sys/kern/link_elf_obj.c | 27 +++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)

diff --git a/sys/kern/link_elf_obj.c b/sys/kern/link_elf_obj.c
index a4871900c5c4..02bbc3112751 100644
--- a/sys/kern/link_elf_obj.c
+++ b/sys/kern/link_elf_obj.c
@@ -359,6 +359,27 @@ link_elf_obj_check_symtab(elf_file_t ef, const char *filename)
 	return (0);
 }
 
+static int
+link_elf_obj_check_shstrtab(elf_file_t ef, const Elf_Shdr *shdr, int shnum,
+    const char *filename)
+{
+	int i;
+
+	if (ef->shstrtab == NULL)
+		return (0);
+	if (ef->shstrcnt == 0 || ef->shstrtab[ef->shstrcnt - 1] != '\0') {
+		link_elf_error(filename, "corrupt section name string table");
+		return (ENOEXEC);
+	}
+	for (i = 0; i < shnum; i++) {
+		if (shdr[i].sh_name >= ef->shstrcnt) {
+			link_elf_error(filename, "corrupt section name offset");
+			return (ENOEXEC);
+		}
+	}
+	return (0);
+}
+
 static int
 link_elf_link_preload(linker_class_t cls, const char *filename,
     linker_file_t *result)
@@ -507,6 +528,9 @@ link_elf_link_preload(linker_class_t cls, const char *filename,
 		goto out;
 	ef->shstrcnt = shdr[shstrindex].sh_size;
 	ef->shstrtab = (char *)shdr[shstrindex].sh_addr;
+	error = link_elf_obj_check_shstrtab(ef, shdr, hdr->e_shnum, filename);
+	if (error != 0)
+		goto out;
 
 	/* Now fill out progtab and the relocation tables. */
 	pb = 0;
@@ -1000,6 +1024,9 @@ link_elf_load_file(linker_class_t cls, const char *filename,
 			goto out;
 		}
 	}
+	error = link_elf_obj_check_shstrtab(ef, shdr, hdr->e_shnum, filename);
+	if (error != 0)
+		goto out;
 
 	/* Size up code/data(progbits) and bss(nobits). */
 	alignmask = 0;