Add independent Companion Bluetooth stealth flag

Keep stealth separate from custom, saved-random and rotating MAC policies without migrating the development MAC mode. Persist authenticated peer state, guard advertising transitions and recovery, and expose the setting through the CLI and WebConfig.

Add regression and CI checks and record exact XIAO BLE pairing, reconnect, reboot and address-rotation hardware results.
This commit is contained in:
mikecarper committed 2026-09-07 23:46:55 -07:00
1 parent 4b400ea56b
commit 6958d82432
29 files changed
+3984 -2020

No files matched your search

+85 -2
View File
@@ -15,15 +15,46 @@ enum BluetoothMacMode : uint8_t {
BLUETOOTH_MAC_CUSTOM = 1,
BLUETOOTH_MAC_RANDOM_SAVED = 2,
BLUETOOTH_MAC_RANDOM_EVERY_BOOT = 3,
BLUETOOTH_MAC_RANDOM_AFTER_CONNECT = 4,
// Internal persisted state: the current identity completed an authenticated
// connection and must rotate before it advertises next boot.
BLUETOOTH_MAC_RANDOM_AFTER_CONNECT_ARMED = 5,
};
inline bool isValidBluetoothMacMode(uint8_t mode) {
return mode <= BLUETOOTH_MAC_RANDOM_EVERY_BOOT;
return mode <= BLUETOOTH_MAC_RANDOM_AFTER_CONNECT_ARMED;
}
inline bool bluetoothMacModeIsRandomAfterConnect(uint8_t mode) {
return mode == BLUETOOTH_MAC_RANDOM_AFTER_CONNECT
|| mode == BLUETOOTH_MAC_RANDOM_AFTER_CONNECT_ARMED;
}
enum BluetoothStealthMode : uint8_t {
BLUETOOTH_STEALTH_OFF = 0,
BLUETOOTH_STEALTH_PAIRING = 1,
BLUETOOTH_STEALTH_PAIRED = 2,
};
inline bool isValidBluetoothStealthMode(uint8_t mode) {
return mode <= BLUETOOTH_STEALTH_PAIRED;
}
inline bool bluetoothStealthEnabled(uint8_t mode) {
return mode == BLUETOOTH_STEALTH_PAIRING
|| mode == BLUETOOTH_STEALTH_PAIRED;
}
inline bool bluetoothMacPoliciesMatch(uint8_t first, uint8_t second) {
return first == second
|| (bluetoothMacModeIsRandomAfterConnect(first)
&& bluetoothMacModeIsRandomAfterConnect(second));
}
inline bool bluetoothMacModeUsesSavedAddress(uint8_t mode) {
return mode == BLUETOOTH_MAC_CUSTOM
|| mode == BLUETOOTH_MAC_RANDOM_SAVED;
|| mode == BLUETOOTH_MAC_RANDOM_SAVED
|| bluetoothMacModeIsRandomAfterConnect(mode);
}
inline bool hasCustomBluetoothMac(
@@ -51,6 +82,40 @@ inline bool isValidBluetoothMac(
return !payload_all_zero && !payload_all_one;
}
inline bool bluetoothMacShouldRotateAtBoot(
uint8_t mode, const uint8_t address[BLUETOOTH_MAC_BYTES]) {
return bluetoothMacModeIsRandomAfterConnect(mode)
&& (mode == BLUETOOTH_MAC_RANDOM_AFTER_CONNECT_ARMED
|| !isValidBluetoothMac(address));
}
enum BluetoothPeerAddressType : uint8_t {
BLUETOOTH_PEER_ADDRESS_NONE = 0,
BLUETOOTH_PEER_ADDRESS_PUBLIC = 1,
BLUETOOTH_PEER_ADDRESS_RANDOM = 2,
};
struct BluetoothPeerIdentity {
uint8_t type = BLUETOOTH_PEER_ADDRESS_NONE;
uint8_t address[BLUETOOTH_MAC_BYTES] = {};
};
inline bool isValidBluetoothPeerIdentity(
const BluetoothPeerIdentity& peer) {
if (peer.type != BLUETOOTH_PEER_ADDRESS_PUBLIC
&& peer.type != BLUETOOTH_PEER_ADDRESS_RANDOM) {
return false;
}
bool all_zero = true;
bool all_one = true;
for (size_t i = 0; i < BLUETOOTH_MAC_BYTES; i++) {
all_zero = all_zero && peer.address[i] == 0;
all_one = all_one && peer.address[i] == 0xFFu;
}
return !all_zero && !all_one;
}
// Convert six random bytes into a valid BLE random-static identity. This is
// deterministic for a given input so both saved-random and per-boot modes can
// use the platform's existing entropy source without platform-specific rules.
@@ -61,6 +126,24 @@ inline void makeRandomStaticBluetoothMac(
if (!isValidBluetoothMac(address)) address[5] ^= 0x01u;
}
inline void makeRandomStaticBluetoothMacDifferentFrom(
uint8_t address[BLUETOOTH_MAC_BYTES],
const uint8_t previous[BLUETOOTH_MAC_BYTES]) {
makeRandomStaticBluetoothMac(address);
if (address == NULL || previous == NULL
|| memcmp(address, previous, BLUETOOTH_MAC_BYTES) != 0) {
return;
}
address[5] ^= 0x01u;
if (!isValidBluetoothMac(address)) {
// The old payload was one bit away from all-zero or all-one. Restore that
// bit and flip a second payload bit so the result is valid and different.
address[5] ^= 0x01u;
address[4] ^= 0x01u;
}
}
inline int bluetoothMacHexDigit(char value) {
if (value >= '0' && value <= '9') return value - '0';
if (value >= 'a' && value <= 'f') return value - 'a' + 10;
+4 -2
View File
@@ -18,7 +18,8 @@
// separately, see wcIsAdminPasswordKey below.
static const char* const WC_ALLOWED_SET_KEYS[] = {
// NodePrefs (radio / node)
"name", "bluetooth.name", "bluetooth.mac", "lat", "lon", "radio", "tx", "af", "rxdelay", "txdelay",
"name", "bluetooth.name", "bluetooth.mac", "bluetooth.stealth",
"lat", "lon", "radio", "tx", "af", "rxdelay", "txdelay",
"cad", "radio.rxgain", "radio.fem.rxgain", "radio.rxps", "powersaving",
"repeat",
"advert.interval", "flood.advert.interval",
@@ -66,7 +67,8 @@ static inline bool wcIsEspNowChannelKey(const char* key) {
static inline bool wcSetKeyRequiresReboot(const char* key) {
return key != NULL
&& (wcIsEspNowChannelKey(key)
|| strcmp(key, "bluetooth.mac") == 0);
|| strcmp(key, "bluetooth.mac") == 0
|| strcmp(key, "bluetooth.stealth") == 0);
}
// The admin password maps to the top-level `password` command, not a setter, so
+314 -9
View File
@@ -27,6 +27,7 @@ extern "C" bool bleInUse(void) {
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
#define ADVERT_RESTART_DELAY 1000 // millis
#define BLE_BOND_PERSIST_TIMEOUT_MS 15000
static void clearStoredBluetoothBonds() {
#if defined(CONFIG_NIMBLE_ENABLED)
@@ -58,11 +59,245 @@ static void clearStoredBluetoothBonds() {
#endif
}
static bool bluetoothPeersEqual(
const mesh::companion::BluetoothPeerIdentity& lhs,
const mesh::companion::BluetoothPeerIdentity& rhs) {
return lhs.type == rhs.type
&& memcmp(lhs.address, rhs.address, sizeof(lhs.address)) == 0;
}
void SerialBLEInterface::noteSuccessfulConnection(
const mesh::companion::BluetoothPeerIdentity& peer) {
if (_stealth_pair_once) {
_advertisingSuppressed.store(true, std::memory_order_release);
_adv_restart_pending = false;
}
if (!_successfulConnectionPending.load(std::memory_order_acquire)) {
_successfulPeer = peer;
_successfulConnectionStarted.store(
(uint32_t)millis(), std::memory_order_relaxed);
_successfulConnectionPending.store(true, std::memory_order_release);
}
}
#if defined(CONFIG_NIMBLE_ENABLED)
static void bluetoothPeerFromNimbleAddress(
const ble_addr_t& address,
mesh::companion::BluetoothPeerIdentity& peer) {
peer.type = (address.type & 0x01u) == BLE_ADDR_PUBLIC
? mesh::companion::BLUETOOTH_PEER_ADDRESS_PUBLIC
: mesh::companion::BLUETOOTH_PEER_ADDRESS_RANDOM;
for (size_t i = 0; i < mesh::companion::BLUETOOTH_MAC_BYTES; i++) {
peer.address[i] = address.val[
mesh::companion::BLUETOOTH_MAC_BYTES - 1 - i];
}
}
static ble_addr_t nimbleAddressFromBluetoothPeer(
const mesh::companion::BluetoothPeerIdentity& peer) {
ble_addr_t address = {};
address.type =
peer.type == mesh::companion::BLUETOOTH_PEER_ADDRESS_PUBLIC
? BLE_ADDR_PUBLIC
: BLE_ADDR_RANDOM;
for (size_t i = 0; i < mesh::companion::BLUETOOTH_MAC_BYTES; i++) {
address.val[i] = peer.address[
mesh::companion::BLUETOOTH_MAC_BYTES - 1 - i];
}
return address;
}
static bool nimbleBondExistsForPeer(
const mesh::companion::BluetoothPeerIdentity& peer) {
ble_addr_t bonded_peers[8];
int count = 0;
if (ble_store_util_bonded_peers(
bonded_peers, &count,
sizeof(bonded_peers) / sizeof(bonded_peers[0])) != 0) {
return false;
}
for (int i = 0; i < count; i++) {
mesh::companion::BluetoothPeerIdentity candidate;
bluetoothPeerFromNimbleAddress(bonded_peers[i], candidate);
if (bluetoothPeersEqual(candidate, peer)) return true;
}
return false;
}
#else
static void bluetoothPeerFromBluedroidBond(
const esp_ble_bond_dev_t& bond, uint8_t fallback_type,
mesh::companion::BluetoothPeerIdentity& peer) {
const bool has_identity =
(bond.bond_key.key_mask & ESP_LE_KEY_PID) != 0;
const uint8_t* address = has_identity
? bond.bond_key.pid_key.static_addr
: bond.bd_addr;
const uint8_t address_type = has_identity
? bond.bond_key.pid_key.addr_type
: fallback_type;
peer.type = address_type == BLE_ADDR_TYPE_PUBLIC
? mesh::companion::BLUETOOTH_PEER_ADDRESS_PUBLIC
: mesh::companion::BLUETOOTH_PEER_ADDRESS_RANDOM;
memcpy(peer.address, address, sizeof(peer.address));
}
static bool findBluedroidBondedPeer(
const mesh::companion::BluetoothPeerIdentity& requested,
mesh::companion::BluetoothPeerIdentity& resolved) {
int count = esp_ble_get_bond_device_num();
if (count <= 0) return false;
esp_ble_bond_dev_t* devices = static_cast<esp_ble_bond_dev_t*>(
malloc(sizeof(esp_ble_bond_dev_t) * count));
if (devices == NULL) return false;
if (esp_ble_get_bond_device_list(&count, devices) != ESP_OK) {
free(devices);
return false;
}
bool found = false;
for (int i = 0; i < count; i++) {
mesh::companion::BluetoothPeerIdentity candidate;
bluetoothPeerFromBluedroidBond(
devices[i],
requested.type == mesh::companion::BLUETOOTH_PEER_ADDRESS_PUBLIC
? BLE_ADDR_TYPE_PUBLIC
: BLE_ADDR_TYPE_RANDOM,
candidate);
if (bluetoothPeersEqual(candidate, requested)
|| memcmp(devices[i].bd_addr, requested.address,
sizeof(requested.address)) == 0
|| count == 1) {
resolved = candidate;
found = mesh::companion::isValidBluetoothPeerIdentity(resolved);
break;
}
}
free(devices);
return found;
}
#endif
bool SerialBLEInterface::resolveSuccessfulPeer(
mesh::companion::BluetoothPeerIdentity& peer) const {
#if defined(CONFIG_NIMBLE_ENABLED)
if (!mesh::companion::isValidBluetoothPeerIdentity(_successfulPeer)
|| !nimbleBondExistsForPeer(_successfulPeer)) {
return false;
}
peer = _successfulPeer;
return true;
#else
if (!mesh::companion::isValidBluetoothPeerIdentity(_successfulPeer)) {
return false;
}
return findBluedroidBondedPeer(_successfulPeer, peer);
#endif
}
bool SerialBLEInterface::configureBondedOnlyAdvertising(
const mesh::companion::BluetoothPeerIdentity& peer,
bool require_stored_bond) {
if (!mesh::companion::isValidBluetoothPeerIdentity(peer)
|| pServer == NULL) {
return false;
}
#if defined(CONFIG_NIMBLE_ENABLED)
if (require_stored_bond && !nimbleBondExistsForPeer(peer)) {
requestBondedOnlyRecovery("saved peer bond is unavailable");
return false;
}
const ble_addr_t native_peer = nimbleAddressFromBluetoothPeer(peer);
if (ble_gap_wl_set(&native_peer, 1) != 0) {
requestBondedOnlyRecovery("could not set NimBLE allowlist");
return false;
}
#else
if (require_stored_bond) {
mesh::companion::BluetoothPeerIdentity resolved;
if (!findBluedroidBondedPeer(peer, resolved)
|| !bluetoothPeersEqual(peer, resolved)) {
requestBondedOnlyRecovery("saved peer bond is unavailable");
return false;
}
}
esp_bd_addr_t native_peer;
memcpy(native_peer, peer.address, sizeof(native_peer));
const esp_ble_wl_addr_type_t address_type =
peer.type == mesh::companion::BLUETOOTH_PEER_ADDRESS_PUBLIC
? BLE_WL_ADDR_TYPE_PUBLIC
: BLE_WL_ADDR_TYPE_RANDOM;
// The Bluedroid API adds one entry at a time. Replace any controller state
// left by an older mode/session so the requested peer is genuinely the only
// address allowed to scan or connect.
if (esp_ble_gap_clear_whitelist() != ESP_OK) {
requestBondedOnlyRecovery("could not clear Bluedroid allowlist");
return false;
}
if (esp_ble_gap_update_whitelist(true, native_peer, address_type)
!= ESP_OK) {
requestBondedOnlyRecovery("could not set Bluedroid allowlist");
return false;
}
#endif
BLEAdvertising* advertising = pServer->getAdvertising();
if (advertising == NULL) {
requestBondedOnlyRecovery("Bluetooth advertising is unavailable");
return false;
}
advertising->stop();
BLEAdvertisementData minimal_advertisement;
minimal_advertisement.setFlags(ESP_BLE_ADV_FLAG_BREDR_NOT_SPT);
advertising->setScanResponse(false);
advertising->setScanFilter(true, true);
advertising->setAdvertisementData(minimal_advertisement);
_bonded_only = true;
_stealth_pair_once = false;
_advertisingSuppressed.store(false, std::memory_order_release);
_adv_restart_pending = false;
if (_isEnabled && pServer->getConnectedCount() == 0) {
advertising->start();
}
return true;
}
void SerialBLEInterface::requestBondedOnlyRecovery(const char* cause) {
BLE_DEBUG_PRINTLN("SerialBLEInterface: stealth recovery required (%s)",
cause);
_bonded_only = true;
_stealth_pair_once = false;
_advertisingSuppressed.store(true, std::memory_order_release);
_bondedOnlyRecoveryPending.store(true, std::memory_order_release);
_adv_restart_pending = false;
if (pServer != NULL && pServer->getAdvertising() != NULL) {
pServer->getAdvertising()->stop();
}
}
bool SerialBLEInterface::advertisingAllowed() const {
return _isEnabled
&& !_advertisingSuppressed.load(std::memory_order_acquire)
&& !_bondedOnlyRecoveryPending.load(std::memory_order_acquire);
}
bool SerialBLEInterface::begin(const char* prefix, const char* name,
uint32_t pin_code,
const uint8_t* custom_address,
bool clear_bonds) {
bool clear_bonds, bool stealth_pair_once,
const mesh::companion::BluetoothPeerIdentity*
bonded_only_peer) {
_pin_code = pin_code;
_successfulConnectionPending.store(false, std::memory_order_release);
_successfulConnectionStarted.store(0, std::memory_order_relaxed);
_bondedOnlyRecoveryPending.store(false, std::memory_order_release);
_advertisingSuppressed.store(false, std::memory_order_release);
_successfulPeer = mesh::companion::BluetoothPeerIdentity();
_stealth_pair_once = stealth_pair_once;
_bonded_only = false;
if (custom_address != nullptr
&& !mesh::companion::isValidBluetoothMac(custom_address)) {
@@ -220,6 +455,9 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
pRxCharacteristic->setCallbacks(this);
pServer->getAdvertising()->addServiceUUID(SERVICE_UUID);
if (bonded_only_peer != nullptr) {
configureBondedOnlyAdvertising(*bonded_only_peer, true);
}
return true;
}
@@ -250,10 +488,14 @@ bool SerialBLEInterface::onSecurityRequest() {
#if defined(CONFIG_NIMBLE_ENABLED)
void SerialBLEInterface::onAuthenticationComplete(ble_gap_conn_desc* desc) {
const bool success = desc != NULL && desc->sec_state.encrypted &&
desc->sec_state.authenticated;
desc->sec_state.authenticated
&& desc->sec_state.bonded;
if (success) {
BLE_DEBUG_PRINTLN(" - SecurityCallback - Authentication Success");
deviceConnected = true;
mesh::companion::BluetoothPeerIdentity peer;
bluetoothPeerFromNimbleAddress(desc->peer_id_addr, peer);
noteSuccessfulConnection(peer);
} else {
BLE_DEBUG_PRINTLN(" - SecurityCallback - Authentication Failure");
@@ -268,10 +510,15 @@ void SerialBLEInterface::onAuthenticationComplete(ble_gap_conn_desc* desc) {
}
deviceConnected = false;
if (_bonded_only) {
requestBondedOnlyRecovery("bond authentication failed");
}
if (desc != NULL) {
pServer->disconnect(desc->conn_handle);
}
scheduleAdvertisingRestart((uint32_t)millis());
if (advertisingAllowed()) {
scheduleAdvertisingRestart((uint32_t)millis());
}
}
}
#else
@@ -279,6 +526,12 @@ void SerialBLEInterface::onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl) {
if (cmpl.success) {
BLE_DEBUG_PRINTLN(" - SecurityCallback - Authentication Success");
deviceConnected = true;
mesh::companion::BluetoothPeerIdentity peer;
peer.type = cmpl.addr_type == BLE_ADDR_TYPE_PUBLIC
? mesh::companion::BLUETOOTH_PEER_ADDRESS_PUBLIC
: mesh::companion::BLUETOOTH_PEER_ADDRESS_RANDOM;
memcpy(peer.address, cmpl.bd_addr, sizeof(peer.address));
noteSuccessfulConnection(peer);
} else {
BLE_DEBUG_PRINTLN(" - SecurityCallback - Authentication Failure, reason=%u", (unsigned)cmpl.fail_reason);
@@ -294,8 +547,13 @@ void SerialBLEInterface::onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl) {
}
deviceConnected = false;
if (_bonded_only) {
requestBondedOnlyRecovery("bond authentication failed");
}
pServer->disconnect(pServer->getConnId());
scheduleAdvertisingRestart((uint32_t)millis());
if (advertisingAllowed()) {
scheduleAdvertisingRestart((uint32_t)millis());
}
}
}
#endif
@@ -355,7 +613,7 @@ void SerialBLEInterface::onDisconnect(BLEServer* pServer) {
xQueueReset(recv_queue);
_tx_reset_pending.store(true, std::memory_order_release);
if (pTxDescriptor != NULL) pTxDescriptor->setNotifications(false);
if (_isEnabled) {
if (advertisingAllowed()) {
scheduleAdvertisingRestart((uint32_t)millis());
}
}
@@ -416,6 +674,47 @@ void SerialBLEInterface::onStatus(BLECharacteristic* pCharacteristic, Status sta
// ---------- public methods
bool SerialBLEInterface::takeSuccessfulConnection(
mesh::companion::BluetoothPeerIdentity* peer) {
if (!_successfulConnectionPending.load(std::memory_order_acquire)) {
return false;
}
if (peer != nullptr && !resolveSuccessfulPeer(*peer)) {
// Bond storage can finish shortly after authentication. Keep the event
// pending so the main loop can retry without reopening general access. A
// failed bond write must not leave the node unavailable indefinitely.
const uint32_t started = _successfulConnectionStarted.load(
std::memory_order_relaxed);
if (_stealth_pair_once
&& (uint32_t)((uint32_t)millis() - started)
>= BLE_BOND_PERSIST_TIMEOUT_MS) {
_successfulConnectionPending.store(false, std::memory_order_release);
requestBondedOnlyRecovery("new peer bond did not persist");
}
return false;
}
const bool pending = _successfulConnectionPending.exchange(
false, std::memory_order_acq_rel);
if (pending) {
_successfulConnectionStarted.store(0, std::memory_order_relaxed);
}
return pending;
}
bool SerialBLEInterface::enableBondedOnlyAdvertising(
const mesh::companion::BluetoothPeerIdentity& peer) {
return configureBondedOnlyAdvertising(peer, false);
}
void SerialBLEInterface::cancelStealthPairingTransition() {
if (!_stealth_pair_once) return;
_stealth_pair_once = false;
_advertisingSuppressed.store(false, std::memory_order_release);
if (_isEnabled && pServer != NULL && pServer->getConnectedCount() == 0) {
scheduleAdvertisingRestart((uint32_t)millis());
}
}
void SerialBLEInterface::clearBuffers() {
xQueueReset(recv_queue);
send_queue_len = 0;
@@ -435,6 +734,10 @@ void SerialBLEInterface::servicePendingTxReset() {
}
void SerialBLEInterface::scheduleAdvertisingRestart(uint32_t now) {
if (!advertisingAllowed()) {
_adv_restart_pending = false;
return;
}
_adv_restart_started = now;
_adv_restart_pending = true;
}
@@ -446,7 +749,7 @@ void SerialBLEInterface::serviceTxRecovery(uint32_t now) {
BLE_DEBUG_PRINTLN("SerialBLEInterface: stalled TX link is already closed");
deviceConnected = false;
clearBuffers();
if (_isEnabled) scheduleAdvertisingRestart(now);
if (advertisingAllowed()) scheduleAdvertisingRestart(now);
return;
}
@@ -488,7 +791,9 @@ void SerialBLEInterface::enable() {
//pServer->getAdvertising()->setMinInterval(500);
//pServer->getAdvertising()->setMaxInterval(1000);
pServer->getAdvertising()->start();
if (advertisingAllowed()) {
pServer->getAdvertising()->start();
}
_adv_restart_pending = false;
}
@@ -607,7 +912,7 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
//pServer->getAdvertising()->setMinInterval(500);
//pServer->getAdvertising()->setMaxInterval(1000);
scheduleAdvertisingRestart(now);
if (advertisingAllowed()) scheduleAdvertisingRestart(now);
} else {
BLE_DEBUG_PRINTLN("SerialBLEInterface -> stopping advertising");
BLE_DEBUG_PRINTLN("SerialBLEInterface -> connecting...");
@@ -619,7 +924,7 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
oldDeviceConnected = deviceConnected;
}
if (_adv_restart_pending &&
if (advertisingAllowed() && _adv_restart_pending &&
mesh::bleElapsedAtLeast(now, _adv_restart_started,
ADVERT_RESTART_DELAY)) {
if (pServer->getConnectedCount() == 0) {
+33 -1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "../BaseSerialInterface.h"
#include "../BluetoothMac.h"
#include "../BleTxStallWatchdog.h"
#include "../UsbLogging.h"
#include <BLEDevice.h>
@@ -30,6 +31,13 @@ class SerialBLEInterface : public BaseSerialInterface, BLESecurityCallbacks, BLE
mesh::BleDisconnectRecovery _tx_disconnect_recovery;
std::atomic<bool> _tx_reset_pending{false};
std::atomic<bool> _pairingRequestPending{false};
std::atomic<bool> _successfulConnectionPending{false};
std::atomic<uint32_t> _successfulConnectionStarted{0};
mesh::companion::BluetoothPeerIdentity _successfulPeer;
bool _stealth_pair_once;
bool _bonded_only;
std::atomic<bool> _advertisingSuppressed{false};
std::atomic<bool> _bondedOnlyRecoveryPending{false};
struct Frame {
uint8_t len;
@@ -48,6 +56,15 @@ class SerialBLEInterface : public BaseSerialInterface, BLESecurityCallbacks, BLE
void scheduleAdvertisingRestart(uint32_t now);
void recoverStalledTx(const char* cause);
void serviceTxRecovery(uint32_t now);
void noteSuccessfulConnection(
const mesh::companion::BluetoothPeerIdentity& peer);
bool resolveSuccessfulPeer(
mesh::companion::BluetoothPeerIdentity& peer) const;
bool configureBondedOnlyAdvertising(
const mesh::companion::BluetoothPeerIdentity& peer,
bool require_stored_bond);
void requestBondedOnlyRecovery(const char* cause);
bool advertisingAllowed() const;
protected:
// BLESecurityCallbacks methods
@@ -95,6 +112,8 @@ public:
_adv_restart_started = 0;
_adv_restart_pending = false;
_isEnabled = false;
_stealth_pair_once = false;
_bonded_only = false;
_last_write = 0;
last_conn_id = 0;
recv_queue = xQueueCreateStatic(
@@ -110,10 +129,14 @@ public:
* @param pin_code the BLE security pin
* @param custom_address optional human-order BLE random-static address
* @param clear_bonds clear saved peer bonds before accepting connections
* @param stealth_pair_once suppress general advertising after first pairing
* @param bonded_only_peer optional peer allowed to reconnect in stealth mode
*/
bool begin(const char* prefix, const char* name, uint32_t pin_code,
const uint8_t* custom_address = nullptr,
bool clear_bonds = false);
bool clear_bonds = false, bool stealth_pair_once = false,
const mesh::companion::BluetoothPeerIdentity*
bonded_only_peer = nullptr);
// BaseSerialInterface methods
void enable() override;
@@ -130,6 +153,15 @@ public:
bool takePairingRequest() override {
return _pairingRequestPending.exchange(false, std::memory_order_acq_rel);
}
bool takeSuccessfulConnection(
mesh::companion::BluetoothPeerIdentity* peer = nullptr);
bool enableBondedOnlyAdvertising(
const mesh::companion::BluetoothPeerIdentity& peer);
void cancelStealthPairingTransition();
bool takeBondedOnlyRecovery() {
return _bondedOnlyRecoveryPending.exchange(
false, std::memory_order_acq_rel);
}
size_t writeFrame(const uint8_t src[], size_t len) override;
size_t checkRecvFrame(uint8_t dest[]) override;
};
File diff suppressed because it is too large. Load diff
+1
View File
@@ -1797,6 +1797,7 @@ void WebConfigServer::handleConfigGet(AsyncWebServerRequest* req) {
radio["name"] = (const char*)node.name;
radio["bluetooth_name"] = (const char*)node.bluetooth_name;
radio["bluetooth_mac"] = (const char*)node.bluetooth_mac;
radio["bluetooth_stealth"] = node.bluetooth_stealth;
radio["lat"] = node.lat;
radio["lon"] = node.lon;
radio["advert_interval"] = node.advert_interval;
+2
View File
@@ -85,6 +85,7 @@ public:
CAP_BLUETOOTH_NAME = 1UL << 14,
CAP_ESPNOW_CHANNEL = 1UL << 15,
CAP_BLUETOOTH_MAC = 1UL << 16,
CAP_BLUETOOTH_STEALTH = 1UL << 17,
CAP_DELAYS = CAP_RX_DELAY | CAP_TX_DELAY,
};
@@ -95,6 +96,7 @@ public:
char name[32];
char bluetooth_name[32]; // empty = transport's default device name
char bluetooth_mac[24]; // empty = chipset factory address
bool bluetooth_stealth; // independent of the address policy
char admin_password[32]; // empty = trusted LAN/no login prompt
double lat;
double lon;
+255 -10
View File
@@ -10,6 +10,7 @@
// Magic numbers came from actual testing
#define BLE_HEALTH_CHECK_INTERVAL 10000 // Advertising watchdog check every 10 seconds
#define BLE_RETRY_THROTTLE_MS 250 // Throttle retries to 250ms when queue buildup detected
#define BLE_BOND_PERSIST_TIMEOUT_MS 15000 // Bound first-pair transition recovery
// Connection parameters (units: interval=1.25ms, timeout=10ms)
#define BLE_MIN_CONN_INTERVAL 12 // 15ms
@@ -108,11 +109,20 @@ void SerialBLEInterface::onSecured(uint16_t connection_handle) {
if (conn != nullptr && conn->bonded()) {
instance->removeStoredBondForPeer("unsecured link");
}
if (instance->_bonded_only) {
instance->requestBondedOnlyRecovery("unsecured bonded-only link");
}
instance->disconnect();
return;
}
instance->_isDeviceConnected = true;
if (conn->bonded()) {
instance->noteSuccessfulConnection(conn->getPeerAddr());
} else {
BLE_DEBUG_PRINTLN(
"SerialBLEInterface: secured connection was not bonded");
}
instance->_security_timer.cancel();
// Connection interval units: 1.25ms, supervision timeout units: 10ms
@@ -155,8 +165,19 @@ void SerialBLEInterface::onPairingComplete(uint16_t connection_handle, uint8_t a
if (instance->isValidConnection(connection_handle)) {
if (auth_status == BLE_GAP_SEC_STATUS_SUCCESS) {
BLE_DEBUG_PRINTLN("SerialBLEInterface: pairing successful");
BLEConnection* conn = Bluefruit.Connection(connection_handle);
if (conn != nullptr && conn->secured()) {
// Bluefruit may invoke onSecured before it marks a newly paired
// connection as bonded. Record the completed pairing here as well;
// resolveSuccessfulPeer() will keep the event pending until the
// deferred bond write can be loaded.
instance->noteSuccessfulConnection(conn->getPeerAddr());
}
} else {
BLE_DEBUG_PRINTLN("SerialBLEInterface: pairing failed, clearing stale bond and disconnecting");
if (instance->_bonded_only) {
instance->requestBondedOnlyRecovery("pairing failure");
}
BLEConnection* conn = Bluefruit.Connection(connection_handle);
if (conn != nullptr && conn->bonded()) {
instance->removeStoredBondForPeer("pairing failure");
@@ -189,6 +210,9 @@ void SerialBLEInterface::onBLEEvent(ble_evt_t* evt) {
if (conn->bonded()) {
instance->removeStoredBondForPeer("failed bond encryption");
}
if (instance->_bonded_only) {
instance->requestBondedOnlyRecovery("failed bond encryption");
}
instance->_isDeviceConnected = false;
instance->_security_timer.cancel();
sd_ble_gap_disconnect(conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
@@ -197,6 +221,10 @@ void SerialBLEInterface::onBLEEvent(ble_evt_t* evt) {
ble_gap_evt_disconnected_t const* disconnected = &evt->evt.gap_evt.params.disconnected;
if (isBondAuthenticationFailure(disconnected->reason)) {
instance->removeStoredBondForPeer("authentication disconnect");
if (instance->_bonded_only) {
instance->requestBondedOnlyRecovery(
"bond authentication disconnect");
}
}
instance->_peer_address_valid = false;
} else if (evt->header.evt_id == BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST) {
@@ -239,11 +267,149 @@ bool SerialBLEInterface::removeStoredBondForPeer(const char* cause) {
return true;
}
void SerialBLEInterface::noteSuccessfulConnection(
const ble_gap_addr_t& peer_address) {
if (_stealth_pair_once) {
_advertisingSuppressed.store(true, std::memory_order_release);
Bluefruit.Advertising.restartOnDisconnect(false);
}
if (!_successfulConnectionPending.load(std::memory_order_acquire)) {
_successful_peer_address = peer_address;
_successfulConnectionStarted.store(
(uint32_t)millis(), std::memory_order_relaxed);
_successfulConnectionPending.store(true, std::memory_order_release);
}
}
bool SerialBLEInterface::resolveSuccessfulPeer(
mesh::companion::BluetoothPeerIdentity& peer) const {
ble_gap_addr_t lookup = _successful_peer_address;
bond_keys_t keys;
if (!bond_load_keys(BLE_GAP_ROLE_PERIPH, &lookup, &keys)) {
return false;
}
const ble_gap_addr_t& identity = keys.peer_id.id_addr_info;
if (identity.addr_type == BLE_GAP_ADDR_TYPE_PUBLIC) {
peer.type = mesh::companion::BLUETOOTH_PEER_ADDRESS_PUBLIC;
} else if (identity.addr_type == BLE_GAP_ADDR_TYPE_RANDOM_STATIC) {
peer.type = mesh::companion::BLUETOOTH_PEER_ADDRESS_RANDOM;
} else {
return false;
}
for (size_t i = 0; i < mesh::companion::BLUETOOTH_MAC_BYTES; i++) {
peer.address[i] = identity.addr[
mesh::companion::BLUETOOTH_MAC_BYTES - 1 - i];
}
return mesh::companion::isValidBluetoothPeerIdentity(peer);
}
bool SerialBLEInterface::configureBondedOnlyAdvertising(
const mesh::companion::BluetoothPeerIdentity& peer,
bool require_stored_bond) {
if (!mesh::companion::isValidBluetoothPeerIdentity(peer)) return false;
ble_gap_addr_t native_peer = {};
native_peer.addr_type =
peer.type == mesh::companion::BLUETOOTH_PEER_ADDRESS_PUBLIC
? BLE_GAP_ADDR_TYPE_PUBLIC
: BLE_GAP_ADDR_TYPE_RANDOM_STATIC;
for (size_t i = 0; i < mesh::companion::BLUETOOTH_MAC_BYTES; i++) {
native_peer.addr[i] = peer.address[
mesh::companion::BLUETOOTH_MAC_BYTES - 1 - i];
}
ble_gap_addr_t lookup = native_peer;
bond_keys_t keys;
if (!bond_load_keys(BLE_GAP_ROLE_PERIPH, &lookup, &keys)
|| keys.peer_id.id_addr_info.addr_type != native_peer.addr_type
|| memcmp(keys.peer_id.id_addr_info.addr, native_peer.addr,
sizeof(native_peer.addr)) != 0) {
if (require_stored_bond) {
requestBondedOnlyRecovery("saved peer bond is unavailable");
}
return false;
}
if (isAdvertising() && !Bluefruit.Advertising.stop()) {
requestBondedOnlyRecovery("general advertising could not stop");
return false;
}
// A bonded phone may reconnect from a resolvable private address. Loading
// its identity key lets the SoftDevice put a current RPA in TargetA instead
// of directing advertisements only to the phone's static identity address.
const ble_gap_id_key_t* peer_identities[] = {&keys.peer_id};
const uint32_t identity_error = sd_ble_gap_device_identities_set(
peer_identities, nullptr, 1);
if (identity_error != NRF_SUCCESS) {
BLE_DEBUG_PRINTLN(
"SerialBLEInterface: peer identity-list setup failed: %lu",
(unsigned long)identity_error);
requestBondedOnlyRecovery("peer identity-list setup failed");
return false;
}
// Legacy directed advertisements do not carry an advertising or scan
// response payload. Leaving the normal name/service payload configured can
// make the SoftDevice reject the directed advertising parameters.
Bluefruit.Advertising.clearData();
Bluefruit.ScanResponse.clearData();
Bluefruit.Advertising.setType(
BLE_GAP_ADV_TYPE_CONNECTABLE_NONSCANNABLE_DIRECTED);
Bluefruit.Advertising.setPeerAddress(native_peer);
Bluefruit.Advertising.restartOnDisconnect(true);
_bonded_only = true;
_stealth_pair_once = false;
_advertisingSuppressed.store(false, std::memory_order_release);
if (_isEnabled && _conn_handle == BLE_CONN_HANDLE_INVALID
&& !startAdvertising("directed advertising failed to start")) {
return false;
}
return true;
}
void SerialBLEInterface::requestBondedOnlyRecovery(const char* cause) {
BLE_DEBUG_PRINTLN("SerialBLEInterface: stealth recovery required (%s)",
cause);
_bonded_only = true;
_stealth_pair_once = false;
_advertisingSuppressed.store(true, std::memory_order_release);
_bondedOnlyRecoveryPending.store(true, std::memory_order_release);
Bluefruit.Advertising.restartOnDisconnect(false);
if (isAdvertising()) Bluefruit.Advertising.stop();
}
bool SerialBLEInterface::advertisingAllowed() const {
return _isEnabled
&& !_advertisingSuppressed.load(std::memory_order_acquire)
&& !_bondedOnlyRecoveryPending.load(std::memory_order_acquire);
}
bool SerialBLEInterface::startAdvertising(const char* failure_cause) {
if (!advertisingAllowed()) return false;
if (Bluefruit.Advertising.start(0)) return true;
if (_bonded_only) requestBondedOnlyRecovery(failure_cause);
return false;
}
bool SerialBLEInterface::begin(const char* prefix, const char* name,
uint32_t pin_code,
const uint8_t* custom_address,
bool clear_bonds) {
bool clear_bonds, bool stealth_pair_once,
const mesh::companion::BluetoothPeerIdentity*
bonded_only_peer) {
instance = this;
_successfulConnectionPending.store(false, std::memory_order_release);
_successfulConnectionStarted.store(0, std::memory_order_relaxed);
_bondedOnlyRecoveryPending.store(false, std::memory_order_release);
_advertisingSuppressed.store(false, std::memory_order_release);
_stealth_pair_once = stealth_pair_once;
_bonded_only = false;
_bonded_only_configure_pending = false;
_pending_bonded_peer = mesh::companion::BluetoothPeerIdentity();
char charpin[20];
snprintf(charpin, sizeof(charpin), "%lu", (unsigned long)pin_code);
@@ -377,6 +543,8 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
bledfu.setPermission(SECMODE_ENC_WITH_MITM, SECMODE_ENC_WITH_MITM);
bledfu.begin();
Bluefruit.Advertising.setType(
BLE_GAP_ADV_TYPE_CONNECTABLE_SCANNABLE_UNDIRECTED);
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
Bluefruit.Advertising.addTxPower();
Bluefruit.Advertising.addService(bleuart);
@@ -388,9 +556,84 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
Bluefruit.Advertising.restartOnDisconnect(true);
if (bonded_only_peer != nullptr) {
configureBondedOnlyAdvertising(*bonded_only_peer, true);
}
return true;
}
bool SerialBLEInterface::takeSuccessfulConnection(
mesh::companion::BluetoothPeerIdentity* peer) {
if (!_successfulConnectionPending.load(std::memory_order_acquire)) {
return false;
}
if (peer != nullptr && !resolveSuccessfulPeer(*peer)) {
// Bond persistence is deferred by Bluefruit. Leave the event pending and
// let the main loop retry after that callback has written the keys. If the
// deferred write failed, reopen pairing instead of remaining hidden until
// somebody manually power-cycles the node.
const uint32_t started = _successfulConnectionStarted.load(
std::memory_order_relaxed);
if (_stealth_pair_once
&& (uint32_t)((uint32_t)millis() - started)
>= BLE_BOND_PERSIST_TIMEOUT_MS) {
_successfulConnectionPending.store(false, std::memory_order_release);
requestBondedOnlyRecovery("new peer bond did not persist");
}
return false;
}
const bool pending = _successfulConnectionPending.exchange(
false, std::memory_order_acq_rel);
if (pending) {
_successfulConnectionStarted.store(0, std::memory_order_relaxed);
}
return pending;
}
bool SerialBLEInterface::enableBondedOnlyAdvertising(
const mesh::companion::BluetoothPeerIdentity& peer) {
if (!mesh::companion::isValidBluetoothPeerIdentity(peer)) return false;
// The SoftDevice may reject identity-list changes while a connection is
// using that list. Preserve the newly paired session and finish switching
// to directed advertising from the main loop after it disconnects.
if (_conn_handle != BLE_CONN_HANDLE_INVALID) {
_pending_bonded_peer = peer;
_bonded_only_configure_pending = true;
_bonded_only = true;
_stealth_pair_once = false;
_advertisingSuppressed.store(true, std::memory_order_release);
Bluefruit.Advertising.restartOnDisconnect(false);
return true;
}
return configureBondedOnlyAdvertising(peer, false);
}
void SerialBLEInterface::serviceBondedOnlyTransition() {
if (!_bonded_only_configure_pending
|| _conn_handle != BLE_CONN_HANDLE_INVALID) {
return;
}
const mesh::companion::BluetoothPeerIdentity peer = _pending_bonded_peer;
_bonded_only_configure_pending = false;
configureBondedOnlyAdvertising(peer, true);
}
void SerialBLEInterface::cancelStealthPairingTransition() {
if (!_stealth_pair_once) return;
_stealth_pair_once = false;
_advertisingSuppressed.store(false, std::memory_order_release);
Bluefruit.Advertising.setType(
BLE_GAP_ADV_TYPE_CONNECTABLE_SCANNABLE_UNDIRECTED);
Bluefruit.Advertising.restartOnDisconnect(true);
if (_isEnabled && _conn_handle == BLE_CONN_HANDLE_INVALID
&& !isAdvertising()) {
startAdvertising("advertising failed after stealth cancellation");
}
}
void SerialBLEInterface::clearBuffers() {
send_queue_len = 0;
recv_queue_len = 0;
@@ -454,8 +697,8 @@ void SerialBLEInterface::serviceTxRecovery(uint32_t now) {
_peer_address_valid = false;
_security_timer.cancel();
clearBuffers();
if (_isEnabled && !isAdvertising()) {
Bluefruit.Advertising.start(0);
if (advertisingAllowed() && !isAdvertising()) {
startAdvertising("advertising failed after TX recovery");
}
return;
}
@@ -510,9 +753,7 @@ bool SerialBLEInterface::isValidConnection(uint16_t handle, bool requireWaitingF
}
bool SerialBLEInterface::isAdvertising() const {
ble_gap_addr_t adv_addr;
uint32_t err_code = sd_ble_gap_adv_addr_get(0, &adv_addr);
return (err_code == NRF_SUCCESS);
return Bluefruit.Advertising.isRunning();
}
void SerialBLEInterface::enable() {
@@ -523,8 +764,10 @@ void SerialBLEInterface::enable() {
clearBuffers();
_last_health_check = millis();
Bluefruit.Advertising.restartOnDisconnect(true);
Bluefruit.Advertising.start(0);
if (advertisingAllowed()) {
Bluefruit.Advertising.restartOnDisconnect(true);
startAdvertising("advertising failed while enabling Bluetooth");
}
}
void SerialBLEInterface::disconnect() {
@@ -568,6 +811,7 @@ size_t SerialBLEInterface::writeFrame(const uint8_t src[], size_t len) {
size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
const uint32_t check_now = (uint32_t)millis();
serviceBondedOnlyTransition();
if (_tx_disconnect_recovery.pending()) {
serviceTxRecovery(check_now);
return 0;
@@ -655,13 +899,14 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
_security_timer.cancel();
disconnect();
}
if (_isEnabled && !isConnected() && _conn_handle == BLE_CONN_HANDLE_INVALID) {
if (advertisingAllowed() && !isConnected()
&& _conn_handle == BLE_CONN_HANDLE_INVALID) {
if (now - _last_health_check >= BLE_HEALTH_CHECK_INTERVAL) {
_last_health_check = now;
if (!isAdvertising()) {
BLE_DEBUG_PRINTLN("SerialBLEInterface: advertising watchdog - advertising stopped, restarting");
Bluefruit.Advertising.start(0);
startAdvertising("advertising watchdog restart failed");
}
}
}
+37 -1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "../BaseSerialInterface.h"
#include "../BluetoothMac.h"
#include "../BleTxStallWatchdog.h"
#include "../UsbLogging.h"
#include "SecuritySessionTimer.h"
@@ -34,7 +35,16 @@ class SerialBLEInterface : public BaseSerialInterface {
ble_gap_addr_t _peer_address = {};
bool _peer_address_valid;
bool _bond_removed_for_connection;
ble_gap_addr_t _successful_peer_address = {};
bool _stealth_pair_once;
bool _bonded_only;
bool _bonded_only_configure_pending;
mesh::companion::BluetoothPeerIdentity _pending_bonded_peer;
std::atomic<bool> _advertisingSuppressed{false};
std::atomic<bool> _bondedOnlyRecoveryPending{false};
std::atomic<bool> _pairingRequestPending{false};
std::atomic<bool> _successfulConnectionPending{false};
std::atomic<uint32_t> _successfulConnectionStarted{0};
SecuritySessionTimer _security_timer;
mesh::BleTxStallWatchdog _tx_stall_watchdog;
mesh::BleDisconnectRecovery _tx_disconnect_recovery;
@@ -59,6 +69,16 @@ class SerialBLEInterface : public BaseSerialInterface {
void recoverStalledTx(const char* cause);
void serviceTxRecovery(uint32_t now);
bool removeStoredBondForPeer(const char* cause);
void noteSuccessfulConnection(const ble_gap_addr_t& peer_address);
bool resolveSuccessfulPeer(
mesh::companion::BluetoothPeerIdentity& peer) const;
bool configureBondedOnlyAdvertising(
const mesh::companion::BluetoothPeerIdentity& peer,
bool require_stored_bond);
void serviceBondedOnlyTransition();
void requestBondedOnlyRecovery(const char* cause);
bool advertisingAllowed() const;
bool startAdvertising(const char* failure_cause);
bool isValidConnection(uint16_t handle, bool requireWaitingForSecurity = false) const;
bool isAdvertising() const;
static void onConnect(uint16_t connection_handle);
@@ -85,6 +105,9 @@ public:
_last_retry_attempt = 0;
_peer_address_valid = false;
_bond_removed_for_connection = false;
_stealth_pair_once = false;
_bonded_only = false;
_bonded_only_configure_pending = false;
send_queue_len = 0;
recv_queue_len = 0;
}
@@ -96,10 +119,14 @@ public:
* @param pin_code the BLE security pin
* @param custom_address optional human-order BLE random-static address
* @param clear_bonds clear saved peer bonds before accepting connections
* @param stealth_pair_once suppress general advertising after first pairing
* @param bonded_only_peer optional peer allowed to reconnect in stealth mode
*/
bool begin(const char* prefix, const char* name, uint32_t pin_code,
const uint8_t* custom_address = nullptr,
bool clear_bonds = false);
bool clear_bonds = false, bool stealth_pair_once = false,
const mesh::companion::BluetoothPeerIdentity*
bonded_only_peer = nullptr);
void disconnect();
void enable() override;
@@ -112,6 +139,15 @@ public:
bool takePairingRequest() override {
return _pairingRequestPending.exchange(false, std::memory_order_acq_rel);
}
bool takeSuccessfulConnection(
mesh::companion::BluetoothPeerIdentity* peer = nullptr);
bool enableBondedOnlyAdvertising(
const mesh::companion::BluetoothPeerIdentity& peer);
void cancelStealthPairingTransition();
bool takeBondedOnlyRecovery() {
return _bondedOnlyRecoveryPending.exchange(
false, std::memory_order_acq_rel);
}
size_t writeFrame(const uint8_t src[], size_t len) override;
size_t checkRecvFrame(uint8_t dest[]) override;
#if COMPANION_FEATURE_BLE_MOTA_SOURCE