Debian Codegraph @

src/nitrokey/trussed/_bootloader/lpc55_upload/sbfile/sb2/headers.py

raw
1 #!/usr/bin/env python
2 # -*- coding: UTF-8 -*-
3 #
4 # Copyright 2019-2023 NXP
5 #
6 # SPDX-License-Identifier: BSD-3-Clause
7
8 """Image header."""
9
10 from datetime import datetime
11 from struct import calcsize, unpack_from
12 from typing import TYPE_CHECKING, Optional
13
14 from ...exceptions import SPSDKError
15 from ...sbfile.misc import BcdVersion3, unpack_timestamp
16 from ...utils.abstract import BaseClass
17 from ...utils.misc import swap16
18
19 if TYPE_CHECKING:
20 from typing_extensions import Self
21
22
23 ########################################################################################################################
24 # Image Header Class (Version SB2)
25 ########################################################################################################################
26 # pylint: disable=too-many-instance-attributes
27 class ImageHeaderV2(BaseClass):
28 """Image Header V2 class."""
29
30 FORMAT = "<16s4s4s2BH4I4H4sQ12HI4s"
31 SIZE = calcsize(FORMAT)
32 SIGNATURE1 = b"STMP"
33 SIGNATURE2 = b"sgtl"
34
35 def __init__(
36 self,
37 version: str = "2.0",
38 product_version: str = "1.0.0",
39 component_version: str = "1.0.0",
40 build_number: int = 0,
41 flags: int = 0x08,
42 nonce: Optional[bytes] = None,
43 timestamp: Optional[datetime] = None,
44 ) -> None:
45 """Initialize Image Header Version 2.x.
46
47 :param version: The image version value (default: 2.0)
48 :param product_version: The product version (default: 1.0.0)
49 :param component_version: The component version (default: 1.0.0)
50 :param build_number: The build number value (default: 0)
51 :param flags: The flags value (default: 0x08)
52 :param nonce: The NONCE value; None if TODO ????
53 :param timestamp: value requested in the test; None to use current value
54 """
55 self.nonce = nonce
56 self.version = version
57 self.flags = flags
58 self.image_blocks = 0 # will be updated from boot image
59 self.first_boot_tag_block = 0
60 self.first_boot_section_id = 0
61 self.offset_to_certificate_block = 0 # will be updated from boot image
62 self.header_blocks = 0 # will be calculated in the BootImage later
63 self.key_blob_block = 8
64 self.key_blob_block_count = 5
65 self.max_section_mac_count = 0 # will be calculated in the BootImage later
66 self.timestamp = (
67 timestamp
68 if timestamp is not None
69 else datetime.fromtimestamp(int(datetime.now().timestamp()))
70 )
71 self.product_version: BcdVersion3 = BcdVersion3.to_version(product_version)
72 self.component_version: BcdVersion3 = BcdVersion3.to_version(component_version)
73 self.build_number = build_number
74
75 def __repr__(self) -> str:
76 return f"Header: v{self.version}, {self.image_blocks}"
77
78 def flags_desc(self) -> str:
79 """Return flag description."""
80 return "Signed" if self.flags == 0x8 else "Unsigned"
81
82 def __str__(self) -> str:
83 """Get info of Header as string."""
84 nfo = str()
85 nfo += f" Version: {self.version}\n"
86 if self.nonce is not None:
87 nfo += f" Digest: {self.nonce.hex().upper()}\n"
88 nfo += f" Flag: 0x{self.flags:X} ({self.flags_desc()})\n"
89 nfo += f" Image Blocks: {self.image_blocks}\n"
90 nfo += f" First Boot Tag Block: {self.first_boot_tag_block}\n"
91 nfo += f" First Boot SectionID: {self.first_boot_section_id}\n"
92 nfo += f" Offset to Cert Block: {self.offset_to_certificate_block}\n"
93 nfo += f" Key Blob Block: {self.key_blob_block}\n"
94 nfo += f" Header Blocks: {self.header_blocks}\n"
95 nfo += f" Sections MAC Count: {self.max_section_mac_count}\n"
96 nfo += f" Key Blob Block Count: {self.key_blob_block_count}\n"
97 nfo += f" Timestamp: {self.timestamp.strftime('%H:%M:%S (%d.%m.%Y)')}\n"
98 nfo += f" Product Version: {self.product_version}\n"
99 nfo += f" Component Version: {self.component_version}\n"
100 nfo += f" Build Number: {self.build_number}\n"
101 return nfo
102
103 # pylint: disable=too-many-locals
104 @classmethod
105 def parse(cls, data: bytes) -> "Self":
106 """Deserialization from binary form.
107
108 :param data: binary representation
109 :return: parsed instance of the header
110 :raises SPSDKError: Unable to parse data
111 """
112 if cls.SIZE > len(data):
113 raise SPSDKError("Insufficient amount of data")
114 (
115 nonce,
116 # padding0
117 _,
118 signature1,
119 # header version
120 major_version,
121 minor_version,
122 flags,
123 image_blocks,
124 first_boot_tag_block,
125 first_boot_section_id,
126 offset_to_certificate_block,
127 header_blocks,
128 key_blob_block,
129 key_blob_block_count,
130 max_section_mac_count,
131 signature2,
132 raw_timestamp,
133 # product version
134 pv0,
135 _,
136 pv1,
137 _,
138 pv2,
139 _,
140 # component version
141 cv0,
142 _,
143 cv1,
144 _,
145 cv2,
146 _,
147 build_number,
148 # padding1
149 _,
150 ) = unpack_from(cls.FORMAT, data)
151
152 # check header signature 1
153 if signature1 != cls.SIGNATURE1:
154 raise SPSDKError("SIGNATURE #1 doesn't match")
155
156 # check header signature 2
157 if signature2 != cls.SIGNATURE2:
158 raise SPSDKError("SIGNATURE #2 doesn't match")
159
160 obj = cls(
161 version=f"{major_version}.{minor_version}",
162 flags=flags,
163 product_version=f"{swap16(pv0):X}.{swap16(pv1):X}.{swap16(pv2):X}",
164 component_version=f"{swap16(cv0):X}.{swap16(cv1):X}.{swap16(cv2):X}",
165 build_number=build_number,
166 )
167
168 obj.nonce = nonce
169 obj.image_blocks = image_blocks
170 obj.first_boot_tag_block = first_boot_tag_block
171 obj.first_boot_section_id = first_boot_section_id
172 obj.offset_to_certificate_block = offset_to_certificate_block
173 obj.header_blocks = header_blocks
174 obj.key_blob_block = key_blob_block
175 obj.key_blob_block_count = key_blob_block_count
176 obj.max_section_mac_count = max_section_mac_count
177 obj.timestamp = unpack_timestamp(raw_timestamp)
178
179 return obj