fix(python): wait for the device to leave before reconnecting after a reboot
What changed, and why it matters
This commit fixes a reliability bug in the Trezor Python library that manages firmware updates. After telling a Trezor device to reboot into bootloader mode, the old code immediately tried to reconnect. Because the pre-reboot device can still respond briefly, or because a Bluetooth link can stay alive while the main processor reboots, the reconnection could grab the wrong device state and fail. The fix waits for the device to truly leave and then come back before continuing. It also adds a timeout to Bluetooth writes so a stuck packet does not hang forever. There is no direct evidence this is a security vulnerability, but a failed or confused update flow could in theory be abused or cause user confusion.
Treat as a reliability/stability fix rather than an urgent security patch. Review whether the broad exception handling in the reconnect loop could mask errors that have security relevance, and verify that the new is_present() check cannot select a different unintended Trezor device on multi-device systems.
Security signals we found
Race condition between reboot command and reconnect loop
Stale BLE link can outlive MCU reboot and return Failure(Busy) instead of bootloader Features
Pre-reboot device briefly still answers, risking connection to wrong device state
Broad exception swallowing in reconnect loop (unchanged behavior, now wrapped in new wait logic)
BLE write now has a bounded timeout, preventing indefinite stalls
Evidence from the diff
The patch modifies trezorlib’s CLI firmware-update path. It introduces _wait_for_device(), which first waits for the device to stop enumerating (USB) or stop answering probes (BLE), then waits for it to reappear, before reopening the connection. It also adds a 5-second timeout around BLE GATT writes. The change prevents the reconnect loop from reaching the soon-to-reboot device or reusing a stale BLE link that returns Failure(Busy) from the nRF while the main MCU is offline. The commit message frames this as a fix for post-reboot reconnection races, not a security bug.
Changed components
python/src/trezorlib/cli/firmware.pypython/src/trezorlib/cli/__init__.pypython/src/trezorlib/transport/ble.pyInspect captured patch +93 / −12
### python/src/trezorlib/cli/__init__.py
@@ -280,6 +280,15 @@ def _record_screen(self, start: bool) -> None:
assert self._transport is not None
record_screen(self._transport, self.record_dir if start else None)
+ def is_present(self) -> bool:
+ """Whether the device enumerates right now, without opening it (opening
+ would claim the interface and toggle screen recording)."""
+ try:
+ self._get_transport()
+ return True
+ except click.ClickException:
+ return False
+
def open(self) -> None:
if self._transport is None:
self._transport = self._get_transport()
### python/src/trezorlib/cli/firmware.py
@@ -31,6 +31,8 @@
if TYPE_CHECKING:
from ..client import Session, TrezorClient
+ from ..mapping import ProtobufMapping
+ from ..transport import Transport
from . import TrezorConnection
# Built from the single-source model registry: every model is selectable by its
@@ -444,6 +446,74 @@ def upload_firmware_into_device(
sys.exit(3)
+_REBOOT_DEPART_TIMEOUT = 5.0
+_PROBE_TIMEOUT = 1.0
+
+
+def _answers(
+ transport: "Transport", mapping: "ProtobufMapping", reconnect: bool
+) -> bool:
+ """Whether the device answers a message right now. A Busy failure does not
+ count: the nRF sends it on its own while the main MCU is not accepting
+ messages, e.g. during a reboot. Without `reconnect`, a closed link counts
+ as not answering."""
+ from .. import protocol_v1
+
+ try:
+ if not transport.is_open():
+ if not reconnect:
+ return False
+ transport.open()
+ protocol_v1.write(transport, *mapping.encode(messages.Cancel()))
+ resp = mapping.decode(
+ *protocol_v1.read(transport, timeout=_PROBE_TIMEOUT, _ignore_bad_magic=True)
+ )
+ except exceptions.TrezorException:
+ return False
+ return not (
+ isinstance(resp, messages.Failure) and resp.code == messages.FailureType.Busy
+ )
+
+
+def _wait_for_device(
+ obj: "TrezorConnection", mapping: "ProtobufMapping", message: str
+) -> None:
+ """Close the connection and wait for the device to leave and come back: the
+ device still answers for a moment before it reboots, so a reconnect could
+ reach it instead of the rebooted one. Features cannot tell them apart when
+ the device reboots from the bootloader into the bootloader again.
+
+ Over BLE the link can outlive the reboot (the nRF keeps running), so the
+ device is watched to stop and resume answering instead of enumerating."""
+ from ..transport.ble import BleTransport
+
+ transport = obj.transport
+ ble = isinstance(transport, BleTransport)
+ obj.close()
+ click.echo(message)
+ deadline = time.monotonic() + _REBOOT_DEPART_TIMEOUT
+ while time.monotonic() < deadline:
+ # a dropped BLE link already means it left; reconnecting here could
+ # also outlast the deadline
+ if not (
+ _answers(transport, mapping, reconnect=False) if ble else obj.is_present()
+ ):
+ break
+ time.sleep(0.1)
+ if ble:
+ while not _answers(transport, mapping, reconnect=True):
+ time.sleep(0.5)
+ while True:
+ time.sleep(0.5)
+ try:
+ obj.open()
+ break
+ except Exception:
+ # Broad on purpose: a device that is still rebooting fails to open
+ # in transport-specific ways, e.g. a raw usb1.USBError from WebUSB.
+ pass
+
+
def _is_strict_update(client: "TrezorClient", firmware_data: bytes) -> bool:
"""Check if the firmware is from the same vendor and the
firmware is newer than the currently installed firmware.
@@ -667,15 +737,7 @@ def update(
else:
device.reboot_to_bootloader(seedless_session)
- obj.close()
- click.echo("Waiting for bootloader...")
- while True:
- time.sleep(0.5)
- try:
- obj.open()
- break
- except Exception:
- pass
+ _wait_for_device(obj, client.mapping, "Waiting for bootloader...")
with obj.client_context() as client:
if not client.features.bootloader_mode:
### python/src/trezorlib/transport/ble.py
@@ -51,6 +51,8 @@
SCAN_INTERVAL_SECONDS = 3
SHUTDOWN_TIMEOUT_SECONDS = 10
+# A single GATT write; a stalled one must not block the caller forever.
+WRITE_TIMEOUT_SECONDS = 5
SHOULD_WRITE_WITH_RESPONSE = sys.platform == "darwin"
@@ -355,9 +357,17 @@ async def write(self, address: str, chunk: bytes) -> None:
periph = self.devices[address]
if periph.client is None:
raise RuntimeError("Connect to peripheral before writing")
- await periph.client.write_gatt_char(
- TREZOR_CHARACTERISTIC_RX, chunk, response=SHOULD_WRITE_WITH_RESPONSE
- )
+ try:
+ await asyncio.wait_for(
+ periph.client.write_gatt_char(
+ TREZOR_CHARACTERISTIC_RX, chunk, response=SHOULD_WRITE_WITH_RESPONSE
+ ),
+ timeout=WRITE_TIMEOUT_SECONDS,
+ )
+ except (TimeoutError, asyncio.TimeoutError) as err:
+ raise Timeout(
+ f"Timeout writing BLE packet ({WRITE_TIMEOUT_SECONDS}s)"
+ ) from err
async def shutdown(self) -> None:
raise self.ShutdownWhy this scored 25/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.