Fix 1-byte out-of-bounds read in receive() scan loop - #108
Merged
Conversation
The scan loop that advances rPtr past running-status data bytes evaluated buffer[rPtr + 1] before checking rPtr < (length - 1), due to && operand order. When the trailing data byte(s) of a packet are all below MIDI_TYPE, this reads one byte past the end of the receive buffer before the bounds check can short-circuit it. Swapping the operand order so the bounds check runs first fixes this; parsing behavior for valid packets is unchanged.
Owner
|
Super nice catch @94xhn . Kudos!! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Bug
In
BLEMIDI_Transport::receive(), the scan loop that advancesrPtrpast trailing data bytes checks the buffer content before checking the bounds:Because
&&is evaluated left-to-right,buffer[rPtr + 1]is read beforerPtr < (length - 1)is checked. WhenrPtrreacheslength - 1and the final byte(s) are all data bytes (<MIDI_TYPE), this readsbuffer[length], one byte past the end of the caller-supplied buffer.This function is called from every hardware backend (
BLEMIDI_ESP32.h,BLEMIDI_ESP32_NimBLE.h,BLEMIDI_Client_ESP32.h,BLEMIDI_ArduinoBLE.h,BLEMIDI_nRF52.h) with a buffer that comes directly off the BLE transport, so this is reachable from an ordinary MIDI message ending near the buffer boundary.Fix
Swap the
&&operand order so the bounds check is evaluated first and short-circuits before the array index:No other logic changes. Verified against a real 5-byte NoteOn packet (
0x80, 0x80, 0x90, 0x3C, 0x64) placed immediately before a guard page: the unmodified code reliably reads one byte past the buffer end, and the one-line fix eliminates the out-of-bounds access while parsing the same packet identically (mBleClass.add(0x90),add(0x3C),add(0x64)).