From 2922b62888aafd32093f75d61430d6ae548599ff Mon Sep 17 00:00:00 2001 From: taco Date: Sat, 20 Sep 2025 17:36:52 +1000 Subject: [PATCH] add bounds check to _countLfsBlock / _getLfsUsedBlockCount --- examples/companion_radio/DataStore.cpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/examples/companion_radio/DataStore.cpp b/examples/companion_radio/DataStore.cpp index 7631b905..f1adb05e 100644 --- a/examples/companion_radio/DataStore.cpp +++ b/examples/companion_radio/DataStore.cpp @@ -42,12 +42,17 @@ static File openWrite(FILESYSTEM* fs, const char* filename) { #endif } +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + static uint32_t _ContactsChannelsTotalBlocks = 0; +#endif + void DataStore::begin() { #if defined(RP2040_PLATFORM) identity_store.begin(); #endif #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + _ContactsChannelsTotalBlocks = _getContactsChannelsFS()->_getFS()->cfg->block_count; checkAdvBlobFile(); #if defined(EXTRAFS) || defined(QSPIFLASH) migrateToSecondaryFS(); @@ -74,14 +79,22 @@ void DataStore::begin() { #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) int _countLfsBlock(void *p, lfs_block_t block){ + if (block > _ContactsChannelsTotalBlocks) { + MESH_DEBUG_PRINTLN("ERROR: Block %d exceeds filesystem bounds - CORRUPTION DETECTED!", block); + return LFS_ERR_CORRUPT; // return error to abort lfs_traverse() gracefully + } lfs_size_t *size = (lfs_size_t*) p; *size += 1; - return 0; + return 0; } lfs_ssize_t _getLfsUsedBlockCount(FILESYSTEM* fs) { lfs_size_t size = 0; - lfs_traverse(fs->_getFS(), _countLfsBlock, &size); + int err = lfs_traverse(fs->_getFS(), _countLfsBlock, &size); + if (err) { + MESH_DEBUG_PRINTLN("ERROR: lfs_traverse() error: %d", err); + return 0; + } return size; } #endif