Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions components/hid-rp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
122 changes: 115 additions & 7 deletions components/hid-rp/include/hid-rp-report-map.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReportMap> parse(std::span<const uint8_t> 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.
Expand All @@ -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<const uint8_t> 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<uint32_t>(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<ReportField> &fields() const { return fields_; }
/// Every Output field (host -> device: rumble, LEDs...), in descriptor order.
Expand Down Expand Up @@ -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<uint64_t>(cursor) + static_cast<uint64_t>(report_size) * report_count >
static_cast<uint64_t>(kMaxReportBytes) * 8) {
map_.too_large_ = true;
return control::BREAK;
}
Comment thread
finger563 marked this conversation as resolved.
Resolved

// local items of this main section: a usage list and/or a usage range
std::vector<uint32_t> usages; // full usage (page << 16 | id)
Expand Down Expand Up @@ -305,7 +409,10 @@ class ReportMap {
f.usage_max = static_cast<uint16_t>(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;
}
Expand All @@ -323,6 +430,7 @@ class ReportMap {

std::vector<ReportField> fields_;
std::vector<ReportField> output_fields_;
bool too_large_{false}; ///< a report longer than kMaxReportBytes (parse() refuses the map)
std::map<uint8_t, uint32_t> bit_cursor_; ///< input bit position per report ID
std::map<uint8_t, uint32_t> out_bit_cursor_; ///< output bit position per report ID
bool uses_report_ids_{false};
Expand Down
147 changes: 147 additions & 0 deletions components/hid-rp/test/hid_rp_report_map_host_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
//
// No ESP-IDF headers required.

#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
Expand Down Expand Up @@ -529,3 +530,149 @@ 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<uint8_t>{0x05, 0x01, 0x26, 0xff}).has_value());
// an Input (1 data byte) with none left
CHECK_FALSE(
ReportMap::parse(std::vector<uint8_t>{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<uint8_t>{0xfe, 0x04}).has_value());
CHECK_FALSE(ReportMap::well_formed(std::vector<uint8_t>{0xfe, 0x02, 0x00, 0x01, 0x02}));
Comment thread
finger563 marked this conversation as resolved.
Resolved
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<uint8_t>;
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<Bytes> 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<uint8_t> 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<uint8_t> cut(full.begin(), full.begin() + static_cast<std::ptrdiff_t>(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<uint8_t> bytes(next() % 64);
std::generate(bytes.begin(), bytes.end(), [&next]() { return static_cast<uint8_t>(next()); });
(void)ReportMap::parse(bytes);
// a real descriptor with one byte changed
std::vector<uint8_t> mutated = full;
mutated[next() % mutated.size()] = static_cast<uint8_t>(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<uint8_t>;
// 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<uint8_t>(count & 0xff),
static_cast<uint8_t>(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());
// 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);
}
Loading