-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·736 lines (648 loc) · 31.8 KB
/
Copy pathmain.py
File metadata and controls
executable file
·736 lines (648 loc) · 31.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
#! /usr/bin/env python3
#
# Copyright 2017-2020 Linaro Limited
# Copyright 2019-2023 Arm Limited
#
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import getpass
import lzma
import re
import struct
import sys
from pathlib import Path
import click
import imgtool.keys as keys
from imgtool import image, imgtool_version
from imgtool.dumpinfo import dump_imginfo
from imgtool.version import decode_version
from .keys import ECDSAUsageError, Ed25519UsageError, RSAUsageError, X25519UsageError
MIN_PYTHON_VERSION = (3, 6)
if sys.version_info < MIN_PYTHON_VERSION:
sys.exit("Python {}.{} or newer is required by imgtool.".format(*MIN_PYTHON_VERSION))
def gen_rsa2048(keyfile, passwd):
keys.RSA.generate().export_private(path=keyfile, passwd=passwd)
def gen_rsa3072(keyfile, passwd):
keys.RSA.generate(key_size=3072).export_private(path=keyfile,
passwd=passwd)
def gen_ecdsa_p256(keyfile, passwd):
keys.ECDSA256P1.generate().export_private(keyfile, passwd=passwd)
def gen_ecdsa_p384(keyfile, passwd):
keys.ECDSA384P1.generate().export_private(keyfile, passwd=passwd)
def gen_ed25519(keyfile, passwd):
keys.Ed25519.generate().export_private(path=keyfile, passwd=passwd)
def gen_x25519(keyfile, passwd):
keys.X25519.generate().export_private(path=keyfile, passwd=passwd)
valid_langs = ['c', 'rust']
valid_hash_encodings = ['lang-c', 'raw']
valid_encodings = ['lang-c', 'lang-rust', 'pem', 'raw']
def _validate_name_suffix(ctx: click.Context, param: click.Parameter, value: str) -> str:
if value and not re.match(r"^[A-Za-z0-9_]*$", value):
raise click.BadParameter(
f"{value!r} must contain only [A-Za-z0-9_]; it is appended "
f"directly to a C/Rust identifier."
)
return value
keygens = {
'rsa-2048': gen_rsa2048,
'rsa-3072': gen_rsa3072,
'ecdsa-p256': gen_ecdsa_p256,
'ecdsa-p384': gen_ecdsa_p384,
'ed25519': gen_ed25519,
'x25519': gen_x25519,
}
valid_formats = ['openssl', 'pkcs8']
valid_sha = [ 'auto', '256', '384', '512' ]
valid_hmac_sha = [ 'auto', '256', '512' ]
def load_signature(sigfile):
with open(sigfile, 'rb') as f:
signature = base64.b64decode(f.read())
return signature
def save_signature(sigfile, sig):
with open(sigfile, 'wb') as f:
signature = base64.b64encode(sig)
f.write(signature)
def load_key(keyfile):
# TODO: better handling of invalid pass-phrase
key = keys.load(keyfile)
if key is not None:
return key
passwd = getpass.getpass("Enter key passphrase: ").encode('utf-8')
return keys.load(keyfile, passwd)
def get_password():
while True:
passwd = getpass.getpass("Enter key passphrase: ")
passwd2 = getpass.getpass("Reenter passphrase: ")
if passwd == passwd2:
break
print("Passwords do not match, try again")
# Password must be bytes, always use UTF-8 for consistent
# encoding.
return passwd.encode('utf-8')
@click.option('-p', '--password', is_flag=True,
help='Prompt for password to protect key')
@click.option('-t', '--type', metavar='type', required=True,
type=click.Choice(keygens.keys()), prompt=True,
help='{}'.format('One of: {}'.format(', '.join(keygens.keys()))))
@click.option('-k', '--key', metavar='filename', required=True)
@click.command(help='Generate pub/private keypair')
def keygen(type, key, password):
password = get_password() if password else None
keygens[type](key, password)
@click.option('-l', '--lang', metavar='lang',
type=click.Choice(valid_langs),
help='This option is deprecated. Please use the '
'`--encoding` option. '
'Valid langs: {}'.format(', '.join(valid_langs)))
@click.option('-e', '--encoding', metavar='encoding',
type=click.Choice(valid_encodings),
help='Valid encodings: {}'.format(', '.join(valid_encodings)))
@click.option('--name-suffix', 'name_suffix', metavar='SUFFIX', default='',
callback=_validate_name_suffix,
help='Append SUFFIX to the emitted C/Rust symbol names '
'(e.g. `--name-suffix _2` emits `rsa_pub_key_2` / '
'`rsa_pub_key_2_len`). Useful when embedding multiple '
'signing keys in the same image. Rejected for PEM/raw '
'encodings (those emit no identifiers).')
@click.option('-k', '--key', metavar='filename', required=True)
@click.option('-o', '--output', metavar='output', required=False,
help='Specify the output file\'s name. \
The stdout is used if it is not provided.')
@click.command(help='Dump public key from keypair')
def getpub(key, encoding, lang, output, name_suffix):
if encoding and lang:
raise click.UsageError('Please use only one of `--encoding/-e` '
'or `--lang/-l`')
elif not encoding and not lang:
# Preserve old behavior defaulting to `c`. If `lang` is removed,
# `default=valid_encodings[0]` should be added to `-e` param.
lang = valid_langs[0]
if name_suffix and (encoding in ('pem', 'raw')):
raise click.UsageError(
'`--name-suffix` is only meaningful for lang-c / lang-rust encodings')
key = load_key(key)
if not output:
output = sys.stdout
if key is None:
print("Invalid passphrase")
elif lang == 'c' or encoding == 'lang-c':
key.emit_c_public(file=output, name_suffix=name_suffix)
elif lang == 'rust' or encoding == 'lang-rust':
key.emit_rust_public(file=output, name_suffix=name_suffix)
elif encoding == 'pem':
key.emit_public_pem(file=output)
elif encoding == 'raw':
key.emit_raw_public(file=output)
else:
raise click.UsageError()
@click.option('-e', '--encoding', metavar='encoding',
type=click.Choice(valid_hash_encodings),
help='Valid encodings: {}. '
'Default value is {}.'
.format(', '.join(valid_hash_encodings),
valid_hash_encodings[0]))
@click.option('--name-suffix', 'name_suffix', metavar='SUFFIX', default='',
callback=_validate_name_suffix,
help='Append SUFFIX to the emitted C symbol names (lang-c '
'encoding only). Rejected for raw encoding.')
@click.option('-k', '--key', metavar='filename', required=True)
@click.option('-o', '--output', metavar='output', required=False,
help='Specify the output file\'s name. \
The stdout is used if it is not provided.')
@click.command(help='Dump the SHA256 hash of the public key')
def getpubhash(key, output, encoding, name_suffix):
if not encoding:
encoding = valid_hash_encodings[0]
if name_suffix and encoding == 'raw':
raise click.UsageError(
'`--name-suffix` is only meaningful for the lang-c encoding')
key = load_key(key)
if not output:
output = sys.stdout
if key is None:
print("Invalid passphrase")
elif encoding == 'lang-c':
key.emit_c_public_hash(file=output, name_suffix=name_suffix)
elif encoding == 'raw':
key.emit_raw_public_hash(file=output)
else:
raise click.UsageError()
@click.option('--require', 'require', type=click.Choice(['private', 'public']),
default=None,
help='Exit non-zero if the key kind does not match REQUIRE. '
'Without this option, keyinfo always exits 0 and prints '
'the detected kind on stdout.')
@click.option('-k', '--key', metavar='filename', required=True)
@click.command(help='Print whether KEY is a keypair PEM (`private`) or a '
'public-only PEM (`public`). Intended for build-system '
'use: pair with `--require` to gate the build on the '
'expected key kind.')
def keyinfo(key, require):
loaded = keys.load(key)
if loaded is None:
raise click.UsageError(
f"Cannot inspect {key}: key is password-protected or unreadable. "
f"keyinfo runs non-interactively and does not prompt for a "
f"passphrase."
)
key_obj = getattr(loaded, "key", None)
kind = "private" if (key_obj is not None and hasattr(key_obj, "private_bytes")) else "public"
click.echo(kind)
if require is not None and kind != require:
raise click.UsageError(
f"Key {key} is {kind}, but {require} was required."
)
@click.option('--minimal', default=False, is_flag=True,
help='Reduce the size of the dumped private key to include only '
'the minimum amount of data required to decrypt. This '
'might require changes to the build config. Check the docs!'
)
@click.option('-k', '--key', metavar='filename', required=True)
@click.option('-f', '--format',
type=click.Choice(valid_formats),
help='Valid formats: {}'.format(', '.join(valid_formats))
)
@click.command(help='Dump private key from keypair')
def getpriv(key, minimal, format):
key = load_key(key)
if key is None:
print("Invalid passphrase")
try:
key.emit_private(minimal, format)
except (RSAUsageError, ECDSAUsageError, Ed25519UsageError,
X25519UsageError) as e:
raise click.UsageError(e)
@click.argument('imgfile')
@click.option('-k', '--key', metavar='filename')
@click.command(help="Check that signed image can be verified by given key")
def verify(key, imgfile):
key = load_key(key) if key else None
ret, version, digest, signature = image.Image.verify(imgfile, key)
if ret == image.VerifyResult.OK:
print("Image was correctly validated")
print("Image version: {}.{}.{}+{}".format(*version))
if digest:
print(f"Image digest: {digest.hex()}")
if signature and digest is None:
print(f"Image signature over image: {signature.hex()}")
return
elif ret == image.VerifyResult.INVALID_MAGIC:
print("Invalid image magic; is this an MCUboot image?")
elif ret == image.VerifyResult.INVALID_TLV_INFO_MAGIC:
print("Invalid TLV info magic; is this an MCUboot image?")
elif ret == image.VerifyResult.INVALID_HASH:
print("Image has an invalid hash")
elif ret == image.VerifyResult.INVALID_SIGNATURE:
print("No signature found for the given key")
elif ret == image.VerifyResult.KEY_MISMATCH:
print("Key type does not match TLV record")
else:
print(f"Unknown return code: {ret}")
sys.exit(1)
@click.argument('imgfile')
@click.option('-o', '--outfile', metavar='filename', required=False,
help='Save image information to outfile in YAML format')
@click.option('-s', '--silent', default=False, is_flag=True,
help='Do not print image information to output')
@click.command(help='Print header, TLV area and trailer information '
'of a signed image')
def dumpinfo(imgfile, outfile, silent):
dump_imginfo(imgfile, outfile, silent)
if not silent:
print("dumpinfo has run successfully")
def validate_version(ctx, param, value):
try:
decode_version(value)
return value
except ValueError as e:
raise click.BadParameter(f"{e}")
def validate_security_counter(ctx, param, value):
if value is not None:
if value.lower() == 'auto':
return 'auto'
else:
try:
return int(value, 0)
except ValueError:
raise click.BadParameter(
f"{value} is not a valid integer. Please use code literals "
"prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary."
)
def validate_header_size(ctx, param, value):
min_hdr_size = image.IMAGE_HEADER_SIZE
if value.lower() == 'auto':
return min_hdr_size
if isinstance(value, int):
converted = value
else:
try:
converted = int(value, 0)
except ValueError:
raise click.BadParameter(
f"{value} is not a valid integer. Please use code literals "
"prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary."
)
if converted < min_hdr_size:
raise click.BadParameter(
f"Minimum value for -H/--header-size is {min_hdr_size}")
return converted
def get_dependencies(ctx, param, value):
if value is not None:
versions = []
images = re.findall(r"\((\d+)", value)
if len(images) == 0:
raise click.BadParameter(
f"Image dependency format is invalid: {value}")
raw_versions = re.findall(r",\s*([0-9.+]+)\)", value)
if len(images) != len(raw_versions):
raise click.BadParameter(
f'''There's a mismatch between the number of dependency images
and versions in: {value}''')
for raw_version in raw_versions:
try:
versions.append(decode_version(raw_version))
except ValueError as e:
raise click.BadParameter(f"{e}")
dependencies = dict()
dependencies[image.DEP_IMAGES_KEY] = images
dependencies[image.DEP_VERSIONS_KEY] = versions
return dependencies
def create_lzma2_header(dictsize, pb, lc, lp):
header = bytearray()
for i in range(0, 40):
if dictsize <= ((2 | ((i) & 1)) << int((i) / 2 + 11)):
header.append(i)
break
header.append( ( pb * 5 + lp) * 9 + lc)
return header
class BasedIntParamType(click.ParamType):
name = 'integer'
def convert(self, value, param, ctx):
try:
return int(value, 0)
except ValueError:
self.fail(f'{value} is not a valid integer. Please use code literals '
'prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary.', param, ctx)
@click.argument('outfile')
@click.argument('infile')
@click.option('--non-bootable', default=False, is_flag=True,
help='Mark the image as non-bootable.')
@click.option('--custom-tlv', required=False, nargs=2, default=[],
multiple=True, metavar='[tag] [value]',
help='Custom TLV that will be placed into protected area. '
'Add "0x" prefix if the value should be interpreted as an '
'integer, otherwise it will be interpreted as a string. '
'Specify the option multiple times to add multiple TLVs.')
@click.option('--custom-tlv-file', required=False, nargs=2, default=[],
multiple=True, metavar='[tag] [filename]',
help='Custom TLV that will be placed into protected area. '
'The second argument is the path to a binary file '
'containing the TLV data. Specify the option multiple '
'times to add multiple TLVs.')
@click.option('-R', '--erased-val', type=click.Choice(['0', '0xff']),
required=False,
help='The value that is read back from erased flash.')
@click.option('--pad-value', type=click.Choice(['0', '0xff']),
required=False,
help='Byte value used for header and slot padding. When set, '
'header padding is applied with this value regardless of '
'whether --pad-header is used.')
@click.option('-x', '--hex-addr', type=BasedIntParamType(), required=False,
help='Adjust address in hex output file.')
@click.option('-L', '--load-addr', type=BasedIntParamType(), required=False,
help='Load address for image when it should run from RAM.')
@click.option('-F', '--rom-fixed', type=BasedIntParamType(), required=False,
help='Set flash address the image is built for.')
@click.option('--save-enctlv', default=False, is_flag=True,
help='When upgrading, save encrypted key TLVs instead of plain '
'keys. Enable when BOOT_SWAP_SAVE_ENCTLV config option '
'was set.')
@click.option('-E', '--encrypt', metavar='filename',
help='Encrypt image using the provided public key. '
'(Not supported in direct-xip or ram-load mode.)')
@click.option('--encrypt-keylen', default='128',
type=click.Choice(['128', '256']),
help='When encrypting the image using AES, select a 128 bit or '
'256 bit key len.')
@click.option('--compression', default='disabled',
type=click.Choice(['disabled', 'lzma2', 'lzma2armthumb']),
help='Enable image compression using specified type. '
'Will fall back without image compression automatically '
'if the compression increases the image size.')
@click.option('-c', '--clear', required=False, is_flag=True, default=False,
help='Output a non-encrypted image with encryption capabilities,'
'so it can be installed in the primary slot, and encrypted '
'when swapped to the secondary.')
@click.option('-e', '--endian', type=click.Choice(['little', 'big']),
default='little', help="Select little or big endian")
@click.option('--overwrite-only', default=False, is_flag=True,
help='Use overwrite-only instead of swap upgrades')
@click.option('--boot-record', metavar='sw_type', help='Create CBOR encoded '
'boot record TLV. The sw_type represents the role of the '
'software component (e.g. CoFM for coprocessor firmware). '
'[max. 12 characters]')
@click.option('-M', '--max-sectors', type=int,
help='When padding allow for this amount of sectors (defaults '
'to 128)')
@click.option('--confirm', default=False, is_flag=True,
help='When padding the image, mark it as confirmed (implies '
'--pad)')
@click.option('--pad', default=False, is_flag=True,
help='Pad image to --slot-size bytes, adding trailer magic')
@click.option('-S', '--slot-size', type=BasedIntParamType(), required=True,
help='Size of the slot. If the slots have different sizes, use '
'the size of the secondary slot.')
@click.option('--pad-header', default=False, is_flag=True,
help='Add --header-size zeroed bytes at the beginning of the '
'image')
@click.option('-H', '--header-size', callback=validate_header_size, required=False,
default='auto',
help='Unsigned integer in hex, dec or oct format, or auto;'
' auto will use smallest possible value , rounded up to 32 bits,'
' capable of storing full header in current version. The auto'
' is preffered when no address/size requirement are needed for header,'
' and will give smallest image.')
@click.option('--pad-sig', default=False, is_flag=True,
help='Add 0-2 bytes of padding to ECDSA signature '
'(for mcuboot <1.5)')
@click.option('-d', '--dependencies', callback=get_dependencies,
required=False, help='''Add dependence on another image, format:
"(<image_ID>,<image_version>), ... "''')
@click.option('-s', '--security-counter', callback=validate_security_counter,
help='Specify the value of security counter. Use the `auto` '
'keyword to automatically generate it from the image version.')
@click.option('-v', '--version', callback=validate_version, required=True)
@click.option('--align', type=click.Choice(['1', '2', '4', '8', '16', '32']),
default='1',
required=False,
help='Alignment used by swap update modes.')
@click.option('--max-align', type=click.Choice(['8', '16', '32']),
required=False,
help='Maximum flash alignment. Set if flash alignment of the '
'primary and secondary slot differ and any of them is larger '
'than 8.')
@click.option('--public-key-format', type=click.Choice(['hash', 'full']),
default='hash', help='In what format to add the public key to '
'the image manifest: full key or hash of the key.')
@click.option('-k', '--key', metavar='filename')
@click.option('--fix-sig', metavar='filename',
help='fixed signature for the image. It will be used instead of '
'the signature calculated using the public key')
@click.option('--fix-sig-pubkey', metavar='filename',
help='public key relevant to fixed signature')
@click.option('--pure', 'is_pure', is_flag=True, default=False, show_default=True,
help='Expected Pure variant of signature; the Pure variant is '
'expected to be signature done over an image rather than hash of '
'that image.')
@click.option('--sig-out', metavar='filename',
help='Path to the file to which signature will be written. '
'The image signature will be encoded as base64 formatted string')
@click.option('--sha', 'user_sha', type=click.Choice(valid_sha), default='auto',
help='selected sha algorithm to use; defaults to "auto" which is 256 if '
'no cryptographic signature is used, or default for signature type')
@click.option('--hmac-sha', 'hmac_sha', type=click.Choice(valid_hmac_sha), default='auto',
help='sha algorithm used in HKDF/HMAC in ECIES key exchange TLV')
@click.option('--vector-to-sign', type=click.Choice(['payload', 'digest']),
help='send to OUTFILE the payload or payload''s digest instead '
'of complied image. These data can be used for external image '
'signing')
@click.command(help='''Create a signed or unsigned image\n
INFILE and OUTFILE are parsed as Intel HEX if the params have
.hex extension, otherwise binary format is used''')
@click.option('--vid', default=None, required=False,
help='Unique vendor identifier, format: (<raw_uuid>|<domain_name)>')
@click.option('--cid', default=None, required=False,
help='Unique image class identifier, format: (<raw_uuid>|<image_class_name>)')
@click.option('--edt-config', default=None, required=False,
help='Path to the pickle-encoded devicetree file with bootloader configuration.')
@click.option('--manifest', default=None, required=False,
help='Path to the update manifest file')
@click.option('--compression-lzma-dictsize', type=int, default=128*1024,
help='LZMA - dictionary size, in bytes', show_default=True)
@click.option('--compression-lzma-pb', type=int, default=2,
help='LZMA - number of position bits', show_default=True)
@click.option('--compression-lzma-lc', type=int, default=3,
help='LZMA - number of literal context bits', show_default=True)
@click.option('--compression-lzma-lp', type=int, default=1,
help='LZMA - number of literal position bits', show_default=True)
@click.option('--compression-lzma-preset', type=int, default=9,
help='LZMA - compression level preset', show_default=True)
def sign(key, public_key_format, align, version, pad_sig, header_size,
pad_header, slot_size, pad, confirm, max_sectors, overwrite_only,
endian, encrypt_keylen, encrypt, compression, infile, outfile,
dependencies, load_addr, hex_addr, erased_val, pad_value, save_enctlv,
security_counter, boot_record, custom_tlv, custom_tlv_file, rom_fixed, max_align,
clear, fix_sig, fix_sig_pubkey, sig_out, user_sha, hmac_sha, is_pure,
vector_to_sign, non_bootable, vid, cid, edt_config, manifest,
compression_lzma_dictsize, compression_lzma_pb, compression_lzma_lc, compression_lzma_lp, compression_lzma_preset):
if confirm:
# Confirmed but non-padded images don't make much sense, because
# otherwise there's no trailer area for writing the confirmed status.
pad = True
img = image.Image(version=decode_version(version), header_size=header_size,
pad_header=pad_header, pad=pad, confirm=confirm,
align=int(align), slot_size=slot_size,
max_sectors=max_sectors, overwrite_only=overwrite_only,
endian=endian, load_addr=load_addr, rom_fixed=rom_fixed,
erased_val=erased_val, pad_value=pad_value,
save_enctlv=save_enctlv,
security_counter=security_counter, max_align=max_align,
non_bootable=non_bootable, vid=vid, cid=cid,
edt_config=edt_config, manifest=manifest)
compression_tlvs = {}
img.load(infile)
key = load_key(key) if key else None
enckey = load_key(encrypt) if encrypt else None
if enckey and key and ((isinstance(key, keys.ECDSA256P1) and
not isinstance(enckey, keys.ECDSA256P1Public))
or (isinstance(key, keys.ECDSA384P1) and
not isinstance(enckey, keys.ECDSA384P1Public))
or (isinstance(key, keys.RSA) and
not isinstance(enckey, keys.RSAPublic))):
# FIXME
raise click.UsageError("Signing and encryption must use the same "
"type of key")
if pad_sig and hasattr(key, 'pad_sig'):
key.pad_sig = True
# Get list of custom protected TLVs from the command-line
custom_tlvs = {}
custom_tlv_args = list(custom_tlv) + [(tag, Path(fn)) for tag, fn in custom_tlv_file]
for tlv in custom_tlv_args:
tag = int(tlv[0], 0)
if tag in custom_tlvs:
raise click.UsageError(f'Custom TLV {hex(tag)} already exists.')
if tag in image.TLV_VALUES.values():
raise click.UsageError(
f'Custom TLV {hex(tag)} conflicts with predefined TLV.')
value = tlv[1]
if isinstance(value, Path):
with value.open("rb") as fp:
custom_tlvs[tag] = fp.read()
elif value.startswith('0x'):
if len(value[2:]) % 2:
raise click.UsageError('Custom TLV length is odd.')
custom_tlvs[tag] = bytes.fromhex(value[2:])
else:
custom_tlvs[tag] = value.encode('utf-8')
# Allow signature calculated externally.
raw_signature = load_signature(fix_sig) if fix_sig else None
baked_signature = None
pub_key = None
if raw_signature is not None:
if fix_sig_pubkey is None:
raise click.UsageError(
'public key of the fixed signature is not specified')
pub_key = load_key(fix_sig_pubkey)
baked_signature = {
'value': raw_signature
}
if is_pure and user_sha != 'auto':
raise click.UsageError(
'Pure signatures, currently, enforces preferred hash algorithm, '
'and forbids sha selection by user.')
if compression in ["lzma2", "lzma2armthumb"]:
img.create(key, public_key_format, enckey, dependencies, boot_record,
custom_tlvs, compression_tlvs, None, int(encrypt_keylen), clear,
baked_signature, pub_key, vector_to_sign, user_sha=user_sha,
hmac_sha=hmac_sha, is_pure=is_pure, keep_comp_size=False, dont_encrypt=True)
compressed_img = image.Image(version=decode_version(version),
header_size=header_size, pad_header=pad_header,
pad=pad, confirm=confirm, align=int(align),
slot_size=slot_size, max_sectors=max_sectors,
overwrite_only=overwrite_only, endian=endian,
load_addr=load_addr, rom_fixed=rom_fixed,
erased_val=erased_val, pad_value=pad_value,
save_enctlv=save_enctlv,
security_counter=security_counter, max_align=max_align,
vid=vid, cid=cid, edt_config=edt_config, manifest=manifest)
compression_filters = [
{"id": lzma.FILTER_LZMA2, "preset": compression_lzma_preset,
"dict_size": compression_lzma_dictsize, "lp": compression_lzma_lp,
"lc": compression_lzma_lc}
]
if compression == "lzma2armthumb":
compression_filters.insert(0, {"id":lzma.FILTER_ARMTHUMB})
infile_offset = 0 if pad_header else header_size
compressed_data = lzma.compress(img.get_infile_data()[infile_offset:],
filters=compression_filters, format=lzma.FORMAT_RAW)
uncompressed_size = len(img.get_infile_data()[infile_offset:])
compressed_size = len(compressed_data)
print(f"compressed image size: {compressed_size} bytes")
print(f"original image size: {uncompressed_size} bytes")
compression_tlvs["DECOMP_SIZE"] = struct.pack(
img.get_struct_endian() + 'L', img.image_size)
compression_tlvs["DECOMP_SHA"] = img.image_hash
compression_tlvs_size = len(compression_tlvs["DECOMP_SIZE"])
compression_tlvs_size += len(compression_tlvs["DECOMP_SHA"])
if img.get_signature():
compression_tlvs["DECOMP_SIGNATURE"] = img.get_signature()
compression_tlvs_size += len(compression_tlvs["DECOMP_SIGNATURE"])
if (compressed_size + compression_tlvs_size) < uncompressed_size:
compression_header = create_lzma2_header(
dictsize = compression_lzma_dictsize, pb = compression_lzma_pb,
lc = compression_lzma_lc, lp = compression_lzma_lp)
compressed_img.load_compressed(compressed_data, compression_header)
compressed_img.base_addr = img.base_addr
keep_comp_size = False
if enckey:
keep_comp_size = True
compressed_img.create(key, public_key_format, enckey,
dependencies, boot_record, custom_tlvs, compression_tlvs,
compression, int(encrypt_keylen), clear, baked_signature,
pub_key, vector_to_sign, user_sha=user_sha, hmac_sha=hmac_sha,
is_pure=is_pure, keep_comp_size=keep_comp_size)
img = compressed_img
else:
img.create(key, public_key_format, enckey, dependencies, boot_record,
custom_tlvs, compression_tlvs, None, int(encrypt_keylen), clear,
baked_signature, pub_key, vector_to_sign, user_sha=user_sha,
hmac_sha=hmac_sha, is_pure=is_pure)
img.save(outfile, hex_addr)
if sig_out is not None:
new_signature = img.get_signature()
save_signature(sig_out, new_signature)
class AliasesGroup(click.Group):
_aliases = {
"create": "sign",
}
def list_commands(self, ctx):
cmds = [k for k in self.commands]
aliases = [k for k in self._aliases]
return sorted(cmds + aliases)
def get_command(self, ctx, cmd_name):
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
if cmd_name in self._aliases:
return click.Group.get_command(self, ctx, self._aliases[cmd_name])
return None
@click.command(help='Print imgtool version information')
def version():
print(imgtool_version)
@click.command(cls=AliasesGroup,
context_settings=dict(help_option_names=['-h', '--help']))
def imgtool():
pass
imgtool.add_command(keygen)
imgtool.add_command(getpub)
imgtool.add_command(getpubhash)
imgtool.add_command(getpriv)
imgtool.add_command(keyinfo)
imgtool.add_command(verify)
imgtool.add_command(sign)
imgtool.add_command(version)
imgtool.add_command(dumpinfo)
if __name__ == '__main__':
imgtool()