#!/usr/bin/env python3 import sys import struct import binascii import ed25519 import pyblake2 def get_sig(data): print('Enter privkey: ', end='') seckey = binascii.unhexlify(input()) signkey = ed25519.SigningKey(seckey) digest = pyblake2.blake2s(data).digest() sigmask = 0x01 # (1 _ _ _ _) sig = signkey.sign(digest) return sigmask, sig # loader/firmware headers specification: https://github.com/trezor/trezor-core/blob/master/docs/bootloader.md class BinImage: def __init__(self, data, magic, max_size): header = struct.unpack('<4sIIIBBBB427sB64s', data[:512]) self.magic, \ self.hdrlen, \ self.expiry, \ self.codelen, \ self.vmajor, \ self.vminor, \ self.vpatch, \ self.vbuild, \ self.reserved, \ self.sigmask, \ self.sig = header assert self.magic == magic assert self.hdrlen == 512 total_len = self.hdrlen + self.codelen assert total_len % 512 == 0 assert total_len >= 4 * 1024 assert total_len <= max_size assert self.reserved == 427 * b'\x00' self.code = data[self.hdrlen:] assert len(self.code) == self.codelen def print(self): if self.magic == b'TRZF': print('TREZOR Firmware Image') elif self.magic == b'TRZL': print('TREZOR Loader Image') else: print('TREZOR Unknown Image') print(' * magic :', self.magic.decode('ascii')) print(' * hdrlen :', self.hdrlen) print(' * expiry :', self.expiry) print(' * codelen :', self.codelen) print(' * version : %d.%d.%d.%d' % (self.vmajor, self.vminor, self.vpatch, self.vbuild)) print(' * sigmask :', self.sigmask) print(' * sig :', binascii.hexlify(self.sig).decode('ascii')) def serialize_header(self, sig=True): header = struct.pack('<4sIIIBBBB427s', \ self.magic, self.hdrlen, self.expiry, self.codelen, \ self.vmajor, self.vminor, self.vpatch, self.vbuild, \ self.reserved) if sig: header += struct.pack(' 0 and self.vsig_m <= self.vsig_n assert self.vsig_n > 0 and self.vsig_n <= 8 p = 16 self.vpub = [] for _ in range(self.vsig_n): self.vpub.append(data[p:p + 32]) p += 32 self.vstr_len = data[p] p += 1 self.vstr = data[p:p + self.vstr_len] p += self.vstr_len self.vimg_len, _ = struct.unpack(' 2 and sys.argv[2] == '-s' b = binopen(fn) b.print() if sign: print() b.sign() print() b.print() b.write(fn) if __name__ == '__main__': main()