From e49a735134b7ba8236e9914b57f5c0ce30727300 Mon Sep 17 00:00:00 2001 From: totonii Date: Sun, 22 Nov 2026 08:55:31 -0300 Subject: fix(pe_loader): validate SizeOfHeaders covers NT/section headers and guard truncated relocation blocks --- runtime/src/pe_loader.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) (limited to 'runtime/src/pe_loader.cpp') diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 15a62d9b4..3e2a1a725 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -292,12 +292,15 @@ Module& Loader::map_image(const std::filesystem::path& path) { nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) throw std::runtime_error(name + ": not a PE32+ image"); auto& oh = nt->OptionalHeader; - uint64_t sections = static_cast(dos->e_lfanew) + 4 + sizeof(IMAGE_FILE_HEADER) + - nt->FileHeader.SizeOfOptionalHeader; - if (sections + static_cast(nt->FileHeader.NumberOfSections) * sizeof(IMAGE_SECTION_HEADER) > file.size()) + const uint64_t sections = static_cast(dos->e_lfanew) + 4 + sizeof(IMAGE_FILE_HEADER) + + nt->FileHeader.SizeOfOptionalHeader; + const uint64_t headers_end = + sections + static_cast(nt->FileHeader.NumberOfSections) * sizeof(IMAGE_SECTION_HEADER); + if (headers_end > file.size()) throw std::runtime_error(name + ": the section table runs past the end of the file"); - if (!oh.SizeOfImage || oh.SizeOfHeaders > oh.SizeOfImage || oh.SizeOfHeaders > file.size()) - throw std::runtime_error(name + ": SizeOfHeaders and SizeOfImage don't fit the file"); + if (!oh.SizeOfImage || oh.SizeOfHeaders < headers_end || oh.SizeOfHeaders > oh.SizeOfImage || + oh.SizeOfHeaders > file.size()) + throw std::runtime_error(name + ": SizeOfHeaders and SizeOfImage don't fit the headers and file"); auto* m = new Module; m->name = name; @@ -338,8 +341,9 @@ Module& Loader::map_image(const std::filesystem::path& path) { auto* block = at(m->base, dir.VirtualAddress); auto* end = reinterpret_cast(block) + dir.Size; while (reinterpret_cast(block) < end) { - if (block->SizeOfBlock < sizeof(IMAGE_BASE_RELOCATION) || - reinterpret_cast(block) + block->SizeOfBlock > end) + const size_t remaining = static_cast(end - reinterpret_cast(block)); + if (remaining < sizeof(IMAGE_BASE_RELOCATION) || block->SizeOfBlock < sizeof(IMAGE_BASE_RELOCATION) || + block->SizeOfBlock > remaining) throw std::runtime_error(m->name + ": a relocation block doesn't fit the relocation table"); auto* entries = reinterpret_cast(block + 1); size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2; -- cgit v1.2.3