blob: e43eaf1405f4d7b49bfaaf4266e514f49b320981 [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
Salome Thirot0f641972021-05-14 11:19:55 +01004# Copyright 2019-2021 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
50def gen_ecdsa_p224(keyfile, passwd):
51 print("TODO: p-224 not yet implemented")
52
53
Fabio Utzig8101d1f2019-05-09 15:03:22 -030054def gen_ed25519(keyfile, passwd):
Fabio Utzig4bd4c7c2019-06-27 08:23:21 -030055 keys.Ed25519.generate().export_private(path=keyfile, passwd=passwd)
Fabio Utzig8101d1f2019-05-09 15:03:22 -030056
57
Fabio Utzig4facd1b2020-04-02 13:17:38 -030058def gen_x25519(keyfile, passwd):
59 keys.X25519.generate().export_private(path=keyfile, passwd=passwd)
60
61
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -030062valid_langs = ['c', 'rust']
63valid_encodings = ['lang-c', 'lang-rust', 'pem']
Fabio Utzige89841d2018-12-21 11:19:06 -020064keygens = {
65 'rsa-2048': gen_rsa2048,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030066 'rsa-3072': gen_rsa3072,
Fabio Utzige89841d2018-12-21 11:19:06 -020067 'ecdsa-p256': gen_ecdsa_p256,
68 'ecdsa-p224': gen_ecdsa_p224,
Fabio Utzig4facd1b2020-04-02 13:17:38 -030069 'ed25519': gen_ed25519,
70 'x25519': gen_x25519,
Fabio Utzige89841d2018-12-21 11:19:06 -020071}
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +000072valid_formats = ['openssl', 'pkcs8']
Fabio Utzige89841d2018-12-21 11:19:06 -020073
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +010074def load_signature(sigfile):
75 with open(sigfile, 'rb') as f:
76 signature = base64.b64decode(f.read())
77 return signature
Fabio Utzige89841d2018-12-21 11:19:06 -020078
Andrzej Puzdrowskif72e3742022-03-17 11:34:38 +010079def save_signature(sigfile, sig):
80 with open(sigfile, 'wb') as f:
81 signature = base64.b64encode(sig)
82 f.write(signature)
83
Fabio Utzige89841d2018-12-21 11:19:06 -020084def load_key(keyfile):
85 # TODO: better handling of invalid pass-phrase
86 key = keys.load(keyfile)
87 if key is not None:
88 return key
89 passwd = getpass.getpass("Enter key passphrase: ").encode('utf-8')
90 return keys.load(keyfile, passwd)
91
92
93def get_password():
94 while True:
95 passwd = getpass.getpass("Enter key passphrase: ")
96 passwd2 = getpass.getpass("Reenter passphrase: ")
97 if passwd == passwd2:
98 break
99 print("Passwords do not match, try again")
100
101 # Password must be bytes, always use UTF-8 for consistent
102 # encoding.
103 return passwd.encode('utf-8')
104
105
106@click.option('-p', '--password', is_flag=True,
107 help='Prompt for password to protect key')
108@click.option('-t', '--type', metavar='type', required=True,
Fabio Utzig7ca28552019-12-13 11:24:20 -0300109 type=click.Choice(keygens.keys()), prompt=True,
110 help='{}'.format('One of: {}'.format(', '.join(keygens.keys()))))
Fabio Utzige89841d2018-12-21 11:19:06 -0200111@click.option('-k', '--key', metavar='filename', required=True)
112@click.command(help='Generate pub/private keypair')
113def keygen(type, key, password):
114 password = get_password() if password else None
115 keygens[type](key, password)
116
117
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -0300118@click.option('-l', '--lang', metavar='lang',
119 type=click.Choice(valid_langs),
120 help='This option is deprecated. Please use the '
121 '`--encoding` option. '
122 'Valid langs: {}'.format(', '.join(valid_langs)))
123@click.option('-e', '--encoding', metavar='encoding',
124 type=click.Choice(valid_encodings),
125 help='Valid encodings: {}'.format(', '.join(valid_encodings)))
Fabio Utzige89841d2018-12-21 11:19:06 -0200126@click.option('-k', '--key', metavar='filename', required=True)
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200127@click.command(help='Dump public key from keypair')
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -0300128def getpub(key, encoding, lang):
129 if encoding and lang:
130 raise click.UsageError('Please use only one of `--encoding/-e` or `--lang/-l`')
131 elif not encoding and not lang:
132 # Preserve old behavior defaulting to `c`. If `lang` is removed,
133 # `default=valid_encodings[0]` should be added to `-e` param.
134 lang = valid_langs[0]
Fabio Utzige89841d2018-12-21 11:19:06 -0200135 key = load_key(key)
136 if key is None:
137 print("Invalid passphrase")
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -0300138 elif lang == 'c' or encoding == 'lang-c':
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200139 key.emit_c_public()
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -0300140 elif lang == 'rust' or encoding == 'lang-rust':
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200141 key.emit_rust_public()
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -0300142 elif encoding == 'pem':
Fabio Utzig6f286772022-09-04 20:03:11 -0300143 key.emit_public_pem()
Fabio Utzige89841d2018-12-21 11:19:06 -0200144 else:
Fabio Utzig4e2cdfe2022-09-28 17:44:01 -0300145 raise click.UsageError()
Fabio Utzige89841d2018-12-21 11:19:06 -0200146
147
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200148@click.option('--minimal', default=False, is_flag=True,
149 help='Reduce the size of the dumped private key to include only '
150 'the minimum amount of data required to decrypt. This '
151 'might require changes to the build config. Check the docs!'
152 )
153@click.option('-k', '--key', metavar='filename', required=True)
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000154@click.option('-f', '--format',
155 type=click.Choice(valid_formats),
156 help='Valid formats: {}'.format(', '.join(valid_formats)),
157 default='pkcs8')
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200158@click.command(help='Dump private key from keypair')
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000159def getpriv(key, minimal, format):
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200160 key = load_key(key)
161 if key is None:
162 print("Invalid passphrase")
Fabio Utzig1f508922020-01-15 11:37:51 -0300163 try:
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000164 key.emit_private(minimal, format)
Fabio Utzig4facd1b2020-04-02 13:17:38 -0300165 except (RSAUsageError, ECDSAUsageError, Ed25519UsageError,
166 X25519UsageError) as e:
Fabio Utzig1f508922020-01-15 11:37:51 -0300167 raise click.UsageError(e)
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200168
169
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300170@click.argument('imgfile')
171@click.option('-k', '--key', metavar='filename')
172@click.command(help="Check that signed image can be verified by given key")
173def verify(key, imgfile):
174 key = load_key(key) if key else None
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200175 ret, version, digest = image.Image.verify(imgfile, key)
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300176 if ret == image.VerifyResult.OK:
177 print("Image was correctly validated")
Marek Pietae9555102019-08-08 16:08:16 +0200178 print("Image version: {}.{}.{}+{}".format(*version))
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200179 print("Image digest: {}".format(digest.hex()))
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300180 return
181 elif ret == image.VerifyResult.INVALID_MAGIC:
182 print("Invalid image magic; is this an MCUboot image?")
Christian Skubichf13db122019-07-31 11:34:15 +0200183 elif ret == image.VerifyResult.INVALID_TLV_INFO_MAGIC:
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300184 print("Invalid TLV info magic; is this an MCUboot image?")
185 elif ret == image.VerifyResult.INVALID_HASH:
186 print("Image has an invalid sha256 digest")
187 elif ret == image.VerifyResult.INVALID_SIGNATURE:
188 print("No signature found for the given key")
Christian Skubichf13db122019-07-31 11:34:15 +0200189 else:
190 print("Unknown return code: {}".format(ret))
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300191 sys.exit(1)
192
193
Fabio Utzige89841d2018-12-21 11:19:06 -0200194def validate_version(ctx, param, value):
195 try:
196 decode_version(value)
197 return value
198 except ValueError as e:
199 raise click.BadParameter("{}".format(e))
200
201
David Vincze1a7a6902020-02-18 15:05:16 +0100202def validate_security_counter(ctx, param, value):
203 if value is not None:
204 if value.lower() == 'auto':
205 return 'auto'
206 else:
207 try:
208 return int(value, 0)
209 except ValueError:
210 raise click.BadParameter(
211 "{} is not a valid integer. Please use code literals "
212 "prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary."
213 .format(value))
214
215
Fabio Utzige89841d2018-12-21 11:19:06 -0200216def validate_header_size(ctx, param, value):
217 min_hdr_size = image.IMAGE_HEADER_SIZE
218 if value < min_hdr_size:
219 raise click.BadParameter(
220 "Minimum value for -H/--header-size is {}".format(min_hdr_size))
221 return value
222
223
David Vinczeda8c9192019-03-26 17:17:41 +0100224def get_dependencies(ctx, param, value):
225 if value is not None:
226 versions = []
227 images = re.findall(r"\((\d+)", value)
228 if len(images) == 0:
229 raise click.BadParameter(
230 "Image dependency format is invalid: {}".format(value))
231 raw_versions = re.findall(r",\s*([0-9.+]+)\)", value)
232 if len(images) != len(raw_versions):
233 raise click.BadParameter(
234 '''There's a mismatch between the number of dependency images
235 and versions in: {}'''.format(value))
236 for raw_version in raw_versions:
237 try:
238 versions.append(decode_version(raw_version))
239 except ValueError as e:
240 raise click.BadParameter("{}".format(e))
241 dependencies = dict()
242 dependencies[image.DEP_IMAGES_KEY] = images
243 dependencies[image.DEP_VERSIONS_KEY] = versions
244 return dependencies
245
246
Fabio Utzige89841d2018-12-21 11:19:06 -0200247class BasedIntParamType(click.ParamType):
248 name = 'integer'
249
250 def convert(self, value, param, ctx):
251 try:
David Vincze1a7a6902020-02-18 15:05:16 +0100252 return int(value, 0)
Fabio Utzige89841d2018-12-21 11:19:06 -0200253 except ValueError:
David Vincze1a7a6902020-02-18 15:05:16 +0100254 self.fail('%s is not a valid integer. Please use code literals '
255 'prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary.'
256 % value, param, ctx)
Fabio Utzige89841d2018-12-21 11:19:06 -0200257
258
259@click.argument('outfile')
260@click.argument('infile')
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200261@click.option('--custom-tlv', required=False, nargs=2, default=[],
262 multiple=True, metavar='[tag] [value]',
263 help='Custom TLV that will be placed into protected area. '
264 'Add "0x" prefix if the value should be interpreted as an '
265 'integer, otherwise it will be interpreted as a string. '
266 'Specify the option multiple times to add multiple TLVs.')
Fabio Utzig9117fde2019-10-17 11:11:46 -0300267@click.option('-R', '--erased-val', type=click.Choice(['0', '0xff']),
268 required=False,
269 help='The value that is read back from erased flash.')
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300270@click.option('-x', '--hex-addr', type=BasedIntParamType(), required=False,
271 help='Adjust address in hex output file.')
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000272@click.option('-L', '--load-addr', type=BasedIntParamType(), required=False,
David Vincze1e0c5442020-04-07 14:12:33 +0200273 help='Load address for image when it should run from RAM.')
Dominik Ermel50820b12020-12-14 13:16:46 +0000274@click.option('-F', '--rom-fixed', type=BasedIntParamType(), required=False,
275 help='Set flash address the image is built for.')
Fabio Utzig9a492d52020-01-15 11:31:52 -0300276@click.option('--save-enctlv', default=False, is_flag=True,
277 help='When upgrading, save encrypted key TLVs instead of plain '
278 'keys. Enable when BOOT_SWAP_SAVE_ENCTLV config option '
279 'was set.')
Fabio Utzige89841d2018-12-21 11:19:06 -0200280@click.option('-E', '--encrypt', metavar='filename',
David Vinczee574f2d2020-07-10 11:42:03 +0200281 help='Encrypt image using the provided public key. '
Tamas Banfe031092020-09-10 17:32:39 +0200282 '(Not supported in direct-xip or ram-load mode.)')
Salome Thirot0f641972021-05-14 11:19:55 +0100283@click.option('--encrypt-keylen', default='128',
284 type=click.Choice(['128','256']),
285 help='When encrypting the image using AES, select a 128 bit or '
286 '256 bit key len.')
Michel Jaouend09aa6b2022-01-07 16:48:58 +0100287@click.option('-c', '--clear', required=False, is_flag=True, default=False,
288 help='Output a non-encrypted image with encryption capabilities,'
289 'so it can be installed in the primary slot, and encrypted '
290 'when swapped to the secondary.')
Fabio Utzige89841d2018-12-21 11:19:06 -0200291@click.option('-e', '--endian', type=click.Choice(['little', 'big']),
292 default='little', help="Select little or big endian")
293@click.option('--overwrite-only', default=False, is_flag=True,
294 help='Use overwrite-only instead of swap upgrades')
David Vincze71b8f982020-03-17 19:08:12 +0100295@click.option('--boot-record', metavar='sw_type', help='Create CBOR encoded '
296 'boot record TLV. The sw_type represents the role of the '
297 'software component (e.g. CoFM for coprocessor firmware). '
298 '[max. 12 characters]')
Fabio Utzige89841d2018-12-21 11:19:06 -0200299@click.option('-M', '--max-sectors', type=int,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300300 help='When padding allow for this amount of sectors (defaults '
301 'to 128)')
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100302@click.option('--confirm', default=False, is_flag=True,
Martí Bolívar009a1502020-09-04 14:23:39 -0700303 help='When padding the image, mark it as confirmed (implies '
304 '--pad)')
Fabio Utzige89841d2018-12-21 11:19:06 -0200305@click.option('--pad', default=False, is_flag=True,
306 help='Pad image to --slot-size bytes, adding trailer magic')
307@click.option('-S', '--slot-size', type=BasedIntParamType(), required=True,
Fabio Utzig826abf42020-07-13 20:56:35 -0300308 help='Size of the slot. If the slots have different sizes, use '
309 'the size of the secondary slot.')
Fabio Utzige89841d2018-12-21 11:19:06 -0200310@click.option('--pad-header', default=False, is_flag=True,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300311 help='Add --header-size zeroed bytes at the beginning of the '
312 'image')
Fabio Utzige89841d2018-12-21 11:19:06 -0200313@click.option('-H', '--header-size', callback=validate_header_size,
314 type=BasedIntParamType(), required=True)
David Brown4878c272020-03-10 16:23:56 -0600315@click.option('--pad-sig', default=False, is_flag=True,
316 help='Add 0-2 bytes of padding to ECDSA signature '
317 '(for mcuboot <1.5)')
David Vinczeda8c9192019-03-26 17:17:41 +0100318@click.option('-d', '--dependencies', callback=get_dependencies,
319 required=False, help='''Add dependence on another image, format:
320 "(<image_ID>,<image_version>), ... "''')
David Vincze1a7a6902020-02-18 15:05:16 +0100321@click.option('-s', '--security-counter', callback=validate_security_counter,
322 help='Specify the value of security counter. Use the `auto` '
323 'keyword to automatically generate it from the image version.')
Fabio Utzige89841d2018-12-21 11:19:06 -0200324@click.option('-v', '--version', callback=validate_version, required=True)
Kristine Jassmann73c38c62021-02-03 16:56:14 +0000325@click.option('--align', type=click.Choice(['1', '2', '4', '8', '16', '32']),
Fabio Utzige89841d2018-12-21 11:19:06 -0200326 required=True)
Kristine Jassmann73c38c62021-02-03 16:56:14 +0000327@click.option('--max-align', type=click.Choice(['8', '16', '32']),
Piotr Mienkowskib6d5cf32022-01-31 01:01:11 +0100328 required=False,
329 help='Maximum flash alignment. Set if flash alignment of the '
330 'primary and secondary slot differ and any of them is larger '
331 'than 8.')
David Vinczedde178d2020-03-26 20:06:01 +0100332@click.option('--public-key-format', type=click.Choice(['hash', 'full']),
333 default='hash', help='In what format to add the public key to '
334 'the image manifest: full key or hash of the key.')
Fabio Utzige89841d2018-12-21 11:19:06 -0200335@click.option('-k', '--key', metavar='filename')
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +0100336@click.option('--fix-sig', metavar='filename',
iysheng6093cbb2022-05-28 17:00:40 +0800337 help='fixed signature for the image. It will be used instead of '
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +0100338 'the signature calculated using the public key')
339@click.option('--fix-sig-pubkey', metavar='filename',
340 help='public key relevant to fixed signature')
Andrzej Puzdrowskif72e3742022-03-17 11:34:38 +0100341@click.option('--sig-out', metavar='filename',
iysheng6093cbb2022-05-28 17:00:40 +0800342 help='Path to the file to which signature will be written. '
Andrzej Puzdrowskif72e3742022-03-17 11:34:38 +0100343 'The image signature will be encoded as base64 formatted string')
Andrzej Puzdrowskidfce0be2022-03-28 09:34:15 +0200344@click.option('--vector-to-sign', type=click.Choice(['payload', 'digest']),
iysheng6093cbb2022-05-28 17:00:40 +0800345 help='send to OUTFILE the payload or payload''s digest instead of '
346 'complied image. These data can be used for external image '
Andrzej Puzdrowskidfce0be2022-03-28 09:34:15 +0200347 'signing')
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200348@click.command(help='''Create a signed or unsigned image\n
349 INFILE and OUTFILE are parsed as Intel HEX if the params have
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000350 .hex extension, otherwise binary format is used''')
David Vinczedde178d2020-03-26 20:06:01 +0100351def sign(key, public_key_format, align, version, pad_sig, header_size,
352 pad_header, slot_size, pad, confirm, max_sectors, overwrite_only,
Salome Thirot0f641972021-05-14 11:19:55 +0100353 endian, encrypt_keylen, encrypt, infile, outfile, dependencies,
354 load_addr, hex_addr, erased_val, save_enctlv, security_counter,
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +0100355 boot_record, custom_tlv, rom_fixed, max_align, clear, fix_sig,
Andrzej Puzdrowskidfce0be2022-03-28 09:34:15 +0200356 fix_sig_pubkey, sig_out, vector_to_sign):
Martí Bolívar009a1502020-09-04 14:23:39 -0700357
358 if confirm:
359 # Confirmed but non-padded images don't make much sense, because
360 # otherwise there's no trailer area for writing the confirmed status.
361 pad = True
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200362 img = image.Image(version=decode_version(version), header_size=header_size,
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100363 pad_header=pad_header, pad=pad, confirm=confirm,
364 align=int(align), slot_size=slot_size,
365 max_sectors=max_sectors, overwrite_only=overwrite_only,
Dominik Ermel50820b12020-12-14 13:16:46 +0000366 endian=endian, load_addr=load_addr, rom_fixed=rom_fixed,
367 erased_val=erased_val, save_enctlv=save_enctlv,
Kristine Jassmann73c38c62021-02-03 16:56:14 +0000368 security_counter=security_counter, max_align=max_align)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200369 img.load(infile)
Fabio Utzige89841d2018-12-21 11:19:06 -0200370 key = load_key(key) if key else None
371 enckey = load_key(encrypt) if encrypt else None
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300372 if enckey and key:
373 if ((isinstance(key, keys.ECDSA256P1) and
374 not isinstance(enckey, keys.ECDSA256P1Public))
375 or (isinstance(key, keys.RSA) and
376 not isinstance(enckey, keys.RSAPublic))):
377 # FIXME
Fabio Utzig1f508922020-01-15 11:37:51 -0300378 raise click.UsageError("Signing and encryption must use the same "
379 "type of key")
David Brown4878c272020-03-10 16:23:56 -0600380
381 if pad_sig and hasattr(key, 'pad_sig'):
382 key.pad_sig = True
383
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200384 # Get list of custom protected TLVs from the command-line
385 custom_tlvs = {}
386 for tlv in custom_tlv:
387 tag = int(tlv[0], 0)
388 if tag in custom_tlvs:
389 raise click.UsageError('Custom TLV %s already exists.' % hex(tag))
390 if tag in image.TLV_VALUES.values():
391 raise click.UsageError(
392 'Custom TLV %s conflicts with predefined TLV.' % hex(tag))
393
394 value = tlv[1]
395 if value.startswith('0x'):
396 if len(value[2:]) % 2:
397 raise click.UsageError('Custom TLV length is odd.')
398 custom_tlvs[tag] = bytes.fromhex(value[2:])
399 else:
400 custom_tlvs[tag] = value.encode('utf-8')
401
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +0100402 # Allow signature calculated externally.
403 raw_signature = load_signature(fix_sig) if fix_sig else None
404
405 baked_signature = None
406 pub_key = None
407
408 if raw_signature is not None:
409 if fix_sig_pubkey is None:
410 raise click.UsageError(
411 'public key of the fixed signature is not specified')
412
413 pub_key = load_key(fix_sig_pubkey)
414
415 baked_signature = {
416 'value' : raw_signature
417 }
418
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200419 img.create(key, public_key_format, enckey, dependencies, boot_record,
Andrzej Puzdrowskidfce0be2022-03-28 09:34:15 +0200420 custom_tlvs, int(encrypt_keylen), clear, baked_signature, pub_key,
421 vector_to_sign)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300422 img.save(outfile, hex_addr)
Fabio Utzige89841d2018-12-21 11:19:06 -0200423
Andrzej Puzdrowskif72e3742022-03-17 11:34:38 +0100424 if sig_out is not None:
425 new_signature = img.get_signature()
426 save_signature(sig_out, new_signature)
427
Fabio Utzige89841d2018-12-21 11:19:06 -0200428
429class AliasesGroup(click.Group):
430
431 _aliases = {
432 "create": "sign",
433 }
434
435 def list_commands(self, ctx):
436 cmds = [k for k in self.commands]
437 aliases = [k for k in self._aliases]
438 return sorted(cmds + aliases)
439
440 def get_command(self, ctx, cmd_name):
441 rv = click.Group.get_command(self, ctx, cmd_name)
442 if rv is not None:
443 return rv
444 if cmd_name in self._aliases:
445 return click.Group.get_command(self, ctx, self._aliases[cmd_name])
446 return None
447
448
Fabio Utzig25c6a152019-09-10 12:52:26 -0300449@click.command(help='Print imgtool version information')
450def version():
451 print(imgtool_version)
452
453
Fabio Utzige89841d2018-12-21 11:19:06 -0200454@click.command(cls=AliasesGroup,
455 context_settings=dict(help_option_names=['-h', '--help']))
456def imgtool():
457 pass
458
459
460imgtool.add_command(keygen)
461imgtool.add_command(getpub)
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200462imgtool.add_command(getpriv)
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300463imgtool.add_command(verify)
Fabio Utzige89841d2018-12-21 11:19:06 -0200464imgtool.add_command(sign)
Fabio Utzig25c6a152019-09-10 12:52:26 -0300465imgtool.add_command(version)
Fabio Utzige89841d2018-12-21 11:19:06 -0200466
467
468if __name__ == '__main__':
469 imgtool()