git: db8b81ca99aa - stable/15 - rtld: Reject ELF files with PT_LOAD or PT_TLS segments where filesz > memsz

From: John Baldwin <jhb_at_FreeBSD.org>
Date: Thu, 08 Oct 2026 20:44:00 UTC
The branch stable/15 has been updated by jhb:

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

commit db8b81ca99aaa06a5ffbe5ca2d364a14d7987067
Author:     John Baldwin <jhb@FreeBSD.org>
AuthorDate: 2026-07-31 17:52:24 +0000
Commit:     John Baldwin <jhb@FreeBSD.org>
CommitDate: 2026-10-08 20:42:32 +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 | 12 ++++++++++++
 libexec/rtld-elf/rtld.c       |  6 ++++++
 2 files changed, 18 insertions(+)

diff --git a/libexec/rtld-elf/map_object.c b/libexec/rtld-elf/map_object.c
index f00f2a84ed07..6852daf13d68 100644
--- a/libexec/rtld-elf/map_object.c
+++ b/libexec/rtld-elf/map_object.c
@@ -121,6 +121,12 @@ 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(
@@ -140,6 +146,12 @@ 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 63bf32c87e3c..00cbba276ef3 100644
--- a/libexec/rtld-elf/rtld.c
+++ b/libexec/rtld-elf/rtld.c
@@ -1748,6 +1748,12 @@ 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;