Skip to content

fix(hid-rp): ReportMap::parse refuses malformed and oversized descriptors - #964

Merged
finger563 merged 2 commits into
mainfrom
fix/hid-rp-truncated-descriptor
Dec 2, 2026
Merged

finger563 merged 2 commits into
mainfrom
fix/hid-rp-truncated-descriptor

Conversation

@finger563

Copy link
Copy Markdown
Contributor

Summary

espp::hid_rp::ReportMap::parse() maps the report descriptor a device sends: a USB HID device on UsbHost, or a BLE HID service. A truncated or malformed descriptor made it read or write out of bounds, and a huge one could exhaust memory. Now parse() checks the descriptor first and returns std::nullopt for one it can't safely parse. Every valid descriptor parses exactly as before.

I found this while building a HID descriptor inspector (a web tool that parses pasted descriptors), and confirmed each case with ASan.

What went wrong

hid-rp's parser checks what it reads with HID_RDF_ASSERT. That macro throws when exceptions are enabled, but is a no-op without them, which is ESP-IDF's default, and the parser then carries on.

Input With exceptions (host) Without (ESP-IDF)
An item whose data runs past the end heap read past the buffer the same
A global tag past Report Count, or an unbalanced / too-deep Push / Pop caught by the assert write outside the global item stack
A short usage with no usage page in effect caught null pointer dereference
Report Count up to 2^32 bit cursor overflow, one field per count the same: memory exhaustion

The fix

ReportMap::well_formed() checks, without hid-rp, every rule its parser asserts:

  • every item fits in the descriptor;
  • no long or reserved-type items;
  • only known main and global tags;
  • data items sit inside a collection, there is no application collection inside another, and every collection is closed;
  • Push / Pop items carry no data, are balanced, and nest at most 3 deep (hid-rp's global stack holds 4 levels);
  • no Report ID 0;
  • a usage page is in effect for every 1- or 2-byte usage. A 4-byte usage carries its own page.

parse() returns std::nullopt unless the descriptor passes. On top of that:

  • kMaxReportBytes (4096): a longer input or output report refuses the whole descriptor. The bit math is done in 64 bits. For scale, a USB full-speed interrupt report is at most 64 bytes, and a BLE HID report at most 512.
  • kMaxFields (1024): ReportMap keeps at most this many fields per direction. Fields past it still take their bits, so later offsets stay correct.

Tests

New cases in hid_rp_report_map_host_test.cpp:

  • one test per rule;
  • every truncation of the Xbox descriptor;
  • 2,000 random descriptors, and 2,000 copies of the Xbox descriptor each with one byte changed;
  • the size caps.

Without the fix, ASan reports the heap-buffer-overflow on these tests. With it, the hid-rp and gamepad_map host tests pass under ASan, and all 39 host tests pass.

Locally I also fuzzed parse() plus GamepadDecoder::decode() for 2,000,000 rounds, built with -fno-exceptions (the firmware's configuration) under ASan and UBSan. It was clean; the same fuzz found the stack overflow before the fix.

Not changed

Running the component tests under UBSan, which CI doesn't do, shows two older misaligned-load reports. Both are unrelated to this change:

  • hid-rp-3dconnexion.hpp:106 (a packed report struct);
  • alpaca's from_bytes.h:26.

The decoder's heuristics also classify a SpaceMouse as a gamepad as well as a mouse.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU

…tors

The report descriptor comes from the device (USB host, BLE HID), so it can
be truncated or malformed. hid-rp's parser checks what it reads with
HID_RDF_ASSERT, which throws when exceptions are enabled but is a no-op
without them (ESP-IDF's default), and then reads on. Found while building
a descriptor inspector, confirmed with ASan:

- an item running past the end of the descriptor made it read beyond the
  buffer (with exceptions on or off);
- without exceptions, an unknown global tag or an unbalanced / too deep
  Push / Pop wrote outside its global item stack, and a usage with no
  usage page dereferenced a null pointer;
- Report Size x Report Count is unbounded: a huge count overflowed the bit
  cursor and built one field per count (memory exhaustion).

parse() now checks ReportMap::well_formed() first (every item fits; no long
or reserved items; known main / global tags; data items inside a
collection, no nested application collection, collections closed; Push /
Pop without data, balanced, at most 3 deep; no Report ID 0; a usage page in
effect for every short usage), refuses a report longer than
kMaxReportBytes (4096), and keeps at most kMaxFields (1024) fields per
direction. Every valid descriptor parses as before.

Tests: each rule; every truncation of the Xbox descriptor; 2,000 random and
mutated descriptors; the size caps. Locally the new cases fail under ASan
without the fix, and a 2,000,000-round fuzz of parse() + decode() built
with -fno-exceptions under ASan + UBSan is clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
Copilot AI balanced review requested due to automatic review settings December 2, 2026 01:41
@github-actions

github-actions Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

✅Static analysis result - no issues found! ✅

Copilot AI left a comment

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.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

4 open issues
What changed in this PR

Hardens espp::hid_rp::ReportMap::parse() against malformed/truncated HID report descriptors and maliciously large layouts by pre-validating structure and enforcing size/field caps, preventing OOB access and memory exhaustion.

Changes:

  • Add ReportMap::well_formed() and gate parse() on it to reject descriptors hid-rp would otherwise only assert on.
  • Enforce kMaxReportBytes and kMaxFields limits during parsing.
  • Add host tests covering truncations, malformed structure, fuzz-like random inputs, and size caps; update README with the new behavior.
File Description
components/​hid-rp/​test/​hid_rp_report_map_host_test.cpp Adds regression and fuzz-style tests for malformed/truncated/oversized descriptors.
components/​hid-rp/​include/​hid-rp-report-map.hpp Adds well_formed() validation and size/field caps to make parsing safe without exceptions.
components/​hid-rp/​README.md Documents the new pre-validation behavior and rationale.

Review effort: Lite

…the fuzz test

From review: pins that a Report Size 0 field (whatever its Report Count)
maps nothing and costs nothing - the field handler returns before the cap
check and any per-field loop. cppcheck (useStlAlgorithm): std::generate
for the random bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
@finger563
finger563 merged commit 9736546 into main Dec 2, 2026
194 checks passed
@finger563
finger563 deleted the fix/hid-rp-truncated-descriptor branch December 2, 2026 03:17
finger563 added a commit that referenced this pull request Dec 2, 2026
…wn parser (#965)

## Summary

This adds a new web app, the **HID Descriptor Inspector**. You paste a USB or BLE HID report descriptor and see it the way espp's firmware reads it. The parsing is hid-rp's own C++, the code the firmware runs on a device's descriptor, compiled to WebAssembly. hid-rp can't be exposed to Python, and the browser's WebHID API doesn't hand a page the raw descriptor bytes, so this is parsing a web page couldn't otherwise do.

It's part of step 4d of the testing plan (previews of on-device code in the browser), and it's the "HID descriptor inspector" tool the plan names.

> #964 (the `ReportMap::parse()` safety fix this tool relies on) is merged; this is rebased onto `main`.

## What it shows

- **Every item:** named, with usage-page and usage names, collections indented, and main-item flags such as `Data, Var, Abs`. A cut-off descriptor is listed up to where it's cut, with the reason.
- **The fields** `ReportMap` maps, inputs and outputs: report ID, bit offset and size, usage, logical range, array or variable.
- **The report sizes**, and what the decoders take the descriptor for: a gamepad and its button layout (Xbox-style, DirectInput or Android), a keyboard or a mouse.
- **A decoded input report**, as the `GamepadState` a remapper (gamepad_map) sees:
  - **Report:** typed in, or decoded **live from a HID device** over WebHID; the VID/PID fill in from the device.
  - **Options:** pass-through or combined controls, and per-device quirks by VID/PID.
- **Presets:** hid-rp's generated Xbox, DualSense-over-BLE and SpaceMouse descriptors, plus a real controller's (ShanWan BM-769, Android mode, over BLE) with a sample report.

## What's in it

- **`inspector/hid_inspector.hpp`:**
  - `parse_json()`, `decode_json()` and `presets_json()`;
  - built on `ReportMap`, `GamepadDecoder`, `KeyboardDecoder`, `MouseDecoder` and gamepad_map's `to_gamepad_state()`.
- **`inspector/hid_inspector_wasm.cpp` and `build_wasm.sh`:**
  - Emscripten 4.0.10, built with `-fno-exceptions` like the firmware;
  - writes `web/hid_inspector.js`, 84 KB and gitignored; the docs build publishes it beside the page.
- **`web/hid_descriptor_inspector.html`:** the page. Without the module, it explains how to build it or links the published copy.
- **CI:** the WebAssembly job also builds this module and requires the page's test.
- **Docs:** the hid-rp README and the web apps page describe it.

## Tests

- **`test/hid_inspector_host_test.cpp` (C++):**
  - every preset parses;
  - items, fields and classification for the Xbox descriptor and the SpaceMouse;
  - the real controller's report, pass-through and combined;
  - sign-extended item values, malformed descriptors, JSON escaping.
- **`web/test/hid_inspector_ui_test.js` (headless Chrome):** the presets, the real controller (classification, 60 items, 24 fields, its report decoded, R2 when combined), item naming, hex with commas / `0x` / comments, a truncated descriptor refused with where it's cut, and bad hex.
- **Results:** 3 of 3 runs pass, 8 checks each, and all 40 host tests and 17 web tests pass.
- **Mutation check:** inverting the combine flag in `decode_json` fails the UI test.

## Worth knowing

The inspector shows what the decoders conclude, not what a device is:
- **Xbox:** hid-rp's Xbox descriptor is the Xbox Wireless controller over BLE, which reads with the **Android** layout.
- **SpaceMouse:** a SpaceMouse classifies as a gamepad *and* a mouse.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
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.

2 participants