mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-11-29 08:29:22 +00:00
Fix concurrency races across BLE, TorManager, SecureNoiseSession, and ChatViewModel (#1886)
This commit is contained in:
5 files changed
+255
-52
No files matched your search
@@ -9,21 +9,28 @@
|
||||
import Foundation
|
||||
|
||||
final class SecureNoiseSession: NoiseSession {
|
||||
private(set) var messageCount: UInt64 = 0
|
||||
private var sessionStartTime = Date()
|
||||
private(set) var lastActivityTime = Date()
|
||||
|
||||
private let stateLock = NSLock()
|
||||
private var _messageCount: UInt64 = 0
|
||||
private var _sessionStartTime = Date()
|
||||
private var _lastActivityTime = Date()
|
||||
|
||||
override func encrypt(_ plaintext: Data) throws -> Data {
|
||||
let now = Date()
|
||||
stateLock.lock()
|
||||
let startTime = _sessionStartTime
|
||||
let count = _messageCount
|
||||
stateLock.unlock()
|
||||
|
||||
// Check session age
|
||||
if Date().timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout {
|
||||
if now.timeIntervalSince(startTime) > NoiseSecurityConstants.sessionTimeout {
|
||||
throw NoiseSecurityError.sessionExpired
|
||||
}
|
||||
|
||||
|
||||
// Check message count
|
||||
if messageCount >= NoiseSecurityConstants.maxMessagesPerSession {
|
||||
if count >= NoiseSecurityConstants.maxMessagesPerSession {
|
||||
throw NoiseSecurityError.sessionExhausted
|
||||
}
|
||||
|
||||
|
||||
// Ordinary Noise messages keep the protocol ceiling. Finalized media
|
||||
// is the sole typed-payload extension and remains under the framed-file
|
||||
// cap enforced again at the service and file-decoder layers.
|
||||
@@ -32,20 +39,27 @@ final class SecureNoiseSession: NoiseSession {
|
||||
guard NoiseSecurityValidator.validateMessageSize(plaintext) || isPrivateFile else {
|
||||
throw NoiseSecurityError.messageTooLarge
|
||||
}
|
||||
|
||||
|
||||
let encrypted = try super.encrypt(plaintext)
|
||||
messageCount += 1
|
||||
lastActivityTime = Date()
|
||||
|
||||
stateLock.lock()
|
||||
_messageCount += 1
|
||||
_lastActivityTime = Date()
|
||||
stateLock.unlock()
|
||||
|
||||
return encrypted
|
||||
}
|
||||
|
||||
|
||||
override func decrypt(_ ciphertext: Data) throws -> Data {
|
||||
let now = Date()
|
||||
stateLock.lock()
|
||||
let startTime = _sessionStartTime
|
||||
stateLock.unlock()
|
||||
|
||||
// Check session age
|
||||
if Date().timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout {
|
||||
if now.timeIntervalSince(startTime) > NoiseSecurityConstants.sessionTimeout {
|
||||
throw NoiseSecurityError.sessionExpired
|
||||
}
|
||||
|
||||
|
||||
// The payload type is encrypted, so a large candidate can only be
|
||||
// bounded here; `NoiseEncryptionService.decrypt` authenticates it and
|
||||
// then requires the resulting type to be `.privateFile`.
|
||||
@@ -53,22 +67,31 @@ final class SecureNoiseSession: NoiseSession {
|
||||
|| NoiseSecurityValidator.validatePrivateFileCiphertextSize(ciphertext) else {
|
||||
throw NoiseSecurityError.messageTooLarge
|
||||
}
|
||||
|
||||
|
||||
let decrypted = try super.decrypt(ciphertext)
|
||||
lastActivityTime = Date()
|
||||
|
||||
stateLock.lock()
|
||||
_lastActivityTime = Date()
|
||||
stateLock.unlock()
|
||||
|
||||
return decrypted
|
||||
}
|
||||
|
||||
|
||||
func needsRenegotiation() -> Bool {
|
||||
let now = Date()
|
||||
stateLock.lock()
|
||||
let count = _messageCount
|
||||
let lastActivity = _lastActivityTime
|
||||
let startTime = _sessionStartTime
|
||||
stateLock.unlock()
|
||||
|
||||
// Check if we've used more than 90% of message limit
|
||||
let messageThreshold = UInt64(Double(NoiseSecurityConstants.maxMessagesPerSession) * 0.9)
|
||||
if messageCount >= messageThreshold {
|
||||
if count >= messageThreshold {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check if last activity exceeded sessionTimeout
|
||||
if Date().timeIntervalSince(lastActivityTime) > NoiseSecurityConstants.sessionTimeout {
|
||||
if now.timeIntervalSince(lastActivity) > NoiseSecurityConstants.sessionTimeout {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -80,25 +103,31 @@ final class SecureNoiseSession: NoiseSession {
|
||||
// (checked every 60s, see NoiseEncryptionService.rekeyCheckInterval)
|
||||
// room to complete a full handshake well before the old session
|
||||
// starts throwing sessionExpired on every call.
|
||||
if Date().timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout * 0.9 {
|
||||
if now.timeIntervalSince(startTime) > NoiseSecurityConstants.sessionTimeout * 0.9 {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Testing Support
|
||||
#if DEBUG
|
||||
func setLastActivityTimeForTesting(_ date: Date) {
|
||||
lastActivityTime = date
|
||||
stateLock.lock()
|
||||
_lastActivityTime = date
|
||||
stateLock.unlock()
|
||||
}
|
||||
|
||||
|
||||
func setMessageCountForTesting(_ count: UInt64) {
|
||||
messageCount = count
|
||||
stateLock.lock()
|
||||
_messageCount = count
|
||||
stateLock.unlock()
|
||||
}
|
||||
|
||||
func setSessionStartTimeForTesting(_ date: Date) {
|
||||
sessionStartTime = date
|
||||
stateLock.lock()
|
||||
_sessionStartTime = date
|
||||
stateLock.unlock()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -491,15 +491,22 @@ final class BLEService: NSObject {
|
||||
)
|
||||
|
||||
// Debounced publish to coalesce rapid changes
|
||||
private let peerPublishCoalescerLock = NSLock()
|
||||
private var peerPublishCoalescer = BLEPeerPublishCoalescer()
|
||||
private func requestPeerDataPublish() {
|
||||
switch peerPublishCoalescer.requestPublish(now: Date()) {
|
||||
peerPublishCoalescerLock.lock()
|
||||
let action = peerPublishCoalescer.requestPublish(now: Date())
|
||||
peerPublishCoalescerLock.unlock()
|
||||
|
||||
switch action {
|
||||
case .publishNow:
|
||||
publishFullPeerData()
|
||||
case .schedule(let delay):
|
||||
engineScheduler.schedule(after: delay) { [weak self] in
|
||||
guard let self = self else { return }
|
||||
self.peerPublishCoalescerLock.lock()
|
||||
self.peerPublishCoalescer.scheduledPublishFired(now: Date())
|
||||
self.peerPublishCoalescerLock.unlock()
|
||||
self.publishFullPeerData()
|
||||
}
|
||||
case .skip:
|
||||
@@ -1088,9 +1095,12 @@ final class BLEService: NSObject {
|
||||
}
|
||||
}
|
||||
|
||||
// Send to centrals subscribed to us as peripheral
|
||||
// Send to centrals subscribed to us as peripheral (on bleQueue to
|
||||
// stay affine with CBPeripheralManager delegate callbacks).
|
||||
if centralsCount > 0, let ch = char {
|
||||
peripheralManager?.updateValue(data, for: ch, onSubscribedCentrals: nil)
|
||||
bleQueue.sync {
|
||||
_ = self.peripheralManager?.updateValue(data, for: ch, onSubscribedCentrals: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2241,12 +2251,18 @@ final class BLEService: NSObject {
|
||||
}
|
||||
|
||||
// Notify via central link (dual-role)
|
||||
if let characteristic = characteristic, !sentEncrypted, let recipientCentral {
|
||||
let success = peripheralManager?.updateValue(data, for: characteristic, onSubscribedCentrals: [recipientCentral]) ?? false
|
||||
if success {
|
||||
if !sentEncrypted,
|
||||
let recipientCentral,
|
||||
let localCharacteristic = readLinkState({ _ in self.characteristic }) {
|
||||
let accepted = notifyOrEnqueueIfAccepted(
|
||||
data: data,
|
||||
centrals: [recipientCentral],
|
||||
characteristic: localCharacteristic,
|
||||
context: "encrypted",
|
||||
requiredAuthenticatedPeer: nil
|
||||
)
|
||||
if accepted {
|
||||
sentEncrypted = true
|
||||
} else {
|
||||
enqueuePendingNotification(data: data, centrals: [recipientCentral], context: "encrypted")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2363,6 +2379,28 @@ final class BLEService: NSObject {
|
||||
return bleQueue.sync(execute: accept)
|
||||
}
|
||||
|
||||
private func notifyOrEnqueueOnBLEQueue(
|
||||
data: Data,
|
||||
centrals: [CBCentral],
|
||||
characteristic: CBMutableCharacteristic,
|
||||
context: String
|
||||
) {
|
||||
guard !isPanicSuspended else { return }
|
||||
bleQueue.async { [weak self] in
|
||||
guard let self = self, !self.isPanicSuspended else { return }
|
||||
let success = self.peripheralManager?.updateValue(
|
||||
data,
|
||||
for: characteristic,
|
||||
onSubscribedCentrals: centrals
|
||||
) ?? false
|
||||
if !success {
|
||||
// Notification queue full - queue for retry to prevent silent packet loss
|
||||
// This is critical for fragment delivery reliability
|
||||
self.enqueuePendingNotification(data: data, centrals: centrals, context: context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true only when the packet was accepted by at least one current
|
||||
/// physical link (including its link-specific backpressure queue). A
|
||||
/// process-local directed spool is deliberately not success: callers
|
||||
@@ -2387,7 +2425,8 @@ final class BLEService: NSObject {
|
||||
// silently dropped if its bound link is still mid-rediscovery.
|
||||
let connectedStates = states.filter { $0.isConnected && $0.characteristic != nil }
|
||||
let centralSnapshot = allLinks.centralSnapshot
|
||||
let subscribedCentrals = characteristic == nil ? [] : centralSnapshot.centrals
|
||||
let localCharacteristic = allLinks.characteristic
|
||||
let subscribedCentrals = localCharacteristic == nil ? [] : centralSnapshot.centrals
|
||||
|
||||
// Fast path when no physical links are active: skip ingress SHA-256,
|
||||
// binding dictionaries, and fanout planning; delegate the spooling
|
||||
@@ -2491,7 +2530,7 @@ final class BLEService: NSObject {
|
||||
}
|
||||
}
|
||||
// Notify selected subscribed centrals
|
||||
if let ch = characteristic {
|
||||
if let ch = localCharacteristic {
|
||||
let targets = subscribedCentrals.filter { plan.selectedLinks.centralIDs.contains($0.identifier.uuidString) }
|
||||
if !targets.isEmpty {
|
||||
if requireDirectPeerLink || requireNoiseAuthenticatedPeerLink {
|
||||
@@ -2503,13 +2542,13 @@ final class BLEService: NSObject {
|
||||
requiredAuthenticatedPeer: requireNoiseAuthenticatedPeerLink ? directedOnlyPeer : nil
|
||||
) || acceptedByPhysicalLink
|
||||
} else {
|
||||
let success = peripheralManager?.updateValue(data, for: ch, onSubscribedCentrals: targets) ?? false
|
||||
if !success {
|
||||
// Notification queue full - queue for retry to prevent silent packet loss
|
||||
// This is critical for fragment delivery reliability
|
||||
let context = packet.type == MessageType.fragment.rawValue ? "fragment" : "broadcast"
|
||||
enqueuePendingNotification(data: data, centrals: targets, context: context)
|
||||
}
|
||||
let context = packet.type == MessageType.fragment.rawValue ? "fragment" : "broadcast"
|
||||
notifyOrEnqueueOnBLEQueue(
|
||||
data: data,
|
||||
centrals: targets,
|
||||
characteristic: ch,
|
||||
context: context
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5212,16 +5251,24 @@ extension BLEService {
|
||||
}
|
||||
}
|
||||
|
||||
/// Snapshots both physical link tables in a single `bleQueue.sync` hop
|
||||
/// alongside the engine's central-UUID bindings. Engine-confined.
|
||||
private func snapshotAllLinks() -> (peripheralStates: [BLEPeripheralLinkState], centralSnapshot: BLESubscribedCentralSnapshot) {
|
||||
let (peripherals, centrals) = readLinkState { ($0.peripheralStates, $0.subscribedCentrals) }
|
||||
/// Snapshots both physical link tables and the peripheral characteristic in
|
||||
/// a single `bleQueue.sync` hop alongside the engine's central-UUID bindings.
|
||||
/// Engine-confined.
|
||||
private func snapshotAllLinks() -> (
|
||||
peripheralStates: [BLEPeripheralLinkState],
|
||||
centralSnapshot: BLESubscribedCentralSnapshot,
|
||||
characteristic: CBMutableCharacteristic?
|
||||
) {
|
||||
let (peripherals, centrals, localCharacteristic) = readLinkState {
|
||||
($0.peripheralStates, $0.subscribedCentrals, self.characteristic)
|
||||
}
|
||||
return (
|
||||
peripheralStates: peripherals,
|
||||
centralSnapshot: BLESubscribedCentralSnapshot(
|
||||
centrals: centrals,
|
||||
peerIDsByCentralUUID: linkBindings.centralPeersByUUID
|
||||
)
|
||||
),
|
||||
characteristic: localCharacteristic
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1323,6 +1323,12 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
_ = panicClearAllData(restartServices: false)
|
||||
}
|
||||
|
||||
// Eagerly initialize coordinators before transports attach so non-main
|
||||
// BitchatDelegate callers (e.g. test transports like MockTransport or
|
||||
// any future off-main delegate delivery) cannot race Swift lazy var init.
|
||||
_ = transportEventCoordinator
|
||||
_ = peerListCoordinator
|
||||
|
||||
if networkActivationAllowed {
|
||||
ChatViewModelBootstrapper(viewModel: self).configure()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
//
|
||||
// SecureNoiseSessionConcurrencyTests.swift
|
||||
// bitchatTests
|
||||
//
|
||||
// This is free and unencumbered software released into the public domain.
|
||||
// For more information, see <https://unlicense.org>
|
||||
//
|
||||
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
import Testing
|
||||
import BitFoundation
|
||||
@testable import bitchat
|
||||
|
||||
struct SecureNoiseSessionConcurrencyTests {
|
||||
|
||||
private func makeEstablishedPair() throws -> (initiator: SecureNoiseSession, responder: SecureNoiseSession) {
|
||||
let aliceKey = Curve25519.KeyAgreement.PrivateKey()
|
||||
let bobKey = Curve25519.KeyAgreement.PrivateKey()
|
||||
let keychain = MockKeychain()
|
||||
|
||||
let alice = SecureNoiseSession(
|
||||
peerID: PeerID(publicKey: bobKey.publicKey.rawRepresentation),
|
||||
role: .initiator,
|
||||
keychain: keychain,
|
||||
localStaticKey: aliceKey
|
||||
)
|
||||
let bob = SecureNoiseSession(
|
||||
peerID: PeerID(publicKey: aliceKey.publicKey.rawRepresentation),
|
||||
role: .responder,
|
||||
keychain: keychain,
|
||||
localStaticKey: bobKey
|
||||
)
|
||||
|
||||
let msg1 = try alice.startHandshake()
|
||||
let msg2 = try #require(try bob.processHandshakeMessage(msg1))
|
||||
let msg3 = try #require(try alice.processHandshakeMessage(msg2))
|
||||
_ = try bob.processHandshakeMessage(msg3)
|
||||
|
||||
#expect(alice.getState() == .established)
|
||||
#expect(bob.getState() == .established)
|
||||
return (alice, bob)
|
||||
}
|
||||
|
||||
@Test func concurrentEncryptDecryptAndRenegotiationCheckAreThreadSafe() throws {
|
||||
let (alice, bob) = try makeEstablishedPair()
|
||||
let iterations = 200
|
||||
let ciphertextsLock = NSLock()
|
||||
var ciphertexts: [Data] = []
|
||||
ciphertexts.reserveCapacity(iterations)
|
||||
var encryptionErrors: [Error] = []
|
||||
|
||||
DispatchQueue.concurrentPerform(iterations: iterations) { index in
|
||||
do {
|
||||
let payload = Data("msg-\(index)".utf8)
|
||||
let encrypted = try alice.encrypt(payload)
|
||||
_ = alice.needsRenegotiation()
|
||||
ciphertextsLock.lock()
|
||||
ciphertexts.append(encrypted)
|
||||
ciphertextsLock.unlock()
|
||||
} catch {
|
||||
ciphertextsLock.lock()
|
||||
encryptionErrors.append(error)
|
||||
ciphertextsLock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
#expect(encryptionErrors.isEmpty)
|
||||
#expect(ciphertexts.count == iterations)
|
||||
|
||||
let decryptedLock = NSLock()
|
||||
var decryptedPayloads: Set<String> = []
|
||||
var decryptionErrors: [Error] = []
|
||||
|
||||
DispatchQueue.concurrentPerform(iterations: ciphertexts.count) { index in
|
||||
do {
|
||||
let plaintext = try bob.decrypt(ciphertexts[index])
|
||||
_ = bob.needsRenegotiation()
|
||||
if let text = String(data: plaintext, encoding: .utf8) {
|
||||
decryptedLock.lock()
|
||||
decryptedPayloads.insert(text)
|
||||
decryptedLock.unlock()
|
||||
}
|
||||
} catch {
|
||||
decryptedLock.lock()
|
||||
decryptionErrors.append(error)
|
||||
decryptedLock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
#expect(decryptionErrors.isEmpty)
|
||||
#expect(decryptedPayloads.count == iterations)
|
||||
}
|
||||
|
||||
@Test func renegotiationThresholdTriggersUnderConcurrentIncrements() throws {
|
||||
let (alice, _) = try makeEstablishedPair()
|
||||
let threshold = UInt64(Double(NoiseSecurityConstants.maxMessagesPerSession) * 0.9)
|
||||
let batch = 50
|
||||
alice.setMessageCountForTesting(threshold - UInt64(batch))
|
||||
#expect(!alice.needsRenegotiation())
|
||||
|
||||
let errorLock = NSLock()
|
||||
var errors: [Error] = []
|
||||
|
||||
DispatchQueue.concurrentPerform(iterations: batch) { index in
|
||||
do {
|
||||
_ = try alice.encrypt(Data("rekey-\(index)".utf8))
|
||||
} catch {
|
||||
errorLock.lock()
|
||||
errors.append(error)
|
||||
errorLock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
#expect(errors.isEmpty)
|
||||
#expect(alice.needsRenegotiation())
|
||||
}
|
||||
}
|
||||
@@ -274,7 +274,9 @@ public final class TorManager: ObservableObject {
|
||||
// already-running Arti instances (fenced to this bootstrap
|
||||
// generation) so `socksReady` cannot remain stuck at `false`
|
||||
// after dormancy or an overlapping restart.
|
||||
let ready = await self.waitForSocksReady(port: port, timeout: 60.0)
|
||||
// Timeout exceeds bootstrapPollLoop's 75s deadline because Arti
|
||||
// binds the SOCKS port only after bootstrap reaches 100%.
|
||||
let ready = await self.waitForSocksReady(port: port, timeout: 80.0)
|
||||
await MainActor.run {
|
||||
guard generation == self.bootstrapGeneration else { return }
|
||||
self.socksReady = ready
|
||||
@@ -318,6 +320,7 @@ public final class TorManager: ObservableObject {
|
||||
}
|
||||
let endpoint = NWEndpoint.hostPort(host: host, port: port)
|
||||
let conn = NWConnection(to: endpoint, using: params)
|
||||
let probeQueue = DispatchQueue(label: "chat.bitchat.tor.socks-probe", qos: .utility)
|
||||
|
||||
let resumed = AtomicOnceFlag()
|
||||
let resumeOnce: @Sendable (Bool) -> Void = { value in
|
||||
@@ -338,12 +341,12 @@ public final class TorManager: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 1.0) {
|
||||
probeQueue.asyncAfter(deadline: .now() + 1.0) {
|
||||
resumeOnce(false)
|
||||
conn.cancel()
|
||||
}
|
||||
|
||||
conn.start(queue: DispatchQueue.global(qos: .utility))
|
||||
conn.start(queue: probeQueue)
|
||||
}
|
||||
#else
|
||||
_ = socksPort
|
||||
|
||||
Reference in new issue
Block a user