From 6f89b367bca3d927d24c422cbcdb7e0fee954a90 Mon Sep 17 00:00:00 2001 From: mkilijanek Date: Tue, 20 Oct 2026 15:28:41 +0200 Subject: [PATCH] [BUGFIX] Resources: bound the parsed tree (self-referencing and overlapping directories) Since "Removed limit for resources to be parsed" the number of entries per directory is unbounded and only the depth (MAX_DEPTH 5) limits the tree. A directory whose entries point back at itself (or at the top directory), or a chain of distinct directories whose N entries all point at the next one, makes the parsed tree grow as N^MAX_DEPTH. With N=100 the parser does not return and memory grows until the process is killed (hasherezade/pe-bear#77). Two bounds, neither of which limits a well-formed resource tree: 1. Every directory is expanded at most once per tree (a set of raw offsets held by the top directory). This removes cycles and shared children. 2. The tree has a budget of getRawSize() / sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY) entries. In a well-formed tree every entry occupies its own bytes, so the budget cannot be exceeded. It is needed because the directories of a malformed file may overlap (a directory header placed over the entries of another directory), so that distinct offsets still share the same bytes as entries; the first bound alone does not stop that. Both are reset by the top directory's wrap(), the only place where a resource tree is rewrapped. Behaviour change: a directory referenced by more than one entry is expanded only under the first one. tests/gen_rsrc_poc.py generates synthetic PE32 files for the three shapes (selfloop, chain, overlap); run bearcommander on them with the `rsl` command. Without this change all three run past a 20 s limit; with it they finish in under 0.1 s. The tests_list.txt cases give the same results before and after. --- .../bearparser/pe/ResourceDirWrapper.h | 26 ++++++++++- parser/pe/ResourceDirWrapper.cpp | 13 +++++- tests/gen_rsrc_poc.py | 46 +++++++++++++++++++ 3 files changed, 82 insertions(+), 3 deletions(-) create mode 100644 tests/gen_rsrc_poc.py diff --git a/parser/include/bearparser/pe/ResourceDirWrapper.h b/parser/include/bearparser/pe/ResourceDirWrapper.h index 8baf9fe39..27d7ac699 100644 --- a/parser/include/bearparser/pe/ResourceDirWrapper.h +++ b/parser/include/bearparser/pe/ResourceDirWrapper.h @@ -7,6 +7,7 @@ #include "rsrc/ResourceContentFactory.h" #include +#include #include @@ -25,9 +26,9 @@ class ResourceDirWrapper : public DataDirEntryWrapper FIELD_COUNTER }; - ResourceDirWrapper(PEFile* pe, ResourcesAlbum *resAlbum = NULL, offset_t rawOffset = 0, long depth = 0, long topEntryId = TOP_ENTRY_ROOT) + ResourceDirWrapper(PEFile* pe, ResourcesAlbum *resAlbum = NULL, offset_t rawOffset = 0, long depth = 0, long topEntryId = TOP_ENTRY_ROOT, ResourceDirWrapper *rootDir = NULL) : DataDirEntryWrapper(pe, pe::DIR_RESOURCE), - rawOff(rawOffset), dirDepth(depth), album(resAlbum), topEntryID(topEntryId) + rawOff(rawOffset), dirDepth(depth), album(resAlbum), topEntryID(topEntryId), root(rootDir ? rootDir : this), entriesLeft(0) { wrap(); } @@ -55,12 +56,33 @@ class ResourceDirWrapper : public DataDirEntryWrapper IMAGE_RESOURCE_DIRECTORY* mainResourceDir(); ResourcesAlbum* getAlbumPtr() { return album; } + /* Registers the directory at the given raw offset as expanded in the tree + * this directory belongs to. Returns false if it was already expanded: + * a directory is parsed at most once, so entries that form cycles or share + * children do not make the tree grow exponentially. */ + bool markExpanded(offset_t dirRawOffset) { return root->expandedDirs.insert(dirRawOffset).second; } + + /* Takes one entry from the budget of the tree. Returns false when the budget is spent. + * The budget is the number of entries that fit in the file: in a well-formed tree + * every entry occupies its own bytes, but directories of a malformed file may overlap + * and reuse the same bytes as entries of many other directories. */ + bool takeEntry() + { + if (root->entriesLeft == 0) return false; + root->entriesLeft--; + return true; + } + ResourceDirWrapper* getRoot() { return root; } + private: IMAGE_RESOURCE_DIRECTORY* resourceDir(); offset_t rawOff; long dirDepth; ResourcesAlbum *album; long topEntryID; + ResourceDirWrapper *root; // the top directory of this tree (this, for the top directory itself) + std::set expandedDirs; // used only in the root + size_t entriesLeft; // used only in the root }; class ResourceEntryWrapper : public PENodeWrapper diff --git a/parser/pe/ResourceDirWrapper.cpp b/parser/pe/ResourceDirWrapper.cpp index 08c91c4a9..5cbc4b9d2 100644 --- a/parser/pe/ResourceDirWrapper.cpp +++ b/parser/pe/ResourceDirWrapper.cpp @@ -78,11 +78,18 @@ bool ResourceDirWrapper::wrap() } IMAGE_RESOURCE_DIRECTORY* dir = resourceDir(); if (dir == NULL) return false; + if (this->root == this) { + // the top directory is the first one to be expanded (it is addressed by rawOff == 0) + this->expandedDirs.clear(); + this->entriesLeft = static_cast(m_Exe->getRawSize()) / sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY); + markExpanded(getOffset(mainResourceDir())); + } size_t namesNum = dir->NumberOfNamedEntries; size_t idsNum = dir->NumberOfIdEntries; size_t totalEntries = namesNum + idsNum; for (size_t i = 0; i < totalEntries && i < MAX_ENTRIES; i++ ) { + if (!takeEntry()) break; long topDirId = (this->topEntryID != TOP_ENTRY_ROOT) ? this->topEntryID : long(i) ; @@ -183,7 +190,11 @@ bool ResourceEntryWrapper::wrap() if (this->isDir()) { long depth = this->parentDir->getDepth() + 1; if (depth >= MAX_DEPTH) return false; - this->childDir = new ResourceDirWrapper(this->m_PE, this->album, childRaw, depth, topEntryID); + // A malformed file may make directories point back at themselves (or at the top directory), + // or make many entries point at the same child. Expand every directory only once; + // otherwise the tree grows exponentially with the depth. + if (!this->parentDir->markExpanded(childRaw)) return false; + this->childDir = new ResourceDirWrapper(this->m_PE, this->album, childRaw, depth, topEntryID, this->parentDir->getRoot()); } else { this->childLeaf = new ResourceLeafWrapper(m_Exe, childRaw, topEntryID); if (this->album != NULL) { diff --git a/tests/gen_rsrc_poc.py b/tests/gen_rsrc_poc.py new file mode 100644 index 000000000..0d2246733 --- /dev/null +++ b/tests/gen_rsrc_poc.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Generates synthetic PE32 files with malformed resource directories (no malware). +usage: gen_rsrc_poc.py {selfloop|chain|overlap} OUT [ENTRIES]""" +import struct, sys +mode, out = sys.argv[1], sys.argv[2] +N = int(sys.argv[3]) if len(sys.argv) > 3 else 100 +DIR = 0x80000000 +def rdir(entries): + b = struct.pack('= 0x8000) + rs = rdir([DIR | (16 + 8 * j) for j in range(N)]) + rs += b'\0' * 16 +else: + raise SystemExit('unknown mode') +rs = rs.ljust((len(rs) + 0x1ff) & ~0x1ff, b'\0') +hdr = bytearray(0x200) +hdr[0:2] = b'MZ'; struct.pack_into('