Skip to content

Commit 10b1924

Browse files
Alexey Dobriyankees
authored andcommitted
ELF: fix overflow in total mapping size calculation
Kernel assumes that ELF program headers are ordered by mapping address, but doesn't enforce it. It is possible to make mapping size extremely huge by simply shuffling first and last PT_LOAD segments. As long as PT_LOAD segments do not overlap, it is silly to require sorting by v_addr anyway because mmap() doesn't care. Don't assume PT_LOAD segments are sorted and calculate min and max addresses correctly. Signed-off-by: Alexey Dobriyan <[email protected]> Tested-by: "Magnus Groß" <[email protected]> Link: https://lore.kernel.org/all/[email protected]/ Signed-off-by: Kees Cook <[email protected]> Link: https://lore.kernel.org/lkml/YVmd7D0M6G%[email protected]
1 parent 439a846 commit 10b1924

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

fs/binfmt_elf.c

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ static int elf_core_dump(struct coredump_params *cprm);
9393
#define ELF_CORE_EFLAGS 0
9494
#endif
9595

96-
#define ELF_PAGESTART(_v) ((_v) & ~(unsigned long)(ELF_MIN_ALIGN-1))
96+
#define ELF_PAGESTART(_v) ((_v) & ~(int)(ELF_MIN_ALIGN-1))
9797
#define ELF_PAGEOFFSET(_v) ((_v) & (ELF_MIN_ALIGN-1))
9898
#define ELF_PAGEALIGN(_v) (((_v) + ELF_MIN_ALIGN - 1) & ~(ELF_MIN_ALIGN - 1))
9999

@@ -399,22 +399,21 @@ static unsigned long elf_map(struct file *filep, unsigned long addr,
399399
return(map_addr);
400400
}
401401

402-
static unsigned long total_mapping_size(const struct elf_phdr *cmds, int nr)
402+
static unsigned long total_mapping_size(const struct elf_phdr *phdr, int nr)
403403
{
404-
int i, first_idx = -1, last_idx = -1;
404+
elf_addr_t min_addr = -1;
405+
elf_addr_t max_addr = 0;
406+
bool pt_load = false;
407+
int i;
405408

406409
for (i = 0; i < nr; i++) {
407-
if (cmds[i].p_type == PT_LOAD) {
408-
last_idx = i;
409-
if (first_idx == -1)
410-
first_idx = i;
410+
if (phdr[i].p_type == PT_LOAD) {
411+
min_addr = min(min_addr, ELF_PAGESTART(phdr[i].p_vaddr));
412+
max_addr = max(max_addr, phdr[i].p_vaddr + phdr[i].p_memsz);
413+
pt_load = true;
411414
}
412415
}
413-
if (first_idx == -1)
414-
return 0;
415-
416-
return cmds[last_idx].p_vaddr + cmds[last_idx].p_memsz -
417-
ELF_PAGESTART(cmds[first_idx].p_vaddr);
416+
return pt_load ? (max_addr - min_addr) : 0;
418417
}
419418

420419
static int elf_read(struct file *file, void *buf, size_t len, loff_t pos)

0 commit comments

Comments
 (0)