mirror of
https://github.com/permissionlesstech/bitchat-android.git
synced 2026-07-25 03:05:20 +00:00
improve identity announcements (#198)
* improve identity announcements * touches * signing noise id * panic mode delete signing key
This commit is contained in:
@@ -41,13 +41,23 @@ class BluetoothConnectionManager(
|
||||
// Delegate for component managers to call back to main manager
|
||||
private val componentDelegate = object : BluetoothConnectionManagerDelegate {
|
||||
override fun onPacketReceived(packet: BitchatPacket, peerID: String, device: BluetoothDevice?) {
|
||||
Log.d(TAG, "onPacketReceived: Packet received from ${device?.address} ($peerID)")
|
||||
device?.let { bluetoothDevice ->
|
||||
// if connection does not have a peerID yet, we assume that the first package
|
||||
// we receive from that connection is from the peer
|
||||
if (!connectionTracker.addressPeerMap.containsKey(device.address)) {
|
||||
Log.d(TAG, "First packet received from new device: ${bluetoothDevice.address}, assuming peerID: $peerID")
|
||||
connectionTracker.addressPeerMap[device.address] = peerID
|
||||
}
|
||||
// Get current RSSI for this device and update if available
|
||||
val currentRSSI = connectionTracker.getBestRSSI(bluetoothDevice.address)
|
||||
if (currentRSSI != null) {
|
||||
delegate?.onRSSIUpdated(bluetoothDevice.address, currentRSSI)
|
||||
}
|
||||
}
|
||||
|
||||
if (peerID == myPeerID) return // Ignore messages from self
|
||||
|
||||
delegate?.onPacketReceived(packet, peerID, device)
|
||||
}
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ class BluetoothConnectionTracker(
|
||||
* Add a device connection
|
||||
*/
|
||||
fun addDeviceConnection(deviceAddress: String, deviceConn: DeviceConnection) {
|
||||
Log.d(TAG, "Tracker: Adding device connection for $deviceAddress")
|
||||
Log.d(TAG, "Tracker: Adding device connection for $deviceAddress (isClient: ${deviceConn.isClient}")
|
||||
connectedDevices[deviceAddress] = deviceConn
|
||||
pendingConnections.remove(deviceAddress)
|
||||
}
|
||||
|
||||
@@ -133,6 +133,13 @@ class BluetoothGattServerManager(
|
||||
isClient = false
|
||||
)
|
||||
connectionTracker.addDeviceConnection(device.address, deviceConn)
|
||||
|
||||
connectionScope.launch {
|
||||
delay(1000)
|
||||
if (isActive) { // Check if still active
|
||||
delegate?.onDeviceConnected(device)
|
||||
}
|
||||
}
|
||||
}
|
||||
BluetoothProfile.STATE_DISCONNECTED -> {
|
||||
Log.i(TAG, "Server: Device disconnected ${device.address}")
|
||||
@@ -204,9 +211,9 @@ class BluetoothGattServerManager(
|
||||
}
|
||||
|
||||
if (BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE.contentEquals(value)) {
|
||||
Log.d(TAG, "Device ${device.address} subscribed to notifications")
|
||||
connectionTracker.addSubscribedDevice(device)
|
||||
|
||||
|
||||
Log.d(TAG, "Server: Connection setup complete for ${device.address}")
|
||||
connectionScope.launch {
|
||||
delay(100)
|
||||
if (isActive) { // Check if still active
|
||||
@@ -272,7 +279,9 @@ class BluetoothGattServerManager(
|
||||
*/
|
||||
@Suppress("DEPRECATION")
|
||||
private fun startAdvertising() {
|
||||
if (!permissionManager.hasBluetoothPermissions() || bleAdvertiser == null || !isActive) return
|
||||
if (!permissionManager.hasBluetoothPermissions() || bleAdvertiser == null || !isActive || bluetoothAdapter == null || !bluetoothAdapter.isMultipleAdvertisementSupported()) {
|
||||
throw Exception("Missing Bluetooth permissions or BLE advertiser not available")
|
||||
}
|
||||
|
||||
val settings = powerManager.getAdvertiseSettings()
|
||||
|
||||
|
||||
@@ -63,11 +63,8 @@ class BluetoothMeshService(private val context: Context) {
|
||||
|
||||
init {
|
||||
setupDelegates()
|
||||
|
||||
// Wire up PacketProcessor reference for recursive handling in MessageHandler
|
||||
messageHandler.packetProcessor = packetProcessor
|
||||
sendPeriodicBroadcastAnnounce()
|
||||
// startPeriodicDebugLogging()
|
||||
startPeriodicDebugLogging()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,6 +95,7 @@ class BluetoothMeshService(private val context: Context) {
|
||||
try {
|
||||
delay(30000) // 30 seconds
|
||||
sendBroadcastAnnounce()
|
||||
broadcastNoiseIdentityAnnouncement()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error in periodic broadcast announce: ${e.message}")
|
||||
}
|
||||
@@ -126,11 +124,7 @@ class BluetoothMeshService(private val context: Context) {
|
||||
|
||||
// SecurityManager delegate for key exchange notifications
|
||||
securityManager.delegate = object : SecurityManagerDelegate {
|
||||
override fun onKeyExchangeCompleted(peerID: String, peerPublicKeyData: ByteArray, receivedAddress: String?) {
|
||||
receivedAddress?.let { address ->
|
||||
connectionManager.addressPeerMap[address] = peerID
|
||||
}
|
||||
|
||||
override fun onKeyExchangeCompleted(peerID: String, peerPublicKeyData: ByteArray) {
|
||||
// Send announcement and cached messages after key exchange
|
||||
serviceScope.launch {
|
||||
delay(100)
|
||||
@@ -150,7 +144,7 @@ class BluetoothMeshService(private val context: Context) {
|
||||
recipientID = hexStringToByteArray(peerID),
|
||||
timestamp = System.currentTimeMillis().toULong(),
|
||||
payload = response,
|
||||
ttl = 1u
|
||||
ttl = MAX_TTL
|
||||
)
|
||||
connectionManager.broadcastPacket(RoutedPacket(responsePacket))
|
||||
Log.d(TAG, "Sent Noise handshake response to $peerID (${response.size} bytes)")
|
||||
@@ -225,6 +219,10 @@ class BluetoothMeshService(private val context: Context) {
|
||||
return securityManager.decryptFromPeer(encryptedData, senderPeerID)
|
||||
}
|
||||
|
||||
override fun verifyEd25519Signature(signature: ByteArray, data: ByteArray, publicKey: ByteArray): Boolean {
|
||||
return encryptionService.verifyEd25519Signature(signature, data, publicKey)
|
||||
}
|
||||
|
||||
// Noise protocol operations
|
||||
override fun hasNoiseSession(peerID: String): Boolean {
|
||||
return encryptionService.hasEstablishedSession(peerID)
|
||||
@@ -243,7 +241,7 @@ class BluetoothMeshService(private val context: Context) {
|
||||
recipientID = hexStringToByteArray(peerID),
|
||||
timestamp = System.currentTimeMillis().toULong(),
|
||||
payload = handshakeData,
|
||||
ttl = 1u
|
||||
ttl = MAX_TTL
|
||||
)
|
||||
|
||||
connectionManager.broadcastPacket(RoutedPacket(packet))
|
||||
@@ -387,13 +385,13 @@ class BluetoothMeshService(private val context: Context) {
|
||||
override fun onDeviceConnected(device: android.bluetooth.BluetoothDevice) {
|
||||
// Send initial announcements after services are ready
|
||||
serviceScope.launch {
|
||||
delay(100)
|
||||
delay(200)
|
||||
sendBroadcastAnnounce()
|
||||
}
|
||||
// Send key exchange to newly connected device
|
||||
serviceScope.launch {
|
||||
delay(100) // Ensure connection is stable
|
||||
sendKeyExchangeToDevice()
|
||||
delay(400) // Ensure connection is stable
|
||||
broadcastNoiseIdentityAnnouncement()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -685,7 +683,7 @@ class BluetoothMeshService(private val context: Context) {
|
||||
|
||||
val announcePacket = BitchatPacket(
|
||||
type = MessageType.ANNOUNCE.value,
|
||||
ttl = 3u,
|
||||
ttl = MAX_TTL,
|
||||
senderID = myPeerID,
|
||||
payload = nickname.toByteArray()
|
||||
)
|
||||
@@ -703,7 +701,7 @@ class BluetoothMeshService(private val context: Context) {
|
||||
val nickname = delegate?.getNickname() ?: myPeerID
|
||||
val packet = BitchatPacket(
|
||||
type = MessageType.ANNOUNCE.value,
|
||||
ttl = 3u,
|
||||
ttl = MAX_TTL,
|
||||
senderID = myPeerID,
|
||||
payload = nickname.toByteArray()
|
||||
)
|
||||
@@ -715,7 +713,7 @@ class BluetoothMeshService(private val context: Context) {
|
||||
/**
|
||||
* Send key exchange to newly connected device
|
||||
*/
|
||||
fun sendKeyExchangeToDevice() {
|
||||
fun broadcastNoiseIdentityAnnouncement() {
|
||||
serviceScope.launch {
|
||||
try {
|
||||
val nickname = delegate?.getNickname() ?: myPeerID
|
||||
@@ -726,13 +724,11 @@ class BluetoothMeshService(private val context: Context) {
|
||||
val announcementData = announcement.toBinaryData()
|
||||
|
||||
val packet = BitchatPacket(
|
||||
version = 1u,
|
||||
type = MessageType.NOISE_IDENTITY_ANNOUNCE.value,
|
||||
senderID = hexStringToByteArray(myPeerID),
|
||||
recipientID = SpecialRecipients.BROADCAST,
|
||||
timestamp = System.currentTimeMillis().toULong(),
|
||||
ttl = MAX_TTL,
|
||||
senderID = myPeerID,
|
||||
payload = announcementData,
|
||||
ttl = 1u
|
||||
|
||||
)
|
||||
|
||||
connectionManager.broadcastPacket(RoutedPacket(packet))
|
||||
@@ -838,7 +834,7 @@ class BluetoothMeshService(private val context: Context) {
|
||||
val nickname = delegate?.getNickname() ?: myPeerID
|
||||
val packet = BitchatPacket(
|
||||
type = MessageType.LEAVE.value,
|
||||
ttl = 1u,
|
||||
ttl = MAX_TTL,
|
||||
senderID = myPeerID,
|
||||
payload = nickname.toByteArray()
|
||||
)
|
||||
@@ -984,6 +980,40 @@ class BluetoothMeshService(private val context: Context) {
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// MARK: - Panic Mode Support
|
||||
|
||||
/**
|
||||
* Clear all internal mesh service data (for panic mode)
|
||||
*/
|
||||
fun clearAllInternalData() {
|
||||
Log.w(TAG, "🚨 Clearing all mesh service internal data")
|
||||
try {
|
||||
// Clear all managers
|
||||
fragmentManager.clearAllFragments()
|
||||
storeForwardManager.clearAllCache()
|
||||
securityManager.clearAllData()
|
||||
peerManager.clearAllPeers()
|
||||
peerManager.clearAllFingerprints()
|
||||
Log.d(TAG, "✅ Cleared all mesh service internal data")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "❌ Error clearing mesh service internal data: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all encryption and cryptographic data (for panic mode)
|
||||
*/
|
||||
fun clearAllEncryptionData() {
|
||||
Log.w(TAG, "🚨 Clearing all encryption data")
|
||||
try {
|
||||
// Clear encryption service persistent identity (includes Ed25519 signing keys)
|
||||
encryptionService.clearPersistentIdentity()
|
||||
Log.d(TAG, "✅ Cleared all encryption data")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "❌ Error clearing encryption data: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -20,8 +20,19 @@ import kotlinx.coroutines.channels.actor
|
||||
/**
|
||||
* Handles packet broadcasting to connected devices using actor pattern for serialization
|
||||
*
|
||||
* SERIALIZATION FIX: Uses Kotlin coroutine actor to serialize all packet broadcasting
|
||||
* This prevents race conditions when multiple threads try to broadcast simultaneously
|
||||
* In Bluetooth Low Energy (BLE):
|
||||
*
|
||||
* Peripheral (server):
|
||||
* Advertises.
|
||||
* Accepts connections.
|
||||
* Hosts a GATT server.
|
||||
* Remote devices read/write/subscribe to characteristics.
|
||||
*
|
||||
* Central (client):
|
||||
* Scans.
|
||||
* Initiates connections.
|
||||
* Hosts a GATT client.
|
||||
* Reads/writes to the peripheral’s characteristics.
|
||||
*/
|
||||
class BluetoothPacketBroadcaster(
|
||||
private val connectionScope: CoroutineScope,
|
||||
@@ -52,9 +63,7 @@ class BluetoothPacketBroadcaster(
|
||||
Log.d(TAG, "🎭 Created packet broadcaster actor")
|
||||
try {
|
||||
for (request in channel) {
|
||||
Log.d(TAG, "Processing broadcast for packet type ${request.routed.packet.type} (serialized)")
|
||||
broadcastSinglePacketInternal(request.routed, request.gattServer, request.characteristic)
|
||||
Log.d(TAG, "Completed broadcast for packet type ${request.routed.packet.type}")
|
||||
}
|
||||
} finally {
|
||||
Log.d(TAG, "🎭 Packet broadcaster actor terminated")
|
||||
@@ -158,25 +167,25 @@ class BluetoothPacketBroadcaster(
|
||||
// Send to server connections (devices connected to our GATT server)
|
||||
subscribedDevices.forEach { device ->
|
||||
if (device.address == routed.relayAddress) {
|
||||
Log.d(TAG, "Skipping broadcast back to relayer: ${device.address}")
|
||||
Log.d(TAG, "Skipping broadcast to client back to relayer: ${device.address}")
|
||||
return@forEach
|
||||
}
|
||||
if (connectionTracker.addressPeerMap[device.address] == senderID) {
|
||||
Log.d(TAG, "Skipping broadcast back to sender: ${device.address}")
|
||||
Log.d(TAG, "Skipping broadcast to client back to sender: ${device.address}")
|
||||
return@forEach
|
||||
}
|
||||
notifyDevice(device, data, gattServer, characteristic)
|
||||
}
|
||||
|
||||
// Send to client connections
|
||||
// Send to client connections (GATT servers we are connected to)
|
||||
connectedDevices.values.forEach { deviceConn ->
|
||||
if (deviceConn.isClient && deviceConn.gatt != null && deviceConn.characteristic != null) {
|
||||
if (deviceConn.device.address == routed.relayAddress) {
|
||||
Log.d(TAG, "Skipping broadcast back to relayer: ${deviceConn.device.address}")
|
||||
Log.d(TAG, "Skipping broadcast to server back to relayer: ${deviceConn.device.address}")
|
||||
return@forEach
|
||||
}
|
||||
if (connectionTracker.addressPeerMap[deviceConn.device.address] == senderID) {
|
||||
Log.d(TAG, "Skipping broadcast back to sender: ${deviceConn.device.address}")
|
||||
Log.d(TAG, "Skipping roadcast to server back to sender: ${deviceConn.device.address}")
|
||||
return@forEach
|
||||
}
|
||||
writeToDeviceConn(deviceConn, data)
|
||||
@@ -185,7 +194,7 @@ class BluetoothPacketBroadcaster(
|
||||
}
|
||||
|
||||
/**
|
||||
* Send data to a single device (server side)
|
||||
* Send data to a single device (server->client)
|
||||
*/
|
||||
private fun notifyDevice(
|
||||
device: BluetoothDevice,
|
||||
@@ -211,7 +220,7 @@ class BluetoothPacketBroadcaster(
|
||||
}
|
||||
|
||||
/**
|
||||
* Send data to a single device (client side)
|
||||
* Send data to a single device (client->server)
|
||||
*/
|
||||
private fun writeToDeviceConn(
|
||||
deviceConn: BluetoothConnectionTracker.DeviceConnection,
|
||||
|
||||
@@ -120,13 +120,27 @@ class MessageHandler(private val myPeerID: String) {
|
||||
Log.d(TAG, "Parsed identity announcement: peerID=${announcement.peerID}, " +
|
||||
"nickname=${announcement.nickname}, fingerprint=${announcement.fingerprint?.take(16)}...")
|
||||
|
||||
// Verify the announcement signature (basic validation)
|
||||
// In a full implementation, this would use cryptographic verification
|
||||
// Verify the announcement signature using Ed25519 (iOS compatibility)
|
||||
if (announcement.signature.isEmpty()) {
|
||||
Log.w(TAG, "Identity announcement from $peerID has no signature")
|
||||
Log.w(TAG, "❌ Identity announcement from $peerID has no signature - rejecting")
|
||||
return
|
||||
}
|
||||
|
||||
// Verify signature using the same format as iOS
|
||||
val timestampMs = announcement.timestamp.time
|
||||
val bindingData = announcement.peerID.toByteArray(Charsets.UTF_8) +
|
||||
announcement.publicKey +
|
||||
timestampMs.toString().toByteArray(Charsets.UTF_8)
|
||||
|
||||
val isSignatureValid = delegate?.verifyEd25519Signature(announcement.signature, bindingData, announcement.signingPublicKey) ?: false
|
||||
|
||||
if (!isSignatureValid) {
|
||||
Log.w(TAG, "❌ Signature verification failed for identity announcement from $peerID - rejecting")
|
||||
return
|
||||
}
|
||||
|
||||
Log.d(TAG, "✅ Signature verification successful for identity announcement from $peerID")
|
||||
|
||||
// Update peer binding in the delegate (ChatViewModel/BluetoothMeshService)
|
||||
delegate?.updatePeerIDBinding(
|
||||
newPeerID = announcement.peerID,
|
||||
@@ -377,6 +391,7 @@ interface MessageHandlerDelegate {
|
||||
fun verifySignature(packet: BitchatPacket, peerID: String): Boolean
|
||||
fun encryptForPeer(data: ByteArray, recipientPeerID: String): ByteArray?
|
||||
fun decryptFromPeer(encryptedData: ByteArray, senderPeerID: String): ByteArray?
|
||||
fun verifyEd25519Signature(signature: ByteArray, data: ByteArray, publicKey: ByteArray): Boolean
|
||||
|
||||
// Noise protocol operations
|
||||
fun hasNoiseSession(peerID: String): Boolean
|
||||
|
||||
@@ -70,7 +70,15 @@ class PacketProcessor(private val myPeerID: String) {
|
||||
* SURGICAL FIX: Route to per-peer actor for serialized processing
|
||||
*/
|
||||
fun processPacket(routed: RoutedPacket) {
|
||||
val peerID = routed.peerID ?: "unknown"
|
||||
Log.d(TAG, "processPacket ${routed.packet.type}")
|
||||
val peerID = routed.peerID
|
||||
|
||||
if (peerID == null) {
|
||||
Log.w(TAG, "Received packet with no peer ID, skipping")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Get or create actor for this peer
|
||||
val actor = actors.getOrPut(peerID) { getOrCreateActorForPeer(peerID) }
|
||||
|
||||
@@ -135,7 +135,7 @@ class SecurityManager(private val encryptionService: EncryptionService, private
|
||||
// Check if session is now established (handshake complete)
|
||||
if (encryptionService.hasEstablishedSession(peerID)) {
|
||||
Log.d(TAG, "✅ Noise handshake completed with $peerID")
|
||||
delegate?.onKeyExchangeCompleted(peerID, packet.payload, routed.relayAddress)
|
||||
delegate?.onKeyExchangeCompleted(peerID, packet.payload)
|
||||
}
|
||||
return true
|
||||
|
||||
@@ -145,48 +145,7 @@ class SecurityManager(private val encryptionService: EncryptionService, private
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// /**
|
||||
// * Handle key exchange packet
|
||||
// */
|
||||
// suspend fun handleKeyExchange(routed: RoutedPacket): Boolean {
|
||||
// val packet = routed.packet
|
||||
// val peerID = routed.peerID ?: "unknown"
|
||||
//
|
||||
// if (peerID == myPeerID) return false
|
||||
//
|
||||
// if (packet.payload.isEmpty()) {
|
||||
// Log.w(TAG, "Key exchange packet has empty payload")
|
||||
// return false
|
||||
// }
|
||||
//
|
||||
// // Prevent duplicate key exchange processing
|
||||
// val exchangeKey = "$peerID-${packet.payload.sliceArray(0 until minOf(16, packet.payload.size)).contentHashCode()}"
|
||||
//
|
||||
// if (processedKeyExchanges.contains(exchangeKey)) {
|
||||
// Log.d(TAG, "Already processed key exchange: $exchangeKey")
|
||||
// return false
|
||||
// }
|
||||
//
|
||||
// processedKeyExchanges.add(exchangeKey)
|
||||
//
|
||||
// try {
|
||||
// // Process the key exchange
|
||||
// encryptionService.addPeerPublicKey(peerID, packet.payload)
|
||||
//
|
||||
// Log.d(TAG, "Successfully processed key exchange from $peerID")
|
||||
//
|
||||
// // Notify delegate
|
||||
// delegate?.onKeyExchangeCompleted(peerID, packet.payload, routed.relayAddress)
|
||||
//
|
||||
// return true
|
||||
//
|
||||
// } catch (e: Exception) {
|
||||
// Log.e(TAG, "Failed to process key exchange from $peerID: ${e.message}")
|
||||
// return false
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
/**
|
||||
* Verify packet signature
|
||||
*/
|
||||
@@ -377,6 +336,6 @@ class SecurityManager(private val encryptionService: EncryptionService, private
|
||||
* Delegate interface for security manager callbacks
|
||||
*/
|
||||
interface SecurityManagerDelegate {
|
||||
fun onKeyExchangeCompleted(peerID: String, peerPublicKeyData: ByteArray, receivedAddress: String?)
|
||||
fun onKeyExchangeCompleted(peerID: String, peerPublicKeyData: ByteArray)
|
||||
fun sendHandshakeResponse(peerID: String, response: ByteArray)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user