Add signed private fleet controls for filtering and secondary radio

Enroll a private channel and publisher public key on repeaters and room servers. Local Companion fleet sends sign targeted or whole-fleet commands, with expiry, durable replay protection, and a restricted command allowlist. Preserve exact transmitted-reply barriers for secondary-radio changes, bound validation and replies, and qualify crypto, persistence, transport scope, role permissions, and compact-profile exclusions with regression tests.
This commit is contained in:
mikecarper committed 2026-10-08 16:45:19 -07:00
1 parent a14bbdc58f
commit d83fa7cf8e
27 files changed
+3028 -2

No files matched your search

+1
View File
@@ -296,6 +296,7 @@ typedef uint32_t DispatcherAction;
* and scheduling of outbound Packets.
*/
class Dispatcher {
friend class FleetChannel; // bounded deferred receiver and exact reply retirement
enum class OutboundCancellation : uint8_t { None, Cancelled, Delivered };
Packet* outbound; // current outbound packet
unsigned long outbound_expiry, outbound_start, total_air_time, rx_air_time;
+3
View File
@@ -2856,6 +2856,9 @@ uint8_t CommonCLI::buildAdvertData(uint8_t node_type, uint8_t* app_data) {
void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* reply) {
PrefsSaveReplyGuard save_reply(_prefs_save_failures, reply);
mesh::cli::normalizeCommandVerb(command);
#if MESH_ENABLE_FLEET_CONTROL
if (handleFleetCommand(command, reply)) return;
#endif
#if MESH_BATTERY_CHARGE_CONTROL
if (mesh::power::handleBatteryChargeCommand(*_board, command, reply, 160)) return;
#endif
+12
View File
@@ -15,6 +15,10 @@
#include <helpers/RepeaterRadioTiming.h>
#include <helpers/RadioProfileCLI.h>
#include <helpers/WirelessControl.h>
#include <helpers/FleetCommand.h>
#if MESH_ENABLE_FLEET_CONTROL
#include <helpers/FleetChannel.h>
#endif
#ifndef DEFAULT_CAD_ENABLED
#define DEFAULT_CAD_ENABLED 0
@@ -478,6 +482,7 @@ struct LegacyObserverTail {
class CommonCLICallbacks {
public:
virtual bool supportsFleetControl() const { return false; }
// True only after an actual NTP response this boot, not a plausible RTC.
virtual bool managementNtpSynced() const { return false; }
virtual mesh::Radio* getProfileRadio() { return nullptr; }
@@ -831,6 +836,10 @@ class CommonCLI {
bool _common_save_succeeded = false;
uint32_t _prefs_save_failures = 0;
mesh::RadioProfileCLI _radio_profiles;
#if MESH_ENABLE_FLEET_CONTROL
mesh::FleetChannel* _fleet_channel = nullptr; // allocate only when enrolled
bool handleFleetCommand(const char* command, char* reply);
#endif
mesh::RTCClock* getRTCClock() { return _rtc; }
void savePrefs(
@@ -887,6 +896,9 @@ public:
uint16_t preamble);
mesh::RadioProfileCLI& radioProfiles() { return _radio_profiles; }
const mesh::RadioProfileCLI& radioProfiles() const { return _radio_profiles; }
#if MESH_ENABLE_FLEET_CONTROL
mesh::FleetChannel* fleetChannel() { return _fleet_channel; }
#endif
static bool calculateRxPowerSavingLevel(uint32_t level, uint8_t sf, float bw, uint32_t preamble,
uint32_t* rx_us, uint32_t* sleep_us);
static bool recalculateRxPowerSavingFromLevel(NodePrefs* prefs);
+25
View File
@@ -245,6 +245,12 @@ static bool resolveDataScope(DataRouteState& route, TransportKey& scope,
void CommonCLI::beginManagement(mesh::Mesh& mesh, FILESYSTEM* fs) {
_management_mesh = &mesh; _management_fs = fs;
_management_last_ms = millis(); _management_uptime_ms = _management_last_ms;
#if MESH_ENABLE_FLEET_CONTROL
if (_callbacks->supportsFleetControl()
&& (fs->exists("/fleet_channel") || fs->exists("/fleet_channel.bak"))) {
_fleet_channel = new (std::nothrow) mesh::FleetChannel(fs);
}
#endif
if (!_data_route) {
mesh::hilStartupTrace("management_route_begin");
_data_route = new (std::nothrow) mesh::DataRouteState;
@@ -265,6 +271,25 @@ void CommonCLI::beginManagement(mesh::Mesh& mesh, FILESYSTEM* fs) {
mesh::hilStartupTrace("management_probe_ready");
}
#if MESH_ENABLE_FLEET_CONTROL
bool CommonCLI::handleFleetCommand(const char* command, char* reply) {
const bool fleet_command = !strncmp(command, "get fleet.", 10)
|| !strncmp(command, "set fleet.", 10);
if (!fleet_command) return false;
if (!_callbacks->supportsFleetControl()) {
strcpy(reply, "Err - fleet control is available on infrastructure roles"); return true;
}
if (!_fleet_channel) _fleet_channel = new (std::nothrow) mesh::FleetChannel(_management_fs);
if (!_fleet_channel) {
strcpy(reply, "Err - fleet control memory unavailable"); return true;
}
if (!_fleet_channel->handleConfig(command, reply, 160)) {
strcpy(reply, "Err - use fleet.channel, fleet.controller, or fleet.stats");
}
return true;
}
#endif
void CommonCLI::loopManagement() {
const uint32_t now = millis();
_management_uptime_ms += uint32_t(now - _management_last_ms); _management_last_ms = now;
+237
View File
@@ -0,0 +1,237 @@
#include "FleetChannel.h"
#include "FilePresence.h"
#include "FileRead.h"
#include "PersistentStoreFormat.h"
#include <Arduino.h>
#include <stdio.h>
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
#include "AtomicFileWriter.h"
#else
#include "ContactFileTransaction.h"
#endif
namespace mesh {
namespace {
constexpr char Path[] = "/fleet_channel";
constexpr size_t ImageSize = 64;
bool zero(const uint8_t* p, size_t length) {
uint8_t value = 0;
while (length--) value |= *p++;
return value == 0;
}
}
bool FleetChannel::load() {
if (!fs_) return false;
#if defined(ESP32_PLATFORM) || defined(RP2040_PLATFORM)
if (!ContactFileTransaction::recover(fs_, Path, filePresence<FILESYSTEM>)) return false;
#endif
bool present = false;
if (!filePresence(fs_, Path, present)) return false;
if (!present) return true;
auto file = openFileRead(fs_, Path);
uint8_t image[ImageSize];
const bool read = file && file.size() == ImageSize
&& file.read(image, ImageSize) == (int)ImageSize;
file.close();
if (!read || memcmp(image, "FCS1", 4) != 0 || image[4] > 1
|| !zero(image + 5, 3)
|| storage::readLE32(image + 60) != storage::updateCRC32(0xffffffff, image, 60)) return false;
if (!zero(image + 8, 16) && !FleetCommand::privateKeyAllowed(image + 8)) return false;
configured_ = image[4] != 0;
if (configured_ && zero(image + 8, 16)) return false;
memcpy(channel_.secret, image + 8, 16);
Utils::sha256(channel_.hash, sizeof(channel_.hash), channel_.secret, 16);
memcpy(controller_.pub_key, image + 24, 32);
controller_set_ = !zero(controller_.pub_key, 32);
last_sequence_ = storage::readLE32(image + 56);
return true;
}
bool FleetChannel::save(bool enabled, const uint8_t* key, const uint8_t* controller,
uint32_t sequence) {
if (!healthy_ || !fs_) return false;
uint8_t image[ImageSize] = {'F', 'C', 'S', '1', uint8_t(enabled)};
memcpy(image + 8, key, 16);
memcpy(image + 24, controller, 32);
storage::writeLE32(image + 56, sequence);
storage::writeLE32(image + 60, storage::updateCRC32(0xffffffff, image, 60));
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
AtomicFileWriter writer(fs_, Path);
#else
ContactFileTransaction writer(fs_, Path, filePresence<FILESYSTEM>);
#endif
return writer && writer.write(image, sizeof(image)) == sizeof(image) && writer.commit();
}
bool FleetChannel::handleConfig(const char* command, char* reply, size_t capacity) {
if (!strcmp(command, "get fleet.channel")) {
char fingerprint[3];
Utils::toHex(fingerprint, channel_.hash, 1);
snprintf(reply, capacity, "> %s,controller=%s,store=%s,hash=%s,last=%lu",
configured_ ? "on" : "off", controller_set_ ? "set" : "unset",
healthy_ ? "ok" : "error", fingerprint, (unsigned long)last_sequence_);
} else if (!strcmp(command, "get fleet.controller")) {
if (controller_set_) {
char key[65];
Utils::toHex(key, controller_.pub_key, 32);
snprintf(reply, capacity, "> %s", key);
} else snprintf(reply, capacity, "> unset");
} else if (!strcmp(command, "get fleet.stats")) {
snprintf(reply, capacity, "> accepted=%lu rejected=%lu busy=%lu pending=%u ack=%u",
(unsigned long)accepted_, (unsigned long)rejected_, (unsigned long)busy_,
unsigned(pending_), unsigned(barrier_.waiting()));
} else if (!strncmp(command, "set fleet.channel ", 18)) {
if (pending_ || barrier_.waiting()) {
snprintf(reply, capacity, "Err - fleet command pending; retry later"); return true;
}
const char* value = command + 18;
uint8_t key[16] = {};
const bool enabled = strcmp(value, "off") != 0;
if (enabled && (strlen(value) != 32 || !Utils::fromHex(key, 16, value)
|| !FleetCommand::privateKeyAllowed(key))) {
snprintf(reply, capacity, "Err - use a private random 128-bit key or off"); return true;
}
if (!save(enabled, key, controller_.pub_key, last_sequence_)) {
snprintf(reply, capacity, "Err - fleet settings not saved; store unavailable"); return true;
}
configured_ = enabled;
memset(channel_.secret, 0, sizeof(channel_.secret));
memcpy(channel_.secret, key, sizeof(key));
Utils::sha256(channel_.hash, sizeof(channel_.hash), key, sizeof(key));
snprintf(reply, capacity, "OK - fleet channel %s; publisher signature required",
enabled ? "on" : "off");
} else if (!strncmp(command, "set fleet.controller ", 21)) {
if (pending_ || barrier_.waiting()) {
snprintf(reply, capacity, "Err - fleet command pending; retry later"); return true;
}
const char* value = command + 21;
uint8_t key[32] = {};
if (strcmp(value, "off") && (strlen(value) != 64 || !Utils::fromHex(key, 32, value) || zero(key, 32))) {
snprintf(reply, capacity, "Err - use publisher public key (64 hex) or off"); return true;
}
if (!save(configured_, channel_.secret, key, last_sequence_)) {
snprintf(reply, capacity, "Err - fleet settings not saved; store unavailable"); return true;
}
memcpy(controller_.pub_key, key, 32);
controller_set_ = !zero(key, 32);
snprintf(reply, capacity, "OK - fleet publisher %s", controller_set_ ? "set" : "off");
} else return false;
return true;
}
void FleetChannel::receive(Packet* packet, Mesh& mesh, const TransportKey* scope) {
if (!healthy_ || !configured_ || !controller_set_ || !packet
|| packet->getPayloadType() != PAYLOAD_TYPE_GRP_DATA
|| packet->payload_len < 1 + CIPHER_MAC_SIZE + CIPHER_BLOCK_SIZE
|| packet->payload_len > sizeof(incoming_) || packet->payload[0] != channel_.hash[0]) return;
if (pending_ || barrier_.waiting()) { ++busy_; return; }
// Do no decryption, signature verification, or writes on the receive stack.
memcpy(incoming_, packet->payload, packet->payload_len);
incoming_len_ = packet->payload_len;
rx_profile_ = packet->radio_profile;
rx_generation_ = packet->radio_generation;
path_hash_size_ = packet->getPathHashSize();
reply_scoped_ = packet->hasTransportCodes();
reply_scope_known_ = scope != nullptr && !scope->isNull();
if (reply_scope_known_) reply_scope_ = *scope;
pending_ = true;
(void)mesh;
}
bool FleetChannel::decode(Mesh& mesh, FleetCommand::Decoded& command) {
const uint32_t now_ms = millis();
if (uint32_t(now_ms - verify_window_) >= 1000) {
verify_window_ = now_ms; verify_attempts_ = 0;
}
// A forged matching channel hash must not monopolize the radio loop with
// Ed25519 work. Legitimate publishers can retry with a fresh sequence.
if (verify_attempts_ >= 4) return false;
++verify_attempts_;
uint8_t data[MAX_PACKET_PAYLOAD];
const int length = Utils::MACThenDecrypt(channel_.secret, data, incoming_ + 1, incoming_len_ - 1);
if (length < 3 || data[0] != uint8_t(FleetCommand::DataType)
|| data[1] != uint8_t(FleetCommand::DataType >> 8)) return false;
const size_t payload_length = data[2];
const size_t unpadded = 3 + payload_length;
if (unpadded > (size_t)length || (unpadded + 15) / 16 * 16 != (size_t)length
|| !zero(data + unpadded, length - unpadded)) return false;
if (payload_length < FleetCommand::HeaderSize + FleetCommand::SignatureSize
|| storage::readLE32(data + 7) <= last_sequence_) return false;
if (!FleetCommand::decode(controller_, channel_.secret, data + 3, payload_length,
mesh.getRTCClock()->getCurrentTime(), mesh.self_id.pub_key, command)) return false;
broadcast_ = zero(data + 3 + 12, FleetCommand::TargetSize);
return true;
}
bool FleetChannel::acknowledge(Mesh& mesh, const char* name, uint32_t sequence,
const char* reply, bool radio_mutation) {
// Mesh::createGroupDatagram reserves one channel byte and a full block's
// padding allowance, so at most 168 plaintext bytes fit a 184-byte payload.
uint8_t data[MAX_PACKET_PAYLOAD - CIPHER_BLOCK_SIZE] = {};
const uint32_t time = mesh.getRTCClock()->getCurrentTime();
memcpy(data, &time, sizeof(time));
data[4] = 0; // TXT_TYPE_PLAIN
char identity[13];
Utils::toHex(identity, mesh.self_id.pub_key, 6);
// Keep names bounded and remove ':' so ordinary app channel parsers agree.
char sender[17];
snprintf(sender, sizeof(sender), "%.16s", name ? name : "node");
for (char* p = sender; *p; ++p) if (*p == ':') *p = ';';
const int count = snprintf((char*)data + 5, sizeof(data) - 5,
"%s: fleet %lu %s: %s", sender,
(unsigned long)sequence, identity, reply);
if (count < 0) return false;
const size_t length = count >= int(sizeof(data) - 5) ? sizeof(data) - 6 : size_t(count);
Packet* packet = mesh.createGroupDatagram(PAYLOAD_TYPE_GRP_TXT, channel_, data, 5 + length);
if (!packet) return false;
packet->radio_reply = true;
packet->flood_retry_policy = FLOOD_RETRY_POLICY_DENY;
// Acknowledgements have one tracked physical attempt per profile. A later
// untracked retry must never trigger a completed radio transition twice.
packet->radio_bound = false;
if (radio_mutation) barrier_.prepare(packet);
// Keep short temporary leases useful: their clock started at admission and
// may not be extended by waiting for a fleet acknowledgement.
const uint32_t maximum_delay = broadcast_ ? (radio_mutation ? 15500 : 60500) : 1500;
const uint32_t delay = mesh.getRNG()->nextInt(500, maximum_delay);
bool queued = false;
if (reply_scoped_) {
if (!reply_scope_known_) {
mesh.releasePacket(packet);
if (radio_mutation) barrier_.clear();
return false;
}
uint16_t codes[2] = {reply_scope_.calcTransportCode(packet), 0};
queued = mesh.sendFlood(packet, codes, delay, path_hash_size_);
} else queued = mesh.sendFlood(packet, delay, path_hash_size_);
if (!queued) { if (radio_mutation) barrier_.clear(); return false; }
if (radio_mutation) {
barrier_.arm(packet);
ack_deadline_ = millis() + 300000UL;
}
return true;
}
void FleetChannel::finish(RadioProfileCLI& profiles, bool delivered) {
barrier_.clear(); ack_deadline_ = 0;
profiles.finishReplyMutation(delivered);
}
void FleetChannel::complete(Packet* packet, RadioProfileCLI& profiles) {
if (barrier_.complete(packet) && !barrier_.waiting()) finish(profiles, true);
}
void FleetChannel::fail(Packet* packet, RadioProfileCLI& profiles) {
if (barrier_.fail(packet)) finish(profiles, false);
else if (!barrier_.waiting() && barrier_.succeeded()) finish(profiles, true);
}
void FleetChannel::serviceDeadline(Mesh& mesh, RadioProfileCLI& profiles) {
if (!barrier_.waiting() || int32_t(uint32_t(millis()) - ack_deadline_) < 0) return;
if (barrier_.contains(mesh.getOutboundInFlight())) mesh.cancelOutboundRadioRetry(mesh.getOutboundInFlight());
for (int i = mesh._mgr->getOutboundTotal() - 1; i >= 0; --i) {
if (!barrier_.contains(mesh._mgr->getOutboundByIdx(i))) continue;
Packet* packet = mesh._mgr->removeOutboundByIdx(i);
static_cast<Dispatcher&>(mesh).onSendFail(packet);
mesh.releasePacket(packet);
}
}
} // namespace mesh
+100
View File
@@ -0,0 +1,100 @@
#pragma once
#include <Mesh.h>
#include <helpers/IdentityStore.h>
#include <helpers/RadioProfileCLI.h>
#include <helpers/TempRadioReplyBarrier.h>
#include <helpers/FleetCommand.h>
#include <helpers/TransportKeyStore.h>
namespace mesh {
// Scope codes authenticate the original packet's payload. A new reply needs
// fresh codes from the exact matching region key, including rotated keys.
template <typename Regions, typename Region>
bool captureFleetReplyScope(Regions& regions, const Region* region,
const Packet* packet, TransportKey& scope) {
if (!packet || !packet->hasTransportCodes() || !region || region->isWildcard()) return false;
TransportKey candidates[MAX_TKS_ENTRIES];
const int count = regions.getTransportKeysFor(*region, candidates, MAX_TKS_ENTRIES);
for (int i = 0; i < count && i < MAX_TKS_ENTRIES; ++i) {
const uint16_t code = candidates[i].calcTransportCode(packet);
if (code == packet->transport_codes[0] || code == packet->transport_codes[1]) {
scope = candidates[i]; return true;
}
}
return false;
}
// Optional infrastructure-only receiver. The publisher's private key is never
// enrolled here. The ordinary channel key provides privacy; signatures grant
// the deliberately narrower fleet capability.
class FleetChannel {
FILESYSTEM* fs_;
GroupChannel channel_{};
Identity controller_;
uint32_t last_sequence_ = 0;
uint32_t ack_deadline_ = 0;
uint32_t verify_window_ = 0;
uint32_t accepted_ = 0, rejected_ = 0, busy_ = 0;
uint8_t verify_attempts_ = 0;
bool configured_ = false, controller_set_ = false, healthy_ = false;
bool pending_ = false;
bool broadcast_ = false;
uint8_t incoming_[MAX_PACKET_PAYLOAD]{};
uint8_t incoming_len_ = 0, rx_profile_ = 0, path_hash_size_ = 1;
uint32_t rx_generation_ = 0;
TransportKey reply_scope_{};
bool reply_scoped_ = false, reply_scope_known_ = false;
TempRadioReplyBarrier barrier_;
bool load();
bool save(bool enabled, const uint8_t* key, const uint8_t* controller,
uint32_t sequence);
bool decode(Mesh& mesh, FleetCommand::Decoded& command);
bool acknowledge(Mesh& mesh, const char* name, uint32_t sequence,
const char* reply, bool radio_mutation);
void finish(RadioProfileCLI& profiles, bool delivered);
void serviceDeadline(Mesh& mesh, RadioProfileCLI& profiles);
public:
explicit FleetChannel(FILESYSTEM* fs) : fs_(fs) { healthy_ = load(); }
bool handleConfig(const char* command, char* reply, size_t capacity);
void receive(Packet* packet, Mesh& mesh, const TransportKey* scope = nullptr);
void complete(Packet* packet, RadioProfileCLI& profiles);
void fail(Packet* packet, RadioProfileCLI& profiles);
void copy(Packet* packet, const Packet* original) { barrier_.trackCopy(original, packet); }
bool waiting() const { return barrier_.waiting(); }
template <typename Handler>
void service(Mesh& mesh, RadioProfileCLI& profiles, const char* name,
Handler handle) {
serviceDeadline(mesh, profiles);
if (!pending_) return;
pending_ = false;
if (barrier_.waiting() || profiles.hasReplyMutation()) { ++busy_; return; }
FleetCommand::Decoded command;
if (!decode(mesh, command)) { ++rejected_; return; }
// Reserve before dispatch, including failed commands. A lost reply, reboot,
// or retry can never repeat a mutation. A storage failure grants no control.
if (!save(configured_, channel_.secret, controller_.pub_key, command.sequence)) {
healthy_ = false;
++rejected_;
return;
}
last_sequence_ = command.sequence;
++accepted_;
Dispatcher::ReceiveProfileScope receive_scope(mesh, rx_profile_, rx_generation_);
char reply[160] = {};
const uint32_t generation = profiles.replyMutationGeneration();
profiles.beginReplyCommand();
handle(command.sequence, command.command, reply);
profiles.endReplyCommand();
const bool changed = profiles.replyMutationGeneration() != generation;
if (!acknowledge(mesh, name, command.sequence, reply, changed) && changed) {
finish(profiles, false);
}
}
};
} // namespace mesh
+262
View File
@@ -0,0 +1,262 @@
#include "FleetCommand.h"
#include <SHA256.h>
#include <string.h>
namespace mesh {
namespace {
constexpr char Domain[] = "MeshCoreFleet1";
constexpr size_t SignedMessageCapacity = sizeof(Domain) - 1
+ FleetCommand::KeySize + FleetCommand::HeaderSize
+ FleetCommand::MaxCommandLength;
constexpr uint8_t PublicKey[FleetCommand::KeySize] = {
0x8b, 0x33, 0x87, 0xe9, 0xc5, 0xcd, 0xea, 0x6a,
0xc9, 0xe5, 0xed, 0xba, 0xa1, 0x15, 0xcd, 0x72
};
bool zero(const uint8_t* value, size_t size) {
uint8_t combined = 0;
for (size_t i = 0; i < size; ++i) combined |= value[i];
return combined == 0;
}
void erase(uint8_t* bytes, size_t length) {
volatile uint8_t* destination = bytes;
while (length--) *destination++ = 0;
}
void write32(uint8_t* dest, uint32_t value) {
for (unsigned i = 0; i < 4; ++i) dest[i] = value >> (i * 8);
}
uint32_t read32(const uint8_t* source) {
uint32_t value = 0;
for (unsigned i = 0; i < 4; ++i) value |= uint32_t(source[i]) << (i * 8);
return value;
}
void targetHash(const uint8_t* full_key, uint8_t* target) {
SHA256 hash;
hash.update(full_key, PUB_KEY_SIZE);
hash.finalize(target, FleetCommand::TargetSize);
}
int hexDigit(char digit) {
if (digit >= '0' && digit <= '9') return digit - '0';
if (digit >= 'a' && digit <= 'f') return digit - 'a' + 10;
if (digit >= 'A' && digit <= 'F') return digit - 'A' + 10;
return -1;
}
bool lifetimeAllowed(uint32_t sequence, uint32_t expires) {
return sequence >= FleetCommand::MinEpoch && expires >= sequence
&& expires - sequence <= FleetCommand::MaxLifetime;
}
size_t signedMessage(const uint8_t* key, const uint8_t* payload,
size_t length, uint8_t* output) {
const size_t prefix = sizeof(Domain) - 1 + FleetCommand::KeySize;
memcpy(output, Domain, sizeof(Domain) - 1);
memcpy(output + sizeof(Domain) - 1, key, FleetCommand::KeySize);
memcpy(output + prefix, payload, length);
return prefix + length;
}
bool keyEquals(const char* key, size_t length, const char* candidate) {
return strlen(candidate) == length && !memcmp(key, candidate, length);
}
// The CLI handler owns board-specific range checks. Authorization admits
// only the exact namespace and a strictly numeric optional row suffix.
bool rowKey(const char* key, size_t length, const char* family) {
const size_t family_length = strlen(family);
if (length < family_length || memcmp(key, family, family_length)) return false;
if (length == family_length) return true;
if (key[family_length] != '.') return false;
size_t cursor = family_length + 1;
if (cursor == length || key[cursor] < '1' || key[cursor] > '9') return false;
unsigned row = 0;
for (; cursor < length; ++cursor) {
if (key[cursor] < '0' || key[cursor] > '9') return false;
row = row * 10 + unsigned(key[cursor] - '0');
if (row > 255) return false;
}
return true;
}
bool decimalToken(const char* text, size_t length) {
if (!length) return false;
bool dot = false, digit = false;
for (size_t i = 0; i < length; ++i) {
if (text[i] >= '0' && text[i] <= '9') digit = true;
else if (text[i] == '.' && !dot) dot = true;
else return false;
}
return digit;
}
bool integerToken(const char* text, size_t length) {
if (!length) return false;
for (size_t i = 0; i < length; ++i)
if (text[i] < '0' || text[i] > '9') return false;
return true;
}
bool radioTuple(const char* arguments, bool temporary) {
if (!strcmp(arguments, "off")) return true;
unsigned fields = 0;
const unsigned expected = temporary ? 6 : 5;
const char* cursor = arguments;
for (;;) {
const char* end = strchr(cursor, ',');
const size_t length = end ? size_t(end - cursor) : strlen(cursor);
bool valid;
if (fields < 2) valid = decimalToken(cursor, length);
else if (fields < 4 || (temporary && fields == 5))
valid = integerToken(cursor, length);
else if (fields == 4) valid = keyEquals(cursor, length, "rx")
|| keyEquals(cursor, length, "rxtx");
else valid = fields == expected
&& (integerToken(cursor, length) || keyEquals(cursor, length, "auto"));
if (!valid || ++fields > expected + 1) return false;
if (!end) return fields == expected || fields == expected + 1;
cursor = end + 1;
}
}
} // namespace
bool FleetCommand::privateKeyAllowed(const uint8_t* key) {
return key && !zero(key, KeySize) && memcmp(key, PublicKey, KeySize) != 0;
}
bool FleetCommand::parseTarget(const char* text, uint8_t* target) {
if (!text || !target) return false;
if (!strcmp(text, "all")) {
memset(target, 0, TargetSize);
return true;
}
if (strlen(text) != PUB_KEY_SIZE * 2) return false;
uint8_t full_key[PUB_KEY_SIZE];
for (size_t i = 0; i < PUB_KEY_SIZE; ++i) {
const int upper = hexDigit(text[i * 2]);
const int lower = hexDigit(text[i * 2 + 1]);
if (upper < 0 || lower < 0) return false;
full_key[i] = uint8_t((upper << 4) | lower);
}
// An invalid zero identity must not masquerade as the reserved all target.
if (zero(full_key, PUB_KEY_SIZE)) return false;
targetHash(full_key, target);
return !zero(target, TargetSize);
}
bool FleetCommand::commandAllowed(const char* command) {
if (!command) return false;
size_t length = 0;
while (command[length]) {
const unsigned char byte = command[length];
if (++length > MaxCommandLength || byte < 0x20 || byte > 0x7e
|| byte == ';' || byte == '|' || byte == '&' || byte == '`'
|| byte == '\\') return false;
}
if (!length || command[0] == ' ' || command[length - 1] == ' ') return false;
bool get = false, set = false, del = false;
if (!strncmp(command, "get ", 4)) get = true;
else if (!strncmp(command, "set ", 4)) set = true;
else if (!strncmp(command, "del ", 4)) del = true;
else return false;
const char* key = command + 4;
const char* separator = strchr(key, ' ');
const size_t key_length = separator ? size_t(separator - key) : strlen(key);
const char* arguments = separator ? separator + 1 : "";
if (!key_length || (separator && (!*arguments || *arguments == ' '))) return false;
if (keyEquals(key, key_length, "radio2")
|| keyEquals(key, key_length, "tempradio2")) {
return get ? !*arguments : set && radioTuple(arguments, key_length == 10);
}
if (keyEquals(key, key_length, "radio2.status")
|| keyEquals(key, key_length, "radio2.timing")) return get && !*arguments;
if (keyEquals(key, key_length, "radio2.cross")) {
return get ? !*arguments : set && (!strcmp(arguments, "on")
|| !strcmp(arguments, "off") || !strcmp(arguments, "auto"));
}
const bool rows = rowKey(key, key_length, "flood.filter")
|| rowKey(key, key_length, "flood.filter.blacklist")
|| rowKey(key, key_length, "flood.rule")
|| rowKey(key, key_length, "flood.moderation")
|| rowKey(key, key_length, "flood.channel.scope")
|| rowKey(key, key_length, "flood.channel.scope.require");
if (rows) return get ? !*arguments
: set ? *arguments != 0 : del && (!*arguments || !strcmp(arguments, "all"));
const bool settings = keyEquals(key, key_length, "flood.channel.data")
|| keyEquals(key, key_length, "flood.channel.data.hops")
|| keyEquals(key, key_length, "flood.max")
|| keyEquals(key, key_length, "flood.max.unscoped")
|| keyEquals(key, key_length, "flood.max.advert");
return settings && (get ? !*arguments : set && *arguments);
}
size_t FleetCommand::encode(const LocalIdentity& publisher, const uint8_t* key,
uint32_t sequence, uint32_t expires,
const uint8_t* target, const char* command,
uint8_t* output, size_t capacity) {
if (!privateKeyAllowed(key) || !target || !output
|| !lifetimeAllowed(sequence, expires) || !commandAllowed(command)
|| zero(publisher.pub_key, PUB_KEY_SIZE)) return 0;
const size_t command_length = strlen(command);
const size_t unsigned_length = HeaderSize + command_length;
const size_t length = unsigned_length + SignatureSize;
if (capacity < length) return 0;
memcpy(output, "FMC1", 4);
write32(output + 4, sequence);
write32(output + 8, expires);
memcpy(output + 12, target, TargetSize);
output[28] = uint8_t(command_length);
memcpy(output + HeaderSize, command, command_length);
uint8_t message[SignedMessageCapacity];
const size_t message_length = signedMessage(key, output, unsigned_length, message);
publisher.sign(output + unsigned_length, message, int(message_length));
erase(message, sizeof(message));
return length;
}
bool FleetCommand::decode(const Identity& publisher, const uint8_t* key,
const uint8_t* payload, size_t length, uint32_t now,
const uint8_t* self_public_key, Decoded& output) {
memset(&output, 0, sizeof(output));
if (!privateKeyAllowed(key) || !payload || !self_public_key
|| zero(publisher.pub_key, PUB_KEY_SIZE) || zero(self_public_key, PUB_KEY_SIZE)
|| now < MinEpoch || length < HeaderSize + SignatureSize
|| length > MaxPayloadLength || memcmp(payload, "FMC1", 4)) return false;
const size_t command_length = payload[28];
if (!command_length || command_length > MaxCommandLength
|| length != HeaderSize + command_length + SignatureSize) return false;
const uint32_t sequence = read32(payload + 4), expires = read32(payload + 8);
if (!lifetimeAllowed(sequence, expires) || expires < now
|| (sequence > now && sequence - now > MaxClockLead)) return false;
if (!zero(payload + 12, TargetSize)) {
uint8_t target[TargetSize];
targetHash(self_public_key, target);
if (memcmp(target, payload + 12, TargetSize)) return false;
}
// Reject embedded NUL bytes, which would authorize a different text from
// the signed byte string when passed to the CLI parser.
if (memchr(payload + HeaderSize, 0, command_length)) return false;
char command[MaxCommandLength + 1];
memcpy(command, payload + HeaderSize, command_length);
command[command_length] = 0;
if (!commandAllowed(command)) return false;
const size_t unsigned_length = HeaderSize + command_length;
uint8_t message[SignedMessageCapacity];
const size_t message_length = signedMessage(key, payload, unsigned_length, message);
const bool valid = publisher.verify(payload + unsigned_length, message, int(message_length));
erase(message, sizeof(message));
if (!valid) return false;
output.sequence = sequence;
output.expires = expires;
memcpy(output.command, command, command_length + 1);
return true;
}
} // namespace mesh
+61
View File
@@ -0,0 +1,61 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "../Identity.h"
#ifndef MESH_ENABLE_FLEET_CONTROL
// Fixed 240 KiB STM32 images have no room for fleet control.
#if defined(STM32_PLATFORM)
#define MESH_ENABLE_FLEET_CONTROL 0
#else
#define MESH_ENABLE_FLEET_CONTROL 1
#endif
#endif
namespace mesh {
// Signed, private-channel fleet commands. The channel key supplies privacy;
// only the publisher's Ed25519 signature authorizes a command. Receivers store
// the public identity and never need the publisher's private identity.
class FleetCommand {
public:
static constexpr uint16_t DataType = 0xFF01;
static constexpr size_t KeySize = 16;
static constexpr size_t TargetSize = 16;
static constexpr size_t SignatureSize = 64;
static constexpr size_t MaxCommandLength = 72;
static constexpr size_t HeaderSize = 29;
static constexpr size_t MaxPayloadLength = 165;
static constexpr uint32_t MinEpoch = 1735689600UL; // 2025-01-01 UTC
static constexpr uint32_t MaxLifetime = 600;
static constexpr uint32_t MaxClockLead = 60;
struct Decoded {
uint32_t sequence;
uint32_t expires;
char command[MaxCommandLength + 1];
};
static bool privateKeyAllowed(const uint8_t* key);
// "all" becomes the reserved zero target; otherwise require one complete
// public key and derive the first 16 bytes of SHA-256, not a short node ID.
static bool parseTarget(const char* text, uint8_t* target);
static bool commandAllowed(const char* command);
// Return the exact envelope size, or zero on invalid input. The signature
// binds the domain, private channel key, complete header, and command bytes.
static size_t encode(const LocalIdentity& publisher, const uint8_t* key,
uint32_t sequence, uint32_t expires,
const uint8_t* target, const char* command,
uint8_t* output, size_t capacity);
// Accept an exact envelope only: group framing owns padding validation.
// On success the caller must durably reject an old/repeated sequence before
// any mutation, and defer execution until the receive stack has unwound.
static bool decode(const Identity& publisher, const uint8_t* key,
const uint8_t* payload, size_t length, uint32_t now,
const uint8_t* self_public_key, Decoded& output);
};
} // namespace mesh