diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 0b8ff9f8..2755e3bc 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -9,6 +9,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter_blue_plus/flutter_blue_plus.dart'; import 'package:flutter_blue_plus_platform_interface/flutter_blue_plus_platform_interface.dart'; +import '../utils/advert_signature.dart'; import '../models/channel.dart'; import '../models/channel_message.dart'; import '../models/companion_radio_stats.dart'; @@ -6433,6 +6434,13 @@ class MeshCoreConnector extends ChangeNotifier { _contactsStorageFull = false; // capacity freed up since the warning } _hasLoadedContacts = true; + if (!_preserveContactsOnRefresh && !_contactSyncUsesSinceFilter) { + // A full sync replaced _contacts; drop keys the radio no longer + // holds so removed nodes reappear in discovery. + _knownContactKeys + ..clear() + ..addAll(_contacts.map((c) => c.publicKeyHex)); + } _preserveContactsOnRefresh = false; _telemetryFixesDuringSync.clear(); _contactSyncUsesSinceFilter = false; @@ -9383,13 +9391,15 @@ class MeshCoreConnector extends ChangeNotifier { final rawPacket = frame.sublist(3); switch (payloadType) { case payloadTypeADVERT: - _handlePayloadAdvertReceived( - rawPacket, - payload, - pathBytes, - pathHashWidth, - routeType, - snr, + unawaited( + _verifyThenHandleAdvert( + rawPacket, + payload, + pathBytes, + pathHashWidth, + routeType, + snr, + ), ); break; default: @@ -9400,89 +9410,32 @@ class MeshCoreConnector extends ChangeNotifier { } } - void importContact(Uint8List frame) { - final packet = BufferReader(frame); - int payloadType = 0; - Uint8List pathBytes = Uint8List(0); - int pathHashWidth = 1; - try { - packet.skipBytes(1); // Skip frame type byte - packet.skipBytes(1); // Skip SNR byte - packet.skipBytes(1); // Skip RSSI byte - final header = packet.readByte(); - final routeType = header & 0x03; - payloadType = (header >> 2) & 0x0F; - if (routeType == _routeTransportFlood || - routeType == _routeTransportDirect) { - packet.skipBytes(4); // Skip transport-specific bytes - } - //final payloadVer = (header >> 6) & 0x03; - final pathLenRaw = packet.readByte(); - final pathByteLen = decodePathByteLen(pathLenRaw); - pathHashWidth = decodePathHashWidth(pathLenRaw); - pathBytes = packet.readBytes(pathByteLen); - } catch (e) { - appLogger.warn('Malformed RX frame: $e', tag: 'Connector'); + /// Drops adverts whose Ed25519 signature does not verify against the + /// advertised public key, so forged adverts cannot add or update a contact + /// of any type (chat, repeater, room, sensor). + Future _verifyThenHandleAdvert( + Uint8List rawPacket, + Uint8List payload, + Uint8List path, + int pathHashWidth, + int routeType, + double snr, + ) async { + if (!await verifyAdvertSignature(payload)) { + appLogger.warn( + 'Dropped advert with invalid signature' + '${payload.length >= 4 ? ' from ${pubKeyToHex(payload.sublist(0, 4))}' : ''}', + tag: 'Connector', + ); return; } - double? latitude; - double? longitude; - String name = ''; - Uint8List publicKey = Uint8List(0); - int type = 0; - int timestamp = 0; - bool hasLocation = false; - bool hasName = false; - if (payloadType != payloadTypeADVERT) { - appLogger.warn('Unexpected payload type: $payloadType', tag: 'Connector'); - return; - } - try { - publicKey = packet.readBytes(32); - timestamp = packet.readInt32LE(); - //TODO add signature verification - packet.skipBytes(64); // Skip signature for now - final flags = packet.readByte(); - type = flags & 0x0F; - hasLocation = (flags & 0x10) != 0; - hasName = (flags & 0x80) != 0; - if (hasLocation && packet.remaining >= 8) { - latitude = packet.readInt32LE() / 1e6; - longitude = packet.readInt32LE() / 1e6; - } - // Two optional 16-bit feature fields sit between the location and the - // name (AdvertDataParser in MeshCore AdvertDataHelpers.cpp). Skip them - // so their bytes aren't read as the start of the name. - for (final featureMask in const [0x20, 0x40]) { - if ((flags & featureMask) != 0 && packet.remaining >= 2) { - packet.skipBytes(2); - } - } - if (hasName && packet.remaining > 0) { - name = packet.readCString(); - } - } catch (e) { - appLogger.warn('Malformed advert frame: $e', tag: 'Connector'); - return; - } - - importDiscoveredContact( - Contact( - rawPacket: frame, - publicKey: publicKey, - name: name, - type: type, - pathLength: pathBytes.isEmpty - ? -1 - : (pathBytes.length ~/ pathHashWidth), - // Store hop order reversed for easier outgoing messages; keep bytes - // inside each multi-byte hop in their original order. - path: _reversePathByHop(pathBytes, pathHashWidth), - pathHashWidth: pathHashWidth, - latitude: latitude, - longitude: longitude, - lastSeen: DateTime.fromMillisecondsSinceEpoch(timestamp * 1000), - ), + _handlePayloadAdvertReceived( + rawPacket, + payload, + path, + pathHashWidth, + routeType, + snr, ); } @@ -9522,8 +9475,8 @@ class MeshCoreConnector extends ChangeNotifier { .join(); timestamp = advert.readInt32LE(); - //TODO add signature verification - advert.skipBytes(64); // Skip signature for now + // Signature already checked by _verifyThenHandleAdvert. + advert.skipBytes(signatureSize); final flags = advert.readByte(); type = flags & 0x0F; hasLocation = (flags & 0x10) != 0; diff --git a/lib/utils/advert_signature.dart b/lib/utils/advert_signature.dart new file mode 100644 index 00000000..49068405 --- /dev/null +++ b/lib/utils/advert_signature.dart @@ -0,0 +1,73 @@ +import 'dart:typed_data'; + +import 'package:cryptography/cryptography.dart'; + +/// Advert payload layout (MeshCore `Mesh::createAdvert`): +/// `[pub_key 32][timestamp u32 LE][signature 64][app_data …]`. +const int _pubKeyLen = 32; +const int _timestampLen = 4; +const int _signatureLen = 64; +const int advertSignedHeaderLen = _pubKeyLen + _timestampLen + _signatureLen; + +final Ed25519 _ed25519 = Ed25519(); + +/// Verified results keyed by signature, so the same advert heard over +/// several paths is only checked once. +final Map _verifiedCache = {}; +const int _verifiedCacheMax = 256; + +/// Returns true when [payload] is an advert whose Ed25519 signature over +/// `pub_key || timestamp || app_data` verifies against its own public key. +/// Applies to every advert type (chat, repeater, room, sensor). +Future verifyAdvertSignature(Uint8List payload) async { + if (payload.length < advertSignedHeaderLen) return false; + + final publicKey = Uint8List.sublistView(payload, 0, _pubKeyLen); + final timestamp = Uint8List.sublistView( + payload, + _pubKeyLen, + _pubKeyLen + _timestampLen, + ); + final signature = Uint8List.sublistView( + payload, + _pubKeyLen + _timestampLen, + advertSignedHeaderLen, + ); + final appData = Uint8List.sublistView(payload, advertSignedHeaderLen); + + final cacheKey = + String.fromCharCodes(publicKey) + String.fromCharCodes(signature); + final cached = _verifiedCache[cacheKey]; + if (cached != null) return cached; + + final message = Uint8List(_pubKeyLen + _timestampLen + appData.length) + ..setRange(0, _pubKeyLen, publicKey) + ..setRange(_pubKeyLen, _pubKeyLen + _timestampLen, timestamp) + ..setRange( + _pubKeyLen + _timestampLen, + _pubKeyLen + _timestampLen + appData.length, + appData, + ); + + bool valid; + try { + valid = await _ed25519.verify( + message, + signature: Signature( + Uint8List.fromList(signature), + publicKey: SimplePublicKey( + Uint8List.fromList(publicKey), + type: KeyPairType.ed25519, + ), + ), + ); + } catch (_) { + valid = false; + } + + if (_verifiedCache.length >= _verifiedCacheMax) { + _verifiedCache.remove(_verifiedCache.keys.first); + } + _verifiedCache[cacheKey] = valid; + return valid; +} diff --git a/test/connector/advert_signature_test.dart b/test/connector/advert_signature_test.dart new file mode 100644 index 00000000..2be6c30f --- /dev/null +++ b/test/connector/advert_signature_test.dart @@ -0,0 +1,145 @@ +import 'dart:typed_data'; + +import 'package:cryptography/cryptography.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/utils/advert_signature.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// Builds an advert payload signed the way MeshCore's Mesh::createAdvert does. +Future _signedAdvert( + int seedByte, { + required int type, + required String name, + int timestamp = 1700000000, +}) async { + final algo = Ed25519(); + final keys = await algo.newKeyPairFromSeed(List.filled(32, seedByte)); + final pub = (await keys.extractPublicKey()).bytes; + final ts = Uint8List(4) + ..buffer.asByteData().setUint32(0, timestamp, Endian.little); + final appData = [0x80 | type, ...name.codeUnits]; + final sig = await algo.sign([...pub, ...ts, ...appData], keyPair: keys); + return Uint8List.fromList([...pub, ...ts, ...sig.bytes, ...appData]); +} + +/// Wraps an advert payload in a PUSH_CODE_LOG_RX_DATA frame (flood, no path). +List _rxFrame(Uint8List payload) => [ + pushCodeLogRxData, + 0, // snr + 0, // rssi + (payloadTypeADVERT << 2) | 0x01, // header: flood route + 0, // path length + ...payload, +]; + +List _contactFrame(int code, List key, String name) { + final data = ByteData(1 + 32 + 3 + 64 + 32 + 4 + 12); + final bytes = data.buffer.asUint8List(); + bytes[0] = code; + bytes.setRange(1, 33, key); + bytes[33] = advTypeRepeater; + bytes[35] = 0xFF; + bytes.setRange(100, 100 + name.length, name.codeUnits); + data.setUint32(132, 1700000000, Endian.little); + return bytes; +} + +Future _settle() async { + for (var i = 0; i < 20; i++) { + await Future.delayed(Duration.zero); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + group('verifyAdvertSignature', () { + for (final type in [ + advTypeChat, + advTypeRepeater, + advTypeRoom, + advTypeSensor, + ]) { + test('accepts a valid advert of type $type', () async { + final advert = await _signedAdvert( + type + 10, + type: type, + name: 'N$type', + ); + expect(await verifyAdvertSignature(advert), isTrue); + }); + } + + test('rejects tampered app data', () async { + final advert = await _signedAdvert(1, type: advTypeRepeater, name: 'Rpt'); + advert[advert.length - 1] ^= 0x01; + expect(await verifyAdvertSignature(advert), isFalse); + }); + + test('rejects a swapped public key', () async { + final advert = await _signedAdvert(2, type: advTypeChat, name: 'Bob'); + final other = await _signedAdvert(3, type: advTypeChat, name: 'Bob'); + advert.setRange(0, 32, other.sublist(0, 32)); + expect(await verifyAdvertSignature(advert), isFalse); + }); + + test('rejects a short payload', () async { + expect(await verifyAdvertSignature(Uint8List(99)), isFalse); + }); + }); + + group('RX advert handling', () { + test('valid advert is discovered', () async { + final connector = MeshCoreConnector(); + final advert = await _signedAdvert(4, type: advTypeRoom, name: 'Room'); + connector.handleFrameForTest(_rxFrame(advert)); + await _settle(); + expect(connector.discoveredContacts.map((c) => c.name), contains('Room')); + }); + + test('forged advert is dropped', () async { + final connector = MeshCoreConnector(); + final advert = await _signedAdvert( + 5, + type: advTypeRepeater, + name: 'Real', + ); + // Rename without re-signing. + advert.setRange(advert.length - 4, advert.length, 'Fake'.codeUnits); + connector.handleFrameForTest(_rxFrame(advert)); + await _settle(); + expect(connector.discoveredContacts, isEmpty); + }); + }); + + test('full contact sync forgets keys the radio dropped', () async { + final connector = MeshCoreConnector(); + final kept = List.generate(32, (i) => i + 1); + final dropped = List.generate(32, (i) => 100 + i); + + connector.handleFrameForTest([respCodeContactsStart, 0, 0, 0, 0]); + connector.handleFrameForTest(_contactFrame(respCodeContact, kept, 'Kept')); + connector.handleFrameForTest( + _contactFrame(respCodeContact, dropped, 'Gone'), + ); + connector.handleFrameForTest([respCodeEndOfContacts, 0, 0, 0, 0]); + expect(connector.knownContactKeys.length, 2); + + connector.handleFrameForTest([respCodeContactsStart, 0, 0, 0, 0]); + connector.handleFrameForTest(_contactFrame(respCodeContact, kept, 'Kept')); + connector.handleFrameForTest([respCodeEndOfContacts, 0, 0, 0, 0]); + await _settle(); + + expect(connector.contacts.map((c) => c.name), ['Kept']); + expect(connector.knownContactKeys, hasLength(1)); + }); +}