From 6f7881851758d5ca8e19444f8f61b2784ab03d31 Mon Sep 17 00:00:00 2001 From: Jozef Koval Date: Sat, 31 Oct 2026 22:13:33 +0100 Subject: [PATCH] Drop REQUEST_SYNC addressed to another peer at ingress A directed REQUEST_SYNC is for its recipient only. When the requester has no link to the recipient, the send falls back to every link. Other neighbours then get the request. The responder did not check the recipient. So they answered a request that was not for them, and a reply can be many packets. The ingress guard now rejects a REQUEST_SYNC whose recipient is set and is not this node. This covers link frames and reassembled packets. Broadcast requests are unchanged. The check runs before the ingress record and the duplicate filter on purpose. One periodic round sends a directed request to each connected peer. Two copies with the same millisecond timestamp share a packet ID, because the ID has no recipient. If a stray copy arrives first and is dropped later, the addressee drops its own copy as a duplicate. The requester now builds the recipient from PeerID.routingData instead of parsing hex by hand. A long-form peer ID then still gives the 8-byte ID that responders compare against. BLEIngressPacketGuardTests checks the rule. The end-to-end test requestSyncIsAnsweredOnlyByItsRecipient sends a stray copy and then our own copy with the same packet ID through the real ingress path. The first gets no reply, and the second does. Full SwiftPM suite green: 2202 tests in 237 suites. --- .../Services/BLE/BLEIngressPacketGuard.swift | 14 +++ bitchat/Services/BLE/BLEService.swift | 12 +++ bitchat/Sync/GossipSyncManager.swift | 9 +- bitchatTests/BLEServiceCoreTests.swift | 62 +++++++++++++ .../Services/BLEIngressPacketGuardTests.swift | 89 ++++++++++++++++++- docs/REQUEST_SYNC_MANAGER.md | 1 + 6 files changed, 178 insertions(+), 9 deletions(-) diff --git a/bitchat/Services/BLE/BLEIngressPacketGuard.swift b/bitchat/Services/BLE/BLEIngressPacketGuard.swift index 3081a5b3..ea2ae5cc 100644 --- a/bitchat/Services/BLE/BLEIngressPacketGuard.swift +++ b/bitchat/Services/BLE/BLEIngressPacketGuard.swift @@ -7,6 +7,7 @@ enum BLEIngressPacketGuard { case directSenderMismatch(boundPeerID: PeerID, claimedSenderID: PeerID) case invalidRSR(peerID: PeerID) case timestampSkew(peerID: PeerID, skewMs: UInt64, maxSkewMs: UInt64) + case requestSyncForAnotherPeer(peerID: PeerID) } static func evaluate( @@ -40,6 +41,7 @@ enum BLEIngressPacketGuard { switch validatePayload( packet, from: context.validationPeerID, + localPeerID: localPeerID, nowMs: nowMs, maxTimestampSkewMs: maxTimestampSkewMs, isValidSyncResponse: isValidSyncResponse @@ -54,10 +56,22 @@ enum BLEIngressPacketGuard { static func validatePayload( _ packet: BitchatPacket, from peerID: PeerID, + localPeerID: PeerID, nowMs: UInt64 = UInt64(Date().timeIntervalSince1970 * 1000), maxTimestampSkewMs: UInt64 = TransportConfig.bleMaxTimestampSkewMs, isValidSyncResponse: (PeerID) -> Bool ) -> Result { + // A directed REQUEST_SYNC is for its recipient only. A copy for + // another peer reaches us when the requester has no link to that + // peer: the send then falls back to every link. Reject it before + // the ingress and duplicate records. Its packet ID has no recipient, + // so it can hide the copy addressed to us from the same round. + if packet.type == MessageType.requestSync.rawValue, + !BLEPacketFreshnessPolicy.isBroadcastRecipient(packet.recipientID), + packet.recipientID != localPeerID.routingData { + return .failure(.requestSyncForAnotherPeer(peerID: peerID)) + } + let packetTime = packet.timestamp if packet.isRSR { guard isValidSyncResponse(peerID) else { diff --git a/bitchat/Services/BLE/BLEService.swift b/bitchat/Services/BLE/BLEService.swift index a07e5d31..a54a9ead 100644 --- a/bitchat/Services/BLE/BLEService.swift +++ b/bitchat/Services/BLE/BLEService.swift @@ -1914,6 +1914,9 @@ final class BLEService: NSObject { case .failure(.timestampSkew(let peerID, let skewMs, let maxSkewMs)): SecureLogger.warning("Packet timestamp skewed by \(skewMs)ms (max \(maxSkewMs)ms) from \(peerID.id.prefix(8))…", category: .security) return nil + case .failure(.requestSyncForAnotherPeer(let peerID)): + logRequestSyncForAnotherPeer(from: peerID) + return nil } } @@ -1921,6 +1924,7 @@ final class BLEService: NSObject { switch BLEIngressPacketGuard.validatePayload( packet, from: peerID, + localPeerID: myPeerID, isValidSyncResponse: { [requestSyncManager] peerID in requestSyncManager.isValidResponse(from: peerID, isRSR: true) } @@ -1936,6 +1940,9 @@ final class BLEService: NSObject { case .failure(.timestampSkew(let peerID, let skewMs, let maxSkewMs)): SecureLogger.warning("Packet timestamp skewed by \(skewMs)ms (max \(maxSkewMs)ms) from \(peerID.id.prefix(8))…", category: .security) return false + case .failure(.requestSyncForAnotherPeer(let peerID)): + logRequestSyncForAnotherPeer(from: peerID) + return false case .failure(.selfLoopback), .failure(.directSenderMismatch): return false } @@ -1946,6 +1953,11 @@ final class BLEService: NSObject { SecureLogger.debug("Valid RSR packet from \(peerID.id.prefix(8))… - skipping past-timestamp check", category: .security) } + private func logRequestSyncForAnotherPeer(from peerID: PeerID) { + guard logRateLimiter.shouldLog(key: "sync-recipient:\(peerID.id)") else { return } + SecureLogger.debug("Ignoring REQUEST_SYNC addressed to another peer from \(peerID.id.prefix(8))…", category: .sync) + } + private func logSelfLoopback(packetType: UInt8, linkDescription: String) { guard logRateLimiter.shouldLog( key: "self-loopback:\(packetType)", diff --git a/bitchat/Sync/GossipSyncManager.swift b/bitchat/Sync/GossipSyncManager.swift index c54140f0..ae9dc7d8 100644 --- a/bitchat/Sync/GossipSyncManager.swift +++ b/bitchat/Sync/GossipSyncManager.swift @@ -385,17 +385,12 @@ final class GossipSyncManager { } private func sendRequestSync(to peerID: PeerID, types: SyncTypeFlags, fragmentIdFilter: String? = nil) { + // Responders answer only a request addressed to their 8-byte peer ID. + guard let recipient = peerID.routingData else { return } // Register the request for RSR validation requestSyncManager.registerRequest(to: peerID) let payload = buildGcsPayload(for: types, fragmentIdFilter: fragmentIdFilter) - var recipient = Data() - var temp = peerID.id - while temp.count >= 2 && recipient.count < 8 { - let hexByte = String(temp.prefix(2)) - if let b = UInt8(hexByte, radix: 16) { recipient.append(b) } - temp = String(temp.dropFirst(2)) - } let pkt = BitchatPacket( type: MessageType.requestSync.rawValue, senderID: Data(hexString: myPeerID.id) ?? Data(), diff --git a/bitchatTests/BLEServiceCoreTests.swift b/bitchatTests/BLEServiceCoreTests.swift index 13f2bb25..36e92450 100644 --- a/bitchatTests/BLEServiceCoreTests.swift +++ b/bitchatTests/BLEServiceCoreTests.swift @@ -292,6 +292,68 @@ struct BLEServiceCoreTests { #expect(!ble._test_acceptsIngress(packet: packet, boundPeerID: boundPeer)) } + /// A directed REQUEST_SYNC is for its recipient only. One periodic round + /// sends a copy to each connected peer, and the copies can share a packet + /// ID, because the ID has no recipient. A copy for a peer without a link + /// goes out on every link. We must not answer it, and it must not make our + /// own copy look like a duplicate. + @Test + func requestSyncIsAnsweredOnlyByItsRecipient() async throws { + let ble = makeService() + // Our own announce goes into the gossip store, so a request with an + // empty filter has something to receive. + ble.setNickname("tester") + ble._test_fenceEngine() + + let requester = NoiseEncryptionService(keychain: MockKeychain()) + let requesterID = PeerID(publicKey: requester.getStaticPublicKeyData()) + let now = UInt64(Date().timeIntervalSince1970 * 1000) + func signed(_ type: MessageType, to recipient: PeerID?, payload: Data, ttl: UInt8) throws -> BitchatPacket { + let unsigned = BitchatPacket( + type: type.rawValue, + senderID: Data(hexString: requesterID.id) ?? Data(), + recipientID: recipient?.routingData, + timestamp: now, + payload: payload, + signature: nil, + ttl: ttl + ) + return try #require(requester.signPacket(unsigned), "Failed to sign \(type)") + } + + // The requester announces on the link first, so its requests verify. + let link = BLEIngressLinkID.central("central-requester") + let announcement = AnnouncementPacket( + nickname: "requester", + noisePublicKey: requester.getStaticPublicKeyData(), + signingPublicKey: requester.getSigningPublicKeyData(), + directNeighbors: nil + ) + let announcePayload = try #require(announcement.encode(), "Failed to encode announcement") + ble._test_ingestFrame(try signed(.announce, to: nil, payload: announcePayload, ttl: 7), link: link) + ble._test_fenceEngine() + + let outbound = OutboundPacketTap() + ble._test_onOutboundPacket = outbound.record + let sentSyncReply = { outbound.snapshot().contains { $0.isRSR } } + let request = RequestSyncPacket(p: 4, m: 1, data: Data(), types: .publicMessages).encode() + + ble._test_ingestFrame( + try signed(.requestSync, to: PeerID(str: "8899aabbccddeeff"), payload: request, ttl: 0), + link: link + ) + let answeredForAnotherPeer = await TestHelpers.waitUntil( + sentSyncReply, + timeout: TestConstants.negativeWaitWindow + ) + #expect(!answeredForAnotherPeer) + + // The same packet ID, addressed to us. + ble._test_ingestFrame(try signed(.requestSync, to: ble.myPeerID, payload: request, ttl: 0), link: link) + let answeredForUs = await TestHelpers.waitUntil(sentSyncReply, timeout: TestConstants.longTimeout) + #expect(answeredForUs) + } + @Test func verifiedDirectAnnounceRebindsRotatedLinkAndRetiresOldPeer() async throws { let ble = makeService() diff --git a/bitchatTests/Services/BLEIngressPacketGuardTests.swift b/bitchatTests/Services/BLEIngressPacketGuardTests.swift index 37112a3d..3d6d3cd4 100644 --- a/bitchatTests/Services/BLEIngressPacketGuardTests.swift +++ b/bitchatTests/Services/BLEIngressPacketGuardTests.swift @@ -186,6 +186,7 @@ struct BLEIngressPacketGuardTests { let innerResult = BLEIngressPacketGuard.validatePayload( innerPacket, from: sender, + localPeerID: local, nowMs: nowMs, maxTimestampSkewMs: skewMs, isValidSyncResponse: { _ in true } @@ -217,16 +218,100 @@ struct BLEIngressPacketGuardTests { #expect(result == .failure(.invalidRSR(peerID: bound))) } + @Test("a REQUEST_SYNC addressed to another peer is rejected, also after reassembly") + func requestSyncForAnotherPeerIsRejected() { + let local = PeerID(str: "0011223344556677") + let sender = PeerID(str: "8899aabbccddeeff") + let packet = makePacket( + type: .requestSync, + sender: sender, + timestamp: 1_000, + ttl: 0, + recipient: Data(hexString: "1122334455667788") + ) + + let result = BLEIngressPacketGuard.evaluate( + packet: packet, + claimedSenderID: sender, + boundPeerID: nil, + localPeerID: local, + directAnnounceTTL: 7, + nowMs: 1_000, + isValidSyncResponse: { _ in false } + ) + #expect(result == .failure(.requestSyncForAnotherPeer(peerID: sender))) + + // Reassembled inner packets are checked through validatePayload alone. + let innerResult = BLEIngressPacketGuard.validatePayload( + packet, + from: sender, + localPeerID: local, + nowMs: 1_000, + isValidSyncResponse: { _ in false } + ) + guard case .failure(.requestSyncForAnotherPeer(peerID: sender)) = innerResult else { + Issue.record("Expected a reassembled REQUEST_SYNC for another peer to be rejected, got \(innerResult)") + return + } + } + + @Test( + "a REQUEST_SYNC passes when it is a broadcast or addressed to us", + arguments: [nil, Data(repeating: 0xFF, count: 8), Data(hexString: "0011223344556677")] + ) + func requestSyncForUsOrEveryonePasses(recipient: Data?) { + let local = PeerID(str: "0011223344556677") + let sender = PeerID(str: "8899aabbccddeeff") + let packet = makePacket(type: .requestSync, sender: sender, timestamp: 1_000, ttl: 0, recipient: recipient) + + let result = BLEIngressPacketGuard.evaluate( + packet: packet, + claimedSenderID: sender, + boundPeerID: nil, + localPeerID: local, + directAnnounceTTL: 7, + nowMs: 1_000, + isValidSyncResponse: { _ in false } + ) + + #expect(success(result) != nil) + } + + @Test("other packets addressed to another peer still pass, so they can be relayed") + func directedPacketsForOtherPeersStillPass() { + let local = PeerID(str: "0011223344556677") + let sender = PeerID(str: "8899aabbccddeeff") + let packet = makePacket( + type: .noiseEncrypted, + sender: sender, + timestamp: 1_000, + recipient: Data(hexString: "1122334455667788") + ) + + let result = BLEIngressPacketGuard.evaluate( + packet: packet, + claimedSenderID: sender, + boundPeerID: nil, + localPeerID: local, + directAnnounceTTL: 7, + nowMs: 1_000, + isValidSyncResponse: { _ in false } + ) + + #expect(success(result) != nil) + } + private func makePacket( type: MessageType = .message, sender: PeerID, timestamp: UInt64, - ttl: UInt8 = 3 + ttl: UInt8 = 3, + recipient: Data? = nil ) -> BitchatPacket { BitchatPacket( type: type.rawValue, senderID: Data(hexString: sender.id) ?? Data(), - recipientID: nil, + recipientID: recipient, timestamp: timestamp, payload: Data([0x01, 0x02, 0x03]), signature: nil, diff --git a/docs/REQUEST_SYNC_MANAGER.md b/docs/REQUEST_SYNC_MANAGER.md index a885f159..ed4cd0f2 100644 --- a/docs/REQUEST_SYNC_MANAGER.md +++ b/docs/REQUEST_SYNC_MANAGER.md @@ -44,6 +44,7 @@ A new component (`Sync/RequestSyncManager.swift`) responsible for: * **Conditional Exemption**: If `packet.isRSR` is true (or packet is a legacy TTL=0 response), it queries `RequestSyncManager`. * **Valid**: If solicited, timestamp check is skipped (allowing historical data sync). * **Invalid**: If unsolicited or timed out, the packet is rejected. +* **Recipient Check**: A directed `REQUEST_SYNC` is answered only by its recipient. Ingress drops a copy addressed to another peer before the duplicate checks. Copies of one periodic round can share a packet ID, so a stray copy must not hide the right one. Other clients must address a directed request with the responder's 8-byte peer ID. ## Usage