1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-23 06:48:16 +00:00

adapt python scripts to Python3

This commit is contained in:
Pavol Rusnak 2017-02-01 18:07:47 +01:00
parent 1943d840e3
commit 801ca6e644
No known key found for this signature in database
GPG Key ID: 91F3B339B9A02A3D
6 changed files with 68 additions and 51 deletions

View File

@ -1,4 +1,4 @@
#!/usr/bin/env python2
#!/usr/bin/env python
import sys
import os

View File

@ -1,10 +1,16 @@
#!/usr/bin/env python2
#!/usr/bin/python
from __future__ import print_function
import argparse
import hashlib
import struct
import binascii
import ecdsa
try:
raw_input
except:
raw_input = input
SLOTS = 3
pubkeys = {
@ -31,17 +37,17 @@ def prepare(data):
# Takes raw OR signed firmware and clean out metadata structure
# This produces 'clean' data for signing
meta = 'TRZR' # magic
if data[:4] == 'TRZR':
meta = b'TRZR' # magic
if data[:4] == b'TRZR':
meta += data[4:4 + struct.calcsize('<I')]
else:
meta += struct.pack('<I', len(data)) # length of the code
meta += '\x00' * SLOTS # signature index #1-#3
meta += '\x01' # flags
meta += '\x00' * 52 # reserved
meta += '\x00' * 64 * SLOTS # signature #1-#3
meta += b'\x00' * SLOTS # signature index #1-#3
meta += b'\x01' # flags
meta += b'\x00' * 52 # reserved
meta += b'\x00' * 64 * SLOTS # signature #1-#3
if data[:4] == 'TRZR':
if data[:4] == b'TRZR':
# Replace existing header
out = meta + data[len(meta):]
else:
@ -54,19 +60,22 @@ def check_signatures(data):
# Analyses given firmware and prints out
# status of included signatures
indexes = [ ord(x) for x in data[INDEXES_START:INDEXES_START + SLOTS] ]
try:
indexes = [ ord(x) for x in data[INDEXES_START:INDEXES_START + SLOTS] ]
except:
indexes = [ x for x in data[INDEXES_START:INDEXES_START + SLOTS] ]
to_sign = prepare(data)[256:] # without meta
fingerprint = hashlib.sha256(to_sign).hexdigest()
print "Firmware fingerprint:", fingerprint
print("Firmware fingerprint:", fingerprint)
used = []
for x in range(SLOTS):
signature = data[SIG_START + 64 * x:SIG_START + 64 * x + 64]
if indexes[x] == 0:
print "Slot #%d" % (x + 1), 'is empty'
print("Slot #%d" % (x + 1), 'is empty')
else:
pk = pubkeys[indexes[x]]
verify = ecdsa.VerifyingKey.from_string(binascii.unhexlify(pk)[1:],
@ -76,13 +85,13 @@ def check_signatures(data):
verify.verify(signature, to_sign, hashfunc=hashlib.sha256)
if indexes[x] in used:
print "Slot #%d signature: DUPLICATE" % (x + 1), binascii.hexlify(signature)
print("Slot #%d signature: DUPLICATE" % (x + 1), binascii.hexlify(signature))
else:
used.append(indexes[x])
print "Slot #%d signature: VALID" % (x + 1), binascii.hexlify(signature)
print("Slot #%d signature: VALID" % (x + 1), binascii.hexlify(signature))
except:
print "Slot #%d signature: INVALID" % (x + 1), binascii.hexlify(signature)
print("Slot #%d signature: INVALID" % (x + 1), binascii.hexlify(signature))
def modify(data, slot, index, signature):
@ -104,8 +113,8 @@ def sign(data, is_pem):
raise Exception("Invalid slot")
if is_pem:
print "Paste ECDSA private key in PEM format and press Enter:"
print "(blank private key removes the signature on given index)"
print("Paste ECDSA private key in PEM format and press Enter:")
print("(blank private key removes the signature on given index)")
pem_key = ''
while True:
key = raw_input()
@ -117,8 +126,8 @@ def sign(data, is_pem):
return modify(data, slot, 0, '\x00' * 64)
key = ecdsa.SigningKey.from_pem(pem_key)
else:
print "Paste SECEXP (in hex) and press Enter:"
print "(blank private key removes the signature on given index)"
print("Paste SECEXP (in hex) and press Enter:")
print("(blank private key removes the signature on given index)")
secexp = raw_input()
if secexp.strip() == '':
# Blank key,let's remove existing signature from slot
@ -128,9 +137,9 @@ def sign(data, is_pem):
to_sign = prepare(data)[256:] # without meta
# Locate proper index of current signing key
pubkey = '04' + binascii.hexlify(key.get_verifying_key().to_string())
pubkey = b'04' + binascii.hexlify(key.get_verifying_key().to_string())
index = None
for i, pk in pubkeys.iteritems():
for i, pk in pubkeys.items():
if pk == pubkey:
index = i
break
@ -148,15 +157,15 @@ def main(args):
curve=ecdsa.curves.SECP256k1,
hashfunc=hashlib.sha256)
print "PRIVATE KEY (SECEXP):"
print binascii.hexlify(key.to_string())
print
print("PRIVATE KEY (SECEXP):")
print(binascii.hexlify(key.to_string()))
print()
print "PRIVATE KEY (PEM):"
print key.to_pem()
print("PRIVATE KEY (PEM):")
print(key.to_pem())
print "PUBLIC KEY:"
print '04' + binascii.hexlify(key.get_verifying_key().to_string())
print("PUBLIC KEY:")
print('04' + binascii.hexlify(key.get_verifying_key().to_string()))
return
if not args.path:
@ -165,14 +174,14 @@ def main(args):
data = open(args.path, 'rb').read()
assert len(data) % 4 == 0
if data[:4] != 'TRZR':
print "Metadata has been added..."
if data[:4] != b'TRZR':
print("Metadata has been added...")
data = prepare(data)
if data[:4] != 'TRZR':
if data[:4] != b'TRZR':
raise Exception("Firmware header expected")
print "Firmware size %d bytes" % len(data)
print("Firmware size %d bytes" % len(data))
check_signatures(data)

View File

@ -1,27 +1,31 @@
#!/usr/bin/env python2
#!/usr/bin/env python
from __future__ import print_function
import hashlib
import os
import subprocess
import ecdsa
from binascii import hexlify, unhexlify
print 'master secret:',
h = raw_input()
print('master secret:', end='')
try:
h = raw_input()
except:
h = input()
if h:
h = unhexlify(h)
h = unhexlify(h).encode('ascii')
else:
h = hashlib.sha256(os.urandom(1024)).digest()
print
print 'master secret:', hexlify(h)
print
print()
print('master secret:', hexlify(h))
print()
for i in range(1, 6):
se = hashlib.sha256(h + chr(i)).hexdigest()
print 'seckey', i, ':', se
se = hashlib.sha256(h + chr(i).encode('ascii')).hexdigest()
print('seckey', i, ':', se)
sk = ecdsa.SigningKey.from_secret_exponent(secexp = int(se, 16), curve=ecdsa.curves.SECP256k1, hashfunc=hashlib.sha256)
print 'pubkey', i, ':', '04' + hexlify(sk.get_verifying_key().to_string())
print sk.to_pem()
print('pubkey', i, ':', (b'04' + hexlify(sk.get_verifying_key().to_string())).decode('ascii'))
print(sk.to_pem().decode('ascii'))
p = subprocess.Popen('ssss-split -t 3 -n 5 -x'.split(' '), stdin = subprocess.PIPE)
p.communicate(input = hexlify(h) + '\n')

View File

@ -1,4 +1,5 @@
#!/usr/bin/env python2
#!/usr/bin/env python
from __future__ import print_function
import glob
import os
from PIL import Image
@ -10,14 +11,14 @@ imgs = []
def encode_pixels(img):
r = ''
img = [ (x[0] + x[1] + x[2] > 384 and '1' or '0') for x in img]
for i in range(len(img) / 8):
for i in range(len(img) // 8):
c = ''.join(img[i * 8 : i * 8 + 8])
r += '0x%02x, ' % int(c, 2)
return r
cnt = 0
for fn in sorted(glob.glob('*.png')):
print 'Processing:', fn
print('Processing:', fn)
im = Image.open(fn)
name = os.path.splitext(fn)[0]
w, h = im.size

View File

@ -1,4 +1,5 @@
#!/usr/bin/env python2
#!/usr/bin/env python
from __future__ import print_function
from PIL import Image
class Img(object):
@ -23,12 +24,12 @@ cur = ''
for i in range(256):
x = (i % 16) * 10
y = (i / 16) * 10
y = (i // 16) * 10
cur = ''
while img.pixel(x, y) != None:
val = ''.join(img.pixel(x, y + j) for j in range(8))
x += 1
cur += '\\x%02x' % int(val, 2)
cur = '\\x%02x' % (len(cur) / 4) + cur
cur = '\\x%02x' % (len(cur) // 4) + cur
ch = chr(i) if i >= 32 and i <= 126 else '_'
print '\t/* 0x%02x %c */ (uint8_t *)"%s",' % (i, ch , cur)
print('\t/* 0x%02x %c */ (uint8_t *)"%s",' % (i, ch , cur))

View File

@ -1,4 +1,6 @@
#!/usr/bin/env python2
#!/usr/bin/env python
from __future__ import print_function
handlers = [
'hard_fault_handler',
'mem_manage_handler',