blob: 476884c3a55c40cc5a56fbe2ad151e255b1cdcd4 [file] [log] [blame]
Fabio Utzige89841d2018-12-21 11:19:06 -02001#! /usr/bin/env python3
2#
3# Copyright 2017 Linaro Limited
David Vinczeda8c9192019-03-26 17:17:41 +01004# Copyright 2019 Arm Limited
Fabio Utzige89841d2018-12-21 11:19:06 -02005#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
David Vinczeda8c9192019-03-26 17:17:41 +010018import re
Fabio Utzige89841d2018-12-21 11:19:06 -020019import click
20import getpass
21import imgtool.keys as keys
Fabio Utzig4a5477a2019-05-27 15:45:08 -030022import sys
Fabio Utzige89841d2018-12-21 11:19:06 -020023from imgtool import image
24from imgtool.version import decode_version
25
26
27def gen_rsa2048(keyfile, passwd):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030028 keys.RSA.generate().export_private(path=keyfile, passwd=passwd)
29
30
31def gen_rsa3072(keyfile, passwd):
32 keys.RSA.generate(key_size=3072).export_private(path=keyfile,
33 passwd=passwd)
Fabio Utzige89841d2018-12-21 11:19:06 -020034
35
36def gen_ecdsa_p256(keyfile, passwd):
37 keys.ECDSA256P1.generate().export_private(keyfile, passwd=passwd)
38
39
40def gen_ecdsa_p224(keyfile, passwd):
41 print("TODO: p-224 not yet implemented")
42
43
44valid_langs = ['c', 'rust']
45keygens = {
46 'rsa-2048': gen_rsa2048,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030047 'rsa-3072': gen_rsa3072,
Fabio Utzige89841d2018-12-21 11:19:06 -020048 'ecdsa-p256': gen_ecdsa_p256,
49 'ecdsa-p224': gen_ecdsa_p224,
50}
51
52
53def load_key(keyfile):
54 # TODO: better handling of invalid pass-phrase
55 key = keys.load(keyfile)
56 if key is not None:
57 return key
58 passwd = getpass.getpass("Enter key passphrase: ").encode('utf-8')
59 return keys.load(keyfile, passwd)
60
61
62def get_password():
63 while True:
64 passwd = getpass.getpass("Enter key passphrase: ")
65 passwd2 = getpass.getpass("Reenter passphrase: ")
66 if passwd == passwd2:
67 break
68 print("Passwords do not match, try again")
69
70 # Password must be bytes, always use UTF-8 for consistent
71 # encoding.
72 return passwd.encode('utf-8')
73
74
75@click.option('-p', '--password', is_flag=True,
76 help='Prompt for password to protect key')
77@click.option('-t', '--type', metavar='type', required=True,
78 type=click.Choice(keygens.keys()))
79@click.option('-k', '--key', metavar='filename', required=True)
80@click.command(help='Generate pub/private keypair')
81def keygen(type, key, password):
82 password = get_password() if password else None
83 keygens[type](key, password)
84
85
86@click.option('-l', '--lang', metavar='lang', default=valid_langs[0],
87 type=click.Choice(valid_langs))
88@click.option('-k', '--key', metavar='filename', required=True)
89@click.command(help='Get public key from keypair')
90def getpub(key, lang):
91 key = load_key(key)
92 if key is None:
93 print("Invalid passphrase")
94 elif lang == 'c':
95 key.emit_c()
96 elif lang == 'rust':
97 key.emit_rust()
98 else:
99 raise ValueError("BUG: should never get here!")
100
101
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300102@click.argument('imgfile')
103@click.option('-k', '--key', metavar='filename')
104@click.command(help="Check that signed image can be verified by given key")
105def verify(key, imgfile):
106 key = load_key(key) if key else None
107 ret = image.Image.verify(imgfile, key)
108 if ret == image.VerifyResult.OK:
109 print("Image was correctly validated")
110 return
111 elif ret == image.VerifyResult.INVALID_MAGIC:
112 print("Invalid image magic; is this an MCUboot image?")
113 elif ret == image.VerifyResult.INVALID_MAGIC:
114 print("Invalid TLV info magic; is this an MCUboot image?")
115 elif ret == image.VerifyResult.INVALID_HASH:
116 print("Image has an invalid sha256 digest")
117 elif ret == image.VerifyResult.INVALID_SIGNATURE:
118 print("No signature found for the given key")
119 sys.exit(1)
120
121
Fabio Utzige89841d2018-12-21 11:19:06 -0200122def validate_version(ctx, param, value):
123 try:
124 decode_version(value)
125 return value
126 except ValueError as e:
127 raise click.BadParameter("{}".format(e))
128
129
130def validate_header_size(ctx, param, value):
131 min_hdr_size = image.IMAGE_HEADER_SIZE
132 if value < min_hdr_size:
133 raise click.BadParameter(
134 "Minimum value for -H/--header-size is {}".format(min_hdr_size))
135 return value
136
137
David Vinczeda8c9192019-03-26 17:17:41 +0100138def get_dependencies(ctx, param, value):
139 if value is not None:
140 versions = []
141 images = re.findall(r"\((\d+)", value)
142 if len(images) == 0:
143 raise click.BadParameter(
144 "Image dependency format is invalid: {}".format(value))
145 raw_versions = re.findall(r",\s*([0-9.+]+)\)", value)
146 if len(images) != len(raw_versions):
147 raise click.BadParameter(
148 '''There's a mismatch between the number of dependency images
149 and versions in: {}'''.format(value))
150 for raw_version in raw_versions:
151 try:
152 versions.append(decode_version(raw_version))
153 except ValueError as e:
154 raise click.BadParameter("{}".format(e))
155 dependencies = dict()
156 dependencies[image.DEP_IMAGES_KEY] = images
157 dependencies[image.DEP_VERSIONS_KEY] = versions
158 return dependencies
159
160
Fabio Utzige89841d2018-12-21 11:19:06 -0200161class BasedIntParamType(click.ParamType):
162 name = 'integer'
163
164 def convert(self, value, param, ctx):
165 try:
166 if value[:2].lower() == '0x':
167 return int(value[2:], 16)
168 elif value[:1] == '0':
169 return int(value, 8)
170 return int(value, 10)
171 except ValueError:
172 self.fail('%s is not a valid integer' % value, param, ctx)
173
174
175@click.argument('outfile')
176@click.argument('infile')
177@click.option('-E', '--encrypt', metavar='filename',
178 help='Encrypt image using the provided public key')
179@click.option('-e', '--endian', type=click.Choice(['little', 'big']),
180 default='little', help="Select little or big endian")
181@click.option('--overwrite-only', default=False, is_flag=True,
182 help='Use overwrite-only instead of swap upgrades')
183@click.option('-M', '--max-sectors', type=int,
184 help='When padding allow for this amount of sectors (defaults to 128)')
185@click.option('--pad', default=False, is_flag=True,
186 help='Pad image to --slot-size bytes, adding trailer magic')
187@click.option('-S', '--slot-size', type=BasedIntParamType(), required=True,
188 help='Size of the slot where the image will be written')
189@click.option('--pad-header', default=False, is_flag=True,
190 help='Add --header-size zeroed bytes at the beginning of the image')
191@click.option('-H', '--header-size', callback=validate_header_size,
192 type=BasedIntParamType(), required=True)
David Vinczeda8c9192019-03-26 17:17:41 +0100193@click.option('-d', '--dependencies', callback=get_dependencies,
194 required=False, help='''Add dependence on another image, format:
195 "(<image_ID>,<image_version>), ... "''')
Fabio Utzige89841d2018-12-21 11:19:06 -0200196@click.option('-v', '--version', callback=validate_version, required=True)
197@click.option('--align', type=click.Choice(['1', '2', '4', '8']),
198 required=True)
199@click.option('-k', '--key', metavar='filename')
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200200@click.command(help='''Create a signed or unsigned image\n
201 INFILE and OUTFILE are parsed as Intel HEX if the params have
202 .hex extension, othewise binary format is used''')
Fabio Utzige89841d2018-12-21 11:19:06 -0200203def sign(key, align, version, header_size, pad_header, slot_size, pad,
David Vinczeda8c9192019-03-26 17:17:41 +0100204 max_sectors, overwrite_only, endian, encrypt, infile, outfile,
205 dependencies):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200206 img = image.Image(version=decode_version(version), header_size=header_size,
207 pad_header=pad_header, pad=pad, align=int(align),
208 slot_size=slot_size, max_sectors=max_sectors,
209 overwrite_only=overwrite_only, endian=endian)
210 img.load(infile)
Fabio Utzige89841d2018-12-21 11:19:06 -0200211 key = load_key(key) if key else None
212 enckey = load_key(encrypt) if encrypt else None
213 if enckey:
Fabio Utzig19fd79a2019-05-08 18:20:39 -0300214 if not isinstance(enckey, (keys.RSA, keys.RSAPublic)):
Chris Bittnerfda937a2019-03-29 10:11:31 +0100215 raise Exception("Encryption only available with RSA key")
Fabio Utzig19fd79a2019-05-08 18:20:39 -0300216 if key and not isinstance(key, keys.RSA):
Chris Bittnerfda937a2019-03-29 10:11:31 +0100217 raise Exception("Signing only available with private RSA key")
David Vinczeda8c9192019-03-26 17:17:41 +0100218 img.create(key, enckey, dependencies)
Fabio Utzige89841d2018-12-21 11:19:06 -0200219 img.save(outfile)
220
221
222class AliasesGroup(click.Group):
223
224 _aliases = {
225 "create": "sign",
226 }
227
228 def list_commands(self, ctx):
229 cmds = [k for k in self.commands]
230 aliases = [k for k in self._aliases]
231 return sorted(cmds + aliases)
232
233 def get_command(self, ctx, cmd_name):
234 rv = click.Group.get_command(self, ctx, cmd_name)
235 if rv is not None:
236 return rv
237 if cmd_name in self._aliases:
238 return click.Group.get_command(self, ctx, self._aliases[cmd_name])
239 return None
240
241
242@click.command(cls=AliasesGroup,
243 context_settings=dict(help_option_names=['-h', '--help']))
244def imgtool():
245 pass
246
247
248imgtool.add_command(keygen)
249imgtool.add_command(getpub)
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300250imgtool.add_command(verify)
Fabio Utzige89841d2018-12-21 11:19:06 -0200251imgtool.add_command(sign)
252
253
254if __name__ == '__main__':
255 imgtool()