Skip to content

Conversation

spacepc-de
Copy link

  • Fixes a potential buffer overflow when reading from the Bluefruit BLE UART on nRF52 by
    clamping reads to MAX_FRAME_SIZE and draining any surplus bytes.

    • No protocol or API changes; normal behavior remains unchanged for valid frames.

    Motivation

    • SerialBLEInterface::checkRecvFrame() previously did:
      • len = bleuart.available()
      • bleuart.readBytes(dest, len)
    • If len > MAX_FRAME_SIZE (172), this could write past the caller’s buffer (e.g.,
      cmd_frame), causing memory corruption or crashes. This situation is possible if the peer
      sends multiple frames quickly or if the BLE stack coalesces data.

    Changes

    • In src/helpers/nrf52/SerialBLEInterface.cpp:
      • Limit read size to MAX_FRAME_SIZE.
      • If more data is pending than MAX_FRAME_SIZE, drain the remaining bytes in small
        chunks.
      • Log a warning with BLE_DEBUG_PRINTLN when an overflow scenario is detected.
    • The function still returns the number of bytes copied into the destination buffer,
      preserving existing semantics.

    Behavior and Compatibility

    • Normal operation (each frame ≤ MAX_FRAME_SIZE) is unaffected.
    • If more than MAX_FRAME_SIZE bytes are pending:
      • The first MAX_FRAME_SIZE bytes are delivered to the caller.
      • The surplus is discarded to avoid mixing multiple frames into a single return or
        leaving partial data that would corrupt subsequent parsing.
    • No changes required in client applications; in rare overflow cases, the sender may need to
      retry per its existing timeout logic.

    Testing

    • Verified that single frames ≤ MAX_FRAME_SIZE continue to flow unchanged.
    • Simulated overflow by sending multiple back-to-back writes that exceed 172 bytes:
      • Confirmed no crashes or memory corruption.
      • Observed “WARN: BLE RX overflow” log and that the first frame is processed, with
        excess drained.
    • Sanity-checked that send path and timing logic remain the same.

Impact

  • In overflow scenarios, some extra incoming bytes may be dropped; this is preferable to
    undefined behavior and aligns with the current single-frame-per-read assumption.

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.

1 participant