forked from esp8266/Arduino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsigning.py
executable file
·109 lines (98 loc) · 4.19 KB
/
signing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
import argparse
import hashlib
import os
import struct
import subprocess
import sys
def parse_args():
parser = argparse.ArgumentParser(description='Binary signing tool')
parser.add_argument('-m', '--mode', help='Mode (header, sign)')
parser.add_argument('-b', '--bin', help='Unsigned binary')
parser.add_argument('-o', '--out', help='Output file');
parser.add_argument('-l', '--legacy', help='Legacy output file');
parser.add_argument('-p', '--publickey', help='Public key file');
parser.add_argument('-s', '--privatekey', help='Private(secret) key file');
return parser.parse_args()
def sign_and_write(data, priv_key, out_file):
"""Signs the data (bytes) with the private key (file path)."""
"""Save the signed firmware to out_file (file path)."""
signcmd = [ 'openssl', 'dgst', '-sha256', '-sign', priv_key ]
proc = subprocess.Popen(signcmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
signout, signerr = proc.communicate(input=data)
if proc.returncode:
sys.stderr.write("OpenSSL returned an error signing the binary: " + str(proc.returncode) + "\nSTDERR: " + str(signerr))
else:
with open(out_file, "wb") as out:
out.write(data)
out.write(signout)
out.write(struct.pack("<L", len(signout))) # u32, little-endian
sys.stderr.write("Signed binary: " + out_file + "\n")
def sign_and_write_legacy(data, priv_key, out_file):
"""Signs the data (bytes) with the private key (file path)."""
"""Save the signed firmware to out_file (file path)."""
sha256 = hashlib.sha256(data)
signcmd = [ 'openssl', 'rsautl', '-sign', '-inkey', priv_key ]
proc = subprocess.Popen(signcmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
signout, signerr = proc.communicate(input=sha256.digest())
if proc.returncode:
sys.stderr.write("OpenSSL returned an error legacy signing the binary: " + str(proc.returncode) + "\nSTDERR: " + str(signerr))
else:
with open(out_file, "wb") as out:
out.write(data)
out.write(signout)
out.write(struct.pack("<L", len(signout))) # u32, little-endian
sys.stderr.write("Legacy signed binary: " + out_file + "\n")
def main():
args = parse_args()
if args.mode == "header":
val = ""
try:
with open(args.publickey, "rb") as f:
pub = f.read()
val += "#include <pgmspace.h>\n"
val += "#define ARDUINO_SIGNING 1\n"
val += "static const char signing_pubkey[] PROGMEM = {\n"
for i in bytearray(pub):
val += "0x%02x, \n" % i
val = val[:-3]
val +="\n};\n"
sys.stderr.write("Enabling binary signing\n")
except IOError:
# Silence the default case to avoid people thinking something is wrong.
# Only people who care about signing will know what it means, anyway,
# and they can check for the positive acknowledgement above.
# sys.stderr.write("Not enabling binary signing\n")
val += "#define ARDUINO_SIGNING 0\n"
outdir = os.path.dirname(args.out)
if not os.path.exists(outdir):
os.makedirs(outdir)
try:
with open(args.out, "r") as inp:
old_val = inp.read()
if old_val == val:
return
except Exception:
pass
with open(args.out, "w") as f:
f.write(val)
return 0
elif args.mode == "sign":
if not os.path.isfile(args.privatekey):
return
try:
with open(args.bin, "rb") as b:
bin = b.read()
sign_and_write(bin, args.privatekey, args.out)
if args.legacy:
sign_and_write_legacy(bin, args.privatekey, args.legacy)
except Exception as e:
sys.stderr.write(str(e))
sys.stderr.write("Not signing the generated binary\n")
return 0
else:
sys.stderr.write("ERROR: Mode not specified as header or sign\n")
if __name__ == '__main__':
sys.exit(main())