| 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 |
"""Commands and responses used by MBOOT module.""" |
| 10 |
|
| 11 |
from struct import pack, unpack, unpack_from |
| 12 |
from typing import Dict, List, Optional, Type |
| 13 |
|
| 14 |
from ..utils.interfaces.commands import CmdPacketBase, CmdResponseBase |
| 15 |
from ..utils.spsdk_enum import SpsdkEnum |
| 16 |
from .error_codes import StatusCode |
| 17 |
from .exceptions import McuBootError |
| 18 |
|
| 19 |
######################################################################################################################## |
| 20 |
# McuBoot Commands and Responses Tags |
| 21 |
######################################################################################################################## |
| 22 |
|
| 23 |
|
| 24 |
# fmt: off |
| 25 |
class CommandTag(SpsdkEnum): |
| 26 |
"""McuBoot Commands.""" |
| 27 |
|
| 28 |
NO_COMMAND = (0x00, "NoCommand", "No Command") |
| 29 |
FLASH_ERASE_ALL = (0x01, "FlashEraseAll", "Erase Complete Flash") |
| 30 |
FLASH_ERASE_REGION = (0x02, "FlashEraseRegion", "Erase Flash Region") |
| 31 |
READ_MEMORY = (0x03, "ReadMemory", "Read Memory") |
| 32 |
WRITE_MEMORY = (0x04, "WriteMemory", "Write Memory") |
| 33 |
FILL_MEMORY = (0x05, "FillMemory", "Fill Memory") |
| 34 |
FLASH_SECURITY_DISABLE = (0x06, "FlashSecurityDisable", "Disable Flash Security") |
| 35 |
GET_PROPERTY = (0x07, "GetProperty", "Get Property") |
| 36 |
RECEIVE_SB_FILE = (0x08, "ReceiveSBFile", "Receive SB File") |
| 37 |
EXECUTE = (0x09, "Execute", "Execute") |
| 38 |
CALL = (0x0A, "Call", "Call") |
| 39 |
RESET = (0x0B, "Reset", "Reset MCU") |
| 40 |
SET_PROPERTY = (0x0C, "SetProperty", "Set Property") |
| 41 |
FLASH_ERASE_ALL_UNSECURE = (0x0D, "FlashEraseAllUnsecure", "Erase Complete Flash and Unlock") |
| 42 |
FLASH_PROGRAM_ONCE = (0x0E, "FlashProgramOnce", "Flash Program Once") |
| 43 |
FLASH_READ_ONCE = (0x0F, "FlashReadOnce", "Flash Read Once") |
| 44 |
FLASH_READ_RESOURCE = (0x10, "FlashReadResource", "Flash Read Resource") |
| 45 |
CONFIGURE_MEMORY = (0x11, "ConfigureMemory", "Configure Quad-SPI Memory") |
| 46 |
RELIABLE_UPDATE = (0x12, "ReliableUpdate", "Reliable Update") |
| 47 |
GENERATE_KEY_BLOB = (0x13, "GenerateKeyBlob", "Generate Key Blob") |
| 48 |
FUSE_PROGRAM = (0x14, "ProgramFuse", "Program Fuse") |
| 49 |
KEY_PROVISIONING = (0x15, "KeyProvisioning", "Key Provisioning") |
| 50 |
TRUST_PROVISIONING = (0x16, "TrustProvisioning", "Trust Provisioning") |
| 51 |
FUSE_READ = (0x17, "ReadFuse", "Read Fuse") |
| 52 |
UPDATE_LIFE_CYCLE = (0x18, "UpdateLifeCycle", "Update Life Cycle") |
| 53 |
ELE_MESSAGE = (0x19, "EleMessage", "Send EdgeLock Enclave Message") |
| 54 |
|
| 55 |
# reserved commands |
| 56 |
CONFIGURE_I2C = (0xC1, "ConfigureI2c", "Configure I2C") |
| 57 |
CONFIGURE_SPI = (0xC2, "ConfigureSpi", "Configure SPI") |
| 58 |
CONFIGURE_CAN = (0xC3, "ConfigureCan", "Configure CAN") |
| 59 |
|
| 60 |
|
| 61 |
class CommandFlag(SpsdkEnum): |
| 62 |
"""Flags for McuBoot commands.""" |
| 63 |
|
| 64 |
NONE = (0, "NoFlags", "No flags specified") |
| 65 |
HAS_DATA_PHASE = (1, "DataPhase", "Command has a data phase") |
| 66 |
|
| 67 |
|
| 68 |
class ResponseTag(SpsdkEnum): |
| 69 |
"""McuBoot Responses to Commands.""" |
| 70 |
|
| 71 |
GENERIC = (0xA0, "GenericResponse", "Generic Response") |
| 72 |
READ_MEMORY = (0xA3, "ReadMemoryResponse", "Read Memory Response") |
| 73 |
GET_PROPERTY = (0xA7, "GetPropertyResponse", "Get Property Response") |
| 74 |
FLASH_READ_ONCE = (0xAF, "FlashReadOnceResponse", "Flash Read Once Response") |
| 75 |
FLASH_READ_RESOURCE = (0xB0, "FlashReadResourceResponse", "Flash Read Resource Response") |
| 76 |
KEY_BLOB_RESPONSE = (0xB3, "CreateKeyBlobResponse", "Create Key Blob") |
| 77 |
KEY_PROVISIONING_RESPONSE = (0xB5, "KeyProvisioningResponse", "Key Provisioning Response") |
| 78 |
TRUST_PROVISIONING_RESPONSE = (0xB6, "TrustProvisioningResponse", "Trust Provisioning Response") |
| 79 |
|
| 80 |
|
| 81 |
class KeyProvOperation(SpsdkEnum): |
| 82 |
"""Type of key provisioning operation.""" |
| 83 |
|
| 84 |
ENROLL = (0, "Enroll", "Enroll Operation") |
| 85 |
SET_USER_KEY = (1, "SetUserKey", "Set User Key Operation") |
| 86 |
SET_INTRINSIC_KEY = (2, "SetIntrinsicKey", "Set Intrinsic Key Operation") |
| 87 |
WRITE_NON_VOLATILE = (3, "WriteNonVolatile", "Write Non Volatile Operation") |
| 88 |
READ_NON_VOLATILE = (4, "ReadNonVolatile", "Read Non Volatile Operation") |
| 89 |
WRITE_KEY_STORE = (5, "WriteKeyStore", "Write Key Store Operation") |
| 90 |
READ_KEY_STORE = (6, "ReadKeyStore", "Read Key Store Operation") |
| 91 |
|
| 92 |
|
| 93 |
class KeyProvUserKeyType(SpsdkEnum): |
| 94 |
"""Enumeration of supported user keys in PUF. Keys are SoC specific, not all will be supported for the processor.""" |
| 95 |
|
| 96 |
OTFADKEK = (2, "OTFADKEK", "Key for OTFAD encryption") |
| 97 |
SBKEK = (3, "SBKEK", "Key for SB file encryption") |
| 98 |
PRINCE_REGION_0 = (7, "PRINCE0", "Key for Prince region 0") |
| 99 |
PRINCE_REGION_1 = (8, "PRINCE1", "Key for Prince region 1") |
| 100 |
PRINCE_REGION_2 = (9, "PRINCE2", "Key for Prince region 2") |
| 101 |
PRINCE_REGION_3 = (10, "PRINCE3", "Key for Prince region 3") |
| 102 |
|
| 103 |
USERKEK = (11, "USERKEK", "Encrypted boot image key") |
| 104 |
UDS = (12, "UDS", "Universal Device Secret for DICE") |
| 105 |
|
| 106 |
|
| 107 |
class GenerateKeyBlobSelect(SpsdkEnum): |
| 108 |
"""Key selector for the generate-key-blob function. |
| 109 |
|
| 110 |
For devices with SNVS, valid options of [key_sel] are |
| 111 |
0, 1 or OTPMK: OTPMK from FUSE or OTP(default), |
| 112 |
2 or ZMK: ZMK from SNVS, |
| 113 |
3 or CMK: CMK from SNVS, |
| 114 |
For devices without SNVS, this option will be ignored. |
| 115 |
""" |
| 116 |
|
| 117 |
OPTMK = (0, "OPTMK", "OTPMK from FUSE or OTP(default)") |
| 118 |
ZMK = (2, "ZMK", "ZMK from SNVS") |
| 119 |
CMK = (3, "CMK", "CMK from SNVS") |
| 120 |
|
| 121 |
|
| 122 |
class TrustProvOperation(SpsdkEnum): |
| 123 |
"""Operations supported by Trust Provisioning flow.""" |
| 124 |
|
| 125 |
PROVE_GENUINITY = (0xF4, "ProveGenuinity", "Start the proving genuinity process") |
| 126 |
ISP_SET_WRAPPED_DATA = (0xF0, "SetWrappedData", "Start processing Wrapped data") |
| 127 |
"""Type of trust provisioning operation.""" |
| 128 |
|
| 129 |
OEM_GEN_MASTER_SHARE = (0, "OemGenMasterShare", "Enroll Operation") |
| 130 |
OEM_SET_MASTER_SHARE = (1, "SetUserKey", "Set User Key Operation") |
| 131 |
OEM_GET_CUST_CERT_DICE_PUK = (2, "SetIntrinsicKey", "Set Intrinsic Key Operation") |
| 132 |
HSM_GEN_KEY = (3, "HsmGenKey", "HSM gen key") |
| 133 |
HSM_STORE_KEY = (4, "HsmStoreKey", "HSM store key") |
| 134 |
HSM_ENC_BLOCK = (5, "HsmEncBlock", "HSM Enc block") |
| 135 |
HSM_ENC_SIGN = (6, "HsnEncSign", "HSM enc sign") |
| 136 |
|
| 137 |
|
| 138 |
class TrustProvOemKeyType(SpsdkEnum): |
| 139 |
"""Type of oem key type definition.""" |
| 140 |
|
| 141 |
MFWISK = (0xC3A5, "MFWISK", "ECDSA Manufacturing Firmware Signing Key") |
| 142 |
MFWENCK = (0xA5C3, "MFWENCK", "CKDF Master Key for Manufacturing Firmware Encryption Key") |
| 143 |
GENSIGNK = (0x5A3C, "GENSIGNK", "Generic ECDSA Signing Key") |
| 144 |
GETCUSTMKSK = (0x3C5A, "GETCUSTMKSK", "CKDF Master Key for Production Firmware Encryption Key") |
| 145 |
|
| 146 |
|
| 147 |
class TrustProvKeyType(SpsdkEnum): |
| 148 |
"""Type of key type definition.""" |
| 149 |
|
| 150 |
CKDFK = (1, "CKDFK", "CKDF Master Key") |
| 151 |
HKDFK = (2, "HKDFK", "HKDF Master Key") |
| 152 |
HMACK = (3, "HMACK", "HMAC Key") |
| 153 |
CMACK = (4, "CMACK", "CMAC Key") |
| 154 |
AESK = (5, "AESK", "AES Key") |
| 155 |
KUOK = (6, "KUOK", "Key Unwrap Only Key") |
| 156 |
|
| 157 |
|
| 158 |
class TrustProvWrappingKeyType(SpsdkEnum): |
| 159 |
"""Type of wrapping key type definition.""" |
| 160 |
|
| 161 |
INT_SK = (0x10, "INT_SK", "The wrapping key for wrapping of MFG_CUST_MK_SK0_BLOB") |
| 162 |
EXT_SK = (0x11, "EXT_SK", "The wrapping key for wrapping of MFG_CUST_MK_SK0_BLOB") |
| 163 |
|
| 164 |
|
| 165 |
class TrustProvWpc(SpsdkEnum): |
| 166 |
"""Type of WPC trusted facility commands for DSC.""" |
| 167 |
|
| 168 |
WPC_GET_ID = (0x5000000, "wpc_get_id", "WPC get ID") |
| 169 |
NXP_GET_ID = (0x5000001, "nxp_get_id", "NXP get ID") |
| 170 |
WPC_INSERT_CERT = (0x5000002, "wpc_insert_cert", "WPC insert certificate") |
| 171 |
WPC_SIGN_CSR = (0x5000003, "wpc_sign_csr", "WPC sign CSR") |
| 172 |
|
| 173 |
|
| 174 |
class TrustProvDevHsmDsc(SpsdkEnum): |
| 175 |
"""Type of DSC Device HSM.""" |
| 176 |
|
| 177 |
DSC_HSM_CREATE_SESSION = (0x6000000, "dsc_hsm_create_session", "DSC HSM create session") |
| 178 |
DSC_HSM_ENC_BLK = (0x6000001, "dsc_hsm_enc_blk", "DSC HSM encrypt bulk") |
| 179 |
DSC_HSM_ENC_SIGN = (0x6000002, "dsc_hsm_enc_sign", "DSC HSM sign") |
| 180 |
|
| 181 |
# fmt: on |
| 182 |
|
| 183 |
######################################################################################################################## |
| 184 |
# McuBoot Command and Response packet classes |
| 185 |
######################################################################################################################## |
| 186 |
|
| 187 |
|
| 188 |
class CmdHeader: |
| 189 |
"""McuBoot command/response header.""" |
| 190 |
|
| 191 |
SIZE = 4 |
| 192 |
|
| 193 |
def __init__(self, tag: int, flags: int, reserved: int, params_count: int) -> None: |
| 194 |
"""Initialize the Command Header. |
| 195 |
|
| 196 |
:param tag: Tag indicating the command, see: `CommandTag` class |
| 197 |
:param flags: Flags for the command |
| 198 |
:param reserved: Reserved? |
| 199 |
:param params_count: Number of parameter for the command |
| 200 |
""" |
| 201 |
self.tag = tag |
| 202 |
self.flags = flags |
| 203 |
self.reserved = reserved |
| 204 |
self.params_count = params_count |
| 205 |
|
| 206 |
def __eq__(self, obj: object) -> bool: |
| 207 |
return isinstance(obj, CmdHeader) and vars(obj) == vars(self) |
| 208 |
|
| 209 |
def __ne__(self, obj: object) -> bool: |
| 210 |
return not self.__eq__(obj) |
| 211 |
|
| 212 |
def __repr__(self) -> str: |
| 213 |
return f"<Tag=0x{self.tag:02X}, Flags=0x{self.flags:02X}, ParamsCount={self.params_count}>" |
| 214 |
|
| 215 |
def __str__(self) -> str: |
| 216 |
return ( |
| 217 |
f"CmdHeader(tag=0x{self.tag:02X}, flags=0x{self.flags:02X}, " |
| 218 |
f"reserved={self.reserved}, params_count={self.params_count})" |
| 219 |
) |
| 220 |
|
| 221 |
def to_bytes(self) -> bytes: |
| 222 |
"""Serialize header into bytes.""" |
| 223 |
return pack("4B", self.tag, self.flags, self.reserved, self.params_count) |
| 224 |
|
| 225 |
@classmethod |
| 226 |
def from_bytes(cls, data: bytes, offset: int = 0) -> "CmdHeader": |
| 227 |
"""Deserialize header from bytes. |
| 228 |
|
| 229 |
:param data: Input data in bytes |
| 230 |
:param offset: The offset of input data |
| 231 |
:return: De-serialized CmdHeader object |
| 232 |
:raises McuBootError: Invalid data format |
| 233 |
""" |
| 234 |
if len(data) < 4: |
| 235 |
raise McuBootError(f"Invalid format of RX packet (data length is {len(data)} bytes)") |
| 236 |
return cls(*unpack_from("4B", data, offset)) |
| 237 |
|
| 238 |
|
| 239 |
class CmdPacket(CmdPacketBase): |
| 240 |
"""McuBoot command packet format class.""" |
| 241 |
|
| 242 |
SIZE = 32 |
| 243 |
EMPTY_VALUE = 0x00 |
| 244 |
|
| 245 |
def __init__( |
| 246 |
self, tag: CommandTag, flags: int, *args: int, data: Optional[bytes] = None |
| 247 |
) -> None: |
| 248 |
"""Initialize the Command Packet object. |
| 249 |
|
| 250 |
:param tag: Tag identifying the command |
| 251 |
:param flags: Flags used by the command |
| 252 |
:param args: Arguments used by the command |
| 253 |
:param data: Additional data, defaults to None |
| 254 |
""" |
| 255 |
self.header = CmdHeader(tag.tag, flags, 0, len(args)) |
| 256 |
self.params = list(args) |
| 257 |
if data is not None: |
| 258 |
if len(data) % 4: |
| 259 |
data += b"\0" * (4 - len(data) % 4) |
| 260 |
self.params.extend(unpack_from(f"<{len(data) // 4}I", data)) |
| 261 |
self.header.params_count = len(self.params) |
| 262 |
|
| 263 |
def __eq__(self, obj: object) -> bool: |
| 264 |
return isinstance(obj, CmdPacket) and vars(obj) == vars(self) |
| 265 |
|
| 266 |
def __ne__(self, obj: object) -> bool: |
| 267 |
return not self.__eq__(obj) |
| 268 |
|
| 269 |
def __str__(self) -> str: |
| 270 |
"""Get object info.""" |
| 271 |
tag = ( |
| 272 |
CommandTag.get_label(self.header.tag) |
| 273 |
if self.header.tag in CommandTag.tags() |
| 274 |
else f"0x{self.header.tag:02X}" |
| 275 |
) |
| 276 |
return f"Tag={tag}, Flags=0x{self.header.flags:02X}" + "".join( |
| 277 |
f", P[{n}]=0x{param:08X}" for n, param in enumerate(self.params) |
| 278 |
) |
| 279 |
|
| 280 |
def to_bytes(self, padding: bool = True) -> bytes: |
| 281 |
"""Serialize CmdPacket into bytes. |
| 282 |
|
| 283 |
:param padding: If True, add padding to specific size |
| 284 |
:return: Serialized object into bytes |
| 285 |
""" |
| 286 |
self.header.params_count = len(self.params) |
| 287 |
data = self.header.to_bytes() |
| 288 |
data += pack(f"<{self.header.params_count}I", *self.params) |
| 289 |
if padding and len(data) < self.SIZE: |
| 290 |
data += bytes([self.EMPTY_VALUE] * (self.SIZE - len(data))) |
| 291 |
return data |
| 292 |
|
| 293 |
|
| 294 |
class CmdResponse(CmdResponseBase): |
| 295 |
"""McuBoot response base format class.""" |
| 296 |
|
| 297 |
def __init__(self, header: CmdHeader, raw_data: bytes) -> None: |
| 298 |
"""Initialize the Command Response object. |
| 299 |
|
| 300 |
:param header: Header for the response |
| 301 |
:param raw_data: Response data |
| 302 |
""" |
| 303 |
assert isinstance(header, CmdHeader) |
| 304 |
assert isinstance(raw_data, (bytes, bytearray)) |
| 305 |
self.header = header |
| 306 |
self.raw_data = raw_data |
| 307 |
(status,) = unpack_from("<L", raw_data) |
| 308 |
self.status: int = status |
| 309 |
|
| 310 |
@property |
| 311 |
def value(self) -> int: |
| 312 |
"""Return a integer representation of the response.""" |
| 313 |
value = unpack_from(">I", self.raw_data)[0] |
| 314 |
assert isinstance(value, int) |
| 315 |
return value |
| 316 |
|
| 317 |
def _get_status_label(self) -> str: |
| 318 |
return ( |
| 319 |
StatusCode.get_label(self.status) |
| 320 |
if self.status in StatusCode.tags() |
| 321 |
else f"Unknown[0x{self.status:08X}]" |
| 322 |
) |
| 323 |
|
| 324 |
def __eq__(self, obj: object) -> bool: |
| 325 |
return isinstance(obj, CmdResponse) and vars(obj) == vars(self) |
| 326 |
|
| 327 |
def __ne__(self, obj: object) -> bool: |
| 328 |
return not self.__eq__(obj) |
| 329 |
|
| 330 |
def __str__(self) -> str: |
| 331 |
"""Get object info.""" |
| 332 |
return ( |
| 333 |
f"Tag=0x{self.header.tag:02X}, Flags=0x{self.header.flags:02X}" |
| 334 |
+ " [" |
| 335 |
+ ", ".join(f"{b:02X}" for b in self.raw_data) |
| 336 |
+ "]" |
| 337 |
) |
| 338 |
|
| 339 |
|
| 340 |
class GenericResponse(CmdResponse): |
| 341 |
"""McuBoot generic response format class.""" |
| 342 |
|
| 343 |
def __init__(self, header: CmdHeader, raw_data: bytes) -> None: |
| 344 |
"""Initialize the Generic response object. |
| 345 |
|
| 346 |
:param header: Header for the response |
| 347 |
:param raw_data: Response data |
| 348 |
""" |
| 349 |
super().__init__(header, raw_data) |
| 350 |
_, tag = unpack_from("<2I", raw_data) |
| 351 |
self.cmd_tag: int = tag |
| 352 |
|
| 353 |
def __str__(self) -> str: |
| 354 |
"""Get object info.""" |
| 355 |
tag = ResponseTag.get_label(self.header.tag) |
| 356 |
status = self._get_status_label() |
| 357 |
cmd = ( |
| 358 |
CommandTag.get_label(self.cmd_tag) |
| 359 |
if self.cmd_tag in CommandTag.tags() |
| 360 |
else f"Unknown[0x{self.cmd_tag:02X}]" |
| 361 |
) |
| 362 |
return f"Tag={tag}, Status={status}, Cmd={cmd}" |
| 363 |
|
| 364 |
|
| 365 |
class GetPropertyResponse(CmdResponse): |
| 366 |
"""McuBoot get property response format class.""" |
| 367 |
|
| 368 |
def __init__(self, header: CmdHeader, raw_data: bytes) -> None: |
| 369 |
"""Initialize the Get-Property response object. |
| 370 |
|
| 371 |
:param header: Header for the response |
| 372 |
:param raw_data: Response data |
| 373 |
""" |
| 374 |
super().__init__(header, raw_data) |
| 375 |
_, *values = unpack_from(f"<{self.header.params_count}I", raw_data) |
| 376 |
self.values: List[int] = list(values) |
| 377 |
|
| 378 |
def __str__(self) -> str: |
| 379 |
"""Get object info.""" |
| 380 |
tag = ResponseTag.get_label(self.header.tag) |
| 381 |
status = self._get_status_label() |
| 382 |
return f"Tag={tag}, Status={status}" + "".join( |
| 383 |
f", v{n}=0x{value:08X}" for n, value in enumerate(self.values) |
| 384 |
) |
| 385 |
|
| 386 |
|
| 387 |
class ReadMemoryResponse(CmdResponse): |
| 388 |
"""McuBoot read memory response format class.""" |
| 389 |
|
| 390 |
def __init__(self, header: CmdHeader, raw_data: bytes) -> None: |
| 391 |
"""Initialize the Read-Memory response object. |
| 392 |
|
| 393 |
:param header: Header for the response |
| 394 |
:param raw_data: Response data |
| 395 |
""" |
| 396 |
super().__init__(header, raw_data) |
| 397 |
_, length = unpack_from("<2I", raw_data) |
| 398 |
self.length: int = length |
| 399 |
|
| 400 |
def __str__(self) -> str: |
| 401 |
"""Get object info.""" |
| 402 |
tag = ResponseTag.get_label(self.header.tag) |
| 403 |
status = self._get_status_label() |
| 404 |
return f"Tag={tag}, Status={status}, Length={self.length}" |
| 405 |
|
| 406 |
|
| 407 |
class FlashReadOnceResponse(CmdResponse): |
| 408 |
"""McuBoot flash read once response format class.""" |
| 409 |
|
| 410 |
def __init__(self, header: CmdHeader, raw_data: bytes) -> None: |
| 411 |
"""Initialize the Flash-Read-Once response object. |
| 412 |
|
| 413 |
:param header: Header for the response |
| 414 |
:param raw_data: Response data |
| 415 |
""" |
| 416 |
super().__init__(header, raw_data) |
| 417 |
_, length, *values = unpack_from(f"<{self.header.params_count}I", raw_data) |
| 418 |
self.length: int = length |
| 419 |
self.values: List[int] = list(values) |
| 420 |
self.data = raw_data[8 : 8 + self.length] if self.length > 0 else b"" |
| 421 |
|
| 422 |
def __str__(self) -> str: |
| 423 |
"""Get object info.""" |
| 424 |
tag = ResponseTag.get_label(self.header.tag) |
| 425 |
status = self._get_status_label() |
| 426 |
return f"Tag={tag}, Status={status}, Length={self.length}" |
| 427 |
|
| 428 |
|
| 429 |
class FlashReadResourceResponse(CmdResponse): |
| 430 |
"""McuBoot flash read resource response format class.""" |
| 431 |
|
| 432 |
def __init__(self, header: CmdHeader, raw_data: bytes) -> None: |
| 433 |
"""Initialize the Flash-Read-Resource response object. |
| 434 |
|
| 435 |
:param header: Header for the response |
| 436 |
:param raw_data: Response data |
| 437 |
""" |
| 438 |
super().__init__(header, raw_data) |
| 439 |
_, length = unpack_from("<2I", raw_data) |
| 440 |
self.length: int = length |
| 441 |
|
| 442 |
def __str__(self) -> str: |
| 443 |
"""Get object info.""" |
| 444 |
tag = ResponseTag.get_label(self.header.tag) |
| 445 |
status = self._get_status_label() |
| 446 |
return f"Tag={tag}, Status={status}, Length={self.length}" |
| 447 |
|
| 448 |
|
| 449 |
class KeyProvisioningResponse(CmdResponse): |
| 450 |
"""McuBoot Key Provisioning response format class.""" |
| 451 |
|
| 452 |
def __init__(self, header: CmdHeader, raw_data: bytes) -> None: |
| 453 |
"""Initialize the Key-Provisioning response object. |
| 454 |
|
| 455 |
:param header: Header for the response |
| 456 |
:param raw_data: Response data |
| 457 |
""" |
| 458 |
super().__init__(header, raw_data) |
| 459 |
_, length = unpack_from("<2I", raw_data) |
| 460 |
self.length: int = length |
| 461 |
|
| 462 |
def __str__(self) -> str: |
| 463 |
"""Get object info.""" |
| 464 |
tag = ResponseTag.get_label(self.header.tag) |
| 465 |
status = self._get_status_label() |
| 466 |
return f"Tag={tag}, Status={status}, Length={self.length}" |
| 467 |
|
| 468 |
|
| 469 |
class TrustProvisioningResponse(CmdResponse): |
| 470 |
"""McuBoot Trust Provisioning response format class.""" |
| 471 |
|
| 472 |
def __init__(self, header: CmdHeader, raw_data: bytes) -> None: |
| 473 |
"""Initialize the Trust-Provisioning response object. |
| 474 |
|
| 475 |
:param header: Header for the response |
| 476 |
:param raw_data: Response data |
| 477 |
""" |
| 478 |
super().__init__(header, raw_data) |
| 479 |
_, *values = unpack(f"<{self.header.params_count}I", raw_data) |
| 480 |
self.values: List[int] = list(values) |
| 481 |
|
| 482 |
def __str__(self) -> str: |
| 483 |
"""Get object info.""" |
| 484 |
tag = ResponseTag.get_label(self.header.tag) |
| 485 |
status = self._get_status_label() |
| 486 |
return f"Tag={tag}, Status={status}" |
| 487 |
|
| 488 |
|
| 489 |
class NoResponse(CmdResponse): |
| 490 |
"""Special internal case when no response is provided by the target.""" |
| 491 |
|
| 492 |
def __init__(self, cmd_tag: int) -> None: |
| 493 |
"""Create a NoResponse to an command that was issued, indicated by its tag. |
| 494 |
|
| 495 |
:param cmd_tag: Tag of the command that preceded the no-response from target |
| 496 |
""" |
| 497 |
header = CmdHeader(tag=cmd_tag, flags=0, reserved=0, params_count=0) |
| 498 |
raw_data = pack("<L", StatusCode.NO_RESPONSE.tag) |
| 499 |
super().__init__(header, raw_data) |
| 500 |
|
| 501 |
|
| 502 |
def parse_cmd_response(data: bytes, offset: int = 0) -> CmdResponse: |
| 503 |
"""Parse command response. |
| 504 |
|
| 505 |
:param data: Input data in bytes |
| 506 |
:param offset: The offset of input data |
| 507 |
:return: De-serialized object from data |
| 508 |
""" |
| 509 |
known_response: Dict[int, Type[CmdResponse]] = { |
| 510 |
ResponseTag.GENERIC.tag: GenericResponse, |
| 511 |
ResponseTag.GET_PROPERTY.tag: GetPropertyResponse, |
| 512 |
ResponseTag.READ_MEMORY.tag: ReadMemoryResponse, |
| 513 |
ResponseTag.FLASH_READ_RESOURCE.tag: FlashReadResourceResponse, |
| 514 |
ResponseTag.FLASH_READ_ONCE.tag: FlashReadOnceResponse, |
| 515 |
ResponseTag.KEY_BLOB_RESPONSE.tag: ReadMemoryResponse, |
| 516 |
ResponseTag.KEY_PROVISIONING_RESPONSE.tag: KeyProvisioningResponse, |
| 517 |
ResponseTag.TRUST_PROVISIONING_RESPONSE.tag: TrustProvisioningResponse, |
| 518 |
} |
| 519 |
header = CmdHeader.from_bytes(data, offset) |
| 520 |
if header.tag in known_response: |
| 521 |
return known_response[header.tag](header, data[CmdHeader.SIZE :]) |
| 522 |
|
| 523 |
return CmdResponse(header, data[CmdHeader.SIZE :]) |