fix(python): resolve keyring desync issue
What changed, and why it matters
This update fixes a bookkeeping problem in the Trezor Python command-line tool (trezorctl). Previously, if a user deleted a THP (Trezor-Host Protocol) pairing secret from the operating system's password/keyring manager, trezorctl would still remember the pairing ID in its own config file and then fail or behave oddly when trying to connect. The fix makes trezorctl notice the missing keyring entry, remove the stale ID from its config, and continue using the remaining valid credentials. It is a reliability/usability fix rather than a direct fix for a remote attack.
Treat as a normal reliability fix. Reviewers should verify that _load_and_forget_missing only removes credentials when keyring entries are genuinely missing and that the finally block does not overwrite unrelated config changes. No urgent security response is indicated by the diff alone.
Security signals we found
Fixes a desync between local config file and OS keyring that could cause connection failures or stale-credential errors
Adds graceful handling of missing keyring secrets by removing stale credential IDs
Prevents exception propagation from keyring deletion when the password is already gone
Ensures config-file cleanup happens in a finally block so state stays consistent
No evidence of memory-safety bug, cryptographic flaw, or remote code execution
Evidence from the diff
The change is in python/src/trezorlib/cli/credentials.py. A new _load_and_forget_missing() method checks each stored credential ID by reading its keyring entries. If any required key (trezor public key, host private key, or credential) is missing, it logs a warning, deletes the credential, removes the ID from the in-memory app_data list, and returns only valid credentials. The _with_app() context manager now saves changes in a finally block so that cleanup is persisted even when exceptions occur. _delete_from_keyring() now treats keyring.errors.PasswordDeleteError as a benign ‘not found’ case. Tests were added to verify that list(), contains/getitem, and delete() all gracefully forget credentials whose keyring entries were removed.
Changed components
python/src/trezorlib/cli/credentials.pytrezorctl THP credential storeOS keyring integration for THP pairing credentialsInspect captured patch +173 / −18
### python/.changelog.d/7043.fixed
@@ -0,0 +1 @@
+trezorctl: forget THP pairing credentials that were removed from the OS keyring, instead of failing to connect.
### python/src/trezorlib/cli/credentials.py
@@ -27,6 +27,7 @@
import keyring
import platformdirs
+from keyring.errors import PasswordDeleteError
from typing_extensions import Self
from ..thp.credentials import Credential, TrezorPublicKeys, matches
@@ -66,6 +67,8 @@ def _delete_from_keyring(self, key: str) -> None:
keyring_key = self._key(key)
try:
keyring.delete_password(keyring_key, self._username)
+ except PasswordDeleteError:
+ LOG.debug("Not found in keyring: %s", keyring_key)
except Exception as e:
LOG.warning("Failed to delete %s from keyring: %s", keyring_key, e)
@@ -130,14 +133,16 @@ def _with_app(self) -> t.Generator[list[bytes], None, None]:
app_data_b64 = data.get(self.app_name, ())
app_data = [base64.b64decode(id) for id in app_data_b64]
original = app_data[:]
- yield app_data
- if original != app_data:
- modified_b64 = [base64.b64encode(id).decode() for id in app_data]
- if modified_b64:
- data[self.app_name] = modified_b64
- else:
- data.pop(self.app_name, None)
- self._save(data)
+ try:
+ yield app_data
+ finally:
+ if original != app_data:
+ modified_b64 = [base64.b64encode(id).decode() for id in app_data]
+ if modified_b64:
+ data[self.app_name] = modified_b64
+ else:
+ data.pop(self.app_name, None)
+ self._save(data)
def _load(self) -> dict[str, t.Any]:
if not self.config_path.exists():
@@ -147,13 +152,32 @@ def _load(self) -> dict[str, t.Any]:
def _save(self, data: dict[str, t.Any]) -> None:
self.config_path.write_text(json.dumps(data, indent=2) + "\n")
+ def _load_and_forget_missing(
+ self, app_data: list[bytes]
+ ) -> list[KeyringCredential]:
+ """Load stored credentials, forgetting those missing from the keyring"""
+ result = []
+ for id in app_data[:]:
+ credential = KeyringCredential(self.app_name, id)
+ try:
+ _ = (
+ credential.trezor_pubkey,
+ credential.host_privkey,
+ credential.credential,
+ )
+ except ValueError as e:
+ LOG.warning("Forgetting credential %s: %s", id.hex(), e)
+ credential.delete()
+ app_data.remove(id)
+ else:
+ result.append(credential)
+ return result
+
def list(self) -> t.Collection[Credential]:
with self._with_app() as app_data:
- # Use recent credentials first (in case older credentials were invalidated)
- return [
- KeyringCredential(self.app_name, id).as_credential()
- for id in reversed(app_data)
- ]
+ credentials = self._load_and_forget_missing(app_data)
+ # Use recent credentials first (in case older credentials were invalidated)
+ return [c.as_credential() for c in reversed(credentials)]
def add(self, credential: Credential) -> None:
with self._with_app() as app_data:
@@ -163,12 +187,10 @@ def add(self, credential: Credential) -> None:
def _get(
self, app_data: list[bytes], id_or_key: bytes | TrezorPublicKeys
) -> KeyringCredential | None:
- if isinstance(id_or_key, bytes):
- if id_or_key in app_data:
+ for credential in self._load_and_forget_missing(app_data):
+ if id_or_key == credential.id:
# found by the unique identifier
- return KeyringCredential(self.app_name, id_or_key)
- for id in app_data:
- credential = KeyringCredential(self.app_name, id)
+ return credential
if isinstance(id_or_key, TrezorPublicKeys) and matches(
credential.as_credential(), id_or_key
):
### python/tests/test_credentials.py
@@ -0,0 +1,132 @@
+# 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 base64
+import json
+import secrets
+from hashlib import sha256
+from pathlib import Path
+
+import keyring
+import pytest
+from cryptography.hazmat.primitives.asymmetric import x25519
+from keyring.errors import PasswordDeleteError
+
+from trezorlib.cli.credentials import (
+ KEY_CREDENTIAL,
+ KEY_HOST_PRIVKEY,
+ KEY_TREZOR_PUBKEY,
+ CredentialStore,
+)
+from trezorlib.thp.credentials import StaticCredential, TrezorPublicKeys
+
+APP = "trezorctl"
+ALL_KEYS = (KEY_TREZOR_PUBKEY, KEY_HOST_PRIVKEY, KEY_CREDENTIAL)
+
+Passwords = dict[tuple[str, str], str]
+
+
+@pytest.fixture
+def passwords(monkeypatch: pytest.MonkeyPatch) -> Passwords:
+ passwords: Passwords = {}
+
+ def set_password(service: str, username: str, password: str) -> None:
+ passwords[service, username] = password
+
+ def delete_password(service: str, username: str) -> None:
+ if passwords.pop((service, username), None) is None:
+ raise PasswordDeleteError(service)
+
+ monkeypatch.setattr(keyring, "get_password", lambda s, u: passwords.get((s, u)))
+ monkeypatch.setattr(keyring, "set_password", set_password)
+ monkeypatch.setattr(keyring, "delete_password", delete_password)
+ return passwords
+
+
+def make_credential() -> StaticCredential:
+ trezor_privkey = x25519.X25519PrivateKey.generate()
+ return StaticCredential(
+ trezor_pubkey=trezor_privkey.public_key().public_bytes_raw(),
+ host_privkey=secrets.token_bytes(32),
+ credential=secrets.token_bytes(64),
+ )
+
+
+def public_keys_for(credential: StaticCredential) -> TrezorPublicKeys:
+ ephemeral = secrets.token_bytes(32)
+ mask = sha256(credential.trezor_pubkey + ephemeral).digest()
+ static_masked = x25519.X25519PrivateKey.from_private_bytes(mask).exchange(
+ x25519.X25519PublicKey.from_public_bytes(credential.trezor_pubkey)
+ )
+ return TrezorPublicKeys(ephemeral=ephemeral, static_masked=static_masked)
+
+
+def stored_ids(store: CredentialStore) -> list[str]:
+ return json.loads(store.config_path.read_text()).get(APP, [])
+
+
+def setup_store(
+ passwords: Passwords, path: Path, removed_keys: tuple[str, ...]
+) -> tuple[CredentialStore, StaticCredential, str]:
+ store = CredentialStore(APP, config_file=path / "thp-credentials.json")
+ store.add(make_credential())
+ valid = make_credential()
+ store.add(valid)
+
+ # simulate removing the first credential via the OS keyring manager
+ stale_id = stored_ids(store)[0]
+ for key in removed_keys:
+ del passwords[f"{APP}/thp-credentials/{key}", stale_id]
+ return store, valid, stale_id
+
+
+@pytest.mark.parametrize("removed_keys", [ALL_KEYS, (KEY_CREDENTIAL,)])
+def test_list_forgets_missing(
+ passwords: Passwords, tmp_path: Path, removed_keys: tuple[str, ...]
+) -> None:
+ store, valid, stale_id = setup_store(passwords, tmp_path, removed_keys)
+
+ assert [c.trezor_pubkey for c in store.list()] == [valid.trezor_pubkey]
+ assert stale_id not in stored_ids(store)
+ assert all(username != stale_id for _, username in passwords)
+
+
+def test_delete_with_missing(passwords: Passwords, tmp_path: Path) -> None:
+ store, valid, _ = setup_store(passwords, tmp_path, ALL_KEYS)
+
+ assert public_keys_for(valid) in store
+ store.delete(public_keys_for(valid))
+ assert not passwords
+ assert stored_ids(store) == []
+
+
+def test_failed_lookup_forgets_missing(passwords: Passwords, tmp_path: Path) -> None:
+ store, _, stale_id = setup_store(passwords, tmp_path, ALL_KEYS)
+
+ with pytest.raises(KeyError):
+ store[public_keys_for(make_credential())]
+ assert stale_id not in stored_ids(store)
+
+
+def test_lookup_by_id(passwords: Passwords, tmp_path: Path) -> None:
+ store, valid, stale_id = setup_store(passwords, tmp_path, ALL_KEYS)
+ valid_id = stored_ids(store)[1]
+
+ assert base64.b64decode(stale_id) not in store
+ assert stale_id not in stored_ids(store)
+ assert store[base64.b64decode(valid_id)].trezor_pubkey == valid.trezor_pubkeyWhy this scored 28/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.