Procházet zdrojové kódy

add bounds check to _countLfsBlock / _getLfsUsedBlockCount

taco před 10 měsíci
rodič
revize
2922b62888
1 změnil soubory, kde provedl 15 přidání a 2 odebrání
  1. 15 2
      examples/companion_radio/DataStore.cpp

+ 15 - 2
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