Skip to content

feat(native): static packer identification for PE and ELF - #3775

Open
Kizuno18 wants to merge 4 commits into
morluto:mainfrom
Kizuno18:feat/static-packer-identification
Open

Kizuno18 wants to merge 4 commits into
morluto:mainfrom
Kizuno18:feat/static-packer-identification

Conversation

@Kizuno18

@Kizuno18 Kizuno18 commented Oct 15, 2026 •

Copy link
Copy Markdown

Summary

Fixes #3413 (Part A only: static packer identification). Part B — producing a decompressed derived artifact with a caller-supplied upx -d — is not included. It waits for the maintainer answer to the scope question in #3413 and would be a separate follow-up PR. This PR does not close the Part B request.

REA had no packer signal. Callers had to infer packing from scattered hints (few imports, odd section names), and different runs reached different conclusions. This adds a read-only inspect_packer_indicators MCP tool and rea inspect-packer-indicators CLI command for PE32, PE32+, ELF32 and ELF64. It returns per-region facts, named indicators and a likely_packed / not_observed / unknown verdict as observed Evidence.

Problem and expected behavior

For an admitted PE or ELF, the issue asks for:

  • per-section raw/virtual size, flags and Shannon entropy;
  • known packer section names and magic (UPX0/UPX1, UPX!) with byte offsets;
  • import count and whether imports are limited to loader-style APIs;
  • entry point in a non-first or writable+executable section;
  • overlay presence and size;
  • a verdict with supporting facts and explicit limitations, where an empty result does not mean the file is unpacked.

All of these are in the report:

Field Content
regions PE sections, or ELF PT_LOAD segments followed by any section headers: virtual address (PE RVA), virtual size, file range, raw flags, R/W/X, entropy (null when no file bytes back the region)
entry_point address, containing region, file offset
signatures packer section names (UPX, ASPack, MPRESS, PECompact, Petite, NsPack, RLPack, kkrunchy, MEW) and magic (UPX!, UPX info string) with offsets; up to 16 offsets listed, plus magic_matches_total
imports PE: libraries, function/ordinal counts, loader-style APIs present, only_loader_style. An inconsistent directory is reported as unreadable, not partially decoded. ELF: not_applicable
overlay trailing bytes after headers/sections/segments, with entropy and any PE certificate-table range
indicators / verdict strong = known name or magic. supporting = entry outside the first PE section, entry in a W+X region, entry outside every region, high-entropy executable region (≥ 7.2 bits/byte over ≥ 1 KiB), executable virtual-only region (virtual ≥ 4× file size and ≥ 64 KiB), loader-only imports, ELF executable without section headers, non-certificate overlay. likely_packed = any strong or ≥ 2 supporting; unknown = 1 supporting or part of the image unexamined; otherwise not_observed

Change and scope

  • src/native/packer/: a tolerant PE reader and an ELF reader (both classes and byte orders), the shared indicator and verdict derivation, and a provider over the existing readStableArtifact snapshot. Packed layouts such as a zero-raw UPX0 or no ELF section headers are reported rather than rejected. Section ranges past EOF are clamped and listed as limitations.
  • PackerIndicatorsService validates input and cross-checks provider output (every range inside the snapshot, every region reference resolves, overlay ends at EOF) before creating Evidence. This follows PeResourcesService.
  • The stable-file failure mapping that used to be private to PeResourcesProvider moved to src/native/stableFileFailure.ts, and both providers now use it. Error behavior for inspect_pe_resources is unchanged, and its existing tests pass.
  • MCP registration reuses the registerPeResourcesTool path. The tool contract, effects (evidence: no launch, no writes, no network), capability inventory, catalog provider entry (rea-packer-indicators) and CLI command are added.
  • Docs: a new section in docs/binary-diagnostics.md and a spec at docs/specs/3413-static-packer-identification/spec.md.

Intentionally not included:

Contract and boundary impact

  • Semantic owner and earliest changed stage: new domain schema src/domain/native/packerIndicators.ts, then the provider in src/native/packer/.
  • Contribution scope fit and linked maintainer decision: static identification only. The [Feature] Android APK unpacking support for Ijiami (爱加密) packer #2080 closing comment invites a detection-only proposal. The Part B scope decision is pending in [Feature] Static packer identification and UPX extraction as a derived artifact for PE/ELF #3413 and is not needed for this diff.
  • CLI and MCP/tool-catalog contract: new inspect_packer_indicators / inspect-packer-indicators. Input is path and max_file_bytes (default 64 MiB, max 512 MiB). No existing contract changes.
  • Provider, bridge, target-format, or platform compatibility: portable Node parser, with no external tool or engine.
  • Evidence, artifact, provenance, or reconstruction contract: Evidence subject is pe or elf with the snapshot SHA-256; confidence is observed, and limitations are copied into the Evidence. No derived artifacts.
  • Target selection, authority, upstream behavior, and cleanup details: explicit path only. Regular files only; symlinks are rejected; the snapshot is checked for identity.
  • Generated metadata, package, or installation impact: catalog builder adds the provider entry. metadata:check and mcp-catalog:check pass. No committed build outputs.

Expected effects:

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Tests added or updated:
    • src/native/packer/PackerIndicatorParser.test.ts (12 tests):
      • entropy;
      • ordinary PE32/PE32+ → not_observed;
      • a UPX-shaped PE (empty RWX UPX0, high-entropy RWX UPX1 holding the entry, UPX! magic, loader-only imports) → likely_packed with exact offsets;
      • a single vs. double supporting-indicator verdict;
      • an overlay vs. a certificate-only overlay;
      • an unreadable import directory → unknown;
      • an ordinary ELF64 → not_observed;
      • UPX-shaped ELF64 and ELF32;
      • non-PE/ELF and truncated headers → format failure;
      • hostile section ranges.
    • src/native/packer/PackerIndicatorReview.test.ts (11 tests, each failing on the previous head 453913b7f): shared entropy work budget for overlapping headers; one high-entropy fact for an ELF segment and its section over the same bytes; PE import descriptor leaving its section → unreadable; extended ELF section numbering (e_shnum == 0); trailing PT_NOTE not reported as overlay; section names bounded by the string table and invalid e_shstrndx reported; executable derived from IMAGE_SCN_MEM_EXECUTE only; section-name match locations point at the name bytes; SizeOfHeaders padding not treated as overlay; truncated certificate table not treated as complete.
    • tests/boundary/filesystem/packerIndicators.test.ts: Evidence through the composed service; directory, symlink, malformed, missing and relative paths → typed input errors; budget and cancellation failures.
    • toolEffects.test.ts and localToolContracts.test.ts include the new tool.
  • Fixtures: all images are hand-built in PackerIndicators.fixture.ts from deterministic filler. No packed program or third-party binary is committed.
  • User-visible CLI output (hand-built UPX-shaped PE, abbreviated):
{
  "verdict": { "status": "likely_packed", "basis": "Known packer signature observed (packer_section_name, packer_magic)." },
  "indicators": ["packer_section_name", "packer_section_name", "packer_magic", "entry_outside_first_section",
                 "entry_in_writable_executable_region", "virtual_only_region", "high_entropy_executable_region",
                 "loader_style_imports_only"],
  "regions": [
    { "name": "UPX0", "raw": { "offset": 0, "bytes": 0 }, "virtual_size": 131072, "writable": true, "executable": true, "entropy": null },
    { "name": "UPX1", "raw": { "offset": 512, "bytes": 8704 }, "virtual_size": 12288, "writable": true, "executable": true, "entropy": 7.8136 }
  ],
  "signatures": { "magic": [{ "family": "upx", "value": "UPX!", "location": { "offset": 517, "bytes": 4 } }] },
  "entry_point": { "address": "0x21010", "region_index": 1, "file_offset": 528 }
}

The same command on an ordinary one-section PE returns {"status":"not_observed", ...}.

  • Remaining proof gaps:
    • Not yet checked against real upx --best output of a self-built PE and ELF, which is the verification suggested in the issue. Thresholds (7.2 bits/byte, 4×/64 KiB) are chosen conservatively and may need tuning on real samples.
    • No real Windows host run; none is needed, because the parser is portable.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

After the review hardening commit ca8b671fb (Node 24.18.0, Linux x64):

  • npx tsc --noEmit -p .: passes.
  • npm run check:ci: passes.
  • npm run test:fast: 12384 passed, 9 skipped.
  • npx vitest run src/native/packer: 23 passed.

Earlier, on the initial head:

  • npx tsc --noEmit -p .: passes.
  • npm run build: passes.
  • npx vitest run src/native/packer tests/boundary/filesystem/packerIndicators.test.ts: 15 passed.
  • npx vitest run src/contracts tests/acceptance/tools/localToolContracts.test.ts tests/acceptance/applications/peResources.test.ts tests/boundary/filesystem tests/boundary/providers/artifactReadCleanupRetry.test.ts src/application/binaryDiagnostics: 2715 passed and 6 failed. All 6 failures are environmental and unrelated to this change:
    • zip is not installed;
    • ignored generated files docs/public/product-catalog.json and docs/verification/managed-conformance-manifest.json are absent from this checkout.
  • npx oxlint on changed paths: no errors. Some complexity/max-params warnings remain in the new readers, as is common elsewhere in the tree.
  • npm run verify:module-boundaries: passes.
  • npx knip: passes.
  • npm run metadata:check: passes.
  • npm run mcp-catalog:check: passes.
  • npx oxfmt on changed files: applied.

Compatibility, safety, and release

  • Breaking changes or migration steps: none. This only adds a tool.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable (no provider involved). Linux x64 host.
  • Package or release metadata impact: new tool in the catalog.
  • Security, privacy, process, or containment review: bounded read of one regular file. No process launch, no writes, no network. Import walking is bounded (4096 libraries, 65536 functions, 512-byte names), and magic output is capped.

Author readiness

Human owner: @Kizuno18

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

Add inspect_packer_indicators / inspect-packer-indicators, a read-only
report of packer indicators for PE32, PE32+, ELF32 and ELF64 images.
It reports per-region raw/virtual sizes, flags and Shannon entropy,
known packer section names and magic with file offsets, PE import
loader-style detection, entry-point placement and overlay range, and
derives a likely_packed / not_observed / unknown verdict with its
supporting indicators and limitations.

The image is never executed, emulated or unpacked. Producing a
decompressed derived artifact (Part B of morluto#3413) is not included.

Stable-file failure mapping is shared with inspect_pe_resources.
@kaoru0822-kitauji
kaoru0822-kitauji marked this pull request as ready for review October 15, 2026 06:17
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-15T06:23:04.517798Z aff9524 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 0/5 Tier: apex

[Medium impact] The change reaches a new bounded file-inspection workflow through both CLI and MCP.

Do not merge until the file-controlled searches are bounded and unused ELF headers are skipped.

Findings

  1. P1 Security Region searches freeze the server ▶
  2. P1 Security Import searches freeze the server ▶
  3. P1 Unused ELF headers break inspection ▶
  4. P2 Imports exceed their declared directory ▶
  5. P2 Missing ELF bytes go unreported ▶
  6. P2 PE header padding becomes overlay ▶
  7. P2 ELF header checks drift ▶
  8. P2 PE directory counts are repaired ▶
Fix with agent prompt
### Issue 1
src/native/packer/packerFacts.ts:186-190
`newVirtualRange` scans every earlier accepted range for each executable, virtual-only region. A roughly 2.6 MiB PE can declare 65,535 disjoint qualifying sections, causing about 2.1 billion checks. These run synchronously and block other MCP requests and cancellation. The entropy budget does not cover them. Use sorted ranges or add a shared work limit before these searches.

> **How this was verified:** File-controlled section headers reach the nested range searches, and the provider runs them synchronously on the MCP server thread.

### Issue 2
src/native/packer/PePackerReader.ts:63-71
Each import lookup scans `sections` again, and `cString` scans it twice. A PE can put 65,536 named imports in the last of 65,535 sections, causing over 12 billion section visits within the default file limit. This blocks other MCP requests, and cancellation cannot interrupt the walk. The separate import-count limits do not bound this combined work. Build a checked lookup index or enforce a shared lookup-work limit.

> **How this was verified:** File-controlled import entries repeatedly call the linear section searches, and the provider runs the entire walk synchronously on the MCP server thread.

### Issue 3
src/native/packer/ElfPackerReader.ts:142-143
`PT_NULL` entries are unused program-header slots; their remaining fields do not describe file bytes. This loop reads them anyway. An unused 64-bit `p_offset` above the supported number range rejects an otherwise valid ELF. Smaller leftover values can extend `mappedEnd` and hide a real overlay. Skip `PT_NULL` entries before reading their ranges.

### Issue 4
src/native/packer/PePackerReader.ts:294
`readImports` receives the import directory address but not its declared size. Its descriptor loop can leave the declared directory and accept a zero descriptor from unrelated mapped bytes. The report then calls the imports `parsed` rather than `unreadable`, giving callers apparently complete counts and loader-style facts from outside the directory. Pass the size through and bound the descriptor array separately from the referenced thunks and names.

### Issue 5
src/native/packer/ElfPackerReader.ts:150-153
The non-`PT_LOAD` branch discards `range.truncated`. An otherwise ordinary sectioned ELF with a cut-off `PT_NOTE` can return `not_observed` without any warning, although that declared range could not be examined completely. For file-backed segment types, preserve the truncation as a limitation and set `incomplete`, just as `region` already does.

### Issue 6
src/native/packer/PePackerReader.ts:undefined-191
`mappedEnd` starts at the section-table end rather than `SizeOfHeaders`. If every section has zero raw bytes, normal aligned header padding becomes an overlay and adds `overlay_present`. For a one-section PE32 with 512-byte headers, this mislabels the 96 bytes after the section table. Validate `SizeOfHeaders` and include it when setting the initial mapped end.

### Issue 7
src/native/packer/ElfPackerReader.ts:31-37
This reader checks class, byte order, and minimum length, but skips the ELF version and declared header-size checks. Changing an otherwise valid image's header size to zero still allows observed Evidence instead of the documented input error. `readElfFixedHeader` already checks these fields for both classes and byte orders. Reuse it before reading the tables so this new parser does not maintain a weaker copy.

### Issue 8
src/native/packer/PePackerReader.ts:196-199
`Math.min` silently shrinks a directory count that exceeds the optional header's available slots. A header claiming 16 directories while providing none is accepted, and imports become `absent` without a limitation. Reject this inconsistent header instead of repairing its count. The existing PE reader already performs that check.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds read-only PE and ELF packer inspection through MCP and the CLI.

  • PE and ELF inspections report packer clues with a cautious verdict.
  • Callers can run packer inspection from the CLI or MCP.
  • Stable-file reads share the same caller-facing error mapping.
  • HTTP cleanup waits and Flutter path checks keep their behavior.

No new runtime checks were run. Whether another PR replaces this work could not be confirmed.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[MCP or CLI request] --> B[Check path and byte limit]
  B --> C[Read stable snapshot]
  C --> D[Read PE or ELF facts]
  D --> E[Find signatures and derive indicators]
  E --> F[Check report and create Evidence]
  F --> G[Return report]
Loading

Reviews (2) · Last reviewed commit: "fix(native): harden packer readers again..." · Reviewed by Greptile

Comment thread src/native/packer/ElfPackerReader.ts Resolved
Comment thread src/native/packer/packerFacts.ts Resolved
Comment thread src/native/packer/PePackerReader.ts Resolved
Comment thread src/native/packer/ElfPackerReader.ts Resolved
Comment thread src/native/packer/ElfPackerReader.ts Resolved
Comment thread src/native/packer/PePackerReader.ts Outdated
let incomplete = false;
const sections: Section[] = [];
const regions: PackerRegion[] = [];
let mappedEnd = table + sectionCount * 40;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 PE header padding becomes overlay

mappedEnd starts at the section-table end rather than SizeOfHeaders. If every section has zero raw bytes, normal aligned header padding becomes an overlay and adds overlay_present. For a one-section PE32 with 512-byte headers, this mislabels the 96 bytes after the section table. Validate SizeOfHeaders and include it when setting the initial mapped end.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/packer/PePackerReader.ts
Line: 191

Comment:
**PE header padding becomes overlay**

`mappedEnd` starts at the section-table end rather than `SizeOfHeaders`. If every section has zero raw bytes, normal aligned header padding becomes an overlay and adds `overlay_present`. For a one-section PE32 with 512-byte headers, this mislabels the 96 bytes after the section table. Validate `SizeOfHeaders` and include it when setting the initial mapped end.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment thread src/native/packer/PePackerReader.ts Resolved
Comment on lines +24 to +30
if (bytes.length < 52) formatFailure("Truncated ELF header.");
const elf64 = bytes[4] === 2;
if (bytes[4] !== 1 && !elf64) formatFailure("Unsupported ELF class.");
const little = bytes[5] === 1;
if (bytes[5] !== 1 && bytes[5] !== 2)
formatFailure("Unsupported ELF byte order.");
if (elf64 && bytes.length < 64) formatFailure("Truncated ELF64 header.");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 ELF header checks drift

This reader checks class, byte order, and minimum length, but skips the ELF version and declared header-size checks. Changing an otherwise valid image's header size to zero still allows observed Evidence instead of the documented input error. readElfFixedHeader already checks these fields for both classes and byte orders. Reuse it before reading the tables so this new parser does not maintain a weaker copy.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/packer/ElfPackerReader.ts
Line: 24-30

Comment:
**ELF header checks drift**

This reader checks class, byte order, and minimum length, but skips the ELF version and declared header-size checks. Changing an otherwise valid image's header size to zero still allows observed Evidence instead of the documented input error. `readElfFixedHeader` already checks these fields for both classes and byte orders. Reuse it before reading the tables so this new parser does not maintain a weaker copy.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +174 to +177
const directoryCount = Math.min(
bytes.readUInt32LE(optional + directoriesAt - 4),
Math.floor((optionalSize - directoriesAt) / 8),
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 PE directory counts are repaired

Math.min silently shrinks a directory count that exceeds the optional header's available slots. A header claiming 16 directories while providing none is accepted, and imports become absent without a limitation. Reject this inconsistent header instead of repairing its count. The existing PE reader already performs that check.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/packer/PePackerReader.ts
Line: 174-177

Comment:
**PE directory counts are repaired**

`Math.min` silently shrinks a directory count that exceeds the optional header's available slots. A header claiming 16 directories while providing none is accepted, and imports become `absent` without a limitation. Reject this inconsistent header instead of repairing its count. The existing PE reader already performs that check.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@CassieFox23

Copy link
Copy Markdown
Contributor

TL;DR: Thanks, Kizuno18. On current main this PR fails to compile on one stale line. With my one-line fix, all 56 tests pass, but I did not check Greptile's parser findings.

The compile failure

Main c7f6b8b (#4179) plus this PR's diff fails npm run typecheck:

src/cli/binaryDiagnosticsCommands.ts(75,27): error TS2304: Cannot find name 'resolve'.

Main now uses absoluteCallerPath and no longer imports resolve. The PR's packer command still calls resolve(args.path). The diff applies with offsets and fuzz 1 on two files, and no rejects. It is a rebase issue, not a design issue.

Results

Every row below ran on main plus the PR diff plus one line changed by me. I changed line 75 to absoluteCallerPath(args.path). After that change, npm run typecheck passes. That change is mine, not the author's.

Check Result
New packer parser tests 12 passed
New packer boundary tests 3 passed
Tool effects tests 6 passed
Existing PE resource tests (the refactored provider), 5 files 35 passed
Those 8 files together 56 passed
Local tool contracts, acceptance 5 passed
PE resource and tool effects set on clean main, before the PR 41 passed
  • The 41 tests on clean main are the 35 PE tests plus the 6 tool effects tests. All 41 also pass after the PR, and the 15 new packer tests make 56. So the PE resources refactor kept behavior for these tests.
  • No file I ran calls doctor. No test makes a real network call. The acceptance files start only local processes and local servers.
  • Real CI did not run on this PR. Only the Greptile review check shows. Greptile scored it 0 of 5, with 12 inline findings on parser correctness. I did not confirm or refute them. The named tests use only the PR's own synthetic fixtures.
  • The PR branch is far behind main. So I tested main with the diff applied, not the branch head.

Not run

  • Real packed binaries, such as UPX output, and real PE or ELF files.
  • The packer CLI command end to end. None of the named tests call it.
  • The Greptile findings, such as the overlapping ELF regions.
  • Docs checks, the full suite, and every other test file.
  • Node 22 and Node 26. Windows and macOS.

Thanks, Kizuno18, for the large, well-tested PE and ELF work and the spec.

Test setup
Commands
PATH=~/.local/opt/node24/bin:$PATH
patch -p1 -d <tree> < 3775.diff
npm run typecheck     # fails: TS2304 'resolve' (line 75)
# my one-line fix: resolve(args.path) -> absoluteCallerPath(args.path)
npm run typecheck     # passes
npm run build && npm run test:prepare
npm run test:focused -- src/native/packer/PackerIndicatorParser.test.ts \
  tests/boundary/filesystem/packerIndicators.test.ts src/contracts/toolEffects.test.ts \
  src/native/pe/PeResourceParser.test.ts src/application/binaryDiagnostics/PeResourcesService.test.ts \
  tests/boundary/filesystem/peResources.test.ts tests/acceptance/applications/peResources.test.ts \
  tests/boundary/cli/callerPathSymlinkParentCli.test.ts      # 56 passed
npm run test:focused -- tests/acceptance/tools/localToolContracts.test.ts   # 5 passed
# before: clean main, same PE and tool effects files (6 files)   # 41 passed

🤖 Generated with Claude Code (Sonnet 5.5, verified by Opus 5.5) 🦊

…identification

# Conflicts:
#	src/contracts/toolEffects.test.ts
#	src/native/pe/PeResourcesProvider.ts
#	src/server/createServer.ts
Bound entropy work across overlapping regions, count overlapping ELF
views once, keep PE import walks inside their section mappings, decode
extended ELF section numbering, bound overlays by non-load segments,
keep ELF names inside the string table, derive PE execute from
MEM_EXECUTE only, report name locations, honor SizeOfHeaders and
mark truncated certificate tables incomplete.
Comment on lines +186 to +190
const newVirtualRange = (region: PackerRegion) => {
const start = BigInt(region.virtual_address);
const end = start + BigInt(region.virtual_size);
if (virtualRanges.some((r) => start < r.end && r.start < end)) return false;
virtualRanges.push({ start, end });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Region searches freeze the server

newVirtualRange scans every earlier accepted range for each executable, virtual-only region. A roughly 2.6 MiB PE can declare 65,535 disjoint qualifying sections, causing about 2.1 billion checks. These run synchronously and block other MCP requests and cancellation. The entropy budget does not cover them. Use sorted ranges or add a shared work limit before these searches.

How this was verified: File-controlled section headers reach the nested range searches, and the provider runs them synchronously on the MCP server thread.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/packer/packerFacts.ts
Line: 186-190

Comment:
**Region searches freeze the server**

`newVirtualRange` scans every earlier accepted range for each executable, virtual-only region. A roughly 2.6 MiB PE can declare 65,535 disjoint qualifying sections, causing about 2.1 billion checks. These run synchronously and block other MCP requests and cancellation. The entropy budget does not cover them. Use sorted ranges or add a shared work limit before these searches.

> **How this was verified:** File-controlled section headers reach the nested range searches, and the provider runs them synchronously on the MCP server thread.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +63 to +71
for (const section of sections) {
const extent = Math.max(section.virtualSize, section.size);
if (rva >= section.rva && rva < section.rva + extent) {
const delta = rva - section.rva;
if (delta + length > section.size)
throw new ImportFailure(
`RVA 0x${rva.toString(16)} + ${String(length)} is not backed by file bytes of its section.`,
);
return section.offset + delta;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Import searches freeze the server

Each import lookup scans sections again, and cString scans it twice. A PE can put 65,536 named imports in the last of 65,535 sections, causing over 12 billion section visits within the default file limit. This blocks other MCP requests, and cancellation cannot interrupt the walk. The separate import-count limits do not bound this combined work. Build a checked lookup index or enforce a shared lookup-work limit.

How this was verified: File-controlled import entries repeatedly call the linear section searches, and the provider runs the entire walk synchronously on the MCP server thread.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/packer/PePackerReader.ts
Line: 63-71

Comment:
**Import searches freeze the server**

Each import lookup scans `sections` again, and `cString` scans it twice. A PE can put 65,536 named imports in the last of 65,535 sections, causing over 12 billion section visits within the default file limit. This blocks other MCP requests, and cancellation cannot interrupt the walk. The separate import-count limits do not bound this combined work. Build a checked lookup index or enforce a shared lookup-work limit.

> **How this was verified:** File-controlled import entries repeatedly call the linear section searches, and the provider runs the entire walk synchronously on the MCP server thread.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

? entrySection.offset + entryDelta
: null,
firstSectionIndex: sectionCount > 0 ? 0 : undefined,
imports: readImports(bytes, sections, directory(1).value, plus),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Imports exceed their declared directory

readImports receives the import directory address but not its declared size. Its descriptor loop can leave the declared directory and accept a zero descriptor from unrelated mapped bytes. The report then calls the imports parsed rather than unreadable, giving callers apparently complete counts and loader-style facts from outside the directory. Pass the size through and bound the descriptor array separately from the referenced thunks and names.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/packer/PePackerReader.ts
Line: 294

Comment:
**Imports exceed their declared directory**

`readImports` receives the import directory address but not its declared size. Its descriptor loop can leave the declared directory and accept a zero descriptor from unrelated mapped bytes. The report then calls the imports `parsed` rather than `unreadable`, giving callers apparently complete counts and loader-style facts from outside the directory. Pass the size through and bound the descriptor array separately from the referenced thunks and names.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +150 to +153
const range = clampRange(bytes.length, offset, declared);
if (range.bytes > 0)
mappedEnd = Math.max(mappedEnd, range.offset + range.bytes);
continue;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Missing ELF bytes go unreported

The non-PT_LOAD branch discards range.truncated. An otherwise ordinary sectioned ELF with a cut-off PT_NOTE can return not_observed without any warning, although that declared range could not be examined completely. For file-backed segment types, preserve the truncation as a limitation and set incomplete, just as region already does.

Knowledge Base Used: Binary diagnostics and comparison

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/packer/ElfPackerReader.ts
Line: 150-153

Comment:
**Missing ELF bytes go unreported**

The non-`PT_LOAD` branch discards `range.truncated`. An otherwise ordinary sectioned ELF with a cut-off `PT_NOTE` can return `not_observed` without any warning, although that declared range could not be examined completely. For file-backed segment types, preserve the truncation as a limitation and set `incomplete`, just as `region` already does.

**Knowledge Base Used:** [Binary diagnostics and comparison](https://app.greptile.com/pre/-/custom-context/knowledge-base/morluto/rea/-/docs/binary-diagnostics-and-comparison.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +142 to +143
const offset = size(word(elf64 ? base + 8 : base + 4), "segment offset");
if (u32(base) !== PT_LOAD) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Unused ELF headers break inspection

PT_NULL entries are unused program-header slots; their remaining fields do not describe file bytes. This loop reads them anyway. An unused 64-bit p_offset above the supported number range rejects an otherwise valid ELF. Smaller leftover values can extend mappedEnd and hide a real overlay. Skip PT_NULL entries before reading their ranges.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/packer/ElfPackerReader.ts
Line: 142-143

Comment:
**Unused ELF headers break inspection**

`PT_NULL` entries are unused program-header slots; their remaining fields do not describe file bytes. This loop reads them anyway. An unused 64-bit `p_offset` above the supported number range rejects an otherwise valid ELF. Smaller leftover values can extend `mappedEnd` and hide a real overlay. Skip `PT_NULL` entries before reading their ranges.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@morluto morluto added area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior enhancement New feature or request labels Nov 23, 2026
@morluto

morluto commented Nov 24, 2026

Copy link
Copy Markdown
Owner

@Kizuno18 thanks for the PR — there are 8 open review threads here:

Could you address or reply to these? Once they're resolved and CI is green we can take another look.
cc @gensokyo-dev @dandgabr

@morluto

morluto commented Nov 24, 2026

Copy link
Copy Markdown
Owner

@Kizuno18 also, this branch has merge conflicts with main — please resolve those along with the open threads.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Static packer identification and UPX extraction as a derived artifact for PE/ELF

3 participants