git: 35d9a9b2fa47 - main - link_elf: validate symbol name offsets

From: Mark Johnston <markj_at_FreeBSD.org>
Date: Wed, 11 Nov 2026 16:49:56 UTC
The branch main has been updated by markj:

URL: https://cgit.FreeBSD.org/src/commit/?id=35d9a9b2fa4796a7e7a9c3bf17547e66007e6b14

commit 35d9a9b2fa4796a7e7a9c3bf17547e66007e6b14
Author:     Osvaldo Janeri Filho <ojanerif@amd.com>
AuthorDate: 2026-11-11 14:58:04 +0000
Commit:     Mark Johnston <markj@FreeBSD.org>
CommitDate: 2026-11-11 16:49:42 +0000

    link_elf: validate symbol name offsets
    
    st_name isn't checked against the string table size, for any of the
    symbol tables used here.  Do what link_elf_obj.c does since 4e2c2842e.
    
    Reported by:    llm-postcr
    MFC after:      1 week
    Reviewed by:    kib
    Differential Revision:  https://reviews.freebsd.org/D61388
---
 sys/kern/link_elf.c | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)

diff --git a/sys/kern/link_elf.c b/sys/kern/link_elf.c
index 0fd1e8c36688..c49ecea0bace 100644
--- a/sys/kern/link_elf.c
+++ b/sys/kern/link_elf.c
@@ -532,6 +532,27 @@ link_elf_init(void* arg)
 
 SYSINIT(link_elf, SI_SUB_KLD, SI_ORDER_THIRD, link_elf_init, NULL);
 
+static int
+link_elf_check_symtab(const char *filename, const Elf_Sym *symtab,
+    long symcnt, const char *strtab, long strcnt)
+{
+	long i;
+
+	if (symcnt == 0)
+		return (0);
+	if (strcnt <= 0 || strtab[strcnt - 1] != '\0') {
+		link_elf_error(filename, "corrupt symbol string table");
+		return (ENOEXEC);
+	}
+	for (i = 0; i < symcnt; i++) {
+		if (symtab[i].st_name >= strcnt) {
+			link_elf_error(filename, "corrupt symbol name offset");
+			return (ENOEXEC);
+		}
+	}
+	return (0);
+}
+
 static int
 link_elf_preload_parse_symbols(elf_file_t ef)
 {
@@ -577,6 +598,10 @@ link_elf_preload_parse_symbols(elf_file_t ef)
 		return (EINVAL);
 	}
 
+	if (link_elf_check_symtab(ef->lf.filename, symtab,
+	    symcnt / sizeof(Elf_Sym), strtab, strcnt) != 0)
+		return (EINVAL);
+
 	ef->ddbsymtab = symtab;
 	ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
 	ef->ddbstrtab = strtab;
@@ -719,6 +744,10 @@ parse_dynamic(elf_file_t ef)
 		ef->pltrelsize = 0;
 	}
 
+	if (ef->lf.size != 0 && link_elf_check_symtab(ef->lf.filename,
+	    ef->symtab, ef->nchains, ef->strtab, ef->strsz) != 0)
+		return (ENOEXEC);
+
 	ef->ddbsymtab = ef->symtab;
 	ef->ddbsymcnt = ef->nchains;
 	ef->ddbstrtab = ef->strtab;
@@ -1403,6 +1432,11 @@ link_elf_load_file(linker_class_t cls, const char* filename,
 	if (error != 0)
 		goto out;
 
+	error = link_elf_check_symtab(filename, (const Elf_Sym *)ef->symbase,
+	    symcnt / sizeof(Elf_Sym), ef->strbase, strcnt);
+	if (error != 0)
+		goto out;
+
 	ef->ddbsymcnt = symcnt / sizeof(Elf_Sym);
 	ef->ddbsymtab = (const Elf_Sym *)ef->symbase;
 	ef->ddbstrcnt = strcnt;