1#-------------------------------------------------------------------------------
2# Copyright (c) 2021-2022, Arm Limited. All rights reserved.
3#
4# SPDX-License-Identifier: BSD-3-Clause
5#
6#-------------------------------------------------------------------------------
7
8import argparse
9import struct
10import secrets
11
12def struct_pack(objects, pad_to=0):
13    defstring = "<"
14    for obj in objects:
15        defstring += str(len(obj)) + "s"
16
17    size = struct.calcsize(defstring)
18    if size < pad_to:
19        defstring += str(pad_to - size) + "x"
20
21    return (bytes(struct.pack(defstring, *objects)))
22
23parser = argparse.ArgumentParser()
24parser.add_argument("--bl2_encryption_key_input_file", help="the key that BL2 was encrypted with", required=True)
25parser.add_argument("--bl2_signing_key_input_file", help="the key that BL2 was signed with", required=False)
26parser.add_argument("--guk_input_file", help="the GUK", required=True)
27parser.add_argument("--bl1_2_padded_hash_input_file", help="the hash of the final bl1_2 image", required=True)
28parser.add_argument("--bl2_signed_hash_input_file", help="the hash of the final bl2 image", required=True)
29parser.add_argument("--bl1_2_input_file", help="the final bl1_2 image", required=True)
30parser.add_argument("--bundle_output_file", help="bundle output file", required=True)
31args = parser.parse_args()
32
33with open(args.bl2_encryption_key_input_file, "rb") as in_file:
34    bl1_2_encryption_key = in_file.read()
35
36with open(args.guk_input_file, "rb") as in_file:
37    guk = in_file.read()
38
39with open(args.bl1_2_padded_hash_input_file, "rb") as in_file:
40    bl1_2_padded_hash = in_file.read()
41
42with open(args.bl2_signed_hash_input_file, "rb") as in_file:
43    bl2_signed_hash = in_file.read()
44
45with open(args.bl1_2_input_file, "rb") as in_file:
46    bl1_2 = in_file.read()
47
48if args.bl2_signing_key_input_file:
49    with open(args.bl2_signing_key_input_file + ".pub", "rb") as in_file:
50        # Remove the first 4 bytes since it's HSS info
51        bl1_rotpk_0 = in_file.read()[4:]
52else:
53    bl1_rotpk_0 = bytes(56)
54
55
56bundle = struct_pack([
57    int("0xC0DEFEED", 16).to_bytes(4, 'little'),
58    bl1_2_encryption_key,
59    guk,
60    bl1_2_padded_hash,
61    bl2_signed_hash,
62    bl1_2,
63    bl1_rotpk_0
64])
65
66with open(args.bundle_output_file, "wb") as out_file:
67    out_file.write(bundle)
68