1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2025-05-07 17:39:03 +00:00

chore(python): update python tools

Co-authored-by: mmilata <martin@martinmilata.cz>
This commit is contained in:
M1nd3r 2025-02-04 14:59:20 +01:00
parent c08828814a
commit 909779f848
9 changed files with 70 additions and 48 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,16 +70,18 @@ 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()) d.open()
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
if client.features.label:
sys.stderr.write(f"[{i}] {client.features.label}\n")
else: else:
sys.stderr.write(f"[{i}] <no label>\n") if client.features.label:
client.close() sys.stderr.write(f"[{i}] {client.features.label}\n")
else:
sys.stderr.write(f"[{i}] <no label>\n")
finally:
d.close()
i += 1 i += 1
sys.stderr.write("----------------------------\n") sys.stderr.write("----------------------------\n")
@ -106,7 +107,9 @@ def main() -> None:
devices = wait_for_devices() devices = wait_for_devices()
transport = choose_device(devices) transport = choose_device(devices)
client = TrezorClient(transport, ui=ClickUI()) transport.open()
client = TrezorClient(transport)
session = client.get_seedless_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 +123,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 +132,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,13 +147,14 @@ 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"]),
False, False,
True, True,
) )
transport.close()
print(passw) print(passw)

View File

@ -24,15 +24,19 @@ 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()
# 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, True)
print("Bitcoin address:", address) print("Bitcoin address:", address)
# Release underlying transport (USB/BLE/UDP)
client.transport.close()
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -62,6 +62,8 @@ def main() -> None:
sectoraddrs[sector] + offset, content[offset : offset + step], flash=True sectoraddrs[sector] + offset, content[offset : offset + step], flash=True
) )
debug.close()
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -58,6 +58,7 @@ def main() -> None:
f.write(mem) f.write(mem)
f.close() f.close()
debug.close()
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -39,6 +39,7 @@ def find_debug() -> DebugLink:
def main() -> None: def main() -> None:
debug = find_debug() debug = find_debug()
debug.memory_write(int(sys.argv[1], 16), bytes.fromhex(sys.argv[2]), flash=True) debug.memory_write(int(sys.argv[1], 16), bytes.fromhex(sys.argv[2]), flash=True)
debug.close()
if __name__ == "__main__": if __name__ == "__main__":

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,15 @@ def main() -> None:
print(e) print(e)
return return
client = TrezorClient(transport=transport, ui=ui.ClickUI()) transport.open()
client = TrezorClient(transport=transport)
session = client.get_seedless_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 +176,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])
@ -183,6 +186,8 @@ def main() -> None:
safeNoteHex = "".join([hex(x)[2:].zfill(2) for x in safeNoteArr]) safeNoteHex = "".join([hex(x)[2:].zfill(2) for x in safeNoteArr])
print("safe_note:", decryptEntryValue(plain_nonce, bytes.fromhex(safeNoteHex))) print("safe_note:", decryptEntryValue(plain_nonce, bytes.fromhex(safeNoteHex)))
client.transport.close()
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -36,12 +36,13 @@ import click
from bottle import post, request, response, run from bottle import post, request, response, run
import trezorlib.mapping import trezorlib.mapping
import trezorlib.messages
import trezorlib.models import trezorlib.models
import trezorlib.transport import trezorlib.transport
from trezorlib.client import TrezorClient from trezorlib.client import TrezorClient
from trezorlib.protobuf import format_message from trezorlib.protobuf import format_message
from trezorlib.transport.bridge import BridgeTransport from trezorlib.transport.bridge import BridgeTransport
from trezorlib.ui import TrezorClientUI from trezorlib.transport.thp.protocol_v1 import ProtocolV1Channel
# ignore bridge. we are the bridge # ignore bridge. we are the bridge
BridgeTransport.ENABLED = False BridgeTransport.ENABLED = False
@ -59,15 +60,8 @@ logging.basicConfig(
LOG = logging.getLogger() LOG = logging.getLogger()
class SilentUI(TrezorClientUI): def pin_callback(request: trezorlib.messages.PinMatrixRequest) -> str:
def get_pin(self, _code: t.Any) -> str: return ""
return ""
def get_passphrase(self) -> str:
return ""
def button_request(self, _br: t.Any) -> None:
pass
class Session: class Session:
@ -102,10 +96,15 @@ class Transport:
self.path = transport.get_path() self.path = transport.get_path()
self.session: Session | None = None self.session: Session | None = None
self.transport = transport self.transport = transport
self.protocol = ProtocolV1Channel(transport, trezorlib.mapping.DEFAULT_MAPPING)
client = TrezorClient(transport, ui=SilentUI()) transport.open()
client = TrezorClient(transport)
client.pin_callback = pin_callback
self.model = client.model self.model = client.model
client.end_session()
client.get_seedless_session().end()
transport.close()
def acquire(self, sid: str) -> str: def acquire(self, sid: str) -> str:
if self.session_id() != sid: if self.session_id() != sid:
@ -114,11 +113,11 @@ class Transport:
self.session.release() self.session.release()
self.session = Session(self) self.session = Session(self)
self.transport.begin_session() self.transport.open()
return self.session.id return self.session.id
def release(self) -> None: def release(self) -> None:
self.transport.end_session() self.transport.close()
self.session = None self.session = None
def session_id(self) -> str | None: def session_id(self) -> str | None:
@ -139,10 +138,10 @@ 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) self.protocol._write(msg_id, data)
def read(self) -> tuple[int, bytes]: def read(self) -> tuple[int, bytes]:
return self.transport.read() return self.protocol._read()
@classmethod @classmethod
def find(cls, path: str) -> Transport | None: def find(cls, path: str) -> Transport | None:

View File

@ -7,14 +7,17 @@
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()) transport = get_transport()
transport.open()
client = TrezorClient(transport)
session = client.get_seedless_session()
except Exception as e: except Exception as e:
print(e) print(e)
return return
@ -25,10 +28,10 @@ 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() transport.close()
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -27,26 +27,29 @@ 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()) transport.open()
client = TrezorClient(transport)
session = client.get_seedless_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() transport.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()) transport.open()
client = TrezorClient(transport)
session = client.get_seedless_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() transport.close()
return dec return dec