-
Notifications
You must be signed in to change notification settings - Fork 24
/
nxpimage.py
2907 lines (2476 loc) · 103 KB
/
nxpimage.py
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright 2022-2024 NXP
#
# SPDX-License-Identifier: BSD-3-Clause
"""NXP MCU Image tool."""
import datetime
import logging
import os
import sys
from binascii import unhexlify
from typing import Optional
import click
from spsdk.apps.utils import spsdk_logger
from spsdk.apps.utils.common_cli_options import (
CommandsTreeGroup,
SpsdkClickGroup,
spsdk_apps_common_options,
spsdk_config_option,
spsdk_family_option,
spsdk_output_option,
spsdk_plugin_option,
spsdk_revision_option,
)
from spsdk.apps.utils.utils import (
INT,
SPSDKAppError,
catch_spsdk_error,
filepath_from_config,
store_key,
)
from spsdk.crypto.crypto_types import SPSDKEncoding
from spsdk.crypto.signature_provider import get_signature_provider
from spsdk.exceptions import SPSDKError
from spsdk.image.ahab.ahab_certificate import AhabCertificate
from spsdk.image.ahab.ahab_data import AhabTargetMemory, FlagsSrkSet
from spsdk.image.ahab.ahab_image import AHABImage
from spsdk.image.ahab.signed_msg import MessageCommands, SignedMessage, SignedMessageContainer
from spsdk.image.ahab.utils import (
ahab_re_sign,
ahab_sign_image,
ahab_update_keyblob,
write_ahab_fuses,
)
from spsdk.image.bee import BeeNxp
from spsdk.image.bootable_image.bimg import BootableImage
from spsdk.image.fcb.fcb import FCB
from spsdk.image.hab import segments as hab_segments
from spsdk.image.hab.hab_container import HabContainer
from spsdk.image.keystore import KeyStore
from spsdk.image.mbi.mbi import (
MasterBootImage,
get_mbi_class,
mbi_generate_config_templates,
mbi_get_supported_families,
)
from spsdk.image.mem_type import MemoryType
from spsdk.image.trustzone import TrustZone
from spsdk.image.wic import replace_uboot
from spsdk.image.xmcd.xmcd import XMCD, ConfigurationBlockType
from spsdk.sbfile.sb2 import sly_bd_parser as bd_parser
from spsdk.sbfile.sb2.commands import CmdLoad
from spsdk.sbfile.sb2.images import BootImageV21
from spsdk.sbfile.sb31.images import SecureBinary31
from spsdk.utils.crypto.cert_blocks import CertBlock, CertBlockV1, CertBlockVx, IskCertificateLite
from spsdk.utils.crypto.iee import IeeNxp
from spsdk.utils.crypto.otfad import OtfadNxp
from spsdk.utils.database import DatabaseManager
from spsdk.utils.images import BinaryImage, BinaryPattern
from spsdk.utils.misc import (
Endianness,
align,
align_block,
get_abs_path,
get_printable_path,
load_binary,
load_configuration,
load_hex_string,
load_text,
value_to_int,
write_file,
)
from spsdk.utils.plugins import load_plugin_from_source
from spsdk.utils.schema_validator import CommentedConfig, check_config
from spsdk.utils.verifier import Verifier, VerifierResult
logger = logging.getLogger(__name__)
def print_verifier_to_console(v: Verifier, problems: bool = False) -> None:
"""Print verifier results to console."""
results = None
if problems:
results = [VerifierResult.WARNING, VerifierResult.ERROR]
click.echo(v.draw(results))
click.echo("Summary table of verifier results:\n" + v.get_summary_table() + "\n")
click.echo("Overall result: " + VerifierResult.draw(v.result))
@click.group(name="nxpimage", no_args_is_help=True, cls=CommandsTreeGroup)
@spsdk_apps_common_options
def main(log_level: int) -> None:
"""NXP Image tool.
Manage various kinds of images for NXP parts.
It's successor of obsolete ELFTOSB tool.
"""
spsdk_logger.install(level=log_level)
@main.group(name="mbi", no_args_is_help=True, cls=SpsdkClickGroup)
def mbi_group() -> None:
"""Group of sub-commands related to Master Boot Images."""
@mbi_group.command(name="export", no_args_is_help=True)
@spsdk_config_option(required=True)
@spsdk_plugin_option
def mbi_export_command(config: str, plugin: str) -> None:
"""Generate Master Boot Image from YAML/JSON configuration.
The configuration template files could be generated by subcommand 'get-templates'.
"""
mbi_export(config, plugin)
def mbi_export(config: str, plugin: Optional[str] = None) -> None:
"""Generate Master Boot Image from YAML/JSON configuration.
:param config: Path to the YAML/JSON configuration
:param plugin: Path to external python file containing a custom SignatureProvider implementation.
"""
config_data = load_configuration(config)
if plugin:
load_plugin_from_source(plugin)
config_dir = os.path.dirname(config)
mbi_cls = get_mbi_class(config_data)
check_config(config_data, mbi_cls.get_validation_schemas_family())
check_config(
config_data,
mbi_cls.get_validation_schemas(config_data["family"]),
search_paths=[config_dir, "."],
)
mbi_obj = mbi_cls()
mbi_obj.load_from_config(config_data, search_paths=[config_dir, "."])
mbi_data = mbi_obj.export_image()
if mbi_obj.rkth:
click.echo(f"RKTH: {mbi_obj.rkth.hex()}")
mbi_output_file_path = get_abs_path(config_data["masterBootOutputFile"], config_dir)
logger.info(mbi_data.draw())
write_file(mbi_data.export(), mbi_output_file_path, mode="wb")
click.echo(f"Success. (Master Boot Image: {get_printable_path(mbi_output_file_path)} created.)")
@mbi_group.command(name="parse", no_args_is_help=True)
@spsdk_family_option(families=mbi_get_supported_families())
@spsdk_revision_option
@click.option(
"-b",
"--binary",
type=click.Path(exists=True, readable=True, resolve_path=True),
required=True,
help="Path to binary MBI image to parse.",
)
@click.option(
"-k",
"--dek",
type=str,
required=False,
help=(
"Data encryption key, if it's specified, the parse method tries decrypt all encrypted images. "
"It could be specified as binary/HEX text file path or directly HEX string"
),
)
@spsdk_output_option(directory=True)
def mbi_parse_command(family: str, revision: str, binary: str, dek: str, output: str) -> None:
"""Parse MBI Image into YAML configuration and binary images."""
mbi_parse(family, revision, binary, dek, output)
def mbi_parse(family: str, revision: str, binary: str, dek: str, output: str) -> None:
"""Parse MBI Image into YAML configuration and binary images."""
mbi = MasterBootImage.parse(family=family, data=load_binary(binary), dek=dek, revision=revision)
if not mbi:
click.echo(f"Failed. (MBI: {binary} parsing failed.)")
return
cfg = mbi.create_config(output_folder=output)
yaml_data = CommentedConfig(
main_title=(
f"Master Boot Image ({mbi.__class__.__name__}) recreated configuration from :"
f"{datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S')}."
),
schemas=mbi.get_validation_schemas(family),
).get_config(cfg)
write_file(yaml_data, os.path.join(output, "mbi_config.yaml"))
click.echo(f"Success. (MBI: {binary} has been parsed and stored into {output} )")
@mbi_group.command(name="get-templates", no_args_is_help=True)
@spsdk_family_option(families=mbi_get_supported_families())
@spsdk_revision_option
@spsdk_output_option(directory=True, force=True)
def mbi_get_templates_command(family: str, revision: str, output: str) -> None:
"""Create template of MBI configurations in YAML format."""
mbi_get_templates(family, revision, output)
def mbi_get_templates(family: str, revision: str, output: str) -> None:
"""Create template of MBI configurations in YAML format."""
templates = mbi_generate_config_templates(family, revision)
for file_name, template in templates.items():
full_file_name = os.path.join(output, file_name + ".yaml")
click.echo(f"Creating {get_printable_path(full_file_name)} template file.")
write_file(template, full_file_name)
@main.group(name="sb21", no_args_is_help=True, cls=SpsdkClickGroup)
def sb21_group() -> None:
"""Group of sub-commands related to Secure Binary 2.1."""
@sb21_group.command(name="export", no_args_is_help=True)
@click.option(
"-c",
"--command",
type=click.Path(exists=True, resolve_path=True),
required=True,
help="BD or YAML configuration file to produce secure binary v2.x",
)
@spsdk_output_option(required=False)
@click.option(
"-k", "--key", type=click.Path(exists=True), help="Add a key file and enable encryption."
)
@click.option(
"-s",
"--pkey",
type=str,
help="Path to private key or signature provider configuration used for signing.",
)
@click.option(
"-S",
"--cert",
type=click.Path(exists=True),
multiple=True,
help="Path to certificate files for signing. The first certificate will be \
the self signed root key certificate.",
)
@click.option(
"-R",
"--root-key-cert",
type=click.Path(exists=True),
multiple=True,
help="Path to root key certificate file(s) for verifying other certificates. \
Only 4 root key certificates are allowed, others are ignored. \
One of the certificates must match the first certificate passed \
with -S/--cert arg.",
)
@click.option(
"-h",
"--hash-of-hashes",
type=click.Path(),
help="Path to output hash of hashes of root keys. If argument is not \
provided, then by default the tool creates hash.bin in the working directory.",
)
@spsdk_plugin_option
@click.argument("external", type=click.Path(), nargs=-1)
def sb21_export_command(
command: str,
output: Optional[str] = None,
key: Optional[str] = None,
pkey: Optional[str] = None,
cert: Optional[list[str]] = None,
root_key_cert: Optional[list[str]] = None,
hash_of_hashes: Optional[str] = None,
plugin: Optional[str] = None,
external: Optional[list[str]] = None,
) -> None:
"""Generate Secure Binary v2.1 Image from configuration.
EXTERNAL is a space separated list of external binary files defined in BD file
"""
sb21_export(command, output, key, pkey, cert, root_key_cert, hash_of_hashes, plugin, external)
def sb21_export(
command: str,
output: Optional[str] = None,
key: Optional[str] = None,
pkey: Optional[str] = None,
cert: Optional[list[str]] = None,
root_key_cert: Optional[list[str]] = None,
hash_of_hashes: Optional[str] = None,
plugin: Optional[str] = None,
external: Optional[list[str]] = None,
) -> None:
"""Generate Secure Binary v2.1 Image from configuration (BD or YAML)."""
if plugin:
load_plugin_from_source(plugin)
signature_provider = None
if pkey:
signature_provider = (
get_signature_provider(local_file_key=pkey)
if os.path.isfile(pkey)
else get_signature_provider(sp_cfg=pkey)
)
config_dir = os.path.dirname(command)
try:
parsed_config = BootImageV21.parse_sb21_config(command, external_files=external)
if not output:
output = get_abs_path(parsed_config["containerOutputFile"], config_dir)
sb2 = BootImageV21.load_from_config(
config=parsed_config,
key_file_path=key,
signature_provider=signature_provider,
signing_certificate_file_paths=cert,
root_key_certificate_paths=root_key_cert,
rkth_out_path=hash_of_hashes,
search_paths=[config_dir],
)
write_file(sb2.export(), output, mode="wb")
except (SPSDKError, KeyError) as exc:
raise SPSDKAppError(f"The SB2.1 file generation failed: ({str(exc)}).") from exc
if sb2.cert_block:
click.echo(f"RKTH: {sb2.cert_block.rkth.hex()}")
click.echo(f"Success. (Secure binary 2.1: {get_printable_path(output)} created.)")
@sb21_group.command(name="parse", no_args_is_help=True)
@click.option(
"-b",
"--binary",
type=click.Path(exists=True, readable=True, resolve_path=True),
required=True,
help="Path to the SB2 container that would be parsed.",
)
@click.option(
"-k",
"--key",
type=click.Path(exists=True, readable=True),
required=True,
help="Key file for SB2 decryption in plaintext",
)
@spsdk_output_option(directory=True)
def sb21_parse_command(binary: str, key: str, output: str) -> None:
"""Parse Secure Binary v2.1 Image."""
sb21_parse(binary, key, output)
def sb21_parse(binary: str, key: str, output: str) -> None:
"""Parse Secure Binary v2.1 Image."""
# transform text-based KEK into bytes
sb_kek = unhexlify(load_text(key))
try:
parsed_sb = BootImageV21.parse(data=load_binary(binary), kek=sb_kek)
except SPSDKError as exc:
raise SPSDKAppError(f"SB21 parse: Attempt to parse image failed: {str(exc)}") from exc
if isinstance(parsed_sb.cert_block, CertBlockV1):
for cert_idx, certificate in enumerate(parsed_sb.cert_block.certificates):
file_name = os.path.join(output, f"certificate_{cert_idx}_der.cer")
logger.debug(f"Dumping certificate {file_name}")
write_file(certificate.export(SPSDKEncoding.DER), file_name, mode="wb")
for section_idx, boot_sections in enumerate(parsed_sb.boot_sections):
for command_idx, command in enumerate(boot_sections._commands):
if isinstance(command, CmdLoad):
file_name = os.path.join(
output, f"section_{section_idx}_load_command_{command_idx}_data.bin"
)
logger.debug(f"Dumping load command data {file_name}")
write_file(command.data, file_name, mode="wb")
logger.debug(str(parsed_sb))
write_file(
str(parsed_sb),
os.path.join(output, "parsed_info.txt"),
)
click.echo(f"Success. (SB21: {binary} has been parsed and stored into {output}.)")
click.echo(
"Please note that the exported binary images from load command might contain padding"
)
@sb21_group.command(name="get-sbkek", no_args_is_help=False)
@click.option(
"-k",
"--master-key",
type=str,
help="AES-256 master key as hexadecimal string or path to file containing key in plain text or in binary",
)
@spsdk_output_option(
required=False,
directory=True,
help="Output folder where the sbkek.txt and sbkek.bin will be stored",
)
def get_sbkek_command(master_key: str, output: str) -> None:
"""Compute SBKEK (AES-256) value and optionally store it as plain text and as binary.
SBKEK is AES-256 symmetric key used for encryption and decryption of SB.
Plain text version is used for SB generation.
Binary format is to be written to the keystore.
The same format is also used for USER KEK.
For OTP, the SBKEK is derived from OTP master key:
SB2_KEK = AES256(OTP_MASTER_KEY,
03000000_00000000_00000000_00000000_04000000_00000000_00000000_00000000)
Master key is not needed when using PUF as key storage
The computed SBKEK is shown as hexadecimal text on STDOUT,
SBKEK is stored in plain text and in binary if the 'output-folder' is specified,
"""
get_sbkek(master_key, output)
def get_sbkek(master_key: str, output_folder: str) -> None:
"""Compute SBKEK (AES-256) value and optionally store it as plain text and as binary."""
otp_master_key = load_hex_string(master_key, KeyStore.OTP_MASTER_KEY_SIZE)
sbkek = KeyStore.derive_sb_kek_key(otp_master_key)
click.echo(f"SBKEK: {sbkek.hex()}")
click.echo(f"(OTP) MASTER KEY: {otp_master_key.hex()}")
if output_folder:
store_key(os.path.join(output_folder, "sbkek"), sbkek, reverse=True)
store_key(os.path.join(output_folder, "otp_master_key"), otp_master_key)
click.echo(f"Keys have been stored to: {get_printable_path(output_folder)}")
@sb21_group.command(name="convert", no_args_is_help=False)
@spsdk_family_option(families=BootImageV21.get_supported_families(), required=True)
@spsdk_output_option(help="Path to converted YAML configuration")
@click.option(
"-c",
"--command",
type=click.Path(resolve_path=True, exists=True),
help="Path to BD file that will be converted to YAML",
required=True,
)
@click.option(
"-k",
"--key",
type=click.Path(exists=True),
help="Add a key file and enable encryption.",
required=True,
)
@click.option(
"-s",
"--pkey",
type=str,
help="Path to private key or signature provider configuration used for signing.",
)
@click.option(
"-S",
"--cert",
type=click.Path(exists=True),
multiple=True,
help="Path to certificate files for signing. The first certificate will be \
the self signed root key certificate.",
)
@click.option(
"-R",
"--root-key-cert",
type=click.Path(exists=True),
multiple=True,
help="Path to root key certificate file(s) for verifying other certificates. \
Only 4 root key certificates are allowed, others are ignored. \
One of the certificates must match the first certificate passed \
with -S/--cert arg.",
)
@click.option(
"-h",
"--hash-of-hashes",
type=click.Path(),
help="Path to output hash of hashes of root keys. If argument is not \
provided, then by default the tool creates hash.bin in the working directory.",
)
@click.argument("external", type=click.Path(), nargs=-1)
def convert_bd(
command: str,
output: str,
key: str,
pkey: str,
cert: list[str],
root_key_cert: list[str],
hash_of_hashes: str,
external: list[str],
family: str,
) -> None:
"""Convert SB 2.1 BD file to YAML."""
convert_bd_conf(
command, output, key, pkey, cert, root_key_cert, hash_of_hashes, external, family
)
def convert_bd_conf(
command: str,
output_conf: str,
key: str,
pkey: str,
cert: list[str],
root_key_cert: list[str],
hash_of_hashes: str,
external: list[str],
family: str,
) -> None:
"""Convert SB 2.1 BD file to YAML."""
config = BootImageV21.parse_sb21_config(command, external_files=external)
cert_config = {}
for idx, root_cert in enumerate(root_key_cert):
cert_config[f"rootCertificate{idx}File"] = root_cert
for crt in cert:
if root_cert == crt:
cert_config["mainRootCertId"] = idx # type: ignore[assignment]
cert_config["imageBuildNumber"] = config["options"].pop("buildNumber")
config["signPrivateKey"] = pkey
if key:
config["containerKeyBlobEncryptionKey"] = key
if hash_of_hashes:
config["RKHTOutputPath"] = hash_of_hashes
config["containerOutputFile"] = "output.sb"
cert_block_file = "cert_block.yaml"
config["certBlock"] = cert_block_file
config["family"] = family
schemas = BootImageV21.get_validation_schemas()
ret = CommentedConfig(main_title="SB 2.1 converted configuration", schemas=schemas).get_config(
config
)
write_file(ret, output_conf)
schemas = CertBlockV1.get_validation_schemas()
ret = CommentedConfig(main_title="Certificate Block V1", schemas=schemas).get_config(
cert_config
)
write_file(ret, os.path.join(os.path.dirname(output_conf), cert_block_file))
click.echo(f"Converted YAML configuration written to {output_conf}")
@sb21_group.command(name="get-template", no_args_is_help=True)
@spsdk_output_option(force=True)
@spsdk_family_option(families=BootImageV21.get_supported_families(), required=False)
def sb21_get_template_command(output: str, family: str) -> None:
"""Create template of configuration in YAML format."""
sb21_get_template(output, family)
def sb21_get_template(output: str, family: Optional[str] = None) -> None:
"""Create template of configuration in YAML format."""
click.echo(f"Creating {get_printable_path(output)} template file.")
write_file(BootImageV21.generate_config_template(family), output)
@main.group(name="sb31", cls=SpsdkClickGroup)
def sb31_group() -> None:
"""Group of sub-commands related to Secure Binary 3.1."""
@sb31_group.command(name="export", no_args_is_help=True)
@spsdk_config_option(required=True)
@spsdk_plugin_option
def sb31_export_command(config: str, plugin: str) -> None:
"""Generate Secure Binary v3.1 Image from YAML/JSON configuration.
SB3KDK is printed out in verbose mode.
The configuration template files could be generated by subcommand 'get-template'.
"""
sb31_export(config, plugin)
def sb31_export(config: str, plugin: Optional[str] = None) -> None:
"""Generate Secure Binary v3.1 Image from YAML/JSON configuration."""
if plugin:
load_plugin_from_source(plugin)
config_data = load_configuration(config)
config_dir = os.path.dirname(config)
check_config(config_data, SecureBinary31.get_validation_schemas_family())
schemas = SecureBinary31.get_validation_schemas(config_data["family"])
check_config(config_data, schemas, search_paths=[config_dir])
sb3 = SecureBinary31.load_from_config(config_data, search_paths=[config_dir, "."])
sb3_data = sb3.export()
sb3_output_file_path = get_abs_path(config_data["containerOutputFile"], config_dir)
write_file(sb3_data, sb3_output_file_path, mode="wb")
click.echo(f"RKTH: {sb3.cert_block.rkth.hex()}")
click.echo(f"Success. (Secure binary 3.1: {get_printable_path(sb3_output_file_path)} created.)")
@sb31_group.command(name="get-template", no_args_is_help=True)
@spsdk_family_option(families=SecureBinary31.get_supported_families())
@spsdk_output_option(force=True)
def sb31_get_template_command(family: str, output: str) -> None:
"""Create template of configuration in YAML format.
The template file name is specified as argument of this command.
"""
sb31_get_template(family, output)
def sb31_get_template(family: str, output: str) -> None:
"""Create template of configuration in YAML format."""
click.echo(f"Creating {get_printable_path(output)} template file.")
write_file(SecureBinary31.generate_config_template(family)[f"{family}_sb31"], output)
@main.group(name="cert-block", no_args_is_help=True, cls=SpsdkClickGroup)
def cert_block_group() -> None: # pylint: disable=unused-argument
"""Group of sub-commands related to certification block."""
@cert_block_group.command(name="get-template", no_args_is_help=True)
@spsdk_family_option(families=CertBlock.get_all_supported_families())
@spsdk_output_option(force=True)
def cert_block_get_template_command(output: str, family: str) -> None:
"""Create template of configuration in YAML format."""
cert_block_get_template(output, family)
def cert_block_get_template(output: str, family: str) -> None:
"""Create template of configuration in YAML format."""
click.echo(f"Creating {get_printable_path(output)} template file.")
cert_block_class = CertBlock.get_cert_block_class(family)
write_file(cert_block_class.generate_config_template(family), output)
@cert_block_group.command(name="export", no_args_is_help=True)
@spsdk_config_option(required=True)
@spsdk_family_option(families=CertBlock.get_all_supported_families())
@spsdk_plugin_option
def cert_block_export_command(config: str, family: str, plugin: str) -> None:
"""Generate Certificate Block from YAML/JSON configuration.
The configuration template files could be generated by subcommand 'get-template'.
"""
cert_block_export(config, family, plugin)
def cert_block_export(config: str, family: str, plugin: Optional[str] = None) -> None:
"""Generate Certificate Block from YAML/JSON configuration."""
if plugin:
load_plugin_from_source(plugin)
config_data = load_configuration(config)
config_data["family"] = family
config_dir = os.path.dirname(config)
cert_block_class = CertBlock.get_cert_block_class(family)
schemas = cert_block_class.get_validation_schemas()
check_config(config_data, schemas, search_paths=[config_dir])
cert_block = cert_block_class.from_config(config_data, search_paths=[config_dir])
cert_data = cert_block.export()
try:
cert_block_output_file_path = get_abs_path(config_data["containerOutputFile"], config_dir)
except KeyError as e:
raise SPSDKAppError(
"containerOutputFile property must be provided in order to export cert-block"
) from e
write_file(cert_data, cert_block_output_file_path, mode="wb")
if cert_block.rkth:
click.echo(f"RKTH: {cert_block.rkth.hex()}")
if hasattr(cert_block, "cert_hash"):
assert isinstance(cert_block, CertBlockVx), "Wrong instance of cert block"
click.echo(f"ISK Certificate hash [0:127]: {cert_block.cert_hash.hex()}\n")
otp_script_path = os.path.join(
os.path.dirname(cert_block_output_file_path), "otp_script.bcf"
)
write_file(cert_block.get_otp_script(), otp_script_path)
click.echo(f"OTP script written to: {get_printable_path(otp_script_path)}")
click.echo(
f"Success. (Certificate Block: {get_printable_path(cert_block_output_file_path)} created.)"
)
@cert_block_group.command(name="get-isk-tbs", no_args_is_help=True)
@spsdk_family_option(families=CertBlockVx.get_supported_families())
@click.option(
"-p",
"--public-key",
required=True,
type=click.Path(exists=True, dir_okay=False, resolve_path=True),
help="Path to file with the ISK public key",
)
@spsdk_output_option()
# pylint: disable=unused-argument # we just filter applicable chip families, the value itself is not used
def cert_block_get_isk_tbs_data(family: str, output: str, public_key: str) -> None:
"""Generate To-Be-Signed data for ISK Certificate created by NXP's EdgeLock2GO service."""
puk = load_binary(path=public_key)
isk = IskCertificateLite(pub_key=puk, constraints=0)
tbs_data = isk.get_tbs_data()
write_file(data=tbs_data, path=output, mode="wb")
click.echo(f"Success. (ISK TBS data: {output} created.)")
@cert_block_group.command(name="parse", no_args_is_help=True)
@click.option(
"-b",
"--binary",
type=click.Path(exists=True, readable=True, resolve_path=True),
required=True,
help="Path to binary Certificate Block image to parse.",
)
@spsdk_family_option(families=CertBlock.get_all_supported_families())
@spsdk_output_option(directory=True)
def cert_block_parse_command(binary: str, family: str, output: str) -> None:
"""Parse Certificate Block.
RoTKTH is printed out in verbose mode.
"""
cert_block_parse(binary, family, output)
# pylint: disable=unused-argument # preparation for future updates
def cert_block_parse(binary: str, family: str, output: str) -> None:
"""Parse Certificate Block."""
cert_block = CertBlock.get_cert_block_class(family).parse(load_binary(binary))
logger.info(str(cert_block))
write_file(cert_block.create_config(output), os.path.join(output, "cert_block_config.yaml"))
click.echo(f"RKTH: {cert_block.rkth.hex()}")
click.echo(f"Success. (Certificate Block: {binary} has been parsed into {output}.)")
@main.group(name="tz", no_args_is_help=True, cls=SpsdkClickGroup)
def tz_group() -> None:
"""Group of sub-commands related to Trust Zone."""
@tz_group.command(name="export", no_args_is_help=True)
@spsdk_config_option(required=True)
def tz_export_command(config: str) -> None:
"""Generate TrustZone Image from YAML/JSON configuration.
The configuration template files could be generated by subcommand 'get-template'.
"""
tz_export(config)
def tz_export(config: str) -> None:
"""Generate TrustZone Image from YAML/JSON configuration."""
config_data = load_configuration(config)
config_dir = os.path.dirname(config)
check_config(config_data, TrustZone.get_validation_schemas_family())
check_config(
config_data,
TrustZone.get_validation_schemas(config_data["family"]),
search_paths=[config_dir],
)
trust_zone = TrustZone.from_config(config_data)
tz_data = trust_zone.export()
output_file = get_abs_path(config_data["tzpOutputFile"], config_dir)
write_file(tz_data, output_file, mode="wb")
click.echo(f"Success. (Trust Zone binary: {output_file} created.)")
@tz_group.command(name="get-template", no_args_is_help=True)
@spsdk_family_option(families=TrustZone.get_supported_families())
@spsdk_revision_option
@spsdk_output_option(force=True)
def tz_get_template_command(family: str, revision: str, output: str) -> None:
"""Create template of configuration in YAML format.
The template file name is specified as argument of this command.
"""
tz_get_template(family, revision, output)
def tz_get_template(family: str, revision: str, output: str) -> None:
"""Create template of configuration in YAML format."""
write_file(TrustZone.generate_config_template(family, revision)[f"{family}_tz"], output)
click.echo(f"Trust zone template file has been created: {output}.")
@main.group(name="ahab", no_args_is_help=True, cls=SpsdkClickGroup)
def ahab_group() -> None:
"""Group of sub-commands related to AHAB."""
@ahab_group.command(name="export", no_args_is_help=True)
@spsdk_config_option(required=True)
@spsdk_plugin_option
def ahab_export_command(config: str, plugin: str) -> None:
"""Generate AHAB Image from YAML/JSON configuration.
The configuration template files could be generated by subcommand 'get-template'.
"""
ahab_export(config, plugin)
def ahab_export(config: str, plugin: Optional[str] = None) -> None:
"""Generate AHAB Image from YAML/JSON configuration."""
if plugin:
load_plugin_from_source(plugin)
config_data = load_configuration(config)
config_dir = os.path.dirname(config)
check_config(config_data, AHABImage.get_validation_schemas_family())
family = config_data["family"]
revision = config_data.get("revision", "latest")
schemas = AHABImage.get_validation_schemas(family, revision)
check_config(config_data, schemas, search_paths=[config_dir])
ahab = AHABImage.load_from_config(config_data, search_paths=[config_dir])
ahab.update_fields()
ahab_data = ahab.export()
ahab_output_file_path = get_abs_path(config_data["output"], config_dir)
write_file(ahab_data, ahab_output_file_path, mode="wb")
logger.info(f"Created AHAB Image:\n{str(ahab.image_info())}")
logger.info(f"Created AHAB Image memory map:\n{ahab.image_info().draw()}")
click.echo(f"Success. (AHAB: {get_printable_path(ahab_output_file_path)} created.)")
ahab_output_dir, ahab_output_file = os.path.split(ahab_output_file_path)
ahab_output_file_no_ext, _ = os.path.splitext(ahab_output_file)
write_ahab_fuses(ahab, ahab_output_dir, ahab_output_file_no_ext, click.echo)
@ahab_group.command(name="parse", no_args_is_help=True)
@spsdk_family_option(families=AHABImage.get_supported_families())
@spsdk_output_option(directory=True)
@click.option(
"-b",
"--binary",
type=click.Path(exists=True, readable=True, resolve_path=True),
required=True,
help="Path to binary AHAB image to parse.",
)
@click.option(
"-k",
"--dek",
type=str,
required=False,
help=(
"Data encryption key, if it's specified, the parse method tries decrypt all encrypted images. "
"It could be specified as binary/HEX text file path or directly HEX string"
),
)
def ahab_parse_command(family: str, binary: str, dek: str, output: str) -> None:
"""Parse AHAB Image into YAML configuration and binary images."""
ahab_parse(family, binary, dek, output)
def ahab_parse_image(family: str, binary: bytes) -> AHABImage:
"""Parse one AHAB Image.
:param family: Chip family.
:param binary: Binary to parse
:return: AHAB image if founded
:raise SPSDKError: In case of AHAB is not found
"""
for target_memory in AhabTargetMemory.labels():
try:
ahab_image = AHABImage(family=family, target_memory=target_memory)
ahab_image.parse(binary)
ahab_image.verify().validate()
except SPSDKError as exc:
logger.debug(
f"AHAB parse: Attempt to parse image for {target_memory} target failed: {str(exc)}"
)
ahab_image = None
else:
break
if not ahab_image:
raise SPSDKError("Cannot find valid AHAB image")
return ahab_image
def ahab_parse(family: str, binary: str, dek: str, output: str) -> None:
"""Parse AHAB Image into YAML configuration and binary images."""
data = load_binary(binary)
parsed_folder = output
try:
ahab_image = ahab_parse_image(family=family, binary=data)
except SPSDKError as exc:
click.echo(f"Failed. (AHAB: {binary} parsing failed.: {str(exc)})")
return
if not os.path.exists(parsed_folder):
os.makedirs(parsed_folder, exist_ok=True)
logger.info(f"Identified AHAB image for {ahab_image.chip_config.target_memory.label} target")
logger.info(f"Parsed AHAB image memory map: {ahab_image.image_info().draw()}")
if dek:
for container in ahab_image.ahab_containers:
if container.flag_srk_set != FlagsSrkSet.NXP:
if container.signature_block and container.signature_block.blob:
container.signature_block.blob.dek = load_hex_string(
dek, container.signature_block.blob._size // 8
)
container.decrypt_data()
else:
logger.info("Nothing to decrypt, the container doesn't contains BLOB")
config = ahab_image.create_config(parsed_folder)
write_file(
CommentedConfig(
main_title=(
f"AHAB recreated configuration from :"
f"{datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S')}."
),
schemas=AHABImage.get_validation_schemas(family=family),
).get_config(config),
os.path.join(parsed_folder, "parsed_config.yaml"),
)
click.echo(f"Success. (AHAB: {binary} has been parsed and stored into {parsed_folder}.)")
write_ahab_fuses(ahab_image, parsed_folder, "", click.echo)
@ahab_group.command(name="verify", no_args_is_help=True)
@spsdk_family_option(families=AHABImage.get_supported_families())
@click.option(
"-b",
"--binary",
type=click.Path(exists=True, readable=True, resolve_path=True),
required=True,
help="Path to binary AHAB image to parse.",
)
@click.option(
"-p",
"--problems",
is_flag=True,
default=False,
help="Show just problems in image.",
)
@click.option(
"-k",
"--dek",
type=str,
required=False,
help=(
"Data encryption key, if it's specified, the parse method tries decrypt all encrypted images. "
"It could be specified as binary/HEX text file path or directly HEX string"
),
)
def ahab_verify_command(family: str, binary: str, dek: str, problems: bool) -> None:
"""Verify AHAB Image."""
ahab_verify(family=family, binary=binary, dek=dek, problems=problems)
def ahab_verify(family: str, binary: str, dek: str, problems: bool) -> None:
"""Verify AHAB Image."""
data = load_binary(binary)
verifiers: list[Verifier] = []
valid_image = None
preparsed = AHABImage.pre_parse_verify(data)
if preparsed.has_errors:
click.echo("The image bases has error, it doesn't passed pre-parse check:")
print_verifier_to_console(preparsed, problems)
raise SPSDKAppError("Pre-parsed check failed")
for target_memory in AhabTargetMemory.labels():
ahab_image = AHABImage(family=family, target_memory=target_memory)
ahab_image.parse(data)
ver = ahab_image.verify()
verifiers.append(ver)
if not ver.has_errors:
valid_image = ahab_image
if not valid_image:
click.echo(
"The binary has errors for all memory targets! All memory targets attempts will be printed.",
err=True,
)
for x, verifier in enumerate(verifiers):
click.echo("\n" + "=" * 120)
click.echo(
f"The verification attempt for target memory: {AhabTargetMemory.labels()[x].upper()}".center(
120
)
)
click.echo("=" * 120 + "\n")
print_verifier_to_console(verifier, problems)
raise SPSDKAppError("Verify failed")
for cnt in valid_image.ahab_containers:
if cnt.flag_srk_set != FlagsSrkSet.NXP and cnt.signature_block and cnt.signature_block.blob:
cnt.signature_block.blob.dek = (
load_hex_string(dek, cnt.signature_block.blob._size // 8) if dek else None
)
if not problems:
click.echo(valid_image.image_info().draw())
print_verifier_to_console(valid_image.verify(), problems)
@ahab_group.command(name="update-keyblob", no_args_is_help=True)
@spsdk_family_option(AHABImage.get_supported_families())