blob: 61ed282fcbff6c546a1a405ca619c0763bbd17d8 [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 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
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
Fabio Utzig8101d1f2019-05-09 15:03:22 -030044def gen_ed25519(keyfile, passwd):
Fabio Utzig4bd4c7c2019-06-27 08:23:21 -030045 keys.Ed25519.generate().export_private(path=keyfile, passwd=passwd)
Fabio Utzig8101d1f2019-05-09 15:03:22 -030046
47
Fabio Utzige89841d2018-12-21 11:19:06 -020048valid_langs = ['c', 'rust']
49keygens = {
50 'rsa-2048': gen_rsa2048,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030051 'rsa-3072': gen_rsa3072,
Fabio Utzige89841d2018-12-21 11:19:06 -020052 'ecdsa-p256': gen_ecdsa_p256,
53 'ecdsa-p224': gen_ecdsa_p224,
Fabio Utzig8101d1f2019-05-09 15:03:22 -030054 'ed25519': gen_ed25519,
Fabio Utzige89841d2018-12-21 11:19:06 -020055}
56
57
58def load_key(keyfile):
59 # TODO: better handling of invalid pass-phrase
60 key = keys.load(keyfile)
61 if key is not None:
62 return key
63 passwd = getpass.getpass("Enter key passphrase: ").encode('utf-8')
64 return keys.load(keyfile, passwd)
65
66
67def get_password():
68 while True:
69 passwd = getpass.getpass("Enter key passphrase: ")
70 passwd2 = getpass.getpass("Reenter passphrase: ")
71 if passwd == passwd2:
72 break
73 print("Passwords do not match, try again")
74
75 # Password must be bytes, always use UTF-8 for consistent
76 # encoding.
77 return passwd.encode('utf-8')
78
79
80@click.option('-p', '--password', is_flag=True,
81 help='Prompt for password to protect key')
82@click.option('-t', '--type', metavar='type', required=True,
Fabio Utzig7ca28552019-12-13 11:24:20 -030083 type=click.Choice(keygens.keys()), prompt=True,
84 help='{}'.format('One of: {}'.format(', '.join(keygens.keys()))))
Fabio Utzige89841d2018-12-21 11:19:06 -020085@click.option('-k', '--key', metavar='filename', required=True)
86@click.command(help='Generate pub/private keypair')
87def keygen(type, key, password):
88 password = get_password() if password else None
89 keygens[type](key, password)
90
91
92@click.option('-l', '--lang', metavar='lang', default=valid_langs[0],
93 type=click.Choice(valid_langs))
94@click.option('-k', '--key', metavar='filename', required=True)
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020095@click.command(help='Dump public key from keypair')
Fabio Utzige89841d2018-12-21 11:19:06 -020096def getpub(key, lang):
97 key = load_key(key)
98 if key is None:
99 print("Invalid passphrase")
100 elif lang == 'c':
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200101 key.emit_c_public()
Fabio Utzige89841d2018-12-21 11:19:06 -0200102 elif lang == 'rust':
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200103 key.emit_rust_public()
Fabio Utzige89841d2018-12-21 11:19:06 -0200104 else:
105 raise ValueError("BUG: should never get here!")
106
107
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200108@click.option('--minimal', default=False, is_flag=True,
109 help='Reduce the size of the dumped private key to include only '
110 'the minimum amount of data required to decrypt. This '
111 'might require changes to the build config. Check the docs!'
112 )
113@click.option('-k', '--key', metavar='filename', required=True)
114@click.command(help='Dump private key from keypair')
115def getpriv(key, minimal):
116 key = load_key(key)
117 if key is None:
118 print("Invalid passphrase")
119 key.emit_private(minimal)
120
121
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300122@click.argument('imgfile')
123@click.option('-k', '--key', metavar='filename')
124@click.command(help="Check that signed image can be verified by given key")
125def verify(key, imgfile):
126 key = load_key(key) if key else None
Marek Pietae9555102019-08-08 16:08:16 +0200127 ret, version = image.Image.verify(imgfile, key)
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300128 if ret == image.VerifyResult.OK:
129 print("Image was correctly validated")
Marek Pietae9555102019-08-08 16:08:16 +0200130 print("Image version: {}.{}.{}+{}".format(*version))
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300131 return
132 elif ret == image.VerifyResult.INVALID_MAGIC:
133 print("Invalid image magic; is this an MCUboot image?")
Christian Skubichf13db122019-07-31 11:34:15 +0200134 elif ret == image.VerifyResult.INVALID_TLV_INFO_MAGIC:
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300135 print("Invalid TLV info magic; is this an MCUboot image?")
136 elif ret == image.VerifyResult.INVALID_HASH:
137 print("Image has an invalid sha256 digest")
138 elif ret == image.VerifyResult.INVALID_SIGNATURE:
139 print("No signature found for the given key")
Christian Skubichf13db122019-07-31 11:34:15 +0200140 else:
141 print("Unknown return code: {}".format(ret))
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300142 sys.exit(1)
143
144
Fabio Utzige89841d2018-12-21 11:19:06 -0200145def validate_version(ctx, param, value):
146 try:
147 decode_version(value)
148 return value
149 except ValueError as e:
150 raise click.BadParameter("{}".format(e))
151
152
153def validate_header_size(ctx, param, value):
154 min_hdr_size = image.IMAGE_HEADER_SIZE
155 if value < min_hdr_size:
156 raise click.BadParameter(
157 "Minimum value for -H/--header-size is {}".format(min_hdr_size))
158 return value
159
160
David Vinczeda8c9192019-03-26 17:17:41 +0100161def get_dependencies(ctx, param, value):
162 if value is not None:
163 versions = []
164 images = re.findall(r"\((\d+)", value)
165 if len(images) == 0:
166 raise click.BadParameter(
167 "Image dependency format is invalid: {}".format(value))
168 raw_versions = re.findall(r",\s*([0-9.+]+)\)", value)
169 if len(images) != len(raw_versions):
170 raise click.BadParameter(
171 '''There's a mismatch between the number of dependency images
172 and versions in: {}'''.format(value))
173 for raw_version in raw_versions:
174 try:
175 versions.append(decode_version(raw_version))
176 except ValueError as e:
177 raise click.BadParameter("{}".format(e))
178 dependencies = dict()
179 dependencies[image.DEP_IMAGES_KEY] = images
180 dependencies[image.DEP_VERSIONS_KEY] = versions
181 return dependencies
182
183
Fabio Utzige89841d2018-12-21 11:19:06 -0200184class BasedIntParamType(click.ParamType):
185 name = 'integer'
186
187 def convert(self, value, param, ctx):
188 try:
189 if value[:2].lower() == '0x':
190 return int(value[2:], 16)
191 elif value[:1] == '0':
192 return int(value, 8)
193 return int(value, 10)
194 except ValueError:
195 self.fail('%s is not a valid integer' % value, param, ctx)
196
197
198@click.argument('outfile')
199@click.argument('infile')
Fabio Utzig9117fde2019-10-17 11:11:46 -0300200@click.option('-R', '--erased-val', type=click.Choice(['0', '0xff']),
201 required=False,
202 help='The value that is read back from erased flash.')
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300203@click.option('-x', '--hex-addr', type=BasedIntParamType(), required=False,
204 help='Adjust address in hex output file.')
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000205@click.option('-L', '--load-addr', type=BasedIntParamType(), required=False,
206 help='Load address for image when it is in its primary slot.')
Fabio Utzige89841d2018-12-21 11:19:06 -0200207@click.option('-E', '--encrypt', metavar='filename',
208 help='Encrypt image using the provided public key')
209@click.option('-e', '--endian', type=click.Choice(['little', 'big']),
210 default='little', help="Select little or big endian")
211@click.option('--overwrite-only', default=False, is_flag=True,
212 help='Use overwrite-only instead of swap upgrades')
213@click.option('-M', '--max-sectors', type=int,
214 help='When padding allow for this amount of sectors (defaults to 128)')
215@click.option('--pad', default=False, is_flag=True,
216 help='Pad image to --slot-size bytes, adding trailer magic')
217@click.option('-S', '--slot-size', type=BasedIntParamType(), required=True,
218 help='Size of the slot where the image will be written')
219@click.option('--pad-header', default=False, is_flag=True,
220 help='Add --header-size zeroed bytes at the beginning of the image')
221@click.option('-H', '--header-size', callback=validate_header_size,
222 type=BasedIntParamType(), required=True)
David Vinczeda8c9192019-03-26 17:17:41 +0100223@click.option('-d', '--dependencies', callback=get_dependencies,
224 required=False, help='''Add dependence on another image, format:
225 "(<image_ID>,<image_version>), ... "''')
Fabio Utzige89841d2018-12-21 11:19:06 -0200226@click.option('-v', '--version', callback=validate_version, required=True)
227@click.option('--align', type=click.Choice(['1', '2', '4', '8']),
228 required=True)
229@click.option('-k', '--key', metavar='filename')
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200230@click.command(help='''Create a signed or unsigned image\n
231 INFILE and OUTFILE are parsed as Intel HEX if the params have
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000232 .hex extension, otherwise binary format is used''')
Fabio Utzige89841d2018-12-21 11:19:06 -0200233def sign(key, align, version, header_size, pad_header, slot_size, pad,
David Vinczeda8c9192019-03-26 17:17:41 +0100234 max_sectors, overwrite_only, endian, encrypt, infile, outfile,
Fabio Utzig9117fde2019-10-17 11:11:46 -0300235 dependencies, load_addr, hex_addr, erased_val):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200236 img = image.Image(version=decode_version(version), header_size=header_size,
237 pad_header=pad_header, pad=pad, align=int(align),
238 slot_size=slot_size, max_sectors=max_sectors,
Fabio Utzig4f0ea742019-09-10 12:53:18 -0300239 overwrite_only=overwrite_only, endian=endian,
Fabio Utzig9117fde2019-10-17 11:11:46 -0300240 load_addr=load_addr, erased_val=erased_val)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200241 img.load(infile)
Fabio Utzige89841d2018-12-21 11:19:06 -0200242 key = load_key(key) if key else None
243 enckey = load_key(encrypt) if encrypt else None
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300244 if enckey and key:
245 if ((isinstance(key, keys.ECDSA256P1) and
246 not isinstance(enckey, keys.ECDSA256P1Public))
247 or (isinstance(key, keys.RSA) and
248 not isinstance(enckey, keys.RSAPublic))):
249 # FIXME
250 raise Exception("Signing and encryption must use the same type of key")
David Vinczeda8c9192019-03-26 17:17:41 +0100251 img.create(key, enckey, dependencies)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300252 img.save(outfile, hex_addr)
Fabio Utzige89841d2018-12-21 11:19:06 -0200253
254
255class AliasesGroup(click.Group):
256
257 _aliases = {
258 "create": "sign",
259 }
260
261 def list_commands(self, ctx):
262 cmds = [k for k in self.commands]
263 aliases = [k for k in self._aliases]
264 return sorted(cmds + aliases)
265
266 def get_command(self, ctx, cmd_name):
267 rv = click.Group.get_command(self, ctx, cmd_name)
268 if rv is not None:
269 return rv
270 if cmd_name in self._aliases:
271 return click.Group.get_command(self, ctx, self._aliases[cmd_name])
272 return None
273
274
Fabio Utzig25c6a152019-09-10 12:52:26 -0300275@click.command(help='Print imgtool version information')
276def version():
277 print(imgtool_version)
278
279
Fabio Utzige89841d2018-12-21 11:19:06 -0200280@click.command(cls=AliasesGroup,
281 context_settings=dict(help_option_names=['-h', '--help']))
282def imgtool():
283 pass
284
285
286imgtool.add_command(keygen)
287imgtool.add_command(getpub)
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200288imgtool.add_command(getpriv)
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300289imgtool.add_command(verify)
Fabio Utzige89841d2018-12-21 11:19:06 -0200290imgtool.add_command(sign)
Fabio Utzig25c6a152019-09-10 12:52:26 -0300291imgtool.add_command(version)
Fabio Utzige89841d2018-12-21 11:19:06 -0200292
293
294if __name__ == '__main__':
295 imgtool()