Debian Codegraph @

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

raw
1 #!/usr/bin/env python
2 # -*- coding: UTF-8 -*-
3 #
4 # Copyright 2019-2024 NXP
5 #
6 # SPDX-License-Identifier: BSD-3-Clause
7
8 """Boot Image V2.0, V2.1."""
9
10 from datetime import datetime
11 from typing import Iterator, List, Optional
12
13 from ...crypto.hash import EnumHashAlgorithm, get_hash
14 from ...crypto.symmetric import Counter, aes_key_unwrap
15 from ...exceptions import SPSDKError
16 from ...sbfile.misc import SecBootBlckSize
17 from ...utils.abstract import BaseClass
18 from ...utils.crypto.cert_blocks import CertBlockV1
19 from .headers import ImageHeaderV2
20 from .sections import BootSectionV2
21
22
23 class SBV2xAdvancedParams:
24 """The class holds advanced parameters for the SB file encryption.
25
26 These parameters are used for the tests; for production, use can use default values (random keys + current time)
27 """
28
29 def __init__(self, dek: bytes, mac: bytes, nonce: bytes, timestamp: datetime) -> None:
30 """Initialize SBV2xAdvancedParams.
31
32 :param dek: DEK key
33 :param mac: MAC key
34 :param nonce: nonce
35 :param timestamp: fixed timestamp for the header; use None to use current date/time
36 :raises SPSDKError: Invalid dek or mac
37 :raises SPSDKError: Invalid length of nonce
38 """
39 self._dek = dek
40 self._mac = mac
41 self._nonce = nonce
42 self._timestamp = datetime.fromtimestamp(int(timestamp.timestamp()))
43 if len(self._dek) != 32 and len(self._mac) != 32:
44 raise SPSDKError("Invalid dek or mac")
45 if len(self._nonce) != 16:
46 raise SPSDKError("Invalid length of nonce")
47
48 @property
49 def dek(self) -> bytes:
50 """Return DEK key."""
51 return self._dek
52
53 @property
54 def mac(self) -> bytes:
55 """Return MAC key."""
56 return self._mac
57
58 @property
59 def nonce(self) -> bytes:
60 """Return NONCE."""
61 return self._nonce
62
63 @property
64 def timestamp(self) -> datetime:
65 """Return timestamp."""
66 return self._timestamp
67
68
69 ########################################################################################################################
70 # Secure Boot Image Class (Version 2.1)
71 ########################################################################################################################
72 class BootImageV21(BaseClass):
73 """Boot Image V2.1 class."""
74
75 # Image specific data
76 HEADER_MAC_SIZE = 32
77 KEY_BLOB_SIZE = 80
78 SHA_256_SIZE = 32
79
80 # defines
81 FLAGS_SHA_PRESENT_BIT = 0x8000 # image contains SHA-256
82 FLAGS_ENCRYPTED_SIGNED_BIT = 0x0008 # image is signed and encrypted
83
84 def __init__(
85 self,
86 kek: bytes,
87 *sections: BootSectionV2,
88 product_version: str,
89 component_version: str,
90 build_number: int,
91 advanced_params: SBV2xAdvancedParams,
92 flags: int = FLAGS_SHA_PRESENT_BIT | FLAGS_ENCRYPTED_SIGNED_BIT,
93 ) -> None:
94 """Initialize Secure Boot Image V2.1.
95
96 :param kek: key to wrap DEC and MAC keys
97
98 :param product_version: The product version (default: 1.0.0)
99 :param component_version: The component version (default: 1.0.0)
100 :param build_number: The build number value (default: 0)
101
102 :param advanced_params: optional advanced parameters for encryption; it is recommended to use default value
103 :param flags: see flags defined in class.
104 :param sections: Boot sections
105 """
106 self._kek = kek
107 self._dek = advanced_params.dek
108 self._mac = advanced_params.mac
109 self._header = ImageHeaderV2(
110 version="2.1",
111 product_version=product_version,
112 component_version=component_version,
113 build_number=build_number,
114 flags=flags,
115 nonce=advanced_params.nonce,
116 timestamp=advanced_params.timestamp,
117 )
118 self._cert_block: Optional[CertBlockV1] = None
119 self.boot_sections: List[BootSectionV2] = []
120 # ...
121 for section in sections:
122 self.add_boot_section(section)
123
124 @property
125 def header(self) -> ImageHeaderV2:
126 """Return image header."""
127 return self._header
128
129 @property
130 def dek(self) -> bytes:
131 """Data encryption key."""
132 return self._dek
133
134 @property
135 def mac(self) -> bytes:
136 """Message authentication code."""
137 return self._mac
138
139 @property
140 def kek(self) -> bytes:
141 """Return key to wrap DEC and MAC keys."""
142 return self._kek
143
144 @property
145 def cert_block(self) -> Optional[CertBlockV1]:
146 """Return certificate block; None if SB file not signed or block not assigned yet."""
147 return self._cert_block
148
149 @cert_block.setter
150 def cert_block(self, value: CertBlockV1) -> None:
151 """Setter.
152
153 :param value: block to be assigned; None to remove previously assigned block
154 """
155 assert isinstance(value, CertBlockV1)
156 self._cert_block = value
157 self._cert_block.alignment = 16
158
159 @property
160 def signed(self) -> bool:
161 """Return flag whether SB file is signed."""
162 return True # SB2.1 is always signed
163
164 @property
165 def cert_header_size(self) -> int:
166 """Return image raw size (not aligned) for certificate header."""
167 size = ImageHeaderV2.SIZE + self.HEADER_MAC_SIZE
168 size += self.KEY_BLOB_SIZE
169 # Certificates Section
170 cert_blk = self.cert_block
171 if cert_blk:
172 size += cert_blk.raw_size
173 return size
174
175 @property
176 def raw_size(self) -> int:
177 """Return image raw size (not aligned)."""
178 # Header, HMAC and KeyBlob
179 size = ImageHeaderV2.SIZE + self.HEADER_MAC_SIZE
180 size += self.KEY_BLOB_SIZE
181 # Certificates Section
182 cert_blk = self.cert_block
183 if cert_blk:
184 size += cert_blk.raw_size
185 if not self.signed: # pragma: no cover # SB2.1 is always signed
186 raise SPSDKError("Certificate block is not signed")
187 size += cert_blk.signature_size
188 # Boot Sections
189 for boot_section in self.boot_sections:
190 size += boot_section.raw_size
191 return size
192
193 def __len__(self) -> int:
194 return len(self.boot_sections)
195
196 def __getitem__(self, key: int) -> BootSectionV2:
197 return self.boot_sections[key]
198
199 def __setitem__(self, key: int, value: BootSectionV2) -> None:
200 self.boot_sections[key] = value
201
202 def __iter__(self) -> Iterator[BootSectionV2]:
203 return self.boot_sections.__iter__()
204
205 def update(self) -> None:
206 """Update BootImageV21."""
207 if self.boot_sections:
208 self._header.first_boot_section_id = self.boot_sections[0].uid
209 # calculate first boot tag block
210 data_size = self._header.SIZE + self.HEADER_MAC_SIZE + self.KEY_BLOB_SIZE
211 cert_blk = self.cert_block
212 if cert_blk is not None:
213 data_size += cert_blk.raw_size
214 if not self.signed: # pragma: no cover # SB2.1 is always signed
215 raise SPSDKError("Certificate block is not signed")
216 data_size += cert_blk.signature_size
217 self._header.first_boot_tag_block = SecBootBlckSize.to_num_blocks(data_size)
218 # ...
219 self._header.image_blocks = SecBootBlckSize.to_num_blocks(self.raw_size)
220 self._header.header_blocks = SecBootBlckSize.to_num_blocks(self._header.SIZE)
221 self._header.offset_to_certificate_block = (
222 self._header.SIZE + self.HEADER_MAC_SIZE + self.KEY_BLOB_SIZE
223 )
224 # Get HMAC count
225 self._header.max_section_mac_count = 0
226 for boot_sect in self.boot_sections:
227 boot_sect.is_last = True # unified with elftosb
228 self._header.max_section_mac_count += boot_sect.hmac_count
229 # Update certificates block header
230 cert_clk = self.cert_block
231 if cert_clk is not None:
232 cert_clk.header.build_number = self._header.build_number
233 cert_clk.header.image_length = self.cert_header_size
234
235 def __repr__(self) -> str:
236 return f"SB2.1, {'Signed' if self.signed else 'Plain'} "
237
238 def __str__(self) -> str:
239 """Return text description of the instance."""
240 self.update()
241 nfo = "\n"
242 nfo += ":::::::::::::::::::::::::::::::::: IMAGE HEADER ::::::::::::::::::::::::::::::::::::::\n"
243 nfo += str(self._header)
244 if self.cert_block is not None:
245 nfo += "::::::::::::::::::::::::::::::: CERTIFICATES BLOCK ::::::::::::::::::::::::::::::::::::\n"
246 nfo += str(self.cert_block)
247 nfo += "::::::::::::::::::::::::::::::::::: BOOT SECTIONS ::::::::::::::::::::::::::::::::::::\n"
248 for index, section in enumerate(self.boot_sections):
249 nfo += f"[ SECTION: {index} | UID: 0x{section.uid:08X} ]\n"
250 nfo += str(section)
251 return nfo
252
253 def add_boot_section(self, section: BootSectionV2) -> None:
254 """Add new Boot section into image.
255
256 :param section: Boot section to be added
257 :raises SPSDKError: Raised when section is not instance of BootSectionV2 class
258 """
259 if not isinstance(section, BootSectionV2):
260 raise SPSDKError("Section is not instance of BootSectionV2 class")
261 self.boot_sections.append(section)
262
263 # pylint: disable=too-many-locals
264 @classmethod
265 def parse(
266 cls, data: bytes, offset: int = 0, kek: bytes = bytes(), plain_sections: bool = False
267 ) -> "BootImageV21":
268 """Parse image from bytes.
269
270 :param data: Raw data of parsed image
271 :param offset: The offset of input data
272 :param kek: The Key for unwrapping DEK and MAC keys (required)
273 :param plain_sections: Sections are not encrypted; this is used only for debugging,
274 not supported by ROM code
275 :return: BootImageV21 parsed object
276 :raises SPSDKError: raised when header is in incorrect format
277 :raises SPSDKError: raised when signature is incorrect
278 :raises SPSDKError: Raised when kek is empty
279 :raises SPSDKError: raised when header's nonce not present"
280 """
281 if not kek:
282 raise SPSDKError("kek cannot be empty")
283 index = offset
284 header_raw_data = data[index : index + ImageHeaderV2.SIZE]
285 index += ImageHeaderV2.SIZE
286 # Not used right now: hmac_data = data[index: index + cls.HEADER_MAC_SIZE]
287 index += cls.HEADER_MAC_SIZE
288 key_blob = data[index : index + cls.KEY_BLOB_SIZE]
289 index += cls.KEY_BLOB_SIZE
290 key_blob_unwrap = aes_key_unwrap(kek, key_blob[:-8])
291 dek = key_blob_unwrap[:32]
292 mac = key_blob_unwrap[32:]
293 # Parse Header
294 header = ImageHeaderV2.parse(header_raw_data)
295 if header.offset_to_certificate_block != (index - offset):
296 raise SPSDKError("Invalid offset")
297 # Parse Certificate Block
298 cert_block = CertBlockV1.parse(data[index:])
299 index += cert_block.raw_size
300
301 # Verify Signature
302 signature_index = index
303 # The image may contain SHA, in such a case the signature is placed
304 # after SHA. Thus we must shift the index by SHA size.
305 if header.flags & BootImageV21.FLAGS_SHA_PRESENT_BIT:
306 signature_index += BootImageV21.SHA_256_SIZE
307 result = cert_block.verify_data(
308 data[signature_index : signature_index + cert_block.signature_size],
309 data[offset:signature_index],
310 )
311
312 if not result:
313 raise SPSDKError("Verification failed")
314 # Check flags, if 0x8000 bit is set, the SB file contains SHA-256 between
315 # certificate and signature.
316 if header.flags & BootImageV21.FLAGS_SHA_PRESENT_BIT:
317 bootable_section_sha256 = data[index : index + BootImageV21.SHA_256_SIZE]
318 index += BootImageV21.SHA_256_SIZE
319 index += cert_block.signature_size
320 # Check first Boot Section HMAC
321 # Not implemented yet
322 # hmac_data_calc = hmac(mac, data[index + CmdHeader.SIZE: index + CmdHeader.SIZE + ((2) * 32)])
323 # if hmac_data != hmac_data_calc:
324 # raise SPSDKError("HMAC failed")
325 if not header.nonce:
326 raise SPSDKError("Header's nonce not present")
327 counter = Counter(header.nonce)
328 counter.increment(SecBootBlckSize.to_num_blocks(index - offset))
329 boot_section = BootSectionV2.parse(
330 data, index, dek=dek, mac=mac, counter=counter, plain_sect=plain_sections
331 )
332 if header.flags & BootImageV21.FLAGS_SHA_PRESENT_BIT:
333 computed_bootable_section_sha256 = get_hash(
334 data[index:], algorithm=EnumHashAlgorithm.SHA256
335 )
336
337 if bootable_section_sha256 != computed_bootable_section_sha256:
338 raise SPSDKError(
339 desc=(
340 "Error: invalid Bootable section SHA."
341 f"Expected {bootable_section_sha256.decode('utf-8')},"
342 f"got {computed_bootable_section_sha256.decode('utf-8')}"
343 )
344 )
345 adv_params = SBV2xAdvancedParams(
346 dek=dek, mac=mac, nonce=header.nonce, timestamp=header.timestamp
347 )
348 obj = cls(
349 kek=kek,
350 product_version=str(header.product_version),
351 component_version=str(header.component_version),
352 build_number=header.build_number,
353 advanced_params=adv_params,
354 )
355 obj.cert_block = cert_block
356 obj.add_boot_section(boot_section)
357 return obj