blob: cb204b0efc2e1880e545f2e96d3e9822b57c300a [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
22from imgtool import image
23from imgtool.version import decode_version
24
25
26def gen_rsa2048(keyfile, passwd):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030027 keys.RSA.generate().export_private(path=keyfile, passwd=passwd)
28
29
30def gen_rsa3072(keyfile, passwd):
31 keys.RSA.generate(key_size=3072).export_private(path=keyfile,
32 passwd=passwd)
Fabio Utzige89841d2018-12-21 11:19:06 -020033
34
35def gen_ecdsa_p256(keyfile, passwd):
36 keys.ECDSA256P1.generate().export_private(keyfile, passwd=passwd)
37
38
39def gen_ecdsa_p224(keyfile, passwd):
40 print("TODO: p-224 not yet implemented")
41
42
43valid_langs = ['c', 'rust']
44keygens = {
45 'rsa-2048': gen_rsa2048,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030046 'rsa-3072': gen_rsa3072,
Fabio Utzige89841d2018-12-21 11:19:06 -020047 'ecdsa-p256': gen_ecdsa_p256,
48 'ecdsa-p224': gen_ecdsa_p224,
49}
50
51
52def load_key(keyfile):
53 # TODO: better handling of invalid pass-phrase
54 key = keys.load(keyfile)
55 if key is not None:
56 return key
57 passwd = getpass.getpass("Enter key passphrase: ").encode('utf-8')
58 return keys.load(keyfile, passwd)
59
60
61def get_password():
62 while True:
63 passwd = getpass.getpass("Enter key passphrase: ")
64 passwd2 = getpass.getpass("Reenter passphrase: ")
65 if passwd == passwd2:
66 break
67 print("Passwords do not match, try again")
68
69 # Password must be bytes, always use UTF-8 for consistent
70 # encoding.
71 return passwd.encode('utf-8')
72
73
74@click.option('-p', '--password', is_flag=True,
75 help='Prompt for password to protect key')
76@click.option('-t', '--type', metavar='type', required=True,
77 type=click.Choice(keygens.keys()))
78@click.option('-k', '--key', metavar='filename', required=True)
79@click.command(help='Generate pub/private keypair')
80def keygen(type, key, password):
81 password = get_password() if password else None
82 keygens[type](key, password)
83
84
85@click.option('-l', '--lang', metavar='lang', default=valid_langs[0],
86 type=click.Choice(valid_langs))
87@click.option('-k', '--key', metavar='filename', required=True)
88@click.command(help='Get public key from keypair')
89def getpub(key, lang):
90 key = load_key(key)
91 if key is None:
92 print("Invalid passphrase")
93 elif lang == 'c':
94 key.emit_c()
95 elif lang == 'rust':
96 key.emit_rust()
97 else:
98 raise ValueError("BUG: should never get here!")
99
100
101def validate_version(ctx, param, value):
102 try:
103 decode_version(value)
104 return value
105 except ValueError as e:
106 raise click.BadParameter("{}".format(e))
107
108
109def validate_header_size(ctx, param, value):
110 min_hdr_size = image.IMAGE_HEADER_SIZE
111 if value < min_hdr_size:
112 raise click.BadParameter(
113 "Minimum value for -H/--header-size is {}".format(min_hdr_size))
114 return value
115
116
David Vinczeda8c9192019-03-26 17:17:41 +0100117def get_dependencies(ctx, param, value):
118 if value is not None:
119 versions = []
120 images = re.findall(r"\((\d+)", value)
121 if len(images) == 0:
122 raise click.BadParameter(
123 "Image dependency format is invalid: {}".format(value))
124 raw_versions = re.findall(r",\s*([0-9.+]+)\)", value)
125 if len(images) != len(raw_versions):
126 raise click.BadParameter(
127 '''There's a mismatch between the number of dependency images
128 and versions in: {}'''.format(value))
129 for raw_version in raw_versions:
130 try:
131 versions.append(decode_version(raw_version))
132 except ValueError as e:
133 raise click.BadParameter("{}".format(e))
134 dependencies = dict()
135 dependencies[image.DEP_IMAGES_KEY] = images
136 dependencies[image.DEP_VERSIONS_KEY] = versions
137 return dependencies
138
139
Fabio Utzige89841d2018-12-21 11:19:06 -0200140class BasedIntParamType(click.ParamType):
141 name = 'integer'
142
143 def convert(self, value, param, ctx):
144 try:
145 if value[:2].lower() == '0x':
146 return int(value[2:], 16)
147 elif value[:1] == '0':
148 return int(value, 8)
149 return int(value, 10)
150 except ValueError:
151 self.fail('%s is not a valid integer' % value, param, ctx)
152
153
154@click.argument('outfile')
155@click.argument('infile')
156@click.option('-E', '--encrypt', metavar='filename',
157 help='Encrypt image using the provided public key')
158@click.option('-e', '--endian', type=click.Choice(['little', 'big']),
159 default='little', help="Select little or big endian")
160@click.option('--overwrite-only', default=False, is_flag=True,
161 help='Use overwrite-only instead of swap upgrades')
162@click.option('-M', '--max-sectors', type=int,
163 help='When padding allow for this amount of sectors (defaults to 128)')
164@click.option('--pad', default=False, is_flag=True,
165 help='Pad image to --slot-size bytes, adding trailer magic')
166@click.option('-S', '--slot-size', type=BasedIntParamType(), required=True,
167 help='Size of the slot where the image will be written')
168@click.option('--pad-header', default=False, is_flag=True,
169 help='Add --header-size zeroed bytes at the beginning of the image')
170@click.option('-H', '--header-size', callback=validate_header_size,
171 type=BasedIntParamType(), required=True)
David Vinczeda8c9192019-03-26 17:17:41 +0100172@click.option('-d', '--dependencies', callback=get_dependencies,
173 required=False, help='''Add dependence on another image, format:
174 "(<image_ID>,<image_version>), ... "''')
Fabio Utzige89841d2018-12-21 11:19:06 -0200175@click.option('-v', '--version', callback=validate_version, required=True)
176@click.option('--align', type=click.Choice(['1', '2', '4', '8']),
177 required=True)
178@click.option('-k', '--key', metavar='filename')
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200179@click.command(help='''Create a signed or unsigned image\n
180 INFILE and OUTFILE are parsed as Intel HEX if the params have
181 .hex extension, othewise binary format is used''')
Fabio Utzige89841d2018-12-21 11:19:06 -0200182def sign(key, align, version, header_size, pad_header, slot_size, pad,
David Vinczeda8c9192019-03-26 17:17:41 +0100183 max_sectors, overwrite_only, endian, encrypt, infile, outfile,
184 dependencies):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200185 img = image.Image(version=decode_version(version), header_size=header_size,
186 pad_header=pad_header, pad=pad, align=int(align),
187 slot_size=slot_size, max_sectors=max_sectors,
188 overwrite_only=overwrite_only, endian=endian)
189 img.load(infile)
Fabio Utzige89841d2018-12-21 11:19:06 -0200190 key = load_key(key) if key else None
191 enckey = load_key(encrypt) if encrypt else None
192 if enckey:
Fabio Utzig19fd79a2019-05-08 18:20:39 -0300193 if not isinstance(enckey, (keys.RSA, keys.RSAPublic)):
Chris Bittnerfda937a2019-03-29 10:11:31 +0100194 raise Exception("Encryption only available with RSA key")
Fabio Utzig19fd79a2019-05-08 18:20:39 -0300195 if key and not isinstance(key, keys.RSA):
Chris Bittnerfda937a2019-03-29 10:11:31 +0100196 raise Exception("Signing only available with private RSA key")
David Vinczeda8c9192019-03-26 17:17:41 +0100197 img.create(key, enckey, dependencies)
Fabio Utzige89841d2018-12-21 11:19:06 -0200198 img.save(outfile)
199
200
201class AliasesGroup(click.Group):
202
203 _aliases = {
204 "create": "sign",
205 }
206
207 def list_commands(self, ctx):
208 cmds = [k for k in self.commands]
209 aliases = [k for k in self._aliases]
210 return sorted(cmds + aliases)
211
212 def get_command(self, ctx, cmd_name):
213 rv = click.Group.get_command(self, ctx, cmd_name)
214 if rv is not None:
215 return rv
216 if cmd_name in self._aliases:
217 return click.Group.get_command(self, ctx, self._aliases[cmd_name])
218 return None
219
220
221@click.command(cls=AliasesGroup,
222 context_settings=dict(help_option_names=['-h', '--help']))
223def imgtool():
224 pass
225
226
227imgtool.add_command(keygen)
228imgtool.add_command(getpub)
229imgtool.add_command(sign)
230
231
232if __name__ == '__main__':
233 imgtool()