1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-04 21:48:17 +00:00

chore(python): update python tools

[no changelog]
This commit is contained in:
M1nd3r 2024-12-02 15:46:51 +01:00
parent 364db7bfa5
commit 36c177a9fb
6 changed files with 42 additions and 35 deletions

View File

@ -35,7 +35,6 @@ import trezorlib.misc
from trezorlib.client import TrezorClient from trezorlib.client import TrezorClient
from trezorlib.tools import Address from trezorlib.tools import Address
from trezorlib.transport import enumerate_devices from trezorlib.transport import enumerate_devices
from trezorlib.ui import ClickUI
version_tuple = tuple(map(int, trezorlib.__version__.split("."))) version_tuple = tuple(map(int, trezorlib.__version__.split(".")))
if not (0, 11) <= version_tuple < (0, 14): if not (0, 11) <= version_tuple < (0, 14):
@ -71,7 +70,7 @@ def choose_device(devices: Sequence["Transport"]) -> "Transport":
sys.stderr.write("Available devices:\n") sys.stderr.write("Available devices:\n")
for d in devices: for d in devices:
try: try:
client = TrezorClient(d, ui=ClickUI()) client = TrezorClient(d)
except IOError: except IOError:
sys.stderr.write("[-] <device is currently in use>\n") sys.stderr.write("[-] <device is currently in use>\n")
continue continue
@ -80,7 +79,7 @@ def choose_device(devices: Sequence["Transport"]) -> "Transport":
sys.stderr.write(f"[{i}] {client.features.label}\n") sys.stderr.write(f"[{i}] {client.features.label}\n")
else: else:
sys.stderr.write(f"[{i}] <no label>\n") sys.stderr.write(f"[{i}] <no label>\n")
client.close() # TODO client.close()
i += 1 i += 1
sys.stderr.write("----------------------------\n") sys.stderr.write("----------------------------\n")
@ -106,7 +105,8 @@ def main() -> None:
devices = wait_for_devices() devices = wait_for_devices()
transport = choose_device(devices) transport = choose_device(devices)
client = TrezorClient(transport, ui=ClickUI()) client = TrezorClient(transport)
session = client.get_management_session()
rootdir = os.environ["encfs_root"] # Read "man encfs" for more rootdir = os.environ["encfs_root"] # Read "man encfs" for more
passw_file = os.path.join(rootdir, "password.dat") passw_file = os.path.join(rootdir, "password.dat")
@ -120,7 +120,7 @@ def main() -> None:
sys.stderr.write("Computer asked Trezor for new strong password.\n") sys.stderr.write("Computer asked Trezor for new strong password.\n")
# 32 bytes, good for AES # 32 bytes, good for AES
trezor_entropy = trezorlib.misc.get_entropy(client, 32) trezor_entropy = trezorlib.misc.get_entropy(session, 32)
urandom_entropy = os.urandom(32) urandom_entropy = os.urandom(32)
passw = hashlib.sha256(trezor_entropy + urandom_entropy).digest() passw = hashlib.sha256(trezor_entropy + urandom_entropy).digest()
@ -129,7 +129,7 @@ def main() -> None:
bip32_path = Address([10, 0]) bip32_path = Address([10, 0])
passw_encrypted = trezorlib.misc.encrypt_keyvalue( passw_encrypted = trezorlib.misc.encrypt_keyvalue(
client, bip32_path, label, passw, False, True session, bip32_path, label, passw, False, True
) )
data = { data = {
@ -144,7 +144,7 @@ def main() -> None:
data = json.load(open(passw_file, "r")) data = json.load(open(passw_file, "r"))
passw = trezorlib.misc.decrypt_keyvalue( passw = trezorlib.misc.decrypt_keyvalue(
client, session,
data["bip32_path"], data["bip32_path"],
data["label"], data["label"],
bytes.fromhex(data["password_encrypted_hex"]), bytes.fromhex(data["password_encrypted_hex"]),

View File

@ -24,13 +24,14 @@ from trezorlib.tools import parse_path
def main() -> None: def main() -> None:
# Use first connected device # Use first connected device
client = get_default_client() client = get_default_client()
session = client.get_session(derive_cardano=True)
# Print out Trezor's features and settings # Print out Trezor's features and settings
print(client.features) print(session.features)
# Get the first address of first BIP44 account # Get the first address of first BIP44 account
bip32_path = parse_path("44h/0h/0h/0/0") bip32_path = parse_path("44h/0h/0h/0/0")
address = btc.get_address(client, "Bitcoin", bip32_path, True) address = btc.get_address(session, "Bitcoin", bip32_path, False)
print("Bitcoin address:", address) print("Bitcoin address:", address)

View File

@ -26,23 +26,24 @@ from urllib.parse import urlparse
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from trezorlib import misc, ui from trezorlib import misc
from trezorlib.client import TrezorClient from trezorlib.client import TrezorClient
from trezorlib.tools import parse_path from trezorlib.tools import parse_path
from trezorlib.transport import get_transport from trezorlib.transport import get_transport
from trezorlib.transport.session import Session
# Return path by BIP-32 # Return path by BIP-32
BIP32_PATH = parse_path("10016h/0") BIP32_PATH = parse_path("10016h/0")
# Deriving master key # Deriving master key
def getMasterKey(client: TrezorClient) -> str: def getMasterKey(session: Session) -> str:
bip32_path = BIP32_PATH bip32_path = BIP32_PATH
ENC_KEY = "Activate TREZOR Password Manager?" ENC_KEY = "Activate TREZOR Password Manager?"
ENC_VALUE = bytes.fromhex( ENC_VALUE = bytes.fromhex(
"2d650551248d792eabf628f451200d7f51cb63e46aadcbb1038aacb05e8c8aee2d650551248d792eabf628f451200d7f51cb63e46aadcbb1038aacb05e8c8aee" "2d650551248d792eabf628f451200d7f51cb63e46aadcbb1038aacb05e8c8aee2d650551248d792eabf628f451200d7f51cb63e46aadcbb1038aacb05e8c8aee"
) )
key = misc.encrypt_keyvalue(client, bip32_path, ENC_KEY, ENC_VALUE, True, True) key = misc.encrypt_keyvalue(session, bip32_path, ENC_KEY, ENC_VALUE, True, True)
return key.hex() return key.hex()
@ -101,7 +102,7 @@ def decryptEntryValue(nonce: str, val: bytes) -> dict:
# Decrypt give entry nonce # Decrypt give entry nonce
def getDecryptedNonce(client: TrezorClient, entry: dict) -> str: def getDecryptedNonce(session: Session, entry: dict) -> str:
print() print()
print("Waiting for Trezor input ...") print("Waiting for Trezor input ...")
print() print()
@ -117,7 +118,7 @@ def getDecryptedNonce(client: TrezorClient, entry: dict) -> str:
ENC_KEY = f"Unlock {item} for user {entry['username']}?" ENC_KEY = f"Unlock {item} for user {entry['username']}?"
ENC_VALUE = entry["nonce"] ENC_VALUE = entry["nonce"]
decrypted_nonce = misc.decrypt_keyvalue( decrypted_nonce = misc.decrypt_keyvalue(
client, BIP32_PATH, ENC_KEY, bytes.fromhex(ENC_VALUE), False, True session, BIP32_PATH, ENC_KEY, bytes.fromhex(ENC_VALUE), False, True
) )
return decrypted_nonce.hex() return decrypted_nonce.hex()
@ -144,13 +145,14 @@ def main() -> None:
print(e) print(e)
return return
client = TrezorClient(transport=transport, ui=ui.ClickUI()) client = TrezorClient(transport=transport)
session = client.get_management_session()
print() print()
print("Confirm operation on Trezor") print("Confirm operation on Trezor")
print() print()
masterKey = getMasterKey(client) masterKey = getMasterKey(session)
# print('master key:', masterKey) # print('master key:', masterKey)
fileName = getFileEncKey(masterKey)[0] fileName = getFileEncKey(masterKey)[0]
@ -173,7 +175,7 @@ def main() -> None:
entry_id = input("Select entry number to decrypt: ") entry_id = input("Select entry number to decrypt: ")
entry_id = str(entry_id) entry_id = str(entry_id)
plain_nonce = getDecryptedNonce(client, entries[entry_id]) plain_nonce = getDecryptedNonce(session, entries[entry_id])
pwdArr = entries[entry_id]["password"]["data"] pwdArr = entries[entry_id]["password"]["data"]
pwdHex = "".join([hex(x)[2:].zfill(2) for x in pwdArr]) pwdHex = "".join([hex(x)[2:].zfill(2) for x in pwdArr])

View File

@ -24,6 +24,8 @@ from __future__ import annotations
from gevent import monkey from gevent import monkey
import trezorlib.transport
monkey.patch_all() monkey.patch_all()
import json import json
@ -103,11 +105,11 @@ class Transport:
self.session: Session | None = None self.session: Session | None = None
self.transport = transport self.transport = transport
client = TrezorClient(transport, ui=SilentUI()) client = TrezorClient(transport) # TODO add silent UI?
self.model = ( self.model = (
trezorlib.models.by_name(client.features.model) or trezorlib.models.TREZOR_T trezorlib.models.by_name(client.features.model) or trezorlib.models.TREZOR_T
) )
client.end_session() # TODO client.end_session()
def acquire(self, sid: str) -> str: def acquire(self, sid: str) -> str:
if self.session_id() != sid: if self.session_id() != sid:
@ -116,11 +118,11 @@ class Transport:
self.session.release() self.session.release()
self.session = Session(self) self.session = Session(self)
self.transport.begin_session() # TODO self.transport.deprecated_begin_session()
return self.session.id return self.session.id
def release(self) -> None: def release(self) -> None:
self.transport.end_session() # TODO self.transport.deprecated_end_session()
self.session = None self.session = None
def session_id(self) -> str | None: def session_id(self) -> str | None:
@ -141,10 +143,14 @@ class Transport:
} }
def write(self, msg_id: int, data: bytes) -> None: def write(self, msg_id: int, data: bytes) -> None:
self.transport.write(msg_id, data) raise NotImplementedError
# TODO
# self.transport.write(msg_id, data)
def read(self) -> tuple[int, bytes]: def read(self) -> tuple[int, bytes]:
return self.transport.read() raise NotImplementedError
# TODO
# return self.transport.read()
@classmethod @classmethod
def find(cls, path: str) -> Transport | None: def find(cls, path: str) -> Transport | None:

View File

@ -7,14 +7,15 @@
import io import io
import sys import sys
from trezorlib import misc, ui from trezorlib import misc
from trezorlib.client import TrezorClient from trezorlib.client import TrezorClient
from trezorlib.transport import get_transport from trezorlib.transport import get_transport
def main() -> None: def main() -> None:
try: try:
client = TrezorClient(get_transport(), ui=ui.ClickUI()) client = TrezorClient(get_transport())
session = client.get_management_session()
except Exception as e: except Exception as e:
print(e) print(e)
return return
@ -25,11 +26,9 @@ def main() -> None:
with io.open(arg1, "wb") as f: with io.open(arg1, "wb") as f:
for _ in range(0, arg2, step): for _ in range(0, arg2, step):
entropy = misc.get_entropy(client, step) entropy = misc.get_entropy(session, step)
f.write(entropy) f.write(entropy)
client.close()
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -27,26 +27,25 @@ from trezorlib.client import TrezorClient
from trezorlib.misc import decrypt_keyvalue, encrypt_keyvalue from trezorlib.misc import decrypt_keyvalue, encrypt_keyvalue
from trezorlib.tools import parse_path from trezorlib.tools import parse_path
from trezorlib.transport import get_transport from trezorlib.transport import get_transport
from trezorlib.ui import ClickUI
BIP32_PATH = parse_path("10016h/0") BIP32_PATH = parse_path("10016h/0")
def encrypt(type: str, domain: str, secret: str) -> str: def encrypt(type: str, domain: str, secret: str) -> str:
transport = get_transport() transport = get_transport()
client = TrezorClient(transport, ClickUI()) client = TrezorClient(transport)
session = client.get_management_session()
dom = type.upper() + ": " + domain dom = type.upper() + ": " + domain
enc = encrypt_keyvalue(client, BIP32_PATH, dom, secret.encode(), False, True) enc = encrypt_keyvalue(session, BIP32_PATH, dom, secret.encode(), False, True)
client.close()
return enc.hex() return enc.hex()
def decrypt(type: str, domain: str, secret: bytes) -> bytes: def decrypt(type: str, domain: str, secret: bytes) -> bytes:
transport = get_transport() transport = get_transport()
client = TrezorClient(transport, ClickUI()) client = TrezorClient(transport)
session = client.get_management_session()
dom = type.upper() + ": " + domain dom = type.upper() + ": " + domain
dec = decrypt_keyvalue(client, BIP32_PATH, dom, secret, False, True) dec = decrypt_keyvalue(session, BIP32_PATH, dom, secret, False, True)
client.close()
return dec return dec