What changed, and why it matters
This commit adds new Python library code for parsing external app images and root packets used by Trezor hardware wallets. It is a feature addition, not a fix for a known vulnerability. The only change to existing code is a one-line bug fix in a sanity-check helper: it now correctly treats pre-existing error messages as a failure, rather than always starting as 'OK'. That helper change could make validation stricter, but there is no evidence it addresses an active security issue.
Review the new parsers for memory-safety and validation edge cases (e.g., zero chunk_size, very large code_size, malformed UTF-8 in curves/paths, and integer overflow in size arithmetic). Confirm the sanity_check behavior change does not break legitimate firmware/app images that previously passed despite caller-reported errors. No urgent security patch appears required based solely on this commit.
Security signals we found
New binary format parsers for external app images and root packets
One-line logic correction in SanityCheckedStruct.sanity_check that makes pre-existing errors fail validation
Use of SHA256 hash chains and ML-DSA signature placeholders in new formats
Strict parsing tests for size mismatches and mask/popcount validation
Evidence from the diff
The commit introduces trezorlib.extapp (AppHeader/AppImage parsing with SHA256 hash-chain verification) and trezorlib.root_packet (root packet parsing with ML-DSA signature slots and ring-mask validation). It also modifies SanityCheckedStruct.sanity_check in firmware/sanity_struct.py so is_ok = not _errors instead of is_ok = True. Previously, if the caller passed in errors, the method would still start with is_ok = True and only flip to False on a rebuild mismatch; with the change, pre-existing errors immediately mark the check as failed. The new parsers include length/size checks and tests cover truncated payloads, trailing bytes, and mask/popcount mismatches. No CVE, advisory, or vendor security statement is present in the supplied materials.
Changed components
python/src/trezorlib/extapp.pypython/src/trezorlib/root_packet.pypython/src/trezorlib/firmware/sanity_struct.pypython/tests/test_extapp.pypython/tests/test_root_packet.pyInspect captured patch +474 / −1
### python/.changelog.d/8083.added
@@ -0,0 +1 @@
+Parse external app images and app root packets.
### python/src/trezorlib/extapp.py
@@ -0,0 +1,159 @@
+# This file is part of the Trezor project.
+#
+# Copyright (C) SatoshiLabs and contributors
+#
+# This library is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# as published by the Free Software Foundation.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the License along with this library.
+# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
+
+from __future__ import annotations
+
+from hashlib import sha256
+from typing import cast
+
+import construct as c
+from construct_classes import subcon
+
+from .construct_helpers import Reserved, TupleAdapter
+from .firmware.sanity_struct import SanityCheckedStruct
+
+
+class AppHeader(SanityCheckedStruct):
+ # Magic number to identify the app binary format
+ magic: bytes
+ # Header size in bytes
+ header_size: int
+ # Unique identifier of the app
+ id: str
+ # Application name
+ name: str
+ # Vendor name
+ vendor: str
+ # Target model
+ model: str
+ # App version in the format major.minor.patch.build, each as a byte
+ version: tuple[int, int, int, int]
+ # SDK version that the app was built against
+ sdk_version: tuple[int, int, int, int]
+ # ABI version that the app was built against
+ abi_version: int
+ # Target architecture of the binary payload (e.g., ARMV8M, X86_64)
+ target_arch: int
+ # Application privilege ring
+ app_ring: int
+ # Application language
+ language: int
+ # Size of binary payload in bytes (code + init and relocation data)
+ code_size: int
+ # Size of RAM required by the app (includes stack, heap, and static data)
+ data_size: int
+ # Hash of the first payload chunk
+ chunk_hash: bytes
+ # Size of each chunk of the binary payload
+ chunk_size: int
+ # Reserved for future use
+ reserved_2: bytes
+ # Curves used for the app (e.g., secp256k1, ed25519)
+ curves: list[str]
+ # Allowed BIP32 path prefixes
+ paths: list[str]
+ # Size in bytes of the IPC inbox Core registers for the app at launch
+ ipc_buffer_size: int
+ # Reserved for future use
+ reserved_3: bytes
+
+ SUBCON = c.Struct(
+ "_start_offset" / c.Tell,
+ "magic" / c.Const(b"TRZA"),
+ "header_size" / c.Int32ul,
+ "id" / c.PaddedString(32, "utf-8"),
+ "name" / c.PaddedString(32, "utf-8"),
+ "vendor" / c.PaddedString(32, "utf-8"),
+ "model" / c.PaddedString(4, "utf-8"),
+ "version" / TupleAdapter(c.Int8ul, c.Int8ul, c.Int8ul, c.Int8ul),
+ "sdk_version" / TupleAdapter(c.Int8ul, c.Int8ul, c.Int8ul, c.Int8ul),
+ "abi_version" / c.Int8ul,
+ "target_arch" / c.Int8ul,
+ "app_ring" / c.Int8ul,
+ "language" / c.Int8ul,
+ "code_size" / c.Int32ul,
+ "data_size" / c.Int32ul,
+ "chunk_hash" / c.Bytes(32),
+ "chunk_size" / c.Int16ul,
+ "reserved_2" / Reserved(2),
+ "curves"
+ / c.ExprAdapter(
+ c.Bytes(64),
+ decoder=lambda obj, ctx: [
+ curve.decode("utf-8")
+ for curve in cast(bytes, obj).split(b"\0")
+ if curve
+ ],
+ encoder=lambda obj, ctx: b"\0".join(
+ curve.encode("utf-8") for curve in cast(list[str], obj)
+ ).ljust(64, b"\0"),
+ ),
+ "paths"
+ / c.ExprAdapter(
+ c.Bytes(256),
+ decoder=lambda obj, ctx: [
+ path.decode("utf-8") for path in cast(bytes, obj).split(b"\0") if path
+ ],
+ encoder=lambda obj, ctx: b"\0".join(
+ path.encode("utf-8") for path in cast(list[str], obj)
+ ).ljust(256, b"\0"),
+ ),
+ "ipc_buffer_size" / c.Int32ul,
+ "_end_offset" / c.Tell,
+ "reserved_3"
+ / Reserved(c.this.header_size - c.this._end_offset + c.this._start_offset),
+ )
+
+ def fingerprint(self) -> bytes:
+ return sha256(self.build()).digest()
+
+
+class AppImage(SanityCheckedStruct):
+ # Parsed fixed-size app header
+ header: AppHeader = subcon(AppHeader)
+ # Image payload (elf file, or other proprietary binary format)
+ payload: bytes
+
+ SUBCON = c.Struct(
+ "header" / AppHeader.SUBCON,
+ "payload" / c.Bytes(c.this.header.code_size),
+ c.Terminated,
+ )
+
+ def header_bytes(self) -> bytes:
+ """Rebuild the original header bytes including padding."""
+ return self.header.build()
+
+ def fingerprint(self) -> bytes:
+ """Calculate the SHA256 hash of the application header."""
+ return self.header.fingerprint()
+
+ def chunks(self) -> list[tuple[bytes, bytes]]:
+ """Split the payload into chunks and calculate the hash chain."""
+ size = self.header.chunk_size
+ chunks = [self.payload[i : i + size] for i in range(0, len(self.payload), size)]
+
+ result = []
+ hash = b"\x00" * 32
+
+ for chunk in reversed(chunks):
+ result.append((chunk, hash))
+ hash = sha256(hash + chunk).digest()
+
+ if hash != self.header.chunk_hash:
+ raise ValueError("Calculated payload hash does not match header")
+
+ return list(reversed(result))
### python/src/trezorlib/firmware/sanity_struct.py
@@ -75,7 +75,7 @@ def sanity_check(self, image: bytes, errors: t.Sequence[str] = ()) -> None:
"""
_errors: list[str] = list(errors)
- is_ok = True
+ is_ok = not _errors
# Parsing and rebuilding does not modify the image bytes
rebuilt_image = self.build()
### python/src/trezorlib/root_packet.py
@@ -0,0 +1,147 @@
+# This file is part of the Trezor project.
+#
+# Copyright (C) SatoshiLabs and contributors
+#
+# This library is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# as published by the Free Software Foundation.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the License along with this library.
+# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
+
+import logging
+import typing as t
+from hashlib import sha256
+
+import construct as c
+from construct_classes import subcon
+
+from .construct_helpers import Reserved
+from .firmware.sanity_struct import SanityCheckedStruct
+
+LOG = logging.getLogger(__name__)
+TREZOR_ROOT_PACKET = b"TRRP"
+MLDSA_SIG = c.Bytes(2420)
+
+# Number of signature slots in the unauthenticated part. `sigmask` must select
+# exactly this many keys.
+NUM_SIGNATURES = 2
+
+
+class RootPacketAuth(SanityCheckedStruct):
+ NAME: t.ClassVar[str] = "root packet (authenticated part)"
+ MAX_RINGS: t.ClassVar[int] = 3
+
+ ring_mask: int
+ reserved: bytes
+ timestamp: int
+ chain_timestamp: int
+ root_rings: list[bytes]
+
+ SUBCON = c.Struct(
+ "_magic" / c.Const(TREZOR_ROOT_PACKET, c.Bytes(4)),
+ "_version" / c.Const(b"\x01", c.Bytes(1)),
+ "ring_mask" / c.Byte,
+ "reserved" / Reserved(2),
+ "timestamp" / c.Int64sl,
+ "chain_timestamp" / c.Int64sl,
+ "root_rings" / c.Array(lambda ctx: bin(ctx.ring_mask).count("1"), c.Bytes(32)),
+ )
+
+ # ---- higher-level, flag-like abstraction ----
+
+ def has_ring(self, index: int) -> bool:
+ """Whether ring `index` is present in the mask."""
+ return bool(self.ring_mask & (1 << index))
+
+ @property
+ def ring_indices(self) -> list[int]:
+ """Ring indices present in the mask, ascending (0..MAX_RINGS-1)."""
+ return [i for i in range(self.MAX_RINGS) if self.has_ring(i)]
+
+ def ring(self, index: int) -> bytes:
+ """The 32-byte root for ring `index`."""
+ if not self.has_ring(index):
+ raise KeyError(f"ring {index} not present in mask {self.ring_mask:#04x}")
+ # array is stored ascending by ring index; position = set bits below `index`
+ pos = bin(self.ring_mask & ((1 << index) - 1)).count("1")
+ return self.root_rings[pos]
+
+ @property
+ def rings(self) -> dict[int, bytes]:
+ """Mapping {ring_index: 32-byte root} for all present rings."""
+ return {i: self.ring(i) for i in self.ring_indices}
+
+ def digest(self) -> bytes:
+ """SHA256 over the authenticated part.
+
+ This is the value that gets signed.
+ """
+ return sha256(self.build()).digest()
+
+ def _mask_errors(self) -> list[str]:
+ errors: list[str] = []
+
+ # `root_rings` length must equal the number of set mask bits
+ expected = bin(self.ring_mask).count("1")
+ if len(self.root_rings) != expected:
+ errors.append(
+ f"root_rings length {len(self.root_rings)} does not match "
+ f"mask popcount {expected} (mask {self.ring_mask:#04x})"
+ )
+
+ # no bits set above MAX_RINGS
+ if self.ring_mask >> self.MAX_RINGS:
+ errors.append(
+ f"ring_mask {self.ring_mask:#04x} has bits set above "
+ f"MAX_RINGS={self.MAX_RINGS}"
+ )
+
+ return errors
+
+ def sanity_check(self, image: bytes, errors: t.Sequence[str] = ()) -> None:
+ super().sanity_check(image, [*errors, *self._mask_errors()])
+
+
+class RootPacket(SanityCheckedStruct):
+ NAME: t.ClassVar[str] = "root packet"
+ MAX_RINGS: t.ClassVar[int] = RootPacketAuth.MAX_RINGS
+
+ # Authenticated part -- the digest is computed over this.
+ auth: RootPacketAuth = subcon(RootPacketAuth)
+ # Unauthenticated part -- signatures of `auth.digest()` only.
+ sigmask: int
+ reserved: bytes
+ signature_0: bytes
+ signature_1: bytes
+
+ SUBCON = c.Struct(
+ "auth" / RootPacketAuth.SUBCON,
+ "sigmask" / c.Byte,
+ "reserved" / Reserved(3),
+ "signature_0" / MLDSA_SIG,
+ "signature_1" / MLDSA_SIG,
+ )
+
+ def digest(self) -> bytes:
+ """SHA256 over the authenticated part; see `RootPacketAuth.digest`."""
+ return self.auth.digest()
+
+ def sanity_check(self, image: bytes, errors: t.Sequence[str] = ()) -> None:
+ # the base class doesn't run nested structs' own checks
+ _errors: list[str] = [*errors, *self.auth._mask_errors()]
+
+ # `sigmask` must select exactly as many keys as there are signatures
+ selected = bin(self.sigmask).count("1")
+ if selected != NUM_SIGNATURES:
+ _errors.append(
+ f"sigmask {self.sigmask:#04x} selects {selected} keys, "
+ f"expected {NUM_SIGNATURES}"
+ )
+
+ super().sanity_check(image, _errors)
### python/tests/test_extapp.py
@@ -0,0 +1,93 @@
+# This file is part of the Trezor project.
+#
+# Copyright (C) SatoshiLabs and contributors
+#
+# This library is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# as published by the Free Software Foundation.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the License along with this library.
+# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
+
+from __future__ import annotations
+
+from hashlib import sha256
+
+import construct as c
+import pytest
+
+from trezorlib.extapp import AppHeader, AppImage
+
+HEADER_SIZE = 512
+CHUNK_SIZE = 4
+PAYLOAD = b"\x01\x02\x03\x04\x05\x06\x07\x08\x09"
+
+
+def chunk_hash(payload: bytes) -> bytes:
+ hash = b"\x00" * 32
+ chunks = [payload[i : i + CHUNK_SIZE] for i in range(0, len(payload), CHUNK_SIZE)]
+ for chunk in reversed(chunks):
+ hash = sha256(hash + chunk).digest()
+ return hash
+
+
+def header_bytes(code_size: int) -> bytes:
+ return AppHeader.SUBCON.build(
+ dict(
+ header_size=HEADER_SIZE,
+ id="test.example.com",
+ name="Test",
+ vendor="Example",
+ model="T3W1",
+ version=(1, 2, 3, 4),
+ sdk_version=(0, 1, 0, 0),
+ abi_version=1,
+ target_arch=0,
+ app_ring=2,
+ language=0,
+ code_size=code_size,
+ data_size=1024,
+ chunk_hash=chunk_hash(PAYLOAD),
+ chunk_size=CHUNK_SIZE,
+ curves=["secp256k1"],
+ paths=["m/44'/1'"],
+ ipc_buffer_size=4096,
+ )
+ )
+
+
+def test_parse_valid() -> None:
+ image = AppImage.parse(header_bytes(len(PAYLOAD)) + PAYLOAD, strict=True)
+ assert image.payload == PAYLOAD
+ assert image.header.code_size == len(PAYLOAD)
+ assert [chunk for chunk, _ in image.chunks()] == [
+ PAYLOAD[0:4],
+ PAYLOAD[4:8],
+ PAYLOAD[8:],
+ ]
+ assert image.build() == header_bytes(len(PAYLOAD)) + PAYLOAD
+
+
+def test_parse_truncated_payload() -> None:
+ data = header_bytes(len(PAYLOAD)) + PAYLOAD[:-1]
+ with pytest.raises(c.StreamError):
+ AppImage.parse(data)
+
+
+def test_parse_trailing_bytes() -> None:
+ # `code_size` covers only part of the payload, the hash covers all of it
+ data = header_bytes(4) + PAYLOAD
+ with pytest.raises(c.TerminatedError):
+ AppImage.parse(data)
+
+
+def test_build_payload_size_mismatch() -> None:
+ header = AppHeader.parse(header_bytes(len(PAYLOAD)))
+ image = AppImage(header=header, payload=PAYLOAD[:-1])
+ with pytest.raises(c.StreamError):
+ image.build()
### python/tests/test_root_packet.py
@@ -0,0 +1,73 @@
+# This file is part of the Trezor project.
+#
+# Copyright (C) SatoshiLabs and contributors
+#
+# This library is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# as published by the Free Software Foundation.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the License along with this library.
+# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
+
+from __future__ import annotations
+
+import pytest
+
+from trezorlib.firmware.sanity_struct import SanityCheckError
+from trezorlib.root_packet import RootPacket, RootPacketAuth
+
+ROOT_0 = b"\x10" * 32
+ROOT_2 = b"\x12" * 32
+
+
+def auth_bytes(ring_mask: int, root_rings: list[bytes]) -> bytes:
+ return RootPacketAuth.SUBCON.build(
+ dict(
+ ring_mask=ring_mask,
+ timestamp=1,
+ chain_timestamp=2,
+ root_rings=root_rings,
+ )
+ )
+
+
+def packet_bytes(ring_mask: int, root_rings: list[bytes], sigmask: int = 0b11) -> bytes:
+ return RootPacket.SUBCON.build(
+ dict(
+ auth=dict(
+ ring_mask=ring_mask,
+ timestamp=1,
+ chain_timestamp=2,
+ root_rings=root_rings,
+ ),
+ sigmask=sigmask,
+ signature_0=b"\x00" * 2420,
+ signature_1=b"\x00" * 2420,
+ )
+ )
+
+
+def test_parse_valid() -> None:
+ packet = RootPacket.parse(packet_bytes(0b101, [ROOT_0, ROOT_2]), strict=True)
+ assert packet.auth.rings == {0: ROOT_0, 2: ROOT_2}
+
+
+def test_auth_ring_above_max() -> None:
+ with pytest.raises(SanityCheckError, match="above MAX_RINGS"):
+ RootPacketAuth.parse(auth_bytes(0b1000, [ROOT_0]), strict=True)
+
+
+def test_packet_ring_above_max() -> None:
+ """The nested auth part is checked when parsing the whole packet."""
+ with pytest.raises(SanityCheckError, match="above MAX_RINGS"):
+ RootPacket.parse(packet_bytes(0b1000, [ROOT_0]), strict=True)
+
+
+def test_packet_sigmask() -> None:
+ with pytest.raises(SanityCheckError, match="sigmask"):
+ RootPacket.parse(packet_bytes(0b1, [ROOT_0], sigmask=0b1), strict=True)Why this scored 20/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.