Skip to content

[high] Fix section entropy computation in pe_parse - #2

Open
elhoim wants to merge 1 commit into
MISP:masterfrom
elhoim:fix/pe-parse-entropy-byte-histogram
Open

elhoim wants to merge 1 commit into
MISP:masterfrom
elhoim:fix/pe-parse-entropy-byte-histogram

Conversation

@elhoim

@elhoim elhoim commented Sep 17, 2026

Copy link
Copy Markdown

BLUF

  • Priority: high.
  • H() in grouping/pe_parse.py never counted byte values, so every PE section entropy written to Redis is wrong.
  • Root cause: data.count(bytes(x)) — bytes(x) is x NUL bytes on Python 3 and the digit string "0".."255" on Python 2, never the single byte x.
  • Knock-on: eval_packed's 6.0 < entropy < 6.7 packer test is unreachable on Python 3, so the +50 packer contribution is dead and every packed score is understated.
  • Fix: build the histogram once with Counter(bytearray(data)) and index it — correct on Python 2 and 3, and O(n) instead of O(256n).
  • Verified with known-entropy buffers: 8.0 for a uniform 0..255 block, 0.0 for an all-zero block, 1.0 for a two-value block.

What was wrong

entropy = 0
for x in range(256):
    p_x = float(data.count(bytes(x))) / len(data)

data is section.get_data(), a bytes object from pefile.

  • Python 3: bytes(x) builds a buffer of x NUL bytes. bytes(0) is b'', so data.count(b'') returns len(data) + 1 and yields p_x > 1, contributing a small negative term. bytes(65) is 65 NUL bytes, not b'A', so it matches nothing in practice. Every other term is zero.
  • Python 2: bytes is str, so bytes(x) is "0", "1", … "255" and the loop counts occurrences of ASCII digit substrings, not byte values.

Under neither interpreter does the loop count occurrences of byte value x.

Concrete impact

  • The per-section entropy hash field written at grouping/pe_parse.py:98 is garbage. Measured before the fix: an all-zero 1 KiB buffer scored 21.4533 (above the theoretical maximum of 8.0) and a uniform 0..255 block scored 0.0256.
  • Because real section data always contains NUL bytes, entropy comes out at or below 0 on Python 3, so eval_packed's 6.0 < float(entropy) < 6.7 window can never be entered and the +50 packer weight never applies. Packer scores are systematically missing that term on Python 3 and arbitrary on Python 2.

What this changes

  • Counts each byte value once via Counter(bytearray(data)) and indexes it inside the existing range(256) loop. bytearray(data) iterates as integers on both Python 2 and 3, which is why the wrap is kept rather than Counter(data) (that would key on 1-character strings under Python 2). Absent byte values return 0 from the Counter, so the if p_x > 0 guard keeps working unchanged.
  • Adds from collections import Counter, matching the existing usage in grouping/examples/helper.py.
  • Nothing else is touched: same signature, same float() division for Python 2, same loop, same early return for empty data, no new dependency (collections is stdlib).

Note: entropy values already stored in Redis are stale and should be re-parsed if packed scores matter, since the packer window now actually fires.

Out of scope on purpose: standalone/Kinginyourcastle.py carries a second, differently broken copy of H() (data.count(chr(x))); it is not touched here.

How it was verified

Syntax gate over all tracked Python files (ast.parse) plus bash -n hashes-extract.sh, then H() exercised directly on buffers with known Shannon entropy:

input before after expected
uniform 0..255 0.0256 8.0000 8.0
1 KiB of 0x00 21.4533 0.0000 0.0
512x 0x00 + 512x 0x01 0.0117 1.0000 1.0
empty 0.0000 0.0000 0.0

The repository has no test suite, so no framework was introduced; H() was extracted with ast and executed standalone, which avoids needing pefile/redis installed.


Local verification

cd /home/elhoim/tmp/misp-review/mwork/data-processing-1 && python3 -m py_compile grouping/pe_parse.py && python3 - <<'PY'
import ast, math, sys
from collections import Counter
src = open('grouping/pe_parse.py').read()
tree = ast.parse(src, 'grouping/pe_parse.py')
has_imp = any(isinstance(n, ast.ImportFrom) and n.module == 'collections'
              and any(a.name == 'Counter' for a in n.names) for n in tree.body)
print('module-level "from collections import Counter":', 'OK' if has_imp else 'MISSING')
fn = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == 'H')
ns = {'math': math, 'Counter': Counter}
exec(compile(ast.Module(body=[fn], type_ignores=[]), 'H', 'exec'), ns)
H = ns['H']
bad = 0 if has_imp else 1
for name, data, want in [('uniform 0..255', bytes(bytearray(range(256))), 8.0),
                         ('all zeros', b'\x00'*1024, 0.0),
                         ('half 00/half 01', b'\x00'*512 + b'\x01'*512, 1.0),
                         ('empty', b'', 0.0)]:
    got = H(data); ok = abs(got - want) < 1e-9; bad += not ok
    print('%-16s -> %.4f (expect %.4f) %s' % (name, got, want, 'OK' if ok else 'FAIL'))
print('RESULT:', 'PASS' if not bad else 'FAIL (%d)' % bad)
sys.exit(1 if bad else 0)
PY

Output:

module-level "from collections import Counter": OK
uniform 0..255   -> 8.0000 (expect 8.0000) OK
all zeros        -> 0.0000 (expect 0.0000) OK
half 00/half 01  -> 1.0000 (expect 1.0000) OK
empty            -> 0.0000 (expect 0.0000) OK
RESULT: PASS
patched_exit=0
  • Verified on a scratch work tree with the patch applied.
  • The same check was re-run with the change stashed and fails on unpatched code, so it discriminates rather than merely passing.

Note: Two corrections to the "How it was verified" section of this PR body, both measured on this tree (Python 3.14):

  • The before-value for the 512x 0x00 + 512x 0x01 case is 13.4067, not 0.0117. The other three before-values in the table (0.0256, 21.4533, 0.0000) are correct as written.
  • The claimed repo-wide ast.parse syntax gate over all tracked Python files does not pass cleanly, before or after this change: four pre-existing Python-2-only files fail to parse under Python 3 (grouping/examples/helper.py, grouping/examples/ssdeep_highmatch.py, standalone/Database.py, standalone/Kinginyourcastle.py). They are unrelated to this change. Verification was therefore scoped to the changed file (python3 -m py_compile grouping/pe_parse.py).

Also unverified end to end: pefile and redis are not installed in the verification environment, and the module's SafeConfigParser imp

H() counted data.count(bytes(x)), which never yields the number of
occurrences of byte value x: on Python 3 bytes(x) is a run of x NUL
bytes (bytes(0) is b'', so the count is len(data) + 1 and the entropy
goes negative), and on Python 2 bytes is str, so it counts the decimal
digit strings "0".."255".

Every section entropy stored in Redis was therefore wrong, and because
the value stayed at or below zero on Python 3, eval_packed's
6.0 < entropy < 6.7 packer window was unreachable and its +50
contribution never applied.

Build the histogram once with Counter(bytearray(data)) and index it.
bytearray() iterates as integers on both Python 2 and 3, so the fix
keeps the module's dual-interpreter support.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant