Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 1 | #! /usr/bin/env python3 |
| 2 | # |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 3 | # Copyright 2017-2020 Linaro Limited |
Roland Mikhel | 3d92a6c | 2023-02-23 15:35:44 +0100 | [diff] [blame] | 4 | # Copyright 2019-2023 Arm Limited |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 5 | # |
David Brown | 79c4fcf | 2021-01-26 15:04:05 -0700 | [diff] [blame] | 6 | # SPDX-License-Identifier: Apache-2.0 |
| 7 | # |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 8 | # 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 Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 20 | import re |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 21 | import click |
| 22 | import getpass |
| 23 | import imgtool.keys as keys |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 24 | import sys |
Andrzej Puzdrowski | 160303c | 2022-03-15 15:41:14 +0100 | [diff] [blame] | 25 | import base64 |
Fabio Utzig | 25c6a15 | 2019-09-10 12:52:26 -0300 | [diff] [blame] | 26 | from imgtool import image, imgtool_version |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 27 | from imgtool.version import decode_version |
David Vincze | ca56135 | 2023-01-27 15:39:12 +0100 | [diff] [blame] | 28 | from imgtool.dumpinfo import dump_imginfo |
Fabio Utzig | 4facd1b | 2020-04-02 13:17:38 -0300 | [diff] [blame] | 29 | from .keys import ( |
| 30 | RSAUsageError, ECDSAUsageError, Ed25519UsageError, X25519UsageError) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 31 | |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 32 | MIN_PYTHON_VERSION = (3, 6) |
| 33 | if sys.version_info < MIN_PYTHON_VERSION: |
| 34 | sys.exit("Python %s.%s or newer is required by imgtool." |
| 35 | % MIN_PYTHON_VERSION) |
| 36 | |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 37 | |
| 38 | def gen_rsa2048(keyfile, passwd): |
Fabio Utzig | 19fd79a | 2019-05-08 18:20:39 -0300 | [diff] [blame] | 39 | keys.RSA.generate().export_private(path=keyfile, passwd=passwd) |
| 40 | |
| 41 | |
| 42 | def gen_rsa3072(keyfile, passwd): |
| 43 | keys.RSA.generate(key_size=3072).export_private(path=keyfile, |
| 44 | passwd=passwd) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 45 | |
| 46 | |
| 47 | def gen_ecdsa_p256(keyfile, passwd): |
| 48 | keys.ECDSA256P1.generate().export_private(keyfile, passwd=passwd) |
| 49 | |
| 50 | |
Roland Mikhel | 5704174 | 2023-02-03 14:43:13 +0100 | [diff] [blame] | 51 | def gen_ecdsa_p384(keyfile, passwd): |
| 52 | keys.ECDSA384P1.generate().export_private(keyfile, passwd=passwd) |
| 53 | |
| 54 | |
Fabio Utzig | 8101d1f | 2019-05-09 15:03:22 -0300 | [diff] [blame] | 55 | def gen_ed25519(keyfile, passwd): |
Fabio Utzig | 4bd4c7c | 2019-06-27 08:23:21 -0300 | [diff] [blame] | 56 | keys.Ed25519.generate().export_private(path=keyfile, passwd=passwd) |
Fabio Utzig | 8101d1f | 2019-05-09 15:03:22 -0300 | [diff] [blame] | 57 | |
| 58 | |
Fabio Utzig | 4facd1b | 2020-04-02 13:17:38 -0300 | [diff] [blame] | 59 | def gen_x25519(keyfile, passwd): |
| 60 | keys.X25519.generate().export_private(path=keyfile, passwd=passwd) |
| 61 | |
| 62 | |
Fabio Utzig | 4e2cdfe | 2022-09-28 17:44:01 -0300 | [diff] [blame] | 63 | valid_langs = ['c', 'rust'] |
Bence Balogh | 97a20f1 | 2023-07-18 15:59:33 +0200 | [diff] [blame^] | 64 | valid_hash_encodings = ['lang-c', 'raw'] |
Bence Balogh | ed8d68a | 2023-07-18 15:57:52 +0200 | [diff] [blame] | 65 | valid_encodings = ['lang-c', 'lang-rust', 'pem', 'raw'] |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 66 | keygens = { |
| 67 | 'rsa-2048': gen_rsa2048, |
Fabio Utzig | 19fd79a | 2019-05-08 18:20:39 -0300 | [diff] [blame] | 68 | 'rsa-3072': gen_rsa3072, |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 69 | 'ecdsa-p256': gen_ecdsa_p256, |
Roland Mikhel | 5704174 | 2023-02-03 14:43:13 +0100 | [diff] [blame] | 70 | 'ecdsa-p384': gen_ecdsa_p384, |
Fabio Utzig | 4facd1b | 2020-04-02 13:17:38 -0300 | [diff] [blame] | 71 | 'ed25519': gen_ed25519, |
| 72 | 'x25519': gen_x25519, |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 73 | } |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 74 | valid_formats = ['openssl', 'pkcs8'] |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 75 | |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame] | 76 | |
Andrzej Puzdrowski | 160303c | 2022-03-15 15:41:14 +0100 | [diff] [blame] | 77 | def load_signature(sigfile): |
| 78 | with open(sigfile, 'rb') as f: |
| 79 | signature = base64.b64decode(f.read()) |
| 80 | return signature |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 81 | |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame] | 82 | |
Andrzej Puzdrowski | f72e374 | 2022-03-17 11:34:38 +0100 | [diff] [blame] | 83 | def save_signature(sigfile, sig): |
| 84 | with open(sigfile, 'wb') as f: |
| 85 | signature = base64.b64encode(sig) |
| 86 | f.write(signature) |
| 87 | |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame] | 88 | |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 89 | def load_key(keyfile): |
| 90 | # TODO: better handling of invalid pass-phrase |
| 91 | key = keys.load(keyfile) |
| 92 | if key is not None: |
| 93 | return key |
| 94 | passwd = getpass.getpass("Enter key passphrase: ").encode('utf-8') |
| 95 | return keys.load(keyfile, passwd) |
| 96 | |
| 97 | |
| 98 | def get_password(): |
| 99 | while True: |
| 100 | passwd = getpass.getpass("Enter key passphrase: ") |
| 101 | passwd2 = getpass.getpass("Reenter passphrase: ") |
| 102 | if passwd == passwd2: |
| 103 | break |
| 104 | print("Passwords do not match, try again") |
| 105 | |
| 106 | # Password must be bytes, always use UTF-8 for consistent |
| 107 | # encoding. |
| 108 | return passwd.encode('utf-8') |
| 109 | |
| 110 | |
| 111 | @click.option('-p', '--password', is_flag=True, |
| 112 | help='Prompt for password to protect key') |
| 113 | @click.option('-t', '--type', metavar='type', required=True, |
Fabio Utzig | 7ca2855 | 2019-12-13 11:24:20 -0300 | [diff] [blame] | 114 | type=click.Choice(keygens.keys()), prompt=True, |
| 115 | help='{}'.format('One of: {}'.format(', '.join(keygens.keys())))) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 116 | @click.option('-k', '--key', metavar='filename', required=True) |
| 117 | @click.command(help='Generate pub/private keypair') |
| 118 | def keygen(type, key, password): |
| 119 | password = get_password() if password else None |
| 120 | keygens[type](key, password) |
| 121 | |
| 122 | |
Fabio Utzig | 4e2cdfe | 2022-09-28 17:44:01 -0300 | [diff] [blame] | 123 | @click.option('-l', '--lang', metavar='lang', |
| 124 | type=click.Choice(valid_langs), |
| 125 | help='This option is deprecated. Please use the ' |
| 126 | '`--encoding` option. ' |
| 127 | 'Valid langs: {}'.format(', '.join(valid_langs))) |
| 128 | @click.option('-e', '--encoding', metavar='encoding', |
| 129 | type=click.Choice(valid_encodings), |
| 130 | help='Valid encodings: {}'.format(', '.join(valid_encodings))) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 131 | @click.option('-k', '--key', metavar='filename', required=True) |
Bence Balogh | 367aefb | 2023-07-18 15:51:54 +0200 | [diff] [blame] | 132 | @click.option('-o', '--output', metavar='output', required=False, |
| 133 | help='Specify the output file\'s name. \ |
| 134 | The stdout is used if it is not provided.') |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 135 | @click.command(help='Dump public key from keypair') |
Bence Balogh | 367aefb | 2023-07-18 15:51:54 +0200 | [diff] [blame] | 136 | def getpub(key, encoding, lang, output): |
Fabio Utzig | 4e2cdfe | 2022-09-28 17:44:01 -0300 | [diff] [blame] | 137 | if encoding and lang: |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame] | 138 | raise click.UsageError('Please use only one of `--encoding/-e` ' |
| 139 | 'or `--lang/-l`') |
Fabio Utzig | 4e2cdfe | 2022-09-28 17:44:01 -0300 | [diff] [blame] | 140 | elif not encoding and not lang: |
| 141 | # Preserve old behavior defaulting to `c`. If `lang` is removed, |
| 142 | # `default=valid_encodings[0]` should be added to `-e` param. |
| 143 | lang = valid_langs[0] |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 144 | key = load_key(key) |
Bence Balogh | 367aefb | 2023-07-18 15:51:54 +0200 | [diff] [blame] | 145 | |
| 146 | if not output: |
| 147 | output = sys.stdout |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 148 | if key is None: |
| 149 | print("Invalid passphrase") |
Fabio Utzig | 4e2cdfe | 2022-09-28 17:44:01 -0300 | [diff] [blame] | 150 | elif lang == 'c' or encoding == 'lang-c': |
Bence Balogh | 367aefb | 2023-07-18 15:51:54 +0200 | [diff] [blame] | 151 | key.emit_c_public(file=output) |
Fabio Utzig | 4e2cdfe | 2022-09-28 17:44:01 -0300 | [diff] [blame] | 152 | elif lang == 'rust' or encoding == 'lang-rust': |
Bence Balogh | 367aefb | 2023-07-18 15:51:54 +0200 | [diff] [blame] | 153 | key.emit_rust_public(file=output) |
Fabio Utzig | 4e2cdfe | 2022-09-28 17:44:01 -0300 | [diff] [blame] | 154 | elif encoding == 'pem': |
Bence Balogh | 367aefb | 2023-07-18 15:51:54 +0200 | [diff] [blame] | 155 | key.emit_public_pem(file=output) |
Bence Balogh | ed8d68a | 2023-07-18 15:57:52 +0200 | [diff] [blame] | 156 | elif encoding == 'raw': |
| 157 | key.emit_raw_public(file=output) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 158 | else: |
Fabio Utzig | 4e2cdfe | 2022-09-28 17:44:01 -0300 | [diff] [blame] | 159 | raise click.UsageError() |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 160 | |
| 161 | |
Bence Balogh | 97a20f1 | 2023-07-18 15:59:33 +0200 | [diff] [blame^] | 162 | @click.option('-e', '--encoding', metavar='encoding', |
| 163 | type=click.Choice(valid_hash_encodings), |
| 164 | help='Valid encodings: {}. ' |
| 165 | 'Default value is {}.' |
| 166 | .format(', '.join(valid_hash_encodings), |
| 167 | valid_hash_encodings[0])) |
| 168 | @click.option('-k', '--key', metavar='filename', required=True) |
| 169 | @click.option('-o', '--output', metavar='output', required=False, |
| 170 | help='Specify the output file\'s name. \ |
| 171 | The stdout is used if it is not provided.') |
| 172 | @click.command(help='Dump the SHA256 hash of the public key') |
| 173 | def getpubhash(key, output, encoding): |
| 174 | if not encoding: |
| 175 | encoding = valid_hash_encodings[0] |
| 176 | key = load_key(key) |
| 177 | |
| 178 | if not output: |
| 179 | output = sys.stdout |
| 180 | if key is None: |
| 181 | print("Invalid passphrase") |
| 182 | elif encoding == 'lang-c': |
| 183 | key.emit_c_public_hash(file=output) |
| 184 | elif encoding == 'raw': |
| 185 | key.emit_raw_public_hash(file=output) |
| 186 | else: |
| 187 | raise click.UsageError() |
| 188 | |
| 189 | |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 190 | @click.option('--minimal', default=False, is_flag=True, |
| 191 | help='Reduce the size of the dumped private key to include only ' |
| 192 | 'the minimum amount of data required to decrypt. This ' |
| 193 | 'might require changes to the build config. Check the docs!' |
| 194 | ) |
| 195 | @click.option('-k', '--key', metavar='filename', required=True) |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 196 | @click.option('-f', '--format', |
| 197 | type=click.Choice(valid_formats), |
Fabio Utzig | 8f289ba | 2023-01-09 21:01:55 -0300 | [diff] [blame] | 198 | help='Valid formats: {}'.format(', '.join(valid_formats)) |
| 199 | ) |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 200 | @click.command(help='Dump private key from keypair') |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 201 | def getpriv(key, minimal, format): |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 202 | key = load_key(key) |
| 203 | if key is None: |
| 204 | print("Invalid passphrase") |
Fabio Utzig | 1f50892 | 2020-01-15 11:37:51 -0300 | [diff] [blame] | 205 | try: |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 206 | key.emit_private(minimal, format) |
Fabio Utzig | 4facd1b | 2020-04-02 13:17:38 -0300 | [diff] [blame] | 207 | except (RSAUsageError, ECDSAUsageError, Ed25519UsageError, |
| 208 | X25519UsageError) as e: |
Fabio Utzig | 1f50892 | 2020-01-15 11:37:51 -0300 | [diff] [blame] | 209 | raise click.UsageError(e) |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 210 | |
| 211 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 212 | @click.argument('imgfile') |
| 213 | @click.option('-k', '--key', metavar='filename') |
| 214 | @click.command(help="Check that signed image can be verified by given key") |
| 215 | def verify(key, imgfile): |
| 216 | key = load_key(key) if key else None |
Casper Meijn | 2a01f3f | 2020-08-22 13:51:40 +0200 | [diff] [blame] | 217 | ret, version, digest = image.Image.verify(imgfile, key) |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 218 | if ret == image.VerifyResult.OK: |
| 219 | print("Image was correctly validated") |
Marek Pieta | e955510 | 2019-08-08 16:08:16 +0200 | [diff] [blame] | 220 | print("Image version: {}.{}.{}+{}".format(*version)) |
Casper Meijn | 2a01f3f | 2020-08-22 13:51:40 +0200 | [diff] [blame] | 221 | print("Image digest: {}".format(digest.hex())) |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 222 | return |
| 223 | elif ret == image.VerifyResult.INVALID_MAGIC: |
| 224 | print("Invalid image magic; is this an MCUboot image?") |
Christian Skubich | f13db12 | 2019-07-31 11:34:15 +0200 | [diff] [blame] | 225 | elif ret == image.VerifyResult.INVALID_TLV_INFO_MAGIC: |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 226 | print("Invalid TLV info magic; is this an MCUboot image?") |
| 227 | elif ret == image.VerifyResult.INVALID_HASH: |
Roland Mikhel | 5704174 | 2023-02-03 14:43:13 +0100 | [diff] [blame] | 228 | print("Image has an invalid hash") |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 229 | elif ret == image.VerifyResult.INVALID_SIGNATURE: |
| 230 | print("No signature found for the given key") |
Christian Skubich | f13db12 | 2019-07-31 11:34:15 +0200 | [diff] [blame] | 231 | else: |
| 232 | print("Unknown return code: {}".format(ret)) |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 233 | sys.exit(1) |
| 234 | |
| 235 | |
David Vincze | ca56135 | 2023-01-27 15:39:12 +0100 | [diff] [blame] | 236 | @click.argument('imgfile') |
| 237 | @click.option('-o', '--outfile', metavar='filename', required=False, |
| 238 | help='Save image information to outfile in YAML format') |
| 239 | @click.option('-s', '--silent', default=False, is_flag=True, |
| 240 | help='Do not print image information to output') |
| 241 | @click.command(help='Print header, TLV area and trailer information ' |
| 242 | 'of a signed image') |
| 243 | def dumpinfo(imgfile, outfile, silent): |
| 244 | dump_imginfo(imgfile, outfile, silent) |
| 245 | print("dumpinfo has run successfully") |
| 246 | |
| 247 | |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 248 | def validate_version(ctx, param, value): |
| 249 | try: |
| 250 | decode_version(value) |
| 251 | return value |
| 252 | except ValueError as e: |
| 253 | raise click.BadParameter("{}".format(e)) |
| 254 | |
| 255 | |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 256 | def validate_security_counter(ctx, param, value): |
| 257 | if value is not None: |
| 258 | if value.lower() == 'auto': |
| 259 | return 'auto' |
| 260 | else: |
| 261 | try: |
| 262 | return int(value, 0) |
| 263 | except ValueError: |
| 264 | raise click.BadParameter( |
| 265 | "{} is not a valid integer. Please use code literals " |
| 266 | "prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary." |
| 267 | .format(value)) |
| 268 | |
| 269 | |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 270 | def validate_header_size(ctx, param, value): |
| 271 | min_hdr_size = image.IMAGE_HEADER_SIZE |
| 272 | if value < min_hdr_size: |
| 273 | raise click.BadParameter( |
| 274 | "Minimum value for -H/--header-size is {}".format(min_hdr_size)) |
| 275 | return value |
| 276 | |
| 277 | |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 278 | def get_dependencies(ctx, param, value): |
| 279 | if value is not None: |
| 280 | versions = [] |
| 281 | images = re.findall(r"\((\d+)", value) |
| 282 | if len(images) == 0: |
| 283 | raise click.BadParameter( |
| 284 | "Image dependency format is invalid: {}".format(value)) |
| 285 | raw_versions = re.findall(r",\s*([0-9.+]+)\)", value) |
| 286 | if len(images) != len(raw_versions): |
| 287 | raise click.BadParameter( |
| 288 | '''There's a mismatch between the number of dependency images |
| 289 | and versions in: {}'''.format(value)) |
| 290 | for raw_version in raw_versions: |
| 291 | try: |
| 292 | versions.append(decode_version(raw_version)) |
| 293 | except ValueError as e: |
| 294 | raise click.BadParameter("{}".format(e)) |
| 295 | dependencies = dict() |
| 296 | dependencies[image.DEP_IMAGES_KEY] = images |
| 297 | dependencies[image.DEP_VERSIONS_KEY] = versions |
| 298 | return dependencies |
| 299 | |
| 300 | |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 301 | class BasedIntParamType(click.ParamType): |
| 302 | name = 'integer' |
| 303 | |
| 304 | def convert(self, value, param, ctx): |
| 305 | try: |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 306 | return int(value, 0) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 307 | except ValueError: |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 308 | self.fail('%s is not a valid integer. Please use code literals ' |
| 309 | 'prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary.' |
| 310 | % value, param, ctx) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 311 | |
| 312 | |
| 313 | @click.argument('outfile') |
| 314 | @click.argument('infile') |
Ihor Slabkyy | 24d9373 | 2020-03-10 15:33:57 +0200 | [diff] [blame] | 315 | @click.option('--custom-tlv', required=False, nargs=2, default=[], |
| 316 | multiple=True, metavar='[tag] [value]', |
| 317 | help='Custom TLV that will be placed into protected area. ' |
| 318 | 'Add "0x" prefix if the value should be interpreted as an ' |
| 319 | 'integer, otherwise it will be interpreted as a string. ' |
| 320 | 'Specify the option multiple times to add multiple TLVs.') |
Fabio Utzig | 9117fde | 2019-10-17 11:11:46 -0300 | [diff] [blame] | 321 | @click.option('-R', '--erased-val', type=click.Choice(['0', '0xff']), |
| 322 | required=False, |
| 323 | help='The value that is read back from erased flash.') |
Fabio Utzig | edbabcf | 2019-10-11 13:03:37 -0300 | [diff] [blame] | 324 | @click.option('-x', '--hex-addr', type=BasedIntParamType(), required=False, |
| 325 | help='Adjust address in hex output file.') |
Håkon Øye Amundsen | df8c891 | 2019-08-26 12:15:28 +0000 | [diff] [blame] | 326 | @click.option('-L', '--load-addr', type=BasedIntParamType(), required=False, |
David Vincze | 1e0c544 | 2020-04-07 14:12:33 +0200 | [diff] [blame] | 327 | help='Load address for image when it should run from RAM.') |
Dominik Ermel | 50820b1 | 2020-12-14 13:16:46 +0000 | [diff] [blame] | 328 | @click.option('-F', '--rom-fixed', type=BasedIntParamType(), required=False, |
| 329 | help='Set flash address the image is built for.') |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 330 | @click.option('--save-enctlv', default=False, is_flag=True, |
| 331 | help='When upgrading, save encrypted key TLVs instead of plain ' |
| 332 | 'keys. Enable when BOOT_SWAP_SAVE_ENCTLV config option ' |
| 333 | 'was set.') |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 334 | @click.option('-E', '--encrypt', metavar='filename', |
David Vincze | e574f2d | 2020-07-10 11:42:03 +0200 | [diff] [blame] | 335 | help='Encrypt image using the provided public key. ' |
Tamas Ban | fe03109 | 2020-09-10 17:32:39 +0200 | [diff] [blame] | 336 | '(Not supported in direct-xip or ram-load mode.)') |
Salome Thirot | 0f64197 | 2021-05-14 11:19:55 +0100 | [diff] [blame] | 337 | @click.option('--encrypt-keylen', default='128', |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame] | 338 | type=click.Choice(['128', '256']), |
Salome Thirot | 0f64197 | 2021-05-14 11:19:55 +0100 | [diff] [blame] | 339 | help='When encrypting the image using AES, select a 128 bit or ' |
| 340 | '256 bit key len.') |
Michel Jaouen | d09aa6b | 2022-01-07 16:48:58 +0100 | [diff] [blame] | 341 | @click.option('-c', '--clear', required=False, is_flag=True, default=False, |
| 342 | help='Output a non-encrypted image with encryption capabilities,' |
| 343 | 'so it can be installed in the primary slot, and encrypted ' |
| 344 | 'when swapped to the secondary.') |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 345 | @click.option('-e', '--endian', type=click.Choice(['little', 'big']), |
| 346 | default='little', help="Select little or big endian") |
| 347 | @click.option('--overwrite-only', default=False, is_flag=True, |
| 348 | help='Use overwrite-only instead of swap upgrades') |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 349 | @click.option('--boot-record', metavar='sw_type', help='Create CBOR encoded ' |
| 350 | 'boot record TLV. The sw_type represents the role of the ' |
| 351 | 'software component (e.g. CoFM for coprocessor firmware). ' |
| 352 | '[max. 12 characters]') |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 353 | @click.option('-M', '--max-sectors', type=int, |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 354 | help='When padding allow for this amount of sectors (defaults ' |
| 355 | 'to 128)') |
Henrik Brix Andersen | 0ce958e | 2020-03-11 14:04:11 +0100 | [diff] [blame] | 356 | @click.option('--confirm', default=False, is_flag=True, |
Martí Bolívar | 009a150 | 2020-09-04 14:23:39 -0700 | [diff] [blame] | 357 | help='When padding the image, mark it as confirmed (implies ' |
| 358 | '--pad)') |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 359 | @click.option('--pad', default=False, is_flag=True, |
| 360 | help='Pad image to --slot-size bytes, adding trailer magic') |
| 361 | @click.option('-S', '--slot-size', type=BasedIntParamType(), required=True, |
Fabio Utzig | 826abf4 | 2020-07-13 20:56:35 -0300 | [diff] [blame] | 362 | help='Size of the slot. If the slots have different sizes, use ' |
| 363 | 'the size of the secondary slot.') |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 364 | @click.option('--pad-header', default=False, is_flag=True, |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 365 | help='Add --header-size zeroed bytes at the beginning of the ' |
| 366 | 'image') |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 367 | @click.option('-H', '--header-size', callback=validate_header_size, |
| 368 | type=BasedIntParamType(), required=True) |
David Brown | 4878c27 | 2020-03-10 16:23:56 -0600 | [diff] [blame] | 369 | @click.option('--pad-sig', default=False, is_flag=True, |
| 370 | help='Add 0-2 bytes of padding to ECDSA signature ' |
| 371 | '(for mcuboot <1.5)') |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 372 | @click.option('-d', '--dependencies', callback=get_dependencies, |
| 373 | required=False, help='''Add dependence on another image, format: |
| 374 | "(<image_ID>,<image_version>), ... "''') |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 375 | @click.option('-s', '--security-counter', callback=validate_security_counter, |
| 376 | help='Specify the value of security counter. Use the `auto` ' |
| 377 | 'keyword to automatically generate it from the image version.') |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 378 | @click.option('-v', '--version', callback=validate_version, required=True) |
Kristine Jassmann | 73c38c6 | 2021-02-03 16:56:14 +0000 | [diff] [blame] | 379 | @click.option('--align', type=click.Choice(['1', '2', '4', '8', '16', '32']), |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 380 | required=True) |
Kristine Jassmann | 73c38c6 | 2021-02-03 16:56:14 +0000 | [diff] [blame] | 381 | @click.option('--max-align', type=click.Choice(['8', '16', '32']), |
Piotr Mienkowski | b6d5cf3 | 2022-01-31 01:01:11 +0100 | [diff] [blame] | 382 | required=False, |
| 383 | help='Maximum flash alignment. Set if flash alignment of the ' |
| 384 | 'primary and secondary slot differ and any of them is larger ' |
| 385 | 'than 8.') |
David Vincze | dde178d | 2020-03-26 20:06:01 +0100 | [diff] [blame] | 386 | @click.option('--public-key-format', type=click.Choice(['hash', 'full']), |
| 387 | default='hash', help='In what format to add the public key to ' |
| 388 | 'the image manifest: full key or hash of the key.') |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 389 | @click.option('-k', '--key', metavar='filename') |
Andrzej Puzdrowski | 160303c | 2022-03-15 15:41:14 +0100 | [diff] [blame] | 390 | @click.option('--fix-sig', metavar='filename', |
iysheng | 6093cbb | 2022-05-28 17:00:40 +0800 | [diff] [blame] | 391 | help='fixed signature for the image. It will be used instead of ' |
Andrzej Puzdrowski | 160303c | 2022-03-15 15:41:14 +0100 | [diff] [blame] | 392 | 'the signature calculated using the public key') |
| 393 | @click.option('--fix-sig-pubkey', metavar='filename', |
| 394 | help='public key relevant to fixed signature') |
Andrzej Puzdrowski | f72e374 | 2022-03-17 11:34:38 +0100 | [diff] [blame] | 395 | @click.option('--sig-out', metavar='filename', |
iysheng | 6093cbb | 2022-05-28 17:00:40 +0800 | [diff] [blame] | 396 | help='Path to the file to which signature will be written. ' |
Andrzej Puzdrowski | f72e374 | 2022-03-17 11:34:38 +0100 | [diff] [blame] | 397 | 'The image signature will be encoded as base64 formatted string') |
Andrzej Puzdrowski | dfce0be | 2022-03-28 09:34:15 +0200 | [diff] [blame] | 398 | @click.option('--vector-to-sign', type=click.Choice(['payload', 'digest']), |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame] | 399 | help='send to OUTFILE the payload or payload''s digest instead ' |
| 400 | 'of complied image. These data can be used for external image ' |
Andrzej Puzdrowski | dfce0be | 2022-03-28 09:34:15 +0200 | [diff] [blame] | 401 | 'signing') |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 402 | @click.command(help='''Create a signed or unsigned image\n |
| 403 | INFILE and OUTFILE are parsed as Intel HEX if the params have |
Håkon Øye Amundsen | df8c891 | 2019-08-26 12:15:28 +0000 | [diff] [blame] | 404 | .hex extension, otherwise binary format is used''') |
David Vincze | dde178d | 2020-03-26 20:06:01 +0100 | [diff] [blame] | 405 | def sign(key, public_key_format, align, version, pad_sig, header_size, |
| 406 | pad_header, slot_size, pad, confirm, max_sectors, overwrite_only, |
Salome Thirot | 0f64197 | 2021-05-14 11:19:55 +0100 | [diff] [blame] | 407 | endian, encrypt_keylen, encrypt, infile, outfile, dependencies, |
| 408 | load_addr, hex_addr, erased_val, save_enctlv, security_counter, |
Andrzej Puzdrowski | 160303c | 2022-03-15 15:41:14 +0100 | [diff] [blame] | 409 | boot_record, custom_tlv, rom_fixed, max_align, clear, fix_sig, |
David Vincze | 7f982b0 | 2023-04-27 16:12:17 +0200 | [diff] [blame] | 410 | fix_sig_pubkey, sig_out, vector_to_sign): |
Martí Bolívar | 009a150 | 2020-09-04 14:23:39 -0700 | [diff] [blame] | 411 | |
| 412 | if confirm: |
| 413 | # Confirmed but non-padded images don't make much sense, because |
| 414 | # otherwise there's no trailer area for writing the confirmed status. |
| 415 | pad = True |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 416 | img = image.Image(version=decode_version(version), header_size=header_size, |
Henrik Brix Andersen | 0ce958e | 2020-03-11 14:04:11 +0100 | [diff] [blame] | 417 | pad_header=pad_header, pad=pad, confirm=confirm, |
| 418 | align=int(align), slot_size=slot_size, |
| 419 | max_sectors=max_sectors, overwrite_only=overwrite_only, |
Dominik Ermel | 50820b1 | 2020-12-14 13:16:46 +0000 | [diff] [blame] | 420 | endian=endian, load_addr=load_addr, rom_fixed=rom_fixed, |
| 421 | erased_val=erased_val, save_enctlv=save_enctlv, |
Kristine Jassmann | 73c38c6 | 2021-02-03 16:56:14 +0000 | [diff] [blame] | 422 | security_counter=security_counter, max_align=max_align) |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 423 | img.load(infile) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 424 | key = load_key(key) if key else None |
| 425 | enckey = load_key(encrypt) if encrypt else None |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 426 | if enckey and key: |
| 427 | if ((isinstance(key, keys.ECDSA256P1) and |
| 428 | not isinstance(enckey, keys.ECDSA256P1Public)) |
Roland Mikhel | 5704174 | 2023-02-03 14:43:13 +0100 | [diff] [blame] | 429 | or (isinstance(key, keys.ECDSA384P1) and |
| 430 | not isinstance(enckey, keys.ECDSA384P1Public)) |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 431 | or (isinstance(key, keys.RSA) and |
| 432 | not isinstance(enckey, keys.RSAPublic))): |
| 433 | # FIXME |
Fabio Utzig | 1f50892 | 2020-01-15 11:37:51 -0300 | [diff] [blame] | 434 | raise click.UsageError("Signing and encryption must use the same " |
| 435 | "type of key") |
David Brown | 4878c27 | 2020-03-10 16:23:56 -0600 | [diff] [blame] | 436 | |
| 437 | if pad_sig and hasattr(key, 'pad_sig'): |
| 438 | key.pad_sig = True |
| 439 | |
Ihor Slabkyy | 24d9373 | 2020-03-10 15:33:57 +0200 | [diff] [blame] | 440 | # Get list of custom protected TLVs from the command-line |
| 441 | custom_tlvs = {} |
| 442 | for tlv in custom_tlv: |
| 443 | tag = int(tlv[0], 0) |
| 444 | if tag in custom_tlvs: |
| 445 | raise click.UsageError('Custom TLV %s already exists.' % hex(tag)) |
| 446 | if tag in image.TLV_VALUES.values(): |
| 447 | raise click.UsageError( |
| 448 | 'Custom TLV %s conflicts with predefined TLV.' % hex(tag)) |
| 449 | |
| 450 | value = tlv[1] |
| 451 | if value.startswith('0x'): |
| 452 | if len(value[2:]) % 2: |
| 453 | raise click.UsageError('Custom TLV length is odd.') |
| 454 | custom_tlvs[tag] = bytes.fromhex(value[2:]) |
| 455 | else: |
| 456 | custom_tlvs[tag] = value.encode('utf-8') |
| 457 | |
Andrzej Puzdrowski | 160303c | 2022-03-15 15:41:14 +0100 | [diff] [blame] | 458 | # Allow signature calculated externally. |
| 459 | raw_signature = load_signature(fix_sig) if fix_sig else None |
| 460 | |
| 461 | baked_signature = None |
| 462 | pub_key = None |
| 463 | |
| 464 | if raw_signature is not None: |
| 465 | if fix_sig_pubkey is None: |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame] | 466 | raise click.UsageError( |
Andrzej Puzdrowski | 160303c | 2022-03-15 15:41:14 +0100 | [diff] [blame] | 467 | 'public key of the fixed signature is not specified') |
| 468 | |
| 469 | pub_key = load_key(fix_sig_pubkey) |
| 470 | |
| 471 | baked_signature = { |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame] | 472 | 'value': raw_signature |
Andrzej Puzdrowski | 160303c | 2022-03-15 15:41:14 +0100 | [diff] [blame] | 473 | } |
| 474 | |
Ihor Slabkyy | 24d9373 | 2020-03-10 15:33:57 +0200 | [diff] [blame] | 475 | img.create(key, public_key_format, enckey, dependencies, boot_record, |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame] | 476 | custom_tlvs, int(encrypt_keylen), clear, baked_signature, |
David Vincze | 7f982b0 | 2023-04-27 16:12:17 +0200 | [diff] [blame] | 477 | pub_key, vector_to_sign) |
Fabio Utzig | edbabcf | 2019-10-11 13:03:37 -0300 | [diff] [blame] | 478 | img.save(outfile, hex_addr) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 479 | |
Andrzej Puzdrowski | f72e374 | 2022-03-17 11:34:38 +0100 | [diff] [blame] | 480 | if sig_out is not None: |
| 481 | new_signature = img.get_signature() |
| 482 | save_signature(sig_out, new_signature) |
| 483 | |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 484 | |
| 485 | class AliasesGroup(click.Group): |
| 486 | |
| 487 | _aliases = { |
| 488 | "create": "sign", |
| 489 | } |
| 490 | |
| 491 | def list_commands(self, ctx): |
| 492 | cmds = [k for k in self.commands] |
| 493 | aliases = [k for k in self._aliases] |
| 494 | return sorted(cmds + aliases) |
| 495 | |
| 496 | def get_command(self, ctx, cmd_name): |
| 497 | rv = click.Group.get_command(self, ctx, cmd_name) |
| 498 | if rv is not None: |
| 499 | return rv |
| 500 | if cmd_name in self._aliases: |
| 501 | return click.Group.get_command(self, ctx, self._aliases[cmd_name]) |
| 502 | return None |
| 503 | |
| 504 | |
Fabio Utzig | 25c6a15 | 2019-09-10 12:52:26 -0300 | [diff] [blame] | 505 | @click.command(help='Print imgtool version information') |
| 506 | def version(): |
| 507 | print(imgtool_version) |
| 508 | |
| 509 | |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 510 | @click.command(cls=AliasesGroup, |
| 511 | context_settings=dict(help_option_names=['-h', '--help'])) |
| 512 | def imgtool(): |
| 513 | pass |
| 514 | |
| 515 | |
| 516 | imgtool.add_command(keygen) |
| 517 | imgtool.add_command(getpub) |
Bence Balogh | 97a20f1 | 2023-07-18 15:59:33 +0200 | [diff] [blame^] | 518 | imgtool.add_command(getpubhash) |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 519 | imgtool.add_command(getpriv) |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 520 | imgtool.add_command(verify) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 521 | imgtool.add_command(sign) |
Fabio Utzig | 25c6a15 | 2019-09-10 12:52:26 -0300 | [diff] [blame] | 522 | imgtool.add_command(version) |
David Vincze | ca56135 | 2023-01-27 15:39:12 +0100 | [diff] [blame] | 523 | imgtool.add_command(dumpinfo) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 524 | |
| 525 | |
| 526 | if __name__ == '__main__': |
| 527 | imgtool() |