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