Зашифрованный путь последовательного восстановления MCUboot содержит контролируемую злоумышленником запись стека out-of-bounds в decrypt_region_inplace() в boot/boot_serial/src/boot_serial_encryption.c. Обычная программа расшифровывает загруженное зашифрованное изображение по одному флэш-сектору за раз в стек размером с сектор VLA buf[sz], но когда текущий сектор все еще находится внутри заголовка изображения, он устанавливает индекс назначения до абсолютного размера заголовка (idx hdr->ih_hdr_size; в boot/boot_serial/src/boot_serial_encryption.c:156), а затем расшифровывается в &buf[idx]. Правильная родственная процедура boot/bootutil/src/loader.c:876 использует секторно-относительный idx hdr->ih_hdr_size - abs_off; последовательный путь не имеет члена - abs_off, поэтому для любого сектора после первого индекс проходит через конец буфера стека.
Поле ih_hdr_size представляет собой uint16_t, дословно взятый из загруженного заголовка изображения. Во втором секторе далее, когда ih_hdr_size превышает размер сектора, точки &buf[idx] за пределами buf и boot_enc_decrypt() записывают контролируемый злоумышленником открытый текст в соседние кадры стека. Путь достигает предварительной аутентификации: bs_upload() вызывает boot_handle_enc_fw() (boot/boot_serial/src/boot_serial.c:1208) после загрузки, и pre-decryption signature gate в decrypt_image_inplace() компилируется (if 0 в boot/boot_serial/src/boot_serial_encryption.c:226-233), поэтому заголовок никогда не проверяется перед расшифровкой.
Вторая ошибка в тех же вычислениях окна влияет на первый сектор. Когда сектор удерживает как конец заголовка, так и начало области TLV, длина расшифровки зажимается до tlv_off - (выкл. + bytes_copied), измеренная от начала сектора, а не от idx (boot/boot_serial/src/boot_serial_encryption.c:166). Зашифрованное изображение, заголовок и полезная нагрузка которого заканчиваются в первом секторе, поэтому расшифровывается для ih_hdr_size байтов больше, чем должно быть: в область TLV и, когда изображение заканчивается ближе к концу сектора, мимо buf.
Эта форма не требует большого размера заголовка, поэтому даже обычное небольшое зашифрованное изображение может вызвать его, и оно достигает устройств с секторами до 128 KiB, а не только тех, чей сектор меньше, чем 16-битный ih_hdr_size. Для достижения раковины требуется сборка с включенным MCUBOOT_ENC_IMAGES и последовательным восстановлением, а также доступ к последовательному интерфейсу восстановления устройства / USB (не аутентифицирован по дизайну). С помощью схем шифрования с открытым ключом ключ содержимого AES обернут в открытый ключ шифрования устройства, поэтому злоумышленник может создать полностью созданное зашифрованное изображение, включая вредоносный ih_hdr_size, без частного ключа подписи изображения.
Результатом является управляемая коррупция памяти стека внутри загрузчика перед любой проверкой подписи, обеспечивающая путь к выполнению кода в корне доверия безопасной загрузки, который обходит аутентификацию изображения, а также denial-of-service. 2048-байтная запись out-of-bounds была воспроизведена под AddressSanitizer (sz4096, off4096, ih_hdr_size=6144). На релизах до v2.0.0 (v1.9.0 и v1.10.0) назначением является статическая файловая область uint8_t buf[SOC_FLASH_ERASE_BLK_SZ] в .bss, а не стек VLA, описанный выше — код тогда жил в boot/zephyr/single_loader.c, прежде чем commit c9fa6088 переместил его в boot/boot_serial/src/boot_serial_encryption.c и изменил класс хранилища буфера. Запись out-of-bounds одинаково реальна и одинаково пред-аутентификация на этих релизах, но она повреждает смежные статические данные, а не стек, поэтому доказательство концепции, написанное против текущего релиза, не будет воспроизводиться как есть.
Показать оригинальное описание (EN)
MCUboot's encrypted serial-recovery path contains an attacker-controlled out-of-bounds stack write in decrypt_region_inplace() in boot/boot_serial/src/boot_serial_encryption.c. The routine decrypts an uploaded encrypted image one flash sector at a time into a sector-sized stack VLA buf[sz], but when the current sector is still inside the image header it sets the destination index to the absolute header size (idx = hdr->ih_hdr_size; at boot/boot_serial/src/boot_serial_encryption.c:156) and then decrypts into &buf[idx]. The correct sibling routine boot/bootutil/src/loader.c:876 uses the sector-relative idx = hdr->ih_hdr_size - abs_off; the serial path is missing the - abs_off term, so for any sector after the first the index runs past the end of the stack buffer. The ih_hdr_size field is a uint16_t taken verbatim from the uploaded image header. On the second sector onward, when ih_hdr_size exceeds the sector size, &buf[idx] points beyond buf and boot_enc_decrypt() writes attacker-controlled plaintext into adjacent stack frames. The path is reached pre-authentication: bs_upload() calls boot_handle_enc_fw() (boot/boot_serial/src/boot_serial.c:1208) after upload, and the pre-decryption signature gate in decrypt_image_inplace() is compiled out (#if 0 at boot/boot_serial/src/boot_serial_encryption.c:226-233), so the header is never validated before decryption. A second error in the same window computation affects the first sector. When a sector holds both the end of the header and the start of the TLV area, the decrypt length is clamped to tlv_off - (off + bytes_copied), measured from the start of the sector rather than from idx (boot/boot_serial/src/boot_serial_encryption.c:166). An encrypted image whose header and payload end within the first sector is therefore decrypted for ih_hdr_size bytes more than it should be: into the TLV area and, when the image ends near the end of the sector, past buf. This form needs no oversized header, so even an ordinary small encrypted image can trigger it, and it reaches devices with sectors of up to about 128 KiB rather than only those whose sector is smaller than the 16-bit ih_hdr_size. Reaching the sink requires a build with MCUBOOT_ENC_IMAGES and serial recovery enabled, and access to the device's serial/USB recovery interface (unauthenticated by design). With the public-key encryption schemes the AES content key is wrapped to the device's public encryption key, so an attacker can author a fully crafted encrypted image — including a malicious ih_hdr_size — without the image-signing private key. The result is a controllable stack memory-corruption inside the bootloader before any signature check, providing a path to code execution in the secure-boot root of trust that bypasses image authentication, as well as a denial-of-service. A 2048-byte out-of-bounds write was reproduced under AddressSanitizer (sz=4096, off=4096, ih_hdr_size=6144). On releases before v2.0.0 (v1.9.0 and v1.10.0) the destination is a file-scope static uint8_t buf[SOC_FLASH_ERASE_BLK_SZ] in .bss rather than the stack VLA described above — the code then lived in boot/zephyr/single_loader.c, before commit c9fa6088 relocated it to boot/boot_serial/src/boot_serial_encryption.c and changed the buffer's storage class. The out-of-bounds write is equally real and equally pre-authentication on those releases, but it corrupts adjacent static data rather than the stack, so a stack-smashing proof of concept written against a current release will not reproduce as-is there.
Характеристики атаки
Последствия
Строка CVSS v3.1