Skip to content

Commit b1b3ab5

Browse files
authored
feat: Add multiple entropy sources support for device reset. (#398)
feat:Add multiple entropy sources support for device reset.
1 parent d6b021d commit b1b3ab5

File tree

17 files changed

+189
-35
lines changed

17 files changed

+189
-35
lines changed

core/embed/extmod/modtrezorcrypto/modtrezorcrypto-random.h

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -44,28 +44,43 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_random_uniform_obj,
4444
mod_trezorcrypto_random_uniform);
4545

4646
/// import builtins
47-
/// def bytes(len: int) -> builtins.bytes:
47+
/// def bytes(len: int, source: int = 1) -> builtins.bytes:
4848
/// """
4949
/// Generate random bytes sequence of length len.
50+
/// source: 0 = use random_buffer, 1 = use se_random_encrypted (default)
5051
/// """
51-
STATIC mp_obj_t mod_trezorcrypto_random_bytes(mp_obj_t len) {
52-
uint32_t l = trezor_obj_get_uint(len);
52+
STATIC mp_obj_t mod_trezorcrypto_random_bytes(size_t n_args,
53+
const mp_obj_t *args) {
54+
uint32_t l = trezor_obj_get_uint(args[0]);
5355
if (l > 1024) {
5456
mp_raise_ValueError("Maximum requested size is 1024");
5557
}
58+
59+
// Default to 1 (se_random_encrypted) if source not provided
60+
uint32_t source = 1;
61+
if (n_args > 1) {
62+
source = trezor_obj_get_uint(args[1]);
63+
}
64+
5665
vstr_t vstr = {0};
5766
vstr_init_len(&vstr, l);
67+
68+
if (source == 0) {
69+
random_buffer((uint8_t *)vstr.buf, l);
70+
} else {
5871
#if USE_THD89
59-
if (sectrue != se_random_encrypted((uint8_t *)vstr.buf, l)) {
60-
mp_raise_ValueError("se_random_encrypted failed");
61-
}
72+
if (sectrue != se_random_encrypted((uint8_t *)vstr.buf, l)) {
73+
mp_raise_ValueError("se_random_encrypted failed");
74+
}
6275
#else
63-
random_buffer((uint8_t *)vstr.buf, l);
76+
random_buffer((uint8_t *)vstr.buf, l);
6477
#endif
78+
}
79+
6580
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
6681
}
67-
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_random_bytes_obj,
68-
mod_trezorcrypto_random_bytes);
82+
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorcrypto_random_bytes_obj, 1,
83+
2, mod_trezorcrypto_random_bytes);
6984

7085
/// def shuffle(data: list) -> None:
7186
/// """

core/mocks/generated/trezorcrypto/random.pyi

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,10 @@ import builtins
1010

1111

1212
# extmod/modtrezorcrypto/modtrezorcrypto-random.h
13-
def bytes(len: int) -> builtins.bytes:
13+
def bytes(len: int, source: int = 1) -> builtins.bytes:
1414
"""
1515
Generate random bytes sequence of length len.
16+
source: 0 = use random_buffer, 1 = use se_random_encrypted (default)
1617
"""
1718

1819

core/src/apps/management/reset_device/__init__.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,9 @@
2727
_DEFAULT_BACKUP_TYPE = B39
2828

2929

30-
async def reset_device(ctx: wire.GenericContext, msg: ResetDevice) -> Success:
30+
async def reset_device(
31+
ctx: wire.GenericContext, msg: ResetDevice, use_multiple_entropy: bool = False
32+
) -> Success:
3133
# validate parameters and device state
3234
_validate_reset_device(msg)
3335

@@ -42,8 +44,13 @@ async def reset_device(ctx: wire.GenericContext, msg: ResetDevice) -> Success:
4244
await layout.show_internal_entropy(ctx, int_entropy)
4345

4446
# request external entropy and compute the master secret
45-
entropy_ack = await ctx.call(EntropyRequest(), EntropyAck)
46-
ext_entropy = entropy_ack.entropy if entropy_ack else b""
47+
if use_multiple_entropy:
48+
# Use MCU random number generator (source=0) for external entropy
49+
ext_entropy = random.bytes(32, 0)
50+
else:
51+
# Request external entropy from host
52+
entropy_ack = await ctx.call(EntropyRequest(), EntropyAck)
53+
ext_entropy = entropy_ack.entropy if entropy_ack else b""
4754
# If either of skip_backup or no_backup is specified, we are not doing backup now.
4855
# Otherwise, we try to do it.
4956
perform_backup = not msg.no_backup and not msg.skip_backup

core/src/trezor/lvglui/i18n/keys.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2295,10 +2295,10 @@
22952295
# BTC, TRON, SOL, ETH, BNB ...
22962296
CONTENT__BTC_TRON_SOL_ETH_BNB = 1041
22972297
# Some crypto assets and hardware features are unavailable in QR Code communic
2298-
# ation mode. \nThis mode is intended only for a small number of users who rar
2299-
# ely operate their hardware wallet and is not compatible with other connectio
2300-
# n methods. \nIf you wish to connect your hardware wallet via Bluetooth or US
2301-
# B, please re-add the wallet to switch the communication mode.
2298+
# ation mode. \n\nThis mode is intended only for a small number of users who r
2299+
# arely operate their hardware wallet and is not compatible with other connect
2300+
# ion methods. \n\nIf you wish to connect your hardware wallet via Bluetooth o
2301+
# r USB, please re-add the wallet to switch the communication mode.
23022302
TITLE__QR_CODE_CONNECT_DESC = 1042
23032303
# Select the way to connect. \nTo use the QR code connection, tap "More" in th
23042304
# e top right corner.
@@ -2311,4 +2311,12 @@
23112311
BUTTON__CONTINUE_WITH_QR_CODE = 1046
23122312
# Connect OneKey App Wallet
23132313
TITLE_BTC_ONLY_CONNECT_WALLET = 1047
2314+
# Advanced Options
2315+
TITLE__ADVANCED_OPTIONS = 1048
2316+
# Use multiple sources of entropy
2317+
BUTTON__USE_MULTIPLE_SOURCES_OF_ENTROPY = 1049
2318+
# By default, the device uses the secure element to generate mnemonic phrases.
2319+
# When enabled, entropy from both the MCU and secure element will be combined
2320+
# . Both methods meet cryptographic security standards.
2321+
BUTTON__USE_MULTIPLE_SOURCES_OF_ENTROPY_DESC = 1050
23142322
# fmt: on

core/src/trezor/lvglui/i18n/locales/de.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1042,11 +1042,14 @@
10421042
"Die Anzahl der Wörter in deiner Seed-Phrase beeinträchtigt ihre Sicherheit nicht; alle sind kryptografisch sicher.",
10431043
"Dynamischer QR-Code",
10441044
"BTC, TRON, SOL, ETH, BNB ...",
1045-
"Einige Krypto-Assets und Hardware-Funktionen sind im QR-Code-Kommunikationsmodus nicht verfügbar. \nDieser Modus ist nur für eine kleine Anzahl von Benutzern gedacht, die ihr Hardware-Wallet selten verwenden, und ist nicht mit anderen Verbindungsmethoden kompatibel. \nWenn Sie Ihr Hardware-Wallet über Bluetooth oder USB verbinden möchten, fügen Sie das Wallet bitte erneut hinzu, um den Kommunikationsmodus zu wechseln.",
1045+
"Einige Krypto-Assets und Hardware-Funktionen sind im QR-Code-Kommunikationsmodus nicht verfügbar. \n\nDieser Modus ist nur für eine kleine Anzahl von Benutzern gedacht, die ihr Hardware-Wallet selten verwenden, und ist nicht mit anderen Verbindungsmethoden kompatibel. \n\nWenn Sie Ihr Hardware-Wallet über Bluetooth oder USB verbinden möchten, fügen Sie das Wallet bitte erneut hinzu, um den Kommunikationsmodus zu wechseln.",
10461046
"Wählen Sie die Verbindungsart aus. \nUm die Verbindung per QR-Code zu verwenden, tippen Sie oben rechts auf \"Mehr\".",
10471047
"Fortschrittlich",
10481048
"Gefahrenzone",
10491049
"Mit QR-Code fortfahren",
10501050
"OneKey App Wallet verbinden",
1051+
"Erweiterte Optionen",
1052+
"Verwenden Sie mehrere Entropiequellen",
1053+
"Standardmäßig verwendet das Gerät das Secure Element, um mnemonische Phrasen zu erzeugen. Wenn aktiviert, wird Entropie sowohl vom MCU als auch vom Secure Element kombiniert. Beide Methoden erfüllen kryptografische Sicherheitsstandards.",
10511054
]
10521055
# fmt: on

core/src/trezor/lvglui/i18n/locales/en.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1042,11 +1042,14 @@
10421042
"The number of words in your seed phrase doesn't affect its security, all are cryptographically secure.",
10431043
"Show Dynamic QR Code",
10441044
"BTC, TRON, SOL, ETH, BNB ...",
1045-
"Some crypto assets and hardware features are unavailable in QR Code communication mode. \nThis mode is intended only for a small number of users who rarely operate their hardware wallet and is not compatible with other connection methods. \nIf you wish to connect your hardware wallet via Bluetooth or USB, please re-add the wallet to switch the communication mode.",
1045+
"Some crypto assets and hardware features are unavailable in QR Code communication mode. \n\nThis mode is intended only for a small number of users who rarely operate their hardware wallet and is not compatible with other connection methods. \n\nIf you wish to connect your hardware wallet via Bluetooth or USB, please re-add the wallet to switch the communication mode.",
10461046
"Select the way to connect. \nTo use the QR code connection, tap \"More\" in the top right corner.",
10471047
"Advanced",
10481048
"Danger Zone",
10491049
"Continue with QR Code",
10501050
"Connect OneKey App Wallet",
1051+
"Advanced Options",
1052+
"Use multiple sources of entropy",
1053+
"By default, the device uses the secure element to generate mnemonic phrases. When enabled, entropy from both the MCU and secure element will be combined. Both methods meet cryptographic security standards.",
10511054
]
10521055
# fmt: on

core/src/trezor/lvglui/i18n/locales/es.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1042,11 +1042,14 @@
10421042
"La cantidad de palabras en tu frase semilla no afecta su seguridad; todas son criptográficamente seguras.",
10431043
"Mostrar código QR dinámico",
10441044
"BTC, TRON, SOL, ETH, BNB ...",
1045-
"Algunos activos cripto y funciones de hardware no están disponibles en el modo de comunicación por código QR. \nEste modo está destinado únicamente a un pequeño número de usuarios que operan raramente su billetera de hardware y no es compatible con otros métodos de conexión. \nSi desea conectar su billetera de hardware a través de Bluetooth o USB, vuelva a agregar la billetera para cambiar el modo de comunicación.",
1045+
"Algunos activos cripto y funciones de hardware no están disponibles en el modo de comunicación por código QR. \n\nEste modo está destinado únicamente a un pequeño número de usuarios que operan raramente su billetera de hardware y no es compatible con otros métodos de conexión. \n\nSi desea conectar su billetera de hardware a través de Bluetooth o USB, vuelva a agregar la billetera para cambiar el modo de comunicación.",
10461046
"Selecciona la forma de conectarte. \nPara usar la conexión mediante código QR, toca \"Más\" en la esquina superior derecha.",
10471047
"Avanzado",
10481048
"Zona peligrosa",
10491049
"Continuar con código QR",
10501050
"Conectar OneKey App Wallet",
1051+
"Opciones avanzadas",
1052+
"Usa múltiples fuentes de entropía",
1053+
"De forma predeterminada, el dispositivo utiliza el elemento seguro para generar frases mnemotécnicas. Cuando está habilitado, se combinará la entropía tanto del MCU como del elemento seguro. Ambos métodos cumplen con los estándares de seguridad criptográfica.",
10511054
]
10521055
# fmt: on

core/src/trezor/lvglui/i18n/locales/fr.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1042,11 +1042,14 @@
10421042
"Le nombre de mots dans votre phrase de récupération n'affecte pas sa sécurité, toutes sont cryptographiquement sécurisées.",
10431043
"Code QR dynamique",
10441044
"BTC, TRON, SOL, ETH, BNB ...",
1045-
"Certains actifs cryptographiques et fonctionnalités matérielles ne sont pas disponibles en mode de communication par code QR. \nCe mode est destiné uniquement à un petit nombre d'utilisateurs qui utilisent rarement leur portefeuille matériel et n'est pas compatible avec d'autres méthodes de connexion. \nSi vous souhaitez connecter votre portefeuille matériel via Bluetooth ou USB, veuillez rajouter le portefeuille pour changer le mode de communication.",
1045+
"Certains actifs cryptographiques et fonctionnalités matérielles ne sont pas disponibles en mode de communication par code QR. \n\nCe mode est destiné uniquement à un petit nombre d'utilisateurs qui utilisent rarement leur portefeuille matériel et n'est pas compatible avec d'autres méthodes de connexion. \n\nSi vous souhaitez connecter votre portefeuille matériel via Bluetooth ou USB, veuillez rajouter le portefeuille pour changer le mode de communication.",
10461046
"Sélectionnez le mode de connexion. \nPour utiliser la connexion par code QR, appuyez sur « Plus » dans le coin supérieur droit.",
10471047
"Avancé",
10481048
"Zone de danger",
10491049
"Continuer avec le code QR",
10501050
"Connecter le portefeuille OneKey App",
1051+
"Options avancées",
1052+
"Utiliser plusieurs sources d'entropie",
1053+
"Par défaut, l'appareil utilise l'élément sécurisé pour générer des phrases mnémoniques. Lorsque cette option est activée, l'entropie du MCU et de l'élément sécurisé sera combinée. Les deux méthodes répondent aux normes de sécurité cryptographique.",
10511054
]
10521055
# fmt: on

core/src/trezor/lvglui/i18n/locales/it.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1042,11 +1042,14 @@
10421042
"Il numero di parole nella tua seed phrase non influisce sulla sua sicurezza: tutte sono crittograficamente sicure.",
10431043
"Mostra codice QR dinamico",
10441044
"BTC, TRON, SOL, ETH, BNB ...",
1045-
"Alcuni asset crypto e funzionalità hardware non sono disponibili nella modalità di comunicazione tramite codice QR. \nQuesta modalità è destinata solo a un numero limitato di utenti che utilizzano raramente il proprio portafoglio hardware e non è compatibile con altri metodi di connessione. \nSe desideri connettere il tuo portafoglio hardware tramite Bluetooth o USB, aggiungi nuovamente il portafoglio per cambiare la modalità di comunicazione.",
1045+
"Alcuni asset crypto e funzionalità hardware non sono disponibili nella modalità di comunicazione tramite codice QR. \n\nQuesta modalità è destinata solo a un numero limitato di utenti che utilizzano raramente il proprio portafoglio hardware e non è compatibile con altri metodi di connessione. \n\nSe desideri connettere il tuo portafoglio hardware tramite Bluetooth o USB, aggiungi nuovamente il portafoglio per cambiare la modalità di comunicazione.",
10461046
"Seleziona il modo di connetterti. \nPer usare la connessione tramite QR code, tocca \"Altro\" nell'angolo in alto a destra.",
10471047
"Avanzate",
10481048
"Zona pericolosa",
10491049
"Continua con codice QR",
10501050
"Collega il wallet OneKey App",
1051+
"Opzioni avanzate",
1052+
"Usa più fonti di entropia",
1053+
"Per impostazione predefinita, il dispositivo utilizza l’elemento sicuro per generare frasi mnemoniche. Quando abilitata, l’entropia sia della MCU che dell’elemento sicuro verrà combinata. Entrambi i metodi soddisfano gli standard di sicurezza crittografica.",
10511054
]
10521055
# fmt: on

core/src/trezor/lvglui/i18n/locales/ja.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1042,11 +1042,14 @@
10421042
"シードフレーズの単語数はセキュリティに影響しません。どの長さでも暗号学的に安全です。",
10431043
"動的QRコードを表示",
10441044
"BTC、TRON、SOL、ETH、BNB ...",
1045-
"一部の暗号資産とハードウェア機能は、QRコード通信モードでは利用できません。 \nこのモードは、ハードウェアウォレットをほとんど操作しない少数のユーザーのみを対象としており、他の接続方法とは互換性がありません。 \nBluetoothまたはUSB経由でハードウェアウォレットを接続する場合は、ウォレットを再度追加して通信モードを切り替えてください。",
1045+
"一部の暗号資産とハードウェア機能は、QRコード通信モードでは利用できません。 \n\nこのモードは、ハードウェアウォレットをほとんど操作しない少数のユーザーのみを対象としており、他の接続方法とは互換性がありません。 \n\nBluetoothまたはUSB経由でハードウェアウォレットを接続する場合は、ウォレットを再度追加して通信モードを切り替えてください。",
10461046
"接続方法を選択してください。 \nQRコード接続を使用するには、右上の「その他」をタップしてください。",
10471047
"高度な",
10481048
"危険地帯",
10491049
"QRコードで続行",
10501050
"OneKey Appウォレットを接続",
1051+
"詳細オプション",
1052+
"複数のエントロピー源を使用する",
1053+
"デフォルトでは、デバイスはセキュアエレメントを使用してニーモニックフレーズを生成します。有効にすると、MCUとセキュアエレメントの両方からのエントロピーが組み合わされます。どちらの方法も暗号セキュリティ標準を満たしています。",
10511054
]
10521055
# fmt: on

0 commit comments

Comments
 (0)