git: 144dbb0bc0e1 - stable/14 - rtld: Reject ELF files with PT_LOAD or PT_TLS segments where filesz > memsz

From: John Baldwin <jhb_at_FreeBSD.org>
Date: Fri, 09 Oct 2026 00:20:47 UTC
The branch stable/14 has been updated by jhb:

URL: https://cgit.FreeBSD.org/src/commit/?id=144dbb0bc0e1e9f6d0997a519cb9d85b3e3d95e3

commit 144dbb0bc0e1e9f6d0997a519cb9d85b3e3d95e3
Author:     John Baldwin <jhb@FreeBSD.org>
AuthorDate: 2026-07-31 17:52:24 +0000
Commit:     John Baldwin <jhb@FreeBSD.org>
CommitDate: 2026-10-08 18:47:10 +0000

    rtld: Reject ELF files with PT_LOAD or PT_TLS segments where filesz > memsz
    
    All sorts of places in the ELF loading code assume that filesz <=
    memsz, so check that explicitly up front.  The kernel already performs
    this check for the PT_LOAD segments in the main binary and rtld in
    imgact_elf.c.
    
    Reviewed by:    jrtc27, kib
    Differential Revision:  https://reviews.freebsd.org/D58541
    
    (cherry picked from commit 535eb24d8451bad8de745937018800df1895a9aa)
---
 libexec/rtld-elf/map_object.c | 10 ++++++++++
 libexec/rtld-elf/rtld.c       |  5 +++++
 2 files changed, 15 insertions(+)

diff --git a/libexec/rtld-elf/map_object.c b/libexec/rtld-elf/map_object.c
index e021f42681a8..ab48d755ef84 100644
--- a/libexec/rtld-elf/map_object.c
+++ b/libexec/rtld-elf/map_object.c
@@ -129,6 +129,11 @@ map_object(int fd, const char *path, const struct stat *sb, bool ismain)
 	    break;
 
 	case PT_LOAD:
+	    if (phdr->p_memsz < phdr->p_filesz) {
+		    _rtld_error("%s: invalid PT_LOAD segment", path);
+		    goto error;
+	    }
+
 	    segs[++nsegs] = phdr;
 	    if ((segs[nsegs]->p_align & (page_size - 1)) != 0) {
 		_rtld_error("%s: PT_LOAD segment %d not page-aligned",
@@ -147,6 +152,11 @@ map_object(int fd, const char *path, const struct stat *sb, bool ismain)
 	    break;
 
 	case PT_TLS:
+	    if (phdr->p_memsz < phdr->p_filesz) {
+		_rtld_error("%s: invalid PT_TLS segment", path);
+		goto error;
+	    }
+
 	    phtls = phdr;
 	    break;
 
diff --git a/libexec/rtld-elf/rtld.c b/libexec/rtld-elf/rtld.c
index 29fad4302528..8ac6a73a962c 100644
--- a/libexec/rtld-elf/rtld.c
+++ b/libexec/rtld-elf/rtld.c
@@ -1687,6 +1687,11 @@ digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path)
 	    break;
 
 	case PT_TLS:
+	    if (ph->p_memsz < ph->p_filesz) {
+		_rtld_error("%s: invalid PT_TLS segment", path);
+		return (NULL);
+	    }
+
 	    obj->tlsindex = 1;
 	    obj->tlssize = ph->p_memsz;
 	    obj->tlsalign = ph->p_align;