From 37cdd922364eae01ae5c28b5ee059bc7b156be7f Mon Sep 17 00:00:00 2001 From: Maschell Date: Sat, 5 Dec 2020 21:31:27 +0100 Subject: [PATCH] Check if the payload.elf will be loaded into a valid location --- src/utils/ElfUtils.c | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/utils/ElfUtils.c b/src/utils/ElfUtils.c index ed685ac..6057236 100644 --- a/src/utils/ElfUtils.c +++ b/src/utils/ElfUtils.c @@ -8,6 +8,7 @@ #include #include #include +#include #include "elf_abi.h" @@ -41,6 +42,10 @@ int32_t LoadFileToMem(const char *relativefilepath, char **fileOut, uint32_t *si static void InstallMain(void *data_elf); +static bool CheckElfLoadedBetween(void *data_elf, uint32_t start_address, uint32_t end_address); + +static unsigned int get_section(void *data, const char *name, unsigned int *size, unsigned int *addr, int fail_on_not_found); + uint32_t load_loader_elf_from_sd(unsigned char *baseAddress, const char *relativePath) { char *elf_data = NULL; uint32_t fileSize = 0; @@ -48,6 +53,9 @@ uint32_t load_loader_elf_from_sd(unsigned char *baseAddress, const char *relativ return 0; } + if (!CheckElfLoadedBetween(elf_data, 0x00800000, 0x00FD0000)) { + return 0; + } InstallMain(elf_data); Elf32_Ehdr *ehdr = (Elf32_Ehdr *) elf_data; @@ -59,6 +67,37 @@ uint32_t load_loader_elf_from_sd(unsigned char *baseAddress, const char *relativ return res; } +static bool CheckElfSectionLoadedBetween(void *data_elf, const char *name, uint32_t start_address, uint32_t end_address) { + unsigned int target_addr = 0; + unsigned int len = 0; + if (get_section(data_elf, name, &target_addr, &len, 0) > 0) { + if (target_addr < start_address || target_addr + len > end_address) { + return false; + } + } + return true; +} + +static bool CheckElfLoadedBetween(void *data_elf, uint32_t start_address, uint32_t end_address) { + if (CheckElfSectionLoadedBetween(data_elf, ".text", start_address, end_address)) { + DEBUG_FUNCTION_LINE("ERROR: The .text would be loaded into a invalid location."); + return false; + } + if (CheckElfSectionLoadedBetween(data_elf, ".rodata", start_address, end_address)) { + DEBUG_FUNCTION_LINE("ERROR: The .rodata would be loaded into a invalid location."); + return false; + } + if (CheckElfSectionLoadedBetween(data_elf, ".data", start_address, end_address)) { + DEBUG_FUNCTION_LINE("ERROR: The .data would be loaded into a invalid location."); + return false; + } + if (CheckElfSectionLoadedBetween(data_elf, ".bss", start_address, end_address)) { + DEBUG_FUNCTION_LINE("ERROR: The .bss would be loaded into a invalid location."); + return false; + } + return true; +} + static unsigned int get_section(void *data, const char *name, unsigned int *size, unsigned int *addr, int fail_on_not_found) { Elf32_Ehdr *ehdr = (Elf32_Ehdr *) data;