Merge pull request #747 from Foundation-Devices/sft-8653-passport-core-recheck-the-firmware-image-while
What changed, and why it matters
This update tightens the firmware update process on the Passport hardware wallet. Previously, the device verified the firmware file once, then copied it to internal flash memory without re-checking. A malicious or tampered file swapped in between those two steps could potentially be installed. The patch now computes a fingerprint (a SHA-256 hash) during the first verification and re-computes it while staging the update, refusing to proceed if the file has changed. This is a defensive hardening change rather than a confirmed exploit fix.
Treat as a security hardening improvement and include in the next firmware release. Review whether any other update paths (recovery, factory, or developer modes) stage firmware without a similar re-check, and apply the same digest-passing pattern if so. No immediate user action is required.
Security signals we found
Time-of-check/time-of-use (TOCTOU) hardening in firmware update path
New digest parameter threaded from verification task to staging task
Staging task now re-hashes firmware image and compares against expected digest
Failure path aborts before writing bootloader authorization hash
Test coverage added for body modification and missing digest mismatch
Evidence from the diff
The commit modifies the firmware update flow so that verify_firmware_signature_task.py returns a double-SHA-256 digest of the header information plus firmware body. copy_firmware_to_spi_flash_task.py now accepts that expected digest, re-hashes the same data while writing it to SPI flash, and aborts with FIRMWARE_UPDATE_FAILED if the staged digest does not match. The change prevents a time-of-check/time-of-use (TOCTOU) issue where the file on the MicroSD card could be altered after signature verification but before the bootloader-authorization hash is written. Tests are updated to exercise both body and digest mismatch cases.
Changed components
ports/stm32/boards/Passport/modules/flows/update_firmware_flow.pyports/stm32/boards/Passport/modules/tasks/copy_firmware_to_spi_flash_task.pyports/stm32/boards/Passport/modules/tasks/verify_firmware_signature_task.pyports/stm32/boards/Passport/modules/tests/test_firmware_update_host.pyInspect captured patch +68 / −26
### ports/stm32/boards/Passport/modules/flows/update_firmware_flow.py
@@ -27,10 +27,13 @@ def __init__(self, reset_after=True, statusbar=None):
self.filename = None
self.error_message = None
self.update_header = None
+ self.update_digest = None
- async def on_done(self, error=None, message=None):
+ async def on_done(self, error=None, message=None, digest=None):
self.error = error
self.error_message = message
+ if digest is not None:
+ self.update_digest = bytes(digest)
self.progress_page.set_result(error is None)
async def choose_file(self):
@@ -152,7 +155,8 @@ async def copy_to_flash(self):
self.progress_page = ProgressPage(text='Preparing Update', left_micron=None, right_micron=None)
self.update_task = start_task(copy_firmware_to_spi_flash_task(
- self.update_file_path, self.size, self.update_header, self.progress_page.set_progress, self.on_done))
+ self.update_file_path, self.size, self.update_header, self.update_digest,
+ self.progress_page.set_progress, self.on_done))
prev_top_level = ui.set_is_top_level(False)
result = await self.progress_page.show()
### ports/stm32/boards/Passport/modules/tasks/copy_firmware_to_spi_flash_task.py
@@ -9,7 +9,7 @@
#
# copy_firmware_to_spi_flash_task.py - Task to perform the copy to SPI flash and update the UI progress
-from constants import FW_HEADER_SIZE, FW_ACTUAL_HEADER_SIZE
+from constants import FW_HEADER_SIZE, FW_ACTUAL_HEADER_SIZE, FW_HEADER_INFORMATION_SIZE
import trezorcrypto
import foundation
import passport
@@ -28,7 +28,7 @@ async def sleep_and_timeout(sleep_time_ms, timeout_ms, sf):
assert timeout_ms > 0, 'Firmware update timed out'
-async def copy_firmware_to_spi_flash_task(file_path, size, expected_header, on_progress, on_done):
+async def copy_firmware_to_spi_flash_task(file_path, size, expected_header, expected_digest, on_progress, on_done):
from common import system, sf
try:
@@ -42,7 +42,10 @@ async def copy_firmware_to_spi_flash_task(file_path, size, expected_header, on_p
return
# Stage the checked header from memory, then read the body
- # from the file's current position.
+ # from the file's current position. Hash what is staged the
+ # same way the signature check did.
+ staged = trezorcrypto.sha256()
+ staged.update(header[:FW_HEADER_INFORMATION_SIZE])
# Calculate the update request hash so that the booloader knows this was requested by the user, not
# injected into SPI flash by some external attacker.
@@ -112,6 +115,7 @@ async def copy_firmware_to_spi_flash_task(file_path, size, expected_header, on_p
else:
buf[:] = bytes(len(buf))
here = fp.readinto(memoryview(buf)[:remaining])
+ staged.update(buf[:remaining])
if here != remaining:
raise ValueError("Firmware file is truncated")
update_display += 1
@@ -147,6 +151,12 @@ async def copy_firmware_to_spi_flash_task(file_path, size, expected_header, on_p
await on_done(Error.FIRMWARE_UPDATE_FAILED, error_message)
return
+ staged_digest = bytearray(32)
+ foundation.sha256(staged.digest(), staged_digest)
+ if expected_digest is None or bytes(staged_digest) != bytes(expected_digest):
+ await on_done(Error.FIRMWARE_UPDATE_FAILED, "Firmware file changed. Select the file again.")
+ return
+
try:
# Do this at the end so we know the rest worked - prevent bootloader from installing bad firmware
buf[0:32] = update_hash # Copy into the buf we'll use to write to SPI flash
### ports/stm32/boards/Passport/modules/tasks/verify_firmware_signature_task.py
@@ -70,4 +70,5 @@ async def verify_firmware_signature_task(file_path, size, expected_header, on_pr
await on_done(Error.FIRMWARE_UPDATE_FAILED, error_message)
return
- await on_done(None, None)
+ # The copy hashes what it stages and checks it against this digest.
+ await on_done(None, None, double_sha)
### ports/stm32/boards/Passport/modules/tests/test_firmware_update_host.py
@@ -94,26 +94,35 @@ def verify_signatures(header, digest):
return SimpleNamespace(flash=flash, errors=errors, verified=verified, device_hash=device_hash)
-def run_task(relative, function, path, size, header, progress=lambda _: None):
+VERIFY = 'verify_firmware_signature_task'
+COPY = 'copy_firmware_to_spi_flash_task'
+
+
+def run_task(function, path, size, header, progress=lambda _: None, digest=None):
results = []
- async def done(error, message):
- results.append((error, message))
+ async def done(error, message, verified=None):
+ results.append((error, message) if verified is None else (error, message, bytes(verified)))
- module = load_module(relative)
+ module = load_module('tasks/' + function + '.py')
module.open = lambda file, mode: open(file, mode, buffering=0)
- asyncio.run(getattr(module, function)(str(path), size, header, progress, done))
+ args = [str(path), size, header] + ([digest] if function == COPY else []) + [progress, done]
+ asyncio.run(getattr(module, function)(*args))
return results
-@pytest.mark.parametrize('task', ['verify_firmware_signature_task', 'copy_firmware_to_spi_flash_task'])
+def image_digest(header, body):
+ return hashlib.sha256(hashlib.sha256(header[:34] + body).digest()).digest()
+
+
+@pytest.mark.parametrize('task', [VERIFY, COPY])
def test_changed_header_rejected_before_staging(environment, tmp_path, task):
expected = bytes(HEADER_SIZE)
changed = bytearray(expected)
changed[102] = 1 # Second public key index in the serialized header.
path = tmp_path / 'firmware.bin'
path.write_bytes(changed + bytes(2048))
- results = run_task('tasks/' + task + '.py', task, path, 4096, expected)
+ results = run_task(task, path, 4096, expected, digest=image_digest(expected, bytes(2048)))
assert len(results) == 1 and results[0][0] == environment.errors.FIRMWARE_UPDATE_FAILED
assert not environment.flash.erases
assert not environment.flash.writes
@@ -126,29 +135,28 @@ def test_checked_header_is_staged_without_rereading(environment, tmp_path):
image = header + body
path = tmp_path / 'firmware.bin'
path.write_bytes(image)
- verify = 'verify_firmware_signature_task'
- assert run_task('tasks/' + verify + '.py', verify, path, len(image), header) == [(None, None)]
- assert environment.verified == [(header, hashlib.sha256(hashlib.sha256(header[:34] + body).digest()).digest())]
+ digest = image_digest(header, body)
+ assert run_task(VERIFY, path, len(image), header) == [(None, None, digest)]
+ assert environment.verified == [(header, digest)]
def change_source(_):
with path.open('r+b') as fp:
fp.seek(102)
fp.write(b'\x01')
- copy = 'copy_firmware_to_spi_flash_task'
- assert run_task('tasks/' + copy + '.py', copy, path, len(image), header, change_source) == [(None, None)]
+ assert run_task(COPY, path, len(image), header, change_source, digest) == [(None, None)]
assert environment.flash.data[256:256 + len(image)] == image
assert environment.flash.writes[-1] == 0
header_hash = hashlib.sha256(hashlib.sha256(header[:ACTUAL_HEADER_SIZE]).digest()).digest()
assert environment.flash.data[:32] == hashlib.sha256(header_hash + environment.device_hash).digest()
-@pytest.mark.parametrize('task', ['verify_firmware_signature_task', 'copy_firmware_to_spi_flash_task'])
+@pytest.mark.parametrize('task', [VERIFY, COPY])
def test_truncated_body_fails_once(environment, tmp_path, task):
header = bytes(HEADER_SIZE)
path = tmp_path / 'firmware.bin'
path.write_bytes(header + b'short')
- results = run_task('tasks/' + task + '.py', task, path, 4096, header)
+ results = run_task(task, path, 4096, header, digest=image_digest(header, bytes(2048)))
assert len(results) == 1 and results[0][0] == environment.errors.FIRMWARE_UPDATE_FAILED
assert 0 not in environment.flash.writes
assert not environment.verified
@@ -159,12 +167,31 @@ def test_copy_failure_never_authorizes_update(environment, tmp_path):
path = tmp_path / 'firmware.bin'
path.write_bytes(header + bytes(2048))
environment.flash.fail_at = 512
- task = 'copy_firmware_to_spi_flash_task'
- results = run_task('tasks/' + task + '.py', task, path, 4096, header)
+ results = run_task(COPY, path, 4096, header, digest=image_digest(header, bytes(2048)))
assert results == [(environment.errors.MICROSD_CARD_MISSING, None)]
assert 0 not in environment.flash.writes
+@pytest.mark.parametrize('change', ['body', 'digest'])
+def test_copy_stages_only_the_verified_body(environment, tmp_path, change):
+ header = bytes(HEADER_SIZE)
+ body = bytes(range(256)) * 8
+ path = tmp_path / 'firmware.bin'
+ path.write_bytes(header + body)
+ digest = image_digest(header, body)
+
+ def change_body(_):
+ if change == 'body':
+ with path.open('r+b') as fp:
+ fp.seek(HEADER_SIZE + 300)
+ fp.write(bytes(1))
+
+ results = run_task(COPY, path, len(header + body), header, change_body, None if change == 'digest' else digest)
+ assert len(results) == 1 and results[0][0] == environment.errors.FIRMWARE_UPDATE_FAILED
+ assert 0 not in environment.flash.writes
+ assert environment.flash.data[:32] == bytes([0xff]) * 32
+
+
def test_installed_firmware_detection_c(tmp_path):
harness = tmp_path / 'detection.c'
source = (BOARD / 'bootloader/update.c').read_text()
@@ -373,10 +400,10 @@ async def show(self):
async def verify(path, size, header, progress, done):
calls.append(('verify', header))
- await done(None, None)
+ await done(None, None, bytearray(b'v' * 32))
- async def copy(path, size, header, progress, done):
- calls.append(('copy', header))
+ async def copy(path, size, header, digest, progress, done):
+ calls.append(('copy', header, digest))
await done(None, None)
page_names = ['ErrorPage', 'ProgressPage', 'QuestionPage', 'SuccessPage', 'InsertMicroSDPage', 'InfoPage']
@@ -406,4 +433,4 @@ async def copy(path, size, header, progress, done):
flow.version = '2.4.0'
asyncio.run(flow.verify_firmware_signature())
asyncio.run(flow.copy_to_flash())
- assert calls == [('verify', header), 'copy_to_flash', ('copy', header), True]
+ assert calls == [('verify', header), 'copy_to_flash', ('copy', header, b'v' * 32), True]Why this scored 59/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.