From 667858cc49f89e87eb5ddd3dd33d1e8632199f90 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 1 Dec 2026 19:40:42 -0600 Subject: [PATCH 1/2] fix(hid-rp): ReportMap::parse refuses malformed and oversized descriptors 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 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/hid-rp/README.md | 7 + .../hid-rp/include/hid-rp-report-map.hpp | 122 +++++++++++++++- .../test/hid_rp_report_map_host_test.cpp | 138 ++++++++++++++++++ 3 files changed, 260 insertions(+), 7 deletions(-) diff --git a/components/hid-rp/README.md b/components/hid-rp/README.md index 55a6477658..9622a10a7b 100644 --- a/components/hid-rp/README.md +++ b/components/hid-rp/README.md @@ -16,6 +16,13 @@ works out where every field sits. Input fields (`fields()`) feed the decoders (`GamepadDecoder`, `KeyboardDecoder`, ...). Output fields (`output_fields()`, host to device: rumble, LEDs) are mapped too, each with its unit. +The descriptor comes from the device, so `parse()` first checks it is well +formed (`ReportMap::well_formed()`: every item fits, collections and Push / +Pop balance, only known items, a usage page for every short usage) and returns +`std::nullopt` otherwise. hid-rp's own checks only stop the parse when +exceptions are enabled; without them (ESP-IDF's default) a truncated or +malformed descriptor made it read past the buffer. + ## Rumble `hid-rp-rumble.hpp` handles rumble in both directions of a controller bridge: diff --git a/components/hid-rp/include/hid-rp-report-map.hpp b/components/hid-rp/include/hid-rp-report-map.hpp index c06ecd7c2c..da9ad55a26 100644 --- a/components/hid-rp/include/hid-rp-report-map.hpp +++ b/components/hid-rp/include/hid-rp-report-map.hpp @@ -49,12 +49,27 @@ struct ReportField { /// The Input fields of a report descriptor, parsed at runtime. class ReportMap { public: - /// Parse a report descriptor. Returns nullopt for a descriptor the parser - /// rejects (malformed items, unmatched push/pop) or that has no Input - /// fields. Input items are mapped into fields(), Output items into - /// output_fields() (each with its own report layout, as a device's input and - /// output reports are separate); Feature items are skipped. + /// The longest input or output report parse() accepts, in bytes (a USB + /// full-speed interrupt report is at most 64, a BLE HID one at most 512). + static constexpr uint32_t kMaxReportBytes = 4096; + /// The most Input (and, separately, Output) fields a map keeps. + static constexpr size_t kMaxFields = 1024; + + /// Parse a report descriptor. Returns nullopt for a descriptor that is not + /// well formed (see well_formed()), has a report longer than + /// kMaxReportBytes, or has no Input fields. Input items are mapped into + /// fields(), Output items into output_fields() (each with its own report + /// layout, as a device's input and output reports are separate); Feature + /// items are skipped. static std::optional parse(std::span descriptor) { + // The descriptor comes from the device. hid-rp's parser checks what it + // reads with HID_RDF_ASSERT, which throws when exceptions are on but is a + // no-op without them (as on ESP-IDF), and then reads on: past the end of + // the buffer for a truncated item, out of its global item array for an + // unknown tag or an unbalanced push / pop, through a null pointer for a + // usage with no usage page. So reject everything it would assert on first. + if (!well_formed(descriptor)) + return std::nullopt; ReportMap map; // hid-rp reports malformed descriptors through HID_RDF_ASSERT, which // throws when exceptions are enabled and is a no-op otherwise. @@ -75,12 +90,93 @@ class ReportMap { [[maybe_unused]] Parser parser( map, ::hid::rdf::descriptor_view(descriptor.data(), descriptor.size())); #endif - if (map.fields_.empty()) { + if (map.too_large_ || map.fields_.empty()) { return std::nullopt; } return map; } + /// Whether `descriptor` is well formed by the rules hid-rp's parser asserts + /// (see parse()), checked without it: every item fits in the descriptor (a + /// short item is a prefix byte and 0, 1, 2 or 4 data bytes, HID 1.11 + /// 6.2.2.2); no long or reserved-type items; known main and global tags; data + /// items inside a collection, no application collection inside another, + /// collections closed; Push / Pop without data, balanced, at most 3 deep; no + /// Report ID 0; and a usage page in effect for every 1- or 2-byte usage (a + /// 4-byte usage carries its own page) when the main item that uses it comes. + static bool well_formed(std::span descriptor) { + static constexpr size_t kMaxPushDepth = 3; // hid-rp's global stack holds 4 levels + bool has_page[kMaxPushDepth + 1] = {false, false, false, false}; + size_t depth = 0; + int collections = 0; + bool short_usage = false; // a 1- / 2-byte usage since the last main item + size_t i = 0; + while (i < descriptor.size()) { + const uint8_t prefix = descriptor[i]; + if (prefix == 0xFE) + return false; // a long item (hid-rp does not take them; no device uses them) + static constexpr size_t data_sizes[4] = {0, 1, 2, 4}; + const size_t data_size = data_sizes[prefix & 0x3]; + if (1 + data_size > descriptor.size() - i) + return false; // the item runs past the end + uint32_t value = 0; + for (size_t b = 0; b < data_size; b++) + value |= static_cast(descriptor[i + 1 + b]) << (8 * b); + const unsigned type = (prefix >> 2) & 0x3, tag = prefix >> 4; + switch (type) { + case 0: // main + switch (tag) { + case 0x8: // Input + case 0x9: // Output + case 0xB: // Feature + if (collections <= 0) + return false; + break; + case 0xA: // Collection + if (++collections > 1 && value == 0x01) + return false; // an application collection inside another + break; + case 0xC: // End Collection + if (--collections < 0) + return false; + break; + default: + return false; + } + if (short_usage && !has_page[depth]) + return false; + short_usage = false; + break; + case 1: // global + if (tag == 0xA) { // Push + if (data_size != 0 || depth == kMaxPushDepth) + return false; + has_page[depth + 1] = has_page[depth]; + depth++; + } else if (tag == 0xB) { // Pop + if (data_size != 0 || depth == 0) + return false; + depth--; + } else if (tag > 0x9) { + return false; // past Report Count: not a global item hid-rp stores + } else if (tag == 0x0) { + has_page[depth] = true; // Usage Page + } else if (tag == 0x8 && value == 0) { + return false; // Report ID 0 + } + break; + case 2: // local + if (tag <= 0x2 && data_size < 4) + short_usage = true; // Usage, Usage Minimum, Usage Maximum + break; + default: + return false; // reserved item type + } + i += 1 + data_size; + } + return depth == 0 && collections == 0; + } + /// Every Input field, in descriptor order. const std::vector &fields() const { return fields_; } /// Every Output field (host -> device: rumble, LEDs...), in descriptor order. @@ -212,6 +308,14 @@ class ReportMap { map_.uses_report_ids_ = true; } uint32_t &cursor = (is_input ? map_.bit_cursor_ : map_.out_bit_cursor_)[report_id]; + // Report Size x Report Count comes from the device: a report longer than + // kMaxReportBytes is refused (the whole descriptor), so the bit cursor + // cannot overflow and a huge count cannot exhaust memory. + if (static_cast(cursor) + static_cast(report_size) * report_count > + static_cast(kMaxReportBytes) * 8) { + map_.too_large_ = true; + return control::BREAK; + } // local items of this main section: a usage list and/or a usage range std::vector usages; // full usage (page << 16 | id) @@ -305,7 +409,10 @@ class ReportMap { f.usage_max = static_cast(hi & 0xFFFF); } cursor += report_size; - dest_fields.push_back(f); + // past kMaxFields the field still takes its bits (later offsets stay + // right) but is not kept: no decoder needs more + if (dest_fields.size() < kMaxFields) + dest_fields.push_back(f); } return control::CONTINUE; } @@ -323,6 +430,7 @@ class ReportMap { std::vector fields_; std::vector output_fields_; + bool too_large_{false}; ///< a report longer than kMaxReportBytes (parse() refuses the map) std::map bit_cursor_; ///< input bit position per report ID std::map out_bit_cursor_; ///< output bit position per report ID bool uses_report_ids_{false}; diff --git a/components/hid-rp/test/hid_rp_report_map_host_test.cpp b/components/hid-rp/test/hid_rp_report_map_host_test.cpp index 43d31e784d..8f015ce5f1 100644 --- a/components/hid-rp/test/hid_rp_report_map_host_test.cpp +++ b/components/hid-rp/test/hid_rp_report_map_host_test.cpp @@ -529,3 +529,141 @@ TEST_CASE("switch pro full scale joystick") { CHECK(rx == 4094); CHECK(ry == 4094); } + +// A descriptor comes from the device, so it can be truncated (a short read, a +// BLE attribute cut at its MTU) or malicious: an item that runs past the end +// must make parse() fail, not read beyond the buffer (it did, inside hid-rp's +// item walk; caught by ASan). +TEST_CASE("truncated items are rejected") { + using espp::hid_rp::ReportMap; + // a 2-byte Logical Maximum with 1 data byte left + CHECK_FALSE(ReportMap::parse(std::vector{0x05, 0x01, 0x26, 0xff}).has_value()); + // an Input (1 data byte) with none left + CHECK_FALSE( + ReportMap::parse(std::vector{0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x81}).has_value()); + // long items (hid-rp does not take them), cut or not + CHECK_FALSE(ReportMap::parse(std::vector{0xfe, 0x04}).has_value()); + CHECK_FALSE(ReportMap::well_formed(std::vector{0xfe, 0x02, 0x00, 0x01, 0x02})); + CHECK(ReportMap::well_formed({})); +} + +// What hid-rp's parser asserts on - and, built without exceptions as on +// ESP-IDF, then reads on past: each is refused before it parses. +TEST_CASE("structurally malformed descriptors are rejected") { + using espp::hid_rp::ReportMap; + using Bytes = std::vector; + const Bytes app_open{0x05, 0x01, 0x09, 0x05, 0xa1, 0x01}; // GD, Gamepad, Application + const Bytes button{0x75, 0x01, 0x95, 0x01, 0x15, 0x00, 0x25, 0x01, // 1 x 1 bit + 0x05, 0x09, 0x09, 0x01, 0x81, 0x02}; // Button 1, Input + auto with = [&](std::initializer_list parts) { + Bytes d; + for (const auto &p : parts) + d.insert(d.end(), p.begin(), p.end()); + return d; + }; + const Bytes ok = with({app_open, button, {0xc0}}); + CHECK(ReportMap::well_formed(ok)); + CHECK(ReportMap::parse(ok).has_value()); + CHECK_FALSE(ReportMap::well_formed(with({app_open, button}))); // collection not closed + CHECK_FALSE(ReportMap::well_formed(with({button}))); // Input outside a collection + CHECK_FALSE( + ReportMap::well_formed(with({app_open, button, {0xc0, 0xc0}}))); // End Collection unmatched + CHECK_FALSE(ReportMap::well_formed( + with({app_open, {0xa1, 0x01}, button, {0xc0, 0xc0}}))); // nested application + CHECK_FALSE(ReportMap::well_formed(with({app_open, {0xb4}, button, {0xc0}}))); // Pop unmatched + CHECK_FALSE(ReportMap::well_formed(with({app_open, {0xa4}, button, {0xc0}}))); // Push unmatched + CHECK_FALSE(ReportMap::well_formed(with({app_open, + {0xa4, 0xa4, 0xa4, 0xa4}, + button, + {0xb4, 0xb4, 0xb4, 0xb4, 0xc0}}))); // Push 4 deep + CHECK(ReportMap::well_formed( + with({app_open, {0xa4, 0xa4, 0xa4}, button, {0xb4, 0xb4, 0xb4, 0xc0}}))); // 3 deep is fine + CHECK_FALSE( + ReportMap::well_formed(with({app_open, {0xa5, 0x00}, button, {0xc0}}))); // Push with data + CHECK_FALSE(ReportMap::well_formed(with({app_open, {0xc4}, button, {0xc0}}))); // global tag 0xC + CHECK_FALSE( + ReportMap::well_formed(with({app_open, {0x85, 0x00}, button, {0xc0}}))); // Report ID 0 + CHECK_FALSE(ReportMap::well_formed(with({app_open, {0xd0}, button, {0xc0}}))); // main tag 0xD + CHECK_FALSE(ReportMap::well_formed(with({app_open, {0x0c}, button, {0xc0}}))); // reserved type + // a usage with no usage page in effect (Pop restored the state before the page) + CHECK_FALSE(ReportMap::well_formed(Bytes{0xa4, 0x05, 0x01, 0xb4, 0x09, 0x05, 0xa1, 0x01, 0x75, + 0x01, 0x95, 0x01, 0x09, 0x30, 0x81, 0x02, 0xc0})); + // a 4-byte usage carries its own page + CHECK(ReportMap::well_formed(Bytes{0x0b, 0x05, 0x00, 0x01, 0x00, 0xa1, 0x01, 0x75, 0x01, 0x95, + 0x01, 0x0b, 0x30, 0x00, 0x01, 0x00, 0x81, 0x02, 0xc0})); +} + +// Every prefix of real descriptors (each cut point a truncated read), and +// pseudo-random bytes: parse() returns a map or nullopt and never reads past +// the end (the host tests run under ASan in CI's sanitizer job). +TEST_CASE("descriptor prefixes and random bytes never read out of bounds") { + using espp::hid_rp::ReportMap; + const auto xbox = espp::xbox_descriptor(); + const std::vector full(xbox.begin(), xbox.end()); + for (size_t n = 0; n <= full.size(); n++) { + // a copy of exactly n bytes, so reading past it is a heap overflow + std::vector cut(full.begin(), full.begin() + static_cast(n)); + (void)ReportMap::parse(cut); + } + uint32_t seed = 0x2545F491u; + auto next = [&seed]() { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + return seed; + }; + for (int round = 0; round < 2000; round++) { + std::vector bytes(next() % 64); + for (auto &b : bytes) + b = static_cast(next()); + (void)ReportMap::parse(bytes); + // a real descriptor with one byte changed + std::vector mutated = full; + mutated[next() % mutated.size()] = static_cast(next()); + (void)ReportMap::parse(mutated); + } + CHECK(ReportMap::parse(full).has_value()); +} + +// Report Size x Report Count comes from the device: a huge count must not +// overflow the bit cursor or exhaust memory. +TEST_CASE("oversized reports are refused, fields are capped") { + using espp::hid_rp::ReportMap; + using Bytes = std::vector; + // 8 bits x 0xFFFFFFFF + const Bytes huge{0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x75, 0x08, 0x97, 0xff, 0xff, 0xff, 0xff, + 0x15, 0x00, 0x25, 0x01, 0x05, 0x09, 0x19, 0x01, 0x29, 0x10, 0x81, 0x02, 0xc0}; + CHECK_FALSE(ReportMap::parse(huge).has_value()); + // exactly kMaxReportBytes (8 bits x 4096) is fine, one byte more is not + auto sized = [](uint16_t count) { + return Bytes{0x05, + 0x01, + 0x09, + 0x05, + 0xa1, + 0x01, + 0x75, + 0x08, + 0x96, + static_cast(count & 0xff), + static_cast(count >> 8), + 0x15, + 0x00, + 0x25, + 0x01, + 0x05, + 0x09, + 0x19, + 0x01, + 0x29, + 0x10, + 0x81, + 0x02, + 0xc0}; + }; + const auto max = ReportMap::parse(sized(ReportMap::kMaxReportBytes)); + REQUIRE(max.has_value()); + CHECK(max->report_bytes(0) == ReportMap::kMaxReportBytes); + CHECK(max->fields().size() == ReportMap::kMaxFields); // 4096 fields, 1024 kept + CHECK_FALSE(ReportMap::parse(sized(ReportMap::kMaxReportBytes + 1)).has_value()); +} From 9eb401f9851daaed6e6a573281f7f730c54c1559 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 1 Dec 2026 20:00:49 -0600 Subject: [PATCH 2/2] test(hid-rp): a zero-width field with a huge count; std::generate in 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 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- .../hid-rp/test/hid_rp_report_map_host_test.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/components/hid-rp/test/hid_rp_report_map_host_test.cpp b/components/hid-rp/test/hid_rp_report_map_host_test.cpp index 8f015ce5f1..a6ab7884c6 100644 --- a/components/hid-rp/test/hid_rp_report_map_host_test.cpp +++ b/components/hid-rp/test/hid_rp_report_map_host_test.cpp @@ -5,6 +5,7 @@ // // No ESP-IDF headers required. +#include #include #include #include @@ -614,8 +615,7 @@ TEST_CASE("descriptor prefixes and random bytes never read out of bounds") { }; for (int round = 0; round < 2000; round++) { std::vector bytes(next() % 64); - for (auto &b : bytes) - b = static_cast(next()); + std::generate(bytes.begin(), bytes.end(), [&next]() { return static_cast(next()); }); (void)ReportMap::parse(bytes); // a real descriptor with one byte changed std::vector mutated = full; @@ -666,4 +666,13 @@ TEST_CASE("oversized reports are refused, fields are capped") { CHECK(max->report_bytes(0) == ReportMap::kMaxReportBytes); CHECK(max->fields().size() == ReportMap::kMaxFields); // 4096 fields, 1024 kept CHECK_FALSE(ReportMap::parse(sized(ReportMap::kMaxReportBytes + 1)).has_value()); + // a zero-width field with a huge count carries no bits: it maps nothing and + // costs nothing (the field handler returns before any per-field loop) + const Bytes zero_width{0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x75, 0x00, 0x97, 0xff, + 0xff, 0xff, 0xff, 0x81, 0x02, 0x75, 0x01, 0x95, 0x01, 0x15, + 0x00, 0x25, 0x01, 0x05, 0x09, 0x09, 0x01, 0x81, 0x02, 0xc0}; + const auto zw = ReportMap::parse(zero_width); + REQUIRE(zw.has_value()); + CHECK(zw->fields().size() == 1); // only the 1-bit button + CHECK(zw->report_bytes(0) == 1); }