Image Module API

Contents

Image Module API#

Module implementing functionality of srktool, dcdgen, mkimage and other similar tools.

Image Classes#

Image.

class spsdk.image.images.BootImg2(address=0, offset=1024, version=65, plugin=False)#

Bases: BootImgBase

IMX Boot Image v2.

Initialize boot image object.

Parameters:
  • address (int) – The start address of img in target memory

  • offset (int) – The IVT offset

  • version (int) – The version of boot img format

  • plugin (bool) – if plugin

APP_ALIGN = 4096#
CSF_SIZE = 8192#
HEAD_SIZE = {256: 768, 1024: 3072}#
add_image(data, img_type=EnumAppType(tag=4, label='APP', description=None), address=0)#

Add specific image into the main boot image.

Parameters:
  • data (bytes) – Raw data of img

  • img_type (EnumAppType) – Type of img

  • address (int) – address in RAM

Raises:

Exception – Raised when the data type is unknown

Return type:

None

property app: SegAPP#

APP.

property bdt: SegBDT#

BDT.

property csf: SegCSF#

CSF.

export()#

Export image as bytes array.

Return type:

bytes

Returns:

bytes

property ivt: SegIVT2#

IVT.

classmethod parse(stream, step=256, size=None)#

Parse image from stream buffer or bytes array.

Parameters:
  • stream (Union[bytes, bytearray, BufferedReader, BytesIO]) – The stream buffer or bytes array

  • step (int) – Image searching step

  • size (Optional[int]) – parsing size

Raises:
  • SPSDKError – Raised when value type is incorrect

  • SPSDKError – Raised when there is not an i.MX Boot Image

Return type:

BootImg2

Returns:

BootImg2 object

property plugin: bool#

Plugin.

property size: int#

Size of IMX Boot Image v2..

property version: int#

Version of IMX Boot Image v2.

class spsdk.image.images.BootImg3a(address=0, offset=1024, version=67)#

Bases: BootImgBase

i.MX Boot Image v3a.

Initialize boot image object.

Parameters:
  • address (int) – The start address of img in target memory

  • offset (int) – The IVT offset

  • version (int) – The version of boot img format

APP_ALIGN = 4608#
COUNT_OF_CONTAINERS = 2#
CSF_SIZE = 8192#
HEAD_SIZE = {1024: 50176, 4096: 5120}#
IMG_AUTO_ALIGN = 16#
IMG_TYPE_CSF = 1#
IMG_TYPE_DATA = 4#
IMG_TYPE_EXEC = 3#
IMG_TYPE_SCD = 2#
INITIAL_LOAD_ADDR_AP_ROM = 1114112#
INITIAL_LOAD_ADDR_FLEXSPI = 134217728#
INITIAL_LOAD_ADDR_SCU_ROM = 536928256#
PADDING_VAL = 0#
SCFW_FLAGS_APP = 20275140#
SCFW_FLAGS_M4_0 = 4870498#
SCFW_FLAGS_M4_1 = 5198499#
SCFW_FLAGS_SCFW = 1#
SECTOR_SIZE = 512#
add_image(data, img_type=EnumAppType(tag=4, label='APP', description=None), address=0)#

Add specific image into the main boot image.

Parameters:
  • data (bytes) – Raw data of image

  • img_type (EnumAppType) – Type of image

  • address (int) – address in RAM

Raises:

Exception – raised when data type is unknown

Return type:

None

property bdt: list[SegBDS3a]#

BDT.

property csf: SegCSF#

CSF.

export()#

Export Image as binary blob.

Return type:

bytes

property ivt: list[SegIVT3a]#

IVT.

classmethod parse(stream, step=256, size=None)#

Parse image from stream buffer or bytes array.

Parameters:
  • stream (Union[bytes, bytearray, BufferedReader, BytesIO]) – The stream buffer or bytes array

  • step (int) – Image searching step

  • size (Optional[int]) – parsing size

Raises:
  • SPSDKError – Raised when the values type is incorrect

  • SPSDKError – Raised when there is not an i.MX Boot Image

Return type:

BootImgBase

Returns:

BootImg3a object

property plg: bool#

PLG.

class spsdk.image.images.BootImg3b(address=0, offset=1024, version=67)#

Bases: BootImgBase

IMX Boot Image v3b.

Initialize boot image object.

Parameters:
  • address (int) – The start address of img in target memory

  • offset (int) – The IVT offset

  • version (int) – The version of boot img format

APP_ALIGN = 4608#
COUNT_OF_CONTAINERS = 2#
CSF_SIZE = 8192#
HEAD_SIZE = {1024: 50176, 4096: 5120}#
IMG_AUTO_ALIGN = 16#
IMG_TYPE_CSF = 1#
IMG_TYPE_DATA = 4#
IMG_TYPE_EXEC = 3#
IMG_TYPE_SCD = 2#
INITIAL_LOAD_ADDR_AP_ROM = 1114112#
INITIAL_LOAD_ADDR_FLEXSPI = 134217728#
INITIAL_LOAD_ADDR_SCU_ROM = 536928256#
PADDING_VAL = 0#
SCFW_FLAGS_A53 = 20267028#
SCFW_FLAGS_A72 = 20267109#
SCFW_FLAGS_M4_0 = 4870498#
SCFW_FLAGS_M4_1 = 5198499#
SCFW_FLAGS_SCFW = 1#
SECTOR_SIZE = 512#
add_image(data, img_type=EnumAppType(tag=4, label='APP', description=None), address=0)#

Add specific image into the main boot image.

Parameters:
  • data (bytes) – Raw data of image

  • img_type (EnumAppType) – Type of image

  • address (int) – address in RAM

Raises:
  • Exception – raised SCFW is not defined before SCD

  • Exception – raised when there is unknown image type

Return type:

None

property bdt: list[SegBDS3b]#

BDT.

property csf: SegCSF#

CSF.

export()#

Export.

Return type:

bytes

property ivt: list[SegIVT3b]#

IVT.

classmethod parse(stream, step=256, size=None)#

Parse image from stream buffer or bytes array.

Parameters:
  • stream (Union[bytes, bytearray, BufferedReader, BytesIO]) – The stream buffer or bytes array

  • step (int) – Image searching step

  • size (Optional[int]) – parsing size

Raises:
Return type:

BootImgBase

Returns:

BootImg3b object

property plg: bool#

PLG.

class spsdk.image.images.BootImg4(address=0, offset=1024)#

Bases: BootImgBase

i.MX Boot Image v4.

Initialize boot image object.

Parameters:
  • address (int) – The start address of image in target memory

  • offset (int) – The image offset

add_image(data, img_type, address)#

Add image.

Raises:

NotImplementedError – Not yet implemented

Return type:

None

export()#

Export.

Return type:

bytes

classmethod parse(stream, step=256, size=None)#

Parse image from stream buffer or bytes array.

Parameters:
  • stream (Union[bytes, bytearray, BufferedReader, BytesIO]) – The stream buffer or bytes array

  • step (int) – Image searching step

  • size (Optional[int]) – parsing size

Return type:

BootImgBase

Returns:

BootImg4 object

Raises:
  • SPSDKError – Raised when the value type is incorrect

  • SPSDKError – If there is not an i.MX Boot Image

class spsdk.image.images.BootImg8m(address=0, offset=1024, version=65, plugin=False)#

Bases: BootImgBase

IMX Boot Image.

Initialize boot image object.

Parameters:
  • address (int) – The start address of img in target memory

  • offset (int) – The IVT offset

  • version (int) – The version of boot img format

  • plugin (bool) – if plugin

APP_ALIGN = 4096#
CSF_SIZE = 8192#
HEAD_SIZE = {256: 768, 1024: 3072}#
add_image(data, img_type=EnumAppType(tag=4, label='APP', description=None), address=0)#

Add specific image into the main boot image.

Parameters:
  • data (bytes) – Raw data of img

  • img_type (EnumAppType) – Type of img

  • address (int) – address in RAM

Raises:

Exception – raised when data type is unknown

Return type:

None

property app: SegAPP#

APP.

property bdt: SegBDT#

BDT.

property csf: SegCSF#

CSF.

export()#

Export Image as bytes array.

Return type:

bytes

Returns:

bytes

property ivt: SegIVT2#

IVT.

classmethod parse(stream, step=256, size=None)#

Parse image from stream buffer or bytes array.

Parameters:
  • stream (Union[bytes, bytearray, BufferedReader, BytesIO]) – The stream buffer or bytes array

  • step (int) – Image searching step

  • size (Optional[int]) – parsing size

Raises:
  • SPSDKError – Raised when the value type is incorrect

  • SPSDKError – Raised when there is not an i.MX Boot Image

Return type:

BootImgBase

Returns:

BootImg2 object

property plugin: bool#

Plugin.

property size: int#

Size of IMX Boot Image.

property version: int#

Version of IMX Boot Image.

class spsdk.image.images.BootImgBase(address, offset)#

Bases: object

IMX Boot Image Base.

Initialize boot image object.

Parameters:
  • address (int) – The start address of img in target memory

  • offset (int) – The IVT offset

add_image(data, img_type, address)#

Add specific image into the main boot image.

Parameters:
  • data (bytes) – Raw binary data of the application image

  • img_type (EnumAppType) – see EnumAppType

  • address (int) – TBD

Raises:

NotImplementedError – Derived class has to implement this method

Return type:

None

property dcd: SegDCD | None#

Device configuration data (DCD) segment; None if not assigned.

export()#

Binary representation of the instance (serialization).

Raises:

NotImplementedError – Derived class has to implement this method

Return type:

bytes

classmethod parse(stream, step=256, size=None)#

Parse of IMX Boot Image Base.

Raises:

NotImplementedError – Derived class has to implement this method

Return type:

BootImgBase

class spsdk.image.images.BootImgRT(address, offset=4096, version=64, plugin=False)#

Bases: BootImgBase

IMX Boot Image v2.

Initialize boot image object.

Parameters:
  • address (int) – The start address of img in target memory, where the image is executed

  • offset (int) – The IVT offset; use IVT_OFFSET_NOR_FLASH for NOR-FLASH or IVT_OFFSET_OTHER

  • version (int) – The version of boot img format; default value should be used

  • plugin (bool) – Do not use; see self.plugin property

Raises:
BDT_SIZE = 32#
BEE_OFFSET = 1024#
CSF_SIZE = 8192#
DEK_SIZE = 512#
FCB_OFFSETS = (0, 1024)#
IVT_OFFSETS = (0, 1024, 3072, 4096)#
IVT_OFFSET_NOR_FLASH = 4096#
IVT_OFFSET_OTHER = 1024#
IVT_OFFSET_OTHER2 = 3072#
NON_XIP_APP_OFFSET = 4096#
VERSIONS = (64, 65, 66, 67)#
XIP_APP_OFFSET = 8192#
XMCD_IVT_OFFSET = 64#
add_csf_encrypted(version, srk_table, src_key_index, csf_cert, csf_priv_key, img_cert, img_priv_key)#

Add CSF with image encryption.

Before calling, application image and address must be assigned

Parameters:
  • version (int) – CSF segment version

  • srk_table (SrkTable) – SRK table of root certificates; must contain min 1, max 4 certificates

  • src_key_index (int) – index of selected SRK key used for authentication, 0..srk_table.len - 1

  • csf_cert (bytes) – CSF certificate

  • csf_priv_key (PrivateKeyRsa) – CSF private key

  • img_cert (bytes) – IMG certificate

  • img_priv_key (PrivateKeyRsa) – IMG private key

Raises:
Return type:

None

add_csf_standard_auth(version, srk_table, src_key_index, csf_cert, csf_priv_key, img_cert, img_priv_key)#

Add CSF with standard authentication.

Before calling, application image and address must be assigned

Parameters:
  • version (int) – CSF segment version

  • srk_table (SrkTable) – SRK table of root certificates; must contain min 1, max 4 certificates

  • src_key_index (int) – index of selected SRK key used for authentication

  • csf_cert (bytes) – CSF certificate

  • csf_priv_key (PrivateKeyRsa) – CSF private key

  • img_cert (bytes) – IMG certificate

  • img_priv_key (PrivateKeyRsa) – IMG private key; decrypted binary data in PEM format

Raises:
Return type:

None

add_dcd_bin(data)#

Add DCD binary data.

Parameters:

data (bytes) – DCD binary data to be added

Raises:
Return type:

None

add_image(data, img_type=EnumAppType(tag=4, label='APP', description=None), address=-1, dek_key=None, nonce=None)#

Add specific image into the main boot image.

Parameters:
  • data (bytes) – Raw data of img

  • img_type (EnumAppType) – value must be EnumAppType.APP, no other options supported in this class

  • address (int) – start address of the application (entry point); Use -1 to detect the address from the image

  • dek_key (Optional[bytes]) – key for AES128 image HAB encryption [16 bytes], - use None for non-encrypted images; - use empty bytes to create random key (recommended) - use fixed key for testing to produce stable output

  • nonce (Optional[bytes]) – initial vector for AEAD HAB encryption, if not specified random value is used; For non-encrypted image use None The parameter should be used only for testing to produce stable output

Raises:
  • ValueError – if any parameter is not valid

  • SPSDKError – If invalid image type

  • SPSDKError – If image was already added

  • SPSDKError – If entry_addr not detected from image, must be specified explicitly

  • SPSDKError – If hab is not encrypted

  • SPSDKError – If nonce is not empty

Return type:

None

static aead_nonce_len(app_data_len)#

Nonce len for AEAD encryption.

Note: The code was taken from CST tool

Return type:

int

property app: SegAPP#

Segment with application image.

property app_offset: int#
Returns:

offset in the binary image, where the application starts.

Please mind: the offset include FCB block (even the FCB block is not exported) The offset is 0x2000 for XIP images and 0x1000 for non-XIP images

property bdt: SegBDT#

Boot Data Table.

property bee: SegBEE#
Returns:

BEE segment that contains configuration of encrypted XIP.

By default, BEE segment is empty. PRDB regions may be specified only for XIP images.

property bee_encrypted: bool#

True if BEE encrypted XIP image (with SW keys); False otherwise; see also hab_encrypted.

property csf: SegCSF | None#

Command Sequence File (CSF), signature block for Secure Boot.

property decrypted_app_data: bytes#

Return decrypted binary application data.

Note: dek key, mac and nonce must be assigned for decryption :raises SPSDKError: If application not present :raises SPSDKError: If invalid length of application data :raises SPSDKError: If Mac or nonce or dek not present

property dek_img_offset: int#

Offset of the DEK key in the image; -1 if DEK key address is available (see dek_ram_address).

property dek_key: bytes | None#

DEK key for encrypted images; None for non-encrypted images.

property dek_ram_address: int#

Address of the DEK key in the RAM memory retrieved from the corresponding command.

-1 if the image does not contain command for DEK key installation

property enabled_csf: SegCSF | None#

Enabled Command Sequence File (CSF) segment; None if CSF is not defined or it is not enabled.

export(zulu=datetime.datetime(2024, 10, 10, 11, 36, 35, 145145, tzinfo=datetime.timezone.utc))#

Export image as bytes array.

Parameters:

zulu (datetime) – optional UTC datetime; should be used only if you need fixed datetime for the test Note: the parameter is applied to CSF only, so it is not used for unsigned images

Raises:
Return type:

bytes

Returns:

bytes

export_bee()#

Export BEE segment.

Return type:

bytes

Returns:

binary BEE segment

Raises:

SPSDKError – if any BEE region is configured for images not located in the FLASH

export_csf(data, zulu=datetime.datetime(2024, 10, 10, 11, 36, 35, 145135, tzinfo=datetime.timezone.utc))#

Export CSF segment.

Parameters:
  • data (bytes) – generated binary data used for creating of signature

  • zulu (datetime) – current UTC datetime

Return type:

bytes

Returns:

binary CFD segment

export_dcd()#

Export DCD segment.

Return type:

bytes

Returns:

binary DCD segment

Raises:

SPSDKError – If DCD padding is not set

export_fcb()#

Export FCB segment.

Return type:

bytes

Returns:

binary FCB segment

Raises:

SPSDKError – If invalid length of data

property fcb: AbstractFCB#

Flash Configuration(Control) Block, binary data; content depends on FLASH type.

static get_app_offset(ivt_offset)#
Return type:

int

Returns:

offset in the binary image, where the application starts.

Please mind: the offset include FCB block (even the FCB block is not exported) The offset is 0x2000 for XIP images and 0x1000 for non-XIP images

Parameters:

ivt_offset (int) – Offset of IVT segment

property hab_encrypted: bool#

True if HAB encrypted; False otherwise; see also bee_encrypted.

property ivt: SegIVT2#

Image Vector Table (IVT) segment.

property ivt_offset: int#

Offset of the Image Vector Table (IVT) in the image.

classmethod parse(stream, step=0, size=None)#

Parse bootable RT image from stream buffer or bytes array.

Parameters:
  • stream (Union[bytes, bytearray, BufferedReader, BytesIO]) – The stream buffer or bytes array

  • step (int) – Image searching step (this parameter is not used for RT)

  • size (Optional[int]) – parsing size; None to parse till the end of the stream

Raises:

SPSDKError – Raised when the value type is incorrect

Return type:

BootImgRT

Returns:

BootImgRT object

property plugin: bool#

Flag whether it is plugin image type; It is not fully supported by SPSDK yet.

Plugin is designed to load a boot image from devices that are not natively supported by boot ROM.

set_flexspi_fcb(data)#

Set FlexSPI external FLASH configuration.

Parameters:

data (Union[bytes, FlexSPIConfBlockFCB]) – FlexSPIConfBlockFCB or binary data representing

Return type:

None

set_xmcd(data)#

Sets the XMCD block.

Return type:

None

property size: int#

Size of the exported binary data.

Please mind, FCB is exported optionally, but it is always included in the size

property version: int#

Version of the image format; must be from BootImgRT.VERSIONS.

property xmcd: SegXMCD | None#

Return the XMCD block.

class spsdk.image.images.KernelImg(address=0, app=None, csf=None, version=65)#

Bases: object

IMX Kernel Image.

Initialize the IMX Kernel Image.

IMAGE_MIN_SIZE = 4096#
property address: int#

Address.

property app: bytes | None#

APP.

property csf: SegCSF#

CSF.

export()#

Export.

Return type:

bytes

property version: int#

Version.

spsdk.image.images.parse(stream, step=256, size=None)#

Common parser for all versions of i.MX boot images.

Parameters:
  • stream (Union[bytes, bytearray, BufferedReader, BytesIO]) – stream buffer to image

  • step (int) – Image searching step

  • size (Optional[int]) – parsing size

Return type:

BootImgBase

Returns:

the object of boot image

Raises:
  • SPSDKError – Raised when the format of string is incorrect

  • SPSDKError – When not i.MX Boot Image is passed

Image Commands#

Commands for image module.

class spsdk.image.commands.CmdAuthData(flags=EnumAuthDat(tag=0, label='CLR', description='No flags set'), key_index=1, sig_format=EnumCertFormat(tag=197, label='CMS', description='CMS/PKCS#7 signature format'), engine=EnumEngine(tag=0, label='ANY', description='First compatible engine will be selected (no engine configuration parameters are allowed)'), engine_cfg=0, location=0, certificate=None, private_key=None, signature_provider=None)#

Bases: CmdBase

Authenticate data command.

Initialize the Authenticate data command.

append(start_address, size)#

Append of Authenticate data command.

Return type:

None

clear()#

Clear of Authenticate data command.

Return type:

None

property cmd_data_offset: int#

Offset of an additional data (such as signature or MAC, etc) in binary image.

property cmd_data_reference: MAC | Signature | None#

Reference to an additional data (such as certificate, signature, etc).

  • None if no reference was assigned;

  • Value type is command-specific

property engine: EnumEngine#

Engine.

export()#

Export to binary form (serialization).

Return type:

bytes

Returns:

binary representation of the command

property flags: EnumAuthDat#

Flag of Authenticate data command.

property key_index: int#

Key index.

property needs_cmd_data_reference: bool#

Whether the command contains a reference to an additional data.

classmethod parse(data)#

Convert binary representation into command (deserialization from binary data).

Parameters:

data (bytes) – being parsed

Return type:

Self

Returns:

parse command

parse_cmd_data(data)#

Parse additional command data from binary data.

Parameters:

data (bytes) – to be parsed

Return type:

Union[MAC, Signature]

Returns:

parsed data object; command-specific: Signature or MAC

Raises:

ExpectedSignatureOrMACError – if unsupported data object is provided

pop(index)#

Pop of Authenticate data command.

Return type:

tuple[int, int]

property signature: MAC | Signature | None#

Signature referenced by location attribute.

update_signature(zulu, data, base_data_addr=4294967295)#

Update signature.

This method must be called from parent to provide data to be signed

Parameters:
  • zulu (datetime) – current UTC time+date

  • data (bytes) – currently generated binary data

  • base_data_addr (int) – base address of the generated data

Raises:
  • ValueError – When certificate or private key are not assigned

  • ValueError – When signatures not assigned explicitly

  • SPSDKError – If incorrect start address

  • SPSDKError – If incorrect end address

  • SPSDKError – If incorrect length

Return type:

bool

Returns:

True if length of the signature was unchanged, as this may affect content of the CSF section (pointer to data);

class spsdk.image.commands.CmdBase(tag, param, length=None)#

Bases: BaseClass

Base class for all commands.

Constructor.

Parameters:
  • tag (CmdTag) – command tag

  • param (int) – TODO

  • length (Optional[int]) – of the binary command representation, in bytes

property cmd_data_offset: int#

Offset of an additional data (such as certificate, signature, etc) in binary image.

property cmd_data_reference: BaseSecretClass | None#

Reference to a command data (such as certificate, signature, etc).

None if no reference was assigned; Value type is command-specific

export()#

Export to binary form (serialization).

Return type:

bytes

Returns:

binary representation of the command

property needs_cmd_data_reference: bool#

Whether the command needs a reference to an additional data.

If returns True, the following methods must be implemented: - cmd_data_offset - cmd_data_reference

classmethod parse(data)#

Convert binary representation into command (deserialization from binary data).

Parameters:

data (bytes) – being parsed

Return type:

Self

Returns:

parse command

Raises:

NotImplementedError – Derived class has to implement this method

parse_cmd_data(data)#

Parse additional command data from binary data.

Parameters:

data (bytes) – to be parsed

Raises:

SPSDKError – If cmd_data is not supported by the command

Return type:

Any

property size: int#

Size of command.

property tag: int#

Command tag.

class spsdk.image.commands.CmdCheckData(numbytes=4, ops=EnumCheckOps(tag=1, label='ALL_SET', description='All bits set'), address=0, mask=0, count=None)#

Bases: CmdBase

Check data command.

Initialize the check data command.

Parameters:
  • numbytes (int) – number of bytes

  • ops (EnumCheckOps) – type of operation

  • address (int) – list of tuples: address and value

  • mask (int) – mask value

  • count (Optional[int]) – count value

Raises:
export()#

Export to binary form (serialization).

Return type:

bytes

Returns:

binary representation of the command

property num_bytes: int#

Number of bytes.

property ops: EnumCheckOps#

Operation of Check data command.

classmethod parse(data)#

Convert binary representation into command (deserialization from binary data).

Parameters:

data (bytes) – being parsed

Return type:

Self

Returns:

parse command

class spsdk.image.commands.CmdInitialize(engine=EnumEngine(tag=0, label='ANY', description='First compatible engine will be selected (no engine configuration parameters are allowed)'), data=None)#

Bases: CmdBase

Initialize command.

Initialize the initialize command.

append(value)#

Appending of Initialize command.

Raises:

SPSDKError – If value out of range

Return type:

None

clear()#

Clear of Initialize command.

Return type:

None

property engine: EnumEngine#

Engine.

export()#

Export to binary form (serialization).

Return type:

bytes

Returns:

binary representation of the command

classmethod parse(data)#

Convert binary representation into command (deserialization from binary data).

Parameters:

data (bytes) – being parsed

Return type:

Self

Returns:

parse command

Raises:

SPSDKError – If incorrect length of data

pop(index)#

Pop of Initialize command.

Return type:

int

Returns:

value from the index

Raises:

SPSDKError – If incorrect length of data

class spsdk.image.commands.CmdInstallKey(flags=EnumInsKey(tag=0, label='CLR', description='No flags set'), cert_fmt=EnumCertFormat(tag=3, label='SRK', description='SRK certificate format'), hash_alg=EnumAlgorithm(tag=0, label='ANY', description='Algorithm type ANY'), src_index=0, tgt_index=0, location=0)#

Bases: CmdBase

Install key command.

Constructor.

Parameters:
  • flags (EnumInsKey) – from EnumInsKey

  • cert_fmt (EnumCertFormat) – format of the certificate; key authentication protocol

  • hash_alg (EnumAlgorithm) – hash algorithm

  • src_index (int) – source key (verification key, KEK) index

  • tgt_index (int) – target key index

  • location (int) – start address of an additional data such as KEY to be installed; Typically it is relative to CSF start; Might be absolute for DEK key

property certificate_format: EnumCertFormat#

Certificate format.

property certificate_ref: CertificateImg | SrkTable | None#

Corresponding certificate referenced by key-location.

property cmd_data_offset: int#

Offset of an additional data (such as certificate, signature, etc) in binary image.

property cmd_data_reference: CertificateImg | SrkTable | None#

Reference to an additional data (such as certificate, signature, etc).

None if no reference was assigned; Value type is command-specific

export()#

Export to binary form (serialization).

Return type:

bytes

Returns:

binary representation of the command

property flags: EnumInsKey#

Flags.

property hash_algorithm: EnumAlgorithm#

Hash algorithm.

property needs_cmd_data_reference: bool#

Whether the command contains a reference to an additional data.

classmethod parse(data)#

Convert binary representation into command (deserialization from binary data).

Parameters:

data (bytes) – being parsed

Return type:

Self

Returns:

parse command

parse_cmd_data(data)#

Parse additional command data from binary data.

Parameters:

data (bytes) – to be parsed

Return type:

Union[CertificateImg, SrkTable, None]

Returns:

parsed data object; command-specific: certificate or SrkTable to be installed

property source_index: int#

Source key (verification key, KEK) index.

  • For SRK, it is index of the SRK key (0-3)

  • For other keys it is index of previously installed target key, typically 0

property target_index: int#

Target key index.

class spsdk.image.commands.CmdNop(param=0)#

Bases: CmdBase

Nop command.

Initialize the nop command.

classmethod parse(data)#

Convert binary representation into command (deserialization from binary data).

Parameters:

data (bytes) – being parsed

Return type:

Self

Returns:

parse command

class spsdk.image.commands.CmdSet(itm=EnumItm(tag=3, label='ENG', description='Preferred engine for a given algorithm'), hash_alg=EnumAlgorithm(tag=0, label='ANY', description='Algorithm type ANY'), engine=EnumEngine(tag=0, label='ANY', description='First compatible engine will be selected (no engine configuration parameters are allowed)'), engine_cfg=0)#

Bases: CmdBase

Set command.

Initialize the set command.

property engine: EnumEngine#

Engine plugin tags.

export()#

Export to binary form (serialization).

Return type:

bytes

Returns:

binary representation of the command

property hash_algorithm: EnumAlgorithm#

Type of hash algorithm.

property itm: EnumItm#

Item of Set command.

classmethod parse(data)#

Convert binary representation into command (deserialization from binary data).

Parameters:

data (bytes) – being parsed

Return type:

Self

Returns:

parse command

class spsdk.image.commands.CmdUnlock(engine=EnumEngine(tag=0, label='ANY', description='First compatible engine will be selected (no engine configuration parameters are allowed)'), features=0, uid=0)#

Bases: CmdUnlockAbstract

Generic unlock engine command.

Constructor.

Parameters:
  • engine (EnumEngine) – to be unlocked

  • features (int) – mask of features to use by the engine

  • uid (int) – Unique ID (if needed)

class spsdk.image.commands.CmdUnlockAbstract(engine=EnumEngine(tag=0, label='ANY', description='First compatible engine will be selected (no engine configuration parameters are allowed)'), features=0, uid=0)#

Bases: CmdBase, ABC

Abstract unlock engine command; the command depends on engine type.

Constructor.

Parameters:
  • engine (EnumEngine) – to be unlocked

  • features (Union[int, SpsdkEnum]) – engine specific features

  • uid (int) – Unique ID required by some engine/feature combinations

property engine: EnumEngine#

Engine to be unlocked.

The term engine denotes a peripheral involved in one or more of the following functions: - cryptographic computation - security state management - security alarm handling - access control

export()#

Export to binary form (serialization).

Return type:

bytes

Returns:

binary representation of the command

static need_uid(engine, features)#

Return True if given Engine and Feature requires UID.

Return type:

bool

classmethod parse(data)#

Convert binary representation into command (deserialization from binary data).

Parameters:

data (bytes) – being parsed

Return type:

Self

Returns:

Unlock command

class spsdk.image.commands.CmdUnlockCAAM(features=0)#

Bases: CmdUnlockAbstract

Command Unlock for Cryptographic Acceleration and Assurance Module .

Initialize.

Parameters:

features (Union[int, UnlockCAAMFeatures]) – mask of FEATURE_UNLOCK_x constants, defaults to 0

FEATURES#

alias of UnlockCAAMFeatures

property unlock_mfg: bool#

Leave Zero is able Master Key write unlocked.

property unlock_mid: bool#

Leave Job Ring and DECO master ID registers unlocked.

property unlock_rng: bool#

Leave RNG un-instantiated.

class spsdk.image.commands.CmdUnlockOCOTP(features=0, uid=0)#

Bases: CmdUnlockAbstract

Command Unlock for On-Chip One-time programable memory (fuses).

Initialize.

Parameters:
  • features (Union[int, UnlockOCOTPFeatures]) – mask of FEATURE_UNLOCK_x constants, defaults to 0

  • uid (int) – Unique ID required by some engine/feature combinations

FEATURES#

alias of UnlockOCOTPFeatures

property unlock_csc: bool#

Leave SCS register unlocked.

property unlock_fld_rtn: bool#

Leave Field Return activation unlocked.

property unlock_jtag: bool#

Unlock JTAG using SCS HAB_JDE bit.

property unlock_srk_rvk: bool#

Leave SRK revocation unlocked.

class spsdk.image.commands.CmdUnlockSNVS(features=0)#

Bases: CmdUnlockAbstract

Command Unlock Secure Non-Volatile Storage (SNVS) Engine.

Constructor.

Parameters:

features (Union[int, UnlockSNVSFeatures]) – mask of FEATURE_UNLOCK_* constants

FEATURES#

alias of UnlockSNVSFeatures

property unlock_lp_swr: bool#

Leave LP SW reset unlocked.

property unlock_zmk_write: bool#

Leave Zero is able Master Key write unlocked.

class spsdk.image.commands.CmdWriteData(numbytes=4, ops=EnumWriteOps(tag=0, label='WRITE_VALUE', description='Write value'), data=None)#

Bases: CmdBase

Write data command.

Initialize Write Data command.

Parameters:
  • numbytes (int) – number of bytes. Must be value: 1, 2 or 4

  • ops (EnumWriteOps) – type of write operation

  • data (Optional[Iterable[tuple[int, int]]]) – list of tuples: address and value

Raises:
append(address, value)#

Append of Write data command.

Return type:

None

clear()#

Clear of Write data command.

Return type:

None

export()#

Export to binary form (serialization).

Return type:

bytes

Returns:

binary representation of the command

property num_bytes: int#

Number of bytes being written by the command.

property ops: EnumWriteOps#

Type of write operation.

classmethod parse(data)#

Convert binary representation into command (deserialization from binary data).

Parameters:

data (bytes) – being parsed

Return type:

Self

Returns:

parse command

pop(index)#

Pop of Write data command.

Return type:

list[int]

class spsdk.image.commands.EnumAuthDat(tag, label, description=None)#

Bases: SpsdkEnum

Flags for Authenticate Data commands.

ABS = (1, 'ABS', 'Absolute signature address')#
CLR = (0, 'CLR', 'No flags set')#
class spsdk.image.commands.EnumCAAM(tag, label, description=None)#

Bases: SpsdkEnum

CAAM Engine Configuration.

DEFAULT = (0, 'DEFAULT')#
DSC_SWAP16 = (128, 'DSC_SWAP16')#
DSC_SWAP8 = (64, 'DSC_SWAP8')#
IN_SWAP16 = (2, 'IN_SWAP16')#
IN_SWAP8 = (1, 'IN_SWAP8')#
OUT_SWAP16 = (16, 'OUT_SWAP16')#
OUT_SWAP8 = (8, 'OUT_SWAP8')#
class spsdk.image.commands.EnumCertFormat(tag, label, description=None)#

Bases: SpsdkEnum

Certificate format tags.

AEAD = (163, 'AEAD', 'Proprietary AEAD MAC format')#
BLOB = (187, 'BLOB', 'SHW-specific wrapped key format')#
CMS = (197, 'CMS', 'CMS/PKCS#7 signature format')#
SRK = (3, 'SRK', 'SRK certificate format')#
X509 = (9, 'X509', 'X.509v3 certificate format')#
class spsdk.image.commands.EnumCheckOps(tag, label, description=None)#

Bases: SpsdkEnum

Enum definition for ‘par’ parameter of Check Data command.

ALL_CLEAR = (0, 'ALL_CLEAR', 'All bits clear')#
ALL_SET = (1, 'ALL_SET', 'All bits set')#
ANY_CLEAR = (2, 'ANY_CLEAR', 'Any bit clear')#
ANY_SET = (3, 'ANY_SET', 'Any bit set')#
class spsdk.image.commands.EnumEngine(tag, label, description=None)#

Bases: SpsdkEnum

Engine plugin tags.

ANY = (0, 'ANY', 'First compatible engine will be selected (no engine configuration parameters are allowed)')#
CAAM = (29, 'CAAM', 'Cryptographic Acceleration and Assurance Module')#
CSU = (10, 'CSU', 'Central Security Unit')#
DCP = (27, 'DCP', 'Data Co-Processor')#
DTCP = (34, 'DTCP', 'DTCP co-processor')#
HDCP = (36, 'HDCP', 'HDCP co-processor')#
OCOTP = (33, 'OCOTP', 'Fuse controller')#
ROM = (54, 'ROM', 'Protected ROM area')#
RTIC = (5, 'RTIC', 'Run-time integrity checker')#
SAHARA = (6, 'SAHARA', 'Crypto accelerator')#
SCC = (3, 'ANY', 'Security controller')#
SNVS = (30, 'SNVS', 'Secure Non-Volatile Storage')#
SRTC = (12, 'SRTC', 'Secure clock')#
SW = (255, 'SW', 'Software engine')#
class spsdk.image.commands.EnumInsKey(tag, label, description=None)#

Bases: SpsdkEnum

Flags for Install Key commands.

ABS = (1, 'ABS', 'Absolute certificate address')#
CFG = (8, 'CFG', 'Key binds to Configuration')#
CID = (64, 'CID', 'Key binds to Caller ID')#
CLR = (0, 'CLR', 'No flags set')#
CSF = (2, 'CSF', 'Install CSF key')#
DAT = (4, 'DAT', 'Key binds to Data Type')#
FID = (16, 'FID', 'Key binds to Fabrication UID')#
HSH = (128, 'HSH', 'Certificate hash present')#
MID = (32, 'MID', 'Key binds to Manufacturing ID')#
class spsdk.image.commands.EnumItm(tag, label, description=None)#

Bases: SpsdkEnum

Engine configuration flags of Set command.

ENG = (3, 'ENG', 'Preferred engine for a given algorithm')#
MID = (1, 'MID', 'Manufacturing ID (MID) fuse locations')#
class spsdk.image.commands.EnumWriteOps(tag, label, description=None)#

Bases: SpsdkEnum

Enum definition for ‘flags’ control flags in ‘par’ parameter of Write Data command.

CLEAR_BITMASK = (2, 'CLEAR_BITMASK', 'Clear bitmask')#
SET_BITMASK = (3, 'SET_BITMASK', 'Set bitmask')#
WRITE_CLEAR_BITS = (1, 'WRITE_CLEAR_BITS', 'Write clear bits')#
WRITE_VALUE = (0, 'WRITE_VALUE', 'Write value')#
exception spsdk.image.commands.ExpectedSignatureOrMACError(desc=None)#

Bases: SPSDKError

CmdAuthData additional data block: expected Signature or MAC object.

Initialize the base SPSDK Exception.

class spsdk.image.commands.UnlockCAAMFeatures(tag, label, description=None)#

Bases: SpsdkEnum

Enum definition for Unlock SNVS features.

MFG = (4, 'MFG', 'Keep manufacturing protection private key in CAAM internal memory.')#
MID = (1, 'MID', 'Leaves Job Ring and DECO master ID registers unlocked')#
RNG = (2, 'RNG', 'Leave RNG uninitialized.')#
class spsdk.image.commands.UnlockOCOTPFeatures(tag, label, description=None)#

Bases: SpsdkEnum

Enum definition for Unlock SNVS features.

FIELD_RETURN = (1, 'FIELD RETURN', 'Leave Field Return activation unlocked.')#
JTAG = (8, 'JTAG', 'Unlock JTAG using SCS HAB_JDE bit.')#
SCS = (4, 'SCS', 'Leave SCS register unlocked.')#
SRK_REVOKE = (2, 'SRK REVOKE', 'Leave SRK revocation unlocked.')#
class spsdk.image.commands.UnlockSNVSFeatures(tag, label, description=None)#

Bases: SpsdkEnum

Enum definition for Unlock SNVS features.

LP_SWR = (1, 'LP SWR', 'Leaves LP SW reset unlocked')#
ZMK_WRITE = (2, 'ZMK WRITE', 'Leaves Zeroisable Master Key write unlocked.')#
spsdk.image.commands.parse_command(data)#

Parse CSF/DCD command.

Parameters:

data (bytes) – binary data to be parsed

Return type:

CmdBase

Returns:

instance of the command

Raises:

SPSDKError – If the command is not valid

Image Headers#

Header.

class spsdk.image.header.CmdHeader(tag, param=0, length=None)#

Bases: Header

Command header.

Constructor.

Parameters:
  • tag (Union[CmdTag, int]) – command tag

  • param (int) – TODO

  • length (Optional[int]) – of the command binary section, in bytes

Raises:

SPSDKError – If invalid command tag

classmethod parse(data, required_tag=None)#

Create Header from binary data.

Parameters:
  • data (bytes) – binary data to convert into header

  • required_tag (Optional[int]) – CmdTag, None if not required

Return type:

Self

Returns:

parsed instance

Raises:
property tag: int#

Command tag.

class spsdk.image.header.CmdTag(tag, label, description=None)#

Bases: SpsdkEnum

CSF/DCD Command Tag.

AUT_DAT = (202, 'AUT_DAT', 'Authenticate Data')#
CHK_DAT = (207, 'CHK_DAT', 'Check Data')#
INIT = (180, 'INIT', 'Initialize')#
INS_KEY = (190, 'INS_KEY', 'Install Key')#
NOP = (192, 'NOP', 'No Operation (NOP)')#
SET = (177, 'SET', 'Set')#
UNLK = (178, 'UNLK', 'Unlock')#
WRT_DAT = (204, 'WRT_DAT', 'Write Data')#
class spsdk.image.header.Header(tag=0, param=0, length=None)#

Bases: BaseClass

Header element type.

Constructor.

Parameters:
  • tag (int) – section tag

  • param (int) – TODO

  • length (Optional[int]) – length of the segment or command; if not specified, size of the header is used

Raises:

SPSDKError – If invalid length

FORMAT = '>BHB'#
SIZE = 4#
export()#

Binary representation of the header.

Return type:

bytes

classmethod parse(data, required_tag=None)#

Parse header.

Parameters:
  • data (bytes) – Raw data as bytes or bytearray

  • required_tag (Optional[int]) – Check header TAG if specified value or ignore if is None

Return type:

Self

Returns:

Header object

Raises:

SPSDKParsingError – if required header tag does not match

property size: int#

Header size in bytes.

property tag: int#
Returns:

section tag: command tag or segment tag, …

property tag_name: str#

Returns the header’s tag name.

class spsdk.image.header.Header2(tag=0, param=0, length=None)#

Bases: Header

Header element type.

Constructor.

Parameters:
  • tag (int) – section tag

  • param (int) – TODO

  • length (Optional[int]) – length of the segment or command; if not specified, size of the header is used

Raises:

SPSDKError – If invalid length

FORMAT = '<BHB'#
export()#

Binary representation of the header.

Return type:

bytes

classmethod parse(data, required_tag=None)#

Parse header.

Parameters:
  • data (bytes) – Raw data as bytes or bytearray

  • required_tag (Optional[int]) – Check header TAG if specified value or ignore if is None

Raises:

SPSDKParsingError – Raises an error if required tag is empty or not valid

Return type:

Self

Returns:

Header2 object

class spsdk.image.header.SegTag(tag, label, description=None)#

Bases: SpsdkEnum

Segments Tag.

BIC1 = (135, 'BIC1', 'Boot Images Container')#
CRT = (215, 'CRT', 'Certificate')#
CSF = (212, 'CSF', 'Command Sequence File Data')#
DCD = (210, 'DCD', 'Device Configuration Data')#
EVT = (219, 'EVT', 'Event')#
IVT2 = (209, 'IVT2', 'Image Vector Table (Version 2)')#
IVT3 = (222, 'IVT3', 'Image Vector Table (Version 3)')#
MAC = (172, 'MAC', 'Message Authentication Code')#
RVT = (221, 'RVT', 'ROM Vector Table')#
SIG = (216, 'SIG', 'Signature')#
SIGB = (144, 'SIGB', 'Signature block')#
WRP = (129, 'WRP', 'Wrapped Key')#
XMCD = (192, 'XMCD', 'External Memory Configuration Data')#

Secret Module#

Commands and responses used by SDP module.

class spsdk.image.secret.BaseSecretClass(tag, version=64)#

Bases: BaseClass

Base SPSDK class.

Constructor.

Parameters:
  • tag (SegTag) – section TAG

  • version (int) – format version

property size: int#

Size of the exported binary data.

Raises:

NotImplementedError – Derived class has to implement this method

property version: int#

Format version.

property version_major: int#

Major format version.

property version_minor: int#

Minor format version.

class spsdk.image.secret.CertificateImg(version=64, data=None)#

Bases: BaseSecretClass

Certificate structure for bootable image.

Initialize the certificate structure for bootable image.

export()#

Export.

Return type:

bytes

classmethod parse(data)#

Parse.

Return type:

Self

property size: int#

Size of Certificate structure for bootable image.

class spsdk.image.secret.EnumAlgorithm(tag, label, description=None)#

Bases: SpsdkEnum

Algorithm types.

AES = (85, 'AES', 'AES algorithm ID')#
ANY = (0, 'ANY', 'Algorithm type ANY')#
BLOB = (113, 'BLOB', 'SHW-specific key wrap')#
CCM = (102, 'CCM', 'Counter with CBC-MAC')#
CIPHER = (5, 'CIPHER', 'Cipher algorithm type')#
EC = (4, 'EC', 'Elliptic curve arithmetic')#
ECDSA = (39, 'ECDSA', 'NIST ECDSA signature algorithm')#
F = (3, 'F', 'Finite field arithmetic')#
HASH = (1, 'HASH', 'Hash algorithm type')#
MODE = (6, 'MODE', 'Cipher/hash modes')#
PKCS1 = (33, 'PKCS1', 'PKCS#1 RSA signature algorithm')#
SHA1 = (17, 'SHA1', 'SHA-1 algorithm ID')#
SHA256 = (23, 'SHA256', 'SHA-256 algorithm ID')#
SHA512 = (27, 'SHA512', 'SHA-512 algorithm ID')#
SIG = (2, 'SIG', 'Signature algorithm type')#
WRAP = (7, 'WRAP', 'Key wrap algorithm type')#
class spsdk.image.secret.EnumSRK(tag, label, description=None)#

Bases: SpsdkEnum

Entry type in the System Root Key Table.

KEY_HASH = (238, 'KEY_HASH', 'Any key: hash only')#
KEY_PUBLIC = (225, 'KEY_PUBLIC', 'Public key type: data present')#
class spsdk.image.secret.MAC(version=64, nonce_len=0, mac_len=16, data=None)#

Bases: BaseSecretClass

Structure that holds initial parameter for AES encryption/decryption.

  • nonce - initialization vector for AEAD AES128 decryption

  • mac - message authentication code to verify the decryption was successful

Constructor.

Parameters:
  • version (int) – format version, should be 0x4x

  • nonce_len (int) – number of NONCE bytes

  • mac_len (int) – number of MAC bytes

  • data (Optional[bytes]) – nonce and mac bytes joined together

AES128_BLK_LEN = 16#
property data: bytes#

NONCE and MAC bytes joined together.

export()#

Export instance into binary form (serialization).

Return type:

bytes

Returns:

binary form

property mac: bytes#

MAC bytes for the encryption/decryption.

property nonce: bytes#

NONCE bytes for the encryption/decryption.

classmethod parse(data)#

Parse binary data and creates the instance (deserialization).

Parameters:

data (bytes) – being parsed

Return type:

Self

Returns:

the instance

property size: int#

Size of binary representation in bytes.

update_aead_encryption_params(nonce, mac)#

Update AEAD encryption parameters for encrypted image.

Parameters:
  • nonce (bytes) – initialization vector, length depends on image size,

  • mac (bytes) – message authentication code used to authenticate decrypted data, 16 bytes

Raises:
Return type:

None

exception spsdk.image.secret.NotImplementedSRKCertificate(desc=None)#

Bases: SRKException

This SRK public key algorithm is not yet implemented.

Initialize the base SPSDK Exception.

exception spsdk.image.secret.NotImplementedSRKItem(desc=None)#

Bases: SRKException

This type of SRK table item is not implemented.

Initialize the base SPSDK Exception.

exception spsdk.image.secret.NotImplementedSRKPublicKeyType(desc=None)#

Bases: SRKException

This SRK public key algorithm is not yet implemented.

Initialize the base SPSDK Exception.

exception spsdk.image.secret.SRKException(desc=None)#

Bases: SPSDKError

SRK table processing exceptions.

Initialize the base SPSDK Exception.

class spsdk.image.secret.SecretKeyBlob(mode, algorithm, flag)#

Bases: object

Secret Key Blob.

Initialize Secret Key Blob.

property blob: bytes#

Data of Secret Key Blob.

export()#

Export of Secret Key Blob.

Return type:

bytes

classmethod parse(data)#

Parse of Secret Key Blob.

Return type:

Self

property size: int#

Size of Secret Key Blob.

class spsdk.image.secret.Signature(version=64, data=None)#

Bases: BaseSecretClass

Class representing a signature.

Initialize the signature.

property data: bytes#

Signature data.

export()#

Export.

Return type:

bytes

classmethod parse(data)#

Parse.

Return type:

Self

property size: int#

Size of a signature.

class spsdk.image.secret.SrkItem#

Bases: object

Base class for items in the SRK Table, see SrkTable class.

We do not inherit from BaseClass because our header parameter is an algorithm identifier, not a version number.

export()#

Serialization to binary form.

Return type:

bytes

Returns:

binary representation of the instance

Raises:

NotImplementedError – Derived class has to implement this method

classmethod from_certificate(cert)#

Pick up the right implementation of an SRK item.

Return type:

SrkItem

hashed_entry()#

This SRK item should be replaced with an incomplete entry with its digest.

Raises:

NotImplementedError – Derived class has to implement this method

Return type:

SrkItem

classmethod parse(data)#

Pick up the right implementation of an SRK item.

Parameters:

data (bytes) – The bytes array of SRK segment

Return type:

Self

Returns:

SrkItem: One of the SrkItem subclasses

Raises:
sha256()#

Export SHA256 hash of the original data.

Raises:

NotImplementedError – Derived class has to implement this method

Return type:

bytes

property size: int#

Size of the exported binary data.

Raises:

NotImplementedError – Derived class has to implement this method

class spsdk.image.secret.SrkItemEcc(key_size, x_coordinate, y_coordinate, flag=0)#

Bases: SrkItem

ECC public key in SRK Table, see SrkTable class.

Initialize the srk table item.

ECC_KEY_TYPE = {EccCurve.SECP256R1: 75, EccCurve.SECP384R1: 77, EccCurve.SECP521R1: 78}#
property algorithm: int#

Algorithm.

export()#

Export.

Return type:

bytes

property flag: int#

Flag.

classmethod from_certificate(cert)#

Create SrkItemEcc from certificate.

Return type:

SrkItemEcc

hashed_entry()#

This SRK item should be replaced with an incomplete entry with its digest.

Return type:

SrkItemHash

classmethod parse(data)#

Parse SRK table item data.

Parameters:

data (bytes) – The bytes array of SRK segment

Return type:

Self

Returns:

SrkItemEcc: SrkItemEcc object

sha256()#

Export SHA256 hash of the data.

Return type:

bytes

property size: int#

Size of an SRK item.

class spsdk.image.secret.SrkItemHash(algorithm, digest)#

Bases: SrkItem

Hashed stub of some public key.

This is a valid entry of the SRK table, it represents some public key of unknown algorithm. Can only provide its hashed value of itself.

Build the stub entry with public key hash only.

Parameters:
  • algorithm (int) – int: Hash algorithm, only SHA256 now

  • digest (bytes) – bytes: Hash digest value

Raises:

SPSDKError – If incorrect algorithm

property algorithm: int#

Hashing algorithm used.

export()#

Export.

Return type:

bytes

hashed_entry()#

This SRK item should be replaced with an incomplete entry with its digest.

Return type:

SrkItemHash

classmethod parse(data)#

Parse SRK table item data.

Parameters:

data (bytes) – The bytes array of SRK segment

Return type:

Self

Returns:

SrkItemHash: SrkItemHash object

Raises:

NotImplementedSRKItem – Unknown tag

sha256()#

Export SHA256 hash of the original data.

Return type:

bytes

property size: int#

Size of an SRK item.

class spsdk.image.secret.SrkItemRSA(modulus, exponent, flag=0)#

Bases: SrkItem

RSA public key in SRK Table, see SrkTable class.

Initialize the srk table item.

property algorithm: int#

Algorithm.

export()#

Export.

Return type:

bytes

property flag: int#

Flag.

classmethod from_certificate(cert)#

Create SRKItemRSA from certificate.

Return type:

SrkItemRSA

hashed_entry()#

This SRK item should be replaced with an incomplete entry with its digest.

Return type:

SrkItemHash

property key_length: int#

Key length of Item in SRK Table.

classmethod parse(data)#

Parse SRK table item data.

Parameters:

data (bytes) – The bytes array of SRK segment

Return type:

Self

Returns:

SrkItemRSA: SrkItemRSA object

sha256()#

Export SHA256 hash of the data.

Return type:

bytes

property size: int#

Size of an SRK item.

class spsdk.image.secret.SrkTable(version=64)#

Bases: BaseSecretClass

SRK table.

Initialize SRT Table.

Parameters:

version (int) – format version

append(srk)#

Add SRK item.

Parameters:

srk (SrkItem) – item to be added

Return type:

None

export()#

Export into binary form (serialization).

Return type:

bytes

Returns:

binary representation of the instance

export_fuses()#

SRK items in binary form, see SRK_fuses.bin file.

Return type:

bytes

get_fuse(index)#

Retrieve fuse value for the given index.

Parameters:

index (int) – of the fuse, 0-7

Return type:

int

Returns:

value of the specified fuse; the value is in format, that cane be used as parameter for SDP efuse_read_once or efuse_write_once

Raises:
classmethod parse(data)#

Parse of SRK table.

Return type:

Self

property size: int#

Size of SRK table.

Data Segments#

Segments within image module.

class spsdk.image.segments.AbstractFCB#

Bases: BaseSegment

Abstract class, predecessor for all FCB classes.

Constructor.

TAG = b'FCB'#
property enabled: bool#

Whether FCB is enabled. Note: it is not generated to output if disabled.

export()#

Export to binary representation (serialization).

Return type:

bytes

Returns:

binary representation

Raises:

NotImplementedError – Derived class has to implement this method

property space: int#

Return length (in bytes) of the exported data including padding (if any).

class spsdk.image.segments.BaseSegment#

Bases: ABC

Base segment.

Initialize the base segment.

PADDING_VALUE = 0#
export()#

Export interface.

Raises:

NotImplementedError – Derived class has to implement this method

Return type:

bytes

property padding_len: int#

Length of padding data in bytes (zero for no padding).

classmethod parse(data)#

Parse interfaces.

Raises:

NotImplementedError – Derived class has to implement this method

Return type:

Self

property size: int#

Size of base segment.

property space: int#

Return length (in bytes) of the exported data including padding (if any).

Please mind, padding is exported optionally.

class spsdk.image.segments.FlexSPIConfBlockFCB#

Bases: AbstractFCB

Flex SPI configuration block; FCB.

Initialize FlexSPIConfBlockFCB.

FORMAT = '<6BH7I5I4B2I4I6I4H'#
TAG = b'FCFB'#
VERSION = b'V\x01\x00\x00'#
export()#

Export into binary form.

Return type:

bytes

Returns:

binary representation used in the bootable image

export_header()#

Export FCB header info binary form.

Return type:

bytes

classmethod parse(data)#

Parse binary data and creates instance of the class.

Parameters:

data (bytes) – data to be parsed

Return type:

Self

Returns:

instance of the class representing the data

Raises:

SPSDKError – If data are not valid Flex SPI configuration block

property size: int#

Length of the binary exported data without padding.

class spsdk.image.segments.PaddingFCB(size, padding_value=0, enabled=True)#

Bases: AbstractFCB

Padding FCB.

Constructor.

Parameters:
  • size (int) – of the exported padding

  • padding_value (int) – byte value used as padding; 0 by default

  • enabled (bool) – whether enabled

Raises:
export()#

Export to binary form (serialization).

Return type:

bytes

Returns:

binary representation

property size: int#

Return size of the exported data in bytes.

class spsdk.image.segments.SegAPP(data=None)#

Bases: BaseSegment

APP segment.

Initialize APP segment.

Parameters:

data (Optional[bytes]) – application binary data

property data: bytes | None#

Application binary data.

export()#

Export segment as bytes array.

Return type:

bytes

Returns:

bytes

property size: int#

Size of APP segment.

class spsdk.image.segments.SegBDS3a#

Bases: BaseSegment

BDS3a segment.

Initialize BDS3a segment.

FORMAT = '<4L'#
HEADER_SIZE = 16#
IMAGES_MAX_COUNT = 6#
SIZE = 256#
export()#

Export segment as bytes array.

Return type:

bytes

Returns:

bytes

property header_size: int#

Header’s size of BDS3a segment.

classmethod parse(data)#

Parse segment from bytes array.

Parameters:

data (bytes) – The bytes array of BDS3a segment

Return type:

Self

Returns:

SegBDS3a object

property size: int#

Size of BDS3a segment.

class spsdk.image.segments.SegBDS3b#

Bases: BaseSegment

BDS3b segment.

Initialize BDS3b segment.

FORMAT = '<4L'#
HEADER_SIZE = 16#
IMAGES_MAX_COUNT = 4#
SIZE = 240#
export()#

Export segment as bytes array.

Return type:

bytes

Returns:

bytes

property header_size: int#

Size of header of BDS3b segment.

classmethod parse(data)#

Parse segment from bytes array.

Parameters:

data (bytes) – The bytes array of BDS3b segment

Return type:

Self

Returns:

SegBDS3b object

property size: int#

Size of BDS3b segment.

class spsdk.image.segments.SegBDT(app_start=0, app_length=0, plugin=0)#

Bases: BaseSegment

Boot Data Table segment.

Initialize BDT segment.

Parameters:
  • app_start (int) – first address of the application

  • app_length (int) – length of the application

  • plugin (int) – 0 .. 2

FORMAT = '<3L'#
SIZE = 12#
export()#

Export segment as bytes array.

Return type:

bytes

Returns:

bytes

classmethod parse(data)#

Parse segment from bytes array.

Parameters:

data (bytes) – The bytes array of BDT segment

Return type:

Self

Returns:

SegBDT object

property plugin: int#

Plugin.

property size: int#

Size of the exported binary data (without padding).

class spsdk.image.segments.SegBEE(regions, max_facs=3)#

Bases: BaseSegment

BEE keys and regions segment.

Constructor.

Parameters:
  • regions (Sequence[BeeRegionHeader]) – list of regions

  • max_facs (int) – maximum total number of FAC in all regions, used for validation

add_region(region)#

Add region.

Parameters:

region (BeeRegionHeader) – to be added

Return type:

None

encrypt_data(start_addr, data)#

Encrypt image data located in any PRDB block.

Parameters:
  • start_addr (int) – start address of the data; must be aligned to block size

  • data (bytes) – to be encrypted

Return type:

bytes

Returns:

encrypted data, aligned to block size; blocks outside any FAC region kept untouched

Raises:

SPSDKError – If invalid start address

export()#

Serialization to binary representation.

Return type:

bytes

Returns:

binary representation of the region (serialization).

classmethod parse(data, decrypt_keys=None)#

De-serialization.

Parameters:
  • data (bytes) – binary data to be parsed

  • decrypt_keys (Optional[list[bytes]]) – list of SW_GP keys used to decrypt EKIB The number of keys must match number of regions to be parsed

Return type:

Self

Returns:

instance created from binary data

property size: int#
Returns:

size of the exported binary data in bytes.

update()#

Updates internal fields of the instance.

Return type:

None

validate()#

Validates settings of the instance.

Raises:

SPSDKError – If number of FAC regions exceeds the limit

Return type:

None

class spsdk.image.segments.SegBIC1(version=0)#

Bases: BaseSegment

Boot Images Container segment.

Initialize Boot Images Container segment.

Parameters:

version (int) – The version of Header for Boot Images Container

FORMAT = '<LH2B2H'#
MAX_NUM_IMGS = 6#
SIZE = 808#
export()#

Export segment as bytes array.

Return type:

bytes

Returns:

bytes

classmethod parse(data)#

Parse segment from bytes array.

Parameters:

data (bytes) – The bytes array of BIC1 segment

Return type:

Self

Returns:

SegBIC1 object

property size: int#

Size.

validate()#

Validate segment.

Return type:

None

property version: int#

Version of Boot Images Container segment.

class spsdk.image.segments.SegBIM#

Bases: BaseSegment

BootImage segment.

Initialize BootImage segment.

FORMAT = '<2L2Q2L'#
SIZE = 128#
export()#

Export segment as bytes array.

Return type:

bytes

Returns:

bytes

classmethod parse(data)#

Parse segment from bytes array.

Parameters:

data (bytes) – The bytes array of BootImage segment

Return type:

Self

Returns:

SegBootImage object

property size: int#

Size of BootImage segment.

class spsdk.image.segments.SegCSF(version=64, enabled=False)#

Bases: BaseSegment

Command Sequence File (CSF), signature block for Secure Boot.

A script of commands used to guide image authentication and device configuration operations.

Initialize CSF segment.

append_command(cmd)#

Append CSF command to the segment.

Parameters:

cmd (CmdBase) – to be added

Raises:

SPSDKError – If invalid command

Return type:

None

clear_commands()#

Removes= all commands.

Return type:

None

property commands: list[CmdBase]#

List of CSF commands in the segment.

export()#

Export segment as bytes array (serialization).

Return type:

bytes

Returns:

bytes

property macs: Iterator[MAC]#

Iterator of all MAC sections.

classmethod parse(data)#

Parse segment from bytes array.

Parameters:

data (bytes) – The bytes array of CSF segment

Raises:
Return type:

Self

Returns:

SegCSF instance

property size: int#

Size of the binary representation of the segment; 0 is not enabled.

property space: int#

Size of the binary representation of the segment including padding; 0 is not enabled.

update(reset_cmddata_offsets)#

Update the offsets for the export.

Parameters:

reset_cmddata_offsets (bool) – True to reset all cmd-data offsets, if cmd-data not specified in the command; False to avoid any reset; Note: reset should be done during parsing process as the data are incomplete

Return type:

None

update_signatures(zulu, data, base_data_addr)#

Update signatures in all CmdAuthData commands.

Parameters:
  • zulu (datetime) – current UTC time+date

  • data (bytes) – currently generated binary data; empty to create “fake” signature to update size of the segment

  • base_data_addr (int) – base address of the generated data

Raises:
Return type:

None

property version: int#

Version of CSF segment.

class spsdk.image.segments.SegDCD(param=65, enabled=False)#

Bases: BaseSegment

Device configuration data (DCD) segment.

IC configuration data, usually is used to configure DDR/SDRAM memory. Typically this is optional

Initialize DCD segment.

append(cmd)#

Appending of Device configuration data (DCD) segment.

Return type:

None

clear()#

Clear of Device configuration data (DCD) segment.

Return type:

None

property commands: list[CmdBase]#

Commands of Device configuration data (DCD) segment.

export()#

Export segment as bytes array.

Return type:

bytes

Returns:

bytes

export_txt(txt_data=None)#

Export txt of Device configuration data (DCD) segment.

Return type:

str

property header: Header#

Header of Device configuration data (DCD) segment.

classmethod parse(data)#

Parse segment from bytes array.

Parameters:

data (bytes) – The bytes array of DCD segment

Raises:

SPSDKCorruptedException – Exception caused by corrupted data

Return type:

Self

Returns:

SegDCD object

classmethod parse_txt(text)#

Parse segment from text file.

Parameters:

text (str) – The string with DCD commands

Return type:

SegDCD

Returns:

SegDCD object

pop(index)#

Popping of Device configuration data (DCD) segment.

Return type:

CmdBase

property size: int#

Size of Device configuration data (DCD) segment.

property space: int#

Add space.

class spsdk.image.segments.SegDcdBuilder#

Bases: object

Builder to create SegDCD from text input.

Initialize SegDcdBuilder.

build(text)#

Parse segment from text file and build SegDCD.

Parameters:

text (str) – input text to import

Return type:

SegDCD

Returns:

SegDCD object

class spsdk.image.segments.SegFCB#

Bases: AbstractFCB, ABC

FCB.

Initialize FCB segment.

FINGERPRINT = b'NFCB'#
SIZE = 1024#
property crc: int#

Cyclic redundancy check.

export()#

Export to binary form.

Return type:

bytes

class spsdk.image.segments.SegIDS3a#

Bases: BaseSegment

IDS3a segment.

Initialize IDS3a segment.

FORMAT = '<3Q4L'#
SIZE = 40#
export()#

Export segment as bytes array.

Return type:

bytes

Returns:

bytes

classmethod parse(data)#

Parse segment from bytes array.

Parameters:

data (bytes) – The bytes array of IDS3a segment

Return type:

Self

Returns:

SegIDS3a object

property size: int#

Size of IDS3a segment.

class spsdk.image.segments.SegIDS3b#

Bases: BaseSegment

IDS3b segment.

Initialize IDS3b segment.

FORMAT = '<3Q2L'#
SIZE = 32#
export()#

Export segment as bytes array.

Return type:

bytes

Returns:

bytes

classmethod parse(data)#

Parse segment from bytes array.

Parameters:

data (bytes) – The bytes array of IDS3b segment

Return type:

Self

Returns:

SegIDS3b object

property size: int#

Size of IDS3b segment.

class spsdk.image.segments.SegIVT2(version)#

Bases: BaseSegment

Image Vector Table, IVT2 segment.

Initialize IVT2 segment.

Parameters:

version (int) – The version of IVT and Image format

FORMAT = '<7L'#
SIZE = 32#
export()#

Export to binary representation (serialization).

Return type:

bytes

Returns:

segment exported as binary data

classmethod parse(data)#

Parse segment from bytes array.

Parameters:

data (bytes) – The bytes array of IVT2 segment

Return type:

Self

Returns:

SegIVT2 object

property size: int#

Size of the binary data.

validate()#

Validate settings of the segment.

Raises:

SPSDKError – If there is configuration problem

Return type:

None

property version: int#

The version of IVT and Image format.

class spsdk.image.segments.SegIVT3a(param)#

Bases: BaseSegment

IVT3a segment.

Initialize IVT segment.

Parameters:

param (int) – The version of IVT and Image format

FORMAT = '<1L5Q'#
SIZE = 48#
export()#

Export segment as bytes array.

Return type:

bytes

Returns:

bytes

property header: Header#

Header of IVT3a segment.

classmethod parse(data)#

Parse segment from bytes array.

Parameters:

data (bytes) – The bytes array of IVT3a segment

Return type:

Self

Returns:

SegIVT3a object

property size: int#

Size of IVT3a segment.

validate()#

Validation of IVT3a segment.

Return type:

None

class spsdk.image.segments.SegIVT3b(version)#

Bases: BaseSegment

IVT3b segment.

Initialize IVT segment.

Parameters:

version (int) – The version of IVT and Image format

FORMAT = '<1L7Q'#
SIZE = 64#
export()#

Export segment as bytes array.

Return type:

bytes

Returns:

bytes

property header: Header#

Header of IVT3b segment.

classmethod parse(data)#

Parse segment from bytes array.

Parameters:

data (bytes) – The bytes array of IVT3b segment

Return type:

Self

Returns:

SegIVT3b object

property size: int#

Size of IVT3b segment.

:return size

validate()#

Validation of IVT3b segment.

Return type:

None

class spsdk.image.segments.SegSIGB(version=0)#

Bases: BaseSegment

SignatureBlock segment.

Initialize SignatureBlock segment.

FORMAT = '<4HL'#
SIZE = 16#
export()#

Export segment as bytes array.

Return type:

bytes

Returns:

bytes

classmethod parse(data)#

Parse segment from bytes array.

Parameters:

data (bytes) – The bytes array of SignatureBlock segment

Return type:

Self

Returns:

SegSigBlk object

property size: int#

Size of Signature Block segment.

property version: int#

Version of Signature Block segment.

class spsdk.image.segments.SegXMCD(header, config_data)#

Bases: BaseSegment

External Memory Configuration Data Segment.

Initialize XMCD Segment.

Parameters:
  • header (XMCDHeader) – XMCD Header

  • config_data (bytes) – XMCD configuration data

TAG = 192#
export()#

Export segment as bytes (serialization).

Return type:

bytes

classmethod parse(data)#

Parse XMCD from binary data.

Return type:

Self

class spsdk.image.segments.XMCDHeader(interface=0, instance=0, block_type=0, block_size=4)#

Bases: object

External Memory Configuration Data Header.

Initialize XMCD Header.

Parameters:
  • interface (int) – Type of the XMCD instance (0 - FlexSPI, 1 - SEMC), defaults to 0

  • instance (int) – Number of the interface instance, defaults to 0

  • block_type (int) – Type of XMCD data (0 - Simplified, 1 - Full), defaults to 0

  • block_size (int) – XMCD data block size, defaults to 4

Raises:
FORMAT = '<4B'#
SIZE = 4#
TAG = 12#
property config_data_size: int#

Size of XMCD config data blob.

export()#

Export segment’s header as bytes (serialization).

Return type:

bytes

classmethod parse(data)#

Parse XMCD Header from binary data.

Return type:

Self

Image Segments#

This module contains generic implementation of image segment.

class spsdk.image.segments_base.SegmentBase(family, revision)#

Bases: BaseClass

Base class for image segment.

Segment base Constructor.

Parameters:
  • family (str) – Chip family.

  • revision (str) – Optional Chip family revision.

Raises:

SPSDKValueError – Unsupported family.

FEATURE = 'unknown'#
abstract create_config()#

Create current configuration YAML.

Return type:

str

Returns:

Configuration of segment.

export()#

Export block binary.

Return type:

bytes

Returns:

Binary representation of segment.

classmethod get_memory_types_config(family, revision='latest')#

Get memory types data from database.

Parameters:
  • family (str) – Chip family.

  • revision (str) – Optional Chip family revision.

Return type:

dict[str, dict]

classmethod get_supported_families()#

Return list of supported families.

Return type:

list

Returns:

List of supported families.

classmethod get_supported_memory_types(family=None, revision='latest')#

Get list of supported memory types data from database.

Parameters:
  • family (Optional[str]) – Chip family.

  • revision (str) – Optional Chip family revision.

Return type:

list[MemoryType]

abstract static load_from_config(config)#

Load configuration file.

Parameters:

config (dict) – Segment configuration file.

Return type:

Any

Returns:

Segment object.

abstract property registers: Registers#

Registers of segment.

TrustZone#

Module provides support for TrustZone configuration data.

class spsdk.image.trustzone.TrustZone(family='Unknown', revision='latest', tz_type=TrustZoneType(tag=0, label='ENABLED', description='TrustZone enabled with default settings'), customizations=None, raw_data=None)#

Bases: object

Provide creation of binary data to set up the TrustZone engine in CM-33.

Initialize the trustzone.

classmethod custom(family, customizations, revision='latest')#

Alternate constructor for CUSTOM type of TrustZone.

Return type:

TrustZone

classmethod disabled()#

Alternate constructor for DISABLED type of TrustZone.

Return type:

TrustZone

Returns:

TrustZone object

classmethod enabled()#

Alternate constructor for ENABLED type of TrustZone.

Return type:

TrustZone

Returns:

TrustZone object

export()#

Return the TrustZone data as bytes.

Return type:

bytes

classmethod from_binary(family, raw_data, revision='latest')#

Alternate constructor using existing binary data.

Return type:

TrustZone

classmethod from_config(config_data)#

Alternate constructor using configuration data.

Raises:

SPSDKError – Invalid configuration file.

Return type:

TrustZone

Returns:

TrustZone class instance.

classmethod generate_config_template(family, revision='latest')#

Generate configuration for selected family.

Parameters:
  • family (str) – Family description.

  • revision (str) – Chip revision specification, as default, latest is used.

Raises:

SPSDKError – Revision is not supported.

Return type:

dict[str, str]

Returns:

Dictionary of individual templates (key is name of template, value is template itself).

classmethod get_preset_data_size(family, revision='latest')#

Get size of preset data in binary form.

Parameters:
  • family (str) – Family description.

  • revision (str) – Chip revision specification, as default, latest is used.

Raises:

SPSDKValueError – Family or revision is not supported.

Return type:

int

Returns:

Size of TZ data.

static get_supported_families()#

Return list of supported families.

Return type:

list[str]

classmethod get_validation_schemas(family, revision='latest')#

Create the validation schema.

Parameters:
  • family (str) – Family description.

  • revision (str) – Chip revision specification, as default, latest is used.

Raises:

SPSDKError – Family or revision is not supported.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas.

classmethod get_validation_schemas_family()#

Create the validation schema just for supported families.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas for TZ supported families.

static validate_custom_data(data, customizations)#

Check whether all register names in custom data are valid (present in presets).

Return type:

bool

class spsdk.image.trustzone.TrustZoneType(tag, label, description=None)#

Bases: SpsdkEnum

Enum defining various types of TrustZone types.

CUSTOM = (1, 'CUSTOM', 'TrustZone enabled with custom settings')#
DISABLED = (2, 'DISABLED', 'Disabled')#
ENABLED = (0, 'ENABLED', 'TrustZone enabled with default settings')#

Support for BEE encryption for RT10xx devices#

Contains support for BEE encryption.

class spsdk.image.bee.BeeBaseClass#

Bases: object

BEE base class.

classmethod check_data_to_parse(data)#

Deserialization.

Parameters:

data (bytes) – binary data to be parsed

Raises:

SPSDKError – If size of the data is not sufficient

Return type:

None

export()#
Return type:

bytes

Returns:

binary representation of the region (serialization).

classmethod get_size()#
Return type:

int

Returns:

size of the exported binary data in bytes.

property size: int#
Returns:

size of the exported binary data in bytes.

update()#

Updates internal fields of the instance.

Return type:

None

validate()#

Validates the configuration of the instance.

It is recommended to call the method before export and after parsing.

Return type:

None

class spsdk.image.bee.BeeFacRegion(start=0, length=0, protected_level=0)#

Bases: BeeBaseClass

BEE Factory Access Control (FAC) region.

Constructor.

Parameters:
  • start (int) – Start address of one FAC region, align at 1KB boundary; 32-bit number

  • length (int) – Length of one FAC region, align at 1KB boundary; 32-bit number

  • protected_level (int) – Protected level: 0/1/2/3; 32-bit number

property end_addr: int#
Returns:

end address of the region (which is last address of the region + 1).

export()#

Exports the binary representation.

Return type:

bytes

classmethod parse(data)#

Deserialization.

Parameters:

data (bytes) – binary data to be parsed

Return type:

Self

Returns:

instance created from binary data

Raises:

SPSDKError – If reserved area is non-zero

validate()#

Validates the configuration of the instance.

Return type:

None

class spsdk.image.bee.BeeKIB(kib_key=None, kib_iv=None)#

Bases: BeeBaseClass

BEE Key block.

Contains keys used to encrypt PRDB content.

Constructor.

Parameters:
  • kib_key (Optional[bytes]) – AES key

  • kib_iv (Optional[bytes]) – AES initialization vector

export()#

Exports binary representation of the region (serialization).

Return type:

bytes

classmethod parse(data)#

Deserialization.

Parameters:

data (bytes) – binary data to be parsed

Return type:

Self

Returns:

instance created from binary data

validate()#

Validates settings of the instance.

Raises:
Return type:

None

class spsdk.image.bee.BeeNxp(headers, input_image, base_address)#

Bases: object

BeeNxp class.

Constructor.

Parameters:
  • headers (list[Optional[BeeRegionHeader]]) – list of BEE Region Headers

  • input_image (bytes) – Input image to be encrypted

  • base_address (int) – Base address of the image

static check_overlaps(bee_headers, start_addr)#

Check for overlaps in regions.

Parameters:
  • bee_headers (list[Optional[BeeRegionHeader]]) – List of BeeRegionHeader

  • start_addr (int) – start address of a region to be checked

Raises:

SPSDKOverlapError – if the address is inside any region

Return type:

None

export_headers()#

Export BEE headers.

Return type:

list[Optional[bytes]]

Returns:

BEE region headers

export_image()#

Export encrypted binary image.

Return type:

bytes

Returns:

encrypted image

static generate_config_template()#

Generate BEE configuration template.

Return type:

str

Returns:

Dictionary of individual templates (key is name of template, value is template itself).

static get_supported_families()#

Get all supported families for BEE.

Return type:

list[str]

Returns:

List of supported families.

static get_validation_schemas()#

Get list of validation schemas.

Return type:

list[dict[str, Any]]

Returns:

Validation list of schemas.

static load_from_config(config, search_paths=None)#

Converts the configuration into an BEE image object.

“config” contains dictionary of configurations.

Raises:

SPSDKError – if the count of BEE engines is invalid.

Parameters:
  • config (dict[str, Any]) – Configuration dictionary.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

BeeNxp

Returns:

initialized BeeNxp object.

class spsdk.image.bee.BeeProtectRegionBlock(encr_mode=BeeProtectRegionBlockAesMode(tag=1, label='CTR', description=None), lock_options=0, counter=None)#

Bases: BeeBaseClass

BEE protect region block (PRDB).

Constructor.

Parameters:
  • encr_mode (BeeProtectRegionBlockAesMode) – AES encryption mode

  • lock_options (int) – Lock options; 32-bit number

  • counter (Optional[bytes]) – Counter for AES-CTR mode; 16 bytes; by default, random value is used

FAC_REGIONS = 4#
SIZE = 256#
TAGH = 1380206661#
TAGL = 1598505300#
VERSION = 1442906112#
add_fac(fac)#

Append FAC region.

Parameters:

fac (BeeFacRegion) – Factory Access Control to be added

Return type:

None

encrypt_block(key, start_addr, data)#

Encrypt block located in any FAC region.

Parameters:
  • key (bytes) – user for encryption

  • start_addr (int) – start address of the data

  • data (bytes) – binary block to be encrypted; the block size must be BEE_ENCR_BLOCK_SIZE

Return type:

bytes

Returns:

encrypted block if it is inside any FAC region; untouched block if it is not in any FAC region

Raises:
  • SPSDKError – When incorrect length of binary block

  • SPSDKError – When encryption mode different from AES/CTR provided

  • SPSDKError – When invalid length of key

  • SPSDKError – When invalid range of region

export()#
Return type:

bytes

Returns:

binary representation of the region (serialization).

property fac_count: int#
Returns:

number of Factory Access Control regions.

classmethod get_size()#
Return type:

int

Returns:

size of the exported binary data in bytes.

is_inside_region(start_addr)#

Returns true if the start address lies within any FAC region.

Parameters:

start_addr (int) – start address of the data

Return type:

bool

classmethod parse(data)#

Deserialization.

Parameters:

data (bytes) – binary data to be parsed

Return type:

Self

Returns:

instance created from binary data

Raises:

SPSDKError – If format does not match

update()#

Updates start and end address of the encryption region.

Return type:

None

validate()#

Validates settings of the instance.

Return type:

None

class spsdk.image.bee.BeeProtectRegionBlockAesMode(tag, label, description=None)#

Bases: SpsdkEnum

AES mode selection for BEE PRDB encryption.

CTR = (1, 'CTR')#
ECB = (0, 'ECB')#
class spsdk.image.bee.BeeRegionHeader(prdb=None, sw_key=None, kib=None)#

Bases: BeeBaseClass

BEE keys and regions header.

Constructor.

Parameters:
  • prdb (Optional[BeeProtectRegionBlock]) – protect region block; None to use default

  • sw_key (Optional[bytes]) – key used to encrypt KIB content

  • kib (Optional[BeeKIB]) – keys block; None to use default

PRDB_OFFSET = 128#
SIZE = 512#
add_fac(fac)#

Append FAC region.

Parameters:

fac (BeeFacRegion) – to be added

Return type:

None

encrypt_block(start_addr, data)#

Encrypt block located in any FAC region.

Parameters:
  • start_addr (int) – start address of the data

  • data (bytes) – binary block to be encrypted; the block size must be BEE_ENCR_BLOCK_SIZE

Return type:

bytes

Returns:

encrypted block if it is inside any FAC region; untouched block if it is not in any FAC region

export()#

Serialization to binary representation.

Return type:

bytes

Returns:

binary representation of the region (serialization).

property fac_regions: Sequence[BeeFacRegion]#
Returns:

lift of Factory Access Control regions.

classmethod get_size()#
Return type:

int

Returns:

size of the exported binary data in bytes.

is_inside_region(start_addr)#

Returns true if the start address lies within any FAC region.

Parameters:

start_addr (int) – start address of the data

Return type:

bool

classmethod parse(data, sw_key=b'')#

Deserialization.

Parameters:
  • data (bytes) – binary data to be parsed

  • sw_key (bytes) – SW key used to decrypt the EKIB data

Return type:

Self

Returns:

instance created from binary data

Raises:

SPSDKError – If invalid sw key

sw_key_fuses()#
Return type:

Sequence[int]

Returns:

sequence of fuse values for SW key to be burned into processor.

The result is ordered, first value should be burned to the lowest address.

update()#

Updates internal fields of the instance.

Return type:

None

validate()#

Validates settings of the instance.

Raises:

SPSDKError – If settings invalid

Return type:

None

Support for KeyStore used in MasterBootImage#

Module provides support for KeyStore used in MasterBootImage.

class spsdk.image.keystore.KeySourceType(tag, label, description=None)#

Bases: SpsdkEnum

Device key source.

KEYSTORE = (1, 'KEYSTORE', 'Device keys stored in KeyStore')#
OTP = (0, 'OTP', 'Device keys stored in OTP')#
class spsdk.image.keystore.KeyStore(key_source, key_store=None)#

Bases: object

Provide info about KeyStore for MaterBootImage.

Initialize Keystore.

Parameters:
  • key_source (KeySourceType) – device key source

  • key_store (Optional[bytes]) – initial content of the key store in the bootable image; None if empty

Raises:
  • SPSDKError – If invalid key-store size

  • SPSDKError – KeyStore can be initialized only if key_source == KEYSTORE

KEY_STORE_SIZE = 1424#
OTFAD_KEY_SIZE = 16#
OTP_MASTER_KEY_SIZE = 32#
SBKEK_SIZE = 32#
static derive_enc_image_key(master_key)#

Derive “enc_image_key” from master key.

Parameters:

master_key (bytes) – stored in OTP

Return type:

bytes

Returns:

key used to decrypt encrypted images during boot

Raises:

SPSDKError – If invalid length of master key

static derive_hmac_key(hmac_key)#

Derive HMAC from master or user key.

Parameters:

hmac_key (bytes) – either master-key (for key_source == OTP) or user key (for key_source == KEYSTORE)

Return type:

bytes

Returns:

key used for image header authentication in LoadToRam images

Raises:

SPSDKError – If invalid length of hmac key

static derive_otfad_kek_key(master_key, otfad_input)#

Derive OTFAD KEK key from master key and OTFAD input.

Parameters:
  • master_key (bytes) – 32 bytes key, stored in OTP

  • otfad_input (bytes) – 16 bytes input, stored in OTP

Return type:

bytes

Returns:

OTFAD encryption key for FLASH encryption/decryption

Raises:
static derive_sb_kek_key(master_key)#

Derive SBKEK key from master key.

Parameters:

master_key (bytes) – 32 bytes key, stored in OTP

Return type:

bytes

Returns:

encryption key to handle SB2 file (update capsule)

Raises:

SPSDKError – If invalid length of master key

export()#

Binary key store content; empty bytes for empty key-store.

Return type:

bytes

property key_source: KeySourceType#

Device key source.

Master Boot Image#

Master Boot Image.

class spsdk.image.mbi.mbi.MasterBootImage(**kwargs)#

Bases: object

Master Boot Image Interface.

Initialization of MBI.

Parameters:

kwargs (Any) – Various input parameters based on used dynamic class.

IMAGE_TYPE = (0, 'Plain Image (either XIP or Load-to-RAM)')#
app: Optional[bytes]#
property app_len: int#

Compute application data length.

Returns:

Final image data length.

app_table: Optional[MultipleImageTable]#
cert_block: Union[CertBlockV1, CertBlockV21, CertBlockVx, None]#
collect_data: Callable[[], BinaryImage]#
create_config(output_folder)#

Create configuration file and its data files from the MBI class.

Parameters:

output_folder (str) – Output folder to store the parsed data

Return type:

dict[str, Any]

Returns:

Configuration dictionary.

disassemble_image: Callable[[bytes], None]#
encrypt: Callable[[BinaryImage, bool], BinaryImage]#
export()#

Export final bootable image.

Return type:

bytes

Returns:

Bootable Image in bytes.

export_image()#

Export final bootable image.

Return type:

BinaryImage

Returns:

Bootable Image in Binary Image format.

finalize: Callable[[BinaryImage, bool], BinaryImage]#
classmethod get_image_type(family, data, revision='latest')#

Get image type from MBI data and family.

Parameters:
  • family (str) – device family to be fetched from DB

  • data (bytes) – MBI raw data

  • revision (str) – Optional chip family revision.

Return type:

int

Returns:

Image type int representation

classmethod get_validation_schemas(family)#

Create the validation schema for current image type.

Parameters:

family (str) – Family description.

Return type:

list[dict[str, Any]]

Returns:

Validation schema.

classmethod get_validation_schemas_family()#

Create the validation family schema for current image type.

Return type:

list[dict[str, Any]]

Returns:

Validation schema.

classmethod hash()#

Unique identifier for MasterBootImage class based on mixins.

Return type:

str

Returns:

Acronym for each MBI base class separated by “-”

load_from_config(config, search_paths=None)#

Load configuration from dictionary.

Parameters:
  • config (dict[str, Any]) – Dictionary with configuration fields.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

None

static parse(family, data, dek=None, revision='latest')#

Parse the final image to individual fields.

Parameters:
  • family (str) – Device family

  • data (bytes) – Final Image in bytes

  • dek (Optional[str]) – The decryption key for encrypted images

  • revision (str) – Optional chip family revision.

Raises:

SPSDKParsingError – Cannot determinate the decoding class

Return type:

MasterBootImage

Returns:

MBI parsed class

post_encrypt: Callable[[BinaryImage, bool], BinaryImage]#
property rkth: bytes | None#

Get Root Key Table Hash from certificate block if present.

Returns:

Root Key Table Hash as hex string.

sign: Callable[[BinaryImage, bool], BinaryImage]#
property total_len: int#

Compute Master Boot Image data length.

Returns:

Final image data length.

property total_length_for_cert_block: int#

Compute Master Boot Image data length.

Returns:

Final image data length.

validate()#

Validate the setting of image.

Return type:

None

spsdk.image.mbi.mbi.create_mbi_class(name, family, revision='latest')#

Create Master Boot image class.

Parameters:
  • name (str) – Name of Class

  • family (str) – Name of chip family

  • revision (str) – Optional chip family revision.

Return type:

Type[MasterBootImage]

Returns:

Master Boot Image class

spsdk.image.mbi.mbi.get_all_mbi_classes()#

Get all Master Boot Image supported classes.

Return type:

list[Type[MasterBootImage]]

Returns:

List with all MBI Classes.

spsdk.image.mbi.mbi.get_mbi_class(config)#

Get Master Boot Image class.

Raises:

SPSDKUnsupportedImageType – The invalid configuration.

Return type:

Type[MasterBootImage]

Returns:

MBI Class.

spsdk.image.mbi.mbi.get_mbi_classes(family, revision='latest')#

Get all Master Boot Image supported classes for chip family.

Parameters:
  • family (str) – Chip family.

  • revision (str) – Optional chip family revision.

Raises:

SPSDKValueError – The invalid family.

Return type:

dict[str, tuple[Type[MasterBootImage], str, str]]

Returns:

Dictionary with key like image name and values are Tuple with it’s MBI Class and target and authentication type.

spsdk.image.mbi.mbi.mbi_generate_config_templates(family, revision='latest')#

Generate all possible configuration for selected family.

Parameters:
  • family (str) – Family description.

  • revision (str) – Optional chip family revision.

Return type:

dict[str, str]

Returns:

Dictionary of individual templates (key is name of template, value is template itself).

spsdk.image.mbi.mbi.mbi_get_supported_families()#

Get supported families by MBI.

Return type:

list[str]

Returns:

List of supported family names.

Master Boot Image - miscellaneous functions#

Misc.

exception spsdk.image.misc.NotEnoughBytesException(desc=None)#

Bases: RawDataException

Read_raw_data could not read enough data.

Initialize the base SPSDK Exception.

exception spsdk.image.misc.RawDataException(desc=None)#

Bases: SPSDKError

Raw data read failed.

Initialize the base SPSDK Exception.

exception spsdk.image.misc.StreamReadFailed(desc=None)#

Bases: RawDataException

Read_raw_data could not read stream.

Initialize the base SPSDK Exception.

spsdk.image.misc.dict_diff(main, mod)#

Return a difference between two dictionaries if key is not present in main, it’s skipped.

Return type:

dict

spsdk.image.misc.hexdump_fmt(data, tab=4, length=16, sep=':')#

Dump some potentially larger data in hex.

Return type:

str

spsdk.image.misc.modulus_fmt(modulus, tab=4, length=15, sep=':')#

Modulus format.

Return type:

str

spsdk.image.misc.read_raw_data(stream, length, index=None, no_seek=False)#

Read raw data.

Return type:

bytes

spsdk.image.misc.read_raw_segment(buffer, segment_tag, index=None)#

Read raw segment.

Return type:

bytes

Master Boot Image - mixin classes#

Master Boot Image.

class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixin#

Bases: object

Base MBI Export Mixin class.

collect_data()#

Collect basic data to create image.

Return type:

BinaryImage

Returns:

Collected raw image.

disassemble_image(image)#

Disassemble image to individual parts from image.

Parameters:

image (bytes) – Image.

Return type:

None

encrypt(image, revert=False)#

Encrypt image if needed.

Parameters:
  • image (BinaryImage) – Input raw image to encrypt.

  • revert (bool) – Revert the operation if possible.

Return type:

BinaryImage

Returns:

Encrypted image.

finalize(image, revert=False)#

Finalize the image for export.

This part could add HMAC/KeyStore etc.

Parameters:
  • image (BinaryImage) – Input image.

  • revert (bool) – Revert the operation if possible.

Return type:

BinaryImage

Returns:

Finalized image suitable for export.

post_encrypt(image, revert=False)#

Optionally do some post encrypt image updates.

Parameters:
  • image (BinaryImage) – Encrypted image.

  • revert (bool) – Revert the operation if possible.

Return type:

BinaryImage

Returns:

Updated encrypted image.

sign(image, revert=False)#

Sign image (by signature or CRC).

Parameters:
  • image (BinaryImage) – Image to sign.

  • revert (bool) – Revert the operation if possible.

Return type:

BinaryImage

Returns:

Optionally signed image.

class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinApp#

Bases: Mbi_ExportMixin

Export Mixin to handle simple application data.

app: Optional[bytes]#
collect_data()#

Collect application data including update IVT.

Return type:

BinaryImage

Returns:

Image with updated IVT.

total_len: Any#
update_ivt: Callable[[bytes, int, int], bytes]#
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppBcaFcf#

Bases: Mbi_ExportMixin

Export Mixin to handle simple application data with BCA and FCF.

IMG_BCA_OFFSET: int#
IMG_DATA_START: int#
IMG_DIGEST_OFFSET: int#
IMG_DUK_BLOCK_OFFSET: int#
IMG_FCF_LIFECYCLE_OFFSET: int#
IMG_FCF_OFFSET: int#
IMG_FCF_SIZE: int#
IMG_ISK_HASH_OFFSET: int#
IMG_ISK_OFFSET: int#
IMG_SIGNATURE_OFFSET: int#
IMG_WPC_MFG_CA_CERT_OFFSET: int#
IMG_WPC_PU_CERT_OFFSET: int#
IMG_WPC_ROOT_CA_CERT_HASH_OFFSET: int#
app: Optional[bytes]#
collect_data()#

Collect application data.

Return type:

BinaryImage

Returns:

Binary Image with updated BCA and FCF.

disassemble_image(image)#

Disassemble image to individual parts from image.

Parameters:

image (bytes) – Image.

Return type:

None

just_header: bool#
total_len: int#
update_bca: Callable[[bytes, int], bytes]#
update_fcf: Callable[[bytes], bytes]#
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppCertBlockManifest#

Bases: Mbi_ExportMixin

Export Mixin to handle simple application data, Certification block and Manifest.

app: Optional[bytes]#
app_len: int#
cert_block: Union[CertBlockV1, CertBlockV21, None]#
collect_data()#

Collect application data, Certification Block and Manifest including update IVT.

Raises:

SPSDKError – When either application data or certification block or manifest is missing

Return type:

BinaryImage

Returns:

Image with updated IVT and added Certification Block with Manifest.

data_to_sign: Optional[bytes]#
disassemble_image(image)#

Disassemble image to individual parts from image.

Parameters:

image (bytes) – Image.

Return type:

None

disassembly_app_data: Callable[[bytes], bytes]#
finalize(image, revert=False)#

Finalize the image for export by adding HMAC a optionally KeyStore.

Parameters:
  • image (BinaryImage) – Input image.

  • revert (bool) – Revert the operation if possible.

Return type:

BinaryImage

Returns:

Finalized image suitable for export.

ivt_table: Mbi_MixinIvt#
manifest: Optional[TypeVar(T_Manifest, MasterBootImageManifest, MasterBootImageManifestDigest, MasterBootImageManifestCrc)]#
total_len: int#
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppFcf#

Bases: Mbi_ExportMixin

Export Mixin to handle simple application data with FCF.

IMG_BCA_OFFSET: int#
IMG_DATA_START: int#
IMG_DIGEST_OFFSET: int#
IMG_DUK_BLOCK_OFFSET: int#
IMG_FCF_LIFECYCLE_OFFSET: int#
IMG_FCF_OFFSET: int#
IMG_FCF_SIZE: int#
IMG_ISK_HASH_OFFSET: int#
IMG_ISK_OFFSET: int#
IMG_SIGNATURE_OFFSET: int#
IMG_WPC_MFG_CA_CERT_OFFSET: int#
IMG_WPC_PU_CERT_OFFSET: int#
IMG_WPC_ROOT_CA_CERT_HASH_OFFSET: int#
app: Optional[bytes]#
collect_data()#

Get app data and update FCF.

Return type:

BinaryImage

Returns:

Binary Image with updated FCF.

update_fcf: Callable[[bytes], bytes]#
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTrustZone#

Bases: Mbi_ExportMixin

Export Mixin to handle simple application data and TrustZone.

app: Optional[bytes]#
app_table: MultipleImageTable#
clean_ivt: Callable[[bytes], bytes]#
collect_data()#

Collect application data and TrustZone including update IVT.

Return type:

BinaryImage

Returns:

Image with updated IVT and added TrustZone.

disassemble_image(image)#

Disassemble image to individual parts from image.

Parameters:

image (bytes) – Image.

Return type:

None

disassembly_app_data: Callable[[bytes], bytes]#
total_len: Any#
trust_zone: TrustZone#
update_ivt: Callable[[bytes, int, int], bytes]#
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTrustZoneCertBlock#

Bases: Mbi_ExportMixin

Export Mixin to handle simple application data, TrustZone and Certification block.

app: Optional[bytes]#
app_len: int#
app_table: MultipleImageTable#
cert_block: Union[CertBlockV1, CertBlockV21, None]#
collect_data()#

Collect application data and TrustZone including update IVT.

Return type:

BinaryImage

Returns:

Image with updated IVT and added TrustZone.

disassemble_image(image)#

Disassemble image to individual parts from image.

Parameters:

image (bytes) – Image.

Return type:

None

disassembly_app_data: Callable[[bytes], bytes]#
ivt_table: Mbi_MixinIvt#
total_len: int#
total_length_for_cert_block: int#
trust_zone: TrustZone#
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTrustZoneCertBlockEncrypt#

Bases: Mbi_ExportMixin

Export Mixin to handle simple application data, TrustZone and Certification block.

HMAC_OFFSET: int#
app: Optional[bytes]#
app_len: int#
app_table: MultipleImageTable#
cert_block: Union[CertBlockV1, CertBlockV21, None]#
collect_data()#

Collect application data and TrustZone including update IVT.

Return type:

BinaryImage

Returns:

Image with updated IVT and added TrustZone.

ctr_init_vector: bytes#
disassemble_image(image)#

Disassemble image to individual parts from image.

Parameters:

image (bytes) – Image.

Return type:

None

disassembly_app_data: Callable[[bytes], bytes]#
encrypt(image, revert=False)#

Encrypt image if needed.

Parameters:
  • image (BinaryImage) – Input raw image to encrypt.

  • revert (bool) – Revert the operation if possible.

Return type:

BinaryImage

Returns:

Encrypted image.

family: str#
hmac_key: Optional[bytes]#
property img_len: int#

Image length of encrypted legacy image.

ivt_table: Mbi_MixinIvt#
key_store: Optional[KeyStore]#
post_encrypt(image, revert=False)#

Optionally do some post encrypt image updates.

Parameters:
  • image (BinaryImage) – Encrypted image.

  • revert (bool) – Revert the operation if possible.

Return type:

BinaryImage

Returns:

Updated encrypted image.

revision: str#
total_len: int#
trust_zone: TrustZone#
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinCrcSign#

Bases: Mbi_ExportMixin

Export Mixin to handle sign by CRC.

IVT_CRC_CERTIFICATE_OFFSET: int#
sign(image, revert=False)#

Do simple calculation of CRC and return updated image with it.

Parameters:
  • image (BinaryImage) – Input raw image.

  • revert (bool) – Revert the operation if possible.

Return type:

BinaryImage

Returns:

Image enriched by CRC in IVT table.

update_crc_val_cert_offset: Callable[[bytes, int], bytes]#
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinCrcSignBca#

Bases: Mbi_ExportMixin

Export Mixin to handle sign by CRC in BCA.

IMG_BCA_OFFSET: int#
IMG_DATA_START: int#
sign(image, revert=False)#

Do simple calculation of CRC and return updated image with it.

Parameters:
  • image (BinaryImage) – Input raw image.

  • revert (bool) – Revert the operation if possible.

Return type:

BinaryImage

Returns:

Image enriched by CRC of application.

class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinEccSign#

Bases: Mbi_ExportMixin

Export Mixin to handle sign by ECC.

cert_block: Union[CertBlockV1, CertBlockV21, None]#
data_to_sign: Optional[bytes]#
sign(image, revert=False)#

Do calculation of ECC signature and return updated image with it.

Parameters:
  • image (BinaryImage) – Input raw image.

  • revert (bool) – Revert the operation if possible.

Return type:

BinaryImage

Returns:

Image enriched by ECC signature at end of image.

signature_provider: Optional[SignatureProvider]#
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinEccSignVx#

Bases: Mbi_ExportMixin

Export Mixin to handle sign by ECC.

IMG_BCA_OFFSET: int#
IMG_DATA_START: int#
IMG_DIGEST_OFFSET: int#
IMG_DIGEST_SIZE: int#
IMG_ISK_HASH_OFFSET: int#
IMG_ISK_HASH_SIZE: int#
IMG_ISK_OFFSET: int#
IMG_SIGNED_HEADER_END: int#
add_hash: bool#
app: Optional[bytes]#
cert_block: CertBlockVx#
sign(image, revert=False)#

Do calculation of ECC signature and digest and return updated image with it.

Parameters:
  • image (BinaryImage) – Input raw image.

  • revert (bool) – Revert the operation if possible.

Return type:

BinaryImage

Returns:

Image enriched by ECC signature and SHA256 digest.

signature_provider: Optional[SignatureProvider]#
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinHmacKeyStoreFinalize#

Bases: Mbi_ExportMixin

Export Mixin to handle finalize by HMAC and optionally KeyStore.

HMAC_OFFSET: int#
HMAC_SIZE: int#
compute_hmac: Callable[[bytes], bytes]#
finalize(image, revert=False)#

Finalize the image for export by adding HMAC a optionally KeyStore.

Parameters:
  • image (BinaryImage) – Input image.

  • revert (bool) – Revert the operation if possible.

Return type:

BinaryImage

Returns:

Finalized image suitable for export.

ivt_table: Mbi_MixinIvt#
key_store: Optional[KeyStore]#
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinRsaSign#

Bases: Mbi_ExportMixin

Export Mixin to handle sign by RSA.

cert_block: Union[CertBlockV1, CertBlockV21, None]#
sign(image, revert=False)#

Do calculation of RSA signature and return updated image with it.

Parameters:
  • image (BinaryImage) – Input raw image.

  • revert (bool) – Revert the operation if possible.

Return type:

BinaryImage

Returns:

Image enriched by RSA signature at end of image.

signature_provider: Optional[SignatureProvider]#
class spsdk.image.mbi.mbi_mixin.Mbi_Mixin#

Bases: object

Base class for Master BOtt Image Mixin classes.

COUNT_IN_LEGACY_CERT_BLOCK_LEN: bool = True#
NEEDED_MEMBERS: dict[str, Any] = {}#
PRE_PARSED: list[str] = []#
VALIDATION_SCHEMAS: list[str] = []#
mix_app_len()#

Compute application data length of individual mixin.

Return type:

int

Returns:

Application data length of atomic Mixin.

mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

classmethod mix_get_extra_validation_schemas()#

Get extra-non standard validation schemas from mixin.

Return type:

list[dict[str, Any]]

Returns:

List of additional validation schemas.

mix_len()#

Compute length of individual mixin.

Return type:

int

Returns:

Length of atomic Mixin.

mix_load_from_config(config)#

Load configuration of mixin from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

mix_validate()#

Validate the setting of image.

Return type:

None

class spsdk.image.mbi.mbi_mixin.Mbi_MixinApp#

Bases: Mbi_Mixin

Master Boot Image App class.

NEEDED_MEMBERS: dict[str, Any] = {'_app': b'', 'app_ext_memory_align': 4096}#
VALIDATION_SCHEMAS: list[str] = ['app']#
property app: bytes#

Application data.

app_ext_memory_align: int#
load_binary_image_file(path)#

Load binary image from file (S19,HEX,BIN).

Parameters:

path (str) – File path

Raises:

SPSDKError – If invalid data file is detected.

Return type:

None

mix_app_len()#

Compute application data length of individual mixin.

Return type:

int

Returns:

Application data length of atomic Mixin.

mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_len()#

Get size of plain input application image.

Return type:

int

Returns:

Length of application.

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_validate()#

Validate the app.

Raises:

SPSDKError – The application format is invalid.

Return type:

None

search_paths: Optional[list[str]]#
class spsdk.image.mbi.mbi_mixin.Mbi_MixinBca#

Bases: Mbi_Mixin

Master Boot Image Boot Configuration Area.

IMG_BCA_FW_VERSION_OFFSET: int#
IMG_BCA_IMAGE_LENGTH_OFFSET: int#
IMG_BCA_OFFSET: int#
IMG_DATA_START: int#
IMG_DIGEST_OFFSET: int#
IMG_FCF_OFFSET: int#
VALIDATION_SCHEMAS: list[str] = ['firmware_version_vx']#
firmware_version: Optional[int]#
mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_len()#

Length of the image.

Return type:

int

Returns:

length in bytes

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

update_bca(app_data, total_len)#

Update BCA table in application image.

Parameters:
  • app_data (bytes) – Application data that should be modified.

  • total_len (int) – Total length of bootable image

Return type:

bytes

Returns:

Updated whole application image

class spsdk.image.mbi.mbi_mixin.Mbi_MixinBcaTable#

Bases: Mbi_Mixin

BCA Table.

IMG_BCA_FW_VERSION_OFFSET = 996#
IMG_BCA_IMAGE_LENGTH_OFFSET = 992#
IMG_BCA_OFFSET = 960#
IMG_DATA_START = 3072#
IMG_DIGEST_OFFSET = 864#
IMG_DIGEST_SIZE = 32#
IMG_DUK_BLOCK_OFFSET = 2048#
IMG_DUK_BLOCK_SIZE = 106#
IMG_FCF_LIFECYCLE_OFFSET = 1036#
IMG_FCF_OFFSET = 1024#
IMG_FCF_SIZE = 16#
IMG_ISK_HASH_OFFSET = 1184#
IMG_ISK_HASH_SIZE = 16#
IMG_ISK_OFFSET = 1040#
IMG_SIGNATURE_OFFSET = 896#
IMG_SIGNED_HEADER_END = 1024#
IMG_WPC_MFG_CA_CERT_OFFSET = 1536#
IMG_WPC_MFG_CA_CERT_SIZE = 512#
IMG_WPC_PU_CERT_OFFSET = 2560#
IMG_WPC_PU_CERT_SIZE = 512#
IMG_WPC_ROOT_CA_CERT_HASH_OFFSET = 1504#
IMG_WPC_ROOT_CA_CERT_HASH_SIZE = 32#
class spsdk.image.mbi.mbi_mixin.Mbi_MixinCertBlockV1#

Bases: Mbi_Mixin

Master Boot Image certification block V1 class.

HMAC_SIZE: int#
NEEDED_MEMBERS: dict[str, Any] = {'cert_block': None, 'signature_provider': None}#
VALIDATION_SCHEMAS: list[str] = ['cert_block_v1', 'signature_provider']#
cert_block: Optional[CertBlockV1]#
get_key_store_presented: Callable[[bytes], int]#
ivt_table: Mbi_MixinIvt#
key_store: Optional[KeyStore]#
mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_len()#

Get length of Certificate Block V1.

Return type:

int

Returns:

Length of Certificate Block V1.

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

mix_validate()#

Validate the setting of image.

Raises:

SPSDKError – Configuration of Certificate block v1 is invalid.

Return type:

None

search_paths: Optional[list[str]]#
signature_provider: Optional[SignatureProvider]#
total_len: Any#
class spsdk.image.mbi.mbi_mixin.Mbi_MixinCertBlockV21#

Bases: Mbi_Mixin

Master Boot Image certification block V3.1 class.

NEEDED_MEMBERS: dict[str, Any] = {'cert_block': None, 'signature_provider': None}#
VALIDATION_SCHEMAS: list[str] = ['cert_block_v21', 'signature_provider']#
cert_block: Optional[CertBlockV21]#
ivt_table: Mbi_MixinIvt#
mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_len()#

Get length of Certificate Block V2.1.

Return type:

int

Returns:

Length of Certificate Block V2.1.

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

mix_validate()#

Validate the setting of image.

Raises:

SPSDKError – The configuration of Certificate v3.1 is invalid.

Return type:

None

search_paths: Optional[list[str]]#
signature_provider: Optional[SignatureProvider]#
class spsdk.image.mbi.mbi_mixin.Mbi_MixinCertBlockVx#

Bases: Mbi_Mixin

Master Boot Image certification block for MC55xx class.

IMG_ISK_OFFSET: int#
NEEDED_MEMBERS: dict[str, Any] = {'cert_block': None, 'signature_provider': None}#
VALIDATION_SCHEMAS: list[str] = ['cert_block_vX', 'signature_provider', 'just_header']#
add_hash: bool#
cert_block: CertBlockVx#
just_header: bool#
mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

mix_validate()#

Validate the setting of image.

Raises:

SPSDKError – The configuration of certificate block is invalid.

Return type:

None

search_paths: Optional[list[str]]#
signature_provider: Optional[SignatureProvider]#
class spsdk.image.mbi.mbi_mixin.Mbi_MixinCtrInitVector#

Bases: Mbi_Mixin

Master Boot Image initial vector for encryption counter.

HMAC_SIZE: int#
NEEDED_MEMBERS: dict[str, Any] = {'_ctr_init_vector': b'I2\x92\x9dav\xc3\xe7\x03\xc6\xcfv\x1a\xd1U\x99'}#
PRE_PARSED: list[str] = ['cert_block']#
VALIDATION_SCHEMAS: list[str] = ['ctr_init_vector']#
cert_block: Union[CertBlockV1, CertBlockV21, None]#
property ctr_init_vector: bytes | None#

Counter init vector.

ivt_table: Mbi_MixinIvt#
mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

mix_validate()#

Validate the setting of image.

raise SPSDKError: Invalid HW key enabled member type.

Return type:

None

search_paths: Optional[list[str]]#
class spsdk.image.mbi.mbi_mixin.Mbi_MixinFcf#

Bases: Mbi_Mixin

Master Boot Image Flash Configuration Field for DSC.

class DSASSLifeCycle(tag, label, description=None)#

Bases: SpsdkEnum

Hash algorithm enum.

NOT_SET = (255, 'NOT_SET')#
OEM_CLOSED_NO_RETURN = (107, 'OEM_CLOSED_NO_RETURN')#
OEM_CLOSED_ROP1 = (144, 'OEM_CLOSED_ROP1')#
OEM_CLOSED_ROP2 = (149, 'OEM_CLOSED_ROP2')#
OEM_CLOSED_ROP3 = (155, 'OEM_CLOSED_ROP3')#
OEM_OPEN = (254, 'OEM_OPEN')#
IMG_DATA_START: int#
IMG_FCF_LIFECYCLE_OFFSET: int#
IMG_FCF_OFFSET: int#
IMG_FCF_SIZE: int#
VALIDATION_SCHEMAS: list[str] = ['lifecycle']#
lifecycle: int#
mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

update_fcf(app_data)#

Update FCF with lifecycle.

Parameters:

app_data (bytes) – Application data that should be modified.

Return type:

bytes

Returns:

Updated FCF with lifecycle.

class spsdk.image.mbi.mbi_mixin.Mbi_MixinFwVersion#

Bases: Mbi_Mixin

Master Boot Image FirmWare Version class.

NEEDED_MEMBERS: dict[str, Any] = {'manifest': None}#
VALIDATION_SCHEMAS: list[str] = ['firmware_version']#
firmware_version: Optional[int]#
mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

class spsdk.image.mbi.mbi_mixin.Mbi_MixinHmac#

Bases: Mbi_Mixin

Master Boot Image HMAC class.

COUNT_IN_LEGACY_CERT_BLOCK_LEN: bool = False#
HMAC_OFFSET = 64#
HMAC_SIZE = 32#
NEEDED_MEMBERS: dict[str, Any] = {'_hmac_key': None}#
VALIDATION_SCHEMAS: list[str] = ['hmac']#
compute_hmac(data)#

Compute HMAC hash.

Parameters:

data (bytes) – Data to be hashed.

Return type:

bytes

Returns:

Result HMAC hash of input data.

dek: Optional[str]#
property hmac_key: bytes | None#

HMAC key in bytes.

mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_len()#

Get length of HMAC block.

Return type:

int

Returns:

Length of HMAC block.

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

mix_validate()#

Validate the setting of image.

raise SPSDKError: Invalid HW key enabled member type.

Return type:

None

search_paths: Optional[list[str]]#
class spsdk.image.mbi.mbi_mixin.Mbi_MixinHmacMandatory#

Bases: Mbi_MixinHmac

Master Boot Image HMAC class (Mandatory use).

VALIDATION_SCHEMAS: list[str] = ['hmac_mandatory']#
mix_validate()#

Validate the setting of image.

raise SPSDKError: Invalid HW key enabled member type.

Return type:

None

class spsdk.image.mbi.mbi_mixin.Mbi_MixinHwKey#

Bases: Mbi_Mixin

Master Boot Image HW key user modes enable class.

NEEDED_MEMBERS: dict[str, Any] = {'user_hw_key_enabled': False}#
VALIDATION_SCHEMAS: list[str] = ['hw_key']#
ivt_table: Mbi_MixinIvt#
mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

mix_validate()#

Validate the setting of image.

raise SPSDKError: Invalid HW key enabled member type.

Return type:

None

user_hw_key_enabled: Optional[bool]#
class spsdk.image.mbi.mbi_mixin.Mbi_MixinImageSubType#

Bases: Mbi_Mixin

Master Boot Image SubType class.

class Mbi_ImageSubTypeKw45xx(tag, label, description=None)#

Bases: SpsdkEnum

Supported MAIN and NBU subtypes for KW45xx and K32W1xx.

MAIN = (0, 'MAIN', 'Default (main) application image')#
NBU = (1, 'NBU', 'NBU (Narrowband Unit) image')#
class Mbi_ImageSubTypeMcxn9xx(tag, label, description=None)#

Bases: SpsdkEnum

Supported MAIN and NBU subtypes for MCXN9xx.

MAIN = (0, 'MAIN', 'Default (main) application image')#
RECOVERY = (1, 'RECOVERY', 'Recovery image')#
NEEDED_MEMBERS: dict[str, Any] = {'image_subtype': 0}#
VALIDATION_SCHEMAS: list[str] = ['image_subtype']#
image_subtype: Optional[int]#
ivt_table: Mbi_MixinIvt#
mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.mb_xip_384_384_recovery_crctest

Return type:

dict[str, Any]

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

set_image_subtype(image_subtype)#

Convert string value to int by enum table and store to class.

Return type:

None

class spsdk.image.mbi.mbi_mixin.Mbi_MixinImageVersion#

Bases: Mbi_Mixin

Master Boot Image Image Version class.

NEEDED_MEMBERS: dict[str, Any] = {'image_version': 0}#
VALIDATION_SCHEMAS: list[str] = ['image_version']#
image_version: Optional[int]#
image_version_to_image_type: bool = True#
ivt_table: Mbi_MixinIvt#
mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

class spsdk.image.mbi.mbi_mixin.Mbi_MixinIvt#

Bases: Mbi_Mixin

Master Boot Image Interrupt Vector table class.

IMAGE_TYPE: tuple[int, str]#
IVT_CRC_CERTIFICATE_OFFSET = 40#
IVT_IMAGE_FLAGS_IMAGE_TYPE_MASK = 63#
IVT_IMAGE_FLAGS_IMG_VER_MASK = 65535#
IVT_IMAGE_FLAGS_IMG_VER_SHIFT = 16#
IVT_IMAGE_FLAGS_OFFSET = 36#
IVT_IMAGE_FLAGS_SUB_TYPE_MASK = 3#
IVT_IMAGE_FLAGS_SUB_TYPE_SHIFT = 6#
IVT_IMAGE_FLAGS_TZ_TYPE_MASK = 3#
IVT_IMAGE_FLAGS_TZ_TYPE_SHIFT = 13#
IVT_IMAGE_LENGTH_OFFSET = 32#
IVT_LOAD_ADDR_OFFSET = 52#
app_table: Optional[MultipleImageTable]#
classmethod check_total_length(data)#

Check total length field from raw data.

Parameters:

data (bytes) – Raw MBI image data.

Raises:

SPSDKParsingError – Insufficient length of image has been detected.

Return type:

None

clean_ivt(app_data)#

Clean IVT table from added information.

Parameters:

app_data (bytes) – Application data that should be cleaned.

Return type:

bytes

Returns:

Cleaned application image

create_flags()#

Create flags of image.

Return type:

int

Returns:

Image type flags

classmethod get_app_table_presented(data)#

Get the Multiple Application table present flag from raw data.

Parameters:

data (bytes) – Raw MBI image data.

Return type:

int

Returns:

Multiple Application table is included or not.

classmethod get_cert_block_offset(data)#

Get the certificate block offset from raw data.

During getting of cert block offset, the length is also validated.

Parameters:

data (bytes) – Raw MBI image data.

Return type:

int

Returns:

Certificate block offset

classmethod get_flags(data)#

Get the Image flags from raw data.

During getting of flags, the length is also validated.

Parameters:

data (bytes) – Raw MBI image data.

Return type:

int

Returns:

Image Flags

classmethod get_flags_from_data(data)#

Get the Image flags from raw data.

Parameters:

data (bytes) – Raw MBI image data.

Return type:

int

Returns:

Image Flags

classmethod get_hw_key_enabled(data)#

Get the HW key enabled setting from raw data.

Parameters:

data (bytes) – Raw MBI image data.

Return type:

bool

Returns:

HW key enabled or not.

classmethod get_image_type(data)#

Get the Image type from raw data.

Parameters:

data (bytes) – Raw MBI image data.

Return type:

int

Returns:

Image type

classmethod get_image_version(data)#

Get the Image firmware version from raw data.

Parameters:

data (bytes) – Raw MBI image data.

Return type:

int

Returns:

Firmware version.

classmethod get_key_store_presented(data)#

Get the KeyStore present flag from raw data.

Parameters:

data (bytes) – Raw MBI image data.

Return type:

int

Returns:

KeyStore is included or not.

classmethod get_load_address(data)#

Get the load address from raw data.

During getting of flags, the length is also validated.

Parameters:

data (bytes) – Raw MBI image data.

Return type:

int

Returns:

Load address

classmethod get_sub_type(data)#

Get the Image sub type from raw data.

Parameters:

data (bytes) – Raw MBI image data.

Return type:

int

Returns:

Image sub type.

classmethod get_tz_type(data)#

Get the Image TrustZone type settings from raw data.

Parameters:

data (bytes) – Raw MBI image data.

Return type:

int

Returns:

TrustZone type.

image_subtype: Optional[int]#
image_version: Optional[int]#
image_version_to_image_type: bool#
property ivt_table: Self#

Get ivt table itself.

Returns:

Current mixin IVT object.

key_store: Optional[KeyStore]#
load_address: Optional[int]#
trust_zone: TrustZone#
update_crc_val_cert_offset(app_data, crc_val_cert_offset)#

Update value just of CRC/Certificate offset field.

Parameters:
  • app_data (bytes) – Input binary array.

  • crc_val_cert_offset (int) – CRC/Certificate offset value.

Return type:

bytes

Returns:

Updated binary array.

update_ivt(app_data, total_len, crc_val_cert_offset=0)#

Update IVT table in application image.

Parameters:
  • app_data (bytes) – Application data that should be modified.

  • total_len (int) – Total length of bootable image

  • crc_val_cert_offset (int) – CRC value or Certification block offset

Return type:

bytes

Returns:

Updated whole application image

user_hw_key_enabled: Optional[bool]#
class spsdk.image.mbi.mbi_mixin.Mbi_MixinIvtZeroTotalLength#

Bases: Mbi_MixinIvt

Master Boot Image Interrupt Vector table class for XIP image.

classmethod check_total_length(data)#

Check total length field from raw data.

Parameters:

data (bytes) – Raw MBI image data.

Raises:

SPSDKParsingError – Insufficient length of image has been detected.

Return type:

None

update_ivt(app_data, total_len, crc_val_cert_offset=0)#

Update IVT table in application image.

Parameters:
  • app_data (bytes) – Application data that should be modified.

  • total_len (int) – Total length of bootable image

  • crc_val_cert_offset (int) – CRC value or Certification block offset

Return type:

bytes

Returns:

Updated whole application image

class spsdk.image.mbi.mbi_mixin.Mbi_MixinKeyStore#

Bases: Mbi_Mixin

Master Boot Image KeyStore class.

COUNT_IN_LEGACY_CERT_BLOCK_LEN: bool = False#
HMAC_OFFSET: int#
HMAC_SIZE: int#
NEEDED_MEMBERS: dict[str, Any] = {'_hmac_key': None, 'key_store': None}#
VALIDATION_SCHEMAS: list[str] = ['key_store']#
hmac_key: Optional[bytes]#
ivt_table: Mbi_MixinIvt#
key_store: Optional[KeyStore]#
mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_len()#

Get length of KeyStore block.

Return type:

int

Returns:

Length of KeyStore block.

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

mix_validate()#

Validate the setting of image.

raise SPSDKError: Invalid HW key enabled member type.

Return type:

None

search_paths: Optional[list[str]]#
class spsdk.image.mbi.mbi_mixin.Mbi_MixinLoadAddress#

Bases: Mbi_Mixin

Master Boot Image load address class.

NEEDED_MEMBERS: dict[str, Any] = {'load_address': 0}#
VALIDATION_SCHEMAS: list[str] = ['load_addr']#
ivt_table: Mbi_MixinIvt#
load_address: Optional[int]#
mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

class spsdk.image.mbi.mbi_mixin.Mbi_MixinLoadAddressOptional#

Bases: Mbi_MixinLoadAddress

Master Boot Image optional load address class.

VALIDATION_SCHEMAS: list[str] = ['load_addr_optional']#
mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

class spsdk.image.mbi.mbi_mixin.Mbi_MixinManifest#

Bases: Mbi_MixinTrustZoneMandatory

Master Boot Image Manifest class.

NEEDED_MEMBERS: dict[str, Any] = {'cert_block': None, 'family': 'Unknown', 'manifest': None, 'revision': 'latest'}#
PRE_PARSED: list[str] = ['cert_block']#
VALIDATION_SCHEMAS: list[str] = ['trust_zone', 'firmware_version']#
cert_block: Union[CertBlockV1, CertBlockV21, None]#
family: str#
firmware_version: Optional[int]#
ivt_table: Mbi_MixinIvt#
manifest: Optional[MasterBootImageManifest]#
manifest_class#

alias of MasterBootImageManifest

mix_len()#

Get length of Manifest block.

Return type:

int

Returns:

Length of Manifest block.

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

mix_validate()#

Validate the setting of image.

Raises:

SPSDKError – The manifest configuration is invalid.

Return type:

None

revision: str#
class spsdk.image.mbi.mbi_mixin.Mbi_MixinManifestCrc#

Bases: Mbi_MixinManifest

Master Boot Image Manifest class with CRC.

manifest: Optional[MasterBootImageManifestCrc]#
manifest_class#

alias of MasterBootImageManifestCrc

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

class spsdk.image.mbi.mbi_mixin.Mbi_MixinManifestDigest#

Bases: Mbi_MixinManifest

Master Boot Image Manifest class for devices supporting ImageDigest functionality.

VALIDATION_SCHEMAS: list[str] = ['trust_zone', 'firmware_version', 'digest_hash_algo', 'add_digest_hash']#
manifest: Optional[MasterBootImageManifestDigest]#
manifest_class#

alias of MasterBootImageManifestDigest

mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_len()#

Get length of Manifest block.

Return type:

int

Returns:

Length of Manifest block.

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

class spsdk.image.mbi.mbi_mixin.Mbi_MixinRelocTable#

Bases: Mbi_Mixin

Master Boot Image Relocation table class.

NEEDED_MEMBERS: dict[str, Any] = {'_app': None, 'app_table': None}#
VALIDATION_SCHEMAS: list[str] = ['app_table']#
app: Optional[bytes]#
app_table: Optional[MultipleImageTable]#
disassembly_app_data(data)#

Disassembly Application data to application and optionally Multiple Application Table.

Return type:

bytes

Returns:

Application data without Multiple Application Table which will be stored in class.

mix_app_len()#

Compute application data length of individual mixin.

Return type:

int

Returns:

Application data length of atomic Mixin.

mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_len()#

Get length of additional binaries block.

Return type:

int

Returns:

Length of additional binaries block.

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_validate()#

Validate the setting of image.

Raises:

SPSDKError – Application table configuration is invalid.

Return type:

None

search_paths: Optional[list[str]]#
class spsdk.image.mbi.mbi_mixin.Mbi_MixinTrustZone#

Bases: Mbi_Mixin

Master Boot Image Trust Zone class.

NEEDED_MEMBERS: dict[str, Any] = {'family': 'Unknown', 'revision': 'latest', 'trust_zone': <TrustZone: type: TrustZoneType.ENABLED (TrustZone enabled with default settings)}#
PRE_PARSED: list[str] = ['cert_block']#
VALIDATION_SCHEMAS: list[str] = ['trust_zone']#
cert_block: Union[CertBlockV1, CertBlockV21, None]#
family: str#
ivt_table: Mbi_MixinIvt#
mix_get_config(output_folder)#

Get the configuration of the mixin.

Parameters:

output_folder (str) – Output folder to store files.

Return type:

dict[str, Any]

mix_len()#

Get length of TrustZone array.

Return type:

int

Returns:

Length of TrustZone.

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_parse(data)#

Parse the binary to individual fields.

Parameters:

data (bytes) – Final Image in bytes.

Return type:

None

revision: str#
search_paths: Optional[list[str]]#
trust_zone: TrustZone#
class spsdk.image.mbi.mbi_mixin.Mbi_MixinTrustZoneMandatory#

Bases: Mbi_MixinTrustZone

Master Boot Image Trust Zone class for devices where is Trustzone mandatory.

mix_load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (dict[str, Any]) – Dictionary with configuration fields.

Return type:

None

mix_validate()#

Validate the setting of image.

Raises:

SPSDKError – The TrustZone configuration is invalid.

Return type:

None

Image Exceptions#

Module provides exceptions for PFR module.

exception spsdk.image.exceptions.SPSDKSegmentNotPresent(desc=None)#

Bases: SPSDKError

The segment is missing in the image.

Initialize the base SPSDK Exception.

exception spsdk.image.exceptions.SPSDKUnsupportedImageType(desc=None)#

Bases: SPSDKError

The specified Image type is not supported.

Initialize the base SPSDK Exception.

AHAB Container#

Implementation of raw AHAB container support.

This module represents a generic AHAB container implementation. You can set the containers values at will. From this perspective, consult with your reference manual of your device for allowed values.

class spsdk.image.ahab.ahab_container.AHABContainerBase(chip_config, flags=0, fuse_version=0, sw_version=0, signature_block=None)#

Bases: HeaderContainer

Class representing AHAB container base class (common for Signed messages and AHAB Image).

Container header:

+---------------+----------------+----------------+----------------+
|    Byte 3     |     Byte 2     |      Byte 1    |     Byte 0     |
+---------------+----------------+----------------+----------------+
|      Tag      |              Length             |    Version     |
+---------------+---------------------------------+----------------+
|                              Flags                               |
+---------------+----------------+---------------------------------+
|  # of images  |  Fuse version  |             SW version          |
+---------------+----------------+---------------------------------+
|              Reserved          |       Signature Block Offset    |
+--------------------------------+---------------------------------+
|             Payload (Signed Message or Image Array)              |
+------------------------------------------------------------------+
|                      Signature block                             |
+------------------------------------------------------------------+

Class object initializer.

Parameters:
  • flags (int) – flags.

  • fuse_version (int) – value must be equal to or greater than the version stored in the fuses to allow loading this container.

  • sw_version (int) – used by PHBC (Privileged Host Boot Companion) to select between multiple images with same fuse version field.

  • signature_block (Union[SignatureBlock, SignatureBlockV2, None]) – signature block.

SIGNATURE_BLOCK#

alias of SignatureBlock

TAG: Union[int, list[int]] = 0#
VERSION: Union[int, list[int]] = 0#
NAME = 'Container'#
CONTAINER_SIZE = 1024#
FLAGS_SRK_SET_OFFSET = 0#
FLAGS_SRK_SET_SIZE = 2#
FLAGS_USED_SRK_ID_OFFSET = 4#
FLAGS_USED_SRK_ID_SIZE = 2#
FLAGS_SRK_REVOKE_MASK_OFFSET = 8#
FLAGS_SRK_REVOKE_MASK_SIZE = 4#
set_flags(srk_set='none', used_srk_id=0, srk_revoke_mask=0)#

Set the flags value.

Parameters:
  • srk_set (str) – Super Root Key (SRK) set, defaults to “none”

  • used_srk_id (int) – Which key from SRK set is being used, defaults to 0

  • srk_revoke_mask (int) – SRK revoke mask, defaults to 0

Return type:

None

property flag_srk_set: FlagsSrkSet#

SRK set flag in string representation.

Returns:

Name of SRK Set flag.

property flag_used_srk_id: int#

Used SRK ID flag.

Returns:

Index of Used SRK ID.

property flag_srk_revoke_keys: int#

SRK Revoke mask flag.

Returns:

SRK revoke mask.

property flag_srk_revoke_mask: str#

SRK Revoke mask flag.

Returns:

SRK revoke mask in HEX.

property srk_count: int#

Get count of used signatures in container.

get_srk_hash(srk_id=0)#

Get SRK hash.

Parameters:

srk_id (int) – ID of SRK table in case of using multiple Signatures, default is 0.

Return type:

bytes

Returns:

SHA256 hash of SRK table.

property image_array_len: int#

Get image array length if available.

Returns:

Length of image array.

header_length()#

Length of AHAB Container header.

Return type:

int

Returns:

Length in bytes of AHAB Container header.

classmethod format()#

Format of binary representation.

Return type:

str

update_fields()#

Updates all volatile information in whole container structure.

Raises:

SPSDKError – When inconsistent image array length is detected.

Return type:

None

get_signature_data()#

Returns binary data to be signed.

The container must be properly initialized, so the data are valid for signing, i.e. the offsets, lengths etc. must be set prior invoking this method, otherwise improper data will be signed.

The whole container gets serialized first. Afterwards the binary data is sliced so only data for signing get’s returned. The signature data length is evaluated based on offsets, namely the signature block offset, the container signature offset and the container signature fixed data length.

Signature data structure:

+---------------------------------------------------+----------------+
|                  Container header                 |                |
+---+---+-----------+---------+--------+------------+     Data       |
| S |   |    tag    | length  | length | version    |                |
| i |   +-----------+---------+--------+------------+                |
| g |   |                  flags                    |      to        |
| n |   +---------------------+---------------------+                |
| a |   |  srk table offset   | certificate offset  |                |
| t |   +---------------------+---------------------+     Sign       |
| u |   |     blob offset     | signature offset    |                |
| r |   +---------------------+---------------------+                |
| e |   |       SRK Table / SRK Table Array         |                |
|   +---+-----------+---------+--------+------------+----------------+
| B | S |   tag     | length  | length | version    | Signature data |
| l | i +-----------+---------+--------+------------+ fixed length   |
| o | g |               Reserved                    |                |
| c | n +-------------------------------------------+----------------+
| k | a |               Signature data              |
|   | t |                                           |
|   | u |                                           |
|   | r |                                           |
|   | e |                                           |
+---+---+-------------------------------------------+
Return type:

bytes

Returns:

bytes representing data to be signed.

sign_itself()#

Sign itself if needed.

Return type:

None

classmethod pre_parse_verify(data)#

Pre-Parse verify of AHAB container.

Parameters:

data (bytes) – Binary data with Container block to pre-parse.

Return type:

Verifier

Returns:

Verifier of pre-parsed binary data.

load_from_config_generic(config)#

Converts the configuration option into an AHAB image object.

“config” content of container configurations.

Parameters:

config (dict[str, Any]) – array of AHAB containers configuration dictionaries.

Return type:

None

class spsdk.image.ahab.ahab_container.AHABContainer(chip_config, flags=0, fuse_version=0, sw_version=0, image_array=None, signature_block=None, container_offset=0)#

Bases: AHABContainerBase

Class representing AHAB container.

Container header:

+---------------+----------------+----------------+----------------+
|    Byte 3     |     Byte 2     |      Byte 1    |     Byte 0     |
+---------------+----------------+----------------+----------------+
|      Tag      |              Length             |    Version     |
+---------------+---------------------------------+----------------+
|                              Flags                               |
+---------------+----------------+---------------------------------+
|  # of images  |  Fuse version  |             SW version          |
+---------------+----------------+---------------------------------+
|              Reserved          |       Signature Block Offset    |
+----+---------------------------+---------------------------------+
| I  |image0: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV  |
+ m  |-------------------------------------------------------------+
| g  |image1: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV  |
+ .  |-------------------------------------------------------------+
| A  |...                                                          |
| r  |...                                                          |
| r  |                                                             |
+ a  |-------------------------------------------------------------+
| y  |imageN: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV  |
+----+-------------------------------------------------------------+
|                      Signature block                             |
+------------------------------------------------------------------+
|                                                                  |
|                                                                  |
|                                                                  |
+------------------------------------------------------------------+
|                      Data block_0                                |
+------------------------------------------------------------------+
|                                                                  |
|                                                                  |
+------------------------------------------------------------------+
|                      Data block_n                                |
+------------------------------------------------------------------+

Class object initializer.

Chip_config:

Chip configuration for AHAB.

Parameters:
  • flags (int) – flags.

  • fuse_version (int) – value must be equal to or greater than the version stored in the fuses to allow loading this container.

  • sw_version (int) – used by PHBC (Privileged Host Boot Companion) to select between multiple images with same fuse version field.

  • image_array (Union[list[ImageArrayEntry], list[ImageArrayEntryV2], None]) – array of image entries, must be number of images long.

  • signature_block (Union[SignatureBlock, SignatureBlockV2, None]) – signature block.

TAG: Union[int, list[int]] = 135#
IAE_TYPE#

alias of ImageArrayEntry

SIGNATURE_BLOCK#

alias of SignatureBlock

START_IMAGE_ADDRESS = 8192#
START_IMAGE_ADDRESS_NAND = 7168#
FLAGS_GDET_ENABLE_OFFSET = 20#
FLAGS_GDET_ENABLE_SIZE = 2#
class FlagsGdetBehavior(tag, label, description=None)#

Bases: SpsdkEnum

Flags Glitch Detector runtime behavior flags.

Disabled = (0, 'disabled', 'Glitch Detector is disabled after the first OEM container has been authenticated (default behavior)')#
EnabledEleApi = (1, 'enabled_eleapi', 'Automatically enable Glitch Detector during all ELE API calls')#
Enabled = (2, 'enabled', 'Leave Glitch Detector enabled')#
property image_array_len: int#

Get image array length if available.

Returns:

Length of image array.

property srk_hash: bytes#

SRK hash if available.

Returns:

SHA256 hash of SRK table.

header_length()#

Length of AHAB Container header.

Return type:

int

Returns:

Length in bytes of AHAB Container header.

update_fields()#

Updates all volatile information in whole container structure.

Raises:

SPSDKError – When inconsistent image array length is detected.

Return type:

None

decrypt_data()#

Decrypt all images if possible.

Return type:

None

export()#

Export container header into bytes.

Return type:

bytes

Returns:

bytes representing container header content including the signature block.

verify()#

Verify container data.

Return type:

Verifier

classmethod parse(data, chip_config, container_id)#

Parse input binary chunk to the container object.

Parameters:
  • data (bytes) – Binary data with Container block to parse.

  • chip_config (AhabChipConfig) – Ahab image chip configuration.

  • container_id (int) – AHAB container ID.

Return type:

Self

Returns:

Object recreated from the binary data.

property flag_gdet_runtime_behavior: FlagsGdetBehavior#

Glitch detector flag as enumeration.

create_config(index, data_path)#

Create configuration of the AHAB Image.

Parameters:
  • index (int) – Container index.

  • data_path (str) – Path to store the data files of configuration.

Return type:

dict[str, Any]

Returns:

Configuration dictionary.

classmethod load_from_config(chip_config, config, container_ix)#

Converts the configuration option into an AHAB image object.

“config” content of container configurations.

Parameters:
  • chip_config (AhabChipConfig) – Ahab chip configuration.

  • config (dict[str, Any]) – array of AHAB containers configuration dictionaries.

  • container_ix (int) – Container index that is loaded.

Return type:

Self

Returns:

AHAB Container object.

image_info()#

Get Image info object.

Return type:

BinaryImage

Returns:

AHAB Container Info object.

create_srk_hash_fuses_script()#

Create fuses script of SRK hash.

Return type:

str

Returns:

Text description of SRK hash.

classmethod get_container_offset(ix)#

Get container offset by index.

Parameters:

ix (int) – Container index

Return type:

int

Returns:

Container offset

property start_of_images: int#

Get real start of container images.

class spsdk.image.ahab.ahab_container.AHABContainerV2(chip_config, flags=0, fuse_version=0, sw_version=0, image_array=None, signature_block=None, container_offset=0)#

Bases: AHABContainer

Class representing AHAB container.

Container header:

+---------------+----------------+----------------+----------------+
|    Byte 3     |     Byte 2     |      Byte 1    |     Byte 0     |
+---------------+----------------+----------------+----------------+
|      Tag      |              Length             |    Version     |
+---------------+---------------------------------+----------------+
|                              Flags                               |
+---------------+----------------+---------------------------------+
|  # of images  |  Fuse version  |             SW version          |
+---------------+----------------+---------------------------------+
|              Reserved          |       Signature Block Offset    |
+----+---------------------------+---------------------------------+
| I  |image0: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV  |
+ m  |-------------------------------------------------------------+
| g  |image1: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV  |
+ .  |-------------------------------------------------------------+
| A  |...                                                          |
| r  |...                                                          |
| r  |                                                             |
+ a  |-------------------------------------------------------------+
| y  |imageN: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV  |
+----+-------------------------------------------------------------+
|                      Signature block                             |
+------------------------------------------------------------------+
|                                                                  |
|                                                                  |
|                                                                  |
+------------------------------------------------------------------+
|                      Data block_0                                |
+------------------------------------------------------------------+
|                                                                  |
|                                                                  |
+------------------------------------------------------------------+
|                      Data block_n                                |
+------------------------------------------------------------------+

Class object initializer.

Chip_config:

Chip configuration for AHAB.

Parameters:
  • flags (int) – flags.

  • fuse_version (int) – value must be equal to or greater than the version stored in the fuses to allow loading this container.

  • sw_version (int) – used by PHBC (Privileged Host Boot Companion) to select between multiple images with same fuse version field.

  • image_array (Union[list[ImageArrayEntry], list[ImageArrayEntryV2], None]) – array of image entries, must be number of images long.

  • signature_block (Union[SignatureBlock, SignatureBlockV2, None]) – signature block.

IAE_TYPE#

alias of ImageArrayEntryV2

SIGNATURE_BLOCK#

alias of SignatureBlockV2

CONTAINER_SIZE = 16384#
VERSION: Union[int, list[int]] = 2#
START_IMAGE_ADDRESS = 49152#
START_IMAGE_ADDRESS_NAND = 48128#
FLAGS_CHECK_ALL_SIGNATURES_OFFSET = 15#
FLAGS_CHECK_ALL_SIGNATURES_SIZE = 1#
class FlagsCheckAllSignatures(tag, label, description=None)#

Bases: SpsdkEnum

Flags Check all signatures.

Default = (0, 'default', 'Apply default fuse policy')#
CheckAllSignatures = (1, 'check_all_signatures', 'Force verification of all present signatures')#
property flag_check_all_signatures: FlagsCheckAllSignatures#

Check all signatures flag as enumeration.

create_srk_hash_fuses_script()#

Create fuses script of SRK hash.

Return type:

str

Returns:

Text description of SRK hash.

property srk_hash0: bytes#

SRK hash if available.

Returns:

SHA256 hash of SRK table.

property srk_hash1: bytes#

SRK hash if available.

Returns:

SHA256 hash of SRK table.

AHAB Utilities#

AHAB utils module.

spsdk.image.ahab.utils.ahab_update_keyblob(family, binary, keyblob, container_id, mem_type)#

Update keyblob in AHAB image.

Parameters:
  • family (str) – MCU family

  • binary (str) – Path to AHAB image binary

  • keyblob (str) – Path to keyblob

  • container_id (int) – Index of the container to be updated

  • mem_type (Optional[str]) – Memory type used for bootable image

Raises:
  • SPSDKError – In case the container id not present

  • SPSDKError – In case the AHAB image does not contain blob

  • SPSDKError – In case the length of keyblobs don’t match

Return type:

None

spsdk.image.ahab.utils.ahab_re_sign(family, binary, container_id, sign_provider_0, sign_provider_1=None, mem_type=None)#

Re-sign the AHAB container in AHAB image.

Parameters:
  • family (str) – MCU family

  • binary (str) – Path to AHAB image binary

  • container_id (int) – Index of the container to be updated

  • sign_provider_0 (SignatureProvider) – Signature provider object for main signature

  • sign_provider_1 (Optional[SignatureProvider]) – Signature provider object for additional signature

  • mem_type (Optional[str]) – Memory type used for bootable image

Raises:

SPSDKError – In case the container id not present

Return type:

None

spsdk.image.ahab.utils.ahab_sign_image(image_path, config_path, mem_type)#

Sign AHAB container set.

Parse segments in Bootable image and sign non NXP AHAB containers.

Return type:

bytes

spsdk.image.ahab.utils.write_ahab_fuses(ahab, ahab_output_dir, ahab_output_file_no_ext, print_func)#

Write AHAB fuses.

Return type:

None

AHAB Container Interface#

AHAB abstract classes.

class spsdk.image.ahab.ahab_abstract_interfaces.Container#

Bases: BaseClass

Base class for any container.

classmethod fixed_length()#

Returns the length of a container which is fixed.

i.e. part of a container holds fixed values, whereas some entries have variable length.

Return type:

int

export()#

Serialize object into bytes array.

Return type:

bytes

classmethod parse(data)#

Deserialize object from bytes array.

Return type:

Self

classmethod format()#

Returns the container data format as defined by struct package.

The base returns only endianness (LITTLE_ENDIAN).

Return type:

str

class spsdk.image.ahab.ahab_abstract_interfaces.HeaderContainerData(tag, length, version)#

Bases: object

Holder for Container header data.

tag: int#
length: int#
version: int#
classmethod parse(binary, inverted=False)#

Parse binary header.

Return type:

Self

class spsdk.image.ahab.ahab_abstract_interfaces.HeaderContainer(tag, length, version)#

Bases: Container

A container with first byte defined as header - tag, length and version.

Every “container” in AHAB consists of a header - tag, length and version.

The only exception is the ‘image array’ or ‘image array entry’ respectively which has no header at all and SRK record, which has ‘signing algorithm’ instead of version. But this can be considered as a sort of SRK record ‘version’.

Class object initialized.

Parameters:
  • tag (int) – container tag.

  • length (int) – container length.

  • version (int) – container version.

TAG: Union[int, list[int]] = 0#
VERSION: Union[int, list[int]] = 0#
classmethod format()#

Format of binary representation.

Return type:

str

verify_header()#

Verifies the header of container properties…

i.e. tag e <0; 255>, otherwise an exception is raised. :raises SPSDKValueError: Any MAndatory field has invalid value.

Return type:

Verifier

verify_parsed_header()#

Verifies the parsed header of container properties…

i.e. tag e <0; 255>, otherwise an exception is raised. :raises SPSDKValueError: Any MAndatory field has invalid value.

Return type:

Verifier

classmethod parse_head(binary)#

Parse binary data to get head members.

Parameters:

binary (bytes) – Binary data.

Raises:

SPSDKLengthError – Binary data length is not enough.

Return type:

tuple[int, int, int]

Returns:

Tuple with TAG, LENGTH, VERSION

classmethod check_container_head(binary)#

Compares the data length and container length.

This is just a helper function used throughout the code.

Parameters:

binary (bytes) – Binary input data

Return type:

Verifier

Returns:

Verifier object of parsed header

class spsdk.image.ahab.ahab_abstract_interfaces.HeaderContainerInverted(tag, length, version)#

Bases: HeaderContainer

A container with first byte defined as header - tag, length and version.

It same as “HeaderContainer” only the tag/length/version are in reverse order in binary form.

Class object initialized.

Parameters:
  • tag (int) – container tag.

  • length (int) – container length.

  • version (int) – container version.

classmethod parse_head(binary)#

Parse binary data to get head members.

Parameters:

binary (bytes) – Binary data.

Raises:

SPSDKLengthError – Binary data length is not enough.

Return type:

tuple[int, int, int]

Returns:

Tuple with TAG, LENGTH, VERSION

Signed Messages#

Implementation of raw AHAB container support.

This module represents a generic AHAB container implementation. You can set the containers values at will. From this perspective, consult with your reference manual of your device for allowed values.

class spsdk.image.ahab.signed_msg.Message(cert_ver=0, permissions=0, issue_date=None, cmd=0, unique_id=None, unique_id_len=8)#

Bases: Container

Class representing the Signed message.

Message::

Off

Byte 3

Byte 2

Byte 1

Byte 0

0x00

Message header

0x10

Message payload

Message header::

Off

Byte 3

Byte 2

Byte 1

Byte 0

0x00

Cert version

Permission

Issue date

0x04

Reserved

Command

Reserved

0x08

0x..

Unique ID (64 or 128 bits)

The message header is common for all signed messages.

Message used to sign and send to device with EdgeLock.

Parameters:
  • cert_ver (int) – Certificate version, defaults to 0

  • permissions (int) – Certificate permission, to be used in future The stated permission must allow the operation requested by the signed message , defaults to 0

  • issue_date (Optional[int]) – Issue date, defaults to None (Current date will be applied)

  • cmd (int) – Message command ID, defaults to 0

  • unique_id (Optional[bytes]) – UUID of device, defaults to None

  • unique_id_len (int) – UUID length - 64 or 128 bits, defaults to 64 bits (8 bytes)

PAYLOAD_LENGTH = 0#
TAG = 0#
UNIQUE_ID_LEN = 8#
static convert_uuid(uuid)#

Convert UUID to binary form of message.

Parameters:

uuid (bytes) – Input format of UUID.

Return type:

bytes

Returns:

Converted UUID.

abstract create_config()#

Create configuration of the Signed Message.

Return type:

dict[str, Any]

Returns:

Configuration dictionary.

export()#

Exports message into to bytes array.

Return type:

bytes

Returns:

Bytes representation of message object.

abstract export_payload()#

Exports message payload to bytes array.

Return type:

bytes

Returns:

Bytes representation of message payload.

classmethod format()#

Format of binary representation.

Return type:

str

classmethod get_message_class(cmd)#

Get the dedicated message class for command.

Return type:

Type[Self]

classmethod load_from_config(config, search_paths=None)#

Converts the configuration option into an message object.

“config” content of container configurations.

Parameters:
  • config (dict[str, Any]) – Message configuration dictionaries.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

Self

Returns:

Message object.

classmethod load_from_config_generic(config)#

Converts the general configuration option into an message object.

“config” content of container configurations.

Parameters:

config (dict[str, Any]) – Message configuration dictionaries.

Return type:

tuple[int, int, Optional[int], bytes]

Returns:

Message object.

classmethod parse(data)#

Parse input binary to the signed message object.

Parameters:

data (bytes) – Binary data with Container block to parse.

Return type:

Self

Returns:

Object recreated from the binary data.

abstract parse_payload(data)#

Parse payload.

Parameters:

data (bytes) – Binary data with Payload to parse.

Return type:

None

property payload_len: int#

Message payload length in bytes.

verify()#

Verify general message properties.

Return type:

Verifier

class spsdk.image.ahab.signed_msg.MessageCommands(tag, label, description=None)#

Bases: SpsdkEnum

Signed messages commands.

DAT_AUTHENTICATION_REQ = (200, 'DAT_AUTHENTICATION_REQ', 'Debug authentication request, internally used for DAT procedure.')#
KEYSTORE_REPROVISIONING_ENABLE_REQ = (63, 'KEYSTORE_REPROVISIONING_ENABLE_REQ', 'Key store reprovisioning enable')#
KEY_EXCHANGE_REQ = (71, 'KEY_EXCHANGE_REQ', 'Key exchange signed message content')#
RETURN_LIFECYCLE_UPDATE_REQ = (160, 'RETURN_LIFECYCLE_UPDATE_REQ', 'Return lifecycle update request.')#
WRITE_SEC_FUSE_REQ = (145, 'WRITE_SEC_FUSE_REQ', 'Write secure fuse request.')#
class spsdk.image.ahab.signed_msg.MessageDat(cert_ver=0, permissions=0, issue_date=None, unique_id=None, unique_id_len=8, challenge_vector=b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', authentication_beacon=0)#

Bases: Message

Debug authentication request message class representation.

Message used to sign and send to device with EdgeLock.

Parameters:
  • cert_ver (int) – Certificate version, defaults to 0

  • permissions (int) – Certificate permission, to be used in future The stated permission must allow the operation requested by the signed message , defaults to 0

  • issue_date (Optional[int]) – Issue date, defaults to None (Current date will be applied)

  • unique_id (Optional[bytes]) – UUID of device, defaults to None

  • unique_id_len (int) – UUID length - 64 or 128 bits, defaults to 64 bits (8 bytes)

  • challenge_vector (bytes) – 32 bytes of challenge request got’s from device by DAC.

  • authentication_beacon (int) – Authentication beacon in range 0-65535. At the moment is the reserved field and must be 0.

CHALLENGE_VECTOR_LEN = 32#
PAYLOAD_LENGTH = 34#
TAG = 200#
create_config()#

Create configuration of the Signed Message.

Return type:

dict[str, Any]

Returns:

Configuration dictionary.

export_payload()#

Exports message payload to bytes array.

Return type:

bytes

Returns:

Bytes representation of message payload.

classmethod load_from_config(config, search_paths=None)#

Converts the configuration option into an message object.

“config” content of container configurations.

Parameters:
  • config (dict[str, Any]) – Message configuration dictionaries.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Raises:

SPSDKError – Invalid configuration detected.

Return type:

Self

Returns:

Message object.

parse_payload(data)#

Parse payload.

Parameters:

data (bytes) – Binary data with Payload to parse.

Return type:

None

verify()#

Verify message properties.

Return type:

Verifier

class spsdk.image.ahab.signed_msg.MessageKeyExchange(cert_ver=0, permissions=0, issue_date=None, unique_id=None, unique_id_len=8, key_store_id=0, key_exchange_algorithm=MessageKeyExchange.KeyExchangeAlgorithm(tag=151126281, label='HKDF SHA256', description=None), salt_flags=0, derived_key_grp=0, derived_key_size_bits=0, derived_key_type=MessageKeyExchange.DerivedKeyType(tag=9216, label='AES SHA256', description='Possible bit widths: 128/192/256'), derived_key_lifetime=MessageKeyExchange.LifeTime(tag=1, label='PERSISTENT', description='Standard persistent key'), derived_key_usage=None, derived_key_permitted_algorithm=MessageKeyExchange.KeyDerivationAlgorithm(tag=134217993, label='HKDF SHA256', description='HKDF SHA256 (HMAC two-step)'), derived_key_lifecycle=MessageKeyExchange.LifeCycle(tag=1, label='OPEN', description=None), derived_key_id=0, private_key_id=0, input_peer_public_key_digest=b'', input_user_fixed_info_digest=b'')#

Bases: Message

Key exchange request message class representation.

Key exchange signed message class init.

Parameters:
  • cert_ver (int) – Certificate version, defaults to 0

  • permissions (int) – Certificate permission, to be used in future The stated permission must allow the operation requested by the signed message , defaults to 0

  • issue_date (Optional[int]) – Issue date, defaults to None (Current date will be applied)

  • unique_id (Optional[bytes]) – UUID of device, defaults to None

  • unique_id_len (int) – UUID length - 64 or 128 bits, defaults to 64 bits (8 bytes)

  • key_store_id (int) – Key store ID where to store the derived key. It must be the key store ID related to the key management handle set in the command API, defaults to 0

  • key_exchange_algorithm (KeyExchangeAlgorithm) –

    Algorithm used by the key exchange process:

    HKDF SHA256 0x09020109
    HKDF SHA384 0x0902010A
    , defaults to HKDF_SHA256

  • salt_flags (int) –

    Bit field indicating the requested operations:

    Bit 0: Salt in step #1 (HKDF-extract) of HMAC based two-step key derivation process:
    - 0: Use zeros salt;
    - 1:Use peer public key hash as salt;
    Bit 1: In case of ELE import, salt used to derive OEM_IMPORT_WRAP_SK and OEM_IMPORT_CMAC_SK:
    - 0: Zeros string;
    - 1: Device SRKH.
    Bit 2 to 15: Reserved, defaults to 0

  • derived_key_grp (int) – Derived key group. 100 groups are available per key store. It must be a value in the range [0; 99]. Keys belonging to the same group can be managed through the Manage key group command, defaults to 0

  • derived_key_size_bits (int) – Derived key size bits attribute, defaults to 0

  • derived_key_type (DerivedKeyType) –

    Key type

    Value

    Key size in bits

    AES

    0x2400

    128/192/256

    HMAC

    0x1100

    224/256/384/512

    OEM_IMPORT_MK_SK*

    0x9200

    128/192/256

    , defaults to AES

  • derived_key_lifetime (LifeTime) –

    Derived key lifetime attribute

    VOLATILE 0x00 Standard volatile key.
    PERSISTENT 0x01 Standard persistent key.
    PERMANENT 0xFF Standard permanent key., defaults to PERSISTENT

  • derived_key_usage (Optional[list[DerivedKeyUsage]]) –

    Derived key usage attribute.

    Cache 0x00000004 Permission to cache the key in the ELE internal secure memory.
    This usage is set by default by ELE FW for all keys generated or imported.
    Encrypt 0x00000100 Permission to encrypt a message with the key. It could be cipher
    encryption, AEAD encryption or asymmetric encryption operation.
    Decrypt 0x00000200 Permission to decrypt a message with the key. It could be
    cipher decryption, AEAD decryption or asymmetric decryption operation.
    Sign message 0x00000400 Permission to sign a message with the key. It could be
    a MAC generation or an asymmetric message signature operation.
    Verify message 0x00000800 Permission to verify a message signature with the key.
    It could be a MAC verification or an asymmetric message signature
    verification operation.
    Sign hash 0x00001000 Permission to sign a hashed message with the key
    with an asymmetric signature operation. Setting this permission automatically
    sets the Sign Message usage.
    Verify hash 0x00002000 Permission to verify a hashed message signature with
    the key with an asymmetric signature verification operation.
    Setting this permission automatically sets the Verify Message usage.
    Derive 0x00004000 Permission to derive other keys from this key.
    , defaults to 0

  • derived_key_permitted_algorithm (KeyDerivationAlgorithm) –

    Derived key permitted algorithm attribute

    HKDF SHA256 (HMAC two-step) 0x08000109
    HKDF SHA384 (HMAC two-step) 0x0800010A, defaults to HKDF_SHA256

  • derived_key_lifecycle (LifeCycle) –

    Derived key lifecycle attribute

    CURRENT 0x00 Key is usable in current lifecycle.
    OPEN 0x01 Key is usable in open lifecycle.
    CLOSED 0x02 Key is usable in closed lifecycle.
    CLOSED and LOCKED 0x04 Key is usable in closed and locked lifecycle.
    , defaults to OPEN

  • derived_key_id (int) –

    Derived key ID attribute. It could be:

    • Wanted key identifier of the generated key: only supported by persistent

      and permanent keys;

    • 0x00000000 to let the FW chose the key identifier: supported by all

      keys (all persistence levels). , defaults to 0

  • private_key_id (int) – Identifier in the ELE key storage of the private key to use with the peer public key during the key agreement process, defaults to 0

  • input_peer_public_key_digest (bytes) – Input peer public key digest buffer. The algorithm used to generate the digest must be SHA256, defaults to list(8)

  • input_user_fixed_info_digest (bytes) – Input user fixed info digest buffer. The algorithm used to generate the digest must be SHA256, defaults to list(8)

class DerivedKeyType(tag, label, description=None)#

Bases: SpsdkEnum

Derived Key Type valid values.

AES = (9216, 'AES SHA256', 'Possible bit widths: 128/192/256')#
HMAC = (4352, 'HMAC SHA384', 'Possible bit widths: 224/256/384/512')#
OEM_IMPORT_MK_SK = (37376, 'OEM_IMPORT_MK_SK', 'Possible bit widths: 128/192/256')#
class DerivedKeyUsage(tag, label, description=None)#

Bases: SpsdkEnum

Derived Key Usage valid values.

CACHE = (4, 'Cache', 'Permission to cache the key in the ELE internal secure memory. This usage is set by default by ELE FW for all keys generated or imported.')#
DECRYPT = (512, 'Decrypt', 'Permission to decrypt a message with the key. It could be cipher decryption, AEAD decryption or asymmetric decryption operation.')#
DERIVE = (16384, 'Derive', 'Permission to derive other keys from this key.')#
ENCRYPT = (256, 'Encrypt', 'Permission to encrypt a message with the key. It could be cipher encryption, AEAD encryption or asymmetric encryption operation.')#
SIGN_HASH = (4096, 'Sign hash', 'Permission to sign a hashed message with the key with an asymmetric signature operation. Setting this permission automatically sets the Sign Message usage.')#
SIGN_MSG = (1024, 'Sign message', 'Permission to sign a message with the key. It could be a MAC generation or an asymmetric message signature operation.')#
VERIFY_HASH = (8192, 'Sign message', 'Permission to verify a hashed message signature with the key with an asymmetric signature verification operation. Setting this permission automatically sets the Verify Message usage.')#
VERIFY_MSG = (2048, 'Verify message', 'Permission to verify a message signature with the key. It could be a MAC verification or an asymmetric message signature verification operation.')#
class KeyDerivationAlgorithm(tag, label, description=None)#

Bases: SpsdkEnum

Key Derivation Algorithm valid values.

HKDF_SHA256 = (134217993, 'HKDF SHA256', 'HKDF SHA256 (HMAC two-step)')#
HKDF_SHA384 = (134217994, 'HKDF SHA384', 'HKDF SHA384 (HMAC two-step)')#
class KeyExchangeAlgorithm(tag, label, description=None)#

Bases: SpsdkEnum

Key Exchange Algorithm valid values.

HKDF_SHA256 = (151126281, 'HKDF SHA256')#
HKDF_SHA384 = (151126282, 'HKDF SHA384')#
class LifeCycle(tag, label, description=None)#

Bases: SpsdkEnum

Chip life cycle valid values.

CLOSED = (2, 'CLOSED')#
CURRENT = (0, 'CURRENT', 'Current device lifecycle')#
LOCKED = (4, 'LOCKED')#
OPEN = (1, 'OPEN')#
class LifeTime(tag, label, description=None)#

Bases: SpsdkEnum

Edgelock Enclave life time valid values.

PERMANENT = (255, 'PERMANENT', 'Standard permanent key')#
PERSISTENT = (1, 'PERSISTENT', 'Standard persistent key')#
VOLATILE = (0, 'VOLATILE', 'Standard volatile key')#
PAYLOAD_FORMAT = '<BBHLLHHHHLLLLLL32s32s'#
PAYLOAD_LENGTH = 108#
PAYLOAD_VERSION = 7#
TAG = 71#
create_config()#

Create configuration of the Signed Message.

Return type:

dict[str, Any]

Returns:

Configuration dictionary.

export_payload()#

Exports message payload to bytes array.

Return type:

bytes

Returns:

Bytes representation of message payload.

classmethod load_from_config(config, search_paths=None)#

Converts the configuration option into an message object.

“config” content of container configurations.

Parameters:
  • config (dict[str, Any]) – Message configuration dictionaries.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Raises:

SPSDKError – Invalid configuration detected.

Return type:

Self

Returns:

Message object.

parse_payload(data)#

Parse payload.

Parameters:

data (bytes) – Binary data with Payload to parse.

Return type:

None

verify()#

Verify message properties.

Return type:

Verifier

class spsdk.image.ahab.signed_msg.MessageKeyStoreReprovisioningEnable(cert_ver=0, permissions=0, issue_date=None, unique_id=None, unique_id_len=8, monotonic_counter=0, user_sab_id=0)#

Bases: Message

Key store reprovisioning enable request message class representation.

Key store reprovisioning enable signed message class init.

Parameters:
  • cert_ver (int) – Certificate version, defaults to 0

  • permissions (int) – Certificate permission, to be used in future The stated permission must allow the operation requested by the signed message , defaults to 0

  • issue_date (Optional[int]) – Issue date, defaults to None (Current date will be applied)

  • unique_id (Optional[bytes]) – UUID of device, defaults to None

  • unique_id_len (int) – UUID length - 64 or 128 bits, defaults to 64 bits (8 bytes)

  • monotonic_counter (int) – Monotonic counter value, defaults to 0

  • user_sab_id (int) – User SAB id, defaults to 0

FLAGS = 0#
PAYLOAD_FORMAT = '<BBHLL'#
PAYLOAD_LENGTH = 12#
TAG = 63#
TARGET = 0#
create_config()#

Create configuration of the Signed Message.

Return type:

dict[str, Any]

Returns:

Configuration dictionary.

export_payload()#

Exports message payload to bytes array.

Return type:

bytes

Returns:

Bytes representation of message payload.

classmethod load_from_config(config, search_paths=None)#

Converts the configuration option into an message object.

“config” content of container configurations.

Parameters:
  • config (dict[str, Any]) – Message configuration dictionaries.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Raises:

SPSDKError – Invalid configuration detected.

Return type:

Self

Returns:

Message object.

parse_payload(data)#

Parse payload.

Parameters:

data (bytes) – Binary data with Payload to parse.

Return type:

None

verify()#

Verify message properties.

Return type:

Verifier

class spsdk.image.ahab.signed_msg.MessageReturnLifeCycle(cert_ver=0, permissions=0, issue_date=None, unique_id=None, unique_id_len=8, life_cycle=0)#

Bases: Message

Return life cycle request message class representation.

Message used to sign and send to device with EdgeLock.

Parameters:
  • cert_ver (int) – Certificate version, defaults to 0

  • permissions (int) – Certificate permission, to be used in future The stated permission must allow the operation requested by the signed message , defaults to 0

  • issue_date (Optional[int]) – Issue date, defaults to None (Current date will be applied)

  • unique_id (Optional[bytes]) – UUID of device, defaults to None

  • unique_id_len (int) – UUID length - 64 or 128 bits, defaults to 64 bits (8 bytes)

  • life_cycle (int) – Requested life cycle, defaults to 0

PAYLOAD_LENGTH = 4#
TAG = 160#
create_config()#

Create configuration of the Signed Message.

Return type:

dict[str, Any]

Returns:

Configuration dictionary.

export_payload()#

Exports message payload to bytes array.

Return type:

bytes

Returns:

Bytes representation of message payload.

classmethod load_from_config(config, search_paths=None)#

Converts the configuration option into an message object.

“config” content of container configurations.

Parameters:
  • config (dict[str, Any]) – Message configuration dictionaries.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Raises:

SPSDKError – Invalid configuration detected.

Return type:

Self

Returns:

Message object.

parse_payload(data)#

Parse payload.

Parameters:

data (bytes) – Binary data with Payload to parse.

Return type:

None

verify()#

Verify message properties.

Return type:

Verifier

class spsdk.image.ahab.signed_msg.MessageV2(cert_ver=0, permissions=0, issue_date=None, cmd=0, unique_id=None, unique_id_len=8)#

Bases: Message

Class representing the Signed message version 2.

Message used to sign and send to device with EdgeLock.

Parameters:
  • cert_ver (int) – Certificate version, defaults to 0

  • permissions (int) – Certificate permission, to be used in future The stated permission must allow the operation requested by the signed message , defaults to 0

  • issue_date (Optional[int]) – Issue date, defaults to None (Current date will be applied)

  • cmd (int) – Message command ID, defaults to 0

  • unique_id (Optional[bytes]) – UUID of device, defaults to None

  • unique_id_len (int) – UUID length - 64 or 128 bits, defaults to 64 bits (8 bytes)

UNIQUE_ID_LEN = 16#
class spsdk.image.ahab.signed_msg.MessageWriteSecureFuse(cert_ver=0, permissions=0, issue_date=None, unique_id=None, unique_id_len=8, fuse_id=0, length=0, flags=0, data=None)#

Bases: Message

Write secure fuse request message class representation.

Message used to sign and send to device with EdgeLock.

Parameters:
  • cert_ver (int) – Certificate version, defaults to 0

  • permissions (int) – Certificate permission, to be used in future The stated permission must allow the operation requested by the signed message , defaults to 0

  • issue_date (Optional[int]) – Issue date, defaults to None (Current date will be applied)

  • unique_id (Optional[bytes]) – UUID of device, defaults to None

  • unique_id_len (int) – UUID length - 64 or 128 bits, defaults to 64 bits (8 bytes)

  • fuse_id (int) – Fuse ID, defaults to 0

  • length (int) – Fuse length, defaults to 0

  • flags (int) – Fuse flags, defaults to 0

  • data (Optional[list[int]]) – List of fuse values

PAYLOAD_FORMAT = '<HBB'#
TAG = 145#
create_config()#

Create configuration of the Signed Message.

Return type:

dict[str, Any]

Returns:

Configuration dictionary.

export_payload()#

Exports message payload to bytes array.

Return type:

bytes

Returns:

Bytes representation of message payload.

classmethod load_from_config(config, search_paths=None)#

Converts the configuration option into an message object.

“config” content of container configurations.

Parameters:
  • config (dict[str, Any]) – Message configuration dictionaries.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Raises:

SPSDKError – Invalid configuration detected.

Return type:

Self

Returns:

Message object.

parse_payload(data)#

Parse payload.

Parameters:

data (bytes) – Binary data with Payload to parse.

Return type:

None

property payload_len: int#

Message payload length in bytes.

verify()#

Verify message properties.

Return type:

Verifier

class spsdk.image.ahab.signed_msg.SignedMessage(family, revision='latest', signed_msg_container=None, search_paths=None)#

Bases: object

Signed message class.

AHAB Image constructor.

Parameters:
  • family (str) – Name of device family.

  • revision (str) – Device silicon revision, defaults to “latest”

  • ahab_containers – _description_, defaults to None

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Raises:

SPSDKValueError – Invalid input configuration.

property container_type: Type[SignedMessageContainer] | Type[SignedMessageContainerV2]#

Get container class type.

create_config(data_path)#

Create configuration of the Signed Message.

Parameters:

data_path (str) – Path to store the data files of configuration.

Return type:

dict[str, Any]

Returns:

Configuration dictionary.

export()#

Export Signed message image.

Return type:

bytes

Returns:

Signed message image.

classmethod generate_config_template(family, revision='latest', message=None)#

Generate AHAB configuration template.

Parameters:
  • family (str) – Family for which the template should be generated.

  • revision (str) – Family revision of chip.

  • message (Optional[MessageCommands]) – Generate the template just for one message type, if not used , its generated for all messages

Return type:

dict[str, Any]

Returns:

Dictionary of individual templates (key is name of template, value is template itself).

classmethod get_family_validation_schemas()#

Get list of validation schemas for family settings.

Return type:

list[dict[str, Any]]

Returns:

Validation list of schemas.

get_srk_hash(srk_id=0)#

Get SRK hash.

Parameters:

srk_id (int) – ID of SRK table in case of using multiple Signatures, default is 0.

Return type:

bytes

Returns:

SHA256 hash of SRK table.

static get_supported_families()#

Get all supported families for AHAB container.

Return type:

list[str]

Returns:

List of supported families.

classmethod get_validation_schemas(family, revision='latest')#

Get list of validation schemas.

Parameters:
  • family (str) – Family for which the validation schema should be generated.

  • revision (str) – Family revision of chip.

Return type:

list[dict[str, Any]]

Returns:

Validation list of schemas.

image_info()#

Get Image info object.

Return type:

BinaryImage

classmethod load_from_config(config, search_paths=None)#

Converts the configuration option into an Signed message object.

“config” content of container configurations.

Parameters:
  • config (dict[str, Any]) – Signed Message configuration dictionaries.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

Self

Returns:

Signed message object.

parse(binary)#

Parse input binary chunk to the container object.

Raises:

SPSDKError – No AHAB container found in binary data.

Return type:

None

classmethod pre_parse_verify(data)#

Pre-Parse verify of AHAB container.

Parameters:

data (bytes) – Binary data with Container block to pre-parse.

Return type:

Verifier

Returns:

Verifier of pre-parsed binary data.

property srk_count: int#

Get count of used SRK’s.

update_fields()#

Automatically updates all volatile fields in every Signed message container.

Return type:

None

verify()#

Verifier object data.

Return type:

Verifier

class spsdk.image.ahab.signed_msg.SignedMessageContainer(chip_config, flags=0, fuse_version=0, sw_version=0, message=None, signature_block=None, encrypt_iv=None)#

Bases: AHABContainerBase

Class representing the Signed message container.

DAT Container:

+-----+--------------+--------------+----------------+----------------+
|Off  |    Byte 3    |    Byte 2    |      Byte 1    |     Byte 0     |
+-----+--------------+--------------+----------------+----------------+
|0x00 |    Tag       | Length (MSB) | Length (LSB)   |     Version    |
+-----+--------------+--------------+----------------+----------------+
|0x04 |                          Flags                                |
+-----+--------------+--------------+---------------------------------+
|0x08 |   Reserved   | Fuse version |       Software version          |
+-----+--------------+--------------+---------------------------------+
|0x10 |                      Signature Block                          |
+-----+---------------------------------------------------------------+

Signed Message:

+-----+--------------+--------------+----------------+----------------+
|Off  |    Byte 3    |    Byte 2    |      Byte 1    |     Byte 0     |
+-----+--------------+--------------+----------------+----------------+
|0x00 |    Tag       | Length (MSB) | Length (LSB)   |     Version    |
+-----+--------------+--------------+----------------+----------------+
|0x04 |                          Flags                                |
+-----+--------------+--------------+---------------------------------+
|0x08 |   Reserved   | Fuse version |       Software version          |
+-----+--------------+--------------+---------------------------------+
|0x10 |                    Message descriptor                         |
+-----+---------------------------------------------------------------+
|0x34 |                      Message header                           |
+-----+---------------------------------------------------------------+
|0x44 |                      Message payload                          |
+-----+---------------------------------------------------------------+
|0xXX |                      Signature Block                          |
+-----+---------------------------------------------------------------+
Message descriptor::

Off

Byte 3

Byte 2

Byte 1

Byte 0

0x00

Reserved

Flags

0x04

IV (256 bits)

Class object initializer.

Chip_config:

Chip configuration for AHAB.

Parameters:
  • flags (int) – flags.

  • fuse_version (int) – value must be equal to or greater than the version stored in the fuses to allow loading this container.

  • sw_version (int) – used by PHBC (Privileged Host Boot Companion) to select between multiple images with same fuse version field.

  • message (Union[Message, MessageV2, None]) – Message command to be signed.

  • signature_block (Union[SignatureBlock, SignatureBlockV2, None]) – signature block.

  • encrypt_iv (Optional[bytes]) – Encryption Initial Vector - if defined the encryption is used.

ENCRYPT_IV_LEN = 32#
MESSAGE_TYPE#

alias of Message

NAME = 'Signed Message'#
SIGNATURE_BLOCK#

alias of SignatureBlock

TAG: Union[int, list[int]] = 137#
create_config(data_path)#

Create configuration of the Signed Message.

Parameters:

data_path (str) – Path to store the data files of configuration.

Return type:

dict[str, Any]

Returns:

Configuration dictionary.

export()#

Export the signed image into one chunk.

Raises:

SPSDKValueError – if the number of images doesn’t correspond the the number of entries in image array info.

Return type:

bytes

Returns:

images exported into single binary

classmethod format()#

Format of binary representation.

Return type:

str

classmethod get_validation_schemas(family, revision='latest')#

Get list of validation schemas.

Parameters:
  • family (str) – Family for which the validation schema should be generated.

  • revision (str) – Family revision of chip.

Return type:

list[dict[str, Any]]

Returns:

Validation list of schemas.

image_info()#

Get Image info object.

Return type:

BinaryImage

Returns:

Signed Message Info object.

classmethod load_from_config(chip_config, config, search_paths=None)#

Converts the configuration option into an Signed message object.

“config” content of container configurations.

Parameters:
  • chip_config (AhabChipConfig) – Ahab chip configuration.

  • config (dict[str, Any]) – Signed Message configuration dictionaries.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

Self

Returns:

Message object.

classmethod parse(data, chip_config)#

Parse input binary to the signed message object.

Parameters:
  • data (bytes) – Binary data with Container block to parse.

  • chip_config (AhabChipConfig) – Ahab image chip configuration.

Return type:

Self

Returns:

The Signed Message Container

update_fields()#

Updates all volatile information in whole container structure.

Raises:

SPSDKError – When inconsistent image array length is detected.

Return type:

None

verify()#

Verify message properties.

Return type:

Verifier

class spsdk.image.ahab.signed_msg.SignedMessageContainerV2(chip_config, flags=0, fuse_version=0, sw_version=0, message=None, signature_block=None, encrypt_iv=None)#

Bases: SignedMessageContainer

Class representing the Signed message container V2.

Class object initializer.

Chip_config:

Chip configuration for AHAB.

Parameters:
  • flags (int) – flags.

  • fuse_version (int) – value must be equal to or greater than the version stored in the fuses to allow loading this container.

  • sw_version (int) – used by PHBC (Privileged Host Boot Companion) to select between multiple images with same fuse version field.

  • message (Union[Message, MessageV2, None]) – Message command to be signed.

  • signature_block (Union[SignatureBlock, SignatureBlockV2, None]) – signature block.

  • encrypt_iv (Optional[bytes]) – Encryption Initial Vector - if defined the encryption is used.

MESSAGE_TYPE#

alias of MessageV2

SIGNATURE_BLOCK#

alias of SignatureBlockV2

VERSION: Union[int, list[int]] = 2#
classmethod get_validation_schemas(family, revision='latest')#

Get list of validation schemas.

Parameters:
  • family (str) – Family for which the validation schema should be generated.

  • revision (str) – Family revision of chip.

Return type:

list[dict[str, Any]]

Returns:

Validation list of schemas.

class spsdk.image.ahab.signed_msg.SignedMessageTags(tag, label, description=None)#

Bases: SpsdkEnum

Signed message container related tags.

SIGNED_MSG = (137, 'SIGNED_MSG', 'Signed message.')#

Bootable image#

This module contains Bootable image related code.

class spsdk.image.bootable_image.bimg.BootableImage(family, mem_type, revision='latest', init_offset=0)#

Bases: BaseClass

Bootable Image class.

Bootable Image constructor.

Parameters:
  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

property bootable_header_only: bool#

The image contains only bootable image header.

No application is available.

export()#

Export bootable image.

Return type:

bytes

Returns:

Complete binary of bootable image.

classmethod generate_config_template(family, mem_type, revision='latest')#

Get validation schema for the family.

Parameters:
  • family (str) – Chip family

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip revision specification, as default, latest is used.

Return type:

str

Returns:

Validation schema.

static get_memory_type_config(family, mem_type, revision='latest')#

Return dictionary with configuration for specific memory type.

Parameters:
  • family (str) – Chip family name.

  • mem_type (MemoryType) – CHip memory type to handle bootable area.

  • revision (str) – Revision of chip.

Raises:

SPSDKKeyError – If memory type does not exist in database

Return type:

dict[str, Any]

Returns:

Dictionary with configuration.

get_segment(segment)#

Get bootable segment by its name or Enum class.

Parameters:

segment (Union[str, BootableImageSegment]) – Name of enum class of segment.

Return type:

Segment

Returns:

Segment.

get_segment_offset(segment)#

Get segment offset.

Parameters:

segment (Segment) – Segment object to get its offset

Return type:

int

Returns:

Segment offset

classmethod get_supported_families()#

Get list of all supported families by bootable image.

Return type:

list[str]

Returns:

List of families.

classmethod get_supported_memory_types(family=None, revision='latest')#

Return list of supported memory types.

Return type:

list[MemoryType]

Returns:

List of supported families.

static get_supported_revisions(family)#

Return list of supported revisions.

Return type:

list[str]

Returns:

List of supported revisions.

static get_validation_schemas(family, mem_type, revision='latest')#

Get validation schema for the family.

Parameters:
  • family (str) – Chip family

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip revision specification, as default, latest is used.

Return type:

list[dict[str, Any]]

Returns:

List of validation schema dictionaries.

static get_validation_schemas_family()#

Create the validation schema just for supported families.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas for Bootable Image supported families.

property header_len: int#

Length of the header.

The length of the space before application data. :return: Length of the bootable image area.

image_info()#

Create Binary image of bootable image.

Return type:

BinaryImage

Returns:

BinaryImage object of bootable image.

property init_offset: int#

Initial offset compared to “full” bootable image.Only segments after this offset are considered.

static load_from_config(config, search_paths=None)#

Load bootable image from configuration.

Parameters:
  • config (dict) – Configuration of Bootable image.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

BootableImage

classmethod parse(binary, family=None, mem_type=None, revision='latest')#

Parse binary into bootable image object.

Parameters:
  • binary (bytes) – Bootable image binary.

  • family (Optional[str]) – Chip family.

  • mem_type (Optional[MemoryType]) – Used memory type.

  • revision (str) – Chip silicon revision.

Return type:

Self

static pre_parse_verify(data, family, mem_type, revision='latest')#

Pre-Parse binary T osee main issue before parsing.

Parameters:
  • data (bytes) – Bootable image binary.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

Return type:

Verifier

Returns:

Verifier object of preparsed data.

property segments: list[Segment]#

List of used segments.

set_init_offset(init_offset)#

Set init offset by name of segment or length.

Return type:

None

store_config(output)#

Store bootable image into configuration and binary blocks.

Parameters:

output (str) – Path to output folder to store bootable image configuration.

Return type:

None

verify()#

Get verifier object of segment.

Return type:

Verifier

Returns:

Verifier of current object.

Bootable image segments#

This module contains Bootable image related code.

class spsdk.image.bootable_image.segments.BootableImageSegment(tag, label, description=None)#

Bases: SpsdkEnum

Bootable image segment.

AHAB_CONTAINER = (12, 'ahab_container', 'AHAB container segment')#
BEE_HEADER_0 = (7, 'bee_header_0', 'BEE header 0 segment')#
BEE_HEADER_1 = (8, 'bee_header_1', 'BEE header 1 segment')#
FCB = (2, 'fcb', 'Fcb segment')#
FCB_XSPI = (3, 'fcb_xspi', 'Fcb segment')#
HAB_CONTAINER = (11, 'hab_container', 'HAB container segment')#
IMAGE_VERSION = (4, 'image_version', 'Image version segment')#
IMAGE_VERSION_AP = (5, 'image_version_ap', 'Image version antipole segment')#
KEYBLOB = (1, 'keyblob', 'Keyblob segment')#
KEYSTORE = (6, 'keystore', 'Keystore segment')#
MBI = (10, 'mbi', 'Masterboot image segment')#
PRIMARY_IMAGE_CONTAINER_SET = (13, 'primary_image_container_set', 'Primary Image Container Set segment')#
SB21 = (15, 'sb21', 'Secure binary 2.1 segment')#
SB31 = (16, 'sb31', 'Secure binary 3.1 segment')#
SECONDARY_IMAGE_CONTAINER_SET = (14, 'secondary_image_container_set', 'Secondary Image Container Set segment')#
UNKNOWN = (0, 'unknown', 'Unknown segment')#
XMCD = (9, 'xmcd', 'XMCD segment')#
exception spsdk.image.bootable_image.segments.SPSDKSegmentNotPresent(desc=None)#

Bases: SPSDKError

The segment is not present in the configuration.

Initialize the base SPSDK Exception.

class spsdk.image.bootable_image.segments.Segment(offset, family, mem_type, revision='latest', raw_block=None)#

Bases: BaseClass

Base Bootable Image Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in the full bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

BOOT_HEADER = True#
CFG_NAME: Optional[str] = None#
IMAGE_PATTERNS = ['zeros', 'ones']#
INIT_SEGMENT = False#
NAME = (0, 'unknown', 'Unknown segment')#
OFFSET_ALIGNMENT = 1#
SIZE = -1#
classmethod cfg_key()#

Configuration key name.

Return type:

str

clear()#

Clear the segment to init state.

Return type:

None

create_config(output_dir)#

Create configuration including store the data to specified path.

Parameters:

output_dir (str) – Path where the information should be stored

Return type:

Union[str, int]

Returns:

Value of segment to configuration file

export()#

Serialize object into bytes array.

Return type:

bytes

Returns:

Raw binary block of segment

static find_segment_offset(binary)#

Try to find the start of the Segment in data blob.

Parameters:

binary (bytes) – Data to be used to find Segment.

Return type:

int

Returns:

Offset in data to new data container.

property full_image_offset: int#

Offset of the segment within the full bootable image.

image_info()#

Get Image info format.

Return type:

BinaryImage

Returns:

The segment content in Binary Image format.

property is_present: bool#

Returns true if the segment is present in the image.

load_config(config, search_paths=None)#

Load segment from configuration.

Parameters:
  • config (dict[str, Any]) – Configuration of Segment.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

None

classmethod parse(data)#

Deserialize object from bytes array.

Return type:

Self

parse_binary(binary)#

Parse binary block into Segment object.

Parameters:

binary (bytes) – Binary image.

Raises:
Return type:

None

pre_parse_verify(data)#

Pre-Parse binary to see main issue before parsing.

Parameters:

data (bytes) – Bootable image binary.

Return type:

Verifier

Returns:

Verifier object of preparsed data.

verify()#

Get verifier object of segment.

Return type:

Verifier

Returns:

Verifier of current object.

class spsdk.image.bootable_image.segments.SegmentAhab(offset, family, mem_type, revision='latest', raw_block=None, ahab=None)#

Bases: Segment

Bootable Image Advanced High Assurance Boot(HAB) Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in whole bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

  • ahab (Optional[AHABImage]) – Advanced High Assurance Boot class.

BOOT_HEADER = False#
INIT_SEGMENT = True#
NAME = (12, 'ahab_container', 'AHAB container segment')#
clear()#

Clear the segment to init state.

Return type:

None

create_config(output_dir)#

Create configuration including store the data to specified path.

Parameters:

output_dir (str) – Path where the information should be stored

Return type:

Union[str, int]

Returns:

Value of segment to configuration file

static find_segment_offset(binary)#

Try to find the start of the AHAB Image in data blob.

Parameters:

binary (bytes) – Data to be used to find AHAB container.

Return type:

int

Returns:

Offset in data to new data container.

image_info()#

Get Image info format.

Return type:

BinaryImage

Returns:

The segment content in Binary Image format.

load_config(config, search_paths=None)#

Load segment from configuration.

Parameters:
  • config (dict[str, Any]) – Configuration of Segment.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

None

parse_binary(binary)#

Parse binary block into Segment object.

Parameters:

binary (bytes) – binary image.

Return type:

None

pre_parse_verify(data)#

Pre-Parse binary T osee main issue before parsing.

Parameters:

data (bytes) – Bootable image binary.

Return type:

Verifier

Returns:

Verifier object of preparsed data.

verify()#

Get verifier object of segment.

Return type:

Verifier

Returns:

Verifier of current object.

class spsdk.image.bootable_image.segments.SegmentBeeHeader0(offset, family, mem_type, revision='latest', raw_block=None)#

Bases: Segment

Bootable Image BEE encryption header 0 Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in the full bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

NAME = (7, 'bee_header_0', 'BEE header 0 segment')#
SIZE = 512#
class spsdk.image.bootable_image.segments.SegmentBeeHeader1(offset, family, mem_type, revision='latest', raw_block=None)#

Bases: Segment

Bootable Image BEE encryption header 1 Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in the full bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

NAME = (8, 'bee_header_1', 'BEE header 1 segment')#
SIZE = 512#
class spsdk.image.bootable_image.segments.SegmentFcb(offset, family, mem_type, revision='latest', raw_block=None, fcb=None)#

Bases: Segment

Bootable Image FCB Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in whole bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

  • fcb (Optional[FCB]) – FCB class.

INIT_SEGMENT = True#
NAME = (2, 'fcb', 'Fcb segment')#
SIZE = 512#
clear()#

Clear the segment to init state.

Return type:

None

create_config(output_dir)#

Create configuration including store the data to specified path.

Parameters:

output_dir (str) – Path where the information should be stored

Return type:

Union[str, int]

Returns:

Value of segment to configuration file

load_config(config, search_paths=None)#

Load segment from configuration.

Parameters:
  • config (dict[str, Any]) – Configuration of Segment.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

None

parse_binary(binary)#

Parse binary block into Segment object.

Parameters:

binary (bytes) – binary image.

Raises:
Return type:

None

class spsdk.image.bootable_image.segments.SegmentFcbXspi(offset, family, mem_type, revision='latest', raw_block=None, fcb=None)#

Bases: SegmentFcb

Bootable Image KeyBlob Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in whole bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

  • fcb (Optional[FCB]) – FCB class.

CFG_NAME: Optional[str] = 'fcb'#
NAME = (3, 'fcb_xspi', 'Fcb segment')#
SIZE = 768#
class spsdk.image.bootable_image.segments.SegmentHab(offset, family, mem_type, revision='latest', raw_block=None, hab=None)#

Bases: Segment

Bootable Image High Assurance Boot(HAB) Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in whole bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

  • hab (Optional[HabContainer]) – High Assurance Boot class.

BOOT_HEADER = False#
INIT_SEGMENT = True#
NAME = (11, 'hab_container', 'HAB container segment')#
clear()#

Clear the segment to init state.

Return type:

None

image_info()#

Get Image info format.

Return type:

BinaryImage

Returns:

The segment content in Binary Image format.

load_config(config, search_paths=None)#

Load segment from configuration.

Parameters:
  • config (dict[str, Any]) – Configuration of Segment.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

None

parse_binary(binary)#

Parse binary block into Segment object.

Parameters:

binary (bytes) – binary image.

Return type:

None

class spsdk.image.bootable_image.segments.SegmentImageVersion(offset, family, mem_type, revision='latest', raw_block=None)#

Bases: Segment

Bootable Image Image version Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in the full bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

NAME = (4, 'image_version', 'Image version segment')#
SIZE = 4#
create_config(output_dir)#

Create configuration including store the data to specified path.

Parameters:

output_dir (str) – Path where the information should be stored

Return type:

Union[str, int]

Returns:

Value of segment to configuration file

load_config(config, search_paths=None)#

Load segment from configuration.

Parameters:
  • config (dict[str, Any]) – Configuration of Segment.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

None

parse_binary(binary)#

Parse binary block into Segment object.

Parameters:

binary (bytes) – binary image.

Raises:

SPSDKParsingError – If given binary block size is not equal to block size in header

Return type:

None

verify()#

Get verifier object of segment.

Return type:

Verifier

Returns:

Verifier of current object.

class spsdk.image.bootable_image.segments.SegmentImageVersionAntiPole(offset, family, mem_type, revision='latest', raw_block=None)#

Bases: Segment

Bootable Image Image version with antipole value Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in the full bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

CFG_NAME: Optional[str] = 'image_version'#
NAME = (5, 'image_version_ap', 'Image version antipole segment')#
SIZE = 4#
UNPROGRAMMED_VALUE = 65535#
create_config(output_dir)#

Create configuration including store the data to specified path.

Parameters:

output_dir (str) – Path where the information should be stored

Return type:

Union[str, int]

Returns:

Value of segment to configuration file

load_config(config, search_paths=None)#

Load segment from configuration.

Parameters:
  • config (dict[str, Any]) – Configuration of Segment.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

None

parse_binary(binary)#

Parse binary block into Segment object.

Parameters:

binary (bytes) – binary image.

Raises:

SPSDKParsingError – If given binary block size is not equal to block size in header

Return type:

None

verify()#

Get verifier object of segment.

Return type:

Verifier

Returns:

Verifier of current object.

class spsdk.image.bootable_image.segments.SegmentKeyBlob(offset, family, mem_type, revision='latest', raw_block=None)#

Bases: Segment

Bootable Image KeyBlob Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in the full bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

NAME = (1, 'keyblob', 'Keyblob segment')#
SIZE = 256#
class spsdk.image.bootable_image.segments.SegmentKeyStore(offset, family, mem_type, revision='latest', raw_block=None)#

Bases: Segment

Bootable Image KeyStore Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in the full bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

NAME = (6, 'keystore', 'Keystore segment')#
SIZE = 2048#
class spsdk.image.bootable_image.segments.SegmentMbi(offset, family, mem_type, revision='latest', raw_block=None, mbi=None)#

Bases: Segment

Bootable Image Master Boot Image(MBI) Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in whole bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

  • mbi (Optional[MasterBootImage]) – Master boot image class.

BOOT_HEADER = False#
INIT_SEGMENT = True#
NAME = (10, 'mbi', 'Masterboot image segment')#
clear()#

Clear the segment to init state.

Return type:

None

create_config(output_dir)#

Create configuration including store the data to specified path.

Parameters:

output_dir (str) – Path where the information should be stored

Return type:

Union[str, int]

Returns:

Value of segment to configuration file

image_info()#

Get Image info format.

Return type:

BinaryImage

Returns:

The segment content in Binary Image format.

load_config(config, search_paths=None)#

Load segment from configuration.

Parameters:
  • config (dict[str, Any]) – Configuration of Segment.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

None

parse_binary(binary)#

Parse binary block into Segment object.

Parameters:

binary (bytes) – binary image.

Return type:

None

class spsdk.image.bootable_image.segments.SegmentPrimaryAhab(offset, family, mem_type, revision='latest', raw_block=None, ahab=None)#

Bases: SegmentAhab

Primary Bootable Image Advanced High Assurance Boot(HAB) Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in whole bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

  • ahab (Optional[AHABImage]) – Advanced High Assurance Boot class.

NAME = (13, 'primary_image_container_set', 'Primary Image Container Set segment')#
class spsdk.image.bootable_image.segments.SegmentSB21(offset, family, mem_type, revision='latest', raw_block=None, sb21=None)#

Bases: Segment

Bootable Image Secure Binary 2.1 Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in whole bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

  • sb21 (Optional[BootImageV21]) – Secure Binary v2.1 class.

BOOT_HEADER = False#
INIT_SEGMENT = True#
NAME = (15, 'sb21', 'Secure binary 2.1 segment')#
clear()#

Clear the segment to init state.

Return type:

None

load_config(config, search_paths=None)#

Load segment from configuration.

Parameters:
  • config (dict[str, Any]) – Configuration of Segment.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

None

parse_binary(binary)#

Parse binary block into Segment object.

Parameters:

binary (bytes) – binary image.

Return type:

None

class spsdk.image.bootable_image.segments.SegmentSB31(offset, family, mem_type, revision='latest', raw_block=None, sb31=None)#

Bases: Segment

Bootable Image Secure Binary 3.1 Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in whole bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

  • sb31 (Optional[SecureBinary31]) – Secure Binary v3.1 class.

BOOT_HEADER = False#
INIT_SEGMENT = True#
NAME = (16, 'sb31', 'Secure binary 3.1 segment')#
clear()#

Clear the segment to init state.

Return type:

None

load_config(config, search_paths=None)#

Load segment from configuration.

Parameters:
  • config (dict[str, Any]) – Configuration of Segment.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

None

parse_binary(binary)#

Parse binary block into Segment object.

Parameters:

binary (bytes) – binary image.

Return type:

None

class spsdk.image.bootable_image.segments.SegmentSecondaryAhab(offset, family, mem_type, revision='latest', raw_block=None, ahab=None)#

Bases: SegmentAhab

Primary Bootable Image Advanced High Assurance Boot(HAB) Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in whole bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

  • ahab (Optional[AHABImage]) – Advanced High Assurance Boot class.

INIT_SEGMENT = False#
NAME = (14, 'secondary_image_container_set', 'Secondary Image Container Set segment')#
OFFSET_ALIGNMENT = 1024#
class spsdk.image.bootable_image.segments.SegmentXmcd(offset, family, mem_type, revision='latest', raw_block=None, xmcd=None)#

Bases: Segment

Bootable Image XMCD Segment class.

Segment initialization, at least raw data are stored.

Parameters:
  • offset (int) – Offset of Segment in whole bootable image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip silicon revision.

  • raw_block (Optional[bytes]) – Raw data of segment.

  • xmcd (Optional[XMCD]) – XMCD class.

NAME = (9, 'xmcd', 'XMCD segment')#
SIZE = 512#
clear()#

Clear the segment to init state.

Return type:

None

create_config(output_dir)#

Create configuration including store the data to specified path.

Parameters:

output_dir (str) – Path where the information should be stored

Return type:

Union[str, int]

Returns:

Value of segment to configuration file

load_config(config, search_paths=None)#

Load segment from configuration.

Parameters:
  • config (dict[str, Any]) – Configuration of Segment.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

None

parse_binary(binary)#

Parse binary block into Segment object.

Parameters:

binary (bytes) – binary image.

Raises:
Return type:

None

verify()#

Get verifier object of segment.

Return type:

Verifier

Returns:

Verifier of current object.

spsdk.image.bootable_image.segments.get_segment_class(name)#

Get the segment class type.

Return type:

Type[Segment]

Returns:

Segment class type.

spsdk.image.bootable_image.segments.get_segments()#

Get list of all supported segments.

Return type:

dict[BootableImageSegment, Type[Segment]]

FCB - Flash Configuration Block#

This module contains FCB (Flash Configuration Block) related code.

class spsdk.image.fcb.fcb.FCB(family, mem_type, revision='latest')#

Bases: SegmentBase

FCB (Flash Configuration Block).

FCB Constructor.

Parameters:
  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Optional Chip family revision.

Raises:

SPSDKValueError – Unsupported family.

FEATURE = 'fcb'#
SIZE = 512#
TAG = b'FCFB'#
TAG_SWAPPED = b'CFBF'#
create_config()#

Create current configuration YAML.

Return type:

str

Returns:

Configuration of FCB Block.

static generate_config_template(family, mem_type, revision='latest')#

Generate configuration for selected family.

Parameters:
  • family (str) – Family description.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip revision specification, as default, latest is used.

Return type:

str

Returns:

Template of FCB Block.

classmethod get_validation_schemas(family, mem_type, revision='latest')#

Create the validation schema.

Parameters:
  • family (str) – Family description.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Chip revision specification, as default, latest is used.

Raises:

SPSDKError – Family or revision is not supported.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas.

static get_validation_schemas_family()#

Create the validation schema just for supported families.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas for FCB supported families.

static load_from_config(config)#

Load configuration file of FCB.

Parameters:

config (dict) – FCB configuration file.

Return type:

FCB

Returns:

FCB object.

classmethod parse(binary, offset=0, family='Unknown', mem_type=MemoryType(tag=4, label='flexspi_nor', description='Flexspi NOR'), revision='latest')#

Parse binary block into FCB object.

Parameters:
  • binary (bytes) – binary image.

  • offset (int) – Offset of FCB in binary image.

  • family (str) – Chip family.

  • mem_type (MemoryType) – Used memory type.

  • revision (str) – Optional Chip family revision.

Raises:

SPSDKError – If given binary block contains wrong FCB tag

Return type:

Self

property registers: Registers#

Registers of segment.

HAB - High Assurance Boot#

This module contains HAB related code.

HAB Container#

This module contains HAB container related code.

class spsdk.image.hab.hab_container.HabContainer(flags, ivt_offset, start_address, segments, image_pattern='zeros')#

Bases: object

Hab container.

HAB container initialization.

Parameters:
  • flags (int) – Flags

  • ivt_offset (int) – IVT offset value which is actually the HAB container offset

  • start_address (int) – Start address of bootable image

  • segments (HabSegments) – Segments list

  • image_pattern (str) – Image pattern used to fill empty spaces

property app_segment: AppHabSegment#

APP segment object.

property bdt_segment: BdtHabSegment#

BDT segment object.

property csf_segment: CsfHabSegment | None#

CSF segment object if exists, None otherwise.

property dcd_segment: DcdHabSegment | None#

DCD segment object if exists, None otherwise.

export()#

Export into binary.

Return type:

bytes

export_padding()#

Get into binary including initial padding.

Return type:

bytes

classmethod generate_config_template(family=None)#

Generate configuration template.

Return type:

str

Returns:

Dictionary of individual templates (key is name of template, value is template itself).

static get_boot_devices(family)#

Get all supported boot devices for given family.

Parameters:

family (str) – Target family name.

Return type:

list[str]

Returns:

List of supported boot devices.

get_segment(segment)#

Get container’s segment.

Parameters:

segment (HabSegment) – Segment enum

Return type:

Optional[HabSegmentBase]

static get_supported_families()#

Get all supported families for HAB container.

Return type:

list[str]

Returns:

List of supported families.

classmethod get_validation_schemas(family=None)#

Create the list of validation schemas.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas.

image_info(padding=False)#

Create Binary image of HAB container.

Return type:

BinaryImage

Returns:

BinaryImage object of HAB container.

property is_authenticated: bool#

Returns true if container is authenticated, false otherwise.

property is_encrypted: bool#

Returns true if container is encrypted, false otherwise.

property ivt_segment: IvtHabSegment#

IVT segment object.

classmethod load_configuration(config_path, external_files=None, search_paths=None)#

Load the BD or YAML Configuration.

Parameters:
  • config_path (str) – Path to configuration file either BD or YAML formatted.

  • external_files (Optional[list[str]]) – Optional list of external files for BD processing

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

dict

Returns:

Dictionary with parsed configuration.

classmethod load_from_config(config, search_paths=None)#

Load the HAB container object from parsed bd_data configuration.

Parameters:
  • config (dict[str, Any]) – Image configuration

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

Self

classmethod parse(data)#

Parse existing binary into HAB container object.

Parameters:

data (bytes) – Binary to be parsed

Return type:

Self

classmethod transform_bd_configuration(config)#

Transform configuration from flat structure to BD structure.

Parameters:

config (dict[Any, Any]) – Parsed configuration from BD parser

Return type:

dict[Any, Any]

Returns:

Transformed configuration

classmethod transform_configuration(config)#

Transform configuration from BD parser to flat YAML structure.

Parameters:

config (dict[Any, Any]) – Parsed configuration from BD parser

Return type:

dict[Any, Any]

Returns:

Transformed configuration

update_csf()#

Update the CSF segment including signing and encryption.

Return type:

None

property xmcd_segment: XmcdHabSegment | None#

XMCD segment object if exists, None otherwise.

XMCD#

This module contains XMCD (External Memory Configuration Data) related code.

class spsdk.image.xmcd.xmcd.ConfigurationBlockType(tag, label, description=None)#

Bases: SpsdkEnum

Support configuration blocks Enum.

FULL = (1, 'full', 'Full configuration')#
SIMPLIFIED = (0, 'simplified', 'Simplified configuration')#
class spsdk.image.xmcd.xmcd.XMCD(family, mem_type, config_type, revision='latest')#

Bases: SegmentBase

XMCD (External Memory Configuration Data).

XMCD Constructor.

Parameters:
  • family (str) – Chip family.

  • config_type (ConfigurationBlockType) – Configuration block type: simplified | full.

  • revision (str) – Optional Chip family revision.

Raises:

SPSDKValueError – Unsupported family.

FEATURE = 'xmcd'#
calculate_crc()#

Calculate XMCD CRC value.

Return type:

bytes

property config_type: ConfigurationBlockType#

Configuration type. It can be either simplified or full.

property crc: bytes#

CRC value if XMCD object.

Returns:

SHA256 hash of SRK table.

create_config()#

Create current configuration YAML.

Raises:

SPSDKError – Registers are not loaded in the object.

Return type:

str

Returns:

Configuration of XMCD Block.

create_crc_hash_fuses_script()#

Create fuses script of CRC hash.

Return type:

str

static generate_config_template(family, mem_type, config_type, revision='latest')#

Generate configuration for selected family.

Parameters:
  • family (str) – Family description.

  • mem_type (MemoryType) – Used memory type.

  • config_type (ConfigurationBlockType) – Config type: either simplified or full.

  • revision (str) – Chip revision specification, as default, latest is used.

Return type:

str

Returns:

Template of XMCD Block.

classmethod get_supported_configuration_types(family, mem_type, revision='latest')#

Return list of supported memory interfaces.

Return type:

list[ConfigurationBlockType]

Returns:

List of supported family interfaces.

classmethod get_validation_schemas(family, mem_type, config_type, revision='latest')#

Create the validation schema.

Parameters:
  • family (str) – Family description.

  • mem_type (MemoryType) – Used memory type.

  • config_type (ConfigurationBlockType) – Config type: either simplified or full.

  • revision (str) – Chip revision specification, as default, latest is used.

Raises:

SPSDKError – Family or revision is not supported.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas.

static get_validation_schemas_family()#

Create the validation schema just for supported families.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas for XMCD supported families.

classmethod load_from_config(config)#

Load from XMCD configuration.

Parameters:

config (dict) – XMCD configuration.

Return type:

Self

Returns:

XMCD object.

property mem_type: MemoryType#

Memory type.

classmethod parse(binary, offset=0, family='Unknown', revision='latest')#

Parse binary block into XMCD object.

Parameters:
  • binary (bytes) – binary image.

  • offset (int) – Offset of XMCD in binary image.

  • family (str) – Chip family.

  • revision (str) – Optional Chip family revision.

Raises:

SPSDKError – If given binary block size is not equal to block size in header

Return type:

Self

property registers: Registers#

Merged XMCD registers containing header and configuration block.

property size: int#

XMCD size.

verify()#

Verify XMCD data.

Return type:

Verifier

class spsdk.image.xmcd.xmcd.XMCDConfigBlock(family, mem_type, config_type, revision='latest')#

Bases: object

External Memory Configuration Data Configuration Block.

Initialize the XMCD Config Block.

export()#

Export segment’s header as bytes (serialization).

Return type:

bytes

Returns:

Binary representation of segment.

load_from_config(config)#

Load from XMCD configuration.

Parameters:

config (dict) – XMCD configuration.

Return type:

None

parse(data)#

Parse XMCD Header from binary data.

Return type:

None

property registers: Registers#

Configuration block registers.

property size: int#

Config block size.

verify()#

Verify XMCD config block data.

Return type:

Verifier

class spsdk.image.xmcd.xmcd.XMCDHeader(family, revision='latest')#

Bases: object

External Memory Configuration Data Header.

Initialize the XMCD Header.

TAG = 12#
property config_block_size: int#

Size of XMCD config data blob.

property config_type: ConfigurationBlockType#

Config type property.

export()#

Export segment’s header as bytes (serialization).

Return type:

bytes

Returns:

Binary representation of segment.

load_from_config(config)#

Load from XMCD configuration.

Parameters:

config (dict) – XMCD configuration.

Return type:

None

property mem_type: MemoryType#

Memory type property.

parse(data)#

Parse XMCD Header from binary data.

Return type:

None

property size: int#

Header size.

verify()#

Verify XMCD header data.

Return type:

Verifier

property xmcd_size: int#

The size of configuration block including XMCD header itself.