Debian Codegraph @

src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/mcuboot.py

raw
1 #!/usr/bin/env python
2 # -*- coding: UTF-8 -*-
3 #
4 # Copyright 2016-2018 Martin Olejar
5 # Copyright 2019-2024 NXP
6 #
7 # SPDX-License-Identifier: BSD-3-Clause
8
9 """Module for communication with the bootloader."""
10
11 import logging
12 import struct
13 import time
14 from types import TracebackType
15 from typing import Callable, Dict, List, Optional, Sequence, Type
16
17 from ..exceptions import SPSDKError
18 from ..mboot.protocol.base import MbootProtocolBase
19 from ..utils.interfaces.device.usb_device import UsbDevice
20 from .commands import (
21 CmdPacket,
22 CmdResponse,
23 CommandFlag,
24 CommandTag,
25 FlashReadOnceResponse,
26 FlashReadResourceResponse,
27 GenerateKeyBlobSelect,
28 GenericResponse,
29 GetPropertyResponse,
30 KeyProvisioningResponse,
31 KeyProvOperation,
32 NoResponse,
33 ReadMemoryResponse,
34 TrustProvDevHsmDsc,
35 TrustProvisioningResponse,
36 TrustProvOperation,
37 TrustProvWpc,
38 )
39 from .error_codes import StatusCode, stringify_status_code
40 from .exceptions import (
41 McuBootCommandError,
42 McuBootConnectionError,
43 McuBootDataAbortError,
44 McuBootError,
45 )
46 from .memories import ExtMemId, ExtMemRegion, FlashRegion, MemoryRegion, RamRegion
47 from .properties import PropertyTag, PropertyValueBase, Version, parse_property_value
48
49 logger = logging.getLogger(__name__)
50
51
52 ########################################################################################################################
53 # McuBoot Class
54 ########################################################################################################################
55 class McuBoot: # pylint: disable=too-many-public-methods
56 """Class for communication with the bootloader."""
57
58 DEFAULT_MAX_PACKET_SIZE = 32
59
60 @property
61 def status_code(self) -> int:
62 """Return status code of the last operation."""
63 return self._status_code
64
65 @property
66 def status_string(self) -> str:
67 """Return status string."""
68 return stringify_status_code(self._status_code)
69
70 @property
71 def is_opened(self) -> bool:
72 """Return True if the device is open."""
73 return self._interface.is_opened
74
75 def __init__(self, interface: MbootProtocolBase, cmd_exception: bool = False) -> None:
76 """Initialize the McuBoot object.
77
78 :param interface: The instance of communication interface class
79 :param cmd_exception: True to throw McuBootCommandError on any error;
80 False to set status code only
81 Note: some operation might raise McuBootCommandError is all cases
82
83 """
84 self._cmd_exception = cmd_exception
85 self._status_code = StatusCode.SUCCESS.tag
86 self._interface = interface
87 self.reopen = False
88 self.enable_data_abort = False
89 self._pause_point: Optional[int] = None
90
91 def __enter__(self) -> "McuBoot":
92 self.reopen = True
93 self.open()
94 return self
95
96 def __exit__(
97 self,
98 exception_type: Optional[Type[Exception]] = None,
99 exception_value: Optional[Exception] = None,
100 traceback: Optional[TracebackType] = None,
101 ) -> None:
102 self.close()
103
104 def _process_cmd(self, cmd_packet: CmdPacket) -> CmdResponse:
105 """Process Command.
106
107 :param cmd_packet: Command Packet
108 :return: command response derived from the CmdResponse
109 :raises McuBootConnectionError: Timeout Error
110 :raises McuBootCommandError: Error during command execution on the target
111 """
112 if not self.is_opened:
113 logger.info("TX: Device not opened")
114 raise McuBootConnectionError("Device not opened")
115
116 logger.debug(f"TX-PACKET: {str(cmd_packet)}")
117
118 try:
119 self._interface.write_command(cmd_packet)
120 response = self._interface.read()
121 except TimeoutError:
122 self._status_code = StatusCode.NO_RESPONSE.tag
123 logger.debug("RX-PACKET: No Response, Timeout Error !")
124 response = NoResponse(cmd_tag=cmd_packet.header.tag)
125
126 assert isinstance(response, CmdResponse)
127 logger.debug(f"RX-PACKET: {str(response)}")
128 self._status_code = response.status
129
130 if self._cmd_exception and self._status_code != StatusCode.SUCCESS:
131 raise McuBootCommandError(CommandTag.get_label(cmd_packet.header.tag), response.status)
132 logger.info(f"CMD: Status: {self.status_string}")
133 return response
134
135 def _read_data(
136 self,
137 cmd_tag: CommandTag,
138 length: int,
139 progress_callback: Optional[Callable[[int, int], None]] = None,
140 ) -> bytes:
141 """Read data from device.
142
143 :param cmd_tag: Tag indicating the read command.
144 :param length: Length of data to read
145 :param progress_callback: Callback for updating the caller about the progress
146 :raises McuBootConnectionError: Timeout error or a problem opening the interface
147 :raises McuBootCommandError: Error during command execution on the target
148 :return: Data read from the device
149 """
150 data = b""
151
152 if not self.is_opened:
153 logger.error("RX: Device not opened")
154 raise McuBootConnectionError("Device not opened")
155 while True:
156 try:
157 response = self._interface.read()
158 except McuBootDataAbortError as e:
159 logger.error(f"RX: {e}")
160 logger.info("Try increasing the timeout value")
161 response = self._interface.read()
162 except TimeoutError:
163 self._status_code = StatusCode.NO_RESPONSE.tag
164 logger.error("RX: No Response, Timeout Error !")
165 response = NoResponse(cmd_tag=cmd_tag.tag)
166 break
167
168 if isinstance(response, bytes):
169 data += response
170 if progress_callback:
171 progress_callback(len(data), length)
172
173 elif isinstance(response, GenericResponse):
174 logger.debug(f"RX-PACKET: {str(response)}")
175 self._status_code = response.status
176 if response.cmd_tag == cmd_tag:
177 break
178
179 if len(data) < length or self.status_code != StatusCode.SUCCESS:
180 status_info = (
181 StatusCode.get_label(self._status_code)
182 if self._status_code in StatusCode.tags()
183 else f"0x{self._status_code:08X}"
184 )
185 logger.debug(f"CMD: Received {len(data)} from {length} Bytes, {status_info}")
186 if self._cmd_exception:
187 assert isinstance(response, CmdResponse)
188 raise McuBootCommandError(cmd_tag.label, response.status)
189 else:
190 logger.info(f"CMD: Successfully Received {len(data)} from {length} Bytes")
191
192 return data[:length] if len(data) > length else data
193
194 def _send_data(
195 self,
196 cmd_tag: CommandTag,
197 data: List[bytes],
198 progress_callback: Optional[Callable[[int, int], None]] = None,
199 ) -> bool:
200 """Send Data part of specific command.
201
202 :param cmd_tag: Tag indicating the command
203 :param data: List of data chunks to send
204 :param progress_callback: Callback for updating the caller about the progress
205 :raises McuBootConnectionError: Timeout error
206 :raises McuBootCommandError: Error during command execution on the target
207 :return: True if the operation is successful
208 """
209 if not self.is_opened:
210 logger.info("TX: Device Disconnected")
211 raise McuBootConnectionError("Device Disconnected !")
212
213 total_sent = 0
214 total_to_send = sum(len(chunk) for chunk in data)
215 # this difference is applicable for load-image and program-aeskey commands
216 expect_response = cmd_tag != CommandTag.NO_COMMAND
217 self._interface.allow_abort = self.enable_data_abort
218 try:
219 for data_chunk in data:
220 self._interface.write_data(data_chunk)
221 total_sent += len(data_chunk)
222 if progress_callback:
223 progress_callback(total_sent, total_to_send)
224 if self._pause_point and total_sent > self._pause_point:
225 time.sleep(0.1)
226 self._pause_point = None
227
228 if expect_response:
229 response = self._interface.read()
230 except TimeoutError as e:
231 self._status_code = StatusCode.NO_RESPONSE.tag
232 logger.error("RX: No Response, Timeout Error !")
233 raise McuBootConnectionError("No Response from Device") from e
234 except SPSDKError as e:
235 logger.error(f"RX: {e}")
236 if expect_response:
237 response = self._interface.read()
238 else:
239 self._status_code = StatusCode.SENDING_OPERATION_CONDITION_ERROR.tag
240
241 if expect_response:
242 assert isinstance(response, CmdResponse)
243 logger.debug(f"RX-PACKET: {str(response)}")
244 self._status_code = response.status
245 if response.status != StatusCode.SUCCESS:
246 status_info = (
247 StatusCode.get_label(self._status_code)
248 if self._status_code in StatusCode.tags()
249 else f"0x{self._status_code:08X}"
250 )
251 logger.debug(f"CMD: Send Error, {status_info}")
252 if self._cmd_exception:
253 raise McuBootCommandError(cmd_tag.label, response.status)
254 return False
255
256 logger.info(f"CMD: Successfully Send {total_sent} out of {total_to_send} Bytes")
257 return total_sent == total_to_send
258
259 def _get_max_packet_size(self) -> int:
260 """Get max packet size.
261
262 :return int: max packet size in B
263 """
264 packet_size_property = None
265 try:
266 packet_size_property = self.get_property(prop_tag=PropertyTag.MAX_PACKET_SIZE)
267 except McuBootError:
268 pass
269 if packet_size_property is None:
270 packet_size_property = [self.DEFAULT_MAX_PACKET_SIZE]
271 logger.warning(
272 f"CMD: Unable to get MAX PACKET SIZE, using: {self.DEFAULT_MAX_PACKET_SIZE}"
273 )
274 return packet_size_property[0]
275
276 def _split_data(self, data: bytes) -> List[bytes]:
277 """Split data to send if necessary.
278
279 :param data: Data to send
280 :return: List of data splices
281 """
282 if not self._interface.need_data_split:
283 return [data]
284 max_packet_size = self._get_max_packet_size()
285 logger.info(f"CMD: Max Packet Size = {max_packet_size}")
286 return [data[i : i + max_packet_size] for i in range(0, len(data), max_packet_size)]
287
288 def open(self) -> None:
289 """Connect to the device."""
290 logger.info(f"Connect: {str(self._interface)}")
291 self._interface.open()
292
293 def close(self) -> None:
294 """Disconnect from the device."""
295 logger.info(f"Closing: {str(self._interface)}")
296 self._interface.close()
297
298 def get_property_list(self) -> List[PropertyValueBase]:
299 """Get a list of available properties.
300
301 :return: List of available properties.
302 :raises McuBootCommandError: Failure to read properties list
303 """
304 property_list: List[PropertyValueBase] = []
305 for property_tag in PropertyTag:
306 try:
307 values = self.get_property(property_tag)
308 except McuBootCommandError:
309 continue
310
311 if values:
312 prop = parse_property_value(property_tag.tag, values)
313 assert prop is not None, "Property values cannot be parsed"
314 property_list.append(prop)
315
316 self._status_code = StatusCode.SUCCESS.tag
317 if not property_list:
318 self._status_code = StatusCode.FAIL.tag
319 if self._cmd_exception:
320 raise McuBootCommandError("GetPropertyList", self.status_code)
321
322 return property_list
323
324 def _get_internal_flash(self) -> List[FlashRegion]:
325 """Get information about the internal flash.
326
327 :return: list of FlashRegion objects
328 """
329 index = 0
330 mdata: List[FlashRegion] = []
331 start_address = 0
332 while True:
333 try:
334 values = self.get_property(PropertyTag.FLASH_START_ADDRESS, index)
335 if not values:
336 break
337 if index == 0:
338 start_address = values[0]
339 elif start_address == values[0]:
340 break
341 region_start = values[0]
342 values = self.get_property(PropertyTag.FLASH_SIZE, index)
343 if not values:
344 break
345 region_size = values[0]
346 values = self.get_property(PropertyTag.FLASH_SECTOR_SIZE, index)
347 if not values:
348 break
349 region_sector_size = values[0]
350 mdata.append(
351 FlashRegion(
352 index=index,
353 start=region_start,
354 size=region_size,
355 sector_size=region_sector_size,
356 )
357 )
358 index += 1
359 except McuBootCommandError:
360 break
361
362 return mdata
363
364 def _get_internal_ram(self) -> List[RamRegion]:
365 """Get information about the internal RAM.
366
367 :return: list of RamRegion objects
368 """
369 index = 0
370 mdata: List[RamRegion] = []
371 start_address = 0
372 while True:
373 try:
374 values = self.get_property(PropertyTag.RAM_START_ADDRESS, index)
375 if not values:
376 break
377 if index == 0:
378 start_address = values[0]
379 elif start_address == values[0]:
380 break
381 start = values[0]
382 values = self.get_property(PropertyTag.RAM_SIZE, index)
383 if not values:
384 break
385 size = values[0]
386 mdata.append(RamRegion(index=index, start=start, size=size))
387 index += 1
388 except McuBootCommandError:
389 break
390
391 return mdata
392
393 def _get_ext_memories(self) -> List[ExtMemRegion]:
394 """Get information about the external memories.
395
396 :return: list of ExtMemRegion objects supported by the device
397 :raises SPSDKError: If no response to get property command
398 :raises SPSDKError: Other Error
399 """
400 ext_mem_list: List[ExtMemRegion] = []
401 ext_mem_ids: Sequence[int] = ExtMemId.tags()
402 try:
403 values = self.get_property(PropertyTag.CURRENT_VERSION)
404 except McuBootCommandError:
405 values = None
406
407 if not values and self._status_code == StatusCode.UNKNOWN_PROPERTY:
408 self._status_code = StatusCode.SUCCESS.tag
409 return ext_mem_list
410
411 if not values:
412 raise SPSDKError("No response to get property command")
413
414 if Version(values[0]) <= Version("2.0.0"):
415 # old versions mboot support only Quad SPI memory
416 ext_mem_ids = [ExtMemId.QUAD_SPI0.tag]
417
418 for mem_id in ext_mem_ids:
419 try:
420 values = self.get_property(PropertyTag.EXTERNAL_MEMORY_ATTRIBUTES, mem_id)
421 except McuBootCommandError:
422 values = None
423
424 if not values: # pragma: no cover # corner-cases are currently untestable without HW
425 if self._status_code == StatusCode.UNKNOWN_PROPERTY:
426 break
427
428 if self._status_code in [
429 StatusCode.QSPI_NOT_CONFIGURED,
430 StatusCode.INVALID_ARGUMENT,
431 ]:
432 continue
433
434 if self._status_code == StatusCode.MEMORY_NOT_CONFIGURED:
435 ext_mem_list.append(ExtMemRegion(mem_id=mem_id))
436
437 if self._status_code == StatusCode.SUCCESS:
438 raise SPSDKError("Other Error")
439
440 else:
441 ext_mem_list.append(ExtMemRegion(mem_id=mem_id, raw_values=values))
442 return ext_mem_list
443
444 def get_memory_list(self) -> dict[str, Sequence[MemoryRegion]]:
445 """Get list of embedded memories.
446
447 :return: dict, with the following keys: internal_flash (optional) - list ,
448 internal_ram (optional) - list, external_mems (optional) - list
449 :raises McuBootCommandError: Error reading the memory list
450 """
451 memory_list: Dict[str, Sequence[MemoryRegion]] = {}
452
453 # Internal FLASH
454 mdata = self._get_internal_flash()
455 if mdata:
456 memory_list["internal_flash"] = mdata
457
458 # Internal RAM
459 ram_data = self._get_internal_ram()
460 if mdata:
461 memory_list["internal_ram"] = ram_data
462
463 # External Memories
464 ext_mem_list = self._get_ext_memories()
465 if ext_mem_list:
466 memory_list["external_mems"] = ext_mem_list
467
468 self._status_code = StatusCode.SUCCESS.tag
469 if not memory_list:
470 self._status_code = StatusCode.FAIL.tag
471 if self._cmd_exception:
472 raise McuBootCommandError("GetMemoryList", self.status_code)
473
474 return memory_list
475
476 def flash_erase_all(self, mem_id: int = 0) -> bool:
477 """Erase complete flash memory without recovering flash security section.
478
479 :param mem_id: Memory ID
480 :return: False in case of any problem; True otherwise
481 """
482 logger.info(f"CMD: FlashEraseAll(mem_id={mem_id})")
483 cmd_packet = CmdPacket(CommandTag.FLASH_ERASE_ALL, CommandFlag.NONE.tag, mem_id)
484 response = self._process_cmd(cmd_packet)
485 return response.status == StatusCode.SUCCESS
486
487 def flash_erase_region(self, address: int, length: int, mem_id: int = 0) -> bool:
488 """Erase specified range of flash.
489
490 :param address: Start address
491 :param length: Count of bytes
492 :param mem_id: Memory ID
493 :return: False in case of any problem; True otherwise
494 """
495 logger.info(
496 f"CMD: FlashEraseRegion(address=0x{address:08X}, length={length}, mem_id={mem_id})"
497 )
498 mem_id = _clamp_down_memory_id(memory_id=mem_id)
499 cmd_packet = CmdPacket(
500 CommandTag.FLASH_ERASE_REGION, CommandFlag.NONE.tag, address, length, mem_id
501 )
502 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
503
504 def read_memory(
505 self,
506 address: int,
507 length: int,
508 mem_id: int = 0,
509 progress_callback: Optional[Callable[[int, int], None]] = None,
510 fast_mode: bool = False,
511 ) -> Optional[bytes]:
512 """Read data from MCU memory.
513
514 :param address: Start address
515 :param length: Count of bytes
516 :param mem_id: Memory ID
517 :param fast_mode: Fast mode for USB-HID data transfer, not reliable !!!
518 :param progress_callback: Callback for updating the caller about the progress
519 :return: Data read from the memory; None in case of a failure
520 """
521 logger.info(f"CMD: ReadMemory(address=0x{address:08X}, length={length}, mem_id={mem_id})")
522 mem_id = _clamp_down_memory_id(memory_id=mem_id)
523
524 # workaround for better USB-HID reliability
525 if isinstance(self._interface.device, UsbDevice) and not fast_mode:
526 payload_size = self._get_max_packet_size()
527 packets = length // payload_size
528 remainder = length % payload_size
529 if remainder:
530 packets += 1
531
532 data = b""
533
534 for idx in range(packets):
535 if idx == packets - 1 and remainder:
536 data_len = remainder
537 else:
538 data_len = payload_size
539
540 cmd_packet = CmdPacket(
541 CommandTag.READ_MEMORY,
542 CommandFlag.NONE.tag,
543 address + idx * payload_size,
544 data_len,
545 mem_id,
546 )
547 cmd_response = self._process_cmd(cmd_packet)
548 if cmd_response.status == StatusCode.SUCCESS:
549 data += self._read_data(CommandTag.READ_MEMORY, data_len)
550 if progress_callback:
551 progress_callback(len(data), length)
552 if self._status_code == StatusCode.NO_RESPONSE:
553 logger.warning(f"CMD: NO RESPONSE, received {len(data)}/{length} B")
554 return data
555 else:
556 return b""
557
558 return data
559
560 cmd_packet = CmdPacket(
561 CommandTag.READ_MEMORY, CommandFlag.NONE.tag, address, length, mem_id
562 )
563 cmd_response = self._process_cmd(cmd_packet)
564 if cmd_response.status == StatusCode.SUCCESS:
565 assert isinstance(cmd_response, ReadMemoryResponse)
566 return self._read_data(CommandTag.READ_MEMORY, cmd_response.length, progress_callback)
567 return None
568
569 def write_memory(
570 self,
571 address: int,
572 data: bytes,
573 mem_id: int = 0,
574 progress_callback: Optional[Callable[[int, int], None]] = None,
575 ) -> bool:
576 """Write data into MCU memory.
577
578 :param address: Start address
579 :param data: List of bytes
580 :param progress_callback: Callback for updating the caller about the progress
581 :param mem_id: Memory ID, see ExtMemId; additionally use `0` for internal memory
582 :return: False in case of any problem; True otherwise
583 """
584 logger.info(
585 f"CMD: WriteMemory(address=0x{address:08X}, length={len(data)}, mem_id={mem_id})"
586 )
587 data_chunks = self._split_data(data=data)
588 mem_id = _clamp_down_memory_id(memory_id=mem_id)
589 cmd_packet = CmdPacket(
590 CommandTag.WRITE_MEMORY, CommandFlag.HAS_DATA_PHASE.tag, address, len(data), mem_id
591 )
592 if self._process_cmd(cmd_packet).status == StatusCode.SUCCESS:
593 return self._send_data(CommandTag.WRITE_MEMORY, data_chunks, progress_callback)
594 return False
595
596 def fill_memory(self, address: int, length: int, pattern: int = 0xFFFFFFFF) -> bool:
597 """Fill MCU memory with specified pattern.
598
599 :param address: Start address (must be word aligned)
600 :param length: Count of words (must be word aligned)
601 :param pattern: Count of wrote bytes
602 :return: False in case of any problem; True otherwise
603 """
604 logger.info(
605 f"CMD: FillMemory(address=0x{address:08X}, length={length}, pattern=0x{pattern:08X})"
606 )
607 cmd_packet = CmdPacket(
608 CommandTag.FILL_MEMORY, CommandFlag.NONE.tag, address, length, pattern
609 )
610 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
611
612 def flash_security_disable(self, backdoor_key: bytes) -> bool:
613 """Disable flash security by using of backdoor key.
614
615 :param backdoor_key: The key value as array of 8 bytes
616 :return: False in case of any problem; True otherwise
617 :raises McuBootError: If the backdoor_key is not 8 bytes long
618 """
619 if len(backdoor_key) != 8:
620 raise McuBootError("Backdoor key must by 8 bytes long")
621 logger.info(f"CMD: FlashSecurityDisable(backdoor_key={backdoor_key!r})")
622 key_high = backdoor_key[0:4][::-1]
623 key_low = backdoor_key[4:8][::-1]
624 cmd_packet = CmdPacket(
625 CommandTag.FLASH_SECURITY_DISABLE, CommandFlag.NONE.tag, data=key_high + key_low
626 )
627 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
628
629 def get_property(self, prop_tag: PropertyTag, index: int = 0) -> Optional[List[int]]:
630 """Get specified property value.
631
632 :param prop_tag: Property TAG (see Properties Enum)
633 :param index: External memory ID or internal memory region index (depends on property type)
634 :return: list integers representing the property; None in case no response from device
635 :raises McuBootError: If received invalid get-property response
636 """
637 logger.info(f"CMD: GetProperty({prop_tag.label}, index={index!r})")
638 cmd_packet = CmdPacket(CommandTag.GET_PROPERTY, CommandFlag.NONE.tag, prop_tag.tag, index)
639 cmd_response = self._process_cmd(cmd_packet)
640 if cmd_response.status == StatusCode.SUCCESS:
641 if isinstance(cmd_response, GetPropertyResponse):
642 return cmd_response.values
643 raise McuBootError(f"Received invalid get-property response: {str(cmd_response)}")
644 return None
645
646 def set_property(self, prop_tag: PropertyTag, value: int) -> bool:
647 """Set value of specified property.
648
649 :param prop_tag: Property TAG (see Property enumerator)
650 :param value: The value of selected property
651 :return: False in case of any problem; True otherwise
652 """
653 logger.info(f"CMD: SetProperty({prop_tag.label}, value=0x{value:08X})")
654 cmd_packet = CmdPacket(CommandTag.SET_PROPERTY, CommandFlag.NONE.tag, prop_tag.tag, value)
655 cmd_response = self._process_cmd(cmd_packet)
656 return cmd_response.status == StatusCode.SUCCESS
657
658 def receive_sb_file(
659 self,
660 data: bytes,
661 progress_callback: Optional[Callable[[int, int], None]] = None,
662 check_errors: bool = False,
663 ) -> bool:
664 """Receive SB file.
665
666 :param data: SB file data
667 :param progress_callback: Callback for updating the caller about the progress
668 :param check_errors: Check for ABORT_FRAME (and related errors) on USB interface between data packets.
669 When this parameter is set to `False` significantly improves USB transfer speed (cca 20x)
670 However, the final status code might be misleading (original root cause may get overridden)
671 In case `receive-sb-file` fails, re-run the operation with this flag set to `True`
672 :return: False in case of any problem; True otherwise
673 """
674 logger.info(f"CMD: ReceiveSBfile(data_length={len(data)})")
675 data_chunks = self._split_data(data=data)
676 cmd_packet = CmdPacket(
677 CommandTag.RECEIVE_SB_FILE, CommandFlag.HAS_DATA_PHASE.tag, len(data)
678 )
679 cmd_response = self._process_cmd(cmd_packet)
680 if cmd_response.status == StatusCode.SUCCESS:
681 self.enable_data_abort = check_errors
682 if isinstance(self._interface.device, UsbDevice):
683 try:
684 # pylint: disable=import-outside-toplevel # import only if needed to save time
685 from ..sbfile.sb2.headers import ImageHeaderV2
686
687 sb2_header = ImageHeaderV2.parse(data=data)
688 self._pause_point = sb2_header.first_boot_tag_block * 16
689 except SPSDKError:
690 pass
691 # Deactivated for pynitrokey
692 # try:
693 # # pylint: disable=import-outside-toplevel # import only if needed to save time
694 # from spsdk.sbfile.sb31.images import SecureBinary31Header
695
696 # sb3_header = SecureBinary31Header.parse(data=data)
697 # self._pause_point = sb3_header.image_total_length
698 # except SPSDKError:
699 # pass
700 result = self._send_data(CommandTag.RECEIVE_SB_FILE, data_chunks, progress_callback)
701 self.enable_data_abort = False
702 return result
703 return False
704
705 def execute(self, address: int, argument: int, sp: int) -> bool: # pylint: disable=invalid-name
706 """Execute program on a given address using the stack pointer.
707
708 :param address: Jump address (must be word aligned)
709 :param argument: Function arguments address
710 :param sp: Stack pointer address
711 :return: False in case of any problem; True otherwise
712 """
713 logger.info(
714 f"CMD: Execute(address=0x{address:08X}, argument=0x{argument:08X}, SP=0x{sp:08X})"
715 )
716 cmd_packet = CmdPacket(CommandTag.EXECUTE, CommandFlag.NONE.tag, address, argument, sp)
717 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
718
719 def call(self, address: int, argument: int) -> bool:
720 """Fill MCU memory with specified pattern.
721
722 :param address: Call address (must be word aligned)
723 :param argument: Function arguments address
724 :return: False in case of any problem; True otherwise
725 """
726 logger.info(f"CMD: Call(address=0x{address:08X}, argument=0x{argument:08X})")
727 cmd_packet = CmdPacket(CommandTag.CALL, CommandFlag.NONE.tag, address, argument)
728 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
729
730 def reset(self, timeout: int = 2000, reopen: bool = True) -> bool:
731 """Reset MCU and reconnect if enabled.
732
733 :param timeout: The maximal waiting time in [ms] for reopen connection
734 :param reopen: True for reopen connection after HW reset else False
735 :return: False in case of any problem; True otherwise
736 :raises McuBootError: if reopen is not supported
737 :raises McuBootConnectionError: Failure to reopen the device
738 """
739 logger.info("CMD: Reset MCU")
740 cmd_packet = CmdPacket(CommandTag.RESET, CommandFlag.NONE.tag)
741 ret_val = False
742 status = self._process_cmd(cmd_packet).status
743 self.close()
744 ret_val = True
745
746 if status not in [StatusCode.NO_RESPONSE, StatusCode.SUCCESS]:
747 ret_val = False
748 if self._cmd_exception:
749 raise McuBootConnectionError("Reset command failed")
750
751 if status == StatusCode.NO_RESPONSE:
752 logger.warning("Did not receive response from reset command, ignoring it")
753 self._status_code = StatusCode.SUCCESS.tag
754
755 if reopen:
756 if not self.reopen:
757 raise McuBootError("reopen is not supported")
758 time.sleep(timeout / 1000)
759 try:
760 self.open()
761 except SPSDKError as e:
762 ret_val = False
763 if self._cmd_exception:
764 raise McuBootConnectionError("reopen failed") from e
765
766 return ret_val
767
768 def flash_erase_all_unsecure(self) -> bool:
769 """Erase complete flash memory and recover flash security section.
770
771 :return: False in case of any problem; True otherwise
772 """
773 logger.info("CMD: FlashEraseAllUnsecure")
774 cmd_packet = CmdPacket(CommandTag.FLASH_ERASE_ALL_UNSECURE, CommandFlag.NONE.tag)
775 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
776
777 def efuse_read_once(self, index: int) -> Optional[int]:
778 """Read from MCU flash program once region.
779
780 :param index: Start index
781 :return: read value (32-bit int); None if operation failed
782 """
783 logger.info(f"CMD: FlashReadOnce(index={index})")
784 cmd_packet = CmdPacket(CommandTag.FLASH_READ_ONCE, CommandFlag.NONE.tag, index, 4)
785 cmd_response = self._process_cmd(cmd_packet)
786 if cmd_response.status == StatusCode.SUCCESS:
787 assert isinstance(cmd_response, FlashReadOnceResponse)
788 return cmd_response.values[0]
789 return None
790
791 def efuse_program_once(self, index: int, value: int, verify: bool = False) -> bool:
792 """Write into MCU once program region (OCOTP).
793
794 :param index: Start index
795 :param value: Int value (4 bytes long)
796 :param verify: Verify that data were written (by comparing value as bitmask)
797 :return: False in case of any problem; True otherwise
798 """
799 logger.info(
800 f"CMD: FlashProgramOnce(index={index}, value=0x{value:X}) "
801 f"with{'' if verify else 'out'} verification."
802 )
803 cmd_packet = CmdPacket(CommandTag.FLASH_PROGRAM_ONCE, CommandFlag.NONE.tag, index, 4, value)
804 cmd_response = self._process_cmd(cmd_packet)
805 if cmd_response.status != StatusCode.SUCCESS:
806 return False
807 if verify:
808 read_value = self.efuse_read_once(index=index & ((1 << 24) - 1))
809 if read_value is None:
810 return False
811 # We check only a bitmask, because OTP allows to burn individual bits separately
812 # Some other bits may have been already written
813 if read_value & value == value:
814 return True
815 # It may happen that ROM will not report error when attempting to write into locked OTP
816 # In such case we substitute the original SUCCESS code with custom-made OTP_VERIFY_FAIL
817 self._status_code = StatusCode.OTP_VERIFY_FAIL.tag
818 return False
819 return cmd_response.status == StatusCode.SUCCESS
820
821 def flash_read_once(self, index: int, count: int = 4) -> Optional[bytes]:
822 """Read from MCU flash program once region (max 8 bytes).
823
824 :param index: Start index
825 :param count: Count of bytes
826 :return: Data read; None in case of an failure
827 :raises SPSDKError: When invalid count of bytes. Must be 4 or 8
828 """
829 if count not in (4, 8):
830 raise SPSDKError("Invalid count of bytes. Must be 4 or 8")
831 logger.info(f"CMD: FlashReadOnce(index={index}, bytes={count})")
832 cmd_packet = CmdPacket(CommandTag.FLASH_READ_ONCE, CommandFlag.NONE.tag, index, count)
833 cmd_response = self._process_cmd(cmd_packet)
834 if cmd_response.status == StatusCode.SUCCESS:
835 assert isinstance(cmd_response, FlashReadOnceResponse)
836 return cmd_response.data
837 return None
838
839 def flash_program_once(self, index: int, data: bytes) -> bool:
840 """Write into MCU flash program once region (max 8 bytes).
841
842 :param index: Start index
843 :param data: Input data aligned to 4 or 8 bytes
844 :return: False in case of any problem; True otherwise
845 :raises SPSDKError: When invalid length of data. Must be aligned to 4 or 8 bytes
846 """
847 if len(data) not in (4, 8):
848 raise SPSDKError("Invalid length of data. Must be aligned to 4 or 8 bytes")
849 logger.info(f"CMD: FlashProgramOnce(index={index!r}, data={data!r})")
850 cmd_packet = CmdPacket(
851 CommandTag.FLASH_PROGRAM_ONCE, CommandFlag.NONE.tag, index, len(data), data=data
852 )
853 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
854
855 def flash_read_resource(self, address: int, length: int, option: int = 1) -> Optional[bytes]:
856 """Read resource of flash module.
857
858 :param address: Start address
859 :param length: Number of bytes
860 :param option: Area to be read. 0 means Flash IFR, 1 means Flash Firmware ID
861 :raises McuBootError: when the length is not aligned to 4 bytes
862 :return: Data from the resource; None in case of an failure
863 """
864 if length % 4:
865 raise McuBootError("The number of bytes to read is not aligned to the 4 bytes")
866 logger.info(
867 f"CMD: FlashReadResource(address=0x{address:08X}, length={length}, option={option})"
868 )
869 cmd_packet = CmdPacket(
870 CommandTag.FLASH_READ_RESOURCE, CommandFlag.NONE.tag, address, length, option
871 )
872 cmd_response = self._process_cmd(cmd_packet)
873 if cmd_response.status == StatusCode.SUCCESS:
874 assert isinstance(cmd_response, FlashReadResourceResponse)
875 return self._read_data(CommandTag.FLASH_READ_RESOURCE, cmd_response.length)
876 return None
877
878 def configure_memory(self, address: int, mem_id: int) -> bool:
879 """Configure memory.
880
881 :param address: The address in memory where are locating configuration data
882 :param mem_id: Memory ID
883 :return: False in case of any problem; True otherwise
884 """
885 logger.info(f"CMD: ConfigureMemory({mem_id}, address=0x{address:08X})")
886 cmd_packet = CmdPacket(CommandTag.CONFIGURE_MEMORY, CommandFlag.NONE.tag, mem_id, address)
887 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
888
889 def reliable_update(self, address: int) -> bool:
890 """Reliable Update.
891
892 :param address: Address where new the firmware is stored
893 :return: False in case of any problem; True otherwise
894 """
895 logger.info(f"CMD: ReliableUpdate(address=0x{address:08X})")
896 cmd_packet = CmdPacket(CommandTag.RELIABLE_UPDATE, CommandFlag.NONE.tag, address)
897 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
898
899 def generate_key_blob(
900 self, dek_data: bytes, key_sel: int = GenerateKeyBlobSelect.OPTMK.tag, count: int = 72
901 ) -> Optional[bytes]:
902 """Generate Key Blob.
903
904 :param dek_data: Data Encryption Key as bytes
905 :param key_sel: select the BKEK used to wrap the BK (default: OPTMK/FUSES)
906 :param count: Key blob count (default: 72 - AES128bit)
907 :return: Key blob; None in case of an failure
908 """
909 logger.info(
910 f"CMD: GenerateKeyBlob(dek_len={len(dek_data)}, key_sel={key_sel}, count={count})"
911 )
912 data_chunks = self._split_data(data=dek_data)
913 cmd_response = self._process_cmd(
914 CmdPacket(
915 CommandTag.GENERATE_KEY_BLOB,
916 CommandFlag.HAS_DATA_PHASE.tag,
917 key_sel,
918 len(dek_data),
919 0,
920 )
921 )
922 if cmd_response.status != StatusCode.SUCCESS:
923 return None
924 if not self._send_data(CommandTag.GENERATE_KEY_BLOB, data_chunks):
925 return None
926 cmd_response = self._process_cmd(
927 CmdPacket(CommandTag.GENERATE_KEY_BLOB, CommandFlag.NONE.tag, key_sel, count, 1)
928 )
929 if cmd_response.status == StatusCode.SUCCESS:
930 assert isinstance(cmd_response, ReadMemoryResponse)
931 return self._read_data(CommandTag.GENERATE_KEY_BLOB, cmd_response.length)
932 return None
933
934 def kp_enroll(self) -> bool:
935 """Key provisioning: Enroll Command (start PUF).
936
937 :return: False in case of any problem; True otherwise
938 """
939 logger.info("CMD: [KeyProvisioning] Enroll")
940 cmd_packet = CmdPacket(
941 CommandTag.KEY_PROVISIONING, CommandFlag.NONE.tag, KeyProvOperation.ENROLL.tag
942 )
943 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
944
945 def kp_set_intrinsic_key(self, key_type: int, key_size: int) -> bool:
946 """Key provisioning: Generate Intrinsic Key.
947
948 :param key_type: Type of the key
949 :param key_size: Size of the key
950 :return: False in case of any problem; True otherwise
951 """
952 logger.info(f"CMD: [KeyProvisioning] SetIntrinsicKey(type={key_type}, key_size={key_size})")
953 cmd_packet = CmdPacket(
954 CommandTag.KEY_PROVISIONING,
955 CommandFlag.NONE.tag,
956 KeyProvOperation.SET_INTRINSIC_KEY.tag,
957 key_type,
958 key_size,
959 )
960 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
961
962 def kp_write_nonvolatile(self, mem_id: int = 0) -> bool:
963 """Key provisioning: Write the key to a nonvolatile memory.
964
965 :param mem_id: The memory ID (default: 0)
966 :return: False in case of any problem; True otherwise
967 """
968 logger.info(f"CMD: [KeyProvisioning] WriteNonVolatileMemory(mem_id={mem_id})")
969 cmd_packet = CmdPacket(
970 CommandTag.KEY_PROVISIONING,
971 CommandFlag.NONE.tag,
972 KeyProvOperation.WRITE_NON_VOLATILE.tag,
973 mem_id,
974 )
975 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
976
977 def kp_read_nonvolatile(self, mem_id: int = 0) -> bool:
978 """Key provisioning: Load the key from a nonvolatile memory to bootloader.
979
980 :param mem_id: The memory ID (default: 0)
981 :return: False in case of any problem; True otherwise
982 """
983 logger.info(f"CMD: [KeyProvisioning] ReadNonVolatileMemory(mem_id={mem_id})")
984 cmd_packet = CmdPacket(
985 CommandTag.KEY_PROVISIONING,
986 CommandFlag.NONE.tag,
987 KeyProvOperation.READ_NON_VOLATILE.tag,
988 mem_id,
989 )
990 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
991
992 def kp_set_user_key(self, key_type: int, key_data: bytes) -> bool:
993 """Key provisioning: Send the user key specified by <key_type> to bootloader.
994
995 :param key_type: type of the user key, see enumeration for details
996 :param key_data: binary content of the user key
997 :return: False in case of any problem; True otherwise
998 """
999 logger.info(
1000 f"CMD: [KeyProvisioning] SetUserKey(key_type={key_type}, key_len={len(key_data)})"
1001 )
1002 data_chunks = self._split_data(data=key_data)
1003 cmd_packet = CmdPacket(
1004 CommandTag.KEY_PROVISIONING,
1005 CommandFlag.HAS_DATA_PHASE.tag,
1006 KeyProvOperation.SET_USER_KEY.tag,
1007 key_type,
1008 len(key_data),
1009 )
1010 cmd_response = self._process_cmd(cmd_packet)
1011 if cmd_response.status == StatusCode.SUCCESS:
1012 return self._send_data(CommandTag.KEY_PROVISIONING, data_chunks)
1013 return False
1014
1015 def kp_write_key_store(self, key_data: bytes) -> bool:
1016 """Key provisioning: Write key data into key store area.
1017
1018 :param key_data: key store binary content to be written to processor
1019 :return: result of the operation; True means success
1020 """
1021 logger.info(f"CMD: [KeyProvisioning] WriteKeyStore(key_len={len(key_data)})")
1022 data_chunks = self._split_data(data=key_data)
1023 cmd_packet = CmdPacket(
1024 CommandTag.KEY_PROVISIONING,
1025 CommandFlag.HAS_DATA_PHASE.tag,
1026 KeyProvOperation.WRITE_KEY_STORE.tag,
1027 0,
1028 len(key_data),
1029 )
1030 cmd_response = self._process_cmd(cmd_packet)
1031 if cmd_response.status == StatusCode.SUCCESS:
1032 return self._send_data(CommandTag.KEY_PROVISIONING, data_chunks)
1033 return False
1034
1035 def kp_read_key_store(self) -> Optional[bytes]:
1036 """Key provisioning: Read key data from key store area."""
1037 logger.info("CMD: [KeyProvisioning] ReadKeyStore")
1038 cmd_packet = CmdPacket(
1039 CommandTag.KEY_PROVISIONING, CommandFlag.NONE.tag, KeyProvOperation.READ_KEY_STORE.tag
1040 )
1041 cmd_response = self._process_cmd(cmd_packet)
1042 if cmd_response.status == StatusCode.SUCCESS:
1043 assert isinstance(cmd_response, KeyProvisioningResponse)
1044 return self._read_data(CommandTag.KEY_PROVISIONING, cmd_response.length)
1045 return None
1046
1047 def load_image(
1048 self, data: bytes, progress_callback: Optional[Callable[[int, int], None]] = None
1049 ) -> bool:
1050 """Load a boot image to the device.
1051
1052 :param data: boot image
1053 :param progress_callback: Callback for updating the caller about the progress
1054 :return: False in case of any problem; True otherwise
1055 """
1056 logger.info(f"CMD: LoadImage(length={len(data)})")
1057 data_chunks = self._split_data(data)
1058 # there's no command in this case
1059 self._status_code = StatusCode.SUCCESS.tag
1060 return self._send_data(CommandTag.NO_COMMAND, data_chunks, progress_callback)
1061
1062 def tp_prove_genuinity(self, address: int, buffer_size: int) -> Optional[int]:
1063 """Start the process of proving genuinity.
1064
1065 :param address: Address where to prove genuinity request (challenge) container
1066 :param buffer_size: Maximum size of the response package (limit 0xFFFF)
1067 :raises McuBootError: Invalid input parameters
1068 :return: True if prove_genuinity operation is successfully completed
1069 """
1070 logger.info(
1071 f"CMD: [TrustProvisioning] ProveGenuinity(address={hex(address)}, "
1072 f"buffer_size={buffer_size})"
1073 )
1074 if buffer_size > 0xFFFF:
1075 raise McuBootError("buffer_size must be less than 0xFFFF")
1076 address_msb = (address >> 32) & 0xFFFF_FFFF
1077 address_lsb = address & 0xFFFF_FFFF
1078 sentinel_cmd = _tp_sentinel_frame(
1079 TrustProvOperation.PROVE_GENUINITY.tag, args=[address_msb, address_lsb, buffer_size]
1080 )
1081 cmd_packet = CmdPacket(
1082 CommandTag.TRUST_PROVISIONING, CommandFlag.NONE.tag, data=sentinel_cmd
1083 )
1084 cmd_response = self._process_cmd(cmd_packet)
1085 if cmd_response.status == StatusCode.SUCCESS:
1086 assert isinstance(cmd_response, TrustProvisioningResponse)
1087 return cmd_response.values[0]
1088 return None
1089
1090 def tp_set_wrapped_data(self, address: int, stage: int = 0x4B, control: int = 1) -> bool:
1091 """Start the process of setting OEM data.
1092
1093 :param address: Address where the wrapped data container on target
1094 :param control: 1 - use the address, 2 - use container within the firmware, defaults to 1
1095 :param stage: Stage of TrustProvisioning flow, defaults to 0x4B
1096 :return: True if set_wrapped_data operation is successfully completed
1097 """
1098 logger.info(f"CMD: [TrustProvisioning] SetWrappedData(address={hex(address)})")
1099 if address == 0:
1100 control = 2
1101
1102 address_msb = (address >> 32) & 0xFFFF_FFFF
1103 address_lsb = address & 0xFFFF_FFFF
1104 stage_control = control << 8 | stage
1105 sentinel_cmd = _tp_sentinel_frame(
1106 TrustProvOperation.ISP_SET_WRAPPED_DATA.tag,
1107 args=[stage_control, address_msb, address_lsb],
1108 )
1109 cmd_packet = CmdPacket(
1110 CommandTag.TRUST_PROVISIONING, CommandFlag.NONE.tag, data=sentinel_cmd
1111 )
1112 cmd_response = self._process_cmd(cmd_packet)
1113 return cmd_response.status == StatusCode.SUCCESS
1114
1115 def fuse_program(self, address: int, data: bytes, mem_id: int = 0) -> bool:
1116 """Program fuse.
1117
1118 :param address: Start address
1119 :param data: List of bytes
1120 :param mem_id: Memory ID
1121 :return: False in case of any problem; True otherwise
1122 """
1123 logger.info(
1124 f"CMD: FuseProgram(address=0x{address:08X}, length={len(data)}, mem_id={mem_id})"
1125 )
1126 data_chunks = self._split_data(data=data)
1127 mem_id = _clamp_down_memory_id(memory_id=mem_id)
1128 cmd_packet = CmdPacket(
1129 CommandTag.FUSE_PROGRAM, CommandFlag.HAS_DATA_PHASE.tag, address, len(data), mem_id
1130 )
1131 cmd_response = self._process_cmd(cmd_packet)
1132 if cmd_response.status == StatusCode.SUCCESS: # pragma: no cover
1133 # command is not supported in any device, thus we can't measure coverage
1134 return self._send_data(CommandTag.FUSE_PROGRAM, data_chunks)
1135 return False
1136
1137 def fuse_read(self, address: int, length: int, mem_id: int = 0) -> Optional[bytes]:
1138 """Read fuse.
1139
1140 :param address: Start address
1141 :param length: Count of bytes
1142 :param mem_id: Memory ID
1143 :return: Data read from the fuse; None in case of a failure
1144 """
1145 logger.info(f"CMD: ReadFuse(address=0x{address:08X}, length={length}, mem_id={mem_id})")
1146 mem_id = _clamp_down_memory_id(memory_id=mem_id)
1147 cmd_packet = CmdPacket(CommandTag.FUSE_READ, CommandFlag.NONE.tag, address, length, mem_id)
1148 cmd_response = self._process_cmd(cmd_packet)
1149 if cmd_response.status == StatusCode.SUCCESS: # pragma: no cover
1150 # command is not supported in any device, thus we can't measure coverage
1151 assert isinstance(cmd_response, ReadMemoryResponse)
1152 return self._read_data(CommandTag.FUSE_READ, cmd_response.length)
1153 return None
1154
1155 def update_life_cycle(self, life_cycle: int) -> bool:
1156 """Update device life cycle.
1157
1158 :param life_cycle: New life cycle value.
1159 :return: False in case of any problems, True otherwise.
1160 """
1161 logger.info(f"CMD: UpdateLifeCycle (life cycle=0x{life_cycle:02X})")
1162 cmd_packet = CmdPacket(CommandTag.UPDATE_LIFE_CYCLE, CommandFlag.NONE.tag, life_cycle)
1163 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
1164
1165 def ele_message(
1166 self, cmdMsgAddr: int, cmdMsgCnt: int, respMsgAddr: int, respMsgCnt: int
1167 ) -> bool:
1168 """Send EdgeLock Enclave message.
1169
1170 :param cmdMsgAddr: Address in RAM where is prepared the command message words
1171 :param cmdMsgCnt: Count of 32bits command words
1172 :param respMsgAddr: Address in RAM where the command store the response
1173 :param respMsgCnt: Count of 32bits response words
1174
1175 :return: False in case of any problems, True otherwise.
1176 """
1177 logger.info(
1178 f"CMD: EleMessage Command (cmdMsgAddr=0x{cmdMsgAddr:08X}, cmdMsgCnt={cmdMsgCnt})"
1179 )
1180 if respMsgCnt:
1181 logger.info(
1182 f"CMD: EleMessage Response (respMsgAddr=0x{respMsgAddr:08X}, respMsgCnt={respMsgCnt})"
1183 )
1184 cmd_packet = CmdPacket(
1185 CommandTag.ELE_MESSAGE,
1186 CommandFlag.NONE.tag,
1187 0, # reserved for future use as a sub command ID or anything else
1188 cmdMsgAddr,
1189 cmdMsgCnt,
1190 respMsgAddr,
1191 respMsgCnt,
1192 )
1193 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
1194
1195 def tp_hsm_gen_key(
1196 self,
1197 key_type: int,
1198 reserved: int,
1199 key_blob_output_addr: int,
1200 key_blob_output_size: int,
1201 ecdsa_puk_output_addr: int,
1202 ecdsa_puk_output_size: int,
1203 ) -> Optional[List[int]]:
1204 """Trust provisioning: OEM generate common keys.
1205
1206 :param key_type: Key to generate (MFW_ISK, MFW_ENCK, GEN_SIGNK, GET_CUST_MK_SK)
1207 :param reserved: Reserved, must be zero
1208 :param key_blob_output_addr: The output buffer address where ROM writes the key blob to
1209 :param key_blob_output_size: The output buffer size in byte
1210 :param ecdsa_puk_output_addr: The output buffer address where ROM writes the public key to
1211 :param ecdsa_puk_output_size: The output buffer size in byte
1212 :return: Return byte count of the key blob + byte count of the public key from the device;
1213 None in case of an failure
1214 """
1215 logger.info("CMD: [TrustProvisioning] OEM generate common keys")
1216 cmd_packet = CmdPacket(
1217 CommandTag.TRUST_PROVISIONING,
1218 CommandFlag.NONE.tag,
1219 TrustProvOperation.HSM_GEN_KEY.tag,
1220 key_type,
1221 reserved,
1222 key_blob_output_addr,
1223 key_blob_output_size,
1224 ecdsa_puk_output_addr,
1225 ecdsa_puk_output_size,
1226 )
1227 cmd_response = self._process_cmd(cmd_packet)
1228 if isinstance(cmd_response, TrustProvisioningResponse):
1229 return cmd_response.values
1230 return None
1231
1232 def tp_oem_gen_master_share(
1233 self,
1234 oem_share_input_addr: int,
1235 oem_share_input_size: int,
1236 oem_enc_share_output_addr: int,
1237 oem_enc_share_output_size: int,
1238 oem_enc_master_share_output_addr: int,
1239 oem_enc_master_share_output_size: int,
1240 oem_cust_cert_puk_output_addr: int,
1241 oem_cust_cert_puk_output_size: int,
1242 ) -> Optional[List[int]]:
1243 """Takes the entropy seed provided by the OEM as input.
1244
1245 :param oem_share_input_addr: The input buffer address
1246 where the OEM Share(entropy seed) locates at
1247 :param oem_share_input_size: The byte count of the OEM Share
1248 :param oem_enc_share_output_addr: The output buffer address
1249 where ROM writes the Encrypted OEM Share to
1250 :param oem_enc_share_output_size: The output buffer size in byte
1251 :param oem_enc_master_share_output_addr: The output buffer address
1252 where ROM writes the Encrypted OEM Master Share to
1253 :param oem_enc_master_share_output_size: The output buffer size in byte.
1254 :param oem_cust_cert_puk_output_addr: The output buffer address where
1255 ROM writes the OEM Customer Certificate Public Key to
1256 :param oem_cust_cert_puk_output_size: The output buffer size in byte
1257 :return: Sizes of two encrypted blobs(the Encrypted OEM Share and the Encrypted OEM Master Share)
1258 and a public key(the OEM Customer Certificate Public Key).
1259 """
1260 logger.info("CMD: [TrustProvisioning] OEM generate master share")
1261 cmd_packet = CmdPacket(
1262 CommandTag.TRUST_PROVISIONING,
1263 CommandFlag.NONE.tag,
1264 TrustProvOperation.OEM_GEN_MASTER_SHARE.tag,
1265 oem_share_input_addr,
1266 oem_share_input_size,
1267 oem_enc_share_output_addr,
1268 oem_enc_share_output_size,
1269 oem_enc_master_share_output_addr,
1270 oem_enc_master_share_output_size,
1271 oem_cust_cert_puk_output_addr,
1272 oem_cust_cert_puk_output_size,
1273 )
1274 cmd_response = self._process_cmd(cmd_packet)
1275 if isinstance(cmd_response, TrustProvisioningResponse):
1276 return cmd_response.values
1277 return None
1278
1279 def tp_oem_set_master_share(
1280 self,
1281 oem_share_input_addr: int,
1282 oem_share_input_size: int,
1283 oem_enc_master_share_input_addr: int,
1284 oem_enc_master_share_input_size: int,
1285 ) -> bool:
1286 """Takes the entropy seed and the Encrypted OEM Master Share.
1287
1288 :param oem_share_input_addr: The input buffer address
1289 where the OEM Share(entropy seed) locates at
1290 :param oem_share_input_size: The byte count of the OEM Share
1291 :param oem_enc_master_share_input_addr: The input buffer address
1292 where the Encrypted OEM Master Share locates at
1293 :param oem_enc_master_share_input_size: The byte count of the Encrypted OEM Master Share
1294 :return: False in case of any problem; True otherwise
1295 """
1296 logger.info(
1297 "CMD: [TrustProvisioning] Takes the entropy seed and the Encrypted OEM Master Share."
1298 )
1299 cmd_packet = CmdPacket(
1300 CommandTag.TRUST_PROVISIONING,
1301 CommandFlag.NONE.tag,
1302 TrustProvOperation.OEM_SET_MASTER_SHARE.tag,
1303 oem_share_input_addr,
1304 oem_share_input_size,
1305 oem_enc_master_share_input_addr,
1306 oem_enc_master_share_input_size,
1307 )
1308 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
1309
1310 def tp_oem_get_cust_cert_dice_puk(
1311 self,
1312 oem_rkth_input_addr: int,
1313 oem_rkth_input_size: int,
1314 oem_cust_cert_dice_puk_output_addr: int,
1315 oem_cust_cert_dice_puk_output_size: int,
1316 ) -> Optional[int]:
1317 """Creates the initial trust provisioning keys.
1318
1319 :param oem_rkth_input_addr: The input buffer address where the OEM RKTH locates at
1320 :param oem_rkth_input_size: The byte count of the OEM RKTH
1321 :param oem_cust_cert_dice_puk_output_addr: The output buffer address where ROM writes the OEM Customer
1322 Certificate Public Key for DICE to
1323 :param oem_cust_cert_dice_puk_output_size: The output buffer size in byte
1324 :return: The byte count of the OEM Customer Certificate Public Key for DICE
1325 """
1326 logger.info("CMD: [TrustProvisioning] Creates the initial trust provisioning keys")
1327 cmd_packet = CmdPacket(
1328 CommandTag.TRUST_PROVISIONING,
1329 CommandFlag.NONE.tag,
1330 TrustProvOperation.OEM_GET_CUST_CERT_DICE_PUK.tag,
1331 oem_rkth_input_addr,
1332 oem_rkth_input_size,
1333 oem_cust_cert_dice_puk_output_addr,
1334 oem_cust_cert_dice_puk_output_size,
1335 )
1336 cmd_response = self._process_cmd(cmd_packet)
1337 if isinstance(cmd_response, TrustProvisioningResponse):
1338 return cmd_response.values[0]
1339 return None
1340
1341 def tp_hsm_store_key(
1342 self,
1343 key_type: int,
1344 key_property: int,
1345 key_input_addr: int,
1346 key_input_size: int,
1347 key_blob_output_addr: int,
1348 key_blob_output_size: int,
1349 ) -> Optional[List[int]]:
1350 """Trust provisioning: OEM generate common keys.
1351
1352 :param key_type: Key to generate (CKDFK, HKDFK, HMACK, CMACK, AESK, KUOK)
1353 :param key_property: Bit 0: Key Size, 0 for 128bit, 1 for 256bit.
1354 Bits 30-31: set key protection CSS mode.
1355 :param key_input_addr: The input buffer address where the key locates at
1356 :param key_input_size: The byte count of the key
1357 :param key_blob_output_addr: The output buffer address where ROM writes the key blob to
1358 :param key_blob_output_size: The output buffer size in byte
1359 :return: Return header of the key blob + byte count of the key blob
1360 (header is not included) from the device; None in case of an failure
1361 """
1362 logger.info("CMD: [TrustProvisioning] OEM generate common keys")
1363 cmd_packet = CmdPacket(
1364 CommandTag.TRUST_PROVISIONING,
1365 CommandFlag.NONE.tag,
1366 TrustProvOperation.HSM_STORE_KEY.tag,
1367 key_type,
1368 key_property,
1369 key_input_addr,
1370 key_input_size,
1371 key_blob_output_addr,
1372 key_blob_output_size,
1373 )
1374 cmd_response = self._process_cmd(cmd_packet)
1375 if isinstance(cmd_response, TrustProvisioningResponse):
1376 return cmd_response.values
1377 return None
1378
1379 def tp_hsm_enc_blk(
1380 self,
1381 mfg_cust_mk_sk_0_blob_input_addr: int,
1382 mfg_cust_mk_sk_0_blob_input_size: int,
1383 kek_id: int,
1384 sb3_header_input_addr: int,
1385 sb3_header_input_size: int,
1386 block_num: int,
1387 block_data_addr: int,
1388 block_data_size: int,
1389 ) -> bool:
1390 """Trust provisioning: Encrypt the given SB3 data block.
1391
1392 :param mfg_cust_mk_sk_0_blob_input_addr: The input buffer address
1393 where the CKDF Master Key Blob locates at
1394 :param mfg_cust_mk_sk_0_blob_input_size: The byte count of the CKDF Master Key Blob
1395 :param kek_id: The CKDF Master Key Encryption Key ID
1396 (0x10: NXP_CUST_KEK_INT_SK, 0x11: NXP_CUST_KEK_EXT_SK)
1397 :param sb3_header_input_addr: The input buffer address,
1398 where the SB3 Header(block0) locates at
1399 :param sb3_header_input_size: The byte count of the SB3 Header
1400 :param block_num: The index of the block. Due to SB3 Header(block 0) is always unencrypted,
1401 the index starts from block1
1402 :param block_data_addr: The buffer address where the SB3 data block locates at
1403 :param block_data_size: The byte count of the SB3 data block
1404 :return: False in case of any problem; True otherwise
1405 """
1406 logger.info("CMD: [TrustProvisioning] Encrypt the given SB3 data block")
1407 cmd_packet = CmdPacket(
1408 CommandTag.TRUST_PROVISIONING,
1409 CommandFlag.NONE.tag,
1410 TrustProvOperation.HSM_ENC_BLOCK.tag,
1411 mfg_cust_mk_sk_0_blob_input_addr,
1412 mfg_cust_mk_sk_0_blob_input_size,
1413 kek_id,
1414 sb3_header_input_addr,
1415 sb3_header_input_size,
1416 block_num,
1417 block_data_addr,
1418 block_data_size,
1419 )
1420 return self._process_cmd(cmd_packet).status == StatusCode.SUCCESS
1421
1422 def tp_hsm_enc_sign(
1423 self,
1424 key_blob_input_addr: int,
1425 key_blob_input_size: int,
1426 block_data_input_addr: int,
1427 block_data_input_size: int,
1428 signature_output_addr: int,
1429 signature_output_size: int,
1430 ) -> Optional[int]:
1431 """Signs the given data.
1432
1433 :param key_blob_input_addr: The input buffer address where signing key blob locates at
1434 :param key_blob_input_size: The byte count of the signing key blob
1435 :param block_data_input_addr: The input buffer address where the data locates at
1436 :param block_data_input_size: The byte count of the data
1437 :param signature_output_addr: The output buffer address where ROM writes the signature to
1438 :param signature_output_size: The output buffer size in byte
1439 :return: Return signature size; None in case of an failure
1440 """
1441 logger.info("CMD: [TrustProvisioning] HSM ENC SIGN")
1442 cmd_packet = CmdPacket(
1443 CommandTag.TRUST_PROVISIONING,
1444 CommandFlag.NONE.tag,
1445 TrustProvOperation.HSM_ENC_SIGN.tag,
1446 key_blob_input_addr,
1447 key_blob_input_size,
1448 block_data_input_addr,
1449 block_data_input_size,
1450 signature_output_addr,
1451 signature_output_size,
1452 )
1453 cmd_response = self._process_cmd(cmd_packet)
1454 if isinstance(cmd_response, TrustProvisioningResponse):
1455 return cmd_response.values[0]
1456 return None
1457
1458 def wpc_get_id(self, wpc_id_blob_addr: int, wpc_id_blob_size: int) -> Optional[int]:
1459 """Command used for harvesting device ID blob.
1460
1461 :param wpc_id_blob_addr: Buffer address
1462 :param wpc_id_blob_size: Buffer size
1463 """
1464 logger.info("CMD: [TrustProvisioning] WPC GET ID")
1465 cmd_packet = CmdPacket(
1466 CommandTag.TRUST_PROVISIONING,
1467 CommandFlag.NONE.tag,
1468 TrustProvWpc.WPC_GET_ID.tag,
1469 wpc_id_blob_addr,
1470 wpc_id_blob_size,
1471 )
1472 cmd_response = self._process_cmd(cmd_packet)
1473 if isinstance(cmd_response, TrustProvisioningResponse):
1474 return cmd_response.values[0]
1475 return None
1476
1477 def nxp_get_id(self, id_blob_addr: int, id_blob_size: int) -> Optional[int]:
1478 """Command used for harvesting device ID blob during wafer test as part of RTS flow.
1479
1480 :param id_blob_addr: address of ID blob defined by Round-trip trust provisioning specification.
1481 :param id_blob_size: length of buffer in bytes
1482 """
1483 logger.info("CMD: [TrustProvisioning] NXP GET ID")
1484 cmd_packet = CmdPacket(
1485 CommandTag.TRUST_PROVISIONING,
1486 CommandFlag.NONE.tag,
1487 TrustProvWpc.NXP_GET_ID.tag,
1488 id_blob_addr,
1489 id_blob_size,
1490 )
1491 cmd_response = self._process_cmd(cmd_packet)
1492 if isinstance(cmd_response, TrustProvisioningResponse):
1493 return cmd_response.values[0]
1494 return None
1495
1496 def wpc_insert_cert(
1497 self, wpc_cert_addr: int, wpc_cert_len: int, ec_id_offset: int, wpc_puk_offset: int
1498 ) -> Optional[int]:
1499 """Command used for certificate validation before it is written into flash.
1500
1501 This command does following things:
1502 Extracts ECID and WPC PUK from certificate
1503 Validates ECID and WPC PUK. If both are OK it returns success. Otherwise returns fail
1504
1505 :param wpc_cert_addr: address of inserted certificate
1506 :param wpc_cert_len: length in bytes of inserted certificate
1507 :param ec_id_offset: offset to 72-bit ECID
1508 :param wpc_puk_offset: WPC PUK offset from beginning of inserted certificate
1509 """
1510 logger.info("CMD: [TrustProvisioning] WPC INSERT CERT")
1511 cmd_packet = CmdPacket(
1512 CommandTag.TRUST_PROVISIONING,
1513 CommandFlag.NONE.tag,
1514 TrustProvWpc.WPC_INSERT_CERT.tag,
1515 wpc_cert_addr,
1516 wpc_cert_len,
1517 ec_id_offset,
1518 wpc_puk_offset,
1519 )
1520 cmd_response = self._process_cmd(cmd_packet)
1521 if cmd_response.status == StatusCode.SUCCESS:
1522 return 0
1523 return None
1524
1525 def wpc_sign_csr(
1526 self, csr_tbs_addr: int, csr_tbs_len: int, signature_addr: int, signature_len: int
1527 ) -> Optional[int]:
1528 """Command used sign CSR data (TBS portion).
1529
1530 :param csr_tbs_addr: address of CSR-TBS data
1531 :param csr_tbs_len: length in bytes of CSR-TBS data
1532 :param signature_addr: address where to store signature
1533 :param signature_len: expected length of signature
1534 :return: actual signature length
1535 """
1536 logger.info("CMD: [TrustProvisioning] WPC SIGN CSR-TBS DATA")
1537 cmd_packet = CmdPacket(
1538 CommandTag.TRUST_PROVISIONING,
1539 CommandFlag.NONE.tag,
1540 TrustProvWpc.WPC_SIGN_CSR.tag,
1541 csr_tbs_addr,
1542 csr_tbs_len,
1543 signature_addr,
1544 signature_len,
1545 )
1546 cmd_response = self._process_cmd(cmd_packet)
1547 if isinstance(cmd_response, TrustProvisioningResponse):
1548 return cmd_response.values[0]
1549 return None
1550
1551 def dsc_hsm_create_session(
1552 self,
1553 oem_seed_input_addr: int,
1554 oem_seed_input_size: int,
1555 oem_share_output_addr: int,
1556 oem_share_output_size: int,
1557 ) -> Optional[int]:
1558 """Command used by OEM to provide it share to create the initial trust provisioning keys.
1559
1560 :param oem_seed_input_addr: address of 128-bit entropy seed value provided by the OEM.
1561 :param oem_seed_input_size: OEM seed size in bytes
1562 :param oem_share_output_addr: A 128-bit encrypted token.
1563 :param oem_share_output_size: size in bytes
1564 """
1565 logger.info("CMD: [TrustProvisioning] DSC HSM CREATE SESSION")
1566 cmd_packet = CmdPacket(
1567 CommandTag.TRUST_PROVISIONING,
1568 CommandFlag.NONE.tag,
1569 TrustProvDevHsmDsc.DSC_HSM_CREATE_SESSION.tag,
1570 oem_seed_input_addr,
1571 oem_seed_input_size,
1572 oem_share_output_addr,
1573 oem_share_output_size,
1574 )
1575 cmd_response = self._process_cmd(cmd_packet)
1576 if isinstance(cmd_response, TrustProvisioningResponse):
1577 return cmd_response.values[0]
1578 return None
1579
1580 def dsc_hsm_enc_blk(
1581 self,
1582 sbx_header_input_addr: int,
1583 sbx_header_input_size: int,
1584 block_num: int,
1585 block_data_addr: int,
1586 block_data_size: int,
1587 ) -> Optional[int]:
1588 """Command used to encrypt the given block sliced by the nxpimage.
1589
1590 This command is only supported after issuance of dsc_hsm_create_session.
1591
1592 :param sbx_header_input_addr: SBx header containing file size, Firmware version and Timestamp data.
1593 Except for hash digest of block 0, all other fields should be valid.
1594 :param sbx_header_input_size: size of the header in bytes
1595 :param block_num: Number of block
1596 :param block_data_addr: Address of data block
1597 :param block_data_size: Size of data block
1598 """
1599 logger.info("CMD: [TrustProvisioning] DSC HSM ENC BLK")
1600 cmd_packet = CmdPacket(
1601 CommandTag.TRUST_PROVISIONING,
1602 CommandFlag.NONE.tag,
1603 TrustProvDevHsmDsc.DSC_HSM_ENC_BLK.tag,
1604 sbx_header_input_addr,
1605 sbx_header_input_size,
1606 block_num,
1607 block_data_addr,
1608 block_data_size,
1609 )
1610 cmd_response = self._process_cmd(cmd_packet)
1611 if isinstance(cmd_response, TrustProvisioningResponse):
1612 return cmd_response.values[0]
1613 return None
1614
1615 def dsc_hsm_enc_sign(
1616 self,
1617 block_data_input_addr: int,
1618 block_data_input_size: int,
1619 signature_output_addr: int,
1620 signature_output_size: int,
1621 ) -> Optional[int]:
1622 """Command used for signing the data buffer provided.
1623
1624 This command is only supported after issuance of dsc_hsm_create_session.
1625
1626 :param block_data_input_addr: Address of data buffer to be signed
1627 :param block_data_input_size: Size of data buffer in bytes
1628 :param signature_output_addr: Address to output signature data
1629 :param signature_output_size: Size of the output signature data in bytes
1630 """
1631 logger.info("CMD: [TrustProvisioning] DSC HSM ENC SIGN")
1632 cmd_packet = CmdPacket(
1633 CommandTag.TRUST_PROVISIONING,
1634 CommandFlag.NONE.tag,
1635 TrustProvDevHsmDsc.DSC_HSM_ENC_SIGN.tag,
1636 block_data_input_addr,
1637 block_data_input_size,
1638 signature_output_addr,
1639 signature_output_size,
1640 )
1641 cmd_response = self._process_cmd(cmd_packet)
1642 if isinstance(cmd_response, TrustProvisioningResponse):
1643 return cmd_response.values[0]
1644 return None
1645
1646
1647 ####################
1648 # Helper functions #
1649 ####################
1650
1651
1652 def _tp_sentinel_frame(command: int, args: List[int], tag: int = 0x17, version: int = 0) -> bytes:
1653 """Prepare frame used by sentinel."""
1654 data = struct.pack("<4B", command, len(args), version, tag)
1655 for item in args:
1656 data += struct.pack("<I", item)
1657 return data
1658
1659
1660 def _clamp_down_memory_id(memory_id: int) -> int:
1661 if memory_id > 255 or memory_id == 0:
1662 return memory_id
1663 logger.warning("Note: memoryId is not required when accessing mapped external memory")
1664 return 0