blob: 0a8fe0df2d4f07da0221f8e4588e3a076ce3f75e [file] [log] [blame]
Fabio Utzige89841d2018-12-21 11:19:06 -02001#! /usr/bin/env python3
2#
3# Copyright 2017 Linaro Limited
David Vinczeda8c9192019-03-26 17:17:41 +01004# Copyright 2019 Arm Limited
Fabio Utzige89841d2018-12-21 11:19:06 -02005#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
David Vinczeda8c9192019-03-26 17:17:41 +010018import re
Fabio Utzige89841d2018-12-21 11:19:06 -020019import click
20import getpass
21import imgtool.keys as keys
Fabio Utzig4a5477a2019-05-27 15:45:08 -030022import sys
Fabio Utzige89841d2018-12-21 11:19:06 -020023from imgtool import image
24from imgtool.version import decode_version
25
26
27def gen_rsa2048(keyfile, passwd):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030028 keys.RSA.generate().export_private(path=keyfile, passwd=passwd)
29
30
31def gen_rsa3072(keyfile, passwd):
32 keys.RSA.generate(key_size=3072).export_private(path=keyfile,
33 passwd=passwd)
Fabio Utzige89841d2018-12-21 11:19:06 -020034
35
36def gen_ecdsa_p256(keyfile, passwd):
37 keys.ECDSA256P1.generate().export_private(keyfile, passwd=passwd)
38
39
40def gen_ecdsa_p224(keyfile, passwd):
41 print("TODO: p-224 not yet implemented")
42
43
Fabio Utzig8101d1f2019-05-09 15:03:22 -030044def gen_ed25519(keyfile, passwd):
45 keys.Ed25519.generate().export_private(path=keyfile)
46
47
Fabio Utzige89841d2018-12-21 11:19:06 -020048valid_langs = ['c', 'rust']
49keygens = {
50 'rsa-2048': gen_rsa2048,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030051 'rsa-3072': gen_rsa3072,
Fabio Utzige89841d2018-12-21 11:19:06 -020052 'ecdsa-p256': gen_ecdsa_p256,
53 'ecdsa-p224': gen_ecdsa_p224,
Fabio Utzig8101d1f2019-05-09 15:03:22 -030054 'ed25519': gen_ed25519,
Fabio Utzige89841d2018-12-21 11:19:06 -020055}
56
57
58def load_key(keyfile):
59 # TODO: better handling of invalid pass-phrase
60 key = keys.load(keyfile)
61 if key is not None:
62 return key
63 passwd = getpass.getpass("Enter key passphrase: ").encode('utf-8')
64 return keys.load(keyfile, passwd)
65
66
67def get_password():
68 while True:
69 passwd = getpass.getpass("Enter key passphrase: ")
70 passwd2 = getpass.getpass("Reenter passphrase: ")
71 if passwd == passwd2:
72 break
73 print("Passwords do not match, try again")
74
75 # Password must be bytes, always use UTF-8 for consistent
76 # encoding.
77 return passwd.encode('utf-8')
78
79
80@click.option('-p', '--password', is_flag=True,
81 help='Prompt for password to protect key')
82@click.option('-t', '--type', metavar='type', required=True,
83 type=click.Choice(keygens.keys()))
84@click.option('-k', '--key', metavar='filename', required=True)
85@click.command(help='Generate pub/private keypair')
86def keygen(type, key, password):
87 password = get_password() if password else None
88 keygens[type](key, password)
89
90
91@click.option('-l', '--lang', metavar='lang', default=valid_langs[0],
92 type=click.Choice(valid_langs))
93@click.option('-k', '--key', metavar='filename', required=True)
94@click.command(help='Get public key from keypair')
95def getpub(key, lang):
96 key = load_key(key)
97 if key is None:
98 print("Invalid passphrase")
99 elif lang == 'c':
100 key.emit_c()
101 elif lang == 'rust':
102 key.emit_rust()
103 else:
104 raise ValueError("BUG: should never get here!")
105
106
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300107@click.argument('imgfile')
108@click.option('-k', '--key', metavar='filename')
109@click.command(help="Check that signed image can be verified by given key")
110def verify(key, imgfile):
111 key = load_key(key) if key else None
112 ret = image.Image.verify(imgfile, key)
113 if ret == image.VerifyResult.OK:
114 print("Image was correctly validated")
115 return
116 elif ret == image.VerifyResult.INVALID_MAGIC:
117 print("Invalid image magic; is this an MCUboot image?")
118 elif ret == image.VerifyResult.INVALID_MAGIC:
119 print("Invalid TLV info magic; is this an MCUboot image?")
120 elif ret == image.VerifyResult.INVALID_HASH:
121 print("Image has an invalid sha256 digest")
122 elif ret == image.VerifyResult.INVALID_SIGNATURE:
123 print("No signature found for the given key")
124 sys.exit(1)
125
126
Fabio Utzige89841d2018-12-21 11:19:06 -0200127def validate_version(ctx, param, value):
128 try:
129 decode_version(value)
130 return value
131 except ValueError as e:
132 raise click.BadParameter("{}".format(e))
133
134
135def validate_header_size(ctx, param, value):
136 min_hdr_size = image.IMAGE_HEADER_SIZE
137 if value < min_hdr_size:
138 raise click.BadParameter(
139 "Minimum value for -H/--header-size is {}".format(min_hdr_size))
140 return value
141
142
David Vinczeda8c9192019-03-26 17:17:41 +0100143def get_dependencies(ctx, param, value):
144 if value is not None:
145 versions = []
146 images = re.findall(r"\((\d+)", value)
147 if len(images) == 0:
148 raise click.BadParameter(
149 "Image dependency format is invalid: {}".format(value))
150 raw_versions = re.findall(r",\s*([0-9.+]+)\)", value)
151 if len(images) != len(raw_versions):
152 raise click.BadParameter(
153 '''There's a mismatch between the number of dependency images
154 and versions in: {}'''.format(value))
155 for raw_version in raw_versions:
156 try:
157 versions.append(decode_version(raw_version))
158 except ValueError as e:
159 raise click.BadParameter("{}".format(e))
160 dependencies = dict()
161 dependencies[image.DEP_IMAGES_KEY] = images
162 dependencies[image.DEP_VERSIONS_KEY] = versions
163 return dependencies
164
165
Fabio Utzige89841d2018-12-21 11:19:06 -0200166class BasedIntParamType(click.ParamType):
167 name = 'integer'
168
169 def convert(self, value, param, ctx):
170 try:
171 if value[:2].lower() == '0x':
172 return int(value[2:], 16)
173 elif value[:1] == '0':
174 return int(value, 8)
175 return int(value, 10)
176 except ValueError:
177 self.fail('%s is not a valid integer' % value, param, ctx)
178
179
180@click.argument('outfile')
181@click.argument('infile')
182@click.option('-E', '--encrypt', metavar='filename',
183 help='Encrypt image using the provided public key')
184@click.option('-e', '--endian', type=click.Choice(['little', 'big']),
185 default='little', help="Select little or big endian")
186@click.option('--overwrite-only', default=False, is_flag=True,
187 help='Use overwrite-only instead of swap upgrades')
188@click.option('-M', '--max-sectors', type=int,
189 help='When padding allow for this amount of sectors (defaults to 128)')
190@click.option('--pad', default=False, is_flag=True,
191 help='Pad image to --slot-size bytes, adding trailer magic')
192@click.option('-S', '--slot-size', type=BasedIntParamType(), required=True,
193 help='Size of the slot where the image will be written')
194@click.option('--pad-header', default=False, is_flag=True,
195 help='Add --header-size zeroed bytes at the beginning of the image')
196@click.option('-H', '--header-size', callback=validate_header_size,
197 type=BasedIntParamType(), required=True)
David Vinczeda8c9192019-03-26 17:17:41 +0100198@click.option('-d', '--dependencies', callback=get_dependencies,
199 required=False, help='''Add dependence on another image, format:
200 "(<image_ID>,<image_version>), ... "''')
Fabio Utzige89841d2018-12-21 11:19:06 -0200201@click.option('-v', '--version', callback=validate_version, required=True)
202@click.option('--align', type=click.Choice(['1', '2', '4', '8']),
203 required=True)
204@click.option('-k', '--key', metavar='filename')
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200205@click.command(help='''Create a signed or unsigned image\n
206 INFILE and OUTFILE are parsed as Intel HEX if the params have
207 .hex extension, othewise binary format is used''')
Fabio Utzige89841d2018-12-21 11:19:06 -0200208def sign(key, align, version, header_size, pad_header, slot_size, pad,
David Vinczeda8c9192019-03-26 17:17:41 +0100209 max_sectors, overwrite_only, endian, encrypt, infile, outfile,
210 dependencies):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200211 img = image.Image(version=decode_version(version), header_size=header_size,
212 pad_header=pad_header, pad=pad, align=int(align),
213 slot_size=slot_size, max_sectors=max_sectors,
214 overwrite_only=overwrite_only, endian=endian)
215 img.load(infile)
Fabio Utzige89841d2018-12-21 11:19:06 -0200216 key = load_key(key) if key else None
217 enckey = load_key(encrypt) if encrypt else None
218 if enckey:
Fabio Utzig19fd79a2019-05-08 18:20:39 -0300219 if not isinstance(enckey, (keys.RSA, keys.RSAPublic)):
Chris Bittnerfda937a2019-03-29 10:11:31 +0100220 raise Exception("Encryption only available with RSA key")
Fabio Utzig19fd79a2019-05-08 18:20:39 -0300221 if key and not isinstance(key, keys.RSA):
Chris Bittnerfda937a2019-03-29 10:11:31 +0100222 raise Exception("Signing only available with private RSA key")
David Vinczeda8c9192019-03-26 17:17:41 +0100223 img.create(key, enckey, dependencies)
Fabio Utzige89841d2018-12-21 11:19:06 -0200224 img.save(outfile)
225
226
227class AliasesGroup(click.Group):
228
229 _aliases = {
230 "create": "sign",
231 }
232
233 def list_commands(self, ctx):
234 cmds = [k for k in self.commands]
235 aliases = [k for k in self._aliases]
236 return sorted(cmds + aliases)
237
238 def get_command(self, ctx, cmd_name):
239 rv = click.Group.get_command(self, ctx, cmd_name)
240 if rv is not None:
241 return rv
242 if cmd_name in self._aliases:
243 return click.Group.get_command(self, ctx, self._aliases[cmd_name])
244 return None
245
246
247@click.command(cls=AliasesGroup,
248 context_settings=dict(help_option_names=['-h', '--help']))
249def imgtool():
250 pass
251
252
253imgtool.add_command(keygen)
254imgtool.add_command(getpub)
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300255imgtool.add_command(verify)
Fabio Utzige89841d2018-12-21 11:19:06 -0200256imgtool.add_command(sign)
257
258
259if __name__ == '__main__':
260 imgtool()