@@ -313,6 +313,7 @@ void invalidateBootloaderSHA256Cache() {
313313// This matches the key validation steps from esp_image_verify() in ESP-IDF
314314// Returns the actual bootloader data pointer and length via the buffer and len parameters
315315bool verifyBootloaderImage (const uint8_t * &buffer, size_t &len, String* bootloaderErrorMsg) {
316+ size_t availableLen = len;
316317 if (!bootloaderErrorMsg) {
317318 DEBUG_PRINTLN (F (" bootloaderErrorMsg is null" ));
318319 return false ;
@@ -464,16 +465,22 @@ bool verifyBootloaderImage(const uint8_t* &buffer, size_t &len, String* bootload
464465 // If hash_appended != 0, there's a 32-byte SHA256 hash after the segments
465466 uint8_t hashAppended = buffer[23 ];
466467 if (hashAppended != 0 ) {
467- // SHA256 hash is appended (32 bytes)
468468 actualBootloaderSize += 32 ;
469+ if (actualBootloaderSize > availableLen) {
470+ *bootloaderErrorMsg = " Bootloader missing SHA256 trailer" ;
471+ return false ;
472+ }
469473 DEBUG_PRINTF_P (PSTR (" Bootloader has appended SHA256 hash\n " ));
470474 }
471475
472476 // 9. The image may also have a 1-byte checksum after segments/hash
473477 // Check if there's at least one more byte available
474- if (actualBootloaderSize < len ) {
478+ if (actualBootloaderSize + 1 <= availableLen ) {
475479 // There's likely a checksum byte
476480 actualBootloaderSize += 1 ;
481+ } else if (actualBootloaderSize > availableLen) {
482+ *bootloaderErrorMsg = " Bootloader truncated before checksum" ;
483+ return false ;
477484 }
478485
479486 // 10. Align to 16 bytes (ESP32 requirement for flash writes)
@@ -490,7 +497,12 @@ bool verifyBootloaderImage(const uint8_t* &buffer, size_t &len, String* bootload
490497 segmentCount, actualBootloaderSize, len, hashAppended);
491498
492499 // 11. Verify we have enough data for all segments + hash + checksum
493- if (offset > len) {
500+ if (actualBootloaderSize > availableLen) {
501+ *bootloaderErrorMsg = " Bootloader truncated - expected at least " + String (actualBootloaderSize) + " bytes, have " + String (availableLen) + " bytes" ;
502+ return false ;
503+ }
504+
505+ if (offset > availableLen) {
494506 *bootloaderErrorMsg = " Bootloader truncated - expected at least " + String (offset) + " bytes, have " + String (len) + " bytes" ;
495507 return false ;
496508 }
0 commit comments