Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 1 | #! /usr/bin/env python3 |
| 2 | # |
| 3 | # Copyright 2017 Linaro Limited |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 4 | # Copyright 2019-2020 Arm Limited |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 5 | # |
| 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 Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 18 | import re |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 19 | import click |
| 20 | import getpass |
| 21 | import imgtool.keys as keys |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 22 | import sys |
Fabio Utzig | 25c6a15 | 2019-09-10 12:52:26 -0300 | [diff] [blame] | 23 | from imgtool import image, imgtool_version |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 24 | from imgtool.version import decode_version |
Fabio Utzig | 1f50892 | 2020-01-15 11:37:51 -0300 | [diff] [blame] | 25 | from .keys import RSAUsageError, ECDSAUsageError, Ed25519UsageError |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 26 | |
| 27 | |
| 28 | def gen_rsa2048(keyfile, passwd): |
Fabio Utzig | 19fd79a | 2019-05-08 18:20:39 -0300 | [diff] [blame] | 29 | keys.RSA.generate().export_private(path=keyfile, passwd=passwd) |
| 30 | |
| 31 | |
| 32 | def gen_rsa3072(keyfile, passwd): |
| 33 | keys.RSA.generate(key_size=3072).export_private(path=keyfile, |
| 34 | passwd=passwd) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 35 | |
| 36 | |
| 37 | def gen_ecdsa_p256(keyfile, passwd): |
| 38 | keys.ECDSA256P1.generate().export_private(keyfile, passwd=passwd) |
| 39 | |
| 40 | |
| 41 | def gen_ecdsa_p224(keyfile, passwd): |
| 42 | print("TODO: p-224 not yet implemented") |
| 43 | |
| 44 | |
Fabio Utzig | 8101d1f | 2019-05-09 15:03:22 -0300 | [diff] [blame] | 45 | def gen_ed25519(keyfile, passwd): |
Fabio Utzig | 4bd4c7c | 2019-06-27 08:23:21 -0300 | [diff] [blame] | 46 | keys.Ed25519.generate().export_private(path=keyfile, passwd=passwd) |
Fabio Utzig | 8101d1f | 2019-05-09 15:03:22 -0300 | [diff] [blame] | 47 | |
| 48 | |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 49 | valid_langs = ['c', 'rust'] |
| 50 | keygens = { |
| 51 | 'rsa-2048': gen_rsa2048, |
Fabio Utzig | 19fd79a | 2019-05-08 18:20:39 -0300 | [diff] [blame] | 52 | 'rsa-3072': gen_rsa3072, |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 53 | 'ecdsa-p256': gen_ecdsa_p256, |
| 54 | 'ecdsa-p224': gen_ecdsa_p224, |
Fabio Utzig | 8101d1f | 2019-05-09 15:03:22 -0300 | [diff] [blame] | 55 | 'ed25519': gen_ed25519, |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 56 | } |
| 57 | |
| 58 | |
| 59 | def load_key(keyfile): |
| 60 | # TODO: better handling of invalid pass-phrase |
| 61 | key = keys.load(keyfile) |
| 62 | if key is not None: |
| 63 | return key |
| 64 | passwd = getpass.getpass("Enter key passphrase: ").encode('utf-8') |
| 65 | return keys.load(keyfile, passwd) |
| 66 | |
| 67 | |
| 68 | def get_password(): |
| 69 | while True: |
| 70 | passwd = getpass.getpass("Enter key passphrase: ") |
| 71 | passwd2 = getpass.getpass("Reenter passphrase: ") |
| 72 | if passwd == passwd2: |
| 73 | break |
| 74 | print("Passwords do not match, try again") |
| 75 | |
| 76 | # Password must be bytes, always use UTF-8 for consistent |
| 77 | # encoding. |
| 78 | return passwd.encode('utf-8') |
| 79 | |
| 80 | |
| 81 | @click.option('-p', '--password', is_flag=True, |
| 82 | help='Prompt for password to protect key') |
| 83 | @click.option('-t', '--type', metavar='type', required=True, |
Fabio Utzig | 7ca2855 | 2019-12-13 11:24:20 -0300 | [diff] [blame] | 84 | type=click.Choice(keygens.keys()), prompt=True, |
| 85 | help='{}'.format('One of: {}'.format(', '.join(keygens.keys())))) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 86 | @click.option('-k', '--key', metavar='filename', required=True) |
| 87 | @click.command(help='Generate pub/private keypair') |
| 88 | def keygen(type, key, password): |
| 89 | password = get_password() if password else None |
| 90 | keygens[type](key, password) |
| 91 | |
| 92 | |
| 93 | @click.option('-l', '--lang', metavar='lang', default=valid_langs[0], |
| 94 | type=click.Choice(valid_langs)) |
| 95 | @click.option('-k', '--key', metavar='filename', required=True) |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 96 | @click.command(help='Dump public key from keypair') |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 97 | def getpub(key, lang): |
| 98 | key = load_key(key) |
| 99 | if key is None: |
| 100 | print("Invalid passphrase") |
| 101 | elif lang == 'c': |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 102 | key.emit_c_public() |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 103 | elif lang == 'rust': |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 104 | key.emit_rust_public() |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 105 | else: |
| 106 | raise ValueError("BUG: should never get here!") |
| 107 | |
| 108 | |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 109 | @click.option('--minimal', default=False, is_flag=True, |
| 110 | help='Reduce the size of the dumped private key to include only ' |
| 111 | 'the minimum amount of data required to decrypt. This ' |
| 112 | 'might require changes to the build config. Check the docs!' |
| 113 | ) |
| 114 | @click.option('-k', '--key', metavar='filename', required=True) |
| 115 | @click.command(help='Dump private key from keypair') |
| 116 | def getpriv(key, minimal): |
| 117 | key = load_key(key) |
| 118 | if key is None: |
| 119 | print("Invalid passphrase") |
Fabio Utzig | 1f50892 | 2020-01-15 11:37:51 -0300 | [diff] [blame] | 120 | try: |
| 121 | key.emit_private(minimal) |
| 122 | except (RSAUsageError, ECDSAUsageError, Ed25519UsageError) as e: |
| 123 | raise click.UsageError(e) |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 124 | |
| 125 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 126 | @click.argument('imgfile') |
| 127 | @click.option('-k', '--key', metavar='filename') |
| 128 | @click.command(help="Check that signed image can be verified by given key") |
| 129 | def verify(key, imgfile): |
| 130 | key = load_key(key) if key else None |
Marek Pieta | e955510 | 2019-08-08 16:08:16 +0200 | [diff] [blame] | 131 | ret, version = image.Image.verify(imgfile, key) |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 132 | if ret == image.VerifyResult.OK: |
| 133 | print("Image was correctly validated") |
Marek Pieta | e955510 | 2019-08-08 16:08:16 +0200 | [diff] [blame] | 134 | print("Image version: {}.{}.{}+{}".format(*version)) |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 135 | return |
| 136 | elif ret == image.VerifyResult.INVALID_MAGIC: |
| 137 | print("Invalid image magic; is this an MCUboot image?") |
Christian Skubich | f13db12 | 2019-07-31 11:34:15 +0200 | [diff] [blame] | 138 | elif ret == image.VerifyResult.INVALID_TLV_INFO_MAGIC: |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 139 | print("Invalid TLV info magic; is this an MCUboot image?") |
| 140 | elif ret == image.VerifyResult.INVALID_HASH: |
| 141 | print("Image has an invalid sha256 digest") |
| 142 | elif ret == image.VerifyResult.INVALID_SIGNATURE: |
| 143 | print("No signature found for the given key") |
Christian Skubich | f13db12 | 2019-07-31 11:34:15 +0200 | [diff] [blame] | 144 | else: |
| 145 | print("Unknown return code: {}".format(ret)) |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 146 | sys.exit(1) |
| 147 | |
| 148 | |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 149 | def validate_version(ctx, param, value): |
| 150 | try: |
| 151 | decode_version(value) |
| 152 | return value |
| 153 | except ValueError as e: |
| 154 | raise click.BadParameter("{}".format(e)) |
| 155 | |
| 156 | |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 157 | def validate_security_counter(ctx, param, value): |
| 158 | if value is not None: |
| 159 | if value.lower() == 'auto': |
| 160 | return 'auto' |
| 161 | else: |
| 162 | try: |
| 163 | return int(value, 0) |
| 164 | except ValueError: |
| 165 | raise click.BadParameter( |
| 166 | "{} is not a valid integer. Please use code literals " |
| 167 | "prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary." |
| 168 | .format(value)) |
| 169 | |
| 170 | |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 171 | def validate_header_size(ctx, param, value): |
| 172 | min_hdr_size = image.IMAGE_HEADER_SIZE |
| 173 | if value < min_hdr_size: |
| 174 | raise click.BadParameter( |
| 175 | "Minimum value for -H/--header-size is {}".format(min_hdr_size)) |
| 176 | return value |
| 177 | |
| 178 | |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 179 | def get_dependencies(ctx, param, value): |
| 180 | if value is not None: |
| 181 | versions = [] |
| 182 | images = re.findall(r"\((\d+)", value) |
| 183 | if len(images) == 0: |
| 184 | raise click.BadParameter( |
| 185 | "Image dependency format is invalid: {}".format(value)) |
| 186 | raw_versions = re.findall(r",\s*([0-9.+]+)\)", value) |
| 187 | if len(images) != len(raw_versions): |
| 188 | raise click.BadParameter( |
| 189 | '''There's a mismatch between the number of dependency images |
| 190 | and versions in: {}'''.format(value)) |
| 191 | for raw_version in raw_versions: |
| 192 | try: |
| 193 | versions.append(decode_version(raw_version)) |
| 194 | except ValueError as e: |
| 195 | raise click.BadParameter("{}".format(e)) |
| 196 | dependencies = dict() |
| 197 | dependencies[image.DEP_IMAGES_KEY] = images |
| 198 | dependencies[image.DEP_VERSIONS_KEY] = versions |
| 199 | return dependencies |
| 200 | |
| 201 | |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 202 | class BasedIntParamType(click.ParamType): |
| 203 | name = 'integer' |
| 204 | |
| 205 | def convert(self, value, param, ctx): |
| 206 | try: |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 207 | return int(value, 0) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 208 | except ValueError: |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 209 | self.fail('%s is not a valid integer. Please use code literals ' |
| 210 | 'prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary.' |
| 211 | % value, param, ctx) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 212 | |
| 213 | |
| 214 | @click.argument('outfile') |
| 215 | @click.argument('infile') |
Fabio Utzig | 9117fde | 2019-10-17 11:11:46 -0300 | [diff] [blame] | 216 | @click.option('-R', '--erased-val', type=click.Choice(['0', '0xff']), |
| 217 | required=False, |
| 218 | help='The value that is read back from erased flash.') |
Fabio Utzig | edbabcf | 2019-10-11 13:03:37 -0300 | [diff] [blame] | 219 | @click.option('-x', '--hex-addr', type=BasedIntParamType(), required=False, |
| 220 | help='Adjust address in hex output file.') |
Håkon Øye Amundsen | df8c891 | 2019-08-26 12:15:28 +0000 | [diff] [blame] | 221 | @click.option('-L', '--load-addr', type=BasedIntParamType(), required=False, |
| 222 | help='Load address for image when it is in its primary slot.') |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 223 | @click.option('--save-enctlv', default=False, is_flag=True, |
| 224 | help='When upgrading, save encrypted key TLVs instead of plain ' |
| 225 | 'keys. Enable when BOOT_SWAP_SAVE_ENCTLV config option ' |
| 226 | 'was set.') |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 227 | @click.option('-E', '--encrypt', metavar='filename', |
| 228 | help='Encrypt image using the provided public key') |
| 229 | @click.option('-e', '--endian', type=click.Choice(['little', 'big']), |
| 230 | default='little', help="Select little or big endian") |
| 231 | @click.option('--overwrite-only', default=False, is_flag=True, |
| 232 | help='Use overwrite-only instead of swap upgrades') |
| 233 | @click.option('-M', '--max-sectors', type=int, |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 234 | help='When padding allow for this amount of sectors (defaults ' |
| 235 | 'to 128)') |
Henrik Brix Andersen | 0ce958e | 2020-03-11 14:04:11 +0100 | [diff] [blame^] | 236 | @click.option('--confirm', default=False, is_flag=True, |
| 237 | help='When padding the image, mark it as confirmed') |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 238 | @click.option('--pad', default=False, is_flag=True, |
| 239 | help='Pad image to --slot-size bytes, adding trailer magic') |
| 240 | @click.option('-S', '--slot-size', type=BasedIntParamType(), required=True, |
| 241 | help='Size of the slot where the image will be written') |
| 242 | @click.option('--pad-header', default=False, is_flag=True, |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 243 | help='Add --header-size zeroed bytes at the beginning of the ' |
| 244 | 'image') |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 245 | @click.option('-H', '--header-size', callback=validate_header_size, |
| 246 | type=BasedIntParamType(), required=True) |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 247 | @click.option('-d', '--dependencies', callback=get_dependencies, |
| 248 | required=False, help='''Add dependence on another image, format: |
| 249 | "(<image_ID>,<image_version>), ... "''') |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 250 | @click.option('-s', '--security-counter', callback=validate_security_counter, |
| 251 | help='Specify the value of security counter. Use the `auto` ' |
| 252 | 'keyword to automatically generate it from the image version.') |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 253 | @click.option('-v', '--version', callback=validate_version, required=True) |
| 254 | @click.option('--align', type=click.Choice(['1', '2', '4', '8']), |
| 255 | required=True) |
| 256 | @click.option('-k', '--key', metavar='filename') |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 257 | @click.command(help='''Create a signed or unsigned image\n |
| 258 | INFILE and OUTFILE are parsed as Intel HEX if the params have |
Håkon Øye Amundsen | df8c891 | 2019-08-26 12:15:28 +0000 | [diff] [blame] | 259 | .hex extension, otherwise binary format is used''') |
Henrik Brix Andersen | 0ce958e | 2020-03-11 14:04:11 +0100 | [diff] [blame^] | 260 | def sign(key, align, version, header_size, pad_header, slot_size, pad, confirm, |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 261 | max_sectors, overwrite_only, endian, encrypt, infile, outfile, |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 262 | dependencies, load_addr, hex_addr, erased_val, save_enctlv, |
| 263 | security_counter): |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 264 | img = image.Image(version=decode_version(version), header_size=header_size, |
Henrik Brix Andersen | 0ce958e | 2020-03-11 14:04:11 +0100 | [diff] [blame^] | 265 | pad_header=pad_header, pad=pad, confirm=confirm, |
| 266 | align=int(align), slot_size=slot_size, |
| 267 | max_sectors=max_sectors, overwrite_only=overwrite_only, |
| 268 | endian=endian, load_addr=load_addr, erased_val=erased_val, |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 269 | save_enctlv=save_enctlv, |
| 270 | security_counter=security_counter) |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 271 | img.load(infile) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 272 | key = load_key(key) if key else None |
| 273 | enckey = load_key(encrypt) if encrypt else None |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 274 | if enckey and key: |
| 275 | if ((isinstance(key, keys.ECDSA256P1) and |
| 276 | not isinstance(enckey, keys.ECDSA256P1Public)) |
| 277 | or (isinstance(key, keys.RSA) and |
| 278 | not isinstance(enckey, keys.RSAPublic))): |
| 279 | # FIXME |
Fabio Utzig | 1f50892 | 2020-01-15 11:37:51 -0300 | [diff] [blame] | 280 | raise click.UsageError("Signing and encryption must use the same " |
| 281 | "type of key") |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 282 | img.create(key, enckey, dependencies) |
Fabio Utzig | edbabcf | 2019-10-11 13:03:37 -0300 | [diff] [blame] | 283 | img.save(outfile, hex_addr) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 284 | |
| 285 | |
| 286 | class AliasesGroup(click.Group): |
| 287 | |
| 288 | _aliases = { |
| 289 | "create": "sign", |
| 290 | } |
| 291 | |
| 292 | def list_commands(self, ctx): |
| 293 | cmds = [k for k in self.commands] |
| 294 | aliases = [k for k in self._aliases] |
| 295 | return sorted(cmds + aliases) |
| 296 | |
| 297 | def get_command(self, ctx, cmd_name): |
| 298 | rv = click.Group.get_command(self, ctx, cmd_name) |
| 299 | if rv is not None: |
| 300 | return rv |
| 301 | if cmd_name in self._aliases: |
| 302 | return click.Group.get_command(self, ctx, self._aliases[cmd_name]) |
| 303 | return None |
| 304 | |
| 305 | |
Fabio Utzig | 25c6a15 | 2019-09-10 12:52:26 -0300 | [diff] [blame] | 306 | @click.command(help='Print imgtool version information') |
| 307 | def version(): |
| 308 | print(imgtool_version) |
| 309 | |
| 310 | |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 311 | @click.command(cls=AliasesGroup, |
| 312 | context_settings=dict(help_option_names=['-h', '--help'])) |
| 313 | def imgtool(): |
| 314 | pass |
| 315 | |
| 316 | |
| 317 | imgtool.add_command(keygen) |
| 318 | imgtool.add_command(getpub) |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 319 | imgtool.add_command(getpriv) |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 320 | imgtool.add_command(verify) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 321 | imgtool.add_command(sign) |
Fabio Utzig | 25c6a15 | 2019-09-10 12:52:26 -0300 | [diff] [blame] | 322 | imgtool.add_command(version) |
Fabio Utzig | e89841d | 2018-12-21 11:19:06 -0200 | [diff] [blame] | 323 | |
| 324 | |
| 325 | if __name__ == '__main__': |
| 326 | imgtool() |