blob: 8b515d5034b3ec100efbb53eb9ee0e50ae24785b [file] [log] [blame]
Fabio Utzige89841d2018-12-21 11:19:06 -02001#! /usr/bin/env python3
2#
David Vincze71b8f982020-03-17 19:08:12 +01003# Copyright 2017-2020 Linaro Limited
Roland Mikhel3d92a6c2023-02-23 15:35:44 +01004# Copyright 2019-2023 Arm Limited
Fabio Utzige89841d2018-12-21 11:19:06 -02005#
David Brown79c4fcf2021-01-26 15:04:05 -07006# SPDX-License-Identifier: Apache-2.0
7#
Fabio Utzige89841d2018-12-21 11:19:06 -02008# Licensed under the Apache License, Version 2.0 (the "License");
9# you may not use this file except in compliance with the License.
10# You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS,
16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19
David Vinczeda8c9192019-03-26 17:17:41 +010020import re
Fabio Utzige89841d2018-12-21 11:19:06 -020021import click
22import getpass
23import imgtool.keys as keys
Fabio Utzig4a5477a2019-05-27 15:45:08 -030024import sys
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +010025import base64
Fabio Utzig25c6a152019-09-10 12:52:26 -030026from imgtool import image, imgtool_version
Fabio Utzige89841d2018-12-21 11:19:06 -020027from imgtool.version import decode_version
Fabio Utzig4facd1b2020-04-02 13:17:38 -030028from .keys import (
29 RSAUsageError, ECDSAUsageError, Ed25519UsageError, X25519UsageError)
Fabio Utzige89841d2018-12-21 11:19:06 -020030
David Vincze71b8f982020-03-17 19:08:12 +010031MIN_PYTHON_VERSION = (3, 6)
32if sys.version_info < MIN_PYTHON_VERSION:
33 sys.exit("Python %s.%s or newer is required by imgtool."
34 % MIN_PYTHON_VERSION)
35
Fabio Utzige89841d2018-12-21 11:19:06 -020036
37def gen_rsa2048(keyfile, passwd):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030038 keys.RSA.generate().export_private(path=keyfile, passwd=passwd)
39
40
41def gen_rsa3072(keyfile, passwd):
42 keys.RSA.generate(key_size=3072).export_private(path=keyfile,
43 passwd=passwd)
Fabio Utzige89841d2018-12-21 11:19:06 -020044
45
46def gen_ecdsa_p256(keyfile, passwd):
47 keys.ECDSA256P1.generate().export_private(keyfile, passwd=passwd)
48
49
Fabio Utzig8101d1f2019-05-09 15:03:22 -030050def gen_ed25519(keyfile, passwd):
Fabio Utzig4bd4c7c2019-06-27 08:23:21 -030051 keys.Ed25519.generate().export_private(path=keyfile, passwd=passwd)
Fabio Utzig8101d1f2019-05-09 15:03:22 -030052
53
Fabio Utzig4facd1b2020-04-02 13:17:38 -030054def gen_x25519(keyfile, passwd):
55 keys.X25519.generate().export_private(path=keyfile, passwd=passwd)
56
57
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -030058valid_langs = ['c', 'rust']
59valid_encodings = ['lang-c', 'lang-rust', 'pem']
Fabio Utzige89841d2018-12-21 11:19:06 -020060keygens = {
61 'rsa-2048': gen_rsa2048,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030062 'rsa-3072': gen_rsa3072,
Fabio Utzige89841d2018-12-21 11:19:06 -020063 'ecdsa-p256': gen_ecdsa_p256,
Fabio Utzig4facd1b2020-04-02 13:17:38 -030064 'ed25519': gen_ed25519,
65 'x25519': gen_x25519,
Fabio Utzige89841d2018-12-21 11:19:06 -020066}
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +000067valid_formats = ['openssl', 'pkcs8']
Fabio Utzige89841d2018-12-21 11:19:06 -020068
Antonio de Angelis7ba01c02022-11-15 15:10:41 +000069
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +010070def load_signature(sigfile):
71 with open(sigfile, 'rb') as f:
72 signature = base64.b64decode(f.read())
73 return signature
Fabio Utzige89841d2018-12-21 11:19:06 -020074
Antonio de Angelis7ba01c02022-11-15 15:10:41 +000075
Andrzej Puzdrowskif72e3742022-03-17 11:34:38 +010076def save_signature(sigfile, sig):
77 with open(sigfile, 'wb') as f:
78 signature = base64.b64encode(sig)
79 f.write(signature)
80
Antonio de Angelis7ba01c02022-11-15 15:10:41 +000081
Fabio Utzige89841d2018-12-21 11:19:06 -020082def load_key(keyfile):
83 # TODO: better handling of invalid pass-phrase
84 key = keys.load(keyfile)
85 if key is not None:
86 return key
87 passwd = getpass.getpass("Enter key passphrase: ").encode('utf-8')
88 return keys.load(keyfile, passwd)
89
90
91def get_password():
92 while True:
93 passwd = getpass.getpass("Enter key passphrase: ")
94 passwd2 = getpass.getpass("Reenter passphrase: ")
95 if passwd == passwd2:
96 break
97 print("Passwords do not match, try again")
98
99 # Password must be bytes, always use UTF-8 for consistent
100 # encoding.
101 return passwd.encode('utf-8')
102
103
104@click.option('-p', '--password', is_flag=True,
105 help='Prompt for password to protect key')
106@click.option('-t', '--type', metavar='type', required=True,
Fabio Utzig7ca28552019-12-13 11:24:20 -0300107 type=click.Choice(keygens.keys()), prompt=True,
108 help='{}'.format('One of: {}'.format(', '.join(keygens.keys()))))
Fabio Utzige89841d2018-12-21 11:19:06 -0200109@click.option('-k', '--key', metavar='filename', required=True)
110@click.command(help='Generate pub/private keypair')
111def keygen(type, key, password):
112 password = get_password() if password else None
113 keygens[type](key, password)
114
115
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -0300116@click.option('-l', '--lang', metavar='lang',
117 type=click.Choice(valid_langs),
118 help='This option is deprecated. Please use the '
119 '`--encoding` option. '
120 'Valid langs: {}'.format(', '.join(valid_langs)))
121@click.option('-e', '--encoding', metavar='encoding',
122 type=click.Choice(valid_encodings),
123 help='Valid encodings: {}'.format(', '.join(valid_encodings)))
Fabio Utzige89841d2018-12-21 11:19:06 -0200124@click.option('-k', '--key', metavar='filename', required=True)
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200125@click.command(help='Dump public key from keypair')
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -0300126def getpub(key, encoding, lang):
127 if encoding and lang:
Antonio de Angelis7ba01c02022-11-15 15:10:41 +0000128 raise click.UsageError('Please use only one of `--encoding/-e` '
129 'or `--lang/-l`')
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -0300130 elif not encoding and not lang:
131 # Preserve old behavior defaulting to `c`. If `lang` is removed,
132 # `default=valid_encodings[0]` should be added to `-e` param.
133 lang = valid_langs[0]
Fabio Utzige89841d2018-12-21 11:19:06 -0200134 key = load_key(key)
135 if key is None:
136 print("Invalid passphrase")
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -0300137 elif lang == 'c' or encoding == 'lang-c':
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200138 key.emit_c_public()
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -0300139 elif lang == 'rust' or encoding == 'lang-rust':
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200140 key.emit_rust_public()
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -0300141 elif encoding == 'pem':
Fabio Utzig6f286772022-09-04 20:03:11 -0300142 key.emit_public_pem()
Fabio Utzige89841d2018-12-21 11:19:06 -0200143 else:
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -0300144 raise click.UsageError()
Fabio Utzige89841d2018-12-21 11:19:06 -0200145
146
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200147@click.option('--minimal', default=False, is_flag=True,
148 help='Reduce the size of the dumped private key to include only '
149 'the minimum amount of data required to decrypt. This '
150 'might require changes to the build config. Check the docs!'
151 )
152@click.option('-k', '--key', metavar='filename', required=True)
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000153@click.option('-f', '--format',
154 type=click.Choice(valid_formats),
Fabio Utzig8f289ba2023-01-09 21:01:55 -0300155 help='Valid formats: {}'.format(', '.join(valid_formats))
156 )
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200157@click.command(help='Dump private key from keypair')
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000158def getpriv(key, minimal, format):
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200159 key = load_key(key)
160 if key is None:
161 print("Invalid passphrase")
Fabio Utzig1f508922020-01-15 11:37:51 -0300162 try:
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000163 key.emit_private(minimal, format)
Fabio Utzig4facd1b2020-04-02 13:17:38 -0300164 except (RSAUsageError, ECDSAUsageError, Ed25519UsageError,
165 X25519UsageError) as e:
Fabio Utzig1f508922020-01-15 11:37:51 -0300166 raise click.UsageError(e)
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200167
168
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300169@click.argument('imgfile')
170@click.option('-k', '--key', metavar='filename')
171@click.command(help="Check that signed image can be verified by given key")
172def verify(key, imgfile):
173 key = load_key(key) if key else None
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200174 ret, version, digest = image.Image.verify(imgfile, key)
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300175 if ret == image.VerifyResult.OK:
176 print("Image was correctly validated")
Marek Pietae9555102019-08-08 16:08:16 +0200177 print("Image version: {}.{}.{}+{}".format(*version))
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200178 print("Image digest: {}".format(digest.hex()))
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300179 return
180 elif ret == image.VerifyResult.INVALID_MAGIC:
181 print("Invalid image magic; is this an MCUboot image?")
Christian Skubichf13db122019-07-31 11:34:15 +0200182 elif ret == image.VerifyResult.INVALID_TLV_INFO_MAGIC:
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300183 print("Invalid TLV info magic; is this an MCUboot image?")
184 elif ret == image.VerifyResult.INVALID_HASH:
185 print("Image has an invalid sha256 digest")
186 elif ret == image.VerifyResult.INVALID_SIGNATURE:
187 print("No signature found for the given key")
Christian Skubichf13db122019-07-31 11:34:15 +0200188 else:
189 print("Unknown return code: {}".format(ret))
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300190 sys.exit(1)
191
192
Fabio Utzige89841d2018-12-21 11:19:06 -0200193def validate_version(ctx, param, value):
194 try:
195 decode_version(value)
196 return value
197 except ValueError as e:
198 raise click.BadParameter("{}".format(e))
199
200
David Vincze1a7a6902020-02-18 15:05:16 +0100201def validate_security_counter(ctx, param, value):
202 if value is not None:
203 if value.lower() == 'auto':
204 return 'auto'
205 else:
206 try:
207 return int(value, 0)
208 except ValueError:
209 raise click.BadParameter(
210 "{} is not a valid integer. Please use code literals "
211 "prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary."
212 .format(value))
213
214
Fabio Utzige89841d2018-12-21 11:19:06 -0200215def validate_header_size(ctx, param, value):
216 min_hdr_size = image.IMAGE_HEADER_SIZE
217 if value < min_hdr_size:
218 raise click.BadParameter(
219 "Minimum value for -H/--header-size is {}".format(min_hdr_size))
220 return value
221
222
David Vinczeda8c9192019-03-26 17:17:41 +0100223def get_dependencies(ctx, param, value):
224 if value is not None:
225 versions = []
226 images = re.findall(r"\((\d+)", value)
227 if len(images) == 0:
228 raise click.BadParameter(
229 "Image dependency format is invalid: {}".format(value))
230 raw_versions = re.findall(r",\s*([0-9.+]+)\)", value)
231 if len(images) != len(raw_versions):
232 raise click.BadParameter(
233 '''There's a mismatch between the number of dependency images
234 and versions in: {}'''.format(value))
235 for raw_version in raw_versions:
236 try:
237 versions.append(decode_version(raw_version))
238 except ValueError as e:
239 raise click.BadParameter("{}".format(e))
240 dependencies = dict()
241 dependencies[image.DEP_IMAGES_KEY] = images
242 dependencies[image.DEP_VERSIONS_KEY] = versions
243 return dependencies
244
245
Fabio Utzige89841d2018-12-21 11:19:06 -0200246class BasedIntParamType(click.ParamType):
247 name = 'integer'
248
249 def convert(self, value, param, ctx):
250 try:
David Vincze1a7a6902020-02-18 15:05:16 +0100251 return int(value, 0)
Fabio Utzige89841d2018-12-21 11:19:06 -0200252 except ValueError:
David Vincze1a7a6902020-02-18 15:05:16 +0100253 self.fail('%s is not a valid integer. Please use code literals '
254 'prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary.'
255 % value, param, ctx)
Fabio Utzige89841d2018-12-21 11:19:06 -0200256
257
258@click.argument('outfile')
259@click.argument('infile')
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200260@click.option('--custom-tlv', required=False, nargs=2, default=[],
261 multiple=True, metavar='[tag] [value]',
262 help='Custom TLV that will be placed into protected area. '
263 'Add "0x" prefix if the value should be interpreted as an '
264 'integer, otherwise it will be interpreted as a string. '
265 'Specify the option multiple times to add multiple TLVs.')
Fabio Utzig9117fde2019-10-17 11:11:46 -0300266@click.option('-R', '--erased-val', type=click.Choice(['0', '0xff']),
267 required=False,
268 help='The value that is read back from erased flash.')
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300269@click.option('-x', '--hex-addr', type=BasedIntParamType(), required=False,
270 help='Adjust address in hex output file.')
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000271@click.option('-L', '--load-addr', type=BasedIntParamType(), required=False,
David Vincze1e0c5442020-04-07 14:12:33 +0200272 help='Load address for image when it should run from RAM.')
Dominik Ermel50820b12020-12-14 13:16:46 +0000273@click.option('-F', '--rom-fixed', type=BasedIntParamType(), required=False,
274 help='Set flash address the image is built for.')
Fabio Utzig9a492d52020-01-15 11:31:52 -0300275@click.option('--save-enctlv', default=False, is_flag=True,
276 help='When upgrading, save encrypted key TLVs instead of plain '
277 'keys. Enable when BOOT_SWAP_SAVE_ENCTLV config option '
278 'was set.')
Fabio Utzige89841d2018-12-21 11:19:06 -0200279@click.option('-E', '--encrypt', metavar='filename',
David Vinczee574f2d2020-07-10 11:42:03 +0200280 help='Encrypt image using the provided public key. '
Tamas Banfe031092020-09-10 17:32:39 +0200281 '(Not supported in direct-xip or ram-load mode.)')
Salome Thirot0f641972021-05-14 11:19:55 +0100282@click.option('--encrypt-keylen', default='128',
Antonio de Angelis7ba01c02022-11-15 15:10:41 +0000283 type=click.Choice(['128', '256']),
Salome Thirot0f641972021-05-14 11:19:55 +0100284 help='When encrypting the image using AES, select a 128 bit or '
285 '256 bit key len.')
Michel Jaouend09aa6b2022-01-07 16:48:58 +0100286@click.option('-c', '--clear', required=False, is_flag=True, default=False,
287 help='Output a non-encrypted image with encryption capabilities,'
288 'so it can be installed in the primary slot, and encrypted '
289 'when swapped to the secondary.')
Fabio Utzige89841d2018-12-21 11:19:06 -0200290@click.option('-e', '--endian', type=click.Choice(['little', 'big']),
291 default='little', help="Select little or big endian")
292@click.option('--overwrite-only', default=False, is_flag=True,
293 help='Use overwrite-only instead of swap upgrades')
David Vincze71b8f982020-03-17 19:08:12 +0100294@click.option('--boot-record', metavar='sw_type', help='Create CBOR encoded '
295 'boot record TLV. The sw_type represents the role of the '
296 'software component (e.g. CoFM for coprocessor firmware). '
297 '[max. 12 characters]')
Fabio Utzige89841d2018-12-21 11:19:06 -0200298@click.option('-M', '--max-sectors', type=int,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300299 help='When padding allow for this amount of sectors (defaults '
300 'to 128)')
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100301@click.option('--confirm', default=False, is_flag=True,
Martí Bolívar009a1502020-09-04 14:23:39 -0700302 help='When padding the image, mark it as confirmed (implies '
303 '--pad)')
Fabio Utzige89841d2018-12-21 11:19:06 -0200304@click.option('--pad', default=False, is_flag=True,
305 help='Pad image to --slot-size bytes, adding trailer magic')
306@click.option('-S', '--slot-size', type=BasedIntParamType(), required=True,
Fabio Utzig826abf42020-07-13 20:56:35 -0300307 help='Size of the slot. If the slots have different sizes, use '
308 'the size of the secondary slot.')
Fabio Utzige89841d2018-12-21 11:19:06 -0200309@click.option('--pad-header', default=False, is_flag=True,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300310 help='Add --header-size zeroed bytes at the beginning of the '
311 'image')
Fabio Utzige89841d2018-12-21 11:19:06 -0200312@click.option('-H', '--header-size', callback=validate_header_size,
313 type=BasedIntParamType(), required=True)
David Brown4878c272020-03-10 16:23:56 -0600314@click.option('--pad-sig', default=False, is_flag=True,
315 help='Add 0-2 bytes of padding to ECDSA signature '
316 '(for mcuboot <1.5)')
David Vinczeda8c9192019-03-26 17:17:41 +0100317@click.option('-d', '--dependencies', callback=get_dependencies,
318 required=False, help='''Add dependence on another image, format:
319 "(<image_ID>,<image_version>), ... "''')
David Vincze1a7a6902020-02-18 15:05:16 +0100320@click.option('-s', '--security-counter', callback=validate_security_counter,
321 help='Specify the value of security counter. Use the `auto` '
322 'keyword to automatically generate it from the image version.')
Fabio Utzige89841d2018-12-21 11:19:06 -0200323@click.option('-v', '--version', callback=validate_version, required=True)
Kristine Jassmann73c38c62021-02-03 16:56:14 +0000324@click.option('--align', type=click.Choice(['1', '2', '4', '8', '16', '32']),
Fabio Utzige89841d2018-12-21 11:19:06 -0200325 required=True)
Kristine Jassmann73c38c62021-02-03 16:56:14 +0000326@click.option('--max-align', type=click.Choice(['8', '16', '32']),
Piotr Mienkowskib6d5cf32022-01-31 01:01:11 +0100327 required=False,
328 help='Maximum flash alignment. Set if flash alignment of the '
329 'primary and secondary slot differ and any of them is larger '
330 'than 8.')
David Vinczedde178d2020-03-26 20:06:01 +0100331@click.option('--public-key-format', type=click.Choice(['hash', 'full']),
332 default='hash', help='In what format to add the public key to '
333 'the image manifest: full key or hash of the key.')
Fabio Utzige89841d2018-12-21 11:19:06 -0200334@click.option('-k', '--key', metavar='filename')
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +0100335@click.option('--fix-sig', metavar='filename',
iysheng6093cbb2022-05-28 17:00:40 +0800336 help='fixed signature for the image. It will be used instead of '
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +0100337 'the signature calculated using the public key')
338@click.option('--fix-sig-pubkey', metavar='filename',
339 help='public key relevant to fixed signature')
Andrzej Puzdrowskif72e3742022-03-17 11:34:38 +0100340@click.option('--sig-out', metavar='filename',
iysheng6093cbb2022-05-28 17:00:40 +0800341 help='Path to the file to which signature will be written. '
Andrzej Puzdrowskif72e3742022-03-17 11:34:38 +0100342 'The image signature will be encoded as base64 formatted string')
Andrzej Puzdrowskidfce0be2022-03-28 09:34:15 +0200343@click.option('--vector-to-sign', type=click.Choice(['payload', 'digest']),
Antonio de Angelis7ba01c02022-11-15 15:10:41 +0000344 help='send to OUTFILE the payload or payload''s digest instead '
345 'of complied image. These data can be used for external image '
Andrzej Puzdrowskidfce0be2022-03-28 09:34:15 +0200346 'signing')
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200347@click.command(help='''Create a signed or unsigned image\n
348 INFILE and OUTFILE are parsed as Intel HEX if the params have
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000349 .hex extension, otherwise binary format is used''')
David Vinczedde178d2020-03-26 20:06:01 +0100350def sign(key, public_key_format, align, version, pad_sig, header_size,
351 pad_header, slot_size, pad, confirm, max_sectors, overwrite_only,
Salome Thirot0f641972021-05-14 11:19:55 +0100352 endian, encrypt_keylen, encrypt, infile, outfile, dependencies,
353 load_addr, hex_addr, erased_val, save_enctlv, security_counter,
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +0100354 boot_record, custom_tlv, rom_fixed, max_align, clear, fix_sig,
Andrzej Puzdrowskidfce0be2022-03-28 09:34:15 +0200355 fix_sig_pubkey, sig_out, vector_to_sign):
Martí Bolívar009a1502020-09-04 14:23:39 -0700356
357 if confirm:
358 # Confirmed but non-padded images don't make much sense, because
359 # otherwise there's no trailer area for writing the confirmed status.
360 pad = True
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200361 img = image.Image(version=decode_version(version), header_size=header_size,
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100362 pad_header=pad_header, pad=pad, confirm=confirm,
363 align=int(align), slot_size=slot_size,
364 max_sectors=max_sectors, overwrite_only=overwrite_only,
Dominik Ermel50820b12020-12-14 13:16:46 +0000365 endian=endian, load_addr=load_addr, rom_fixed=rom_fixed,
366 erased_val=erased_val, save_enctlv=save_enctlv,
Kristine Jassmann73c38c62021-02-03 16:56:14 +0000367 security_counter=security_counter, max_align=max_align)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200368 img.load(infile)
Fabio Utzige89841d2018-12-21 11:19:06 -0200369 key = load_key(key) if key else None
370 enckey = load_key(encrypt) if encrypt else None
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300371 if enckey and key:
372 if ((isinstance(key, keys.ECDSA256P1) and
373 not isinstance(enckey, keys.ECDSA256P1Public))
374 or (isinstance(key, keys.RSA) and
375 not isinstance(enckey, keys.RSAPublic))):
376 # FIXME
Fabio Utzig1f508922020-01-15 11:37:51 -0300377 raise click.UsageError("Signing and encryption must use the same "
378 "type of key")
David Brown4878c272020-03-10 16:23:56 -0600379
380 if pad_sig and hasattr(key, 'pad_sig'):
381 key.pad_sig = True
382
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200383 # Get list of custom protected TLVs from the command-line
384 custom_tlvs = {}
385 for tlv in custom_tlv:
386 tag = int(tlv[0], 0)
387 if tag in custom_tlvs:
388 raise click.UsageError('Custom TLV %s already exists.' % hex(tag))
389 if tag in image.TLV_VALUES.values():
390 raise click.UsageError(
391 'Custom TLV %s conflicts with predefined TLV.' % hex(tag))
392
393 value = tlv[1]
394 if value.startswith('0x'):
395 if len(value[2:]) % 2:
396 raise click.UsageError('Custom TLV length is odd.')
397 custom_tlvs[tag] = bytes.fromhex(value[2:])
398 else:
399 custom_tlvs[tag] = value.encode('utf-8')
400
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +0100401 # Allow signature calculated externally.
402 raw_signature = load_signature(fix_sig) if fix_sig else None
403
404 baked_signature = None
405 pub_key = None
406
407 if raw_signature is not None:
408 if fix_sig_pubkey is None:
Antonio de Angelis7ba01c02022-11-15 15:10:41 +0000409 raise click.UsageError(
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +0100410 'public key of the fixed signature is not specified')
411
412 pub_key = load_key(fix_sig_pubkey)
413
414 baked_signature = {
Antonio de Angelis7ba01c02022-11-15 15:10:41 +0000415 'value': raw_signature
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +0100416 }
417
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200418 img.create(key, public_key_format, enckey, dependencies, boot_record,
Antonio de Angelis7ba01c02022-11-15 15:10:41 +0000419 custom_tlvs, int(encrypt_keylen), clear, baked_signature,
420 pub_key, vector_to_sign)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300421 img.save(outfile, hex_addr)
Fabio Utzige89841d2018-12-21 11:19:06 -0200422
Andrzej Puzdrowskif72e3742022-03-17 11:34:38 +0100423 if sig_out is not None:
424 new_signature = img.get_signature()
425 save_signature(sig_out, new_signature)
426
Fabio Utzige89841d2018-12-21 11:19:06 -0200427
428class AliasesGroup(click.Group):
429
430 _aliases = {
431 "create": "sign",
432 }
433
434 def list_commands(self, ctx):
435 cmds = [k for k in self.commands]
436 aliases = [k for k in self._aliases]
437 return sorted(cmds + aliases)
438
439 def get_command(self, ctx, cmd_name):
440 rv = click.Group.get_command(self, ctx, cmd_name)
441 if rv is not None:
442 return rv
443 if cmd_name in self._aliases:
444 return click.Group.get_command(self, ctx, self._aliases[cmd_name])
445 return None
446
447
Fabio Utzig25c6a152019-09-10 12:52:26 -0300448@click.command(help='Print imgtool version information')
449def version():
450 print(imgtool_version)
451
452
Fabio Utzige89841d2018-12-21 11:19:06 -0200453@click.command(cls=AliasesGroup,
454 context_settings=dict(help_option_names=['-h', '--help']))
455def imgtool():
456 pass
457
458
459imgtool.add_command(keygen)
460imgtool.add_command(getpub)
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200461imgtool.add_command(getpriv)
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300462imgtool.add_command(verify)
Fabio Utzige89841d2018-12-21 11:19:06 -0200463imgtool.add_command(sign)
Fabio Utzig25c6a152019-09-10 12:52:26 -0300464imgtool.add_command(version)
Fabio Utzige89841d2018-12-21 11:19:06 -0200465
466
467if __name__ == '__main__':
468 imgtool()