Skip to content

fix(ble): reject negative and overlapping offsets in inbound write buffer - #1666

Closed
kappaone-eth wants to merge 5 commits into
permissionlesstech:mainfrom
kappaone-eth:fix/ble-inbound-write-buffer-offset-validation
Closed

kappaone-eth wants to merge 5 commits into
permissionlesstech:mainfrom
kappaone-eth:fix/ble-inbound-write-buffer-offset-validation

Conversation

@kappaone-eth

@kappaone-eth kappaone-eth commented Aug 12, 2026 •

Copy link
Copy Markdown

Summary

  • Hardens 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).
  • An offset-0 chunk arriving on a non-empty buffer is treated as a fresh frame replacing stale partial bytes (clear, then apply). This is intentional: our central role writes .withoutResponse, so legit writes always land at offset 0 and a restart must overwrite, not be rejected.
  • The peripheral write handler keeps ACKing with .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 in didReceiveWrite. A later clean frame still decodes against the cleared buffer.

Details

CBATTRequest.offset is attacker-controlled input from the remote central, fed straight into:

combined.replaceSubrange(chunk.offset..<end, with: chunk.data)

Note on reachability: the ATT wire field is 16-bit unsigned, so a negative offset cannot be produced over the air; the offset < 0 guard is defense-in-depth for the Int-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 lastEnd cursor (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 a withResponse multi-chunk transfer retry is indistinguishable from a fresh withoutResponse frame; both are treated as a restart (replace).

Tests

Added to BLEInboundWriteBufferTests:

  • negative offset is rejected and the cleared buffer still decodes a later clean frame
  • overlapping chunks are rejected (within one call and against previously buffered bytes)
  • non-monotonic chunks are rejected
  • offset-0 write on a stale buffer restarts cleanly

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).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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.
@kappaone-eth
kappaone-eth force-pushed the fix/ble-inbound-write-buffer-offset-validation branch from a46c898 to fd131a9 Compare August 12, 2026 14:48

@chessing234 chessing234 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 chessing234 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 chessing234 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@kappaone-eth

Copy link
Copy Markdown
Author

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 offset < 0 can't arrive over the air — I have no repro and have dropped the DoS framing from the PR body. The guard stays as defense-in-depth for the Int-based buffer API; the reachable part of this PR is the overlap/rewrite hardening, which is how the body now frames it.

ATT response on poisoned writes: fixed in 101db18. didReceiveWrite now responds per central group after validation: .invalidOffset for requests that fail offset checks, .success otherwise. Responses still happen inside the same callback, so the sub-millisecond ATT timing requirement is preserved. A central sending bad offsets now gets an explicit abort instead of a silent ACK into a cleared buffer.

Offset-0 restart: implemented in b74e929 and noted as intentional in the PR body, as you suggested. One caveat you flagged stands: CoreBluetooth doesn't tell us whether a write was with or without response, so a withResponse multi-chunk retry at offset 0 is indistinguishable from a fresh withoutResponse frame — both take the restart path. That's documented in the PR body's limitations section.

@chessing234 chessing234 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@kappaone-eth

Copy link
Copy Markdown
Author

Addressed the review feedback in b8fe34a (branch also merged up to latest main):

  • Dropped the invalidOffset NACK. You were right — our centrals write with .withoutResponse (BLEService.swift:5073, 5126, 5167), so an ATT error never reaches the peer that matters, and didReceiveWrite can't distinguish the two write types anyway. The handler is back on the immediate .success respond path; malformed writes are still dropped internally (.invalid clears the per-central buffer) so a later clean frame decodes. The peripheral-role hunk is now just the .invalid switch case plus a comment, so it no longer overlaps Clear a central's partial write buffer when it unsubscribes #1677's didUnsubscribeFrom cleanup.
  • Reframed the negative-offset guard as defense-in-depth for the Int-based buffer API (ATT offsets are UInt16 on air) — code comment and PR body updated. The reachable hardening remains the overlap/rewrite check, kept as-is, along with the offset-0 restart for .withoutResponse semantics.
  • Clear a central's partial write buffer when it unsubscribes #1677 overlap: left Clear a central's partial write buffer when it unsubscribes #1677's removeValue(forCentralID:) / stale-eviction / unsubscribe cleanup untouched in that PR. After this rework the only shared hunk is the append validation region in BLEInboundWriteBuffer.swift, which should rebase trivially once either PR lands first.

Tests unchanged (no Xcode toolchain here — relying on CI).

@chessing234 chessing234 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jackjackbits

Copy link
Copy Markdown
Collaborator

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.

@kappaone-eth
kappaone-eth deleted the fix/ble-inbound-write-buffer-offset-validation branch October 25, 2026 07:39
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.

3 participants