mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-26 19:05:22 +00:00
Encrypt private media before BLE fragmentation (#1434)
Closes the last cleartext private-content path over BLE: private DM images/voice were sent as plaintext signed fileTransfer packets, TTL-relayed across the mesh, so every relay saw the full bytes. Now the complete BitchatFilePacket is encrypted as a single Noise AEAD message (inner type 0x20, matching Android) and the opaque ciphertext is fragmented. Adds an authenticated in-session capability proof (0x21 TLV: capabilities + Ed25519 key), TOFU-style downgrade pinning, a per-send consent dialog for the signed-cleartext fallback to legacy peers, and a cancellation/admission registry so cancel/delete cannot race a deferred cleartext send. Android wire constants (0x20 / 0x21 / capability bit 8) confirmed shipping. The 256-fragment preflight cap applies only to the directed fileTransfer migration fallback; encrypted media to capable peers uses the full receiver ceiling. Rebased over #1428/#1349: identity reads go through BLELocalIdentityStateStore; the session-bound authenticated signing-key check and the announce-path TOFU pin are kept as complementary checks. Full local suite green (1744+197 tests).
This commit is contained in:
@@ -542,8 +542,12 @@ struct NoiseCoverageTests {
|
||||
let aliceManager = NoiseSessionManager(localStaticKey: aliceStaticKey, keychain: keychain)
|
||||
let bobManager = NoiseSessionManager(localStaticKey: bobStaticKey, keychain: keychain)
|
||||
|
||||
aliceManager.onSessionEstablished = establishedRecorder.recordEstablished(peerID:remoteKey:)
|
||||
bobManager.onSessionEstablished = establishedRecorder.recordEstablished(peerID:remoteKey:)
|
||||
aliceManager.onSessionEstablished = establishedRecorder.recordEstablished(
|
||||
peerID:remoteKey:sessionGeneration:
|
||||
)
|
||||
bobManager.onSessionEstablished = establishedRecorder.recordEstablished(
|
||||
peerID:remoteKey:sessionGeneration:
|
||||
)
|
||||
|
||||
try establishManagerSessions(aliceManager: aliceManager, bobManager: bobManager)
|
||||
|
||||
@@ -650,13 +654,121 @@ struct NoiseCoverageTests {
|
||||
try aliceManager.initiateHandshake(with: alicePeerID)
|
||||
}
|
||||
|
||||
try aliceManager.initiateRekey(for: alicePeerID)
|
||||
let rekeyHandshake = try aliceManager.initiateRekey(for: alicePeerID)
|
||||
#expect(!rekeyHandshake.isEmpty)
|
||||
let rekeyedSession = try #require(aliceManager.getSession(for: alicePeerID))
|
||||
|
||||
#expect(rekeyedSession !== establishedSession)
|
||||
#expect(rekeyedSession.getState() == .handshaking)
|
||||
}
|
||||
|
||||
@Test("A stale decrypt generation cannot commit across session promotion")
|
||||
func staleDecryptGenerationCannotCommitAcrossPromotion() throws {
|
||||
let aliceManager = NoiseSessionManager(
|
||||
localStaticKey: aliceStaticKey,
|
||||
keychain: keychain,
|
||||
sessionFactory: { peerID, role in
|
||||
BlockingDecryptNoiseSession(
|
||||
peerID: peerID,
|
||||
role: role,
|
||||
keychain: self.keychain,
|
||||
localStaticKey: self.aliceStaticKey
|
||||
)
|
||||
}
|
||||
)
|
||||
let bobManager = NoiseSessionManager(localStaticKey: bobStaticKey, keychain: keychain)
|
||||
try establishManagerSessions(aliceManager: aliceManager, bobManager: bobManager)
|
||||
|
||||
let oldSession = try #require(
|
||||
aliceManager.getSession(for: alicePeerID) as? BlockingDecryptNoiseSession
|
||||
)
|
||||
let oldGeneration = try #require(aliceManager.sessionGeneration(for: alicePeerID))
|
||||
|
||||
// Prepare a fully authenticated responder candidate without promoting
|
||||
// it yet. Its final XX message is the exact operation that replaces
|
||||
// the old `sessions[peerID]` entry.
|
||||
let replacementInitiator = NoiseSession(
|
||||
peerID: bobPeerID,
|
||||
role: .initiator,
|
||||
keychain: keychain,
|
||||
localStaticKey: bobStaticKey
|
||||
)
|
||||
let message1 = try replacementInitiator.startHandshake()
|
||||
let message2 = try #require(
|
||||
try aliceManager.handleIncomingHandshake(from: alicePeerID, message: message1)
|
||||
)
|
||||
let message3 = try #require(try replacementInitiator.processHandshakeMessage(message2))
|
||||
|
||||
let ciphertext = try bobManager.encrypt(Data("old session".utf8), for: bobPeerID)
|
||||
oldSession.pauseNextDecrypt()
|
||||
|
||||
let decryptResult = ConcurrentTestResult<(plaintext: Data, sessionGeneration: UUID)>()
|
||||
var promotionResultForCleanup: ConcurrentTestResult<Data?>?
|
||||
defer {
|
||||
// A failed startup requirement must not strand a late thread in
|
||||
// the blocking test double after the test has returned.
|
||||
oldSession.resumeDecrypt()
|
||||
_ = decryptResult.wait(timeout: 5)
|
||||
if let promotionResultForCleanup {
|
||||
_ = promotionResultForCleanup.wait(timeout: 5)
|
||||
}
|
||||
}
|
||||
|
||||
let decryptThread = Thread {
|
||||
decryptResult.capture {
|
||||
try aliceManager.decryptWithSessionGeneration(ciphertext, from: self.alicePeerID)
|
||||
}
|
||||
}
|
||||
decryptThread.name = "NoiseCoverageTests.staleDecrypt.decrypt"
|
||||
decryptThread.qualityOfService = .userInitiated
|
||||
decryptThread.start()
|
||||
try #require(oldSession.waitForDecryptStart(timeout: 5))
|
||||
|
||||
let promotionStarted = DispatchSemaphore(value: 0)
|
||||
let promotionResult = ConcurrentTestResult<Data?>()
|
||||
promotionResultForCleanup = promotionResult
|
||||
let promotionThread = Thread {
|
||||
promotionStarted.signal()
|
||||
promotionResult.capture {
|
||||
try aliceManager.handleIncomingHandshake(from: self.alicePeerID, message: message3)
|
||||
}
|
||||
}
|
||||
promotionThread.name = "NoiseCoverageTests.staleDecrypt.promote"
|
||||
promotionThread.qualityOfService = .userInitiated
|
||||
promotionThread.start()
|
||||
try #require(promotionStarted.wait(timeout: .now() + 5) == .success)
|
||||
#expect(
|
||||
promotionResult.wait(timeout: 0.05) == nil,
|
||||
"Promotion must wait for the exact decrypting-session lease"
|
||||
)
|
||||
|
||||
oldSession.resumeDecrypt()
|
||||
let decrypted = try #require(decryptResult.wait(timeout: 5)).get()
|
||||
_ = try #require(promotionResult.wait(timeout: 5)).get()
|
||||
|
||||
#expect(decrypted.plaintext == Data("old session".utf8))
|
||||
#expect(decrypted.sessionGeneration == oldGeneration)
|
||||
#expect(aliceManager.sessionGeneration(for: alicePeerID) != oldGeneration)
|
||||
#expect(throws: NoiseEncryptionError.sessionNotEstablished) {
|
||||
try aliceManager.encrypt(
|
||||
Data("stale send".utf8),
|
||||
for: alicePeerID,
|
||||
expectedSessionGeneration: oldGeneration
|
||||
)
|
||||
}
|
||||
|
||||
var staleCommitRan = false
|
||||
let staleCommit = aliceManager.withCurrentSessionGeneration(
|
||||
for: alicePeerID,
|
||||
expected: decrypted.sessionGeneration
|
||||
) {
|
||||
staleCommitRan = true
|
||||
return true
|
||||
}
|
||||
#expect(staleCommit == nil)
|
||||
#expect(!staleCommitRan)
|
||||
}
|
||||
|
||||
@Test("Secure noise sessions enforce limits and renegotiation thresholds")
|
||||
func secureNoiseSessionsEnforceLimitsAndThresholds() throws {
|
||||
let initiator = SecureNoiseSession(
|
||||
@@ -851,7 +963,11 @@ private final class SessionCallbackRecorder: @unchecked Sendable {
|
||||
return establishedEntries.map(\.0)
|
||||
}
|
||||
|
||||
func recordEstablished(peerID: PeerID, remoteKey: Curve25519.KeyAgreement.PublicKey) {
|
||||
func recordEstablished(
|
||||
peerID: PeerID,
|
||||
remoteKey: Curve25519.KeyAgreement.PublicKey,
|
||||
sessionGeneration _: UUID
|
||||
) {
|
||||
lock.lock()
|
||||
establishedEntries.append((peerID, remoteKey.rawRepresentation))
|
||||
lock.unlock()
|
||||
@@ -873,3 +989,62 @@ private final class FailingNoiseSession: NoiseSession {
|
||||
throw Error.synthetic
|
||||
}
|
||||
}
|
||||
|
||||
private final class BlockingDecryptNoiseSession: NoiseSession, @unchecked Sendable {
|
||||
private let controlLock = NSLock()
|
||||
private var shouldPauseNextDecrypt = false
|
||||
private let decryptStarted = DispatchSemaphore(value: 0)
|
||||
private let resumeDecryptSemaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
func pauseNextDecrypt() {
|
||||
controlLock.lock()
|
||||
shouldPauseNextDecrypt = true
|
||||
controlLock.unlock()
|
||||
}
|
||||
|
||||
func waitForDecryptStart(timeout: TimeInterval) -> Bool {
|
||||
decryptStarted.wait(timeout: .now() + timeout) == .success
|
||||
}
|
||||
|
||||
func resumeDecrypt() {
|
||||
resumeDecryptSemaphore.signal()
|
||||
}
|
||||
|
||||
override func decrypt(_ ciphertext: Data) throws -> Data {
|
||||
controlLock.lock()
|
||||
let shouldPause = shouldPauseNextDecrypt
|
||||
shouldPauseNextDecrypt = false
|
||||
controlLock.unlock()
|
||||
|
||||
if shouldPause {
|
||||
decryptStarted.signal()
|
||||
resumeDecryptSemaphore.wait()
|
||||
}
|
||||
return try super.decrypt(ciphertext)
|
||||
}
|
||||
}
|
||||
|
||||
private final class ConcurrentTestResult<Value>: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private let completed = DispatchGroup()
|
||||
private var storedResult: Result<Value, Error>?
|
||||
|
||||
init() {
|
||||
completed.enter()
|
||||
}
|
||||
|
||||
func capture(_ operation: () throws -> Value) {
|
||||
let result = Result(catching: operation)
|
||||
lock.lock()
|
||||
storedResult = result
|
||||
lock.unlock()
|
||||
completed.leave()
|
||||
}
|
||||
|
||||
func wait(timeout: TimeInterval) -> Result<Value, Error>? {
|
||||
guard completed.wait(timeout: .now() + timeout) == .success else { return nil }
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return storedResult
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user