:: commit 6d78adb8b790e17986435c2dc25b819b26621c54

Mintsuki <mintsuki@protonmail.com> — 2026-02-08 17:50

parents: 129e1b1ca8

lib/elf: Use overflow-safe pattern for phdr bounds check in _elsewhere functions

diff --git a/common/lib/elf.c b/common/lib/elf.c
index eac25a80..2e7145c6 100644
--- a/common/lib/elf.c
+++ b/common/lib/elf.c
@@ -1069,7 +1069,8 @@ bool elf32_load_elsewhere(uint8_t *elf, size_t file_size, uint64_t *entry_point,
         panic(true, "elf: phdr_size < sizeof(struct elf32_phdr)");
     }
 
-    if ((uint64_t)hdr->phoff + (uint64_t)hdr->ph_num * hdr->phdr_size > file_size) {
+    uint64_t phdr_table_size32 = (uint64_t)hdr->ph_num * hdr->phdr_size;
+    if (hdr->phoff > file_size || phdr_table_size32 > file_size - hdr->phoff) {
         panic(true, "elf: Program header table extends beyond file bounds");
     }
 
@@ -1146,7 +1147,8 @@ bool elf64_load_elsewhere(uint8_t *elf, size_t file_size, uint64_t *entry_point,
         panic(true, "elf: phdr_size < sizeof(struct elf64_phdr)");
     }
 
-    if ((uint64_t)hdr->phoff + (uint64_t)hdr->ph_num * hdr->phdr_size > file_size) {
+    uint64_t phdr_table_size64 = (uint64_t)hdr->ph_num * hdr->phdr_size;
+    if (hdr->phoff > file_size || phdr_table_size64 > file_size - hdr->phoff) {
         panic(true, "elf: Program header table extends beyond file bounds");
     }
 
tab: 248 wrap: offon