Harden signed SD and bootloader OTA
This commit is contained in:
1 parent
3d78d9c846
commit
d9f5dfa8a2
29 files changed
+1846
-408
No files matched your search
+1
-1
@@ -415,7 +415,7 @@ void __attribute__((noinline)) Mesh::serviceLoopMaintenance() {
|
||||
&& !oc.manager.fetched_is_bootloader()) {
|
||||
_ota_autoinstall_tried = true;
|
||||
char msg[100];
|
||||
oc.apply_fetched(msg); // arms + sets apply_pending only if signed & allowlisted; refused otherwise
|
||||
oc.apply_fetched_trusted_auto(msg); // signed/trusted and strictly newer; manual install may override
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -107,7 +107,9 @@ void WiFiOtaSeeder::loop() {
|
||||
seeder_client.remoteIP().toString().c_str());
|
||||
context.set_folder_dest(&folder_store, link_info);
|
||||
if (context.manager.fetchState() == OtaManager::PAUSED) {
|
||||
context.manager.resumeStaged(nullptr);
|
||||
// This continues the active host-selected MID; it is not a boot-time
|
||||
// automatic adoption governed by application autofetch policy.
|
||||
context.manager.resumeStaged(context.manager.fetchManifestId());
|
||||
}
|
||||
context.manager.announce();
|
||||
Serial.printf("OTA seeder client connected (%s)\n", link_info);
|
||||
|
||||
@@ -462,7 +462,9 @@ bool ota_apply_detools_mota(const uint8_t*, uint32_t, const SignerAllowlist&, Ap
|
||||
|
||||
void ota_reboot_to_apply() { // public: set the apply magic + reset (does not return)
|
||||
uint8_t stage_handoff = GPREGRET2_OTA_STAGE_LEGACY;
|
||||
#if defined(OTA_QSPI_STORE)
|
||||
#if defined(OTA_SD_STORE)
|
||||
stage_handoff = GPREGRET2_OTA_STAGE_SD;
|
||||
#elif defined(OTA_QSPI_STORE)
|
||||
stage_handoff = GPREGRET2_OTA_STAGE_QSPI;
|
||||
#elif defined(OTA_FLASH_STORE)
|
||||
stage_handoff = mota_nrf52_flash_stage_handoff(ota_nrf52_effective_stage_ceiling());
|
||||
@@ -641,9 +643,24 @@ bool ota_rescue_mota_nrf52(const uint8_t* buf, uint32_t len, const SignerAllowli
|
||||
#if defined(OTA_SD_STORE) || defined(OTA_QSPI_STORE)
|
||||
static const size_t NRF52_APPLY_MSG_CAP = 96;
|
||||
|
||||
#if defined(OTA_SD_STORE)
|
||||
static bool external_application_approve(OtaStoreSdNrf52& store,
|
||||
const uint8_t container_hash[32]) {
|
||||
return store.approve_for_bootloader(nullptr, container_hash);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(OTA_QSPI_STORE)
|
||||
static bool external_application_approve(OtaStoreQspiNrf52& store,
|
||||
const uint8_t[32]) {
|
||||
return store.approve_for_bootloader();
|
||||
}
|
||||
#endif
|
||||
|
||||
template <typename Store>
|
||||
static bool ota_apply_mota_nrf52_external(Store& store, const SignerAllowlist& allow,
|
||||
uint8_t storage_flag, const char* storage_name,
|
||||
bool require_trusted_signature,
|
||||
ApplyState& st, char* msg) {
|
||||
st = ApplyState();
|
||||
uint8_t hdr[8], manifest[MOTA_MFL];
|
||||
@@ -695,14 +712,24 @@ static bool ota_apply_mota_nrf52_external(Store& store, const SignerAllowlist& a
|
||||
return false;
|
||||
}
|
||||
|
||||
VerifyResult vr = ota_verify(static_cast<const OtaStore&>(store), allow);
|
||||
// Require the streamed manifest to remain byte-identical to the local copy
|
||||
// parsed above. The verifier also computes the normalized full-container
|
||||
// digest during that same integrity/authentication pass for removable SD.
|
||||
VerifyResult vr = ota_verify(static_cast<const OtaStore&>(store), allow, manifest);
|
||||
st.sig_ok = vr.sig_ok;
|
||||
st.trusted = vr.trusted;
|
||||
if (!vr.root_ok || !vr.payload_ok || !vr.image_ok) {
|
||||
if (!vr.root_ok || !vr.payload_ok || !vr.image_ok || !vr.container_hash_ok) {
|
||||
snprintf(msg, NRF52_APPLY_MSG_CAP,
|
||||
"payload hash mismatch (incomplete or corrupt %s .mota)", storage_name);
|
||||
return false;
|
||||
}
|
||||
if (require_trusted_signature && !vr.auto_appliable()) {
|
||||
if (!vr.is_signed || !vr.sig_ok)
|
||||
strcpy(msg, "SD application OTA requires a valid signed manifest");
|
||||
else
|
||||
strcpy(msg, "SD application OTA signer is not in the trusted allowlist");
|
||||
return false;
|
||||
}
|
||||
|
||||
SelfFwInfo fi;
|
||||
if (delta) {
|
||||
@@ -738,7 +765,7 @@ static bool ota_apply_mota_nrf52_external(Store& store, const SignerAllowlist& a
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!store.approve_for_bootloader()) {
|
||||
if (!external_application_approve(store, vr.container_hash)) {
|
||||
snprintf(msg, NRF52_APPLY_MSG_CAP, "%s handoff failed: %s", storage_name,
|
||||
store.last_error());
|
||||
return false;
|
||||
@@ -751,80 +778,39 @@ static bool ota_apply_mota_nrf52_external(Store& store, const SignerAllowlist& a
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(OTA_SD_BOOTLOADER_UPDATE) || defined(OTA_QSPI_BOOTLOADER_UPDATE)
|
||||
template <typename Store>
|
||||
static bool external_bootloader_crc_ok(Store& store, uint32_t payload_off,
|
||||
const OtaBootloaderIdentity& identity) {
|
||||
uint8_t buf[512];
|
||||
uint32_t crc = UINT32_MAX;
|
||||
for (uint32_t off = 0; off < OTA_BOOT_IMAGE_SIZE; off += sizeof(buf)) {
|
||||
uint32_t len = OTA_BOOT_IMAGE_SIZE - off;
|
||||
if (len > sizeof(buf)) len = sizeof(buf);
|
||||
if (!store.read(payload_off + off, buf, len)) return false;
|
||||
for (uint32_t i = 0; i < len; i++) {
|
||||
const uint32_t pos = off + i;
|
||||
const uint8_t value = pos >= identity.manifest_offset + 40u &&
|
||||
pos < identity.manifest_offset + 44u ? 0 : buf[i];
|
||||
crc = ota_boot_crc32_update(crc, value);
|
||||
}
|
||||
}
|
||||
return ~crc == identity.crc32;
|
||||
#if defined(OTA_SD_BOOTLOADER_UPDATE) || defined(OTA_QSPI_BOOTLOADER_UPDATE) || \
|
||||
defined(OTA_INTERNAL_BOOTLOADER_UPDATE)
|
||||
static uint16_t ota_runtime_softdevice_fwid() {
|
||||
// Nordic's S140 information structure lives at MBR(0x1000) + 0x2000;
|
||||
// FWID is the little-endian uint16 at +0x0C.
|
||||
return *(const volatile uint16_t*)(uintptr_t)0x0000300Cu;
|
||||
}
|
||||
|
||||
template <typename Store>
|
||||
static bool external_bootloader_image_metadata(Store& store, uint32_t payload_off,
|
||||
OtaBootloaderIdentity& candidate,
|
||||
OtaBootloaderCapsMarker& caps) {
|
||||
// Keep enough overlap to catch a 44-byte manifest or 16-byte capability marker split across a
|
||||
// window. Every aligned manifest candidate is considered; a magic string in a literal pool is not
|
||||
// a terminal failure.
|
||||
static const uint32_t STEP = 512;
|
||||
uint8_t buf[STEP + OTA_BOOT_MANIFEST_SIZE - 1];
|
||||
uint8_t valid_identities = 0;
|
||||
uint8_t valid_caps = 0;
|
||||
for (uint32_t base = 0; base < OTA_BOOT_IMAGE_SIZE; base += STEP) {
|
||||
uint32_t len = OTA_BOOT_IMAGE_SIZE - base;
|
||||
if (len > sizeof(buf)) len = sizeof(buf);
|
||||
if (!store.read(payload_off + base, buf, len)) return false;
|
||||
const uint32_t starts = (OTA_BOOT_IMAGE_SIZE - base < STEP)
|
||||
? OTA_BOOT_IMAGE_SIZE - base : STEP;
|
||||
for (uint32_t local = 0; local < starts; local++) {
|
||||
const uint32_t absolute = base + local;
|
||||
if ((absolute & 3u) == 0 && local + 16u <= len) {
|
||||
OtaBootloaderCapsMarker parsed;
|
||||
if (ota_bootloader_caps_marker_parse(buf + local, parsed) &&
|
||||
parsed.apply_abi >= MOTA_BOOT_FORMAT_VER &&
|
||||
(parsed.codec_mask & OTA_BL_REQUIRED_APP_CODEC_MASK) ==
|
||||
OTA_BL_REQUIRED_APP_CODEC_MASK &&
|
||||
(parsed.storage_flags & OTA_BL_STORAGE_BOOT_UPDATE) != 0) {
|
||||
if (++valid_caps != 1u) return false;
|
||||
if (parsed.storage_flags == ota_bootloader_update_storage_flags()) caps = parsed;
|
||||
}
|
||||
}
|
||||
if ((absolute & 3u) != 0 || local + OTA_BOOT_MANIFEST_SIZE > len) continue;
|
||||
OtaBootloaderIdentity parsed;
|
||||
if (!ota_bootloader_manifest_parse(buf + local, absolute, parsed)) continue;
|
||||
if (external_bootloader_crc_ok(store, payload_off, parsed)) {
|
||||
parsed.crc_ok = true;
|
||||
if (!ota_bootloader_identity_add_unique(parsed, candidate, valid_identities)) return false;
|
||||
}
|
||||
}
|
||||
static const char* ota_bootloader_continuity_error(OtaBootloaderContinuityGate gate) {
|
||||
switch (gate) {
|
||||
case OTA_BOOT_CONTINUITY_CANDIDATE_MISSING: return "candidate lacks boot continuity metadata";
|
||||
case OTA_BOOT_CONTINUITY_OUTER_VERSION: return "candidate embedded/package version mismatch";
|
||||
case OTA_BOOT_CONTINUITY_PLATFORM: return "candidate SoftDevice/application layout mismatch";
|
||||
case OTA_BOOT_CONTINUITY_INSTALLED_PLATFORM: return "installed boot continuity metadata mismatch";
|
||||
case OTA_BOOT_CONTINUITY_NOT_NEWER: return "candidate bootloader is not newer";
|
||||
default: return "boot continuity mismatch";
|
||||
}
|
||||
return valid_identities == 1u && valid_caps == 1u &&
|
||||
candidate.present && candidate.crc_ok && caps.present;
|
||||
}
|
||||
|
||||
#if defined(OTA_SD_BOOTLOADER_UPDATE)
|
||||
static bool external_bootloader_approve(OtaStoreSdNrf52& store,
|
||||
const uint8_t image_hash[32]) {
|
||||
return store.approve_for_bootloader(image_hash);
|
||||
const uint8_t image_hash[32],
|
||||
const uint8_t container_hash[32]) {
|
||||
return store.approve_for_bootloader(image_hash, container_hash);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(OTA_QSPI_BOOTLOADER_UPDATE)
|
||||
static bool external_bootloader_approve(OtaStoreQspiNrf52& store,
|
||||
const uint8_t image_hash[32]) {
|
||||
const uint8_t image_hash[32],
|
||||
const uint8_t container_hash[32]) {
|
||||
(void)image_hash;
|
||||
(void)container_hash;
|
||||
return store.approve_for_bootloader();
|
||||
}
|
||||
#endif
|
||||
@@ -893,7 +879,7 @@ static bool ota_prepare_bootloader_update_external(Store& store,
|
||||
st.trusted = vr.trusted;
|
||||
st.image_size = m.image_size;
|
||||
memcpy(st.image_hash, m.image_hash, sizeof(st.image_hash));
|
||||
if (!vr.auto_appliable()) {
|
||||
if (!vr.auto_appliable() || !vr.container_hash_ok) {
|
||||
if (!vr.root_ok || !vr.payload_ok || !vr.image_ok)
|
||||
strcpy(msg, "bootloader payload hash mismatch");
|
||||
else if (!vr.sig_ok)
|
||||
@@ -909,12 +895,23 @@ static bool ota_prepare_bootloader_update_external(Store& store,
|
||||
}
|
||||
OtaBootloaderIdentity candidate;
|
||||
OtaBootloaderCapsMarker candidate_caps;
|
||||
if (!external_bootloader_image_metadata(store, payload_off, candidate, candidate_caps) ||
|
||||
if (!ota_bootloader_external_image_metadata(
|
||||
store, payload_off, ota_bootloader_update_storage_flags(),
|
||||
candidate, candidate_caps) ||
|
||||
!ota_bootloader_identity_matches(installed, candidate)) {
|
||||
strcpy(msg, "candidate bootloader identity/capability/CRC mismatch"); return false;
|
||||
}
|
||||
const OtaBootloaderContinuityGate continuity = ota_bootloader_continuity_gate(
|
||||
installed, candidate, m.fw_version, OTA_BOOT_CONTINUITY_FAMILY_S140,
|
||||
ota_runtime_softdevice_fwid(), mota_nrf52_app_base(),
|
||||
OTA_BOOT_CONTINUITY_LAYOUT_ABI);
|
||||
if (continuity != OTA_BOOT_CONTINUITY_OK) {
|
||||
strncpy(msg, ota_bootloader_continuity_error(continuity), CAP);
|
||||
msg[CAP - 1] = 0;
|
||||
return false;
|
||||
}
|
||||
st.slot_ok = true;
|
||||
if (!external_bootloader_approve(store, m.image_hash)) {
|
||||
if (!external_bootloader_approve(store, m.image_hash, vr.container_hash)) {
|
||||
snprintf(msg, CAP, "%s bootloader handoff failed: %s", storage_name, store.last_error());
|
||||
return false;
|
||||
}
|
||||
@@ -926,7 +923,19 @@ static bool ota_prepare_bootloader_update_external(Store& store,
|
||||
#if defined(OTA_SD_STORE)
|
||||
bool ota_apply_mota_nrf52(OtaStoreSdNrf52& store, const SignerAllowlist& allow,
|
||||
ApplyState& st, char* msg) {
|
||||
return ota_apply_mota_nrf52_external(store, allow, OTA_BL_STORAGE_SD, "SD", st, msg);
|
||||
#if defined(OTA_SD_BOOTLOADER_UPDATE)
|
||||
OtaBootloaderIdentity installed;
|
||||
if (!ota_installed_bootloader_identity(installed) ||
|
||||
!ota_bootloader_sd_retained_auth_ready(
|
||||
installed, OTA_BOOT_CONTINUITY_FAMILY_S140,
|
||||
ota_runtime_softdevice_fwid(), mota_nrf52_app_base(),
|
||||
OTA_BOOT_CONTINUITY_LAYOUT_ABI)) {
|
||||
st = ApplyState();
|
||||
strcpy(msg, "SD application OTA requires the BLM2 retained-auth bootloader");
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
return ota_apply_mota_nrf52_external(store, allow, OTA_BL_STORAGE_SD, "SD", true, st, msg);
|
||||
}
|
||||
|
||||
#if defined(OTA_SD_BOOTLOADER_UPDATE)
|
||||
@@ -937,6 +946,14 @@ bool ota_prepare_bootloader_update_nrf52(OtaStoreSdNrf52& store,
|
||||
const uint8_t operator_mid[4],
|
||||
const uint8_t operator_hash8[8],
|
||||
ApplyState& st, char* msg) {
|
||||
if (!ota_bootloader_sd_retained_auth_ready(
|
||||
installed, OTA_BOOT_CONTINUITY_FAMILY_S140,
|
||||
ota_runtime_softdevice_fwid(), mota_nrf52_app_base(),
|
||||
OTA_BOOT_CONTINUITY_LAYOUT_ABI)) {
|
||||
st = ApplyState();
|
||||
strcpy(msg, "SD bootloader OTA requires a locally installed BLM2 retained-auth bootloader");
|
||||
return false;
|
||||
}
|
||||
SelfFwInfo fi;
|
||||
if (!ota_self_firmware(fi) ||
|
||||
!ota_bootloader_scratch_headroom_valid(
|
||||
@@ -956,7 +973,7 @@ bool ota_prepare_bootloader_update_nrf52(OtaStoreSdNrf52& store,
|
||||
#if defined(OTA_QSPI_STORE)
|
||||
bool ota_apply_mota_nrf52(OtaStoreQspiNrf52& store, const SignerAllowlist& allow,
|
||||
ApplyState& st, char* msg) {
|
||||
return ota_apply_mota_nrf52_external(store, allow, OTA_BL_STORAGE_QSPI, "QSPI", st, msg);
|
||||
return ota_apply_mota_nrf52_external(store, allow, OTA_BL_STORAGE_QSPI, "QSPI", false, st, msg);
|
||||
}
|
||||
|
||||
#if defined(OTA_QSPI_BOOTLOADER_UPDATE)
|
||||
@@ -1043,7 +1060,8 @@ bool ota_prepare_bootloader_update_nrf52(OtaStoreFlashNrf52& store,
|
||||
}
|
||||
OtaBootloaderIdentity candidate;
|
||||
OtaBootloaderCapsMarker candidate_caps;
|
||||
if (!ota_bootloader_identity_from_image(image, OTA_BOOT_IMAGE_SIZE, candidate) ||
|
||||
if (!ota_bootloader_candidate_identity_from_image(
|
||||
image, OTA_BOOT_IMAGE_SIZE, candidate) ||
|
||||
!ota_bootloader_identity_matches(installed, candidate) ||
|
||||
!ota_bootloader_caps_from_image(
|
||||
image, OTA_BOOT_IMAGE_SIZE,
|
||||
@@ -1051,6 +1069,15 @@ bool ota_prepare_bootloader_update_nrf52(OtaStoreFlashNrf52& store,
|
||||
candidate_caps)) {
|
||||
strcpy(msg, "candidate bootloader identity/capability/CRC mismatch"); return false;
|
||||
}
|
||||
const OtaBootloaderContinuityGate continuity = ota_bootloader_continuity_gate(
|
||||
installed, candidate, m.fw_version, OTA_BOOT_CONTINUITY_FAMILY_S140,
|
||||
ota_runtime_softdevice_fwid(), mota_nrf52_app_base(),
|
||||
OTA_BOOT_CONTINUITY_LAYOUT_ABI);
|
||||
if (continuity != OTA_BOOT_CONTINUITY_OK) {
|
||||
strncpy(msg, ota_bootloader_continuity_error(continuity), CAP);
|
||||
msg[CAP - 1] = 0;
|
||||
return false;
|
||||
}
|
||||
st.slot_ok = true;
|
||||
if (!store.approve_for_bootloader()) {
|
||||
snprintf(msg, CAP, "internal bootloader handoff failed: %s", store.last_error()); return false;
|
||||
|
||||
@@ -94,6 +94,7 @@ inline OtaBlCaps ota_bl_caps_scan_aligned(const uint8_t* bytes, size_t len,
|
||||
OtaBlCaps c;
|
||||
if (!bytes) return c;
|
||||
uint8_t privileged_count = 0;
|
||||
bool exact_privileged = false;
|
||||
for (size_t off = 0; off + 16u <= len; off += 4u) {
|
||||
const uint8_t* p = bytes + off;
|
||||
if (p[0] != OTA_BL_MAGIC[0] || memcmp(p, OTA_BL_MAGIC, 8) != 0) continue;
|
||||
@@ -103,18 +104,21 @@ inline OtaBlCaps ota_bl_caps_scan_aligned(const uint8_t* bytes, size_t len,
|
||||
if (abi == 0 || abi == 0xFFFFu || codecs == 0 || (storage & ~OTA_BL_STORAGE_KNOWN) != 0 ||
|
||||
p[13] != 0 || p[14] != 0 || p[15] != 0) continue;
|
||||
const bool exact_profile = exact_storage_flags == 0 || storage == exact_storage_flags;
|
||||
if (require_boot_update && exact_profile && abi >= 3u &&
|
||||
if (require_boot_update && abi >= 3u &&
|
||||
(codecs & OTA_BL_REQUIRED_APP_CODEC_MASK) == OTA_BL_REQUIRED_APP_CODEC_MASK &&
|
||||
(storage & OTA_BL_STORAGE_BOOT_UPDATE) != 0) {
|
||||
// A self-update build must have one unambiguous privileged marker. Do
|
||||
// not silently choose between two otherwise valid structures (including
|
||||
// two copies of the expected exact profile). Malformed magic/literal
|
||||
// decoys were filtered above and do not count.
|
||||
// not silently choose between two otherwise valid structures, even if
|
||||
// one claims a different known storage profile (or only BOOT_UPDATE).
|
||||
// Malformed magic/literal decoys were filtered above and do not count.
|
||||
if (++privileged_count != 1u) return OtaBlCaps();
|
||||
c.present = true;
|
||||
c.apply_abi = abi;
|
||||
c.codec_mask = codecs;
|
||||
c.storage_flags = storage;
|
||||
if (exact_profile) {
|
||||
exact_privileged = true;
|
||||
c.present = true;
|
||||
c.apply_abi = abi;
|
||||
c.codec_mask = codecs;
|
||||
c.storage_flags = storage;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (ota_bl_caps_prefer(c, abi, storage, require_boot_update)) {
|
||||
@@ -124,7 +128,8 @@ inline OtaBlCaps ota_bl_caps_scan_aligned(const uint8_t* bytes, size_t len,
|
||||
c.storage_flags = storage;
|
||||
}
|
||||
}
|
||||
if (require_boot_update && privileged_count != 1u) return OtaBlCaps();
|
||||
if (require_boot_update &&
|
||||
(privileged_count != 1u || !exact_privileged)) return OtaBlCaps();
|
||||
return c;
|
||||
}
|
||||
|
||||
|
||||
@@ -52,9 +52,20 @@ static const uint32_t OTA_BOOT_MANIFEST_MAGIC0 = 0x464D4C42UL; // bytes "BLMF"
|
||||
static const uint32_t OTA_BOOT_MANIFEST_MAGIC1 = 0x31435243UL; // bytes "CRC1"
|
||||
static const uint16_t OTA_BOOT_MANIFEST_VERSION = 1;
|
||||
static const uint16_t OTA_BOOT_MANIFEST_SIZE = 44;
|
||||
static const uint32_t OTA_BOOT_CONTINUITY_MAGIC0 = 0x324D4C42UL; // bytes "BLM2"
|
||||
static const uint32_t OTA_BOOT_CONTINUITY_MAGIC1 = 0x54464F53UL; // bytes "SOFT"
|
||||
static const uint16_t OTA_BOOT_CONTINUITY_VERSION = 2;
|
||||
static const uint16_t OTA_BOOT_CONTINUITY_SIZE = 32;
|
||||
static const uint16_t OTA_BOOT_CONTINUITY_FAMILY_S140 = 140;
|
||||
static const uint16_t OTA_BOOT_CONTINUITY_LAYOUT_ABI = 1;
|
||||
static const uint32_t OTA_BOOT_CONTINUITY_OFFSET = OTA_BOOT_MANIFEST_SIZE;
|
||||
static const uint32_t OTA_BOOT_ENVELOPE_SIZE =
|
||||
OTA_BOOT_MANIFEST_SIZE + OTA_BOOT_CONTINUITY_SIZE;
|
||||
static const uint8_t OTA_BOOT_DEVICE_NAME_SIZE = 16;
|
||||
static const uint32_t OTA_BOOT_IMAGE_START = 0x000F4000UL;
|
||||
static const uint32_t OTA_BOOT_IMAGE_SIZE = 0x0000A000UL; // F4000..FE000, padded to exactly 40 KiB
|
||||
static const uint32_t OTA_BOOT_CANDIDATE_MANIFEST_OFFSET =
|
||||
OTA_BOOT_IMAGE_SIZE - OTA_BOOT_ENVELOPE_SIZE; // final 76 bytes: 0x9FB4
|
||||
static const uint32_t OTA_BOOT_SCRATCH_START = 0x000E0000UL;
|
||||
static const uint32_t OTA_BOOT_SCRATCH_END = 0x000EA000UL;
|
||||
static const uint32_t OTA_NRF52840_BOOT_SETTINGS_ADDRESS = 0x000FF000UL;
|
||||
@@ -133,6 +144,13 @@ struct OtaBootloaderIdentity {
|
||||
uint32_t board_id = 0;
|
||||
char device_name[OTA_BOOT_DEVICE_NAME_SIZE + 1] = {0};
|
||||
uint32_t crc32 = 0;
|
||||
bool continuity_present = false;
|
||||
uint32_t boot_version = 0;
|
||||
uint16_t softdevice_family = 0;
|
||||
uint16_t softdevice_fwid = 0;
|
||||
uint32_t app_base = 0;
|
||||
uint16_t layout_abi = 0;
|
||||
uint16_t compat_flags = 0;
|
||||
};
|
||||
|
||||
// Accumulate a stream of already CRC-validated candidates without silently
|
||||
@@ -160,6 +178,12 @@ inline uint32_t ota_boot_rd32(const uint8_t* p) {
|
||||
((uint32_t)p[3] << 24);
|
||||
}
|
||||
|
||||
inline bool ota_bootloader_version_valid(uint32_t version) {
|
||||
// Boot builds use preview 1..254 and 0xFF for a stable release. Zero is not
|
||||
// a boot release, and all-ones must not establish an un-upgradable floor.
|
||||
return version != 0 && version != UINT32_MAX && (version & 0xFFu) != 0;
|
||||
}
|
||||
|
||||
inline bool ota_xiao_bootloader_board_id(uint32_t board_id) {
|
||||
return board_id == OTA_XIAO_BOARD_ID_BASE || board_id == OTA_XIAO_BOARD_ID_SENSE;
|
||||
}
|
||||
@@ -246,11 +270,16 @@ inline uint32_t ota_boot_image_crc32(const uint8_t* image, size_t image_size,
|
||||
return ~crc;
|
||||
}
|
||||
|
||||
// Parse one candidate header. The caller independently validates the complete-region CRC so a magic
|
||||
// string in a literal pool cannot establish an identity.
|
||||
inline bool ota_bootloader_manifest_parse(const uint8_t* raw, uint32_t raw_offset,
|
||||
OtaBootloaderIdentity& out) {
|
||||
if (!raw || ota_boot_rd32(raw) != OTA_BOOT_MANIFEST_MAGIC0 ||
|
||||
// Parse only the legacy-v1 identity envelope. The complete-image CRC is checked
|
||||
// by the caller. Identity scanners deliberately count this base record before
|
||||
// interpreting an adjacent BLM2 extension: deployed legacy bootloaders do the
|
||||
// same, so a CRC-valid base record with a corrupt extension must not disappear
|
||||
// from duplicate-identity accounting.
|
||||
inline bool ota_bootloader_manifest_base_parse(const uint8_t* raw, uint32_t raw_offset,
|
||||
OtaBootloaderIdentity& out,
|
||||
size_t available = OTA_BOOT_MANIFEST_SIZE) {
|
||||
if (!raw || available < OTA_BOOT_MANIFEST_SIZE ||
|
||||
ota_boot_rd32(raw) != OTA_BOOT_MANIFEST_MAGIC0 ||
|
||||
ota_boot_rd32(raw + 4) != OTA_BOOT_MANIFEST_MAGIC1 ||
|
||||
ota_boot_rd16(raw + 8) != OTA_BOOT_MANIFEST_VERSION ||
|
||||
ota_boot_rd16(raw + 10) != OTA_BOOT_MANIFEST_SIZE ||
|
||||
@@ -271,6 +300,52 @@ inline bool ota_bootloader_manifest_parse(const uint8_t* raw, uint32_t raw_offse
|
||||
return true;
|
||||
}
|
||||
|
||||
// Interpret continuity metadata only after the scanner has established that
|
||||
// exactly one CRC-valid base identity exists. Neither magic word means a true
|
||||
// legacy-v1 record. One magic word, truncated metadata, or invalid claimed
|
||||
// metadata fails closed instead of silently downgrading to legacy behavior.
|
||||
inline bool ota_bootloader_continuity_parse(const uint8_t* raw, size_t available,
|
||||
OtaBootloaderIdentity& out) {
|
||||
out.continuity_present = false;
|
||||
out.boot_version = 0;
|
||||
out.softdevice_family = 0;
|
||||
out.softdevice_fwid = 0;
|
||||
out.app_base = 0;
|
||||
out.layout_abi = 0;
|
||||
out.compat_flags = 0;
|
||||
if (!raw || available <= OTA_BOOT_MANIFEST_SIZE) return true;
|
||||
|
||||
const bool magic0 = available >= OTA_BOOT_MANIFEST_SIZE + 4u &&
|
||||
ota_boot_rd32(raw + 44) == OTA_BOOT_CONTINUITY_MAGIC0;
|
||||
const bool magic1 = available >= OTA_BOOT_MANIFEST_SIZE + 8u &&
|
||||
ota_boot_rd32(raw + 48) == OTA_BOOT_CONTINUITY_MAGIC1;
|
||||
if (!magic0 && !magic1) return true;
|
||||
if (available < OTA_BOOT_ENVELOPE_SIZE || !magic0 || !magic1 ||
|
||||
ota_boot_rd16(raw + 52) != OTA_BOOT_CONTINUITY_VERSION ||
|
||||
ota_boot_rd16(raw + 54) != OTA_BOOT_CONTINUITY_SIZE ||
|
||||
!ota_bootloader_version_valid(ota_boot_rd32(raw + 56)) ||
|
||||
ota_boot_rd16(raw + 60) == 0 || ota_boot_rd16(raw + 62) == 0 ||
|
||||
ota_boot_rd32(raw + 64) == 0 || ota_boot_rd16(raw + 68) == 0 ||
|
||||
ota_boot_rd16(raw + 70) != 0 || ota_boot_rd32(raw + 72) != 0) return false;
|
||||
out.continuity_present = true;
|
||||
out.boot_version = ota_boot_rd32(raw + 56);
|
||||
out.softdevice_family = ota_boot_rd16(raw + 60);
|
||||
out.softdevice_fwid = ota_boot_rd16(raw + 62);
|
||||
out.app_base = ota_boot_rd32(raw + 64);
|
||||
out.layout_abi = ota_boot_rd16(raw + 68);
|
||||
out.compat_flags = ota_boot_rd16(raw + 70);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Convenience parser for a single already-selected envelope. Whole-image
|
||||
// scanners must use the base parser for duplicate counting first.
|
||||
inline bool ota_bootloader_manifest_parse(const uint8_t* raw, uint32_t raw_offset,
|
||||
OtaBootloaderIdentity& out,
|
||||
size_t available = OTA_BOOT_MANIFEST_SIZE) {
|
||||
return ota_bootloader_manifest_base_parse(raw, raw_offset, out, available) &&
|
||||
ota_bootloader_continuity_parse(raw, available, out);
|
||||
}
|
||||
|
||||
inline bool ota_bootloader_hw_id(const OtaBootloaderIdentity& identity, uint8_t out[32]) {
|
||||
return identity.present && identity.crc_ok &&
|
||||
ota_bootloader_hw_id(identity.board_id,
|
||||
@@ -292,12 +367,30 @@ inline bool ota_bootloader_identity_from_image(const uint8_t* image, size_t imag
|
||||
uint8_t valid_count = 0;
|
||||
for (size_t offset = 0; offset + OTA_BOOT_MANIFEST_SIZE <= image_size; offset += 4) {
|
||||
OtaBootloaderIdentity candidate;
|
||||
if (!ota_bootloader_manifest_parse(image + offset, (uint32_t)offset, candidate)) continue;
|
||||
if (!ota_bootloader_manifest_base_parse(image + offset, (uint32_t)offset, candidate,
|
||||
image_size - offset)) continue;
|
||||
candidate.crc_ok = ota_boot_image_crc32(image, image_size, offset + 40) == candidate.crc32;
|
||||
if (!candidate.crc_ok) continue;
|
||||
if (!ota_bootloader_identity_add_unique(candidate, out, valid_count)) return false;
|
||||
}
|
||||
return valid_count == 1u;
|
||||
return valid_count == 1u &&
|
||||
ota_bootloader_continuity_parse(image + out.manifest_offset,
|
||||
image_size - out.manifest_offset, out);
|
||||
}
|
||||
|
||||
inline bool ota_bootloader_candidate_identity_canonical(
|
||||
const OtaBootloaderIdentity& identity) {
|
||||
return identity.present && identity.crc_ok && identity.continuity_present &&
|
||||
identity.manifest_offset == OTA_BOOT_CANDIDATE_MANIFEST_OFFSET;
|
||||
}
|
||||
|
||||
// New candidates place the complete v1+v2 envelope at one canonical offset.
|
||||
// Installed legacy-v1 discovery above intentionally remains a whole-image
|
||||
// scan for diagnostics and qualified non-SD transition paths.
|
||||
inline bool ota_bootloader_candidate_identity_from_image(
|
||||
const uint8_t* image, size_t image_size, OtaBootloaderIdentity& out) {
|
||||
return ota_bootloader_identity_from_image(image, image_size, out) &&
|
||||
ota_bootloader_candidate_identity_canonical(out);
|
||||
}
|
||||
|
||||
inline bool ota_bootloader_identity_matches(const OtaBootloaderIdentity& a,
|
||||
@@ -308,6 +401,79 @@ inline bool ota_bootloader_identity_matches(const OtaBootloaderIdentity& a,
|
||||
memcmp(a.device_name, b.device_name, OTA_BOOT_DEVICE_NAME_SIZE) == 0;
|
||||
}
|
||||
|
||||
enum OtaBootloaderContinuityGate : uint8_t {
|
||||
OTA_BOOT_CONTINUITY_OK = 0,
|
||||
OTA_BOOT_CONTINUITY_CANDIDATE_MISSING,
|
||||
OTA_BOOT_CONTINUITY_OUTER_VERSION,
|
||||
OTA_BOOT_CONTINUITY_PLATFORM,
|
||||
OTA_BOOT_CONTINUITY_INSTALLED_PLATFORM,
|
||||
OTA_BOOT_CONTINUITY_NOT_NEWER,
|
||||
};
|
||||
|
||||
inline bool ota_bootloader_continuity_matches_runtime(
|
||||
const OtaBootloaderIdentity& identity,
|
||||
uint16_t runtime_softdevice_family,
|
||||
uint16_t runtime_softdevice_fwid,
|
||||
uint32_t runtime_app_base,
|
||||
uint16_t runtime_layout_abi) {
|
||||
return identity.continuity_present &&
|
||||
ota_bootloader_version_valid(identity.boot_version) &&
|
||||
identity.softdevice_family == runtime_softdevice_family &&
|
||||
identity.softdevice_fwid == runtime_softdevice_fwid &&
|
||||
identity.app_base == runtime_app_base &&
|
||||
identity.layout_abi == runtime_layout_abi && identity.compat_flags == 0;
|
||||
}
|
||||
|
||||
// SD OTAFIX accepts geometry only from the reset-retained authorization
|
||||
// record. A legacy BLMF-v1 bootloader predates that protocol and must be
|
||||
// upgraded locally; neither application nor bootloader OTA may fall back to a
|
||||
// raw card sector.
|
||||
inline bool ota_bootloader_sd_retained_auth_ready(
|
||||
const OtaBootloaderIdentity& identity,
|
||||
uint16_t runtime_softdevice_family,
|
||||
uint16_t runtime_softdevice_fwid,
|
||||
uint32_t runtime_app_base,
|
||||
uint16_t runtime_layout_abi) {
|
||||
return identity.present && identity.crc_ok &&
|
||||
ota_bootloader_continuity_matches_runtime(
|
||||
identity, runtime_softdevice_family, runtime_softdevice_fwid,
|
||||
runtime_app_base, runtime_layout_abi);
|
||||
}
|
||||
|
||||
// Qualified internal/QSPI paths may bootstrap a legacy-v1 installed manifest
|
||||
// once because deployed builds do not carry continuity metadata. SD callers
|
||||
// independently require retained-auth continuity before entering this gate.
|
||||
// Every remotely supplied successor must carry the extension. Once v2 is
|
||||
// installed, remote updates are strictly monotonic; rollback/migration remains
|
||||
// a local DFU/SWD operation.
|
||||
inline OtaBootloaderContinuityGate ota_bootloader_continuity_gate(
|
||||
const OtaBootloaderIdentity& installed,
|
||||
const OtaBootloaderIdentity& candidate,
|
||||
uint32_t outer_fw_version,
|
||||
uint16_t runtime_softdevice_family,
|
||||
uint16_t runtime_softdevice_fwid,
|
||||
uint32_t runtime_app_base,
|
||||
uint16_t runtime_layout_abi) {
|
||||
if (!candidate.continuity_present)
|
||||
return OTA_BOOT_CONTINUITY_CANDIDATE_MISSING;
|
||||
if (!ota_bootloader_version_valid(candidate.boot_version) ||
|
||||
outer_fw_version != candidate.boot_version)
|
||||
return OTA_BOOT_CONTINUITY_OUTER_VERSION;
|
||||
if (!ota_bootloader_continuity_matches_runtime(
|
||||
candidate, runtime_softdevice_family, runtime_softdevice_fwid,
|
||||
runtime_app_base, runtime_layout_abi))
|
||||
return OTA_BOOT_CONTINUITY_PLATFORM;
|
||||
if (installed.continuity_present) {
|
||||
if (!ota_bootloader_continuity_matches_runtime(
|
||||
installed, runtime_softdevice_family, runtime_softdevice_fwid,
|
||||
runtime_app_base, runtime_layout_abi))
|
||||
return OTA_BOOT_CONTINUITY_INSTALLED_PLATFORM;
|
||||
if (candidate.boot_version <= installed.boot_version)
|
||||
return OTA_BOOT_CONTINUITY_NOT_NEWER;
|
||||
}
|
||||
return OTA_BOOT_CONTINUITY_OK;
|
||||
}
|
||||
|
||||
// Cheap first-line rejection of a malformed raw bootloader region. OTAFIX repeats this check before
|
||||
// touching internal flash. MSP may point one byte beyond RAM; the reset vector must be Thumb code in
|
||||
// the exact bootloader image range.
|
||||
@@ -331,12 +497,13 @@ struct OtaBootloaderCapsMarker {
|
||||
inline bool ota_bootloader_caps_marker_parse(const uint8_t raw[16],
|
||||
OtaBootloaderCapsMarker& out) {
|
||||
static const uint8_t magic[8] = {'M','O','T','A','B','L','D','R'};
|
||||
if (!raw || memcmp(raw, magic, sizeof(magic)) != 0 ||
|
||||
raw[8] == 0 || (raw[8] == 0xFF && raw[9] == 0xFF) ||
|
||||
if (!raw || memcmp(raw, magic, sizeof(magic)) != 0) return false;
|
||||
const uint16_t apply_abi = ota_boot_rd16(raw + 8);
|
||||
if (apply_abi == 0 || apply_abi == UINT16_MAX ||
|
||||
(raw[10] == 0 && raw[11] == 0) || (raw[12] & ~OTA_BL_STORAGE_KNOWN) != 0 ||
|
||||
raw[13] != 0 || raw[14] != 0 || raw[15] != 0) return false;
|
||||
out.present = true;
|
||||
out.apply_abi = ota_boot_rd16(raw + 8);
|
||||
out.apply_abi = apply_abi;
|
||||
out.codec_mask = ota_boot_rd16(raw + 10);
|
||||
out.storage_flags = raw[12];
|
||||
return true;
|
||||
@@ -362,6 +529,84 @@ inline bool ota_bootloader_caps_from_image(const uint8_t* image, size_t image_si
|
||||
return valid_count == 1u && out.present;
|
||||
}
|
||||
|
||||
// Stream the bootloader payload through an arbitrary random-access store. Keeping
|
||||
// this scanner beside the memory-image parser makes the canonical-envelope and
|
||||
// duplicate-marker policy directly testable and identical for SD/QSPI staging.
|
||||
template <typename Store>
|
||||
inline bool ota_bootloader_external_crc_ok(
|
||||
Store& store, uint32_t payload_off,
|
||||
const OtaBootloaderIdentity& identity) {
|
||||
uint8_t buf[512];
|
||||
uint32_t crc = UINT32_MAX;
|
||||
for (uint32_t off = 0; off < OTA_BOOT_IMAGE_SIZE; off += sizeof(buf)) {
|
||||
uint32_t len = OTA_BOOT_IMAGE_SIZE - off;
|
||||
if (len > sizeof(buf)) len = sizeof(buf);
|
||||
if (!store.read(payload_off + off, buf, len)) return false;
|
||||
for (uint32_t i = 0; i < len; ++i) {
|
||||
const uint32_t pos = off + i;
|
||||
const uint8_t value = pos >= identity.manifest_offset + 40u &&
|
||||
pos < identity.manifest_offset + 44u ? 0 : buf[i];
|
||||
crc = ota_boot_crc32_update(crc, value);
|
||||
}
|
||||
}
|
||||
return ~crc == identity.crc32;
|
||||
}
|
||||
|
||||
template <typename Store>
|
||||
inline bool ota_bootloader_external_image_metadata(
|
||||
Store& store, uint32_t payload_off, uint8_t exact_storage_flags,
|
||||
OtaBootloaderIdentity& candidate, OtaBootloaderCapsMarker& caps) {
|
||||
candidate = OtaBootloaderIdentity();
|
||||
caps = OtaBootloaderCapsMarker();
|
||||
if (exact_storage_flags == 0u) return false;
|
||||
|
||||
static const uint32_t STEP = 512u;
|
||||
uint8_t buf[STEP + OTA_BOOT_ENVELOPE_SIZE - 1u];
|
||||
uint8_t valid_identities = 0;
|
||||
uint8_t valid_caps = 0;
|
||||
for (uint32_t base = 0; base < OTA_BOOT_IMAGE_SIZE; base += STEP) {
|
||||
uint32_t len = OTA_BOOT_IMAGE_SIZE - base;
|
||||
if (len > sizeof(buf)) len = sizeof(buf);
|
||||
if (!store.read(payload_off + base, buf, len)) return false;
|
||||
const uint32_t starts = (OTA_BOOT_IMAGE_SIZE - base < STEP)
|
||||
? OTA_BOOT_IMAGE_SIZE - base : STEP;
|
||||
for (uint32_t local = 0; local < starts; ++local) {
|
||||
const uint32_t absolute = base + local;
|
||||
if ((absolute & 3u) == 0u && local + 16u <= len) {
|
||||
OtaBootloaderCapsMarker parsed;
|
||||
if (ota_bootloader_caps_marker_parse(buf + local, parsed) &&
|
||||
parsed.apply_abi >= MOTA_BOOT_FORMAT_VER &&
|
||||
(parsed.codec_mask & OTA_BL_REQUIRED_APP_CODEC_MASK) ==
|
||||
OTA_BL_REQUIRED_APP_CODEC_MASK &&
|
||||
(parsed.storage_flags & OTA_BL_STORAGE_BOOT_UPDATE) != 0u) {
|
||||
if (++valid_caps != 1u) return false;
|
||||
if (parsed.storage_flags == exact_storage_flags) caps = parsed;
|
||||
}
|
||||
}
|
||||
if ((absolute & 3u) != 0u ||
|
||||
local + OTA_BOOT_MANIFEST_SIZE > len) continue;
|
||||
OtaBootloaderIdentity parsed;
|
||||
if (!ota_bootloader_manifest_base_parse(
|
||||
buf + local, absolute, parsed, len - local)) continue;
|
||||
if (ota_bootloader_external_crc_ok(store, payload_off, parsed)) {
|
||||
parsed.crc_ok = true;
|
||||
if (!ota_bootloader_identity_add_unique(
|
||||
parsed, candidate, valid_identities)) return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (valid_identities != 1u || valid_caps != 1u || !caps.present ||
|
||||
candidate.manifest_offset > OTA_BOOT_IMAGE_SIZE - OTA_BOOT_MANIFEST_SIZE)
|
||||
return false;
|
||||
const uint32_t available = OTA_BOOT_IMAGE_SIZE - candidate.manifest_offset;
|
||||
uint8_t envelope[OTA_BOOT_ENVELOPE_SIZE];
|
||||
uint32_t envelope_len = available;
|
||||
if (envelope_len > sizeof(envelope)) envelope_len = sizeof(envelope);
|
||||
if (!store.read(payload_off + candidate.manifest_offset, envelope, envelope_len) ||
|
||||
!ota_bootloader_continuity_parse(envelope, envelope_len, candidate)) return false;
|
||||
return ota_bootloader_candidate_identity_canonical(candidate);
|
||||
}
|
||||
|
||||
enum OtaBootloaderConfirmGate : uint8_t {
|
||||
OTA_BOOT_CONFIRM_OK = 0,
|
||||
OTA_BOOT_CONFIRM_NOT_BOOT_PACKAGE,
|
||||
|
||||
@@ -109,6 +109,7 @@ static const char* fetch_error_word(OtaManager::FetchError error) {
|
||||
switch (error) {
|
||||
case OtaManager::FETCH_ERROR_MANIFEST: return "invalid manifest";
|
||||
case OtaManager::FETCH_ERROR_HASH_ALGO: return "unsupported hash";
|
||||
case OtaManager::FETCH_ERROR_VERSION: return "not a newer version";
|
||||
case OtaManager::FETCH_ERROR_CODEC: return "unsupported codec";
|
||||
case OtaManager::FETCH_ERROR_GEOMETRY: return "invalid geometry";
|
||||
case OtaManager::FETCH_ERROR_TOO_LARGE: return "image too large";
|
||||
@@ -1051,8 +1052,23 @@ static bool handle_dev(const char* d, char* reply, OtaContext& c) {
|
||||
sprintf(reply, "OK serving | root=%d payload=%d img=%d sig=%d trust=%d",
|
||||
r.root_ok, r.payload_ok, r.image_ok, r.sig_ok, r.trusted);
|
||||
|
||||
} else if (strncmp(d, "resume", 6) == 0) { // re-adopt a container already staged in flash (test/debug)
|
||||
bool ok = c.manager.resumeStaged(nullptr);
|
||||
} else if (is_cmd(d, "resume", &d)) { // explicit re-adopt of a known/active staged MID (test/debug)
|
||||
uint8_t mid[4];
|
||||
if (*d) {
|
||||
if (!parse_hex_exact(d, mid, sizeof(mid))) {
|
||||
strcpy(reply, "ERR usage: ota dev resume [mid8]");
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
// With no argument, reuse only an active/requested session MID. After a reboot the operator must
|
||||
// name the persisted MID explicitly; nullptr is reserved for policy-governed automatic adoption.
|
||||
if (c.manager.fetchState() == OtaManager::IDLE) {
|
||||
strcpy(reply, "ERR usage: ota dev resume <mid8>");
|
||||
return true;
|
||||
}
|
||||
memcpy(mid, c.manager.fetchManifestId(), sizeof(mid));
|
||||
}
|
||||
bool ok = c.manager.resumeStagedExplicit(mid, 0);
|
||||
sprintf(reply, "%s resume: sess=%c %u/%u", ok ? "OK" : "ERR", fstate_char(c.manager.fetchState()),
|
||||
(unsigned)c.manager.blocksHave(), (unsigned)c.manager.blocksTotal());
|
||||
|
||||
@@ -1125,7 +1141,7 @@ static bool handle_dev(const char* d, char* reply, OtaContext& c) {
|
||||
strcpy(reply, "OK cleared");
|
||||
|
||||
} else {
|
||||
strcpy(reply, "ota dev: stage|recv|serve|announce|verify|want|apply slot|manifest|verify|commit|clear");
|
||||
strcpy(reply, "ota dev: stage|recv|serve|announce|resume [mid8]|verify|want|apply|clear");
|
||||
}
|
||||
#endif
|
||||
return true;
|
||||
|
||||
@@ -146,7 +146,13 @@ struct OtaContext {
|
||||
// so the deferred-reboot path (mesh loop) takes over. Caller ensures the fetch is COMPLETE. Shared by
|
||||
// manual `ota applydelta` and the auto-install path.
|
||||
bool apply_fetched(char* msg) {
|
||||
return apply_fetched_impl(nullptr, msg);
|
||||
return apply_fetched_impl(nullptr, false, msg);
|
||||
}
|
||||
|
||||
// Automatic installation has an additional anti-replay/rollback gate. Manual `ota install` remains
|
||||
// the deliberate operator override for equal or older signed firmware.
|
||||
bool apply_fetched_trusted_auto(char* msg) {
|
||||
return apply_fetched_impl(nullptr, true, msg);
|
||||
}
|
||||
|
||||
// Explicit recovery entry point for an internal-flash nRF52 whose normal EndF validation fails. This
|
||||
@@ -158,11 +164,11 @@ struct OtaContext {
|
||||
msg[95] = 0;
|
||||
return false;
|
||||
#else
|
||||
return apply_fetched_impl(operator_base_hash, msg);
|
||||
return apply_fetched_impl(operator_base_hash, false, msg);
|
||||
#endif
|
||||
}
|
||||
|
||||
bool apply_fetched_impl(const uint8_t* rescue_base_hash, char* msg) {
|
||||
bool apply_fetched_impl(const uint8_t* rescue_base_hash, bool trusted_auto, char* msg) {
|
||||
if (fetch_to_folder) {
|
||||
strncpy(msg, "refused: completed fetch was captured to a folder, not local install storage", 96);
|
||||
msg[95] = 0;
|
||||
@@ -209,6 +215,21 @@ struct OtaContext {
|
||||
strncpy(msg, "refused: use ota bootloader install <MID8> <HASH16>", 96);
|
||||
msg[95] = 0; return false;
|
||||
}
|
||||
if (trusted_auto) {
|
||||
SelfFwInfo self;
|
||||
if (!mm.is_signed()) {
|
||||
strncpy(msg, "refused: trusted auto-install requires a signed package", 96);
|
||||
msg[95] = 0; return false;
|
||||
}
|
||||
if (!ota_self_firmware(self) || !self.valid ||
|
||||
!ota_trusted_auto_version_allows(self.fw_version, mm.fw_version)) {
|
||||
snprintf(msg, 96,
|
||||
"refused: trusted auto-install is forward-only (running=%08lX candidate=%08lX); use ota install to override",
|
||||
(unsigned long)(self.valid ? self.fw_version : 0),
|
||||
(unsigned long)mm.fw_version);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!hwMatches(mm.hw_id)) {
|
||||
char want[33] = {0}; memcpy(want, mm.hw_id, 32);
|
||||
snprintf(msg, 96, "refused: .mota hw_id '%.32s' != this device '%s' (incompatible hardware)", want, hw_id);
|
||||
@@ -501,6 +522,7 @@ struct OtaContext {
|
||||
target_id = 0;
|
||||
#endif
|
||||
manager.begin(target_id, send, ctx);
|
||||
manager.set_auto_version_floor(_fi.valid ? _fi.fw_version : 0, true);
|
||||
fetch_to_folder = false;
|
||||
if (hw) { strncpy(hw_id, hw, sizeof(hw_id) - 1); hw_id[sizeof(hw_id) - 1] = 0; }
|
||||
// a node only fetches firmware it can apply: ESP32 A/B -> sequential, nRF52 single-slot -> in-place
|
||||
|
||||
@@ -68,6 +68,12 @@ struct FwVersion {
|
||||
}
|
||||
};
|
||||
|
||||
inline bool ota_trusted_auto_version_allows(uint32_t running_version,
|
||||
uint32_t candidate_version) {
|
||||
return running_version != 0 && candidate_version != 0 &&
|
||||
candidate_version > running_version;
|
||||
}
|
||||
|
||||
// ---- hash truncations -----------------------------------------------------
|
||||
static const uint8_t MH4 = 4; // sha2-256:4 (merkle leaves/nodes/root/proofs)
|
||||
static const uint8_t MH8 = 8; // sha2-256:8 (base/EndF body hash)
|
||||
|
||||
@@ -901,7 +901,7 @@ void OtaManager::handleHave(const uint8_t* m, uint16_t n) {
|
||||
if (c.seeder_have[k] > c.have_max) c.have_max = c.seeder_have[k];
|
||||
if (c.seeder_last_ms[k] > c.last_ms) c.last_ms = c.seeder_last_ms[k];
|
||||
}
|
||||
if (wantRow(mid, target, codec, flags)) startFetch(mid, target);
|
||||
if (wantRow(mid, target, fwver, codec, flags)) startFetch(mid, target);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -916,7 +916,8 @@ void OtaManager::deferCatalog(const uint8_t mid[4], uint32_t until_ms) {
|
||||
}
|
||||
}
|
||||
|
||||
bool OtaManager::wantRow(const uint8_t* mid, uint32_t target, uint8_t codec, uint8_t flags) const {
|
||||
bool OtaManager::wantRow(const uint8_t* mid, uint32_t target, uint32_t fw_version,
|
||||
uint8_t codec, uint8_t flags) const {
|
||||
if (!_fetch || _fstate == FETCHING || _fstate == WANT_MANIFEST
|
||||
|| _fstate == WANT_LEAVES || _fstate == VERIFYING_STAGED
|
||||
|| _fstate == PAUSED) return false; // busy
|
||||
@@ -931,6 +932,8 @@ bool OtaManager::wantRow(const uint8_t* mid, uint32_t target, uint8_t codec, uin
|
||||
if (_autofetch == AUTOFETCH_OFF) return false; // discover only
|
||||
if (target != _target) return false; // auto-fetch = our own target
|
||||
if (_autofetch == AUTOFETCH_SIGNED && !(flags & MFLAG_SIGNED)) return false; // signed-only policy
|
||||
if (_enforce_auto_version &&
|
||||
!ota_trusted_auto_version_allows(_running_fw_version, fw_version)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1068,6 +1071,7 @@ void OtaManager::clearFetchIntent() {
|
||||
_desired_target = 0;
|
||||
_have_desired_mid = false;
|
||||
memset(_desired_mid, 0, sizeof(_desired_mid));
|
||||
_fexpected_target = 0;
|
||||
}
|
||||
|
||||
void OtaManager::failFetch(FetchError error) {
|
||||
@@ -1121,11 +1125,11 @@ OtaManager::PullResult OtaManager::pull_archive(const uint8_t* mid, uint32_t tar
|
||||
|
||||
// Begin (or resume) fetching a chosen mid: try a staged-partial resume first, else request the manifest.
|
||||
OtaManager::PullResult OtaManager::startFetch(const uint8_t* mid, uint32_t target, bool validate) {
|
||||
(void)target;
|
||||
if (!mid) return PULL_BAD_MID;
|
||||
if (!_fetch) return PULL_NO_STORE;
|
||||
if (fetchActive()) return PULL_BUSY;
|
||||
_fetch_error = FETCH_ERROR_NONE;
|
||||
_fexpected_target = target;
|
||||
_validate = validate; // motatool folder-capture warm-start (seed leaf-diff)
|
||||
// A validate pull is a FRESH seed capture, not a resume: the store already holds the seed's payload (not a
|
||||
// real partial), so never adopt it via resumeStaged - always re-begin and run the manifest->leaves->diff.
|
||||
@@ -1142,6 +1146,20 @@ OtaManager::PullResult OtaManager::startFetch(const uint8_t* mid, uint32_t targe
|
||||
return PULL_STARTED;
|
||||
}
|
||||
|
||||
bool OtaManager::resumeStagedExplicit(const uint8_t* want_mid, uint32_t expected_target) {
|
||||
if (!want_mid || !_fetch || fetchActive()) return false;
|
||||
_fetch_error = FETCH_ERROR_NONE;
|
||||
_validate = false;
|
||||
_archive_fetch = false;
|
||||
_desired_target = expected_target;
|
||||
memcpy(_desired_mid, want_mid, sizeof(_desired_mid));
|
||||
_have_desired_mid = true;
|
||||
_fexpected_target = expected_target;
|
||||
const bool adopted = resumeStaged(want_mid);
|
||||
if (!adopted) clearFetchIntent();
|
||||
return adopted;
|
||||
}
|
||||
|
||||
void OtaManager::handleManifest(const uint8_t* m, uint16_t n) {
|
||||
ManifestMsg mm;
|
||||
if (!decode_manifest(m, n, mm) || !_fetch) return;
|
||||
@@ -1174,6 +1192,24 @@ void OtaManager::handleManifest(const uint8_t* m, uint16_t n) {
|
||||
if (mfl != MOTA_MFL) { failFetch(FETCH_ERROR_MANIFEST); return; } // fixed 197-byte manifest
|
||||
MotaManifest parsed;
|
||||
if (!mota_parse_manifest(mf, mfl, parsed)) { failFetch(FETCH_ERROR_MANIFEST); return; }
|
||||
// The OTA_MANIFEST envelope is supplied by the peer and is not an authenticated description of the
|
||||
// bytes inside it. Bind both identifiers from the parsed manifest to the catalog row / explicit pull
|
||||
// that opened this receive slot before the store is planned, erased, or written. Otherwise a peer can
|
||||
// label an unrelated manifest with the requested MID and make us stage a different target/package.
|
||||
if (memcmp(parsed.merkle_root, _fid, sizeof(_fid)) != 0 ||
|
||||
(_fexpected_target != 0 && parsed.target_id != _fexpected_target)) {
|
||||
failFetch(FETCH_ERROR_MANIFEST); return;
|
||||
}
|
||||
// A HAVE row is advisory and may lie about its version. Repeat the
|
||||
// forward-only check against the parsed manifest before touching storage.
|
||||
const bool automatic_fetch = !_have_desired_mid && _desired_target == 0 && !_archive_fetch;
|
||||
if (_enforce_auto_version && automatic_fetch &&
|
||||
!ota_trusted_auto_version_allows(_running_fw_version, parsed.fw_version)) {
|
||||
failFetch(FETCH_ERROR_VERSION); return;
|
||||
}
|
||||
if (automatic_fetch && _autofetch == AUTOFETCH_SIGNED && !parsed.is_signed()) {
|
||||
failFetch(FETCH_ERROR_MANIFEST); return;
|
||||
}
|
||||
if (parsed.hash_algo != HASH_ALGO_SHA256) { failFetch(FETCH_ERROR_HASH_ALGO); return; }
|
||||
if (!_archive_fetch &&
|
||||
!fetchCodecOk(parsed.codec_id, parsed.is_bootloader(), _have_desired_mid)) {
|
||||
@@ -1190,7 +1226,7 @@ void OtaManager::handleManifest(const uint8_t* m, uint16_t n) {
|
||||
if (_archive_fetch && (uint64_t)bc * 4 > OTA_PROOFGEN_SCRATCH) {
|
||||
failFetch(FETCH_ERROR_TOO_LARGE); return; // retaining an image we cannot seed is useless
|
||||
}
|
||||
memcpy(_froot, mf + 20, 4);
|
||||
memcpy(_froot, parsed.merkle_root, sizeof(_froot));
|
||||
|
||||
uint32_t leaves_off = 8 + mfl;
|
||||
uint32_t payload_off = leaves_off + bc * 4;
|
||||
@@ -1324,6 +1360,18 @@ bool OtaManager::resumeStaged(const uint8_t* want_mid) {
|
||||
MotaManifest m;
|
||||
if (!_fetch->read(8, mbuf, mread) || !mota_parse_manifest(mbuf, mread, m)) return false;
|
||||
if (want_mid && memcmp(m.merkle_root, want_mid, 4) != 0) return false; // a different fw is staged
|
||||
const bool automatic_resume = want_mid == nullptr;
|
||||
// A boot-time resume is an automatic fetch decision and therefore belongs
|
||||
// only to this node. An explicit pull retains target=0 as an intentional
|
||||
// MID-only wildcard instead of silently narrowing it to the local target.
|
||||
const uint32_t expected_target = automatic_resume ? _target : _fexpected_target;
|
||||
if (expected_target != 0 && m.target_id != expected_target) return false;
|
||||
if (automatic_resume) {
|
||||
if (_autofetch == AUTOFETCH_OFF) return false;
|
||||
if (_autofetch == AUTOFETCH_SIGNED && !m.is_signed()) return false;
|
||||
if (_enforce_auto_version &&
|
||||
!ota_trusted_auto_version_allows(_running_fw_version, m.fw_version)) return false;
|
||||
}
|
||||
if (m.hash_algo != HASH_ALGO_SHA256) return false;
|
||||
// A bootloader partial is resumed only as part of the same explicit MID pull.
|
||||
// Boot-time resumeStaged(nullptr) must not silently re-adopt privileged data.
|
||||
|
||||
@@ -221,6 +221,7 @@ public:
|
||||
FETCH_ERROR_NONE,
|
||||
FETCH_ERROR_MANIFEST,
|
||||
FETCH_ERROR_HASH_ALGO,
|
||||
FETCH_ERROR_VERSION,
|
||||
FETCH_ERROR_CODEC,
|
||||
FETCH_ERROR_GEOMETRY,
|
||||
FETCH_ERROR_TOO_LARGE,
|
||||
@@ -302,13 +303,19 @@ public:
|
||||
// --- fetch --- Provide the staging store; fetching starts on a matching OTA_ADV.
|
||||
void set_fetch_store(OtaStore* s) { _fetch = s; }
|
||||
|
||||
// Resume a fetch from a container already persisted in the store (after a reboot). want_mid=nullptr
|
||||
// accepts whatever is staged; otherwise only resumes if the staged manifest_id matches. Re-parses the
|
||||
// stored manifest, recomputes geometry, then incrementally rehashes every staged payload block before
|
||||
// continuing FETCHING the holes. A fully staged image also has to reproduce the manifest Merkle root
|
||||
// before it can become COMPLETE. Returns true if it adopted a staged container.
|
||||
// Resume a fetch from a container already persisted in the store (after a reboot). want_mid=nullptr is
|
||||
// automatic adoption and rechecks current autofetch/target/version policy; a non-null MID is an explicit
|
||||
// resume and must match exactly. Re-parses the stored manifest, recomputes geometry, then incrementally
|
||||
// rehashes every staged payload block before continuing FETCHING the holes. A fully staged image also has
|
||||
// to reproduce the manifest Merkle root before it can become COMPLETE. Returns true if it adopted one.
|
||||
bool resumeStaged(const uint8_t* want_mid);
|
||||
|
||||
// Explicit operator/debug re-adoption of one known MID without starting a network fetch. This installs
|
||||
// the same manual intent used by pull(), so target=0 remains a deliberate wildcard and bootloader FULL
|
||||
// containers are eligible for the separately authenticated manual path. Unlike resumeStaged(nullptr),
|
||||
// this never applies boot-time autofetch/version policy.
|
||||
bool resumeStagedExplicit(const uint8_t* want_mid, uint32_t expected_target = 0);
|
||||
|
||||
// Manual cross-target override (decision: deliberate role switch, e.g. companion -> repeater on the
|
||||
// same hardware). Normally a node only auto-fetches its OWN target_id; `want(T)` makes it accept an
|
||||
// ADV for target T instead (T=0 restores auto). The user takes responsibility for HW compatibility;
|
||||
@@ -377,6 +384,10 @@ public:
|
||||
static const uint8_t AUTOFETCH_OFF = 0, AUTOFETCH_ANY = 1, AUTOFETCH_SIGNED = 2;
|
||||
void set_autofetch(uint8_t p) { _autofetch = p; reDiscover(); }
|
||||
uint8_t autofetch() const { return _autofetch; }
|
||||
void set_auto_version_floor(uint32_t running_version, bool enforce = true) {
|
||||
_running_fw_version = running_version;
|
||||
_enforce_auto_version = enforce;
|
||||
}
|
||||
// A persistent archive needs full catalogs even when install-oriented autofetch is off.
|
||||
void set_archive_interest(bool on) {
|
||||
if (_archive_interest != on) { _archive_interest = on; reDiscover(); }
|
||||
@@ -488,7 +499,8 @@ private:
|
||||
bool handleReqProof(const uint8_t* m, uint16_t n);
|
||||
bool handleProof(const uint8_t* m, uint16_t n);
|
||||
PullResult startFetch(const uint8_t* mid, uint32_t target, bool validate = false); // begin/resume a fetch
|
||||
bool wantRow(const uint8_t* mid, uint32_t target, uint8_t codec, uint8_t flags) const; // fetch this row?
|
||||
bool wantRow(const uint8_t* mid, uint32_t target, uint32_t fw_version,
|
||||
uint8_t codec, uint8_t flags) const; // fetch this row?
|
||||
bool fetchActive() const;
|
||||
void clearFetchIntent();
|
||||
void failFetch(FetchError error);
|
||||
@@ -599,6 +611,7 @@ private:
|
||||
FetchError _fetch_error = FETCH_ERROR_NONE;
|
||||
uint8_t _fid[4] = {0};
|
||||
uint8_t _froot[4] = {0};
|
||||
uint32_t _fexpected_target = 0; // catalog/CLI target bound to the requested manifest
|
||||
uint32_t _ftotal = 0, _fpoff = 0, _floff = 0, _fpsize = 0, _fbc = 0, _fbs = 0;
|
||||
uint32_t _have = 0;
|
||||
uint32_t _resume_verify_idx = 0;
|
||||
@@ -616,6 +629,8 @@ private:
|
||||
bool _archive_interest = false; // query full catalogs for the persistent archive
|
||||
uint8_t _seeder_id[4] = {0,0,0,0}; // our node id (pubkey[0:4]) for advert seeder counting
|
||||
uint8_t _autofetch = AUTOFETCH_OFF; // auto-fetch policy (persisted in NodePrefs)
|
||||
uint32_t _running_fw_version = 0; // trusted EndF version used only for automatic admission
|
||||
bool _enforce_auto_version = false; // OtaContext enables this even when EndF/version is unknown
|
||||
uint16_t _checkpoint_blocks = OTA_CHECKPOINT_BLOCKS; // resume checkpoint cadence (persisted)
|
||||
uint16_t _advert_mins = OTA_ADVERT_INTERVAL_MINS; // beacon re-advertise cadence, minutes; 0=off (persisted)
|
||||
uint8_t _max_hops = OTA_HOP_LIMIT_DEFAULT; // OTA flood reach in hops; 0=direct only (persisted)
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
// Reset-retained authorization shared byte-for-byte with OTAFIX. This record is intentionally in MCU RAM,
|
||||
// not on removable media: the application publishes it only after authenticating/verifying the exact SD
|
||||
// container, and OTAFIX consumes it before trusting any card geometry or bytes. A power cycle erases it.
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
static const uintptr_t MOTA_SD_AUTH_ADDR = 0x20006008u;
|
||||
static const uint32_t MOTA_SD_AUTH_SECTOR_SIZE = 512u;
|
||||
static const uint16_t MOTA_SD_AUTH_VERSION = 2u;
|
||||
static const uint16_t MOTA_SD_AUTH_LEN = 72u;
|
||||
static const uint8_t MOTA_SD_AUTH_PURPOSE_APP = 1u;
|
||||
static const uint8_t MOTA_SD_AUTH_PURPOSE_BOOTLOADER = 2u;
|
||||
static const uint8_t MOTA_SD_AUTH_MAGIC[8] = {
|
||||
'M', 'O', 'T', 'A', 'S', 'D', 'A', '2'
|
||||
};
|
||||
|
||||
inline uint16_t mota_sd_auth_rd16(const uint8_t* p) {
|
||||
return (uint16_t)p[0] | ((uint16_t)p[1] << 8);
|
||||
}
|
||||
|
||||
inline uint32_t mota_sd_auth_rd32(const uint8_t* p) {
|
||||
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
|
||||
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
|
||||
inline void mota_sd_auth_wr16(uint8_t* p, uint16_t value) {
|
||||
p[0] = (uint8_t)value;
|
||||
p[1] = (uint8_t)(value >> 8);
|
||||
}
|
||||
|
||||
inline void mota_sd_auth_wr32(uint8_t* p, uint32_t value) {
|
||||
p[0] = (uint8_t)value;
|
||||
p[1] = (uint8_t)(value >> 8);
|
||||
p[2] = (uint8_t)(value >> 16);
|
||||
p[3] = (uint8_t)(value >> 24);
|
||||
}
|
||||
|
||||
inline uint32_t mota_sd_auth_crc32(const uint8_t* data, size_t len) {
|
||||
uint32_t crc = 0xFFFFFFFFu;
|
||||
for (size_t i = 0; i < len; ++i) {
|
||||
crc ^= data[i];
|
||||
for (uint8_t bit = 0; bit < 8; ++bit)
|
||||
crc = (crc >> 1) ^ (0xEDB88320u & (uint32_t)-(int32_t)(crc & 1u));
|
||||
}
|
||||
return ~crc;
|
||||
}
|
||||
|
||||
inline bool mota_sd_auth_geometry_valid(uint32_t first_lba, uint32_t sector_count,
|
||||
uint32_t container_total, uint32_t card_sectors) {
|
||||
const uint64_t needed = ((uint64_t)container_total + MOTA_SD_AUTH_SECTOR_SIZE - 1u) /
|
||||
MOTA_SD_AUTH_SECTOR_SIZE;
|
||||
return first_lba != 0 && sector_count != 0 && container_total != 0 &&
|
||||
card_sectors != 0 && needed == sector_count &&
|
||||
first_lba < card_sectors && sector_count <= card_sectors - first_lba;
|
||||
}
|
||||
|
||||
inline bool mota_sd_auth_encode(uint8_t out[MOTA_SD_AUTH_LEN], uint8_t purpose,
|
||||
uint8_t format, uint32_t first_lba,
|
||||
uint32_t sector_count, uint32_t container_total,
|
||||
uint32_t card_sectors,
|
||||
const uint8_t container_sha256[32]) {
|
||||
if (!out || !container_sha256 ||
|
||||
(purpose != MOTA_SD_AUTH_PURPOSE_APP &&
|
||||
purpose != MOTA_SD_AUTH_PURPOSE_BOOTLOADER) ||
|
||||
((purpose == MOTA_SD_AUTH_PURPOSE_APP && format != 2u) ||
|
||||
(purpose == MOTA_SD_AUTH_PURPOSE_BOOTLOADER && format != 3u)) ||
|
||||
!mota_sd_auth_geometry_valid(first_lba, sector_count, container_total, card_sectors))
|
||||
return false;
|
||||
memset(out, 0, MOTA_SD_AUTH_LEN);
|
||||
memcpy(out, MOTA_SD_AUTH_MAGIC, sizeof(MOTA_SD_AUTH_MAGIC));
|
||||
mota_sd_auth_wr16(out + 8u, MOTA_SD_AUTH_VERSION);
|
||||
mota_sd_auth_wr16(out + 10u, MOTA_SD_AUTH_LEN);
|
||||
out[12] = purpose;
|
||||
out[13] = format;
|
||||
mota_sd_auth_wr32(out + 16u, first_lba);
|
||||
mota_sd_auth_wr32(out + 20u, sector_count);
|
||||
mota_sd_auth_wr32(out + 24u, container_total);
|
||||
mota_sd_auth_wr32(out + 28u, card_sectors);
|
||||
memcpy(out + 32u, container_sha256, 32u);
|
||||
const uint32_t crc = mota_sd_auth_crc32(out, 64u);
|
||||
mota_sd_auth_wr32(out + 64u, crc);
|
||||
mota_sd_auth_wr32(out + 68u, ~crc);
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool mota_sd_auth_valid(const uint8_t record[MOTA_SD_AUTH_LEN]) {
|
||||
if (!record || memcmp(record, MOTA_SD_AUTH_MAGIC, sizeof(MOTA_SD_AUTH_MAGIC)) != 0 ||
|
||||
mota_sd_auth_rd16(record + 8u) != MOTA_SD_AUTH_VERSION ||
|
||||
mota_sd_auth_rd16(record + 10u) != MOTA_SD_AUTH_LEN ||
|
||||
mota_sd_auth_rd16(record + 14u) != 0 ||
|
||||
((record[12] == MOTA_SD_AUTH_PURPOSE_APP && record[13] != 2u) ||
|
||||
(record[12] == MOTA_SD_AUTH_PURPOSE_BOOTLOADER && record[13] != 3u) ||
|
||||
(record[12] != MOTA_SD_AUTH_PURPOSE_APP &&
|
||||
record[12] != MOTA_SD_AUTH_PURPOSE_BOOTLOADER)))
|
||||
return false;
|
||||
const uint32_t crc = mota_sd_auth_rd32(record + 64u);
|
||||
return mota_sd_auth_geometry_valid(mota_sd_auth_rd32(record + 16u),
|
||||
mota_sd_auth_rd32(record + 20u),
|
||||
mota_sd_auth_rd32(record + 24u),
|
||||
mota_sd_auth_rd32(record + 28u)) &&
|
||||
mota_sd_auth_crc32(record, 64u) == crc &&
|
||||
mota_sd_auth_rd32(record + 68u) == ~crc;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -1,64 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
// On-card handoff shared with Adafruit_nRF52_Bootloader_OTAFIX. The staged
|
||||
// .mota is a normal, contiguous filesystem file. Sector 1 is in the unused
|
||||
// gap between the MBR and the first partition and tells the bootloader where
|
||||
// that file's sectors live. Cards without such a gap are rejected.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
static const uint32_t MOTA_SD_SECTOR_SIZE = 512u;
|
||||
static const uint32_t MOTA_SD_HANDOFF_SECTOR = 1u;
|
||||
static const uint32_t MOTA_SD_HANDOFF_VERSION = 1u;
|
||||
static const uint32_t MOTA_SD_HANDOFF_LEN = 36u;
|
||||
static const uint8_t MOTA_SD_HANDOFF_MAGIC[8] = {
|
||||
'M', 'O', 'T', 'A', 'S', 'D', '0', '1'
|
||||
};
|
||||
|
||||
inline uint32_t mota_sd_rd32(const uint8_t* p) {
|
||||
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
|
||||
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
|
||||
inline void mota_sd_wr32(uint8_t* p, uint32_t v) {
|
||||
p[0] = (uint8_t)v;
|
||||
p[1] = (uint8_t)(v >> 8);
|
||||
p[2] = (uint8_t)(v >> 16);
|
||||
p[3] = (uint8_t)(v >> 24);
|
||||
}
|
||||
|
||||
inline uint32_t mota_sd_crc32(const uint8_t* data, size_t len) {
|
||||
uint32_t crc = 0xFFFFFFFFu;
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
crc ^= data[i];
|
||||
for (uint8_t bit = 0; bit < 8; bit++) {
|
||||
crc = (crc >> 1) ^ (0xEDB88320u & (uint32_t)-(int32_t)(crc & 1u));
|
||||
}
|
||||
}
|
||||
return ~crc;
|
||||
}
|
||||
|
||||
inline void mota_sd_encode_handoff(uint8_t sector[MOTA_SD_SECTOR_SIZE],
|
||||
uint32_t first_sector,
|
||||
uint32_t sector_count,
|
||||
uint32_t total_size,
|
||||
uint32_t card_sectors) {
|
||||
// Only own the record bytes. The caller preserves the rest of sector 1 in
|
||||
// case a card formatter placed non-partition metadata there.
|
||||
for (uint32_t i = 0; i < MOTA_SD_HANDOFF_LEN; i++) sector[i] = 0xFF;
|
||||
for (uint8_t i = 0; i < 8; i++) sector[i] = MOTA_SD_HANDOFF_MAGIC[i];
|
||||
mota_sd_wr32(sector + 8, MOTA_SD_HANDOFF_VERSION);
|
||||
mota_sd_wr32(sector + 12, first_sector);
|
||||
mota_sd_wr32(sector + 16, sector_count);
|
||||
mota_sd_wr32(sector + 20, total_size);
|
||||
mota_sd_wr32(sector + 24, ~total_size);
|
||||
mota_sd_wr32(sector + 28, card_sectors);
|
||||
mota_sd_wr32(sector + 32, mota_sd_crc32(sector, 32));
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -12,8 +12,8 @@
|
||||
#include "OtaBootloaderUpdate.h"
|
||||
#include "OtaByteIO.h"
|
||||
#include "OtaFlashLayout_nrf52.h"
|
||||
#include "OtaSdAuthRecord.h"
|
||||
#include "OtaSdBootToken.h"
|
||||
#include "OtaSdHandoff.h"
|
||||
#include "OtaSelf.h"
|
||||
#include "flash/flash_nrf5x.h"
|
||||
|
||||
@@ -27,10 +27,45 @@
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
namespace {
|
||||
|
||||
static void clear_sd_auth_record() {
|
||||
volatile uint8_t* const retained =
|
||||
reinterpret_cast<volatile uint8_t*>(MOTA_SD_AUTH_ADDR);
|
||||
for (uint32_t i = 0; i < MOTA_SD_AUTH_LEN; ++i) retained[i] = 0;
|
||||
__DMB();
|
||||
__DSB();
|
||||
}
|
||||
|
||||
static bool publish_sd_auth_record(const uint8_t record[MOTA_SD_AUTH_LEN]) {
|
||||
volatile uint8_t* const retained =
|
||||
reinterpret_cast<volatile uint8_t*>(MOTA_SD_AUTH_ADDR);
|
||||
// Invalidate magic first, then publish the body and magic last. A reset at any
|
||||
// intermediate instruction therefore leaves a record OTAFIX rejects.
|
||||
for (uint32_t i = 0; i < sizeof(MOTA_SD_AUTH_MAGIC); ++i) retained[i] = 0;
|
||||
__DMB();
|
||||
for (uint32_t i = sizeof(MOTA_SD_AUTH_MAGIC); i < MOTA_SD_AUTH_LEN; ++i)
|
||||
retained[i] = record[i];
|
||||
__DMB();
|
||||
for (uint32_t i = 0; i < sizeof(MOTA_SD_AUTH_MAGIC); ++i) retained[i] = record[i];
|
||||
__DMB();
|
||||
__DSB();
|
||||
for (uint32_t i = 0; i < MOTA_SD_AUTH_LEN; ++i)
|
||||
if (retained[i] != record[i]) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
const char* const OtaStoreSdNrf52::PATH = "/meshcore-ota.mota";
|
||||
|
||||
OtaStoreSdNrf52::OtaStoreSdNrf52()
|
||||
: _sd(new (std::nothrow) SdFs()), _file(new (std::nothrow) FsFile()) {}
|
||||
: _sd(new (std::nothrow) SdFs()), _file(new (std::nothrow) FsFile()) {
|
||||
// If an earlier reset did not enter OTAFIX, stale authorization must not arm a
|
||||
// later unrelated reboot. OTAFIX runs before application constructors and
|
||||
// consumes a valid record on the intended apply boot.
|
||||
clear_sd_auth_record();
|
||||
}
|
||||
|
||||
OtaStoreSdNrf52::~OtaStoreSdNrf52() {
|
||||
if (_file) { _file->close(); delete _file; }
|
||||
@@ -46,8 +81,6 @@ void OtaStoreSdNrf52::resetStoreState() {
|
||||
_total = 0;
|
||||
_first_sector = 0;
|
||||
_allocated_sectors = 0;
|
||||
_partition_start = 0;
|
||||
_partition_end = 0;
|
||||
_planned_bootloader = false;
|
||||
if (_file && *_file) _file->close();
|
||||
if (_sd) _sd->end();
|
||||
@@ -75,15 +108,11 @@ bool OtaStoreSdNrf52::mount() {
|
||||
return false;
|
||||
}
|
||||
_mounted = true;
|
||||
if (!inspect_mbr()) {
|
||||
_sd->end();
|
||||
_mounted = false;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool OtaStoreSdNrf52::formatCard(MainBoard& board) {
|
||||
clear_sd_auth_record();
|
||||
if (!beginCardOnly()) return false;
|
||||
|
||||
board.serviceWatchdog();
|
||||
@@ -100,22 +129,12 @@ bool OtaStoreSdNrf52::formatCard(MainBoard& board) {
|
||||
}
|
||||
|
||||
_mounted = true;
|
||||
if (!inspect_mbr()) {
|
||||
_sd->end();
|
||||
_mounted = false;
|
||||
return false;
|
||||
}
|
||||
if (!invalidate_handoff()) {
|
||||
fail("SD handoff clear failed");
|
||||
_sd->end();
|
||||
_mounted = false;
|
||||
return false;
|
||||
}
|
||||
board.serviceWatchdog();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool OtaStoreSdNrf52::eraseCard(MainBoard& board) {
|
||||
clear_sd_auth_record();
|
||||
if (!beginCardOnly()) return false;
|
||||
|
||||
SdCard* card = _sd->card();
|
||||
@@ -312,58 +331,18 @@ bool OtaStoreSdNrf52::listFiles(MainBoard& board, uint16_t page,
|
||||
return true;
|
||||
}
|
||||
|
||||
bool OtaStoreSdNrf52::inspect_mbr() {
|
||||
uint8_t sector[MOTA_SD_SECTOR_SIZE];
|
||||
if (!_sd->card() || !_sd->card()->readSector(0, sector)) {
|
||||
fail("SD MBR read failed");
|
||||
return false;
|
||||
}
|
||||
if (sector[510] != 0x55 || sector[511] != 0xAA) {
|
||||
fail("SD must use an MBR partition table");
|
||||
return false;
|
||||
}
|
||||
|
||||
// SdFs mounts the first usable MBR partition. Require its start to leave
|
||||
// sector 1 unused; a protective GPT entry (type 0xEE) is not safe here.
|
||||
for (uint8_t i = 0; i < 4; i++) {
|
||||
const uint8_t* p = sector + 446 + (uint32_t)i * 16;
|
||||
uint8_t type = p[4];
|
||||
uint32_t start = mota_sd_rd32(p + 8);
|
||||
uint32_t count = mota_sd_rd32(p + 12);
|
||||
if (type == 0 || count == 0) continue;
|
||||
if (type == 0xEE || start <= MOTA_SD_HANDOFF_SECTOR ||
|
||||
start >= _sd->card()->sectorCount() ||
|
||||
count > _sd->card()->sectorCount() - start) {
|
||||
fail("SD needs an MBR partition starting after sector 1");
|
||||
return false;
|
||||
}
|
||||
_partition_start = start;
|
||||
_partition_end = start + count;
|
||||
return true;
|
||||
}
|
||||
fail("SD has no usable MBR partition");
|
||||
return false;
|
||||
}
|
||||
|
||||
bool OtaStoreSdNrf52::invalidate_handoff() {
|
||||
if (!_mounted || !_sd->card()) return false;
|
||||
uint8_t sector[MOTA_SD_SECTOR_SIZE];
|
||||
if (!_sd->card()->readSector(MOTA_SD_HANDOFF_SECTOR, sector)) return false;
|
||||
memset(sector, 0xFF, MOTA_SD_HANDOFF_LEN);
|
||||
return _sd->card()->writeSector(MOTA_SD_HANDOFF_SECTOR, sector) &&
|
||||
_sd->card()->syncDevice();
|
||||
}
|
||||
|
||||
bool OtaStoreSdNrf52::locate_file() {
|
||||
Sector_t first = 0, last = 0;
|
||||
if (!_file || !_file->contiguousRange(&first, &last) || last < first) {
|
||||
fail("OTA file is not contiguous");
|
||||
return false;
|
||||
}
|
||||
uint64_t need = ((uint64_t)_total + MOTA_SD_SECTOR_SIZE - 1) / MOTA_SD_SECTOR_SIZE;
|
||||
uint64_t need = ((uint64_t)_total + MOTA_SD_AUTH_SECTOR_SIZE - 1) /
|
||||
MOTA_SD_AUTH_SECTOR_SIZE;
|
||||
uint64_t available = (uint64_t)last - first + 1;
|
||||
if (need == 0 || need > available || first < _partition_start ||
|
||||
(uint64_t)first + need > _partition_end) {
|
||||
const uint32_t card_sectors = _sd->card() ? _sd->card()->sectorCount() : 0;
|
||||
if (need == 0 || need > available || first == 0 || card_sectors == 0 ||
|
||||
first >= card_sectors || need > card_sectors - first) {
|
||||
fail("OTA file sector range is invalid");
|
||||
return false;
|
||||
}
|
||||
@@ -401,11 +380,8 @@ bool OtaStoreSdNrf52::begin(uint32_t total_size) {
|
||||
_total = 0;
|
||||
_first_sector = 0;
|
||||
_allocated_sectors = 0;
|
||||
clear_sd_auth_record();
|
||||
if (total_size < 13 || !mount()) return false;
|
||||
if (!invalidate_handoff()) {
|
||||
fail("SD handoff clear failed");
|
||||
return false;
|
||||
}
|
||||
if (*_file) _file->close();
|
||||
_sd->remove(PATH);
|
||||
if (!_file->open(PATH, O_RDWR | O_CREAT | O_EXCL)) {
|
||||
@@ -460,12 +436,13 @@ bool OtaStoreSdNrf52::read(uint32_t offset, uint8_t* buf, uint32_t len) const {
|
||||
|
||||
uint32_t OtaStoreSdNrf52::capacity() const {
|
||||
if (!_mounted || !_sd || !_sd->card()) return 0;
|
||||
uint64_t bytes = (uint64_t)_sd->card()->sectorCount() * MOTA_SD_SECTOR_SIZE;
|
||||
uint64_t bytes = (uint64_t)_sd->card()->sectorCount() * MOTA_SD_AUTH_SECTOR_SIZE;
|
||||
return bytes > UINT32_MAX ? UINT32_MAX : (uint32_t)bytes;
|
||||
}
|
||||
|
||||
bool OtaStoreSdNrf52::finalize() {
|
||||
if (!_file || !*_file || !_file->sync() || !_sd->card()->syncDevice()) {
|
||||
SdCard* const card = _sd ? _sd->card() : nullptr;
|
||||
if (!_file || !*_file || !card || !_file->sync() || !card->syncDevice()) {
|
||||
fail("SD OTA sync failed");
|
||||
return false;
|
||||
}
|
||||
@@ -537,15 +514,22 @@ void OtaStoreSdNrf52::clear() {
|
||||
_planned_bootloader = false;
|
||||
_first_sector = 0;
|
||||
_allocated_sectors = 0;
|
||||
clear_sd_auth_record();
|
||||
if (!mount()) return;
|
||||
invalidate_handoff();
|
||||
if (_file && *_file) _file->close();
|
||||
_sd->remove(PATH);
|
||||
}
|
||||
|
||||
bool OtaStoreSdNrf52::approve_for_bootloader(
|
||||
const uint8_t expected_boot_image_hash[32]) {
|
||||
const uint8_t expected_boot_image_hash[32],
|
||||
const uint8_t authorized_container_hash[32]) {
|
||||
if (!_total || !finalize()) return false;
|
||||
if (!authorized_container_hash) {
|
||||
fail("missing authenticated SD container hash");
|
||||
return false;
|
||||
}
|
||||
SdCard* const card = _sd ? _sd->card() : nullptr;
|
||||
const uint32_t card_sectors = card ? card->sectorCount() : 0;
|
||||
#if defined(OTA_SD_BOOTLOADER_UPDATE)
|
||||
if (_planned_bootloader) {
|
||||
SelfFwInfo fi;
|
||||
@@ -563,7 +547,7 @@ bool OtaStoreSdNrf52::approve_for_bootloader(
|
||||
}
|
||||
#endif
|
||||
if (!write(8 + MOTA_OFF_APPROVAL, APPROVAL_YES, sizeof(APPROVAL_YES)) ||
|
||||
!_file->sync() || !_sd->card()->syncDevice()) {
|
||||
!_file->sync() || !card || !card->syncDevice()) {
|
||||
fail("SD approval write failed");
|
||||
return false;
|
||||
}
|
||||
@@ -591,16 +575,16 @@ bool OtaStoreSdNrf52::approve_for_bootloader(
|
||||
}
|
||||
#endif
|
||||
|
||||
uint8_t sector[MOTA_SD_SECTOR_SIZE];
|
||||
if (!_sd->card()->readSector(MOTA_SD_HANDOFF_SECTOR, sector)) {
|
||||
fail("SD handoff sector read failed");
|
||||
return false;
|
||||
}
|
||||
mota_sd_encode_handoff(sector, _first_sector, _allocated_sectors,
|
||||
_total, _sd->card()->sectorCount());
|
||||
if (!_sd->card()->writeSector(MOTA_SD_HANDOFF_SECTOR, sector) ||
|
||||
!_sd->card()->syncDevice()) {
|
||||
fail("SD bootloader handoff write failed");
|
||||
uint8_t auth[MOTA_SD_AUTH_LEN];
|
||||
const uint8_t purpose = _planned_bootloader
|
||||
? MOTA_SD_AUTH_PURPOSE_BOOTLOADER : MOTA_SD_AUTH_PURPOSE_APP;
|
||||
const uint8_t format = _planned_bootloader ? MOTA_BOOT_FORMAT_VER : MOTA_APP_FORMAT_VER;
|
||||
if (!mota_sd_auth_encode(auth, purpose, format, _first_sector,
|
||||
_allocated_sectors, _total, card_sectors,
|
||||
authorized_container_hash) ||
|
||||
!publish_sd_auth_record(auth)) {
|
||||
clear_sd_auth_record();
|
||||
fail("SD retained authorization publish failed");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -40,12 +40,13 @@ public:
|
||||
|
||||
// Called only after the app has verified package kind, payload, applicable
|
||||
// base/identity, signature, trust, and storage-specific safety geometry.
|
||||
// For a bootloader package it writes APRV, binds the exact authenticated
|
||||
// signed image_hash to an internal-flash token, and only then publishes the
|
||||
// raw-sector handoff. Application packages retain the ordinary APRV+handoff
|
||||
// path and omit expected_boot_image_hash.
|
||||
// Every package writes APRV, then publishes a reset-retained authorization
|
||||
// record containing geometry plus the normalized SHA-256 produced by the
|
||||
// same verification pass. Bootloader packages additionally bind the exact
|
||||
// authenticated signed image_hash to the E0000 scratch token.
|
||||
bool approve_for_bootloader(
|
||||
const uint8_t expected_boot_image_hash[32] = nullptr);
|
||||
const uint8_t expected_boot_image_hash[32],
|
||||
const uint8_t authorized_container_hash[32]);
|
||||
bool formatCard(MainBoard& board);
|
||||
bool eraseCard(MainBoard& board);
|
||||
bool getSpace(MainBoard& board, uint64_t& used_bytes, uint64_t& free_bytes);
|
||||
@@ -58,9 +59,7 @@ private:
|
||||
|
||||
bool mount();
|
||||
bool beginCardOnly();
|
||||
bool inspect_mbr();
|
||||
bool locate_file();
|
||||
bool invalidate_handoff();
|
||||
void resetStoreState();
|
||||
void fail(const char* message);
|
||||
|
||||
@@ -71,8 +70,6 @@ private:
|
||||
uint32_t _total = 0;
|
||||
uint32_t _first_sector = 0;
|
||||
uint32_t _allocated_sectors = 0;
|
||||
uint32_t _partition_start = 0;
|
||||
uint32_t _partition_end = 0;
|
||||
char _error[80] = {0};
|
||||
};
|
||||
|
||||
|
||||
@@ -60,6 +60,14 @@ static VerifyResult ota_verify_store(const OtaStore& store,
|
||||
}
|
||||
|
||||
r.parsed = true;
|
||||
// Bind the removable-media authorization to the exact stream verified below. Approval is the one mutable
|
||||
// field, so normalize its four bytes to zero: the digest remains stable after APRV is written and synced.
|
||||
SHA256 container_sha;
|
||||
static const uint8_t zero_approval[4] = {0, 0, 0, 0};
|
||||
container_sha.update(hdr, sizeof(hdr));
|
||||
container_sha.update(manifest, MOTA_OFF_APPROVAL);
|
||||
container_sha.update(zero_approval, sizeof(zero_approval));
|
||||
container_sha.update(leaves, leaves_len);
|
||||
uint8_t root[4];
|
||||
merkle_root(root, leaves, m.block_count);
|
||||
r.root_ok = memcmp(root, m.merkle_root, sizeof(root)) == 0;
|
||||
@@ -81,6 +89,7 @@ static VerifyResult ota_verify_store(const OtaStore& store,
|
||||
break;
|
||||
}
|
||||
if (m.is_full()) image_sha.update(block, n);
|
||||
container_sha.update(block, n);
|
||||
off += n;
|
||||
}
|
||||
if (off != m.payload_size) r.payload_ok = false;
|
||||
@@ -92,6 +101,12 @@ static VerifyResult ota_verify_store(const OtaStore& store,
|
||||
r.image_ok = !m.is_full();
|
||||
}
|
||||
|
||||
if (r.root_ok && r.payload_ok && r.image_ok) {
|
||||
container_sha.update(trailer, sizeof(trailer));
|
||||
container_sha.finalize(r.container_hash, sizeof(r.container_hash));
|
||||
r.container_hash_ok = true;
|
||||
}
|
||||
|
||||
r.is_signed = m.is_signed();
|
||||
if (r.is_signed) {
|
||||
mesh::Identity signer(m.signer_pubkey);
|
||||
|
||||
@@ -18,6 +18,8 @@ struct VerifyResult {
|
||||
bool is_signed = false;
|
||||
bool sig_ok = false; // Ed25519 signature valid for signer_pubkey
|
||||
bool trusted = false; // signer_pubkey is in the allowlist
|
||||
bool container_hash_ok = false; // normalized full-container SHA was produced from the verified stream
|
||||
uint8_t container_hash[32] = {0}; // SHA256(container with approval bytes normalized to zero)
|
||||
|
||||
// Integrity holds (safe to keep/serve). For a signed image, the signature must also verify.
|
||||
bool integrity_ok() const { return parsed && root_ok && payload_ok && image_ok && (!is_signed || sig_ok); }
|
||||
|
||||
Reference in new issue
Block a user