Repository navigation
fix(ble): reject negative and overlapping offsets in inbound write buffer - #1666
kappaone-eth wants to merge 5 commits into
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a46c898e59
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
…ffer A malicious BLE central can send ATT writes with a negative offset, which reaches Data.replaceSubrange via BLEInboundWriteBuffer.append and traps at runtime, crashing any peripheral that receives the write. Validate each chunk before mutating the buffer: reject negative offsets, non-monotonic sequences, and overlapping chunks, and drop the offending per-central buffer. Add an AppendResult.invalid case, handle it in the peripheral-role write handler, and cover the rejection paths with tests.
a46c898 to
fd131a9
Compare
chessing234
left a comment
There was a problem hiding this comment.
the overlap/rewrite hardening is worth having, but two things first.
the negative offset: CBATTRequest.offset comes straight off the ATT wire and that field is 16-bit unsigned, so i don't think a central can produce offset < 0 at all. can you show a repro or drop the DoS framing?
bigger one: our central role writes with .withoutResponse (BLEService.swift:5073, 5126, 5167), so legit inbound writes land at offset 0. with a stale partial buffer pending, the next offset-0 write now trips chunk.offset >= lastEnd, goes .invalid, and its bytes are dropped — main applied them in place. can you treat offset 0 with a non-empty buffer as a restart (clear, then apply) instead of a reject?
Per review: the central role writes with .withoutResponse, so legit inbound writes always land at offset 0. With a stale partial frame pending, the previous validation rejected the fresh write as invalid and dropped its bytes; clear the buffer and apply instead. Non-monotonic test now uses [8, 4] since offset 0 restarts; adds a test covering the stale-buffer restart path.
chessing234
left a comment
There was a problem hiding this comment.
the negative/overlap rejection before mutate is the right place, and clearing the buffer on .invalid so a later clean frame can decode is good. the offset-0 reset on a non-empty buffer matches withoutResponse rewrite semantics — worth a one-line note in the PR body that this is intentional so reviewers don't treat it as a silent data drop.
chessing234
left a comment
There was a problem hiding this comment.
offset-0 restart on a non-empty buffer treats every fresh withoutResponse write as a replace — good — but a withResponse multi-chunk transfer that legitimately reuses offset 0 after a partial failure isn't distinguished. more important: .invalid clears the buffer and returns, yet the peripheral write handler still needs to respond to the ATT request (success vs error). check the call site sends the right CBATT error instead of silently acking a poisoned write; otherwise the central keeps sending into a cleared buffer and you only log.
Responding .success to a poisoned write let the central believe the bytes were accepted; with the buffer cleared on .invalid, it would keep sending subsequent chunks into a fresh buffer. Respond with CBATTError.Code.invalidOffset for requests that fail offset validation so the central aborts the transfer. Responses still go out within the same callback, preserving the sub-millisecond ATT response requirement.
|
Thanks for the careful review — both points addressed in the latest commits. Negative offset framing: agreed, the ATT wire field is 16-bit unsigned, so ATT response on poisoned writes: fixed in Offset-0 restart: implemented in |
chessing234
left a comment
There was a problem hiding this comment.
changes needed: overlap rejection before mutate is good, but bitchat's central writes .withoutResponse, so respond(.invalidOffset) never reaches the peer that matters, and this fights #1677 on the same three files. also ATT offsets are u16 — the negative-offset DoS story is not an on-air path.
- Always ACK inbound writes with .success, even malformed ones dropped as .invalid: our centrals write with .withoutResponse, so an ATT error never reaches the peer that matters, and CoreBluetooth does not distinguish with/without-response in didReceiveWrite. The poisoned per-central buffer is still discarded internally so a later clean frame can decode. Restores the immediate-respond path so the peripheral-role hunk is only the .invalid case (no overlap with permissionlesstech#1677's didUnsubscribeFrom cleanup). - Reframe the negative-offset guard as defense-in-depth for the Int-based buffer API (ATT offsets are UInt16 on air); the reachable hardening is the overlap/rewrite protection.
|
Addressed the review feedback in b8fe34a (branch also merged up to latest main):
Tests unchanged (no Xcode toolchain here — relying on CI). |
chessing234
left a comment
There was a problem hiding this comment.
malformed writes ack success up front, which matches centrals that write withoutResponse, and the negative offset is spelled out as not an on-air path. no new defect from me.
|
Thanks for sticking with this, and for the careful rework. Dropping the NACK and reframing the negative-offset guard were the right calls, and the overlap check is correct now. We're going to close it, though, because it doesn't change anything a real peer can hit. Each central has its own buffer, so an overlapping write can only corrupt that central's own frame. ATT offsets are UInt16, so negative offsets never arrive. iOS and Android both write whole frames at offset 0 without response, and main already decodes those even over a stale buffer, because decodeCore ignores trailing bytes. The real exposure, buffers left behind by centrals that never unsubscribe, is being handled in #1677, and this PR would conflict with it in the tests. Sorry it took so long to give you a clear answer. We'd be glad to have your eyes on another BLE or protocol issue. |
Summary
BLEInboundWriteBuffer.append(chunks:for:capBytes:)against malformed chunk sequences: rejects negative offsets, non-monotonic sequences, and overlapping chunks (including overlaps with bytes buffered by an earlier callback), and drops the offending per-central buffer (AppendResult.invalid)..withoutResponse, so legit writes always land at offset 0 and a restart must overwrite, not be rejected..success(unchanged immediate-respond path) and drops the poisoned buffer internally: our centrals write with.withoutResponse, so an ATT error never reaches the peer that matters, and CoreBluetooth does not distinguish with/without-response indidReceiveWrite. A later clean frame still decodes against the cleared buffer.Details
CBATTRequest.offsetis attacker-controlled input from the remote central, fed straight into:Note on reachability: the ATT wire field is 16-bit unsigned, so a negative offset cannot be produced over the air; the
offset < 0guard is defense-in-depth for theInt-based buffer API. The reachable hardening is the overlap/rewrite protection: duplicate or out-of-order offsets previously let a sender silently rewrite already-buffered bytes of a pending frame.The fix validates each non-empty chunk against a running
lastEndcursor (seeded with the already-buffered byte count) before touching the buffer. On violation it clears the per-central buffer and returns.invalid(metadata:); the caller ACKs and keeps operating. Legitimate CoreBluetooth long writes (ascending, non-overlapping offsets, including zero-padded gaps) are unaffected.Known limitation: CoreBluetooth does not distinguish write-with-response from write-without-response in
didReceiveWrite, so an offset-0 restart from awithResponsemulti-chunk transfer retry is indistinguishable from a freshwithoutResponseframe; both are treated as a restart (replace).Tests
Added to
BLEInboundWriteBufferTests:Note: tests were authored on a machine without an Xcode toolchain, so they have not been executed locally — relying on CI.
Supersedes #1665 (same change; branch history was rewritten for authorship).