Harden recovery authentication and signed OTA admission

This commit is contained in:
mikecarper committed 2026-10-10 01:25:08 -07:00
1 parent 74bc91bf69
commit 5fa06ea49b
40 files changed
+3631 -2107

No files matched your search

+86
View File
@@ -0,0 +1,86 @@
#include <array>
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
// The unknown-setting branches below are extracted verbatim from production.
// The hardware-dependent recognized-setting branches are outside this fixture.
using Fallback = void (*)(const char*, char*);
static void commonFallback(const char* command, char* reply) {
@COMMON_CONFIG@
(void)config;
if (false) {}
@COMMON_FALLBACK@
}
static void observerFallback(const char* command, char* reply) {
@COMMON_CONFIG@
(void)config;
if (false) {}
@OBSERVER_FALLBACK@
}
static std::string unknownCommand(bool observer, size_t command_length) {
const char* prefix = observer ? "set mqtt1." : "set repeat.";
assert(command_length >= strlen(prefix));
return std::string(prefix) + std::string(command_length - strlen(prefix), 'x');
}
template <size_t Capacity>
static void exact(Fallback fallback, const std::string& command) {
// Standalone arrays expose any past-end write to AddressSanitizer rather
// than hiding it inside an allocation which includes the path/canary.
std::array<char, Capacity> reply;
reply.fill(char(0x55));
fallback(command.c_str(), reply.data());
assert(strcmp(reply.data(), "unknown config") == 0);
for (size_t i = sizeof("unknown config"); i < reply.size(); ++i)
assert(reply[i] == char(0x55));
}
template <size_t Capacity>
static void adjacent(Fallback fallback, const std::string& command) {
struct Buffers {
uint8_t before[16];
char reply[Capacity];
uint8_t reply_path[64];
} buffers;
memset(&buffers, 0x55, sizeof(buffers));
fallback(command.c_str(), buffers.reply);
assert(strcmp(buffers.reply, "unknown config") == 0);
for (uint8_t value : buffers.before) assert(value == 0x55);
for (uint8_t value : buffers.reply_path) assert(value == 0x55);
for (size_t i = sizeof("unknown config"); i < sizeof(buffers.reply); ++i)
assert(buffers.reply[i] == char(0x55));
}
int main(int argc, char** argv) {
assert(argc == 3);
const bool observer = strcmp(argv[1], "observer") == 0;
const std::string scenario(argv[2]);
Fallback fallback = observer ? observerFallback : commonFallback;
if (scenario == "local") {
const auto command = unknownCommand(observer, 159);
exact<160>(fallback, command);
adjacent<160>(fallback, command);
} else if (scenario == "radio") {
const auto command = unknownCommand(observer, 179);
exact<179>(fallback, command);
adjacent<179>(fallback, command);
} else if (scenario == "minimum") {
const auto command = unknownCommand(observer, 179);
exact<sizeof("unknown config")>(fallback, command);
adjacent<sizeof("unknown config")>(fallback, command);
} else if (scenario == "lengths") {
for (size_t length = 16; length < 4096; ++length) {
const auto command = unknownCommand(observer, length);
exact<160>(fallback, command);
exact<179>(fallback, command);
exact<sizeof("unknown config")>(fallback, command);
adjacent<179>(fallback, command);
}
} else assert(false);
return 0;
}
+79
View File
@@ -0,0 +1,79 @@
#include <cassert>
#include <cstdio>
#include <cstring>
#include <vector>
#include <helpers/ota/FolderMotaStore.h>
#include <helpers/ota/MotaSeederProto.h>
#include <helpers/ota/OtaByteIO.h>
using namespace mesh::ota;
struct HostStream : Stream {
bool request=false, noise=false, bad_checksum=false, error=false;
bool stalled=false, short_write=false;
uint32_t byte_delay=0; int stale_reads=0, stale_at_request=0;
size_t response_pos=0; std::vector<uint8_t> response;
int available() override { return request ? int(response.size()-response_pos) : (noise ? 3 : 0); }
int read() override {
if (!request) {
if (noise && stale_reads<100) { ++stale_reads; return 0x5a; }
return -1;
}
if (stalled || response_pos==response.size()) return -1;
g_mock_millis+=byte_delay;
return response[response_pos++];
}
int peek() override { return -1; }
void flush() override { assert(false); }
size_t write(uint8_t) override { assert(false); return 0; }
size_t write(const uint8_t* data, size_t size) override {
if(short_write) return size-1;
assert(size>=4 && data[0]==MOTA_SEEDER_REQ_MAGIC0 && data[1]==MOTA_SEEDER_REQ_MAGIC1);
uint8_t op=data[2], xor_sum=0;
for(size_t i=2;i<size-1;++i)xor_sum^=data[i];
assert(xor_sum==data[size-1]);
stale_at_request=stale_reads; request=true; response_pos=0;
response={MOTA_SEEDER_RSP_MAGIC0,MOTA_SEEDER_RSP_MAGIC1,op,uint8_t(error ? 1 : MS_STATUS_OK)};
if(!error && op==MS_OP_SREAD) {
uint16_t wanted=uint16_t(data[11]) | (uint16_t(data[12])<<8);
for(uint16_t i=0;i<wanted;++i)response.push_back(uint8_t(i));
} else if(!error && op==MS_OP_STAT) {
response.push_back(1); uint8_t length[4]; wr_u32le(length,128);
response.insert(response.end(),length,length+4);
}
xor_sum=0; for(uint8_t value:response)xor_sum^=value;
response.push_back(bad_checksum ? uint8_t(xor_sum^1) : xor_sum);
return size;
}
};
int main() {
uint8_t mid[4]={1,2,3,4}, data[32]={}, output[32]={};
for(uint32_t initial : {0u,UINT32_MAX-10u}) {
HostStream slow; slow.byte_delay=7; g_mock_millis=initial;
FolderMotaStore store(slow,MotaStreamWritePolicy::NoFlush,20); store.set_mid(mid);
assert(!store.reopen());
assert(uint32_t(g_mock_millis-initial)<=27); // last read may cross deadline once
assert(store.staged_size()==0);
}
HostStream stale; stale.noise=true; g_mock_millis=0;
FolderMotaStore bounded(stale,MotaStreamWritePolicy::NoFlush,20); bounded.set_mid(mid);
assert(bounded.begin(128)); assert(stale.stale_at_request==3);
assert(bounded.staged_size()==128);
HostStream good; FolderMotaStore valid(good,MotaStreamWritePolicy::NoFlush,3000); valid.set_mid(mid);
assert(valid.begin(128)); assert(valid.write(4,data,sizeof(data)));
assert(valid.read(0,output,sizeof(output)));
for(size_t i=0;i<sizeof(output);++i)assert(output[i]==uint8_t(i));
assert(valid.finalize() && valid.reopen() && valid.staged_size()==128);
// Keep deliberate SlowFi tolerance: a response arriving within the overall
// three-second budget is accepted without reducing the configured timeout.
HostStream slow_valid; slow_valid.byte_delay=250; g_mock_millis=0;
FolderMotaStore tolerant(slow_valid,MotaStreamWritePolicy::NoFlush,3000);
assert(tolerant.reopen()); assert(g_mock_millis==2500);
for(int scenario=0;scenario<4;++scenario) {
HostStream bad;
bad.stalled=scenario==0; bad.bad_checksum=scenario==1;
bad.error=scenario==2; bad.short_write=scenario==3;
g_mock_millis=0; FolderMotaStore fail(bad,MotaStreamWritePolicy::NoFlush,20);
assert(!fail.begin(128) && fail.staged_size()==0);
assert(g_mock_millis<=20);
}
puts("Folder mOTA deadline regression checks passed");
}
+71
View File
@@ -0,0 +1,71 @@
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <initializer_list>
#define MQTT_DEBUG_PRINTLN(...) ((void)0)
static constexpr int ESP_OK=0;
using esp_err_t=int;
const char* esp_err_to_name(int) { return "mock"; }
uint32_t millis() { return 123; }
const uint8_t rootca_bytes[16]={};
const uint8_t* rootca_crt_bundle_start=nullptr;
const uint8_t* rootca_crt_bundle_end=nullptr;
static bool s_ca_bundle_loaded=false;
struct Client {
int credentials=0, bundles=0, attaches=0; std::string server;
void setServer(const char* uri) { server=uri; }
void setCACertBundle(const uint8_t*, size_t) { ++bundles; }
void attachArduinoCACertBundle(bool value) { assert(value); ++attaches; }
void setCredentials(const char*, const char*) { ++credentials; }
};
struct MQTTBridge {
struct MQTTSlot {
char host[100]="broker.example", broker_uri[150]={};
char username[40]="user", password[40]="secret", audience[40]={};
char token[80]="signed-jwt"; char* auth_token=token;
uint16_t port=8883; Client* client=nullptr;
bool initial_connect_done=true; uint32_t last_reconnect_attempt=0;
} _slots[2];
Client clients[2]; int connects=0, tokens=0;
const char* _jwt_username="jwt";
MQTTBridge() { for (int i=0;i<2;++i) _slots[i].client=&clients[i]; }
bool createSlotAuthToken(int) { ++tokens; return true; }
int reconnectSlotClient(int) { ++connects; return ESP_OK; }
bool setupCustom(int);
};
@METHOD@
int main() {
for (const char* host : {"mqtts://broker", "wss://broker/path", "broker"}) {
for (bool jwt : {false, true}) {
MQTTBridge bridge; auto& slot=bridge._slots[0];
strcpy(slot.host, host); if(jwt) strcpy(slot.audience, "fleet-audience");
assert(!bridge.setupCustom(0));
assert(!slot.initial_connect_done && slot.last_reconnect_attempt==123);
assert(bridge.connects==0 && bridge.tokens==0 && bridge.clients[0].credentials==0);
}
}
// Port 443 infers WSS and needs verification too.
MQTTBridge wss; wss._slots[0].port=443; assert(!wss.setupCustom(0)); assert(wss.connects==0);
// Explicit plaintext is an operator choice; never silently downgrade TLS.
for (const char* host : {"mqtt://broker", "ws://broker/path", "broker"}) {
MQTTBridge plain; strcpy(plain._slots[0].host, host); plain._slots[0].port=1883;
assert(plain.setupCustom(0) && plain.connects==1 && plain.clients[0].credentials==1);
assert(plain.clients[0].bundles==0);
}
rootca_crt_bundle_start=rootca_bytes; rootca_crt_bundle_end=rootca_bytes+sizeof(rootca_bytes);
MQTTBridge trusted;
#ifdef PORTABLE_MQTT_OBSERVER
assert(!trusted.setupCustom(0) && trusted.connects==0); // bundle deliberately unlinked
#else
assert(trusted.setupCustom(0));
assert(s_ca_bundle_loaded && trusted.clients[0].bundles==1 && trusted.clients[0].credentials==1);
strcpy(trusted._slots[1].audience, "fleet-audience");
assert(trusted.setupCustom(1));
assert(trusted.clients[1].bundles==0 && trusted.clients[1].attaches==1);
assert(trusted.tokens==1 && trusted.connects==2);
assert(trusted.clients[0].server=="mqtts://broker.example:8883");
#endif
puts("MQTT custom TLS security regression checks passed");
}
+4 -2
View File
@@ -98,7 +98,8 @@ static void filtered_catalog_remains_queryable(int scenario, bool automatic) {
}
}
for (const auto& message : filtered) client.on_message(message.data(), message.size());
assert(client.catalogCount() == (scenario == 4 ? 1 : scenario == 6 ? 0 : 15));
assert(client.catalogCount() == (scenario == 4 ? 1 : scenario == 6 ? 0 :
automatic ? 15 : OTA_INLINE_CATALOG));
if (scenario == 8) {
// Passive rows arriving before a beacon must not confer completeness on its new digest.
client.on_message(wire, encode_adv(wire, sizeof(wire), adv));
@@ -114,7 +115,7 @@ static void filtered_catalog_remains_queryable(int scenario, bool automatic) {
QueryMsg recovery{};
assert(decode_query(from_client[0].data(), from_client[0].size(), recovery));
assert(recovery.filter_target == 0);
assert(recovery.want_fragments == (scenario == 4 ? 1u : scenario == 5 ? 6u : scenario == 8 ? 0u : 7u));
assert(recovery.want_fragments == (scenario == 4 ? 1u : scenario == 5 && automatic ? 6u : scenario == 8 ? 0u : 7u));
from_server.clear();
server.on_message(from_client[0].data(), from_client[0].size());
for (const auto& message : from_server) client.on_message(message.data(), message.size());
@@ -153,6 +154,7 @@ int main(int argc, char** argv) {
assert(!row(manager, 2));
assert(manager.sourceCount() == OTA_MAX_SOURCES);
} else if (scenario == 1) {
manager.queryAll(); // large catalogs are explicit operator browse policy
for (unsigned i = 1; i <= OTA_MAX_CATALOG; ++i) {
manager.set_clock(old + i * 100);
have(manager, 1, i);
+19
View File
@@ -0,0 +1,19 @@
#include <Identity.h>
#include <openssl/evp.h>
// Real Ed25519 behind the firmware Identity API for host OTA-policy fixtures.
namespace mesh {
unsigned signature_checks = 0;
bool Identity::verify(const uint8_t* signature, const uint8_t* message, int length) const {
++signature_checks;
if (!signature || !message || length < 0) return false;
EVP_PKEY* public_key = EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr,
pub_key, sizeof(pub_key));
EVP_MD_CTX* context = EVP_MD_CTX_new();
const bool valid = public_key && context &&
EVP_DigestVerifyInit(context, nullptr, nullptr, nullptr, public_key) == 1 &&
EVP_DigestVerify(context, signature, SIGNATURE_SIZE, message, length) == 1;
EVP_MD_CTX_free(context); EVP_PKEY_free(public_key);
return valid;
}
}
+394
View File
@@ -0,0 +1,394 @@
#include <helpers/ota/OtaManager.h>
#include <helpers/ota/OtaManifestPolicy.h>
#include <helpers/ota/OtaByteIO.h>
#include <helpers/ota/Multihash.h>
#include "test_ota/mota_vectors.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <openssl/evp.h>
namespace mesh { extern unsigned signature_checks; }
using namespace mesh::ota;
static std::array<void*, 64> allocations{};
static std::array<size_t, 64> allocation_sizes{};
static size_t allocated = 0, peak = 0;
extern "C" void* __real_malloc(size_t);
extern "C" void __real_free(void*);
extern "C" void* __wrap_malloc(size_t size) {
void* result = __real_malloc(size);
if (result) {
const auto free_slot = std::find(allocations.begin(), allocations.end(), nullptr);
assert(free_slot != allocations.end());
const size_t index = free_slot - allocations.begin();
allocations[index] = result; allocation_sizes[index] = size;
allocated += size; peak = std::max(peak, allocated);
}
return result;
}
extern "C" void __wrap_free(void* result) {
const auto found = std::find(allocations.begin(), allocations.end(), result);
if (result && found != allocations.end()) {
const size_t index = found - allocations.begin();
allocated -= allocation_sizes[index]; allocations[index] = nullptr;
}
__real_free(result);
}
struct Wire {
bool admit = true;
unsigned attempts = 0;
std::vector<std::vector<uint8_t>> messages;
static bool send(void* raw, const uint8_t* message, uint16_t length, bool) {
auto& self = *static_cast<Wire*>(raw);
++self.attempts;
if (!self.admit) return false;
self.messages.emplace_back(message, message + length);
return true;
}
};
struct Store : OtaStoreRam<4096> {
unsigned plans = 0, begins = 0, writes = 0;
bool plan_layout(bool, uint32_t, uint32_t, uint32_t, bool) override { ++plans; return true; }
bool begin(uint32_t size) override { ++begins; return OtaStoreRam<4096>::begin(size); }
bool write(uint32_t offset, const uint8_t* bytes, uint32_t size) override {
++writes; return OtaStoreRam<4096>::write(offset, bytes, size);
}
};
struct TrustedPolicy {
SignerAllowlist allow;
unsigned calls = 0;
static bool admit(void* raw, const MotaManifest& manifest) {
auto& policy = *static_cast<TrustedPolicy*>(raw);
++policy.calls;
return ota_manifest_trusted(manifest, policy.allow);
}
};
static std::vector<uint8_t> signed_manifest(TrustedPolicy& policy) {
std::vector<uint8_t> result(SIM_MOTA + 8, SIM_MOTA + 8 + MOTA_MFL);
uint8_t secret[32];
for (unsigned i = 0; i < sizeof(secret); ++i) secret[i] = uint8_t(i + 1);
EVP_PKEY* key = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, secret, sizeof(secret));
assert(key);
size_t public_size = 32;
assert(EVP_PKEY_get_raw_public_key(key, result.data() + 97, &public_size) == 1);
assert(public_size == 32 && policy.allow.add(result.data() + 97));
EVP_MD_CTX* context = EVP_MD_CTX_new();
size_t signature_size = 64;
assert(context && EVP_DigestSignInit(context, nullptr, nullptr, nullptr, key) == 1);
assert(EVP_DigestSign(context, result.data() + 129, &signature_size,
result.data(), MOTA_SIGNED_LEN) == 1);
assert(signature_size == 64);
EVP_MD_CTX_free(context); EVP_PKEY_free(key);
return result;
}
static void deliver_manifest(OtaManager& manager, const uint8_t mid[4], const uint8_t* bytes) {
for (unsigned fragment = 0; fragment < 2; ++fragment) {
ManifestMsg message{};
memcpy(message.manifest_id, mid, 4);
message.frag_idx = fragment; message.frag_total = 2;
message.bytes = bytes + fragment * OTA_MF_FRAG;
message.len = fragment ? MOTA_MFL - OTA_MF_FRAG : OTA_MF_FRAG;
uint8_t wire[256];
manager.on_message(wire, encode_manifest(wire, sizeof(wire), message));
}
}
static void have(OtaManager& manager, const MotaManifest& manifest, uint32_t source = 1) {
uint8_t row[OTA_HAVE_ROW_BYTES]{};
memcpy(row, manifest.merkle_root, 4);
wr_u32le(row + 4, manifest.target_id); wr_u32le(row + 8, manifest.fw_version);
row[12] = manifest.codec_id; row[13] = manifest.flags; wr_u16le(row + 14, 1);
HaveMsg message{};
wr_u32le(message.seeder_id, source); message.frag_total = 1;
message.n_rows = 1; message.rows = row;
uint8_t wire[256];
manager.on_message(wire, encode_have(wire, sizeof(wire), message));
}
static MotaManifest parse(const std::vector<uint8_t>& bytes) {
MotaManifest manifest{};
assert(mota_parse_manifest(bytes.data(), bytes.size(), manifest));
return manifest;
}
static void retain_existing(Store& store) {
assert(store.begin(SIM_MOTA_LEN) && store.write(0, SIM_MOTA, SIM_MOTA_LEN));
store.plans = store.begins = store.writes = 0;
}
static void intact(const Store& store) {
assert(store.plans == 0 && store.begins == 0 && store.writes == 0);
assert(store.staged_size() == SIM_MOTA_LEN);
assert(!memcmp(store.data(), SIM_MOTA, SIM_MOTA_LEN));
}
static void signature_admission() {
TrustedPolicy policy;
const auto good = signed_manifest(policy);
const auto valid = parse(good);
assert(ota_manifest_trusted(valid, policy.allow));
for (unsigned scenario = 0; scenario < 5; ++scenario) {
auto bytes = good;
TrustedPolicy configured = policy;
if (scenario == 1) configured.allow.clear();
if (scenario == 2) bytes[129] ^= 1; // signature corruption
if (scenario == 3) bytes[57] ^= 1; // signed hardware identity corruption
if (scenario == 4) bytes[1] &= uint8_t(~MFLAG_SIGNED);
const auto manifest = parse(bytes);
Store store; retain_existing(store);
Wire wire; OtaManager manager;
manager.begin(valid.target_id, Wire::send, &wire);
manager.set_fetch_store(&store);
manager.set_autofetch(OtaManager::AUTOFETCH_SIGNED);
if (scenario != 0) manager.set_manifest_admission(TrustedPolicy::admit, &configured);
have(manager, valid);
assert(manager.fetchState() == OtaManager::WANT_MANIFEST);
const unsigned checks = mesh::signature_checks;
deliver_manifest(manager, valid.merkle_root, bytes.data());
assert(manager.fetchState() == OtaManager::FAILED);
assert(manager.fetchError() == OtaManager::FETCH_ERROR_MANIFEST);
intact(store);
if (scenario == 0 || scenario == 1 || scenario == 4) assert(mesh::signature_checks == checks);
else assert(mesh::signature_checks == checks + 1);
if (scenario != 4) assert(!ota_manifest_trusted(manifest, configured.allow) || scenario == 0);
}
// Approval is unsigned local authorization and must not survive peer ingress.
auto approved = good;
memset(approved.data() + 193, 0xA5, 4);
Store store; retain_existing(store); Wire wire; OtaManager manager;
manager.begin(valid.target_id, Wire::send, &wire);
manager.set_fetch_store(&store);
manager.set_autofetch(OtaManager::AUTOFETCH_SIGNED);
manager.set_manifest_admission(TrustedPolicy::admit, &policy);
have(manager, valid);
deliver_manifest(manager, valid.merkle_root, approved.data());
assert(manager.fetchState() == OtaManager::FETCHING);
assert(store.plans == 1 && store.begins == 1);
MotaManifest staged;
assert(mota_parse_manifest(store.data() + 8, MOTA_MFL, staged));
assert(ota_manifest_trusted(staged, policy.allow));
assert(!staged.is_approved());
// NOR flash can only clear bits. The unapproved marker must stay erased so
// the separate authorized local installer can program APPROVAL_YES later.
for (unsigned i = 0; i < 4; ++i) {
assert(staged.approval[i] == 0xFF);
assert((staged.approval[i] & APPROVAL_YES[i]) == APPROVAL_YES[i]);
}
// Automatic reboot resume has the same signature gate; manual capture is
// permitted independently and never grants automatic install approval.
const uint8_t corrupt_signature = store.data()[8 + 129] ^ 1u;
assert(store.write(8 + 129, &corrupt_signature, 1));
manager.reset_session();
assert(!manager.resumeStaged(nullptr));
assert(manager.pull(valid.merkle_root, valid.target_id) == OtaManager::PULL_RESUMED);
assert(manager.fetchState() == OtaManager::VERIFYING_STAGED);
}
static void failure_cooldown(bool rollover) {
TrustedPolicy policy;
auto bytes = signed_manifest(policy);
bytes[129] ^= 1;
const auto manifest = parse(bytes);
Store store; retain_existing(store); Wire wire; OtaManager manager;
manager.begin(manifest.target_id, Wire::send, &wire);
manager.set_fetch_store(&store);
manager.set_autofetch(OtaManager::AUTOFETCH_SIGNED);
manager.set_manifest_admission(TrustedPolicy::admit, &policy);
uint32_t now = rollover ? UINT32_MAX - 30000u : 100u;
uint32_t delay = OTA_AUTOFETCH_FAILURE_BACKOFF_MS;
for (unsigned attempt = 0; attempt < 8; ++attempt) {
manager.set_clock(now);
have(manager, manifest);
assert(manager.fetchState() == OtaManager::WANT_MANIFEST);
deliver_manifest(manager, manifest.merkle_root, bytes.data());
assert(manager.fetchState() == OtaManager::FAILED);
intact(store);
const unsigned admitted = policy.calls;
// Neither a repeated source nor rotating a forged MID bypasses cooldown.
auto rotated = bytes; rotated[20] ^= 0x42;
const auto other = parse(rotated);
for (unsigned packet = 0; packet < 100; ++packet) {
have(manager, packet % 2 ? other : manifest, packet + 2);
assert(manager.fetchState() == OtaManager::FAILED);
}
assert(policy.calls == admitted);
manager.set_clock(now + delay - 1u);
have(manager, manifest);
assert(manager.fetchState() == OtaManager::FAILED);
now += delay;
if (delay > OTA_AUTOFETCH_FAILURE_MAX_BACKOFF_MS / 2u) delay = OTA_AUTOFETCH_FAILURE_MAX_BACKOFF_MS;
else delay *= 2u;
}
const unsigned admitted = policy.calls;
// The authorized manual pull works during cooldown, without silently
// altering the signed-only automatic policy or installation trust gate.
auto manual_bytes = bytes; manual_bytes[20] ^= 0x42;
const auto manual_manifest = parse(manual_bytes);
assert(manager.pull(manual_manifest.merkle_root, manual_manifest.target_id) == OtaManager::PULL_STARTED);
deliver_manifest(manager, manual_manifest.merkle_root, manual_bytes.data());
assert(manager.fetchState() == OtaManager::FETCHING && policy.calls == admitted);
MotaManifest staged;
assert(mota_parse_manifest(store.data() + 8, MOTA_MFL, staged));
assert(!ota_manifest_trusted(staged, policy.allow));
}
static std::vector<uint8_t> container(uint32_t blocks) {
const uint32_t block_size = 128, payload_size = blocks * block_size;
const uint32_t size = 8 + MOTA_MFL + blocks * 4 + payload_size + 5;
std::vector<uint8_t> image(size, 0);
memcpy(image.data(), MOTA_MAGIC, 4); wr_u32le(image.data() + 4, size);
uint8_t* manifest = image.data() + 8;
memcpy(manifest, SIM_MOTA + 8, MOTA_MFL);
manifest[1] = MFLAG_FULL; manifest[2] = HASH_ALGO_SHA256;
manifest[19] = 7;
wr_u32le(manifest + 11, payload_size); wr_u32le(manifest + 15, payload_size);
// codec is offset56 in the fixed manifest.
manifest[56] = CODEC_FULL;
uint8_t* leaves = manifest + MOTA_MFL;
uint8_t* payload = leaves + blocks * 4;
for (uint32_t i = 0; i < payload_size; ++i) payload[i] = uint8_t(i * 17u);
for (uint32_t i = 0; i < blocks; ++i) merkle_leaf(leaves + i * 4, payload + i * block_size, block_size);
merkle_root(manifest + 20, leaves, blocks);
memcpy(image.data() + size - 5, MOTA_TRAILER, 5);
MotaManifest parsed; assert(mota_parse(image.data(), size, parsed));
assert(parsed.block_count == blocks);
return image;
}
static bool leaves(OtaManager& manager, const uint8_t* mid, uint16_t mask, OtaReplyRoute route = {}) {
GetLeavesMsg request{};
memcpy(request.manifest_id, mid, 4); request.want_mask = mask;
uint8_t wire[32];
return manager.on_message(wire, encode_get_leaves(wire, sizeof(wire), request), route);
}
static bool route_valid(void* current, const OtaReplyRoute& route) {
return route == *static_cast<OtaReplyRoute*>(current);
}
static void leaf_pacing(bool rollover) {
const auto image = container(OTA_DIFF_MAX_BLOCKS);
MotaManifest manifest; assert(mota_parse(image.data(), image.size(), manifest));
Wire wire; OtaManager manager;
manager.begin(1, Wire::send, &wire); assert(manager.serve(image.data(), image.size()));
uint32_t now = rollover ? UINT32_MAX - 50u : 100u;
manager.set_clock(now);
OtaReplyRoute route; route.profile = 1; route.generation = 7;
assert(leaves(manager, manifest.merkle_root, 0xFFFF, route));
assert(manager.pendingManifestJobs() == 1 && wire.messages.empty());
for (unsigned i = 0; i < 100; ++i) assert(leaves(manager, manifest.merkle_root, 0xFFFF, route));
assert(manager.pendingManifestJobs() == 1 && wire.messages.empty());
manager.serviceEgress(route_valid, &route);
assert(wire.attempts == 0); // turnaround deadline has not expired
now += 100;
manager.set_clock(now); wire.admit = false;
for (unsigned i = 0; i < 100; ++i) manager.serviceEgress(route_valid, &route);
assert(wire.messages.empty() && manager.pendingManifestJobs() == 1);
wire.admit = true;
for (unsigned fragment = 0; fragment < 16; ++fragment) {
const unsigned before = wire.messages.size();
manager.serviceEgress(route_valid, &route);
assert(wire.messages.size() == before + 1);
LeavesMsg reply;
assert(decode_leaves(wire.messages.back().data(), wire.messages.back().size(), reply));
assert(reply.frag_idx == fragment && reply.frag_total == 16);
assert(!memcmp(reply.bytes, manifest.leaves + fragment * OTA_LEAVES_FRAG, reply.len));
if (fragment < 15) {
assert(leaves(manager, manifest.merkle_root, 0xFFFF, route));
manager.serviceEgress(route_valid, &route);
assert(wire.messages.size() == before + 1); // duplicates never reset/send emitted bits
}
now += 100; manager.set_clock(now);
}
assert(manager.pendingManifestJobs() == 0 && wire.messages.size() == 16);
// Retry exactly the requested holes, without synchronous transmission.
assert(leaves(manager, manifest.merkle_root, 0x8001, route));
for (unsigned i = 0; i < 2; ++i) {
now += 100; manager.set_clock(now); manager.serviceEgress(route_valid, &route);
LeavesMsg reply;
assert(decode_leaves(wire.messages.back().data(), wire.messages.back().size(), reply));
assert(reply.frag_idx == (i ? 15 : 0));
}
assert(manager.pendingManifestJobs() == 0);
// Closed temporary radio generations and explicit teardown cannot retain
// stale queued work or reply on another profile.
assert(leaves(manager, manifest.merkle_root, 1, route));
++route.generation;
const auto before = wire.messages.size();
manager.serviceEgress(route_valid, &route);
assert(manager.pendingManifestJobs() == 0 && wire.messages.size() == before);
assert(leaves(manager, manifest.merkle_root, 1, route));
manager.clearPendingEgress();
assert(manager.pendingManifestJobs() == 0);
assert(!leaves(manager, manifest.merkle_root, 0, route));
const auto oversized = container(OTA_DIFF_MAX_BLOCKS + 1);
assert(manager.serve(oversized.data(), oversized.size()));
MotaManifest large; assert(mota_parse(oversized.data(), oversized.size(), large));
assert(!leaves(manager, large.merkle_root, 0xFFFF, route));
assert(manager.pendingManifestJobs() == 0);
}
static void catalog(OtaManager& manager, uint32_t first, uint32_t last) {
for (uint32_t id = first; id < last; ++id) {
uint8_t row[OTA_HAVE_ROW_BYTES]{};
wr_u32le(row, id + 1); wr_u32le(row + 4, 123);
row[12] = CODEC_FULL; row[13] = MFLAG_FULL;
HaveMsg message{}; wr_u32le(message.seeder_id, 42);
message.frag_total = 1; message.n_rows = 1; message.rows = row;
uint8_t wire[256];
manager.on_message(wire, encode_have(wire, sizeof(wire), message));
}
}
static void catalog_budget() {
assert(allocated == 0);
{
OtaManager manager; manager.begin(123, nullptr, nullptr);
catalog(manager, 0, 255);
assert(manager.catalogCount() == OTA_INLINE_CATALOG && allocated == 0);
manager.queryAll(); catalog(manager, 0, 255);
assert(manager.catalogCount() == OTA_MAX_CATALOG);
assert(allocated == sizeof(OtaManager::CatRow) * OTA_MAX_CATALOG && allocated <= 16384);
AdvMsg withdrawal{}; wr_u32le(withdrawal.seeder_id, 42);
uint8_t wire[64]; manager.on_message(wire, encode_adv(wire, sizeof(wire), withdrawal));
assert(manager.catalogCount() == 0 && allocated == 0);
catalog(manager, 0, 255);
assert(allocated != 0);
manager.begin(123, nullptr, nullptr);
assert(manager.catalogCount() == 0 && allocated == 0);
catalog(manager, 0, 255);
assert(manager.catalogCount() == OTA_INLINE_CATALOG && allocated == 0);
}
assert(allocated == 0);
}
static void proof_noise() {
MotaManifest manifest; assert(mota_parse(SIM_MOTA_1K, SIM_MOTA_1K_LEN, manifest));
Store store; Wire wire; OtaManager manager;
manager.begin(manifest.target_id, Wire::send, &wire);
manager.set_fetch_store(&store); manager.set_clock(100);
manager.set_wire_v2_enabled(false);
assert(manager.pull(manifest.merkle_root, manifest.target_id) == OtaManager::PULL_STARTED);
deliver_manifest(manager, manifest.merkle_root, manifest.manifest_start);
uint8_t packet[256];
const uint32_t size = manifest.block_size();
for (uint32_t offset = 0; offset < size; offset += OTA_FRAG_DATA) {
DataMsg data{}; memcpy(data.manifest_id, manifest.merkle_root, 4);
data.block_idx = 0; data.frag_off = offset;
data.data = manifest.payload + offset; data.data_len = std::min(size - offset, uint32_t(OTA_FRAG_DATA));
manager.on_message(packet, encode_data(packet, sizeof(packet), data));
}
std::array<uint8_t, 128> siblings{};
const uint8_t count = merkle_gen_proof(manifest.leaves, manifest.block_count, 0, nullptr, siblings.data());
assert(count > 0);
ProofMsg proof{}; memcpy(proof.manifest_id, manifest.merkle_root, 4);
proof.block_idx = 0; proof.n_proof = count; proof.proof = siblings.data();
siblings[0] ^= 1;
const unsigned before = wire.messages.size();
for (unsigned i = 0; i < 100; ++i) manager.on_message(packet, encode_proof(packet, sizeof(packet), proof));
assert(manager.blocksHave() == 0 && wire.messages.size() == before);
siblings[0] ^= 1;
manager.on_message(packet, encode_proof(packet, sizeof(packet), proof));
assert(manager.blocksHave() == 1); // forged proof did not erase valid DATA
}
int main() {
signature_admission();
failure_cooldown(false); failure_cooldown(true);
leaf_pacing(false); leaf_pacing(true);
catalog_budget(); proof_noise();
assert(allocated == 0);
puts("PASS: authenticated automatic staging, bounded catalog, paced leaves and proof-noise recovery");
}
+104
View File
@@ -0,0 +1,104 @@
#include <cassert>
#include <cstdio>
#include <cstring>
#include <map>
#include <string>
#include <ArduinoJson.h>
struct String : std::string {
using std::string::string;
String(std::string value) : std::string(std::move(value)) {}
int indexOf(const char* value) const { auto pos=find(value); return pos==npos ? -1 : int(pos); }
String substring(int begin, int end) const { return substr(begin, end-begin); }
};
static uint32_t now_ms=10, random_word=0x12345678;
uint32_t millis() { return now_ms; }
uint32_t esp_random() { return ++random_word; }
static constexpr uint32_t WEBCONFIG_SESSION_TTL_MS=10000;
struct NodeSnapshot { char admin_password[16] = {}; };
struct Callback {
NodeSnapshot node;
void getNodeSnapshot(NodeSnapshot& result) { result=node; }
};
struct WCLock { explicit WCLock(int) {} };
struct WiFiMock { int softAPIP() const { return 4; } } WiFi;
struct Client { int local_ip=4; int localIP() const { return local_ip; } };
struct Header { String cookies; const String& value() const { return cookies; } };
struct AsyncWebServerResponse {
int status; std::map<std::string, std::string> headers;
void addHeader(const char* key, const char* value) { headers[key]=value; }
};
struct AsyncWebServerRequest {
Client socket; bool has_client=true;
Header header; std::string body; void* _tempObject=nullptr;
int status=0; AsyncWebServerResponse response{};
Client* client() { return has_client ? &socket : nullptr; }
bool hasHeader(const char*) const { return !header.cookies.empty(); }
Header* getHeader(const char*) { return &header; }
void send(int code, const char* =nullptr, const char* =nullptr) { status=code; }
AsyncWebServerResponse* beginResponse(int code, const char*, const char*) { response.status=code; return &response; }
void send(AsyncWebServerResponse* value) { status=value->status; }
void password(const char* value) { body=std::string("{\"password\":\"")+value+"\"}"; _tempObject=body.data(); }
};
struct WebConfigServer {
enum { MODE_OFF, MODE_SETUP, MODE_LAN };
int _mode=MODE_SETUP, _mux=0;
char _wifi_ssid[33]="SavedNet", _session_token[33] = {};
bool _initial_setup=false, config_accepted=false;
uint32_t _last_activity=0, _session_last_seen=0, _login_lock_until=0;
int _login_fails=0; Callback callback; Callback* _cb=&callback;
WebConfigServer() { strcpy(callback.node.admin_password, "existing-secret"); }
bool checkAuth(AsyncWebServerRequest*);
void handleLogin(AsyncWebServerRequest*);
void handleLogout(AsyncWebServerRequest*);
void checkConfigPost(AsyncWebServerRequest*);
};
@METHODS@
int main() {
WebConfigServer portal; AsyncWebServerRequest attacker;
attacker.body="{\"set\":{\"password\":\"attacker\",\"wifi.ssid\":\"EvilNet\"}}";
attacker._tempObject=attacker.body.data();
assert(!portal.checkAuth(&attacker));
portal.checkConfigPost(&attacker);
assert(attacker.status==401 && !portal.config_accepted);
attacker.password("wrong"); portal.handleLogin(&attacker);
assert(attacker.status==401 && portal._session_token[0]==0);
AsyncWebServerRequest admin; admin.password("existing-secret");
portal.handleLogin(&admin); assert(admin.status==200);
assert(strlen(portal._session_token)==32);
assert(admin.response.headers["Set-Cookie"].find("HttpOnly; SameSite=Lax")!=std::string::npos);
admin.header.cookies=std::string("wcs=")+portal._session_token;
assert(portal.checkAuth(&admin)); portal.checkConfigPost(&admin);
assert(portal.config_accepted);
std::string valid_token=portal._session_token;
portal.handleLogout(&attacker);
assert(attacker.status==401 && valid_token==portal._session_token);
admin.socket.local_ip=9;
assert(!portal.checkAuth(&admin));
admin.password("existing-secret"); portal.handleLogin(&admin);
assert(admin.status==401); // recovery must not authorize a recovered STA/LAN
admin.socket.local_ip=4;
admin.has_client=false; assert(!portal.checkAuth(&admin)); admin.has_client=true;
now_ms+=WEBCONFIG_SESSION_TTL_MS+1; assert(!portal.checkAuth(&admin));
admin.password("existing-secret"); portal.handleLogin(&admin); assert(admin.status==200);
admin.header.cookies=std::string("wcs=")+portal._session_token;
portal.handleLogout(&admin); assert(admin.status==200 && portal._session_token[0]==0);
assert(!portal.checkAuth(&admin));
portal._mode=WebConfigServer::MODE_LAN; admin.socket.local_ip=9;
admin.password("existing-secret"); portal.handleLogin(&admin); assert(admin.status==200);
admin.header.cookies=std::string("wcs=")+portal._session_token; assert(portal.checkAuth(&admin));
portal._mode=WebConfigServer::MODE_OFF; assert(!portal.checkAuth(&admin));
portal.handleLogin(&admin); assert(admin.status==503);
// First provisioning remains possible and retains its AP-only privilege
// through a save batch that changes SSID before the confirmation arrives.
portal._mode=WebConfigServer::MODE_SETUP; portal._wifi_ssid[0]=0;
portal._initial_setup=true; assert(portal.checkAuth(&attacker));
strcpy(portal._wifi_ssid, "ProvisionedNet"); assert(portal.checkAuth(&attacker));
portal.handleLogin(&attacker); assert(attacker.status==200);
attacker.socket.local_ip=9; assert(!portal.checkAuth(&attacker));
portal.handleLogin(&attacker); assert(attacker.status==401); attacker.socket.local_ip=4;
// Companion images deliberately have no administrator password or CLI
// password management. Keep that explicit no-password deployment policy.
portal._initial_setup=false; portal.callback.node.admin_password[0]=0;
assert(portal.checkAuth(&attacker)); portal.handleLogin(&attacker); assert(attacker.status==200);
puts("WebConfig recovery authentication regression checks passed");
}