Debian Codegraph @

src/nitrokey/trussed/_bootloader/lpc55_upload/utils/crypto/cert_blocks.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 """Module for handling Certificate block."""
9
10 import re
11 from struct import calcsize, unpack_from
12 from typing import TYPE_CHECKING, List, Optional, Union
13
14 from ...crypto.certificate import Certificate
15 from ...exceptions import SPSDKError
16 from ...utils.abstract import BaseClass
17 from ...utils.crypto.rkht import RKHTv1
18 from ...utils.misc import Endianness, align
19
20 if TYPE_CHECKING:
21 from typing_extensions import Self
22
23
24 class CertBlock(BaseClass):
25 """Common general class for various CertBlocks."""
26
27 @property
28 def rkth(self) -> bytes:
29 """Root Key Table Hash 32-byte hash (SHA-256) of SHA-256 hashes of up to four root public keys."""
30 return bytes()
31
32
33 ########################################################################################################################
34 # Certificate Block Header Class
35 ########################################################################################################################
36 class CertBlockHeader(BaseClass):
37 """Certificate block header."""
38
39 FORMAT = "<4s2H6I"
40 SIZE = calcsize(FORMAT)
41 SIGNATURE = b"cert"
42
43 def __init__(self, version: str = "1.0", flags: int = 0, build_number: int = 0) -> None:
44 """Constructor.
45
46 :param version: Version of the certificate in format n.n
47 :param flags: Flags for the Certificate Header
48 :param build_number: of the certificate
49 :raises SPSDKError: When there is invalid version
50 """
51 if not re.match(r"[0-9]+\.[0-9]+", version): # check format of the version: N.N
52 raise SPSDKError("Invalid version")
53 self.version = version
54 self.flags = flags
55 self.build_number = build_number
56 self.image_length = 0
57 self.cert_count = 0
58 self.cert_table_length = 0
59
60 def __repr__(self) -> str:
61 nfo = f"CertBlockHeader: V={self.version}, F={self.flags}, BN={self.build_number}, IL={self.image_length}, "
62 nfo += f"CC={self.cert_count}, CTL={self.cert_table_length}"
63 return nfo
64
65 def __str__(self) -> str:
66 """Info of the certificate header in text form."""
67 nfo = str()
68 nfo += f" CB Version: {self.version}\n"
69 nfo += f" CB Flags: {self.flags}\n"
70 nfo += f" CB Build Number: {self.build_number}\n"
71 nfo += f" CB Image Length: {self.image_length}\n"
72 nfo += f" CB Cert. Count: {self.cert_count}\n"
73 nfo += f" CB Cert. Length: {self.cert_table_length}\n"
74 return nfo
75
76 @classmethod
77 def parse(cls, data: bytes) -> "Self":
78 """Deserialize object from bytes array.
79
80 :param data: Input data as bytes
81 :return: Certificate Header instance
82 :raises SPSDKError: Unexpected size or signature of data
83 """
84 if cls.SIZE > len(data):
85 raise SPSDKError("Incorrect size")
86 (
87 signature,
88 major_version,
89 minor_version,
90 length,
91 flags,
92 build_number,
93 image_length,
94 cert_count,
95 cert_table_length,
96 ) = unpack_from(cls.FORMAT, data)
97 if signature != cls.SIGNATURE:
98 raise SPSDKError("Incorrect signature")
99 if length != cls.SIZE:
100 raise SPSDKError("Incorrect length")
101 obj = cls(
102 version=f"{major_version}.{minor_version}", flags=flags, build_number=build_number
103 )
104 obj.image_length = image_length
105 obj.cert_count = cert_count
106 obj.cert_table_length = cert_table_length
107 return obj
108
109
110 ########################################################################################################################
111 # Certificate Block Class
112 ########################################################################################################################
113 class CertBlockV1(CertBlock):
114 """Certificate block.
115
116 Shared for SB file 2.1 and for MasterBootImage using RSA keys.
117 """
118
119 # default size alignment
120 DEFAULT_ALIGNMENT = 16
121
122 @property
123 def header(self) -> CertBlockHeader:
124 """Certificate block header."""
125 return self._header
126
127 @property
128 def rkh(self) -> List[bytes]:
129 """List of root keys hashes (SHA-256), each hash as 32 bytes."""
130 return self._rkht.rkh_list
131
132 @property
133 def rkth(self) -> bytes:
134 """Root Key Table Hash 32-byte hash (SHA-256) of SHA-256 hashes of up to four root public keys."""
135 return self._rkht.rkth()
136
137 @property
138 def rkth_fuses(self) -> List[int]:
139 """List of RKHT fuses, ordered from highest bit to lowest.
140
141 Note: Returned values are in format that should be passed for blhost
142 """
143 result = []
144 rkht = self.rkth
145 while rkht:
146 fuse = int.from_bytes(rkht[:4], byteorder=Endianness.LITTLE.value)
147 result.append(fuse)
148 rkht = rkht[4:]
149 return result
150
151 @property
152 def certificates(self) -> List[Certificate]:
153 """List of certificates in header.
154
155 First certificate is root certificate and followed by optional chain certificates
156 """
157 return self._cert
158
159 @property
160 def signature_size(self) -> int:
161 """Size of the signature in bytes."""
162 return len(
163 self.certificates[0].signature
164 ) # The certificate is self signed, return size of its signature
165
166 @property
167 def rkh_index(self) -> Optional[int]:
168 """Index of the Root Key Hash that matches the certificate; None if does not match."""
169 if self._cert:
170 rkh = self._cert[0].public_key_hash()
171 for index, value in enumerate(self.rkh):
172 if rkh == value:
173 return index
174 return None
175
176 @property
177 def alignment(self) -> int:
178 """Alignment of the binary output, by default it is DEFAULT_ALIGNMENT but can be customized."""
179 return self._alignment
180
181 @alignment.setter
182 def alignment(self, value: int) -> None:
183 """Setter.
184
185 :param value: new alignment
186 :raises SPSDKError: When there is invalid alignment
187 """
188 if value <= 0:
189 raise SPSDKError("Invalid alignment")
190 self._alignment = value
191
192 @property
193 def raw_size(self) -> int:
194 """Aligned size of the certificate block."""
195 size = CertBlockHeader.SIZE
196 size += self._header.cert_table_length
197 size += self._rkht.RKH_SIZE * self._rkht.RKHT_SIZE
198 return align(size, self.alignment)
199
200 @property
201 def expected_size(self) -> int:
202 """Expected size of binary block."""
203 return self.raw_size
204
205 @property
206 def image_length(self) -> int:
207 """Image length in bytes."""
208 return self._header.image_length
209
210 @image_length.setter
211 def image_length(self, value: int) -> None:
212 """Setter.
213
214 :param value: new image length
215 :raises SPSDKError: When there is invalid image length
216 """
217 if value <= 0:
218 raise SPSDKError("Invalid image length")
219 self._header.image_length = value
220
221 def __init__(self, version: str = "1.0", flags: int = 0, build_number: int = 0) -> None:
222 """Constructor.
223
224 :param version: of the certificate in format n.n
225 :param flags: Flags for the Certificate Block Header
226 :param build_number: of the certificate
227 """
228 self._header = CertBlockHeader(version, flags, build_number)
229 self._rkht: RKHTv1 = RKHTv1([])
230 self._cert: List[Certificate] = []
231 self._alignment = self.DEFAULT_ALIGNMENT
232
233 def __len__(self) -> int:
234 return len(self._cert)
235
236 def add_certificate(self, cert: Union[bytes, Certificate]) -> None:
237 """Add certificate.
238
239 First call adds root certificate. Additional calls add chain certificates.
240
241 :param cert: The certificate itself in DER format
242 :raises SPSDKError: If certificate cannot be added
243 """
244 if isinstance(cert, bytes):
245 cert_obj = Certificate.parse(cert)
246 elif isinstance(cert, Certificate):
247 cert_obj = cert
248 else:
249 raise SPSDKError("Invalid parameter type (cert)")
250 if cert_obj.version.name != "v3":
251 raise SPSDKError("Expected certificate v3 but received: " + cert_obj.version.name)
252 if self._cert: # chain certificate?
253 last_cert = self._cert[-1] # verify that it is signed by parent key
254 if not cert_obj.validate(last_cert):
255 raise SPSDKError("Chain certificate cannot be verified using parent public key")
256 else: # root certificate
257 if not cert_obj.self_signed:
258 raise SPSDKError(f"Root certificate must be self-signed.\n{str(cert_obj)}")
259 self._cert.append(cert_obj)
260 self._header.cert_count += 1
261 self._header.cert_table_length += cert_obj.raw_size + 4
262
263 def __repr__(self) -> str:
264 return str(self._header)
265
266 def __str__(self) -> str:
267 """Text info about certificate block."""
268 nfo = str(self.header)
269 nfo += " Public Root Keys Hash e.g. RKH (SHA256):\n"
270 rkh_index = self.rkh_index
271 for index, root_key in enumerate(self._rkht.rkh_list):
272 nfo += (
273 f" {index}) {root_key.hex().upper()} {'<- Used' if index == rkh_index else ''}\n"
274 )
275 rkth = self.rkth
276 nfo += f" RKTH (SHA256): {rkth.hex().upper()}\n"
277 for index, fuse in enumerate(self.rkth_fuses):
278 bit_ofs = (len(rkth) - 4 * index) * 8
279 nfo += f" - RKTH fuse [{bit_ofs:03}:{bit_ofs - 31:03}]: {fuse:08X}\n"
280 for index, cert in enumerate(self._cert):
281 nfo += " Root Certificate:\n" if index == 0 else f" Certificate {index}:\n"
282 nfo += str(cert)
283 return nfo
284
285 def verify_data(self, signature: bytes, data: bytes) -> bool:
286 """Signature verification.
287
288 :param signature: to be verified
289 :param data: that has been signed
290 :return: True if the data signature can be confirmed using the certificate; False otherwise
291 """
292 cert = self._cert[-1]
293 pub_key = cert.get_public_key()
294 return pub_key.verify_signature(signature=signature, data=data)
295
296 @classmethod
297 def parse(cls, data: bytes) -> "Self":
298 """Deserialize CertBlockV1 from binary file.
299
300 :param data: Binary data
301 :return: Certificate Block instance
302 :raises SPSDKError: Length of the data doesn't match Certificate Block length
303 """
304 header = CertBlockHeader.parse(data)
305 offset = CertBlockHeader.SIZE
306 if len(data) < (header.cert_table_length + (RKHTv1.RKHT_SIZE * RKHTv1.RKH_SIZE)):
307 raise SPSDKError("Length of the data doesn't match Certificate Block length")
308 obj = cls(version=header.version, flags=header.flags, build_number=header.build_number)
309 for _ in range(header.cert_count):
310 cert_len = unpack_from("<I", data, offset)[0]
311 offset += 4
312 cert_obj = Certificate.parse(data[offset : offset + cert_len])
313 obj.add_certificate(cert_obj)
314 offset += cert_len
315 obj._rkht = RKHTv1.parse(data[offset : offset + (RKHTv1.RKH_SIZE * RKHTv1.RKHT_SIZE)])
316 return obj