git: 29d4f8bfc642 - main - ELF note parser: provide more info on failure

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Sun, 11 Feb 2024 03:39:20 UTC
The branch main has been updated by kib:

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

commit 29d4f8bfc642f0196c27eb469ea7eb326ff529d1
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2024-02-10 01:36:58 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2024-02-11 03:37:12 +0000

    ELF note parser: provide more info on failure
    
    Print reasons when parser declined to parse notes, due to mis-alignment,
    invalid length, or too many notes (the later typically means that there
    is a loop).  Also increase the loop limit to 4096, which gives enough
    iterations for notes to fill whole notes' page.
    
    Sponsored by:   The FreeBSD Foundation
    MFC after:      3 days
---
 sys/kern/imgact_elf.c | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)

diff --git a/sys/kern/imgact_elf.c b/sys/kern/imgact_elf.c
index 49dcae050d76..8f85a4f5e18a 100644
--- a/sys/kern/imgact_elf.c
+++ b/sys/kern/imgact_elf.c
@@ -2709,6 +2709,7 @@ __elfN(note_procstat_auxv)(void *arg, struct sbuf *sb, size_t *sizep)
 	}
 }
 
+#define	MAX_NOTES_LOOP	4096
 bool
 __elfN(parse_notes)(struct image_params *imgp, Elf_Note *checknote,
     const char *note_vendor, const Elf_Phdr *pnote,
@@ -2748,9 +2749,15 @@ __elfN(parse_notes)(struct image_params *imgp, Elf_Note *checknote,
 		    pnote->p_offset + pnote->p_filesz);
 		buf = NULL;
 	}
-	for (i = 0; i < 100 && note >= note0 && note < note_end; i++) {
-		if (!aligned(note, Elf32_Addr) || (const char *)note_end -
-		    (const char *)note < sizeof(Elf_Note)) {
+	for (i = 0; i < MAX_NOTES_LOOP && note >= note0 && note < note_end;
+	    i++) {
+		if (!aligned(note, Elf32_Addr)) {
+			uprintf("Unaligned ELF note\n");
+			goto retf;
+		}
+		if ((const char *)note_end - (const char *)note <
+		    sizeof(Elf_Note)) {
+			uprintf("ELF note to short\n");
 			goto retf;
 		}
 		if (note->n_namesz != checknote->n_namesz ||
@@ -2770,6 +2777,8 @@ nextnote:
 		    roundup2(note->n_namesz, ELF_NOTE_ROUNDSIZE) +
 		    roundup2(note->n_descsz, ELF_NOTE_ROUNDSIZE));
 	}
+	if (i >= MAX_NOTES_LOOP)
+		uprintf("ELF note parser reached %d notes\n", i);
 retf:
 	res = false;
 ret: