Repository navigation
Conversation
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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
[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
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.SummaryAdds read-only PE and ELF packer inspection through MCP and the CLI.
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]
Reviews (2) · Last reviewed commit: "fix(native): harden packer readers again..." · Reviewed by Greptile |
| let incomplete = false; | ||
| const sections: Section[] = []; | ||
| const regions: PackerRegion[] = []; | ||
| let mappedEnd = table + sectionCount * 40; |
There was a problem hiding this 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.
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.| 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."); |
There was a problem hiding this comment.
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.| const directoryCount = Math.min( | ||
| bytes.readUInt32LE(optional + directoriesAt - 4), | ||
| Math.floor((optionalSize - directoriesAt) / 8), | ||
| ); |
There was a problem hiding this 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.
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.|
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 failureMain c7f6b8b (#4179) plus this PR's diff fails Main now uses ResultsEvery row below ran on main plus the PR diff plus one line changed by me. I changed line 75 to
Not run
Thanks, Kizuno18, for the large, well-tested PE and ELF work and the spec. Test setup
CommandsPATH=~/.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.
| 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 }); |
There was a problem hiding this 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.
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.| 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; |
There was a problem hiding this 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.
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), |
There was a problem hiding this 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.
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.| const range = clampRange(bytes.length, offset, declared); | ||
| if (range.bytes > 0) | ||
| mappedEnd = Math.max(mappedEnd, range.offset + range.bytes); | ||
| continue; |
There was a problem hiding this 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
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.| const offset = size(word(elf64 ? base + 8 : base + 4), "segment offset"); | ||
| if (u32(base) !== PT_LOAD) { |
There was a problem hiding this 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.
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.|
@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. |
|
@Kizuno18 also, this branch has merge conflicts with |
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_indicatorsMCP tool andrea inspect-packer-indicatorsCLI command for PE32, PE32+, ELF32 and ELF64. It returns per-region facts, named indicators and alikely_packed/not_observed/unknownverdict asobservedEvidence.Problem and expected behavior
For an admitted PE or ELF, the issue asks for:
UPX0/UPX1,UPX!) with byte offsets;All of these are in the report:
regionsPT_LOADsegments followed by any section headers: virtual address (PE RVA), virtual size, file range, raw flags, R/W/X, entropy (nullwhen no file bytes back the region)entry_pointsignaturesUPX!, UPX info string) with offsets; up to 16 offsets listed, plusmagic_matches_totalimportsonly_loader_style. An inconsistent directory is reported asunreadable, not partially decoded. ELF:not_applicableoverlayindicators/verdictstrong= 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; otherwisenot_observedChange 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 existingreadStableArtifactsnapshot. Packed layouts such as a zero-rawUPX0or no ELF section headers are reported rather than rejected. Section ranges past EOF are clamped and listed as limitations.PackerIndicatorsServicevalidates input and cross-checks provider output (every range inside the snapshot, every region reference resolves, overlay ends at EOF) before creating Evidence. This followsPeResourcesService.PeResourcesProvidermoved tosrc/native/stableFileFailure.ts, and both providers now use it. Error behavior forinspect_pe_resourcesis unchanged, and its existing tests pass.registerPeResourcesToolpath. 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/binary-diagnostics.mdand a spec atdocs/specs/3413-static-packer-identification/spec.md.Intentionally not included:
Contract and boundary impact
src/domain/native/packerIndicators.ts, then the provider insrc/native/packer/.inspect_packer_indicators/inspect-packer-indicators. Input ispathandmax_file_bytes(default 64 MiB, max 512 MiB). No existing contract changes.peorelfwith the snapshot SHA-256; confidence isobserved, and limitations are copied into the Evidence. No derived artifacts.metadata:checkandmcp-catalog:checkpass. No committed build outputs.Expected effects:
Evidence and regression coverage
src/native/packer/PackerIndicatorParser.test.ts(12 tests):not_observed;UPX0, high-entropy RWXUPX1holding the entry,UPX!magic, loader-only imports) →likely_packedwith exact offsets;unknown;not_observed;src/native/packer/PackerIndicatorReview.test.ts(11 tests, each failing on the previous head453913b7f): 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); trailingPT_NOTEnot reported as overlay; section names bounded by the string table and invalide_shstrndxreported; executable derived fromIMAGE_SCN_MEM_EXECUTEonly; section-name match locations point at the name bytes;SizeOfHeaderspadding 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.tsandlocalToolContracts.test.tsinclude the new tool.PackerIndicators.fixture.tsfrom deterministic filler. No packed program or third-party binary is committed.{ "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", ...}.upx --bestoutput 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.For evidence-bearing changes:
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:zipis not installed;docs/public/product-catalog.jsonanddocs/verification/managed-conformance-manifest.jsonare absent from this checkout.npx oxlinton 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 oxfmton changed files: applied.Compatibility, safety, and release
Author readiness
Human owner: @Kizuno18
Before merge
type(scope): outcome.