Skip to content

App hotfix 1.22.3 - #1106

Merged
apaillier-ledger merged 75 commits into
masterfrom
release/1.22.3
Aug 25, 2026
Merged

apaillier-ledger merged 75 commits into
masterfrom
release/1.22.3

Conversation

@apaillier-ledger

Copy link
Copy Markdown
Contributor

Description

Bring all the changes of the new 1.22.3 app into master. See changelog for details.

Changes include

  • Bugfix (non-breaking change that solves an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (change that is not backwards-compatible and/or changes current functionality)
  • Tests
  • Documentation
  • Other (for changes that might not fit in any category)

apaillier-ledger and others added 30 commits August 24, 2026 14:56
(cherry picked from commit dd1151d)
(cherry picked from commit b207362)
…bounds writes in ui_approve_tx

(cherry picked from commit 77f9112)
(cherry picked from commit 2c3d93c)
(cherry picked from commit 5c102bd)
(cherry picked from commit 085880b)
(cherry picked from commit 38a71ba)
(cherry picked from commit 4744d8e)
Also now check return value of calldata_set_selector in EIP-712

(cherry picked from commit 46e8fb2)
* Add support for non-power of 2 type sizes
* Commonize the formatting between EIP-712 & GCS

(cherry picked from commit 672fc7c)
(cherry picked from commit ecf3a21)
(cherry picked from commit 050fbf0)
The home-screen plugin tagline builder accumulated the FORMAT_PLUGIN
template length and the caller-controlled caller_app->name length into
a uint8_t. A sufficiently long caller name could wrap that accumulator,
leading to an undersized allocation for g_tag_line and a subsequent
snprintf overflow into adjacent memory across the on-device library-call
trust boundary.

Bound the plugin name with strnlen() against an explicit maximum and
perform the length math in size_t to make the wrap unreachable.

(cherry picked from commit 1191ba2)
…th swap

The EIP-7702 authorization handler kept no signing state. handle_sign_
eip7702_authorization() accepted a new P1_FIRST_CHUNK at any time and
immediately overwrote tmpCtx.authSigningContext7702.bip32 before the
TLV payload was complete. Because tlv_from_apdu() returns success for
buffered partial payloads, a hostile host could start a second
authorization mid-review, swap the BIP32 path, and have auth_7702_ok_cb
sign the displayed authorization hash with a different derivation path
than the one shown on screen.

Introduce a dedicated APP_STATE_SIGNING_EIP7702 and gate the handler
on it: refuse P1_FIRST_CHUNK unless idle, refuse continuation chunks
without an active session, and clear the state on error or on
approval (auth_7702_cancel_cb already resets via send_status).

(cherry picked from commit f3cfb53)
Both staking plugins set uiType=ETH_UI_TYPE_GENERIC, which suppresses
the standard Amount/To pair. The review then displayed only the
withdrawal-request amount or validator pubkeys parsed from calldata,
never the native tx.value carried by the transaction. A malicious dApp
could attach an arbitrary ETH/native amount to a staking-style request
and have the user authorize it without seeing the value on screen.

Add a "Tx value" review screen to both EIP-7002 and EIP-7251 plugins
whenever the transaction's native value is non-zero, and adjust the
screen index ? screen kind mapping so the existing validator/amount
screens remain in their expected order.

(cherry picked from commit b1d360a)
The ERC1155 safeBatchTransferFrom (0x2eb2c2d6) review path explicitly
skipped copying token IDs (`// don't copy anything since we won't
display it`) and summed every value into a single context->value. The
device then only rendered "<total> from <count> NFT IDs", which let a
malicious dApp slip a high-value token ID into a batch of innocuous
ones without the user being able to detect it on-screen.

Capture the first ERC1155_BATCH_DISPLAY_MAX (id, value) pairs into the
plugin context, render each pair on its own pair of screens, and add
an explicit "WARNING — Only first N of M IDs shown" screen whenever
the batch is larger than what we can surface. The aggregate Total
Quantity screen is preserved.

(cherry picked from commit 7818c34)
handle_set_plugin() parsed the signed chain_id only to call
app_compatible_with_chain_id() and then discarded it. The stored
tokenContext kept the plugin name, contract address, and selector but
never the chain the registration was signed for. eth_plugin_perform_
init_default() therefore authorized the plugin solely on address +
selector match, which let a host preload a valid signed registration
for chain A and then route a transaction on chain B through the same
plugin UI, masking attacker-controlled calldata behind a familiar
review flow.

Store the signed chain_id alongside the registration and refuse to
activate the plugin when the transaction's chain_id differs.
set_external_plugin keeps its chain-unbound semantics (its signed
payload contains no chain_id) and is marked explicitly via
PLUGIN_CHAIN_ID_ANY; cross-chain protection there requires a protocol
change and is left out of scope.

(cherry picked from commit b8f41b5)
The packaged Python client's TxAuth7702 constructor accepted
chain_id=None and silently coerced it to 0. The TLV with chain_id=0
crossed the host->device boundary and was interpreted by the firmware
as CHAIN_ID_ALL, producing an authorization signature valid on every
chain. A bridge or dApp integration carrying chain_id through Optional
types could end up requesting a far broader signing scope than intended
without any client-side warning.

Tighten the type contract: chain_id is now a required int, with no
Optional in the signature and no silent coercion of None. Callers that
genuinely want an all-chains authorization must pass the explicit
TxAuth7702.CHAIN_ID_ALL sentinel.

(cherry picked from commit 4f48c98)
handle_first_sign_chunk() allocates the global keccak context
g_tx_hash_ctx via APP_MEM_CALLOC and only the success path
(finalize_parsing_helper) and a subset of post-init parsing errors
(handle_sign:180) release it. Other early-error returns inside
handle_first_sign_chunk (init_tx failure, invalid data offset,
unsupported tx type, cx_hash_no_throw failure) propagate the SW
directly to handle_sign and out to main.c without freeing the
allocation. Likewise, reset_app_context() never released the context,
so app_quit() and the implicit reset at the top of
handle_first_sign_chunk left previous-session allocations dangling. A
host repeatedly triggering aborted INS_SIGN first-chunk APDUs could
exhaust the device's app heap.

Add a NULL-checked APP_MEM_FREE_AND_NULL of g_tx_hash_ctx to
reset_app_context(). Errors that bubble out of handle_sign reach
main.c with reset=true, which now centrally releases the context. The
existing late-error free in handle_sign is kept as defense in depth;
the NULL check makes the double path safe.

(cherry picked from commit d282991)
…play

The legacy signing path accepted transactions that omit the EIP-155
chain_id encoding (vLength == 0) and produced a signature with the
legacy v base 27/28. Such signatures are not domain-separated by chain
and can be replayed on any EVM-compatible chain that still accepts
unprotected legacy transactions. The existing chain-consistency check
in finalize_parsing_helper only enforced strict matching for non-mainnet
app configurations, so on Ethereum mainnet the replayable mode was
never rejected.

Reject any LEGACY transaction whose RLP V field is empty, regardless of
app configuration. EIP-155 has been mandatory for safe replay protection
since 2016, and no current ragger tests rely on the unprotected form.

(cherry picked from commit bc1802d)
…fields

format_param_token() declared `ticker` and `token_def` outside the
collection loop. When an iteration matched the native-currency
branch, only `ticker` was overwritten while `token_def` kept the
value left over from a previous ERC-20 match. The stale `token_def`
was then handed to add_to_field_table(), so a generic-parser descriptor
that mixes native and unknown ERC-20 addresses could mislabel later
entries with the previous token's metadata.

Move `ticker` and `token_def` into the per-iteration scope so they
always start at NULL, and force the matching branch to repopulate them
from scratch (the native branch keeps `token_def == NULL` intentionally).

(cherry picked from commit b05035c)
…ields

format_param_raw() accepted MUST_BE and IF_NOT_IN visibility constraints
at the field level but format_int(), format_bool() and format_string()
never called apply_visibility_constraint(). The hide/reject rule encoded
in a signed generic-parser descriptor was therefore a no-op for any
TF_INT, TF_BOOL or TF_STRING parameter, letting attacker-controlled
calldata be approved with misleading on-device output (e.g. a signed
delta the descriptor was meant to constrain, or a boolean toggle hidden
behind an IF_NOT_IN list).

Reshape the three formatters to mirror the existing UINT/ADDRESS/BYTES
flow: they now take the `s_field` and a `to_be_displayed` flag, format
the value first, then evaluate the constraints and call
apply_visibility_constraint(). Per-type comparisons:
  * INT  — canonical decimal-string equality (matches sign-extended
    encodings of varying byte widths).
  * BOOL — both sides normalized to 0/1 before comparison.
  * STRING — byte-level length + memcmp equality.

Also reset `to_be_displayed = true` at the start of every iteration so
that an IF_NOT_IN hit on one collection element no longer drags
subsequent elements out of the review.

(cherry picked from commit e0a44d9)
INS_PERFORM_PRIVACY_OPERATION (0x18) accepted P1_NON_CONFIRM for both
the public encryption key (P2=0x00) and the shared secret (P2=0x01).
The shared secret is computed via X25519 from the device-derived
private key and an attacker-supplied Curve25519 public key, so it is
secret material that should never leave the device without the user
physically approving the action. The non-confirm path turned the device
into a silent ECDH oracle reachable by any host that could send APDUs.

Reject P2_SHARED_SECRET + P1_NON_CONFIRM with
SWO_CONDITIONS_NOT_SATISFIED. The P2_PUBLIC_ENCRYPTION_KEY path keeps
its existing non-confirm semantics — that operation only exposes a
public key.

(cherry picked from commit 768e11a)
handle_safe_tlv_payload() and handle_signer_tlv_payload() verify the
signed CHALLENGE field of their respective descriptors but never call
roll_challenge() afterwards. The global challenge issued by
INS_GET_CHALLENGE stayed valid until the next explicit GET_CHALLENGE,
so any previously captured signed Safe / Signer descriptor could be
replayed within the same app session and the device would display
stale signer / threshold information as freshly authorized.

Roll the challenge at the end of both TLV payload handlers, on both
success and failure, mirroring the pattern already used by the trusted
name and proxy info flows.

(cherry picked from commit 297d44c)
path_update() walks nested TYPE_CUSTOM fields and allocates a fresh
keccak hash context on every step via push_new_hash_depth(). When the
descent reached MAX_PATH_DEPTH, path_depth_list_push() returned false
but its return value was ignored, so the next iteration kept
descending and kept calling push_new_hash_depth(). For a self-referential
or cyclic schema (A { A a; } or A -> B -> A), this turned into an
unbounded allocation loop until the app's heap was exhausted, denying
service to typed-message signing.

Propagate the path_depth_list_push() failure: when the path stack is
full, abort the descent with SWO_INCORRECT_DATA. The depth cap bounds
the loop for any recursive schema while leaving legitimate nested
non-recursive types unaffected.

(cherry picked from commit d09e171)
cedelavergne-ledger and others added 23 commits August 25, 2026 17:04
handle_set_external_plugin() trusted the host-supplied length byte
end-to-end: a zero-length name passed every existing check, the
SHA-256 hash was computed over an empty name prefix, and only the
Ledger PKI signature verification stood between the request and a
plugin registration with pluginName = "". The downstream alias
matching uses strcmp() against entries like "-erc20", so an empty
alias would never match any internal plugin and the registration
would be inert — but the device would still have stored a useless
plugin context and surfaced a stale name on subsequent screens.

Reject pluginNameLength == 0 explicitly before any further work.
This is defense in depth against a backend that signs a malformed
payload, not a bypass of the PKI gate.

(cherry picked from commit f93ef3b)
handle_check_address() read params->address_parameters[0] without
first checking that the pointer was non-NULL or that
address_parameters_length covered at least the length byte. The
function is reachable only from the Exchange app via os_lib_call(),
so this isn't exploitable from a host APDU today, but the contract
between the two libraries lives across a trust boundary and would
silently OOB-read on any future caller that wires up the same
interface less carefully.

Reject params->address_parameters == NULL and
address_parameters_length < 1 early so the function is safe
regardless of who calls it.

(cherry picked from commit c810bc5)
rlp_decode_length() dereferenced its `buffer` argument and then
indexed up to four bytes past the prefix without any length
parameter. Safety relied entirely on the caller running
rlp_can_decode() first — a sibling helper that does check
bufferLength. The single in-tree caller (eth_ustream.c) follows that
discipline, but a future call site that skipped rlp_can_decode would
silently OOB-read into adjacent memory.

Add a bufferLength parameter to rlp_decode_length(), reject zero-
length input up front, and reject inputs shorter than the encoded
length prefix in the long-string / long-list branches. Update the
existing caller to pass context->rlpBufferPos. The function now
upholds its own invariant instead of relying on its companion.

(cherry picked from commit ad3fb1f)
format_field() and format_param_group() in the generic-clear-signing
formatter are mutually recursive: a PARAM_TYPE_GROUP entry recurses
through every sub-field, and a nested PARAM_TYPE_GROUP recurses
again. The only existing bound is the per-APDU TLV buffer size,
which still leaves room for a couple hundred nesting levels — enough
to walk through several KB of device stack with a hostile descriptor
on the Nano S+ where total stack is tight.

Thread an explicit `depth` parameter through format_field() and
format_param_group(): the top-level call from cmd_field.c starts at
0, and format_param_group() bumps it before recursing. When depth
reaches MAX_PARAM_GROUP_DEPTH (8), the formatter refuses the
descriptor. Eight nesting levels is well past any realistic GCS
layout and keeps the worst-case stack usage of this code path
bounded.

The unit-test mock for format_field() is updated to match the new
signature, and a regression test asserts that the cap short-circuits
before any sub-field is visited.

(cherry picked from commit 6964b03)
…chema injection

handle_eip712_filtering() under P2_FILT_ACTIVATE computes the schema
hash that downstream filter signatures are issued against, but left
the EIP-712 type system unlocked: the host could continue sending
INS_EIP712_STRUCT_DEF APDUs after the activate, append fields or
even entire structs to the schema, and then sign a typed message
whose actual schema differs from the one the filter metadata was
issued for.

Compute the schema hash first, and only on success switch the UI
into filtering-full mode and set struct_state to DEFINED so
subsequent handle_eip712_struct_def() calls are refused by the
existing gate at commands_712.c:94. The whole branch is inside the
`!N_storage.verbose_eip712` check (verbose mode never computes the
hash). All three state changes (hash, filtering mode, type-system
lock) move together, so a transient compute_schema_hash() failure
leaves the handle clean and the host can retry the activate.

(cherry picked from commit bc18ee0)
ui_712_format_datetime() decoded the timestamp with
u64_from_BE(data, length), which reads at most 8 bytes from the
start of the buffer. EIP-712 typically declares timestamps as
uint256, so a host-supplied 32-byte value carries its trailing 8
bytes as the meaningful payload and zero-pads the first 24. The
formatter therefore read 8 bytes of padding, displayed 1970-01-01,
and let the user sign a hash computed over the actual timestamp.

Detect that the buffer is wider than uint64_t, verify the leading
bytes are zero, and advance the data pointer past the padding so the
decoded timestamp matches what is being hashed. Non-zero leading
bytes mean the value cannot fit a time_t — refuse the screen in
that case rather than wrap to an arbitrary date.

(cherry picked from commit c09c0e4)
…view

The ERC-20 internal plugin only cleared `extra_data` at
ETH_PLUGIN_INIT_CONTRACT, leaving `destinationAddress`, `amount`,
`ticker`, `decimals`, `contract_name`, and `selectorIndex` from the
previous signing flow alive in the per-plugin global context that
backs dataContext.tokenContext.pluginContext. A host that started a
new transfer with selector-compatible but malformed calldata (wrong
ABI offsets, truncated payload) could then reach
ETH_PLUGIN_FINALIZE with neither the destination nor the amount
parameter actually observed, and the trusted review screen would
display the stale values from the previous flow as if they were the
current ones.

Zero the entire context at INIT and add `destination_parsed` /
`amount_parsed` flags that the parameter handlers flip when the
two mandatory ABI offsets fire. FINALIZE refuses the screen if
either flag is missing, so non-conforming calldata is reported as
ERROR instead of rendering stale state.

(cherry picked from commit 816010e)
… signing is enabled (#1036)

Co-authored-by: Cerberus Merlin <merlin@cerberus.security>
(cherry picked from commit f856296)
Co-authored-by: Cerberus Merlin <merlin@cerberus.security>
(cherry picked from commit 6ff127e)
…g withdrawal credential substitution

(cherry picked from commit 975f0e2)
… stack reads

Passing min_size=0 to get_buffer_from_tlv_data allowed TLV payloads shorter
than the destination buffer to pass validation. memmove would then copy fewer
bytes than the buffer size, leaving the remainder uninitialized on the stack,
which any subsequent memcmp would read.

Fix by passing size as both min and max, enforcing an exact match. Rename the
parameter from max_size to size to reflect this stricter contract.

(cherry picked from commit 6e5bdea)
(cherry picked from commit 770b75d)
eip712_context_init() now sets appState = APP_STATE_PREPARING_EIP712
on success so that handle_first_sign_chunk()'s APP_STATE_IDLE guard blocks
any interleaved INS_SIGN during the struct-definition phase.

ui_712_init() restricts its explicit_bzero to strings.tmp.tmp instead of
the whole strings union; the EIP-712 init path has no business clearing
strings.common, which may belong to another flow.

(cherry picked from commit 7363509)
- v1_set_array: reject re-entry when array_remaining > 0 but
  array_levels_remaining == 0; prevents re-opening a leaf-level
  array frame that is still consuming elements

- filtering handlers: add `if (discarded) return true;` at the
  start of the Handling section in all ten filter handlers that
  were missing the guard (filtering_calldata_{spender,amount,
  selector,chain_id,callee,value}, filtering_trusted_name,
  filtering_date_time, filtering_amount_join_{token,value});
  filtering_raw_field was already the only correct one

- ui_712_start_review: call set_tx_simulation_warning() before
  ui_tx_simulation_finish_str() so the finish button label
  reflects the actual simulation verdict

(cherry picked from commit 39e0ec8)
(cherry picked from commit a946b46)
tokenContext_t (plugin name, contract address, method selector,
pluginChainId, pluginStatus, token lookups) was never zeroed between
signing sessions, allowing stale plugin/token state from a previous
transaction to bleed into the next one.

Add memset(&dataContext) alongside the existing clears of tmpCtx,
txContext and tmpContent.

(cherry picked from commit 68224b2)
Every error path in handle_network_info() called
network_info_cleanup(g_last_added_network) unconditionally.
network_info_cleanup(NULL) erases the entire dynamic network list, so a
single malformed PROVIDE_NETWORK_INFO APDU sent before any network was
registered wiped all previously loaded networks and freed any icons held
by live reviews.

Add a NULL check before each cleanup call on error paths.

(cherry picked from commit a66734d)
ui_pairs_cleanup() was freeing g_pairs while NBGL could still hold a
pointer to the backing array via g_pairsList->pairs. Any render callback
firing between the free and the next idle screen would dereference freed
memory.

Clear g_pairsList->pairs and nbPairs before APP_MEM_FREE_AND_NULL so
that any in-flight NBGL callback finds an empty list rather than a
dangling pointer.

(cherry picked from commit c2b56f8)
tokenContext_t contains an anonymous union where pluginContext[1024]
aliases contractAddress[20]+methodSelector[4] at offset 0. Nothing
prevented code from reading contractAddress after INIT_CONTRACT had
overwritten those bytes with plugin-private data.

Add a plugin_ctx_mode_t enum (PLUGIN_CTX_ADDR_SEL / PLUGIN_CTX_PLUGIN)
that tracks which half of the union is active. The discriminant is set to
PLUGIN_CTX_PLUGIN just before eth_plugin_call(INIT_CONTRACT) activates
the plugin context. An early app_exit() in eth_plugin_perform_init_default()
fires if the flag is already set, catching double-INIT_CONTRACT attempts
that would read stale plugin bytes as an address/selector.

(cherry picked from commit aa00b9a)
eip712_format_hash() was storing NBGL display pointers directly into
strings.tmp.tmp, a scratch buffer shared with every other signing flow.
Any APDU processed while the EIP-712 review is displayed (the APDU loop
stays alive on SWO_NO_RESPONSE) could silently overwrite the domain/
message hash strings without NBGL noticing.

(cherry picked from commit d817f91)
ui_712_approve() and ui_712_reject() explicitly called reset_app_context()
after the _cb, but io_seproxyhal_send_status(..., true, ...) — which both
_cb functions call — already invokes reset_app_context() synchronously
before the APDU response is sent. The wrappers were therefore double-
resetting the context.

With the extra reset removed, the wrappers become trivial pass-throughs.
Remove them entirely and have ui_typed_message_review_choice() call
ui_712_approve_cb/ui_712_reject_cb directly, matching what the v0 path
already did.

(cherry picked from commit ce9725a)
final_process() frees g_msg_hash_ctx on success but leaves signMsgCtx
live for the UI. A subsequent P1_MORE with length=0 bypassed the length
check ((0 + N) > N is false) and re-entered final_process() with a NULL
hash context, causing a null-pointer dereference.

Guard against this by checking g_msg_hash_ctx != NULL before processing
any further data.

(cherry picked from commit 92b1930)
@github-code-quality

Copy link
Copy Markdown

Code Coverage Overview

Languages: C

C / code-coverage/unittests

The overall line coverage in commit d6d699b in the release/1.22.3 branch is 36%. Line coverage data for the master branch is not yet available.

Show a line coverage summary of the most covered files.
File master release/1.22.3 d6d699b +/-
src/features/ge...gtp_param_raw.c — 72% —
src/features/ge...param_network.c — 63% —
src/uint256.c — 62% —
src/features/ge..._trusted_name.c — 62% —
src/uint128.c — 30% —
src/utils.c — 25% —
ethereum-plugin.../common_utils.c — 21% —
src/features/ge...ser/gtp_field.c — 19% —
src/features/ge...ser/gtp_value.c — 15% —
src/tlv_apdu.c — 7% —

@github-actions

Copy link
Copy Markdown
Contributor

Code coverage report

Code Coverage

Per-file coverage
Package Line Rate Branch Rate Health
ethereum-plugin-sdk.src 21% 18% ❌
src.features.generic_tx_parser 45% 43% ❌
src 34% 24% ❌
Summary 36% (460 / 1263) 31% (195 / 626) ❌

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 44.82759% with 48 lines in your changes missing coverage. Please review.
✅ Project coverage is 42.66%. Comparing base (2eb6485) to head (d6d699b).

Files with missing lines Patch % Lines
src/features/generic_tx_parser/gtp_param_raw.c 50.87% 23 Missing and 5 partials ⚠️
src/utils.c 23.80% 16 Missing ⚠️
src/features/generic_tx_parser/gtp_field.c 25.00% 2 Missing and 1 partial ⚠️
src/tlv_apdu.c 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1106      +/-   ##
==========================================
+ Coverage   42.12%   42.66%   +0.54%     
==========================================
  Files          10       10              
  Lines        1016     1050      +34     
  Branches      193      210      +17     
==========================================
+ Hits          428      448      +20     
- Misses        534      543       +9     
- Partials       54       59       +5     
Flag Coverage Δ
unittests 42.66% <44.82%> (+0.54%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@apaillier-ledger
apaillier-ledger marked this pull request as ready for review August 25, 2026 16:31
@apaillier-ledger
apaillier-ledger merged commit bc637f8 into master Aug 25, 2026
300 of 305 checks passed
@apaillier-ledger
apaillier-ledger deleted the release/1.22.3 branch August 25, 2026 16:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants