Skip to content

feat(firmware): decode ESP-IDF Non-Volatile Storage (NVS) flash partitions - #14436

Merged
morluto merged 9 commits into
morluto:mainfrom
liziye627-design:feat/esp-nvs-partition-decoder
Nov 27, 2026
Merged

morluto merged 9 commits into
morluto:mainfrom
liziye627-design:feat/esp-nvs-partition-decoder

Conversation

@liziye627-design

@liziye627-design liziye627-design commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Advances #3615 (Acceptance Criterion 3: Non-Volatile Storage key-value decoding) and #7955 by adding inspect_esp_nvs (rea inspect-esp-nvs), a portable, read-only static decoder for ESP-IDF v1 and v2 Non-Volatile Storage (data/nvs) flash partitions and 4096-byte aligned ESP32/ESP8266 flash dump slices.

Problem and expected behavior

inspect_artifact on an esp-flash-image dump locates and carves partitions/nvs.bin as raw bytes, leaving analysts to invoke external Python nvs_partition_gen.py or custom scripts to inspect persisted device configuration, namespace tables, calibration values, and multi-chunk blobs.

With inspect_esp_nvs:

  • Decodes 4096-byte NVS pages (empty, active, full, freeing, or corrupt_or_encrypted), sequence numbers, v1 (0xff) / v2 (0xfe) format markers, and 2-bit entry-state bitmaps (empty, written, erased).
  • Verifies ESP-IDF esp_rom_crc32_le(0xFFFFFFFF, ...) checksums across page headers ([4..28)), 32-byte item headers ([0..4) || [8..32)), and variable-length payloads, advancing slot-by-slot across damaged item headers so subsequent intact keys remain decoded.
  • Reconstructs namespace definitions (ns_index = 0), primitive integers (u8..u64, i8..i64), UTF-8 strings (sz), v1 single-page blobs, and v2 multi-page BLOB_IDX + BLOB_DATA payloads in linear time with streaming SHA-256 digests, bounded 128-byte hex previews, and explicit blob_data_orphan / missing_chunks reporting.
  • Retains complete decoded NVS Evidence while supporting detail: "summary", bounded inline max_entries, --evidence_output, and inspect_analysis_view (kind: "esp-nvs" and kind: "evidence-json").
  • Rejects explicit partition_offset / partition_bytes selections that extend past EOF rather than silently truncating, preserves caller-selected local values verbatim without guessing secrecy from key names, and reports XTS-AES encrypted or corrupt pages explicitly as corrupt_or_encrypted (coverage.status: "partial").

Change and scope

Follow the contribution scope.
Read-only static byte inspection over a caller-selected local file (not applicable for execution, injection, mutation, or protection recovery). Encrypted NVS (nvs_keys XTS-AES) is not decrypted.

Contract and boundary impact

  • Semantic owner and earliest changed stage: src/domain/firmware/espNvs.ts, src/domain/firmware/espNvsItemDecoder.ts, src/domain/firmware/espNvsParser.ts, and src/domain/analysisView/espNvsView.ts own page/bitmap/CRC32 validation, linear v2 blob reassembly, and retained-Evidence view paging.
  • Contribution scope fit and linked maintainer decision: Read-only static firmware diagnostic advancing [Feature] Hardware and Embedded Reverse Engineering: ESP32 firmware extraction, NVS decoding, raw flash mapping, and bus capture analysis #3615 and [Roadmap] Embedded firmware: make REA work on the devices around us #7955.
  • CLI and MCP/tool-catalog contract: Adds inspect_esp_nvs (rea inspect-esp-nvs <path> [--partition-offset N] [--partition-bytes N] [--max-entries N] [--max-file-bytes N] [--detail complete|summary] [--evidence_output PATH]) and inspect_analysis_view kind: "esp-nvs".
  • Provider, bridge, target-format, or platform compatibility: Portable Node.js provider (ESP_NVS_PROVIDER in src/firmware/espNvs/EspNvsProvider.ts), registered in capability conformance and provider lifecycle coverage.
  • Evidence, artifact, provenance, or reconstruction contract: Emits SHA-256-bound Evidence with caller-selected parameters, file-offset-range partition bounds, retained parent evidence_links when inline max_entries or detail: "summary" bounds delivery, and explicit completeness ("complete" | "missing_chunks" | "crc_mismatch").
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): Uses ArtifactResourceScope and readStableArtifact; max_file_bytes refusals report typed details.limit (control_kind: "parameter"), and out-of-bounds partition_offset / partition_bytes fail closed with AnalysisInputError.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact: Authored guide added at docs/guides/firmware/esp-nvs.md, skill guidance updated in .agents/skills/reverse-engineer-anything/references/native-and-artifacts.md (synced to .cursor-plugin/), and advertised schema summary added at scripts/verify/advertised-schemas/tools/inspect_esp_nvs.json. Ignored generated outputs remain uncommitted.

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/domain/firmware/espNvs.test.ts (executed): namespace registration, u32, sz, and multi-page v2 BLOB_IDX + BLOB_DATA reassembly, 7,812-item chunkCount=255 linear-time regression, damaged span byte slot-by-slot recovery of following intact keys, out-of-bounds partitionBytes refusal, and encrypted/corrupt page handling.
    • src/application/binaryDiagnostics/EspNvsService.test.ts (executed): digest-bound Evidence, callerAnalysisParameters filtering, inline max_entries with retained parent Evidence, max_file_bytes control_kind: "parameter" recovery, and mid-run AbortController cancellation.
    • tests/boundary/mcp/espNvsMcpCli.test.ts (executed): end-to-end advertised MCP and public CLI parity over a non-zero partition_offset flash slice, retained Evidence recovery via inspect_analysis_view (kind: "esp-nvs" and kind: "evidence-json"), detail: "summary", CLI --evidence_output, and out-of-bounds partition_bytes failure.
    • tests/conformance/providerCapabilityCases.ts & tests/support/providerLifecycleCoverage.ts (executed): registered espNvs and "rea-esp-nvs".
  • Base reproduction or other evidence: Prior to this change, REA carved nvs.bin as opaque bytes without decoding ESP-IDF NVS pages or records ([Feature] Hardware and Embedded Reverse Engineering: ESP32 firmware extraction, NVS decoding, raw flash mapping, and bus capture analysis #3615).
  • Remaining proof gaps: Verified against synthetic ESP-IDF v2 NVS pages and corrupt/encrypted negative controls; XTS-AES decryption with nvs_keys is intentionally out of scope.

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

  • node scripts/run-typescript.mjs --noEmit && node scripts/run-typescript.mjs --noEmit -p tsconfig.scripts.json — passed
  • npx oxlint -c .oxlintrc.json --quiet <changed-files> && npx oxfmt --check <changed-files> — passed
  • node scripts/verify-module-boundaries.mjs && node scripts/verify/rea-numeric-limits.mjs && node scripts/verify/fixed-ceilings.mjs && node scripts/verify/architecture-guards.mjs — passed
  • npx vitest run src/domain/firmware/espNvs.test.ts src/application/binaryDiagnostics/EspNvsService.test.ts src/contracts/analysisDetail.test.ts tests/boundary/mcp/espNvsMcpCli.test.ts tests/boundary/mcp/advertisedDialect.test.ts tests/conformance/providerCapabilityConformance.test.ts tests/evaluation/providerLifecycleCoverage.test.ts tests/evaluation/fixedCeilingGuard.test.ts tests/evaluation/moduleReExportGuard.test.ts tests/boundary/cli/cliContractCommandParity.test.ts tests/boundary/mcp/enhancedTools.01-lists-the-complete-target-open.test.ts — passed (11 files, 1,144 tests)

Compatibility, safety, and release

  • Breaking changes or migration steps: None; additive CLI/MCP inspection operation.
  • Real Hopper/Ghidra, browser, or OS coverage: Exercised on Windows x64; portable Node implementation.
  • Package or release metadata impact: Updated .cursor-plugin skill mirror and scripts/verify/advertised-schemas/tools/inspect_esp_nvs.json.
  • Security, privacy, process, or containment review: Linear-time O(N+M) v2 blob reassembly with streaming SHA-256 and 128-byte hex previews, cancellation checkpoints across pages and blob records, slot-by-slot CRC validation before trusting span, and ArtifactResourceScope handle cleanup.

Author readiness

Human owner: @liziye627-design

  • 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.

@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

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

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-25T07:44:39.744966Z
We couldn’t complete this review. Comment @codex review to try again.
79ed9e4 PR opened
ℹ️ 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@greptile-apps

greptile-apps Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The reviewed changes appear safe to merge; no blocking issue remains.RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[Medium impact] The reviewed changes appear safe to merge; no blocking issue remains.

Summary

Adds read-only ESP-IDF NVS decoding through CLI and MCP, with checksum checks, blob reconstruction, retained Evidence, and paged views.

  • ESP-IDF NVS pages now decode into namespaces, stored values, and blob summaries.
  • CLI and MCP callers can inspect NVS ranges and page full reports.
  • Artifact inspection now points ESP flash dumps to populated NVS partitions.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[CLI or MCP request] --> B[Check caller inputs]
  B --> C[Read stable file and digest]
  C --> D[Check selected partition bounds]
  D --> E[Decode pages and check checksums]
  E --> F[Reassemble blobs and derive coverage]
  E --> G{Decoded size fits budget?}
  F --> G
  G -->|No| H[Return typed resource refusal]
  G -->|Yes| I[Create complete Evidence]
  I --> J[Complete inline result]
  I --> K[Retained Evidence with summary or paging]
Loading

Reviews (9) · Last reviewed commit: "fix(firmware): bound decoded NVS represe..." · Reviewed by Greptile

Comment thread src/firmware/espNvs/EspNvsProvider.ts Resolved
Comment thread src/domain/firmware/espNvsParser.ts Resolved
@morluto morluto added area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior enhancement New feature or request labels Nov 26, 2026
@liziye627-design
liziye627-design force-pushed the feat/esp-nvs-partition-decoder branch 3 times, most recently from 735976c to 944cd20 Compare November 26, 2026 20:48
…tions

Add offline ESP-IDF v1/v2 NVS partition decoding via `inspect_esp_nvs`
(`rea inspect-esp-nvs`) with complete retained Evidence, `detail: "summary"`
and `inspect_analysis_view` (`kind: "esp-nvs"`) paging, linear O(N+M) v2
multi-chunk blob reassembly, slot-by-slot CRC recovery past damaged item
headers, fail-closed `partition_offset`/`partition_bytes` bounds validation,
and full capability conformance and provider lifecycle coverage.
@liziye627-design
liziye627-design force-pushed the feat/esp-nvs-partition-decoder branch from 445fee6 to 2fe372e Compare November 27, 2026 16:31
Comment thread src/cli/binaryDiagnosticsCommands.ts Resolved
Comment thread src/domain/analysisView/espNvsView.ts Resolved
…ption layout

Page states now follow ESP-IDF's PageState constants (corrupt 0xfffffff0,
invalid 0, unknown otherwise), with the header CRC and whether entries were
walked reported separately. NVS encryption keeps page headers in plaintext,
so an encrypted page is reported as a valid page whose item headers are all
unreadable instead of as a header CRC failure.

Item headers follow Item::checkHeaderConsistency: span per type, BLOB_IDX
and BLOB_DATA chunk-index rules, and a variable item's span matching its
length. An inconsistent header is not trusted and the walk advances one
slot. Unrecognized types are no longer entries with unknown values, and
namespace index 0 items that are not definitions are reported instead of
skipped silently.

Adds float (0x24) and double (0x28) items, keeps the bytes of non-UTF-8
strings and keys, and marks older copies of a key superseded by a higher
page sequence number or a later slot. Spec constants are named once and
v2 blob reassembly moves to its own module.
@morluto

morluto commented Nov 27, 2026

Copy link
Copy Markdown
Owner

Maintainer review of the NVS decoder, checked against ESP-IDF's own sources. Fixes are in commit 0e7a656 on this branch.

Heads-up: commit 445fee6 was dropped when this branch was force-pushed. I reapplied it on top of your rebased head, so please pull before your next push.

Defects fixed

  1. Wrong encryption claim. The limitation said encrypted pages fail their header CRC32. NVS encryption leaves the page header and the entry-state bitmap in plaintext and encrypts each 32-byte entry. So an encrypted page has a valid header and every item header is unreadable. Such a page is now reported that way, with an anomaly saying it looks encrypted. A failed header CRC is attributed to whole-flash encryption or damage.

  2. Page states. ESP-IDF defines CORRUPT as 0xfffffff0 and INVALID as 0. Both used to collapse into corrupt_or_encrypted.

    • state is now empty, active, full, freeing, corrupt, invalid or unknown.
    • The header CRC is kept as its own fact, header_crc_valid.
    • The new entries_decoded field says whether the page was walked.
    • corrupt_or_encrypted_page_count is renamed undecoded_page_count.
  3. Item header consistency. An item header with a valid CRC can still be inconsistent. ESP-IDF rejects such headers in Item::checkHeaderConsistency, and the decoder now applies the same rules in one function:

    • each type's required span;
    • BLOB_IDX chunk index 0xff, with a size bound;
    • BLOB_DATA chunk index never 0xff;
    • a variable item's span equal to 1 + ceil(len/32), within the page.

    An inconsistent header is not trusted, and the walk advances one slot. Unrecognized types used to become unknown entries whose declared span was trusted.

  4. Silent skips:

    • Namespace-index-0 items other than namespace definitions are now reported instead of skipped.
    • The ILLEGAL entry state (0b01) is now counted, as illegal_slot_count.
    • Uninitialized pages whose bitmap marks slots used are now flagged.
  5. Missing types. FLOAT (0x24) and DOUBLE (0x28) are now decoded into value_float. They exist in current ESP-IDF (nvs_handle.hpp ItemType).

  6. Lossy text. Strings and keys used to be decoded with replacement characters.

    • A string that is not valid UTF-8 now keeps its bytes as a digest and preview, and gets an anomaly.
    • A key without a NUL, or that is not valid UTF-8, is shown byte-for-byte as Latin-1, with an anomaly.
  7. Stale copies. An interrupted rewrite or page move leaves two written copies of a key. Each entry now has a superseded flag that marks the older copy: a lower page sequence number, or an earlier slot on the same page.

Brittleness fixed

  • Duplicated decision. Variable-length type checks were repeated in several places. They are now one isVariableLengthType, as in ESP-IDF.
  • Magic numbers. Layout constants (32/64/126/4096) and type codes were repeated across files. They are now named once, after nvs_constants.h and ItemType.
  • Primitive types. A switch is replaced by one PRIMITIVE_TYPES table. The consistency check and the decoder both use it.
  • Shared helpers. The code now uses REA's shared BinaryReader, the strictUtf8 helpers and byteToHex instead of local copies.
  • File split. v2 blob reassembly moved to its own module, espNvsBlobReassembly.ts.

Left as is

  • reassembleNvsV2Blobs keeps its existing complexity lint warnings. I only moved it.
  • parseEspNvsPartition is slightly over the function-length lint limit.

Tests

There are six new domain regressions: float/double, page states, an encrypted-layout page, inconsistent headers, supersession, and non-UTF-8 bytes. The existing tests are updated. These pass:

  • test:local on espNvs.test.ts and EspNvsService.test.ts;
  • test:focused on espNvsMcpCli.test.ts;
  • check:fast, docs:check, and the advertised-schema check.

Sources

  • espressif/esp-idf components/nvs_flash:
    • private_include/nvs_constants.h: page and entry states, offsets.
    • src/nvs_types.cpp: Item::checkHeaderConsistency.
    • include/nvs_handle.hpp and include/nvs.h: item types.
    • src/nvs_page.hpp.
  • DeepWiki on espressif/esp-idf: the NVS encryption layout (header and bitmap in plaintext, entries encrypted).
  • ESP-IDF's offline nvs_partition_tool/nvs_parser.py. It disagrees with the firmware: it labels state 0 "Corrupted" and has no 0xfffffff0. REA follows the firmware constants, and the guide notes the difference.

Comment thread src/domain/firmware/espNvsParser.ts Resolved
Comment thread src/domain/firmware/espNvsParser.ts Resolved
Comment thread src/firmware/espNvs/EspNvsProvider.ts Resolved
Comment thread src/domain/firmware/espNvsParser.ts Resolved
Comment thread src/domain/firmware/espNvsParser.ts Resolved
liziye627-design and others added 2 commits November 28, 2026 02:02
… dropping them

An interrupted page move leaves an older copy of a BLOB_DATA chunk next to
the copy a recovered blob used. a2e8fc1 stopped reporting it as an
orphan by skipping every chunk with a claimed index, which also dropped the
older copy silently, including one whose bytes differ. It is now reported
as blob_data_copy, superseded, with its own CRC-based completeness, and
does not make coverage partial.
@morluto
morluto enabled auto-merge (squash) November 27, 2026 18:27
auto-merge was automatically disabled November 27, 2026 19:16

Head branch was pushed to by a user without write access

Comment thread src/domain/firmware/espNvsParser.ts Resolved
Comment thread src/domain/firmware/espNvsParser.ts Resolved
@morluto
morluto enabled auto-merge (squash) November 27, 2026 20:01
@morluto
morluto merged commit f6cf6a8 into morluto:main Nov 27, 2026
58 checks passed
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.

2 participants