2017-10-05 05:41:36 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
import binascii
|
2018-01-29 14:02:32 +00:00
|
|
|
import struct
|
2017-10-05 05:41:36 +00:00
|
|
|
import click
|
|
|
|
import pyblake2
|
|
|
|
from trezorlib import ed25519raw, ed25519cosi
|
|
|
|
|
|
|
|
indexmap = {
|
|
|
|
'bootloader': 0,
|
|
|
|
'vendorheader': 1,
|
|
|
|
'firmware': 2,
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2018-01-29 14:02:32 +00:00
|
|
|
def header_digest(index, filename):
|
|
|
|
data = open(filename, 'rb').read()
|
2018-01-28 16:30:46 +00:00
|
|
|
z = bytes(65 * [0x00])
|
2018-01-29 08:10:19 +00:00
|
|
|
if index == 'bootloader':
|
2018-01-29 14:02:32 +00:00
|
|
|
header = data[:0x03BF] + z
|
2018-01-29 08:10:19 +00:00
|
|
|
elif index == 'vendorheader':
|
2018-01-29 14:02:32 +00:00
|
|
|
header = data[:-65] + z
|
2018-01-29 08:10:19 +00:00
|
|
|
elif index == 'firmware':
|
2018-01-29 07:09:02 +00:00
|
|
|
vhdrlen = struct.unpack('<I', data[4:8])[0]
|
2018-01-29 14:02:32 +00:00
|
|
|
header = data[vhdrlen:vhdrlen + 0x03BF] + z
|
2018-01-29 08:10:19 +00:00
|
|
|
else:
|
|
|
|
raise ValueError('Unknown index "%s"' % index)
|
2018-01-29 14:02:32 +00:00
|
|
|
return pyblake2.blake2s(header).digest()
|
2018-01-28 16:30:46 +00:00
|
|
|
|
|
|
|
|
2017-10-05 05:41:36 +00:00
|
|
|
@click.group()
|
|
|
|
def cli():
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
@cli.command(help='')
|
|
|
|
@click.argument('index', type=click.Choice(indexmap.keys()))
|
|
|
|
@click.argument('filename')
|
2018-01-29 14:02:32 +00:00
|
|
|
@click.argument('seckeys', nargs=-1)
|
|
|
|
def sign(index, filename, seckeys):
|
|
|
|
# compute header digest
|
|
|
|
digest = header_digest(index, filename)
|
|
|
|
# collect commits
|
|
|
|
pks, Rs = [], []
|
|
|
|
for ctr, seckey in enumerate(seckeys):
|
2017-10-05 05:41:36 +00:00
|
|
|
sk = binascii.unhexlify(seckey)
|
|
|
|
pk = ed25519raw.publickey(sk)
|
|
|
|
_, R = ed25519cosi.get_nonce(sk, digest, ctr)
|
2018-01-29 14:02:32 +00:00
|
|
|
pks.append(pk)
|
|
|
|
Rs.append(R)
|
|
|
|
# compute global commit
|
|
|
|
global_pk = ed25519cosi.combine_keys(pks)
|
|
|
|
global_R = ed25519cosi.combine_keys(Rs)
|
|
|
|
# collect signatures
|
|
|
|
sigs = []
|
|
|
|
for ctr, seckey in enumerate(seckeys):
|
2017-10-05 05:41:36 +00:00
|
|
|
sk = binascii.unhexlify(seckey)
|
|
|
|
r, _ = ed25519cosi.get_nonce(sk, digest, ctr)
|
|
|
|
h = ed25519raw.H(sk)
|
|
|
|
b = ed25519raw.b
|
|
|
|
a = 2 ** (b - 2) + sum(2 ** i * ed25519raw.bit(h, i) for i in range(3, b - 2))
|
|
|
|
S = (r + ed25519raw.Hint(global_R + global_pk + digest) * a) % ed25519raw.l
|
|
|
|
sig = ed25519raw.encodeint(S)
|
2018-01-29 14:02:32 +00:00
|
|
|
sigs.append(sig)
|
|
|
|
# compute global signature
|
|
|
|
sig = ed25519cosi.combine_sig(global_R, sigs)
|
2017-10-05 05:41:36 +00:00
|
|
|
ed25519raw.checkvalid(sig, digest, global_pk)
|
|
|
|
print(binascii.hexlify(sig).decode())
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
cli()
|