blob: 436f3bea1ceb61f03adaae34099f2a9dd687894e [file] [log] [blame]
Fabio Utzige89841d2018-12-21 11:19:06 -02001#! /usr/bin/env python3
2#
3# Copyright 2017 Linaro Limited
David Vincze1a7a6902020-02-18 15:05:16 +01004# Copyright 2019-2020 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 Utzig25c6a152019-09-10 12:52:26 -030023from imgtool import image, imgtool_version
Fabio Utzige89841d2018-12-21 11:19:06 -020024from imgtool.version import decode_version
Fabio Utzig1f508922020-01-15 11:37:51 -030025from .keys import RSAUsageError, ECDSAUsageError, Ed25519UsageError
Fabio Utzige89841d2018-12-21 11:19:06 -020026
27
28def gen_rsa2048(keyfile, passwd):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030029 keys.RSA.generate().export_private(path=keyfile, passwd=passwd)
30
31
32def gen_rsa3072(keyfile, passwd):
33 keys.RSA.generate(key_size=3072).export_private(path=keyfile,
34 passwd=passwd)
Fabio Utzige89841d2018-12-21 11:19:06 -020035
36
37def gen_ecdsa_p256(keyfile, passwd):
38 keys.ECDSA256P1.generate().export_private(keyfile, passwd=passwd)
39
40
41def gen_ecdsa_p224(keyfile, passwd):
42 print("TODO: p-224 not yet implemented")
43
44
Fabio Utzig8101d1f2019-05-09 15:03:22 -030045def gen_ed25519(keyfile, passwd):
Fabio Utzig4bd4c7c2019-06-27 08:23:21 -030046 keys.Ed25519.generate().export_private(path=keyfile, passwd=passwd)
Fabio Utzig8101d1f2019-05-09 15:03:22 -030047
48
Fabio Utzige89841d2018-12-21 11:19:06 -020049valid_langs = ['c', 'rust']
50keygens = {
51 'rsa-2048': gen_rsa2048,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030052 'rsa-3072': gen_rsa3072,
Fabio Utzige89841d2018-12-21 11:19:06 -020053 'ecdsa-p256': gen_ecdsa_p256,
54 'ecdsa-p224': gen_ecdsa_p224,
Fabio Utzig8101d1f2019-05-09 15:03:22 -030055 'ed25519': gen_ed25519,
Fabio Utzige89841d2018-12-21 11:19:06 -020056}
57
58
59def load_key(keyfile):
60 # TODO: better handling of invalid pass-phrase
61 key = keys.load(keyfile)
62 if key is not None:
63 return key
64 passwd = getpass.getpass("Enter key passphrase: ").encode('utf-8')
65 return keys.load(keyfile, passwd)
66
67
68def get_password():
69 while True:
70 passwd = getpass.getpass("Enter key passphrase: ")
71 passwd2 = getpass.getpass("Reenter passphrase: ")
72 if passwd == passwd2:
73 break
74 print("Passwords do not match, try again")
75
76 # Password must be bytes, always use UTF-8 for consistent
77 # encoding.
78 return passwd.encode('utf-8')
79
80
81@click.option('-p', '--password', is_flag=True,
82 help='Prompt for password to protect key')
83@click.option('-t', '--type', metavar='type', required=True,
Fabio Utzig7ca28552019-12-13 11:24:20 -030084 type=click.Choice(keygens.keys()), prompt=True,
85 help='{}'.format('One of: {}'.format(', '.join(keygens.keys()))))
Fabio Utzige89841d2018-12-21 11:19:06 -020086@click.option('-k', '--key', metavar='filename', required=True)
87@click.command(help='Generate pub/private keypair')
88def keygen(type, key, password):
89 password = get_password() if password else None
90 keygens[type](key, password)
91
92
93@click.option('-l', '--lang', metavar='lang', default=valid_langs[0],
94 type=click.Choice(valid_langs))
95@click.option('-k', '--key', metavar='filename', required=True)
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020096@click.command(help='Dump public key from keypair')
Fabio Utzige89841d2018-12-21 11:19:06 -020097def getpub(key, lang):
98 key = load_key(key)
99 if key is None:
100 print("Invalid passphrase")
101 elif lang == 'c':
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200102 key.emit_c_public()
Fabio Utzige89841d2018-12-21 11:19:06 -0200103 elif lang == 'rust':
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200104 key.emit_rust_public()
Fabio Utzige89841d2018-12-21 11:19:06 -0200105 else:
106 raise ValueError("BUG: should never get here!")
107
108
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200109@click.option('--minimal', default=False, is_flag=True,
110 help='Reduce the size of the dumped private key to include only '
111 'the minimum amount of data required to decrypt. This '
112 'might require changes to the build config. Check the docs!'
113 )
114@click.option('-k', '--key', metavar='filename', required=True)
115@click.command(help='Dump private key from keypair')
116def getpriv(key, minimal):
117 key = load_key(key)
118 if key is None:
119 print("Invalid passphrase")
Fabio Utzig1f508922020-01-15 11:37:51 -0300120 try:
121 key.emit_private(minimal)
122 except (RSAUsageError, ECDSAUsageError, Ed25519UsageError) as e:
123 raise click.UsageError(e)
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200124
125
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300126@click.argument('imgfile')
127@click.option('-k', '--key', metavar='filename')
128@click.command(help="Check that signed image can be verified by given key")
129def verify(key, imgfile):
130 key = load_key(key) if key else None
Marek Pietae9555102019-08-08 16:08:16 +0200131 ret, version = image.Image.verify(imgfile, key)
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300132 if ret == image.VerifyResult.OK:
133 print("Image was correctly validated")
Marek Pietae9555102019-08-08 16:08:16 +0200134 print("Image version: {}.{}.{}+{}".format(*version))
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300135 return
136 elif ret == image.VerifyResult.INVALID_MAGIC:
137 print("Invalid image magic; is this an MCUboot image?")
Christian Skubichf13db122019-07-31 11:34:15 +0200138 elif ret == image.VerifyResult.INVALID_TLV_INFO_MAGIC:
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300139 print("Invalid TLV info magic; is this an MCUboot image?")
140 elif ret == image.VerifyResult.INVALID_HASH:
141 print("Image has an invalid sha256 digest")
142 elif ret == image.VerifyResult.INVALID_SIGNATURE:
143 print("No signature found for the given key")
Christian Skubichf13db122019-07-31 11:34:15 +0200144 else:
145 print("Unknown return code: {}".format(ret))
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300146 sys.exit(1)
147
148
Fabio Utzige89841d2018-12-21 11:19:06 -0200149def validate_version(ctx, param, value):
150 try:
151 decode_version(value)
152 return value
153 except ValueError as e:
154 raise click.BadParameter("{}".format(e))
155
156
David Vincze1a7a6902020-02-18 15:05:16 +0100157def validate_security_counter(ctx, param, value):
158 if value is not None:
159 if value.lower() == 'auto':
160 return 'auto'
161 else:
162 try:
163 return int(value, 0)
164 except ValueError:
165 raise click.BadParameter(
166 "{} is not a valid integer. Please use code literals "
167 "prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary."
168 .format(value))
169
170
Fabio Utzige89841d2018-12-21 11:19:06 -0200171def validate_header_size(ctx, param, value):
172 min_hdr_size = image.IMAGE_HEADER_SIZE
173 if value < min_hdr_size:
174 raise click.BadParameter(
175 "Minimum value for -H/--header-size is {}".format(min_hdr_size))
176 return value
177
178
David Vinczeda8c9192019-03-26 17:17:41 +0100179def get_dependencies(ctx, param, value):
180 if value is not None:
181 versions = []
182 images = re.findall(r"\((\d+)", value)
183 if len(images) == 0:
184 raise click.BadParameter(
185 "Image dependency format is invalid: {}".format(value))
186 raw_versions = re.findall(r",\s*([0-9.+]+)\)", value)
187 if len(images) != len(raw_versions):
188 raise click.BadParameter(
189 '''There's a mismatch between the number of dependency images
190 and versions in: {}'''.format(value))
191 for raw_version in raw_versions:
192 try:
193 versions.append(decode_version(raw_version))
194 except ValueError as e:
195 raise click.BadParameter("{}".format(e))
196 dependencies = dict()
197 dependencies[image.DEP_IMAGES_KEY] = images
198 dependencies[image.DEP_VERSIONS_KEY] = versions
199 return dependencies
200
201
Fabio Utzige89841d2018-12-21 11:19:06 -0200202class BasedIntParamType(click.ParamType):
203 name = 'integer'
204
205 def convert(self, value, param, ctx):
206 try:
David Vincze1a7a6902020-02-18 15:05:16 +0100207 return int(value, 0)
Fabio Utzige89841d2018-12-21 11:19:06 -0200208 except ValueError:
David Vincze1a7a6902020-02-18 15:05:16 +0100209 self.fail('%s is not a valid integer. Please use code literals '
210 'prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary.'
211 % value, param, ctx)
Fabio Utzige89841d2018-12-21 11:19:06 -0200212
213
214@click.argument('outfile')
215@click.argument('infile')
Fabio Utzig9117fde2019-10-17 11:11:46 -0300216@click.option('-R', '--erased-val', type=click.Choice(['0', '0xff']),
217 required=False,
218 help='The value that is read back from erased flash.')
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300219@click.option('-x', '--hex-addr', type=BasedIntParamType(), required=False,
220 help='Adjust address in hex output file.')
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000221@click.option('-L', '--load-addr', type=BasedIntParamType(), required=False,
222 help='Load address for image when it is in its primary slot.')
Fabio Utzig9a492d52020-01-15 11:31:52 -0300223@click.option('--save-enctlv', default=False, is_flag=True,
224 help='When upgrading, save encrypted key TLVs instead of plain '
225 'keys. Enable when BOOT_SWAP_SAVE_ENCTLV config option '
226 'was set.')
Fabio Utzige89841d2018-12-21 11:19:06 -0200227@click.option('-E', '--encrypt', metavar='filename',
228 help='Encrypt image using the provided public key')
229@click.option('-e', '--endian', type=click.Choice(['little', 'big']),
230 default='little', help="Select little or big endian")
231@click.option('--overwrite-only', default=False, is_flag=True,
232 help='Use overwrite-only instead of swap upgrades')
233@click.option('-M', '--max-sectors', type=int,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300234 help='When padding allow for this amount of sectors (defaults '
235 'to 128)')
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100236@click.option('--confirm', default=False, is_flag=True,
237 help='When padding the image, mark it as confirmed')
Fabio Utzige89841d2018-12-21 11:19:06 -0200238@click.option('--pad', default=False, is_flag=True,
239 help='Pad image to --slot-size bytes, adding trailer magic')
240@click.option('-S', '--slot-size', type=BasedIntParamType(), required=True,
241 help='Size of the slot where the image will be written')
242@click.option('--pad-header', default=False, is_flag=True,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300243 help='Add --header-size zeroed bytes at the beginning of the '
244 'image')
Fabio Utzige89841d2018-12-21 11:19:06 -0200245@click.option('-H', '--header-size', callback=validate_header_size,
246 type=BasedIntParamType(), required=True)
David Vinczeda8c9192019-03-26 17:17:41 +0100247@click.option('-d', '--dependencies', callback=get_dependencies,
248 required=False, help='''Add dependence on another image, format:
249 "(<image_ID>,<image_version>), ... "''')
David Vincze1a7a6902020-02-18 15:05:16 +0100250@click.option('-s', '--security-counter', callback=validate_security_counter,
251 help='Specify the value of security counter. Use the `auto` '
252 'keyword to automatically generate it from the image version.')
Fabio Utzige89841d2018-12-21 11:19:06 -0200253@click.option('-v', '--version', callback=validate_version, required=True)
254@click.option('--align', type=click.Choice(['1', '2', '4', '8']),
255 required=True)
256@click.option('-k', '--key', metavar='filename')
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200257@click.command(help='''Create a signed or unsigned image\n
258 INFILE and OUTFILE are parsed as Intel HEX if the params have
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000259 .hex extension, otherwise binary format is used''')
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100260def sign(key, align, version, header_size, pad_header, slot_size, pad, confirm,
David Vinczeda8c9192019-03-26 17:17:41 +0100261 max_sectors, overwrite_only, endian, encrypt, infile, outfile,
David Vincze1a7a6902020-02-18 15:05:16 +0100262 dependencies, load_addr, hex_addr, erased_val, save_enctlv,
263 security_counter):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200264 img = image.Image(version=decode_version(version), header_size=header_size,
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100265 pad_header=pad_header, pad=pad, confirm=confirm,
266 align=int(align), slot_size=slot_size,
267 max_sectors=max_sectors, overwrite_only=overwrite_only,
268 endian=endian, load_addr=load_addr, erased_val=erased_val,
David Vincze1a7a6902020-02-18 15:05:16 +0100269 save_enctlv=save_enctlv,
270 security_counter=security_counter)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200271 img.load(infile)
Fabio Utzige89841d2018-12-21 11:19:06 -0200272 key = load_key(key) if key else None
273 enckey = load_key(encrypt) if encrypt else None
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300274 if enckey and key:
275 if ((isinstance(key, keys.ECDSA256P1) and
276 not isinstance(enckey, keys.ECDSA256P1Public))
277 or (isinstance(key, keys.RSA) and
278 not isinstance(enckey, keys.RSAPublic))):
279 # FIXME
Fabio Utzig1f508922020-01-15 11:37:51 -0300280 raise click.UsageError("Signing and encryption must use the same "
281 "type of key")
David Vinczeda8c9192019-03-26 17:17:41 +0100282 img.create(key, enckey, dependencies)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300283 img.save(outfile, hex_addr)
Fabio Utzige89841d2018-12-21 11:19:06 -0200284
285
286class AliasesGroup(click.Group):
287
288 _aliases = {
289 "create": "sign",
290 }
291
292 def list_commands(self, ctx):
293 cmds = [k for k in self.commands]
294 aliases = [k for k in self._aliases]
295 return sorted(cmds + aliases)
296
297 def get_command(self, ctx, cmd_name):
298 rv = click.Group.get_command(self, ctx, cmd_name)
299 if rv is not None:
300 return rv
301 if cmd_name in self._aliases:
302 return click.Group.get_command(self, ctx, self._aliases[cmd_name])
303 return None
304
305
Fabio Utzig25c6a152019-09-10 12:52:26 -0300306@click.command(help='Print imgtool version information')
307def version():
308 print(imgtool_version)
309
310
Fabio Utzige89841d2018-12-21 11:19:06 -0200311@click.command(cls=AliasesGroup,
312 context_settings=dict(help_option_names=['-h', '--help']))
313def imgtool():
314 pass
315
316
317imgtool.add_command(keygen)
318imgtool.add_command(getpub)
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200319imgtool.add_command(getpriv)
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300320imgtool.add_command(verify)
Fabio Utzige89841d2018-12-21 11:19:06 -0200321imgtool.add_command(sign)
Fabio Utzig25c6a152019-09-10 12:52:26 -0300322imgtool.add_command(version)
Fabio Utzige89841d2018-12-21 11:19:06 -0200323
324
325if __name__ == '__main__':
326 imgtool()