diff --git a/build.yaml b/build.yaml index f3e3669..ae77a3b 100644 --- a/build.yaml +++ b/build.yaml @@ -16,6 +16,8 @@ targets: builders: open_car_builders|constants_builder: enabled: true + open_car_builders|secure_channel_constants_builder: + enabled: true open_car_builders|mqtt_config_builder: enabled: true open_car_builders|proto_builder: diff --git a/contracts b/contracts index 1faf470..4ce23a0 160000 --- a/contracts +++ b/contracts @@ -1 +1 @@ -Subproject commit 1faf470ab2490fdb73bd65da092798396a26bef8 +Subproject commit 4ce23a07186da9982f43183a3e208ea1819893a3 diff --git a/docs/architecture.md b/docs/architecture.md index 3844f45..cc18a33 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -62,6 +62,8 @@ If a paired device later reports a different non-zero `platform_id`, `vehicleSta | `canBusHealthProvider` | Each CAN bus's health by bus id (`SystemState.can_bus_health`): the device's status for the last few seconds and its counters since boot. From the current connection only, like `canAccessStateProvider`; BLE only. `AppEntryRouter` listens to it from the start, so the report sent when the app subscribes is kept for the settings | | `canAccessActionsProvider` | Approves or withdraws vehicle control and toggles the developer write lock | | `phoneAccessStateProvider` | What the device allows this phone (`SystemState.phone_access`): its trust level, whether the car has a validated phone, its validation session. From the current connection only, like `canAccessStateProvider` | +| `clientKeyEnrollmentProvider` | Enrolls this phone's client key with the device and pins the device identity, over Bluetooth once the phone is validated. `AppEntryRouter` listens to it from the start. See [Secure channel keys](#secure-channel-keys) | +| `deviceIdentityMismatchProvider` | The identity the device reported when it differs from the pinned one, for the dashboard banner; in memory only | | `phoneValidationActionsProvider` | Lists the validation methods and the paired phones, and starts, answers or cancels a validation | | `commandAvailabilityProvider` | Which commands the device accepts now (`SystemState.command_availability`), from the current connection only: null until reported on it, cleared on every transport or connection change and when the device goes quiet, never cached. Over MQTT it covers the basic commands | | `vehicleHistoryProvider` | Recent values of the series the paired vehicle's tiles draw (charts, sparklines), sampled from live state only, in memory | @@ -100,6 +102,16 @@ Pairing doesn't prove a phone is the owner's, so the device only accepts vehicle * The limits (`[ble.phone_validation]` in `transport.toml`) are generated with the other constants as `kBlePhoneValidation*`, for the instructions. The session messages carry the time and attempts left. * `phoneValidationMethodText` maps each `method_id` to the app's text, with a generic text per kind for an id the app doesn't know. +### Secure channel keys +The secure channel (contracts `docs/secure-channel.md`) lets the app reach the device off Bluetooth, over a link it doesn't trust (LAN, relay). It rests on two keys, both exchanged over the bonded Bluetooth link: + +* **The app's client key:** one X25519 key pair per install, made on first use by `ClientKeyStore` (`lib/secure/client_key.dart`) and kept in `flutter_secure_storage` (Android Keystore), never in `SharedPreferences`. Tests use an in-memory `SecretStore`. +* **The device identity:** the device's X25519 public key and key ID (`SystemState.device_identity`, and the answer to `EnrollClientKey`). `PinnedDeviceIdentity.fromReport` (`lib/secure/device_identity.dart`) only accepts a 32-byte key whose key ID matches it. The app pins it per vehicle in `PairedVehicleConfig` (`devicePublicKey`, `deviceKeyId`), with the client key the device last accepted (`enrolledClientKey`), so unpairing forgets all three. + +`clientKeyEnrollmentProvider` does the enrollment, over Bluetooth (and the debug HTTP transport) only. On each connection, once `phoneAccessStateProvider` reports the phone validated, it lists the paired phones and sends `EnrollClientKey` (kind phone, labelled with the phone's model, cut to `max_client_label_bytes`) when the device doesn't list this phone with a key, no identity is pinned, or the device last accepted another client key. A failure leaves it for the next connection. The device answers with its identity, which the app pins if it has none. + +A reported identity that differs from the pinned one (the device was erased or replaced, or isn't the same device) is never pinned silently: `deviceIdentityMismatchProvider` holds it, nothing is enrolled, and the dashboard shows "The device has a new identity" with Unpair or Trust new identity. Trusting it pins the new key, forgets the enrolled client key and enrolls again. + ### Command availability The device decides which commands it accepts right now and reports it (firmware `docs/commands.md`, "Command availability"): `SystemState.command_availability`, over BLE and over MQTT (basic commands only), repeated every few seconds. The app greys out the tiles of commands the device doesn't accept, and the dashboard leaves out the tiles of commands reported `UNSUPPORTED` (not on this car; nothing sends that yet), so the tiles after them close the gap. They stay left out in every later connection (see below). A tap on a greyed-out tile (`CommandControl`) says why when the app knows: the device reports no reason, so it comes from the transport and the access states (`commandUnavailableReason`). The device rejects an unavailable command with `COMMAND_STATUS_CODE_REJECTED_UNAVAILABLE` even if the app sends it anyway, and `sendVehicleCommand` shows its reason. diff --git a/docs/ble.md b/docs/ble.md index d041bc8..a4c2e87 100644 --- a/docs/ble.md +++ b/docs/ble.md @@ -13,10 +13,10 @@ The device advertises **only** while its pairing window is open: after its pairi * **Device hidden from this phone:** once a buttonless device has a paired phone, it advertises without its name or service UUID, so a phone it doesn't know (app reinstalled, new phone, bond forgotten in Android's settings) never finds it. The firmware's recovery is a bond reset by power-cycling (firmware `docs/ble.md`): after `kBlePowerCycleResetShortBoots` power-ons in a row that each lose power within `kBlePowerCycleResetUptimeSeconds`, the next power-on clears every bond and opens the first-setup window. `HelpScreen` (`lib/screens/help_screen.dart`) explains pairing mode and these steps with the contract's values; it is reachable from the wizard's header and its error step (the scan timeout message points there), the dashboard's settings screen, and the bond-lost banner. * Android can still report such a device to the wizard's scan, filtered on the service UUID, although it advertises neither the UUID nor its name: it matches from the services it cached while the phone was paired (seen on a Pixel). The scan then doesn't time out. The wizard therefore treats a device found **without a name** as outside pairing mode (in pairing mode the firmware puts its name in every advertisement): the found step says so and links to Help, and Pair stays available, since a phone that still has its bond pairs that way. If Pair then ends in the stale-bond drop, the warning tells the user to reset the paired phones instead of "tap Pair again": outside pairing mode the firmware doesn't clear the old bond, so another attempt would fail the same way. * **HTTP debug path** (debug builds only): the wizard offers host/port entry + POST `/pairing` + POST `/pair`; saves config with `transportPreference = http`. -* **Unpair:** Unpair on a card of the Vehicles screen, or Unpair vehicle in settings for the current one → confirmation dialog → `pairedVehiclesProvider.notifier.unpair()` → the next vehicle becomes current, or with none left the router returns to the wizard. Unpairing only forgets the vehicle in the app; the device keeps its bond, so pairing again needs it in pairing mode. +* **Unpair:** Unpair on a card of the Vehicles screen, or Unpair vehicle in settings for the current one → confirmation dialog → `pairedVehiclesProvider.notifier.unpair()` → the next vehicle becomes current, or with none left the router returns to the wizard. Unpairing only forgets the vehicle in the app, with its pinned device identity (see [Secure channel keys](architecture.md#secure-channel-keys)); the device keeps its bond and this phone's client key, so pairing again needs it in pairing mode. * **`createBond()` is never called** — bonding is driven by the write-probe, not explicit bond requests. * **Stale-bond recovery:** if the firmware drops the link after connecting (it had a stale bond, the phone forgot it), `disconnectCompleter` fires and the wizard returns to the "found" step with a warning banner. Firmware clears its entry on that drop; the next Pair tap succeeds normally (the user sees two OS pairing prompts in total). -* **Phone validation:** bonding doesn't make a phone trusted. Pairing is Just Works, so a newly paired phone (and one that paired again after a bond reset, or a device moved to another car) can send system commands, but no vehicle command until it is validated in the car. See [Phone validation](architecture.md#phone-validation). Trust is only read from `SystemState.phone_access` on the current connection, never cached. +* **Phone validation:** bonding doesn't make a phone trusted. Pairing is Just Works, so a newly paired phone (and one that paired again after a bond reset, or a device moved to another car) can send system commands, but no vehicle command until it is validated in the car. See [Phone validation](architecture.md#phone-validation). Trust is only read from `SystemState.phone_access` on the current connection, never cached. Once validated, the app enrolls its client key for the secure channel ([Secure channel keys](architecture.md#secure-channel-keys)). ## BLE specifics * **Library:** `flutter_reactive_ble: ^5.4.1`. Singleton in `lib/providers/ble_provider.dart` (`bleProvider`). diff --git a/docs/code-generation.md b/docs/code-generation.md index e7de680..2989540 100644 --- a/docs/code-generation.md +++ b/docs/code-generation.md @@ -17,10 +17,13 @@ It does not need to run on every build, only when its inputs change. Unlike Rust |---|---|---| | `contracts/**/*.proto` | `lib/generated/**/*.pb.dart` | `ProtoBuilder` | | `contracts/opencar/cars/*/v1/meta.toml` + `transport.toml` | `lib/cars//constants.g.dart` | `ConstantsBuilder` | +| `contracts/opencar/core/v1/transport.toml` (`[secure_channel]`) | `lib/secure/secure_channel_constants.g.dart` | `SecureChannelConstantsBuilder` | | `config.toml.example` (+ optional `config.toml`, and the `certs/` files it names) | `lib/config/mqtt_broker_config.g.dart` | `MqttConfigBuilder` | **`constants.g.dart`** exposes: `kPlatformId` (CRC32), `kPlatformName`, `kCanBusCount`, BLE UUIDs, MQTT topic templates, `kBlePairingWindowSeconds`, `kBleScanTimeoutSeconds`, and the BLE size and chunking constants (`kBleAttMtu`, `kBleMaxChunkBytes`, `kBleMaxMessageBytes`, `kBleChunk*`, `kBleCrcBytes`, `kBleMaxChunks`, `kBleMinAttMtu`, `kBleReassemblyTimeoutMs`). Never copy-paste TOML values — always import from the generated file. +**`secure_channel_constants.g.dart`** exposes the [secure channel](architecture.md#secure-channel-keys) constants, which don't depend on the vehicle: `kSecureChannelProtocol`, `kSecureChannelPrologueLabel`, the frame types (`kSecureFrameType*`) and the sizes, limits and timeouts (`kSecureChannel*`). + **`mqtt_broker_config.g.dart`** exposes: `kMqttBrokerHost/Port`, `kMqttUsername/Password` (empty with mTLS), `kMqttCaCertPem`, `kMqttClientCertPem`, `kMqttClientKeyPem` (the PEM files of `[broker]`, empty when unused; see [MQTT over TLS](mqtt-tls.md)), `kMqttClientId`, `kDebugServerHost/Port`, `kDebugServerPollingIntervalMs`. ## Local config diff --git a/docs/ui-screens.md b/docs/ui-screens.md index bd40d2d..0369b2b 100644 --- a/docs/ui-screens.md +++ b/docs/ui-screens.md @@ -103,6 +103,7 @@ Opened from the settings button in the dashboard header. A back button and the t ### Paired phones The phones paired with the device, in the order they were paired (BLE only). The device doesn't know phone names, so each phone shows as "This phone" or "Another phone" with the end of its id. Each has a trust chip: **Validated** or **Not validated**. +* A phone with a client key enrolled for the [secure channel](architecture.md#secure-channel-keys) shows "Remote access set up", with the label it enrolled with (the phone's model). * This phone, when it isn't validated, has **Validate**. * Other phones have **Remove**, with a confirmation. Once a phone is validated in this car, only a validated phone can remove a validated phone, so on a phone that isn't validated the button is disabled with that reason. The device only removes phones during its pairing window and doesn't answer an accepted request, so the app reads the list again and says so if the phone is still there. * Removing this phone's own bond and clearing all phones are part of unpairing and [#25](https://github.com/OpenCarControls/mobile-app/issues/25). diff --git a/docs/ui.md b/docs/ui.md index 6f88520..116d68d 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -199,6 +199,7 @@ The screenshot predates the single controls tile and the sheet. | Banner | When | Action | |---|---|---| | Wrong vehicle platform | The device reports a different platform (`vehicleStateProvider` sets `mismatchedPlatformId`) | Unpair | + | The device has a new identity | The device reports a key other than the one pinned for this vehicle (`deviceIdentityMismatchProvider`, see [Secure channel keys](architecture.md#secure-channel-keys)) | Unpair, or trust the new identity | | The device no longer knows this phone | Repeated early drops (`bleBondLostProvider`) | Help, or unpair and pair again | | Control isn't approved | The car is identified but the CAN read-write approval is missing or for another car (`canAccessNeedsApproval`) | Review: the approval dialog | | Validate this phone | This phone is bonded but not validated in this car ([phone validation](ui-screens.md#phone-validation)) | Validate: the validation flow | diff --git a/lib/config/paired_vehicle_config.dart b/lib/config/paired_vehicle_config.dart index 3c1613f..11b3e97 100644 --- a/lib/config/paired_vehicle_config.dart +++ b/lib/config/paired_vehicle_config.dart @@ -58,6 +58,18 @@ class PairedVehicleConfig { /// device over BLE; null until it has, and MQTT stays off until then. final String? mqttClientId; + /// The device's secure channel public key (32 bytes), pinned from the first + /// identity it reported over Bluetooth. Null until then. A device reporting + /// another key later doesn't replace it: the user decides. + final List? devicePublicKey; + + /// The device key ID of [devicePublicKey]. + final String? deviceKeyId; + + /// The app's client public key that this device last accepted, so a new + /// client key (app data cleared) is enrolled again. + final List? enrolledClientKey; + const PairedVehicleConfig({ String? id, this.name, @@ -71,15 +83,23 @@ class PairedVehicleConfig { this.mqttUsername, this.mqttPassword, this.mqttClientId, + this.devicePublicKey, + this.deviceKeyId, + this.enrolledClientKey, }) : id = id ?? vehicleId; /// A copy with the given fields replaced. [clearName] goes back to the - /// platform's name. + /// platform's name. [clearEnrolledClientKey] forgets which client key the + /// device accepted. PairedVehicleConfig copyWith({ String? id, String? name, bool clearName = false, String? mqttClientId, + List? devicePublicKey, + String? deviceKeyId, + List? enrolledClientKey, + bool clearEnrolledClientKey = false, }) => PairedVehicleConfig( id: id ?? this.id, name: clearName ? null : name ?? this.name, @@ -93,6 +113,11 @@ class PairedVehicleConfig { mqttUsername: mqttUsername, mqttPassword: mqttPassword, mqttClientId: mqttClientId ?? this.mqttClientId, + devicePublicKey: devicePublicKey ?? this.devicePublicKey, + deviceKeyId: deviceKeyId ?? this.deviceKeyId, + enrolledClientKey: clearEnrolledClientKey + ? null + : enrolledClientKey ?? this.enrolledClientKey, ); /// Keys what is stored per vehicle (saved layouts, cached state, activity @@ -126,6 +151,11 @@ class PairedVehicleConfig { if (mqttUsername != null) 'mqttUsername': mqttUsername, if (mqttPassword != null) 'mqttPassword': mqttPassword, if (mqttClientId != null) 'mqttClientId': mqttClientId, + if (devicePublicKey != null) + 'devicePublicKey': base64Encode(devicePublicKey!), + if (deviceKeyId != null) 'deviceKeyId': deviceKeyId, + if (enrolledClientKey != null) + 'enrolledClientKey': base64Encode(enrolledClientKey!), }; factory PairedVehicleConfig._fromJson(Map j) => @@ -144,7 +174,13 @@ class PairedVehicleConfig { mqttUsername: j['mqttUsername'] as String?, mqttPassword: j['mqttPassword'] as String?, mqttClientId: j['mqttClientId'] as String?, + devicePublicKey: _bytes(j['devicePublicKey']), + deviceKeyId: j['deviceKeyId'] as String?, + enrolledClientKey: _bytes(j['enrolledClientKey']), ); + + static List? _bytes(Object? base64) => + base64 is String ? base64Decode(base64) : null; } /// The paired vehicles and which one is current: the only one with live links. diff --git a/lib/main.dart b/lib/main.dart index 0ff978a..bcf6d0f 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -18,6 +18,7 @@ import 'package:open_car_app/providers/connection_activity_provider.dart'; import 'package:open_car_app/providers/dashboard_layout_provider.dart'; import 'package:open_car_app/providers/paired_vehicle_provider.dart'; import 'package:open_car_app/providers/vehicle_summary_provider.dart'; +import 'package:open_car_app/providers/secure_channel_provider.dart'; import 'package:open_car_app/providers/selected_vehicle_provider.dart'; import 'package:open_car_app/providers/theme_provider.dart'; import 'package:open_car_app/screens/dashboard/dashboard_screen.dart'; @@ -99,6 +100,9 @@ class AppEntryRouter extends ConsumerWidget { // Listen from the start of each connection, so the bus health sent when // the app subscribes is already there when the settings first show it. ref.listen(canBusHealthProvider, (_, _) {}); + // Enrolls this phone's client key once it is validated in the car, and + // pins the device identity (see the provider). + ref.listen(clientKeyEnrollmentProvider, (_, _) {}); final vehicle = ref.watch(selectedVehicleProvider); final setupPending = ref.watch(wizardSetupPendingProvider); if (vehicle == null || setupPending) return const PairingWizardScreen(); diff --git a/lib/models/paired_phone.dart b/lib/models/paired_phone.dart index 01d5ab7..d580fe6 100644 --- a/lib/models/paired_phone.dart +++ b/lib/models/paired_phone.dart @@ -12,16 +12,27 @@ class PairedPhoneInfo { /// app doesn't know its own BLE address. final bool isThisPhone; + /// The phone has a client key enrolled, so it can reach the device over the + /// secure channel (LAN, relay) as well as Bluetooth. + final bool remoteKeyEnrolled; + + /// The label the phone enrolled its key with; empty without a key. + final String remoteKeyLabel; + const PairedPhoneInfo({ required this.deviceId, required this.trust, required this.isThisPhone, + this.remoteKeyEnrolled = false, + this.remoteKeyLabel = '', }); factory PairedPhoneInfo.fromProto(PairedPhone phone) => PairedPhoneInfo( deviceId: List.unmodifiable(phone.deviceId), trust: phone.trust, isThisPhone: phone.isRequester, + remoteKeyEnrolled: phone.remoteKeyEnrolled, + remoteKeyLabel: phone.remoteKeyLabel, ); bool get isValidated => trust == PhoneTrustLevel.PHONE_TRUST_LEVEL_VALIDATED; diff --git a/lib/providers/paired_vehicle_provider.dart b/lib/providers/paired_vehicle_provider.dart index cbbfa71..c1aeabd 100644 --- a/lib/providers/paired_vehicle_provider.dart +++ b/lib/providers/paired_vehicle_provider.dart @@ -4,6 +4,23 @@ import 'package:open_car_app/providers/command_availability_provider.dart'; import 'package:open_car_app/providers/connection_activity_provider.dart'; import 'package:open_car_app/providers/dashboard_layout_provider.dart'; import 'package:open_car_app/providers/vehicle_summary_provider.dart'; +import 'package:open_car_app/secure/device_identity.dart'; + +/// How a device identity compares with the one pinned for the vehicle. +enum DeviceIdentityCheck { + /// No identity was pinned: this one now is. + pinned, + + /// The same key as the pinned one. + matches, + + /// Another key than the pinned one, which stays: the device was erased or + /// replaced, or it isn't the same device. + mismatch, + + /// No vehicle is paired. + noVehicle, +} /// Holds the value loaded from SharedPreferences before [runApp]. /// Overridden in [ProviderScope] at app startup — never reads storage itself. @@ -88,6 +105,58 @@ class PairedVehiclesNotifier extends Notifier { ); } + /// Pins [identity] for the current vehicle if it has none, and says how it + /// compares with the pinned one. Never replaces a pinned identity: that is + /// [replaceDeviceIdentity], once the user agrees. + Future checkDeviceIdentity( + PinnedDeviceIdentity identity, + ) async { + final current = state.current; + if (current == null) return DeviceIdentityCheck.noVehicle; + final pinned = current.devicePublicKey; + if (pinned == null) { + await _update( + current.id, + (vehicle) => vehicle.copyWith( + devicePublicKey: identity.publicKey, + deviceKeyId: identity.keyId, + ), + ); + return DeviceIdentityCheck.pinned; + } + return sameBytes(pinned, identity.publicKey) + ? DeviceIdentityCheck.matches + : DeviceIdentityCheck.mismatch; + } + + /// Pins [identity] for the current vehicle in place of the one it had (the + /// device was erased or replaced, and the user trusts it). The client key is + /// enrolled again. + Future replaceDeviceIdentity(PinnedDeviceIdentity identity) async { + final current = state.current; + if (current == null) return; + await _update( + current.id, + (vehicle) => vehicle.copyWith( + devicePublicKey: identity.publicKey, + deviceKeyId: identity.keyId, + clearEnrolledClientKey: true, + ), + ); + } + + /// Remembers that the current vehicle's device accepted [clientKey]. + Future setEnrolledClientKey(List clientKey) async { + final current = state.current; + if (current == null || sameBytes(current.enrolledClientKey, clientKey)) { + return; + } + await _update( + current.id, + (vehicle) => vehicle.copyWith(enrolledClientKey: clientKey), + ); + } + Future _update( String id, PairedVehicleConfig Function(PairedVehicleConfig) change, diff --git a/lib/providers/secure_channel_provider.dart b/lib/providers/secure_channel_provider.dart new file mode 100644 index 0000000..aacf5d7 --- /dev/null +++ b/lib/providers/secure_channel_provider.dart @@ -0,0 +1,245 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'package:open_car_app/generated/opencar/core/v1/system.pb.dart'; +import 'package:open_car_app/providers/car_transport_provider.dart'; +import 'package:open_car_app/providers/paired_vehicle_provider.dart'; +import 'package:open_car_app/providers/phone_access_provider.dart'; +import 'package:open_car_app/providers/selected_vehicle_provider.dart'; +import 'package:open_car_app/providers/vehicle_state_provider.dart'; +import 'package:open_car_app/secure/client_key.dart'; +import 'package:open_car_app/secure/device_identity.dart'; +import 'package:open_car_app/secure/flutter_secret_store.dart'; +import 'package:open_car_app/secure/secure_channel_constants.g.dart'; +import 'package:open_car_app/transport/car_transport.dart'; + +/// Where the app keeps its secrets. Overridden in tests with a fake store. +final secretStoreProvider = Provider( + (_) => const FlutterSecretStore(), +); + +/// The app's client key for the secure channel, made on first use. +final clientKeyStoreProvider = Provider( + (ref) => ClientKeyStore(ref.watch(secretStoreProvider)), +); + +/// The label this phone enrolls its key with, shown in the device's phone +/// list: the phone's maker and model, at most `max_client_label_bytes`. +final clientKeyLabelProvider = FutureProvider((_) async { + var label = 'Phone'; + try { + if (Platform.isAndroid) { + final info = await DeviceInfoPlugin().androidInfo; + label = '${info.manufacturer} ${info.model}'.trim(); + } + } catch (_) { + // Keep the generic label. + } + return truncateUtf8(label, kSecureChannelMaxClientLabelBytes); +}); + +/// [text] cut to at most [maxBytes] UTF-8 bytes, on a character boundary. +String truncateUtf8(String text, int maxBytes) { + final out = StringBuffer(); + var bytes = 0; + for (final rune in text.runes) { + final char = String.fromCharCode(rune); + final size = utf8Length(char); + if (bytes + size > maxBytes) break; + out.write(char); + bytes += size; + } + return out.toString(); +} + +/// The UTF-8 length of [text], in bytes. +int utf8Length(String text) => const Utf8Encoder().convert(text).length; + +/// Where the app's client key stands with the current vehicle's device. +enum ClientKeyEnrollment { + /// Nothing to do yet: not on a Bluetooth connection, or the phone isn't + /// validated in the car. + idle, + + /// Checking or enrolling the key. + enrolling, + + /// The device has this phone's key, and the app has pinned its identity: + /// remote access is set up. + enrolled, + + /// Enrolling failed. Tried again on the next connection. + failed, + + /// The device reported another identity than the one pinned for this + /// vehicle ([deviceIdentityMismatchProvider]). Nothing is enrolled until the + /// user decides. + identityMismatch, +} + +/// Enrolls the app's client key with the current vehicle's device, over +/// Bluetooth, once the phone is validated in the car: when the device doesn't +/// list this phone with a key, when the app has no device identity pinned for +/// the vehicle, or when the device last accepted another client key. Also pins +/// the device identity the device reports (`SystemState.device_identity`, or +/// the answer to the enrollment), and flags one that differs from the pinned +/// one instead of replacing it. Runs again on every connection. +/// +/// Listened to from the start by `AppEntryRouter`, so it needs no UI step. +class ClientKeyEnrollmentNotifier extends Notifier { + /// Bumped on every rebuild, so a check that outlived its connection drops + /// its result. + int _generation = 0; + bool _attempted = false; + + @override + ClientKeyEnrollment build() { + final generation = ++_generation; + _attempted = false; + ref.watch(pairedVehicleProvider.select((v) => v?.id)); + final transport = ref.watch(carTransportProvider); + if (!_carriesIdentity(transport.transportType)) { + return ClientKeyEnrollment.idle; + } + final platformId = ref.read(selectedVehicleProvider)?.platformId; + final subscription = transport.messages.listen((msg) { + if (platformId != null && + msg.platformId != 0 && + msg.platformId != platformId) { + return; + } + if (!msg.hasStateUpdate() || !msg.stateUpdate.hasSystemState()) return; + final system = msg.stateUpdate.systemState; + if (system.hasDeviceIdentity()) { + unawaited(_checkIdentity(system.deviceIdentity, generation)); + } + }); + ref.onDispose(subscription.cancel); + ref.listen(phoneAccessStateProvider.select((a) => a?.trust), (_, trust) { + if (trust == PhoneTrustLevel.PHONE_TRUST_LEVEL_VALIDATED) { + unawaited(_ensureEnrolled(generation)); + } + }, fireImmediately: true); + return ClientKeyEnrollment.idle; + } + + /// The identity is only trusted from the bonded Bluetooth link (and the + /// debug HTTP transport, which imitates it). + static bool _carriesIdentity(TransportType type) => + type == TransportType.ble || type == TransportType.http; + + void _set(int generation, ClientKeyEnrollment value) { + if (generation == _generation) state = value; + } + + /// Pins [reported] if no identity is pinned, and flags a different one. + /// Returns false when it doesn't match the pinned identity. + Future _checkIdentity(DeviceIdentity reported, int generation) async { + final identity = await PinnedDeviceIdentity.fromReport(reported); + if (identity == null || generation != _generation) return false; + final check = await ref + .read(pairedVehiclesProvider.notifier) + .checkDeviceIdentity(identity); + if (generation != _generation) return false; + if (check == DeviceIdentityCheck.mismatch) { + ref.read(deviceIdentityMismatchProvider.notifier).report(identity); + _set(generation, ClientKeyEnrollment.identityMismatch); + return false; + } + return true; + } + + Future _ensureEnrolled(int generation) async { + if (_attempted || generation != _generation) return; + _attempted = true; + _set(generation, ClientKeyEnrollment.enrolling); + try { + final key = await ref.read(clientKeyStoreProvider).load(); + final phones = await ref + .read(phoneValidationActionsProvider) + .listPairedPhones(); + if (generation != _generation) return; + final me = phones.where((p) => p.isThisPhone).firstOrNull; + final vehicle = ref.read(pairedVehicleProvider); + final upToDate = + (me?.remoteKeyEnrolled ?? false) && + vehicle?.devicePublicKey != null && + sameBytes(vehicle?.enrolledClientKey, key.publicKey); + if (upToDate) { + _set(generation, ClientKeyEnrollment.enrolled); + return; + } + final label = await ref.read(clientKeyLabelProvider.future); + final response = await ref + .read(vehicleStateProvider.notifier) + .sendSystemCommand( + SystemCommand( + enrollClientKey: EnrollClientKeyCommand( + publicKey: key.publicKey, + kind: ClientKind.CLIENT_KIND_PHONE, + label: label, + ), + ), + ); + if (generation != _generation) return; + final result = response.systemResult; + if (result.whichResult() != SystemCommandResult_Result.deviceIdentity) { + throw const CarTransportException( + 'The device did not send its identity.', + ); + } + if (!await _checkIdentity(result.deviceIdentity, generation)) { + if (state != ClientKeyEnrollment.identityMismatch) { + _set(generation, ClientKeyEnrollment.failed); + } + return; + } + await ref + .read(pairedVehiclesProvider.notifier) + .setEnrolledClientKey(key.publicKey); + _set(generation, ClientKeyEnrollment.enrolled); + } catch (_) { + _set(generation, ClientKeyEnrollment.failed); + } + } +} + +final clientKeyEnrollmentProvider = + NotifierProvider( + ClientKeyEnrollmentNotifier.new, + ); + +/// The identity the current vehicle's device reported when it differs from +/// the pinned one: it was erased or replaced, or isn't the same device. Null +/// otherwise. In memory only, cleared when the vehicle changes. The dashboard +/// shows a banner that lets the user trust it or unpair. +class DeviceIdentityMismatchNotifier extends Notifier { + @override + PinnedDeviceIdentity? build() { + ref.watch(pairedVehicleProvider.select((v) => v?.id)); + return null; + } + + void report(PinnedDeviceIdentity identity) => state = identity; + + /// Pins the reported identity in place of the old one. The client key is + /// enrolled again on the next check. + Future trust() async { + final identity = state; + if (identity == null) return; + await ref + .read(pairedVehiclesProvider.notifier) + .replaceDeviceIdentity(identity); + state = null; + ref.invalidate(clientKeyEnrollmentProvider); + } +} + +final deviceIdentityMismatchProvider = + NotifierProvider( + DeviceIdentityMismatchNotifier.new, + ); diff --git a/lib/screens/dashboard/dashboard_banner.dart b/lib/screens/dashboard/dashboard_banner.dart index 5aecdaa..f024f77 100644 --- a/lib/screens/dashboard/dashboard_banner.dart +++ b/lib/screens/dashboard/dashboard_banner.dart @@ -7,6 +7,7 @@ import 'package:open_car_app/providers/ble_connection_provider.dart'; import 'package:open_car_app/providers/can_access_provider.dart'; import 'package:open_car_app/providers/paired_vehicle_provider.dart'; import 'package:open_car_app/providers/phone_access_provider.dart'; +import 'package:open_car_app/providers/secure_channel_provider.dart'; import 'package:open_car_app/providers/vehicle_state_provider.dart'; import 'package:open_car_app/screens/help_screen.dart'; import 'package:open_car_app/screens/phone_validation_screen.dart'; @@ -15,7 +16,8 @@ import 'package:open_car_app/theme/app_tokens.dart'; import 'package:open_car_app/widgets/can_read_write_approval_dialog.dart'; /// The one banner slot at the top of the tile area. Only the most important -/// banner shows: a wrong vehicle platform, then a lost Bluetooth bond, then +/// banner shows: a wrong vehicle platform, then a changed device identity, +/// then a lost Bluetooth bond, then /// control that isn't approved, then a phone that isn't validated. See /// "Banners" in `docs/ui.md`. class DashboardBannerSlot extends ConsumerWidget { @@ -26,6 +28,7 @@ class DashboardBannerSlot extends ConsumerWidget { final mismatchedId = ref.watch( vehicleStateProvider.select((s) => s.mismatchedPlatformId), ); + final newIdentity = ref.watch(deviceIdentityMismatchProvider); final bondLost = ref.watch(bleBondLostProvider); // Only known over Bluetooth: null otherwise. final access = ref.watch(canAccessStateProvider); @@ -50,6 +53,26 @@ class DashboardBannerSlot extends ConsumerWidget { ), ], ); + } else if (newIdentity != null) { + banner = DashboardBanner( + icon: Symbols.key_off, + title: 'The device has a new identity', + text: + 'Its key (${newIdentity.keyId}) is not the one this phone ' + 'remembers: it was reset or replaced. Remote access stays off ' + 'until you trust it.', + actions: [ + ( + label: 'Unpair', + onPressed: () => ref.read(pairedVehiclesProvider.notifier).unpair(), + ), + ( + label: 'Trust new identity', + onPressed: () => + ref.read(deviceIdentityMismatchProvider.notifier).trust(), + ), + ], + ); } else if (bondLost) { banner = DashboardBanner( icon: Symbols.bluetooth_disabled, diff --git a/lib/screens/paired_phones_screen.dart b/lib/screens/paired_phones_screen.dart index 321eb12..77a4e33 100644 --- a/lib/screens/paired_phones_screen.dart +++ b/lib/screens/paired_phones_screen.dart @@ -195,6 +195,13 @@ class _PhoneRow extends StatelessWidget { style: Theme.of(context).textTheme.titleMedium, ), Text('ID …${_idEnd(phone.deviceId)}', style: noteStyle), + if (phone.remoteKeyEnrolled) + Text( + phone.remoteKeyLabel.isEmpty + ? 'Remote access set up' + : 'Remote access set up (${phone.remoteKeyLabel})', + style: noteStyle, + ), ], ), ), diff --git a/lib/secure/client_key.dart b/lib/secure/client_key.dart new file mode 100644 index 0000000..fc98046 --- /dev/null +++ b/lib/secure/client_key.dart @@ -0,0 +1,73 @@ +/// The app's client key for the secure channel (see the contracts' +/// `docs/secure-channel.md`): one X25519 key pair per app install, made on +/// first use and kept in secure storage. Its public key is enrolled with each +/// vehicle over Bluetooth once the phone is validated in the car. +/// +/// Pure Dart, without Flutter, so it can be used from a background isolate. +library; + +import 'dart:convert'; + +import 'package:cryptography/cryptography.dart'; + +/// Where secrets are kept: Android Keystore-backed storage in the app +/// ([FlutterSecretStore]), a map in tests. Never `SharedPreferences`. +abstract interface class SecretStore { + Future read(String key); + Future write(String key, String value); +} + +/// The app's X25519 static key pair. +class ClientKey { + const ClientKey({required this.privateKey, required this.publicKey}); + + /// The 32-byte private key. Never leaves the phone. + final List privateKey; + + /// The 32-byte public key, enrolled with the device. + final List publicKey; +} + +/// Loads the app's client key, making it on first use. +class ClientKeyStore { + ClientKeyStore(this._store); + + /// The key under which the private key is stored, base64. + static const storageKey = 'secure_channel_client_key'; + + final SecretStore _store; + Future? _key; + + /// The client key, made and stored on first use. A stored key that can't be + /// read is replaced: the vehicles then get the new one enrolled. + Future load() => _key ??= _loadOrCreate().catchError((Object e) { + _key = null; + throw e; + }); + + Future _loadOrCreate() async { + final algorithm = X25519(); + final stored = await _store.read(storageKey); + if (stored != null) { + try { + final seed = base64Decode(stored); + if (seed.length == 32) return await _fromSeed(algorithm, seed); + } on FormatException { + // Replaced below. + } + } + final keyPair = await algorithm.newKeyPair(); + final seed = await keyPair.extractPrivateKeyBytes(); + await _store.write(storageKey, base64Encode(seed)); + return _fromSeed(algorithm, seed); + } + + static Future _fromSeed(X25519 algorithm, List seed) async { + final keyPair = await algorithm.newKeyPairFromSeed(seed); + final publicKey = await keyPair.extractPublicKey(); + return ClientKey( + privateKey: List.unmodifiable(seed), + publicKey: List.unmodifiable(publicKey.bytes), + ); + } +} diff --git a/lib/secure/device_identity.dart b/lib/secure/device_identity.dart new file mode 100644 index 0000000..6725cc6 --- /dev/null +++ b/lib/secure/device_identity.dart @@ -0,0 +1,56 @@ +/// The device's identity for the secure channel: its X25519 static public key +/// and key ID, which the app pins per paired vehicle (see the contracts' +/// `docs/secure-channel.md`). Pure Dart. +library; + +import 'package:cryptography/cryptography.dart'; + +import 'package:open_car_app/generated/opencar/core/v1/system.pb.dart'; +import 'package:open_car_app/secure/secure_channel_constants.g.dart'; + +/// The device key ID of [publicKey]: the lowercase hex of the first +/// [kSecureChannelKeyIdBytes] bytes of its BLAKE2s-256 hash. +Future deviceKeyIdOf(List publicKey) async { + final hash = await Blake2s().hash(publicKey); + return hash.bytes + .take(kSecureChannelKeyIdBytes) + .map((b) => b.toRadixString(16).padLeft(2, '0')) + .join(); +} + +/// A device identity the app pins, or one a device reported. +class PinnedDeviceIdentity { + const PinnedDeviceIdentity({required this.publicKey, required this.keyId}); + + /// The device's 32-byte X25519 public key. + final List publicKey; + + /// The device key ID, as the device reported it. + final String keyId; + + /// The identity a device reported, or null when it isn't a well-formed one: + /// a 32-byte key whose key ID matches it. + static Future fromReport( + DeviceIdentity identity, + ) async { + if (identity.publicKey.length != 32) return null; + final keyId = await deviceKeyIdOf(identity.publicKey); + if (keyId != identity.keyId) return null; + return PinnedDeviceIdentity( + publicKey: List.unmodifiable(identity.publicKey), + keyId: keyId, + ); + } + + bool sameKeyAs(PinnedDeviceIdentity other) => + sameBytes(publicKey, other.publicKey); +} + +/// Whether [a] and [b] hold the same bytes. +bool sameBytes(List? a, List? b) { + if (a == null || b == null || a.length != b.length) return false; + for (var i = 0; i < a.length; i++) { + if (a[i] != b[i]) return false; + } + return true; +} diff --git a/lib/secure/flutter_secret_store.dart b/lib/secure/flutter_secret_store.dart new file mode 100644 index 0000000..6db8356 --- /dev/null +++ b/lib/secure/flutter_secret_store.dart @@ -0,0 +1,19 @@ +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; + +import 'package:open_car_app/secure/client_key.dart'; + +/// [SecretStore] on `flutter_secure_storage`: on Android, values encrypted by a +/// key in the Android Keystore. X25519 isn't a Keystore key type, so the client +/// key is stored encrypted rather than held by the Keystore itself. +class FlutterSecretStore implements SecretStore { + const FlutterSecretStore([this._storage = const FlutterSecureStorage()]); + + final FlutterSecureStorage _storage; + + @override + Future read(String key) => _storage.read(key: key); + + @override + Future write(String key, String value) => + _storage.write(key: key, value: value); +} diff --git a/pubspec.lock b/pubspec.lock index f43303d..4eac78b 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -177,6 +177,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.7" + cryptography: + dependency: "direct main" + description: + name: cryptography + sha256: "3eda3029d34ec9095a27a198ac9785630fe525c0eb6a49f3d575272f8e792ef0" + url: "https://pub.dev" + source: hosted + version: "2.9.0" csslib: dependency: transitive description: @@ -209,6 +217,22 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.14" + device_info_plus: + dependency: "direct main" + description: + name: device_info_plus + sha256: ade1c36f8355d6284c98e4a47992ea263887ed3d1acb281e37635dd45f04c4aa + url: "https://pub.dev" + source: hosted + version: "13.3.0" + device_info_plus_platform_interface: + dependency: transitive + description: + name: device_info_plus_platform_interface + sha256: "04b173a92e2d9161dfead145667037c8d834db725ce2e7b942bfe18fd2f45a46" + url: "https://pub.dev" + source: hosted + version: "8.1.0" event_bus: dependency: transitive description: @@ -299,6 +323,54 @@ packages: url: "https://pub.dev" source: hosted version: "3.5.0" + flutter_secure_storage: + dependency: "direct main" + description: + name: flutter_secure_storage + sha256: d4e1fb6b2cb524868929e78dc0282fa000554b22060fb53789dc481c9fc95bb8 + url: "https://pub.dev" + source: hosted + version: "11.2.0" + flutter_secure_storage_darwin: + dependency: transitive + description: + name: flutter_secure_storage_darwin + sha256: a031ceac9b070e62ef183cd7f7d1a8798ebde402d5049f0fe6eb3a51bd797a21 + url: "https://pub.dev" + source: hosted + version: "0.4.3" + flutter_secure_storage_linux: + dependency: transitive + description: + name: flutter_secure_storage_linux + sha256: caa75bd78f017422912e3a904933113b2428eb79f981ac37acd2dd2a700458ea + url: "https://pub.dev" + source: hosted + version: "3.0.3" + flutter_secure_storage_platform_interface: + dependency: transitive + description: + name: flutter_secure_storage_platform_interface + sha256: "64951127f001f546891c86f414972bf49ef2c4c8a4c92c65f5790cc0c9100045" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + flutter_secure_storage_web: + dependency: transitive + description: + name: flutter_secure_storage_web + sha256: "073a62b3aeb866ab4ce795f960413948e51e5a42a9b0c8333b6daf5bb3208a1c" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + flutter_secure_storage_windows: + dependency: transitive + description: + name: flutter_secure_storage_windows + sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1" + url: "https://pub.dev" + source: hosted + version: "4.2.2" flutter_test: dependency: "direct dev" description: flutter @@ -1097,6 +1169,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.4.0" + win32_registry: + dependency: transitive + description: + name: win32_registry + sha256: "73b1d78920a9d6e03f8b4e43e612b87bf3152a0e5c5e5150267762b7c4116904" + url: "https://pub.dev" + source: hosted + version: "3.0.3" xdg_directories: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 384979e..ff055de 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -50,6 +50,9 @@ dependencies: share_plus: ^13.3.1 material_ui: ^1.11.0 thermion_flutter: ^0.7.0 + cryptography: ^2.9.0 + flutter_secure_storage: ^11.2.0 + device_info_plus: ^13.3.0 dev_dependencies: flutter_test: diff --git a/test/client_key_enrollment_test.dart b/test/client_key_enrollment_test.dart new file mode 100644 index 0000000..750cb08 --- /dev/null +++ b/test/client_key_enrollment_test.dart @@ -0,0 +1,413 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:open_car_app/cars/virtual_car/constants.g.dart' as virtual_car; +import 'package:open_car_app/config/paired_vehicle_config.dart'; +import 'package:open_car_app/generated/opencar/core/v1/core.pb.dart'; +import 'package:open_car_app/generated/opencar/core/v1/system.pb.dart'; +import 'package:open_car_app/providers/ble_source_device_id_provider.dart'; +import 'package:open_car_app/providers/car_transport_provider.dart'; +import 'package:open_car_app/providers/paired_vehicle_provider.dart'; +import 'package:open_car_app/providers/phone_access_provider.dart'; +import 'package:open_car_app/providers/secure_channel_provider.dart'; +import 'package:open_car_app/providers/vehicle_state_provider.dart'; +import 'package:open_car_app/secure/client_key.dart'; +import 'package:open_car_app/secure/device_identity.dart'; +import 'package:open_car_app/secure/secure_channel_constants.g.dart'; +import 'package:open_car_app/transport/car_transport.dart'; + +class _MemoryStore implements SecretStore { + final values = {}; + int writes = 0; + + @override + Future read(String key) async => values[key]; + + @override + Future write(String key, String value) async { + writes++; + values[key] = value; + } +} + +/// A device that answers the system commands the enrollment sends. +class _FakeDevice implements CarTransport { + _FakeDevice({ + required this.identity, + this.validated = true, + this.enrolled = false, + }); + + DeviceIdentity identity; + bool validated; + bool enrolled; + final enrollments = []; + final _controller = StreamController.broadcast(); + + void emit(DeviceToApp msg) => _controller.add(msg); + + void reportTrust(PhoneTrustLevel trust) => emit( + DeviceToApp( + platformId: virtual_car.kPlatformId, + stateUpdate: StateUpdate( + systemState: SystemState(phoneAccess: PhoneAccessState(trust: trust)), + ), + ), + ); + + @override + TransportType get transportType => TransportType.ble; + + @override + Stream get messages => _controller.stream; + + @override + Future send(AppToDevice message) async { + if (!message.hasSystemCommand()) return; + final command = message.systemCommand; + final response = CommandResponse(messageId: message.messageId); + if (command.hasListPairedPhones()) { + response + ..success = true + ..statusCode = CommandStatusCode.COMMAND_STATUS_CODE_OK + ..systemResult = SystemCommandResult( + pairedPhones: PairedPhones( + phones: [ + PairedPhone( + deviceId: [9, 9], + isRequester: true, + trust: validated + ? PhoneTrustLevel.PHONE_TRUST_LEVEL_VALIDATED + : PhoneTrustLevel.PHONE_TRUST_LEVEL_BONDED, + remoteKeyEnrolled: enrolled, + remoteKeyLabel: enrolled ? 'Pixel' : '', + ), + ], + ), + ); + } else if (command.hasEnrollClientKey()) { + enrollments.add(command.enrollClientKey); + if (validated) { + enrolled = true; + response + ..success = true + ..statusCode = CommandStatusCode.COMMAND_STATUS_CODE_OK + ..systemResult = SystemCommandResult(deviceIdentity: identity); + } else { + response.statusCode = + CommandStatusCode.COMMAND_STATUS_CODE_REJECTED_NOT_VALIDATED; + } + } else { + return; + } + scheduleMicrotask(() => emit(DeviceToApp(commandResponse: response))); + } + + @override + void dispose() => _controller.close(); +} + +class _Transport extends Notifier<_FakeDevice> { + _Transport(this._initial); + final _FakeDevice _initial; + + @override + _FakeDevice build() => _initial; + + void use(_FakeDevice device) => state = device; +} + +late NotifierProvider<_Transport, _FakeDevice> _transportProvider; + +const _config = PairedVehicleConfig( + vehicleId: virtual_car.kPlatformName, + bleRemoteId: '00:11:22:33:44:55', + transportPreference: TransportPreference.ble, +); + +/// A well-formed identity for a device whose public key is all [fill]. +Future _identity(int fill) async { + final key = List.filled(32, fill); + return DeviceIdentity(publicKey: key, keyId: await deviceKeyIdOf(key)); +} + +ProviderContainer _container( + _FakeDevice device, + _MemoryStore store, { + PairedVehicleConfig config = _config, +}) { + _transportProvider = NotifierProvider<_Transport, _FakeDevice>( + () => _Transport(device), + ); + final container = ProviderContainer( + overrides: [ + bleSourceDeviceIdProvider.overrideWithValue(const [1, 2, 3]), + initialPairedVehiclesProvider.overrideWithValue( + PairedVehicles.of(config), + ), + carTransportProvider.overrideWith((ref) => ref.watch(_transportProvider)), + secretStoreProvider.overrideWithValue(store), + clientKeyLabelProvider.overrideWith((_) async => 'Test phone'), + ], + ); + addTearDown(container.dispose); + addTearDown(device.dispose); + container.listen(vehicleStateProvider, (_, _) {}, onError: (_, _) {}); + container.listen(phoneAccessStateProvider, (_, _) {}); + container.listen(clientKeyEnrollmentProvider, (_, _) {}); + return container; +} + +/// Lets the async enrollment (key derivation, hashes, round trips) settle. +Future _settle() async { + for (var i = 0; i < 20; i++) { + await pumpEventQueue(); + await Future.delayed(const Duration(milliseconds: 5)); + } +} + +void main() { + setUp(() => SharedPreferences.setMockInitialValues({})); + + group('ClientKeyStore', () { + test('makes the key once and keeps it', () async { + final store = _MemoryStore(); + final first = await ClientKeyStore(store).load(); + expect(first.publicKey, hasLength(32)); + expect(first.privateKey, hasLength(32)); + expect(store.writes, 1); + + final again = await ClientKeyStore(store).load(); + expect(again.publicKey, first.publicKey); + expect(store.writes, 1); + }); + + test('replaces a stored key that cannot be read', () async { + final store = _MemoryStore() + ..values[ClientKeyStore.storageKey] = base64Encode([1, 2, 3]); + final key = await ClientKeyStore(store).load(); + expect(key.publicKey, hasLength(32)); + expect( + base64Decode(store.values[ClientKeyStore.storageKey]!), + hasLength(32), + ); + }); + }); + + group('PinnedDeviceIdentity.fromReport', () { + test('accepts a key whose key ID matches', () async { + final identity = await PinnedDeviceIdentity.fromReport( + await _identity(7), + ); + expect(identity, isNotNull); + expect(identity!.keyId, hasLength(2 * kSecureChannelKeyIdBytes)); + }); + + test('refuses a wrong key ID or key length', () async { + final good = await _identity(7); + expect( + await PinnedDeviceIdentity.fromReport( + DeviceIdentity(publicKey: good.publicKey, keyId: '00' * 10), + ), + isNull, + ); + expect( + await PinnedDeviceIdentity.fromReport( + DeviceIdentity(publicKey: [1, 2], keyId: good.keyId), + ), + isNull, + ); + }); + }); + + test('truncateUtf8 keeps whole characters', () { + expect(truncateUtf8('Pixel 9', 32), 'Pixel 9'); + expect(utf8Length(truncateUtf8('é' * 20, 32)), 32); + expect(utf8Length(truncateUtf8('a${'é' * 20}', 32)), 31); + }); + + group('clientKeyEnrollmentProvider', () { + test('enrolls once the phone is validated and pins the identity', () async { + final device = _FakeDevice(identity: await _identity(7)); + final store = _MemoryStore(); + final container = _container(device, store); + + device.reportTrust(PhoneTrustLevel.PHONE_TRUST_LEVEL_VALIDATED); + await _settle(); + + final key = await container.read(clientKeyStoreProvider).load(); + expect(device.enrollments, hasLength(1)); + final sent = device.enrollments.single; + expect(sent.publicKey, key.publicKey); + expect(sent.kind, ClientKind.CLIENT_KIND_PHONE); + expect(sent.label, 'Test phone'); + + final vehicle = container.read(pairedVehicleProvider)!; + expect(vehicle.devicePublicKey, device.identity.publicKey); + expect(vehicle.deviceKeyId, device.identity.keyId); + expect(vehicle.enrolledClientKey, key.publicKey); + expect( + container.read(clientKeyEnrollmentProvider), + ClientKeyEnrollment.enrolled, + ); + + // Persisted with the pairing. + final saved = await PairedVehicles.load(); + expect(saved.current!.devicePublicKey, device.identity.publicKey); + expect(saved.current!.enrolledClientKey, key.publicKey); + }); + + test('does nothing while the phone is only bonded', () async { + final device = _FakeDevice( + identity: await _identity(7), + validated: false, + ); + final container = _container(device, _MemoryStore()); + + device.reportTrust(PhoneTrustLevel.PHONE_TRUST_LEVEL_BONDED); + await _settle(); + + expect(device.enrollments, isEmpty); + expect(container.read(pairedVehicleProvider)!.devicePublicKey, isNull); + expect( + container.read(clientKeyEnrollmentProvider), + ClientKeyEnrollment.idle, + ); + }); + + test('does not enroll again when already enrolled', () async { + final identity = await _identity(7); + final store = _MemoryStore(); + final key = await ClientKeyStore(store).load(); + final device = _FakeDevice(identity: identity, enrolled: true); + final container = _container( + device, + store, + config: _config.copyWith( + devicePublicKey: identity.publicKey, + deviceKeyId: identity.keyId, + enrolledClientKey: key.publicKey, + ), + ); + + device.reportTrust(PhoneTrustLevel.PHONE_TRUST_LEVEL_VALIDATED); + await _settle(); + + expect(device.enrollments, isEmpty); + expect( + container.read(clientKeyEnrollmentProvider), + ClientKeyEnrollment.enrolled, + ); + }); + + test('enrolls again when the device lost the key', () async { + final identity = await _identity(7); + final store = _MemoryStore(); + final key = await ClientKeyStore(store).load(); + final device = _FakeDevice(identity: identity); + _container( + device, + store, + config: _config.copyWith( + devicePublicKey: identity.publicKey, + deviceKeyId: identity.keyId, + enrolledClientKey: key.publicKey, + ), + ); + + device.reportTrust(PhoneTrustLevel.PHONE_TRUST_LEVEL_VALIDATED); + await _settle(); + + expect(device.enrollments, hasLength(1)); + }); + + test('flags a different device key and keeps the pinned one', () async { + final pinned = await _identity(7); + final device = _FakeDevice(identity: await _identity(8)); + final container = _container( + device, + _MemoryStore(), + config: _config.copyWith( + devicePublicKey: pinned.publicKey, + deviceKeyId: pinned.keyId, + ), + ); + + device.reportTrust(PhoneTrustLevel.PHONE_TRUST_LEVEL_VALIDATED); + await _settle(); + + final vehicle = container.read(pairedVehicleProvider)!; + expect(vehicle.devicePublicKey, pinned.publicKey); + expect(vehicle.enrolledClientKey, isNull); + expect( + container.read(clientKeyEnrollmentProvider), + ClientKeyEnrollment.identityMismatch, + ); + expect( + container.read(deviceIdentityMismatchProvider)!.keyId, + device.identity.keyId, + ); + + // Trusting it pins the new identity and enrolls with it. + await container.read(deviceIdentityMismatchProvider.notifier).trust(); + await _settle(); + final updated = container.read(pairedVehicleProvider)!; + expect(updated.devicePublicKey, device.identity.publicKey); + expect(updated.enrolledClientKey, isNotNull); + expect(container.read(deviceIdentityMismatchProvider), isNull); + expect( + container.read(clientKeyEnrollmentProvider), + ClientKeyEnrollment.enrolled, + ); + }); + + test('flags a different identity in the reported system state', () async { + final pinned = await _identity(7); + final device = _FakeDevice( + identity: await _identity(8), + validated: false, + ); + final container = _container( + device, + _MemoryStore(), + config: _config.copyWith( + devicePublicKey: pinned.publicKey, + deviceKeyId: pinned.keyId, + ), + ); + + device.emit( + DeviceToApp( + platformId: virtual_car.kPlatformId, + stateUpdate: StateUpdate( + systemState: SystemState(deviceIdentity: device.identity), + ), + ), + ); + await _settle(); + + expect(container.read(deviceIdentityMismatchProvider), isNotNull); + expect( + container.read(pairedVehicleProvider)!.devicePublicKey, + pinned.publicKey, + ); + }); + + test('unpairing forgets the pinned identity', () async { + final device = _FakeDevice(identity: await _identity(7)); + final container = _container(device, _MemoryStore()); + + device.reportTrust(PhoneTrustLevel.PHONE_TRUST_LEVEL_VALIDATED); + await _settle(); + expect(container.read(pairedVehicleProvider)!.devicePublicKey, isNotNull); + + await container.read(pairedVehiclesProvider.notifier).unpair(); + expect(container.read(pairedVehicleProvider), isNull); + expect((await PairedVehicles.load()).vehicles, isEmpty); + }); + }); +} diff --git a/tool/builders/build.yaml b/tool/builders/build.yaml index 3a4bad6..7b4f21f 100644 --- a/tool/builders/build.yaml +++ b/tool/builders/build.yaml @@ -7,6 +7,14 @@ builders: auto_apply: root_package build_to: source + secure_channel_constants_builder: + import: "package:open_car_builders/builders.dart" + builder_factories: ["secureChannelConstantsBuilder"] + build_extensions: + "contracts/opencar/core/v1/transport.toml": ["lib/secure/secure_channel_constants.g.dart"] + auto_apply: root_package + build_to: source + mqtt_config_builder: import: "package:open_car_builders/builders.dart" builder_factories: ["mqttConfigBuilder"] diff --git a/tool/builders/lib/builders.dart b/tool/builders/lib/builders.dart index 2f7a06b..3883051 100644 --- a/tool/builders/lib/builders.dart +++ b/tool/builders/lib/builders.dart @@ -3,9 +3,13 @@ import 'package:build/build.dart'; import 'src/constants_builder.dart'; import 'src/mqtt_config_builder.dart'; import 'src/proto_builder.dart'; +import 'src/secure_channel_constants_builder.dart'; Builder constantsBuilder(BuilderOptions options) => ConstantsBuilder(); Builder mqttConfigBuilder(BuilderOptions options) => MqttConfigBuilder(); Builder protoBuilder(BuilderOptions options) => ProtoBuilder(); + +Builder secureChannelConstantsBuilder(BuilderOptions options) => + SecureChannelConstantsBuilder(); diff --git a/tool/builders/lib/src/secure_channel_constants_builder.dart b/tool/builders/lib/src/secure_channel_constants_builder.dart new file mode 100644 index 0000000..99b91cf --- /dev/null +++ b/tool/builders/lib/src/secure_channel_constants_builder.dart @@ -0,0 +1,82 @@ +import 'dart:convert'; + +import 'package:build/build.dart'; +import 'package:toml/toml.dart'; + +/// Generates the secure channel constants (`[secure_channel]` in +/// `transport.toml`, see the contracts' `docs/secure-channel.md`). They don't +/// depend on the vehicle, so they get their own file. +class SecureChannelConstantsBuilder implements Builder { + @override + Map> get buildExtensions => const { + 'contracts/opencar/core/v1/transport.toml': [ + 'lib/secure/secure_channel_constants.g.dart', + ], + }; + + @override + Future build(BuildStep buildStep) async { + final input = buildStep.inputId; + final transport = TomlDocument.parse( + await buildStep.readAsString(input), + ).toMap(); + final section = transport['secure_channel']; + if (section is! Map) { + throw StateError('Expected [secure_channel] to be a table.'); + } + + String string(String key) { + final value = section[key]; + if (value is String) return value; + throw StateError('Expected [secure_channel.$key] to be a string.'); + } + + int integer(String key) { + final value = section[key]; + if (value is int) return value; + throw StateError('Expected [secure_channel.$key] to be an int.'); + } + + // TOML key -> Dart name, in the order they are written. + const ints = { + 'key_id_bytes': 'kSecureChannelKeyIdBytes', + 'frame_type_handshake_init': 'kSecureFrameTypeHandshakeInit', + 'frame_type_handshake_response': 'kSecureFrameTypeHandshakeResponse', + 'frame_type_transport': 'kSecureFrameTypeTransport', + 'frame_type_unknown_session': 'kSecureFrameTypeUnknownSession', + 'session_id_bytes': 'kSecureChannelSessionIdBytes', + 'counter_bytes': 'kSecureChannelCounterBytes', + 'replay_window': 'kSecureChannelReplayWindow', + 'max_plaintext_bytes': 'kSecureChannelMaxPlaintextBytes', + 'stream_length_prefix_bytes': 'kSecureChannelStreamLengthPrefixBytes', + 'max_sessions': 'kSecureChannelMaxSessions', + 'max_sessions_per_client': 'kSecureChannelMaxSessionsPerClient', + 'idle_timeout_seconds': 'kSecureChannelIdleTimeoutSeconds', + 'max_session_seconds': 'kSecureChannelMaxSessionSeconds', + 'max_session_messages': 'kSecureChannelMaxSessionMessages', + 'handshake_timeout_ms': 'kSecureChannelHandshakeTimeoutMs', + 'max_client_label_bytes': 'kSecureChannelMaxClientLabelBytes', + }; + + final buffer = StringBuffer() + ..writeln('// GENERATED CODE - DO NOT MODIFY BY HAND.') + ..writeln('// Source: ${input.path} [secure_channel]') + ..writeln() + ..writeln( + 'const String kSecureChannelProtocol = ' + '${jsonEncode(string('protocol'))};', + ) + ..writeln( + 'const String kSecureChannelPrologueLabel = ' + '${jsonEncode(string('prologue_label'))};', + ); + for (final MapEntry(key: key, value: name) in ints.entries) { + buffer.writeln('const int $name = ${integer(key)};'); + } + + await buildStep.writeAsString( + AssetId(input.package, 'lib/secure/secure_channel_constants.g.dart'), + buffer.toString(), + ); + } +}