Use constant-time comparison for MAC verification#1656
Use constant-time comparison for MAC verification#1656weebl2000 wants to merge 2 commits intomeshcore-dev:devfrom
Conversation
The HMAC check in MACThenDecrypt used standard memcmp(), which short-circuits on the first mismatched byte. This makes the comparison time dependent on how many bytes of the MAC are correct, leaking information through a timing side-channel. With a 2-byte MAC (65,536 possible values), an attacker on a local interface (serial, BLE, or WiFi) can measure response latency to distinguish "first byte wrong" from "first byte correct, second wrong". This reduces a brute-force from 65,536 attempts down to roughly 384 (256 + 128 on average), making MAC forgery practical. An attacker could use this to forge packets that pass MAC verification without knowing the shared secret, allowing them to inject arbitrary messages that appear to come from a trusted peer. Replace memcmp with a constant-time XOR-accumulate loop so the comparison always takes the same time regardless of which bytes match.
What time taken to return are you referring to? As far as I know, none of the firmwares reply to anything over LoRa if the encryption/decryption fails? So there's no response to measure the time of? Or am I missing something? |
You're right. Exploiting this is really hard in practice (near to impossible). Still good to have it in I guess. |
Severity: low
Summary
The HMAC verification in
MACThenDecryptuses standardmemcmp(), which short-circuits on the first mismatched byte. The time taken to return reveals how many leading bytes of the MAC were correct, leaking information through a timing side-channel.How this can be exploited
MeshCore uses a 2-byte MAC (65,536 possible values). With a timing-variable comparison, an attacker can break the MAC verification into two sequential brute-forces:
memcmptakes slightly longer to reject reveals the correct first byte (because it proceeded to compare the second byte before failing).Total: ~384 attempts on average instead of ~32,768 for blind brute-force.
On local interfaces (BLE, WiFi, serial) the timing difference between a 1-byte and 2-byte comparison is measurable with sub-millisecond precision. Over RF the timing window is harder to exploit directly, but a BLE-connected attacker (e.g. a compromised phone app, or someone within Bluetooth range of a companion radio) could:
Fix
Replace
memcmpwith a constant-time XOR-accumulate loop. The comparison now always examines every byte regardless of where the first mismatch occurs, eliminating the timing signal.Test plan
Heltec_v3_companion_radio_bleBuild firmware: Build from this branch