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: spsdk.image.images.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=4, 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: spsdk.image.segments.SegAPP

APP.

Return type

SegAPP

property bdt: spsdk.image.segments.SegBDT

BDT.

Return type

SegBDT

property csf: spsdk.image.segments.SegCSF

CSF.

Return type

SegCSF

export()

Export image as bytes array.

Return type

bytes

Returns

bytes

property ivt: spsdk.image.segments.SegIVT2

IVT.

Return type

SegIVT2

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.

Return type

bool

property size: int

Size of IMX Boot Image v2..

Return type

int

property version: int

Version of IMX Boot Image v2.

Return type

int

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

Bases: spsdk.image.images.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=4, 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[spsdk.image.segments.SegBDS3a]

BDT.

Return type

List[SegBDS3a]

property csf: spsdk.image.segments.SegCSF

CSF.

Return type

SegCSF

export()

Export Image as binary blob.

Return type

bytes

property ivt: List[spsdk.image.segments.SegIVT3a]

IVT.

Return type

List[SegIVT3a]

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.

Return type

bool

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

Bases: spsdk.image.images.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=4, 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[spsdk.image.segments.SegBDS3b]

BDT.

Return type

List[SegBDS3b]

property csf: spsdk.image.segments.SegCSF

CSF.

Return type

SegCSF

export()

Export.

Return type

bytes

property ivt: List[spsdk.image.segments.SegIVT3b]

IVT.

Return type

List[SegIVT3b]

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 – When the value is incorrect

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

Return type

BootImgBase

Returns

BootImg3b object

property plg: bool

PLG.

Return type

bool

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

Bases: spsdk.image.images.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: spsdk.image.images.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=4, 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: spsdk.image.segments.SegAPP

APP.

Return type

SegAPP

property bdt: spsdk.image.segments.SegBDT

BDT.

Return type

SegBDT

property csf: spsdk.image.segments.SegCSF

CSF.

Return type

SegCSF

export()

Export Image as bytes array.

Return type

bytes

Returns

bytes

property ivt: spsdk.image.segments.SegIVT2

IVT.

Return type

SegIVT2

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.

Return type

bool

property size: int

Size of IMX Boot Image.

Return type

int

property version: int

Version of IMX Boot Image.

Return type

int

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: Optional[spsdk.image.segments.SegDCD]

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

Return type

Optional[SegDCD]

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: spsdk.image.images.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
  • SPSDKError – If invalid IVT offset

  • SPSDKError – If invalid version

  • SPSDKError – If Plugin is not supported

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
  • SPSDKError – If invalid length of srk table

  • SPSDKError – If invalid index of srk table

  • SPSDKError – If application data is not present

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
  • SPSDKError – If invalid length of srk table

  • SPSDKError – If invalid index of selected SRK key

  • SPSDKError – If application data not present

Return type

None

add_dcd_bin(data)

Add DCD binary data.

Parameters

data (bytes) – DCD binary data to be added

Raises
  • SPSDKError – If DCD is already present

  • SPSDKError – If DCD is not enabled

Return type

None

add_image(data, img_type=4, 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: spsdk.image.segments.SegAPP

Segment with application image.

Return type

SegAPP

property app_offset: int
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

property bdt: spsdk.image.segments.SegBDT

Boot Data Table.

Return type

SegBDT

property bee: spsdk.image.segments.SegBEE
Return type

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.

Return type

bool

property csf: Optional[spsdk.image.segments.SegCSF]

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

Return type

Optional[SegCSF]

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

Return type

bytes

property dek_img_offset: int

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

Return type

int

property dek_key: Optional[bytes]

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

Return type

Optional[bytes]

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

Return type

int

property enabled_csf: Optional[spsdk.image.segments.SegCSF]

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

Return type

Optional[SegCSF]

export(zulu=datetime.datetime(2023, 12, 15, 13, 7, 17, 367347, 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
  • SPSDKError – If the image is not encrypted

  • SPSDKError – If padding is present

  • SPSDKError – If invalid alignment of application

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(2023, 12, 15, 13, 7, 17, 367341, 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: spsdk.image.segments.AbstractFCB

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

Return type

AbstractFCB

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.

Return type

bool

property ivt: spsdk.image.segments.SegIVT2

Image Vector Table (IVT) segment.

Return type

SegIVT2

property ivt_offset: int

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

Return type

int

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.

Return type

bool

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

Return type

int

property version: int

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

Return type

int

property xmcd: Optional[spsdk.image.segments.SegXMCD]

Return the XMCD block.

Return type

Optional[SegXMCD]

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.

Return type

int

property app: Optional[bytes]

APP.

Return type

Optional[bytes]

property csf: spsdk.image.segments.SegCSF

CSF.

Return type

SegCSF

export()

Export.

Return type

bytes

property version: int

Version.

Return type

int

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=0, key_index=1, sig_format=197, engine=0, engine_cfg=0, location=0, certificate=None, private_key=None)

Bases: spsdk.image.commands.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.

Return type

int

property cmd_data_reference: Optional[Union[spsdk.image.secret.MAC, spsdk.image.secret.Signature]]

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

  • None if no reference was assigned;

  • Value type is command-specific

Return type

Union[MAC, Signature, None]

property engine: spsdk.image.commands.EnumEngine

Engine.

Return type

EnumEngine

export()

Export to binary form (serialization).

Return type

bytes

Returns

binary representation of the command

property flags: int

Flag of Authenticate data command.

Return type

int

property key_index: int

Key index.

Return type

int

property needs_cmd_data_reference: bool

Whether the command contains a reference to an additional data.

Return type

bool

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: Optional[Union[spsdk.image.secret.MAC, spsdk.image.secret.Signature]]

Signature referenced by location attribute.

Return type

Union[MAC, Signature, None]

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: spsdk.utils.abstract.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.

Return type

int

property cmd_data_reference: Optional[spsdk.image.secret.BaseSecretClass]

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

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

Return type

Optional[BaseSecretClass]

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

Return type

bool

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.

Return type

int

property tag: spsdk.image.header.CmdTag

Command tag.

Return type

CmdTag

class spsdk.image.commands.CmdCheckData(numbytes=4, ops=1, address=0, mask=0, count=None)

Bases: spsdk.image.commands.CmdBase

Check data command.

Initialize the check data command.

Parameters
  • numbytes (int) – number of bytes

  • ops (int) – type of operation

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

  • mask (int) – mask value

  • count (Optional[int]) – count value

Raises
  • SPSDKError – If incorrect number of bytes

  • SPSDKError – If incorrect operation

export()

Export to binary form (serialization).

Return type

bytes

Returns

binary representation of the command

property num_bytes: int

Number of bytes.

Return type

int

property ops: int

Operation of Check data command.

Return type

int

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=0, data=None)

Bases: spsdk.image.commands.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: int

Engine.

Return type

int

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=0, cert_fmt=3, hash_alg=0, src_index=0, tgt_index=0, location=0)

Bases: spsdk.image.commands.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: spsdk.image.commands.EnumCertFormat

Certificate format.

Return type

EnumCertFormat

property certificate_ref: Optional[Union[spsdk.image.secret.CertificateImg, spsdk.image.secret.SrkTable]]

Corresponding certificate referenced by key-location.

Return type

Union[CertificateImg, SrkTable, None]

property cmd_data_offset: int

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

Return type

int

property cmd_data_reference: Optional[Union[spsdk.image.secret.CertificateImg, spsdk.image.secret.SrkTable]]

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

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

Return type

Union[CertificateImg, SrkTable, None]

export()

Export to binary form (serialization).

Return type

bytes

Returns

binary representation of the command

property flags: spsdk.image.commands.EnumInsKey

Flags.

Return type

EnumInsKey

property hash_algorithm: spsdk.image.secret.EnumAlgorithm

Hash algorithm.

Return type

EnumAlgorithm

property needs_cmd_data_reference: bool

Whether the command contains a reference to an additional data.

Return type

bool

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

Return type

int

property target_index: int

Target key index.

Return type

int

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

Bases: spsdk.image.commands.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=3, hash_alg=0, engine=0, engine_cfg=0)

Bases: spsdk.image.commands.CmdBase

Set command.

Initialize the set command.

property engine: spsdk.image.commands.EnumEngine

Engine plugin tags.

Return type

EnumEngine

export()

Export to binary form (serialization).

Return type

bytes

Returns

binary representation of the command

property hash_algorithm: spsdk.image.secret.EnumAlgorithm

Type of hash algorithm.

Return type

EnumAlgorithm

property itm: int

Item of Set command.

Return type

int

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=0, features=0, uid=0)

Bases: spsdk.image.commands.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=0, features=0, uid=0)

Bases: spsdk.image.commands.CmdBase, abc.ABC

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

Constructor.

Parameters
  • engine (EnumEngine) – to be unlocked

  • features (int) – engine specific features

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

property engine: spsdk.image.commands.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

Return type

EnumEngine

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: spsdk.image.commands.CmdUnlockAbstract

Command Unlock for Cryptographic Acceleration and Assurance Module .

Initialize.

Parameters

features (int) – mask of FEATURE_UNLOCK_x constants, defaults to 0

FEATURE_UNLOCK_MFG = 4
FEATURE_UNLOCK_MID = 1
FEATURE_UNLOCK_RNG = 2
property unlock_mfg: bool

Leave Zero is able Master Key write unlocked.

Return type

bool

property unlock_mid: bool

Leave Job Ring and DECO master ID registers unlocked.

Return type

bool

property unlock_rng: bool

Leave RNG un-instantiated.

Return type

bool

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

Bases: spsdk.image.commands.CmdUnlockAbstract

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

Initialize.

Parameters
  • features (int) – mask of FEATURE_UNLOCK_x constants, defaults to 0

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

FEATURE_UNLOCK_FLD_RTN = 1
FEATURE_UNLOCK_JTAG = 8
FEATURE_UNLOCK_SCS = 4
FEATURE_UNLOCK_SRK_RVK = 2
property unlock_csc: bool

Leave SCS register unlocked.

Return type

bool

property unlock_fld_rtn: bool

Leave Field Return activation unlocked.

Return type

bool

property unlock_jtag: bool

Unlock JTAG using SCS HAB_JDE bit.

Return type

bool

property unlock_srk_rvk: bool

Leave SRK revocation unlocked.

Return type

bool

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

Bases: spsdk.image.commands.CmdUnlockAbstract

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

Constructor.

Parameters

features (int) – mask of FEATURE_UNLOCK_* constants

FEATURE_UNLOCK_LP_SWR = 1
FEATURE_UNLOCK_ZMK_WRITE = 2
property unlock_lp_swr: bool

Leave LP SW reset unlocked.

Return type

bool

property unlock_zmk_write: bool

Leave Zero is able Master Key write unlocked.

Return type

bool

class spsdk.image.commands.CmdWriteData(numbytes=4, ops=0, data=None)

Bases: spsdk.image.commands.CmdBase

Write data command.

Initialize Write Data command.

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

  • ops (int) – type of write operation

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

Raises
  • SPSDKError – When incorrect number of bytes

  • SPSDKError – When incorrect type of operation

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.

Return type

int

property ops: int

Type of write operation.

Return type

int

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

Bases: spsdk.utils.easy_enum.Enum

Flags for Authenticate Data commands.

ABS = 1
CLR = 0
class spsdk.image.commands.EnumCAAM

Bases: spsdk.utils.easy_enum.Enum

CAAM Engine Configuration.

DEFAULT = 0
DSC_SWAP16 = 128
DSC_SWAP8 = 64
IN_SWAP16 = 2
IN_SWAP8 = 1
OUT_SWAP16 = 16
OUT_SWAP8 = 8
class spsdk.image.commands.EnumCertFormat

Bases: spsdk.utils.easy_enum.Enum

Certificate format tags.

AEAD = 163
BLOB = 187
CMS = 197
SRK = 3
X509 = 9
class spsdk.image.commands.EnumCheckOps

Bases: spsdk.utils.easy_enum.Enum

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

ALL_CLEAR = 0
ALL_SET = 1
ANY_CLEAR = 2
ANY_SET = 3
class spsdk.image.commands.EnumEngine

Bases: spsdk.utils.easy_enum.Enum

Engine plugin tags.

ANY = 0
CAAM = 29
CSU = 10
DCP = 27
DTCP = 34
HDCP = 36
OCOTP = 33
ROM = 54
RTIC = 5
SAHARA = 6
SCC = 3
SNVS = 30
SRTC = 12
SW = 255
class spsdk.image.commands.EnumInsKey

Bases: spsdk.utils.easy_enum.Enum

Flags for Install Key commands.

ABS = 1
CFG = 8
CID = 64
CLR = 0
CSF = 2
DAT = 4
FID = 16
HSH = 128
MID = 32
class spsdk.image.commands.EnumItm

Bases: spsdk.utils.easy_enum.Enum

Engine configuration flags of Set command.

ENG = 3
MID = 1
class spsdk.image.commands.EnumWriteOps

Bases: spsdk.utils.easy_enum.Enum

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

CLEAR_BITMASK = 2
SET_BITMASK = 3
WRITE_CLEAR_BITS = 1
WRITE_VALUE = 0
exception spsdk.image.commands.ExpectedSignatureOrMACError(desc=None)

Bases: spsdk.exceptions.SPSDKError

CmdAuthData additional data block: expected Signature or MAC object.

Initialize the base SPSDK Exception.

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: spsdk.image.header.Header

Command header.

Constructor.

Parameters
  • tag (CmdTag) – 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
  • SPSDKParsingError – If required header tag does not match

  • SPSDKError – If invalid tag

property tag: spsdk.image.header.CmdTag

Command tag.

Return type

CmdTag

class spsdk.image.header.CmdTag

Bases: spsdk.utils.easy_enum.Enum

CSF/DCD Command Tag.

AUT_DAT = 202
CHK_DAT = 207
INIT = 180
INS_KEY = 190
NOP = 192
SET = 177
UNLK = 178
WRT_DAT = 204
class spsdk.image.header.Header(tag=0, param=0, length=None)

Bases: spsdk.utils.abstract.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.

Return type

int

property tag: int
Return type

int

Returns

section tag: command tag or segment tag, …

property tag_name: str

Returns the header’s tag name.

Return type

str

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

Bases: spsdk.image.header.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

length: int
param: int
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

Bases: spsdk.utils.easy_enum.Enum

Segments Tag.

BIC1 = 135
CRT = 215
CSF = 212
DCD = 210
EVT = 219
IVT2 = 209
IVT3 = 222
MAC = 172
RVT = 221
SIG = 216
SIGB = 144
WRP = 129
XMCD = 192

Secret Module

Commands and responses used by SDP module.

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

Bases: spsdk.utils.abstract.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

Return type

int

property version: int

Format version.

Return type

int

property version_major: int

Major format version.

Return type

int

property version_minor: int

Minor format version.

Return type

int

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

Bases: spsdk.image.secret.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.

Return type

int

class spsdk.image.secret.EnumAlgorithm

Bases: spsdk.utils.easy_enum.Enum

Algorithm types.

AES = 85
ANY = 0
BLOB = 113
CCM = 102
CIPHER = 5
EC = 4
ECDSA = 39
F = 3
HASH = 1
MODE = 6
PKCS1 = 33
SHA1 = 17
SHA256 = 23
SHA512 = 27
SIG = 2
WRAP = 7
class spsdk.image.secret.EnumSRK

Bases: spsdk.utils.easy_enum.Enum

Entry type in the System Root Key Table.

KEY_HASH = 238
KEY_PUBLIC = 225
class spsdk.image.secret.MAC(version=64, nonce_len=0, mac_len=16, data=None)

Bases: spsdk.image.secret.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.

Return type

bytes

export()

Export instance into binary form (serialization).

Return type

bytes

Returns

binary form

property mac: bytes

MAC bytes for the encryption/decryption.

Return type

bytes

property nonce: bytes

NONCE bytes for the encryption/decryption.

Return type

bytes

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.

Return type

int

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
  • SPSDKError – If incorrect length of mac

  • SPSDKError – If incorrect length of nonce

  • SPSDKError – If incorrect number of MAC bytes”

Return type

None

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

Bases: spsdk.image.secret.SRKException

This SRK public key algorithm is not yet implemented.

Initialize the base SPSDK Exception.

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

Bases: spsdk.image.secret.SRKException

This type of SRK table item is not implemented.

Initialize the base SPSDK Exception.

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

Bases: spsdk.image.secret.SRKException

This SRK public key algorithm is not yet implemented.

Initialize the base SPSDK Exception.

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

Bases: spsdk.exceptions.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.

Return type

bytes

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.

Return type

int

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

Bases: spsdk.image.secret.BaseSecretClass

Class representing a signature.

Initialize the signature.

property data: bytes

Signature data.

Return type

bytes

export()

Export.

Return type

bytes

classmethod parse(data)

Parse.

Return type

Self

property size: int

Size of a signature.

Return type

int

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

Return type

int

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

Bases: spsdk.image.secret.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.

Return type

int

export()

Export.

Return type

bytes

property flag: int

Flag.

Return type

int

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.

Return type

int

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

Bases: spsdk.image.secret.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.

Return type

int

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.

Return type

int

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

Bases: spsdk.image.secret.SrkItem

RSA public key in SRK Table, see SrkTable class.

Initialize the srk table item.

property algorithm: int

Algorithm.

Return type

int

export()

Export.

Return type

bytes

property flag: int

Flag.

Return type

int

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.

Return type

int

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.

Return type

int

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

Bases: spsdk.image.secret.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
  • SPSDKError – If incorrect index of the fuse

  • SPSDKError – If incorrect length of SRK items

classmethod parse(data)

Parse of SRK table.

Return type

Self

property size: int

Size of SRK table.

Return type

int

Data Segments

Segments within image module.

class spsdk.image.segments.AbstractFCB

Bases: spsdk.image.segments.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.

Return type

bool

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).

Return type

int

class spsdk.image.segments.BaseSegment

Bases: abc.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).

Return type

int

classmethod parse(data)

Parse interfaces.

Raises

NotImplementedError – Derived class has to implement this method

Return type

Self

property size: int

Size of base segment.

Return type

int

property space: int

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

Please mind, padding is exported optionally.

Return type

int

class spsdk.image.segments.FlexSPIConfBlockFCB

Bases: spsdk.image.segments.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.

Return type

int

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

Bases: spsdk.image.segments.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
  • SPSDKError – If invalid size of the exported padding

  • SPSDKError – If invalid padding

export()

Export to binary form (serialization).

Return type

bytes

Returns

binary representation

property size: int

Return size of the exported data in bytes.

Return type

int

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

Bases: spsdk.image.segments.BaseSegment

APP segment.

Initialize APP segment.

Parameters

data (Optional[bytes]) – application binary data

property data: Optional[bytes]

Application binary data.

Return type

Optional[bytes]

export()

Export segment as bytes array.

Return type

bytes

Returns

bytes

property size: int

Size of APP segment.

Return type

int

class spsdk.image.segments.SegBDS3a

Bases: spsdk.image.segments.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.

Return type

int

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.

Return type

int

class spsdk.image.segments.SegBDS3b

Bases: spsdk.image.segments.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.

Return type

int

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.

Return type

int

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

Bases: spsdk.image.segments.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.

Return type

int

property size: int

Size of the exported binary data (without padding).

Return type

int

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

Bases: spsdk.image.segments.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
Return type

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: spsdk.image.segments.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.

Return type

int

validate()

Validate segment.

Return type

None

property version: int

Version of Boot Images Container segment.

Return type

int

class spsdk.image.segments.SegBIM

Bases: spsdk.image.segments.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.

Return type

int

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

Bases: spsdk.image.segments.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[spsdk.image.commands.CmdBase]

List of CSF commands in the segment.

Return type

List[CmdBase]

export()

Export segment as bytes array (serialization).

Return type

bytes

Returns

bytes

property macs: Iterator[spsdk.image.secret.MAC]

Iterator of all MAC sections.

Return type

Iterator[MAC]

classmethod parse(data)

Parse segment from bytes array.

Parameters

data (bytes) – The bytes array of CSF segment

Raises
  • SPSDKCorruptedException – When there is unknown command

  • SPSDKCorruptedException – When command can not be parsed

Return type

Self

Returns

SegCSF instance

property size: int

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

Return type

int

property space: int

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

Return type

int

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
  • SPSDKError – If invalid length of data

  • SPSDKError – If invalid length of data

Return type

None

property version: int

Version of CSF segment.

Return type

int

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

Bases: spsdk.image.segments.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[spsdk.image.commands.CmdBase]

Commands of Device configuration data (DCD) segment.

Return type

List[CmdBase]

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: spsdk.image.header.Header

Header of Device configuration data (DCD) segment.

Return type

Header

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.

Return type

int

property space: int

Add space.

Return type

int

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: spsdk.image.segments.AbstractFCB, abc.ABC

FCB.

Initialize FCB segment.

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

Cyclic redundancy check.

Return type

int

export()

Export to binary form.

Return type

bytes

class spsdk.image.segments.SegIDS3a

Bases: spsdk.image.segments.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.

Return type

int

class spsdk.image.segments.SegIDS3b

Bases: spsdk.image.segments.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.

Return type

int

class spsdk.image.segments.SegIVT2(version)

Bases: spsdk.image.segments.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.

Return type

int

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.

Return type

int

class spsdk.image.segments.SegIVT3a(param)

Bases: spsdk.image.segments.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: spsdk.image.header.Header

Header of IVT3a segment.

Return type

Header

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.

Return type

int

validate()

Validation of IVT3a segment.

Return type

None

class spsdk.image.segments.SegIVT3b(version)

Bases: spsdk.image.segments.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: spsdk.image.header.Header

Header of IVT3b segment.

Return type

Header

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

Return type

int

validate()

Validation of IVT3b segment.

Return type

None

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

Bases: spsdk.image.segments.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.

Return type

int

property version: int

Version of Signature Block segment.

Return type

int

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

Bases: spsdk.image.segments.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
  • SPSDKValueError – If the given interface is not supported

  • SPSDKValueError – If the given blovk type is not supported

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

Size of XMCD config data blob.

Return type

int

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: spsdk.utils.abstract.BaseClass

Base class for image segment.

Segment base Constructor.

Parameters
  • family (str) – Chip family.

  • revision (str) – Optional Chip family revision.

Raises

SPSDKValueError – Unsupported family.

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.

abstract static get_database()

Get the devices database.

Return type

Database

classmethod get_memory_types(family, revision='latest')

Get memory types data from database.

Parameters
  • family (str) – Chip family.

  • revision (str) – Optional Chip family revision.

Return type

Dict

classmethod get_supported_families()

Return list of supported families.

Return type

List

Returns

List of supported families.

classmethod get_supported_memory_types(family, revision='latest')

Get list of supported memory types data from database.

Parameters
  • family (str) – Chip family.

  • revision (str) – Optional Chip family revision.

Return type

List

abstract static load_from_config(config)

Load configuration file.

Parameters

config (Dict) – Segment configuration file.

Return type

Any

Returns

Segment object.

abstract property registers: spsdk.utils.registers.Registers

Registers of segment.

Return type

Registers

TrustZone

Module provides support for TrustZone configuration data.

class spsdk.image.trustzone.TrustZone(tz_type=0, family=None, revision=None, 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=None)

Alternate constructor for CUSTOM type of TrustZone.

Return type

TrustZone

classmethod disabled()

Alternate constructor for DISABLED type of TrustZone.

Return type

TrustZone

classmethod enabled()

Alternate constructor for ENABLED type of TrustZone.

Return type

TrustZone

export()

Return the TrustZone data as bytes.

Return type

bytes

classmethod from_binary(family, raw_data, revision=None)

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).

get_families()

Return list of supported chip families.

Return type

List[str]

get_latest_revision(family=None)

Return latest revision for given family.

Return type

str

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.

get_revisions(family=None)

Return a list of revisions for given family.

Return type

List[str]

classmethod 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.

classmethod load_database()

Load data from TZ config file.

Return type

Database

sanitize_revision(family, revision=None)

Sanitize revision.

if the ‘revision’ is None return the latest revision if the ‘revision’ is provided return it as lower-case

Return type

str

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

Bases: spsdk.utils.easy_enum.Enum

Enum defining various types of TrustZone types.

CUSTOM = 1
DISABLED = 2
ENABLED = 0

Support for BEE encryption for RT10xx devices

Contains support for BEE encryption for RT10xx devices.

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
Return type

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: spsdk.image.bee.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
Return type

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: spsdk.image.bee.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
  • SPSDKError – If invalid length of kib key

  • SPSDKError – If invalid length of kib iv

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=1, lock_options=0, counter=None)

Bases: spsdk.image.bee.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
Return type

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

Bases: spsdk.utils.easy_enum.Enum

AES mode selection for BEE PRDB encryption.

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

Bases: spsdk.image.bee.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[spsdk.image.bee.BeeFacRegion]
Return type

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 (the key is marked as SW_GP2 on RT10xx)

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

Bases: spsdk.utils.easy_enum.Enum

Device key source.

KEYSTORE = 1
OTP = 0
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
  • SPSDKError – If invalid length of master key

  • SPSDKError – If invalid length of input

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: spsdk.image.keystore.KeySourceType

Device key source.

Return type

KeySourceType

Master Boot Image

Master Boot Image.

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

Bases: object

Master Boot Image Interface.

Initialization of MBI.

Parameters

kwargs (Dict[str, 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.

Return type

int

Returns

Final image data length.

app_table: Optional[spsdk.image.mbi.mbi_mixin.MultipleImageTable]
cert_block: Optional[Union[spsdk.utils.crypto.cert_blocks.CertBlockV1, spsdk.utils.crypto.cert_blocks.CertBlockV21, spsdk.utils.crypto.cert_blocks.CertBlockVx]]
collect_data: Callable[[], bytes]
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

None

disassemble_image: Callable[[bytes], None]
encrypt: Any
export()

Export final bootable image.

Return type

bytes

Returns

Bootable Image in bytes.

finalize: Any
classmethod get_supported_families()

Create the list of supported families by this class.

Return type

List[str]

Returns

List of supported families.

classmethod get_validation_schemas()

Create the validation schema for current image type.

Return type

List[Dict[str, Any]]

Returns

Validation schema.

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)

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

Raises

SPSDKParsingError – Cannot determinate the decoding class

Return type

MasterBootImage

Returns

MBI parsed class

post_encrypt: Any
property rkth: Optional[bytes]

Get Root Key Table Hash from certificate block if present.

Return type

Optional[bytes]

Returns

Root Key Table Hash as hex string.

sign: Any
property total_len: int

Compute Master Boot Image data length.

Return type

int

Returns

Final image data length.

validate()

Validate the setting of image.

Return type

None

spsdk.image.mbi.mbi.create_mbi_class(name)

Create Master Boot image class.

Parameters

name (str) – Name of Class

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)

Get all Master Boot Image supported classes for chip family.

Parameters

family (str) – Chip family.

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)

Generate all possible configuration for selected family.

Parameters

family (str) – Family description.

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: spsdk.image.misc.RawDataException

Read_raw_data could not read enough data.

Initialize the base SPSDK Exception.

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

Bases: spsdk.exceptions.SPSDKError

Raw data read failed.

Initialize the base SPSDK Exception.

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

Bases: spsdk.image.misc.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.MasterBootImageManifest(firmware_version, trust_zone=None, digest_hash_algo=None)

Bases: object

MasterBootImage Manifest used in LPC55s3x.

Initialize MBI Manifest object.

Parameters
  • firmware_version (int) – firmware version

  • digest_hash_algo (Optional[EnumHashAlgorithm]) – Digest hash algorithm, defaults to None

  • trust_zone (Optional[TrustZone]) – TrustZone instance, defaults to None

DIGEST_PRESENT_FLAG = 2147483648
FORMAT = '<4s4L'
FORMAT_VERSION = 65536
HASH_TYPE_MASK = 15
MAGIC = b'imgm'
SUPPORTED_ALGORITHMS = [1, 2, 3]
export()

Serialize MBI Manifest.

Return type

bytes

static get_hash_size(algorithm)

Get hash size by used algorithm.

Return type

int

classmethod parse(family, data)

Parse the binary to Master Boot Image Manifest.

Parameters
  • family (str) – Device family.

  • data (bytes) – Binary Image with MBI Manifest.

Raises

SPSDKParsingError – Invalid header is detected.

Return type

Self

Returns

MBI Manifest object

class spsdk.image.mbi.mbi_mixin.MasterBootImageManifestMcxNx(firmware_version, trust_zone=None, digest_hash_algo=None)

Bases: spsdk.image.mbi.mbi_mixin.MasterBootImageManifest

MasterBootImage Manifest used in mcxnx devices.

Initialize MBI Manifest object.

Parameters
  • firmware_version (int) – firmware version

  • digest_hash_algo (Optional[EnumHashAlgorithm]) – Digest hash algorithm, defaults to None

  • trust_zone (Optional[TrustZone]) – TrustZone instance, defaults to None

compute_crc(image)

Compute and add CRC field.

Parameters

image (bytes) – Image data to be used to compute CRC

Return type

None

export()

Serialize MBI Manifest.

Return type

bytes

classmethod parse(family, data)

Parse the binary to Master Boot Image Manifest.

Parameters
  • family (str) – Device family.

  • data (bytes) – Binary Image with MBI Manifest.

Raises

SPSDKParsingError – Invalid header is detected.

Return type

Self

Returns

MBI Manifest object

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

bytes

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 (bytes) – Input raw image to encrypt.

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

Return type

bytes

Returns

Encrypted image.

finalize(image, revert=False)

Finalize the image for export.

This part could add HMAC/KeyStore etc.

Parameters
  • image (bytes) – Input image.

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

Return type

bytes

Returns

Finalized image suitable for export.

post_encrypt(image, revert=False)

Optionally do some post encrypt image updates.

Parameters
  • image (bytes) – Encrypted image.

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

Return type

bytes

Returns

Updated encrypted image.

sign(image, revert=False)

Sign image (by signature or CRC).

Parameters
  • image (bytes) – Image to sign.

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

Return type

bytes

Returns

Optionally signed image.

class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinApp

Bases: spsdk.image.mbi.mbi_mixin.Mbi_ExportMixin

Export Mixin to handle simple application data.

app: Optional[bytes]
collect_data()

Collect application data including update IVT.

Return type

bytes

Returns

Image with updated IVT.

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

Bases: spsdk.image.mbi.mbi_mixin.Mbi_ExportMixin

Export Mixin to handle simple application data with BCA.

app: Optional[bytes]
app_len: int
collect_data()

Collect application data and TrustZone including update IVT.

Return type

bytes

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

update_bca: Callable[[bytes, int], bytes]
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppCertBlockManifest

Bases: spsdk.image.mbi.mbi_mixin.Mbi_ExportMixin

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

app: Optional[bytes]
cert_block: Optional[Union[spsdk.utils.crypto.cert_blocks.CertBlockV1, spsdk.utils.crypto.cert_blocks.CertBlockV21]]
clean_ivt: Callable[[bytes], bytes]
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

bytes

Returns

Image with updated IVT and added Certification Block with Manifest.

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 (bytes) – Input image.

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

Return type

bytes

Returns

Finalized image suitable for export.

get_app_data: Callable[[], bytes]
manifest: Optional[spsdk.image.mbi.mbi_mixin.T_Manifest]
total_len: Any
update_ivt: Callable[[bytes, int, int], bytes]
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTrustZone

Bases: spsdk.image.mbi.mbi_mixin.Mbi_ExportMixin

Export Mixin to handle simple application data and TrustZone.

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

Collect application data and TrustZone including update IVT.

Return type

bytes

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]
get_app_data: Callable[[], bytes]
total_len: Any
trust_zone: spsdk.image.trustzone.TrustZone
update_ivt: Callable[[bytes, int, int], bytes]
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTrustZoneCertBlock

Bases: spsdk.image.mbi.mbi_mixin.Mbi_ExportMixin

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

app: Optional[bytes]
app_len: int
cert_block: Optional[Union[spsdk.utils.crypto.cert_blocks.CertBlockV1, spsdk.utils.crypto.cert_blocks.CertBlockV21]]
clean_ivt: Callable[[bytes], bytes]
collect_data()

Collect application data and TrustZone including update IVT.

Return type

bytes

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]
get_app_data: Callable[[], bytes]
total_len: Any
trust_zone: spsdk.image.trustzone.TrustZone
update_ivt: Callable[[bytes, int, int], bytes]
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTrustZoneCertBlockEncrypt

Bases: spsdk.image.mbi.mbi_mixin.Mbi_ExportMixin

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

app: Optional[bytes]
cert_block: Optional[Union[spsdk.utils.crypto.cert_blocks.CertBlockV1, spsdk.utils.crypto.cert_blocks.CertBlockV21]]
clean_ivt: Callable[[bytes], bytes]
collect_data()

Collect application data and TrustZone including update IVT.

Return type

bytes

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]
family: str
get_app_data: Callable[[], bytes]
get_app_length: Callable[[], int]
img_len: int
total_len: Any
trust_zone: spsdk.image.trustzone.TrustZone
update_ivt: Callable[[bytes, int, int], bytes]
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinCrcSign

Bases: spsdk.image.mbi.mbi_mixin.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 (bytes) – Input raw image.

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

Return type

bytes

Returns

Image enriched by CRC in IVT table.

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

Bases: spsdk.image.mbi.mbi_mixin.Mbi_ExportMixin

Export Mixin to handle sign by ECC.

cert_block: Optional[Union[spsdk.utils.crypto.cert_blocks.CertBlockV1, spsdk.utils.crypto.cert_blocks.CertBlockV21]]
no_signature: Optional[bool]
sign(image, revert=False)

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

Parameters
  • image (bytes) – Input raw image.

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

Return type

bytes

Returns

Image enriched by ECC signature at end of image.

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

Bases: spsdk.image.mbi.mbi_mixin.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_OFFSET: int
IMG_SIGNED_HEADER_END: int
add_hash: bool
app: Optional[bytes]
cert_block: spsdk.utils.crypto.cert_blocks.CertBlockVx
no_signature: Optional[bool]
sign(image, revert=False)

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

Parameters
  • image (bytes) – Input raw image.

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

Return type

bytes

Returns

Image enriched by ECC signature and SHA256 digest.

signature_provider: Optional[spsdk.crypto.signature_provider.SignatureProvider]
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinEncrypt

Bases: spsdk.image.mbi.mbi_mixin.Mbi_ExportMixin

Export Mixin to handle Encrypt MBI in legacy way.

HMAC_OFFSET: int
cert_block: Optional[Union[spsdk.utils.crypto.cert_blocks.CertBlockV1, spsdk.utils.crypto.cert_blocks.CertBlockV21]]
ctr_init_vector: bytes
encrypt(image, revert=False)

Encrypt image if needed.

Parameters
  • image (bytes) – Input raw image to encrypt.

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

Return type

bytes

Returns

Encrypted image.

get_app_length: Callable[[], int]
hmac_key: Optional[bytes]
property img_len: int

Image length of encrypted legacy image.

Return type

int

key_store: Optional[spsdk.image.keystore.KeyStore]
post_encrypt(image, revert=False)

Optionally do some post encrypt image updates.

Parameters
  • image (bytes) – Encrypted image.

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

Return type

bytes

Returns

Updated encrypted image.

total_len: int
trust_zone: spsdk.image.trustzone.TrustZone
update_ivt: Callable[[bytes, int, int], bytes]
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinHmacKeyStoreFinalize

Bases: spsdk.image.mbi.mbi_mixin.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 (bytes) – Input image.

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

Return type

bytes

Returns

Finalized image suitable for export.

key_store: Optional[spsdk.image.keystore.KeyStore]
class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinRsaSign

Bases: spsdk.image.mbi.mbi_mixin.Mbi_ExportMixin

Export Mixin to handle sign by RSA.

cert_block: Optional[Union[spsdk.utils.crypto.cert_blocks.CertBlockV1, spsdk.utils.crypto.cert_blocks.CertBlockV21]]
no_signature: Optional[bool]
sign(image, revert=False)

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

Parameters
  • image (bytes) – Input raw image.

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

Return type

bytes

Returns

Image enriched by RSA signature at end of image.

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

Bases: object

Base class for Master BOtt Image Mixin classes.

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: spsdk.image.mbi.mbi_mixin.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.

Return type

bytes

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_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

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

Bases: spsdk.image.mbi.mbi_mixin.Mbi_Mixin

Master Boot Image Boot Configuration Area.

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_FCB_OFFSET = 1024
IMG_FCB_SIZE = 16
IMG_ISK_HASH_OFFSET = 1184
IMG_ISK_OFFSET = 1040
IMG_SIGNATURE_OFFSET = 896
IMG_SIGNED_HEADER_END = 1024
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_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_MixinCertBlockV1

Bases: spsdk.image.mbi.mbi_mixin.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[Union[spsdk.utils.crypto.cert_blocks.CertBlockV1, spsdk.utils.crypto.cert_blocks.CertBlockV21]]
key_store: Optional[spsdk.image.keystore.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[spsdk.crypto.signature_provider.SignatureProvider]
total_len: Any
class spsdk.image.mbi.mbi_mixin.Mbi_MixinCertBlockV21

Bases: spsdk.image.mbi.mbi_mixin.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[Union[spsdk.utils.crypto.cert_blocks.CertBlockV1, spsdk.utils.crypto.cert_blocks.CertBlockV21]]
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[spsdk.crypto.signature_provider.SignatureProvider]
class spsdk.image.mbi.mbi_mixin.Mbi_MixinCertBlockVx

Bases: spsdk.image.mbi.mbi_mixin.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']
add_hash: bool
cert_block: spsdk.utils.crypto.cert_blocks.CertBlockVx
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[spsdk.crypto.signature_provider.SignatureProvider]
class spsdk.image.mbi.mbi_mixin.Mbi_MixinCtrInitVector

Bases: spsdk.image.mbi.mbi_mixin.Mbi_Mixin

Master Boot Image initial vector for encryption counter.

HMAC_SIZE: int
NEEDED_MEMBERS: Dict[str, Any] = {'_ctr_init_vector': b'\x96Q\x8fL|b\x91:\x1d\xb2\x99\xad\xea\xd4\x8c\xa0'}
PRE_PARSED: List[str] = ['cert_block']
VALIDATION_SCHEMAS: List[str] = ['ctr_init_vector']
cert_block: Optional[Union[spsdk.utils.crypto.cert_blocks.CertBlockV1, spsdk.utils.crypto.cert_blocks.CertBlockV21]]
property ctr_init_vector: Optional[bytes]

Counter init vector.

Return type

Optional[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_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_MixinFwVersion

Bases: spsdk.image.mbi.mbi_mixin.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: spsdk.image.mbi.mbi_mixin.Mbi_Mixin

Master Boot Image HMAC class.

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: Optional[bytes]

HMAC key in bytes.

Return type

Optional[bytes]

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 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: spsdk.image.mbi.mbi_mixin.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: spsdk.image.mbi.mbi_mixin.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']
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: spsdk.image.mbi.mbi_mixin.Mbi_Mixin

Master Boot Image SubType class.

class Mbi_ImageSubTypeKw45xx

Bases: spsdk.utils.easy_enum.Enum

Supported MAIN and NBU subtypes for KW45xx and K32W1xx.

MAIN = 0
NBU = 1
class Mbi_ImageSubTypeMcxn9xx

Bases: spsdk.utils.easy_enum.Enum

Supported MAIN and NBU subtypes for MCXN9xx.

MAIN = 0
RECOVERY = 1
NEEDED_MEMBERS: Dict[str, Any] = {'image_subtype': 0}
VALIDATION_SCHEMAS: List[str] = ['image_subtype']
image_subtype: Optional[int]
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: spsdk.image.mbi.mbi_mixin.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
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: spsdk.image.mbi.mbi_mixin.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[spsdk.image.mbi.mbi_mixin.MultipleImageTable]
static 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

static 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.

static get_cert_block_offset(data)

Get the certificate block offset from raw data.

During getting of flags, the length is also validated.

Parameters

data (bytes) – Raw MBI image data.

Return type

int

Returns

Certificate block offset

static 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

static 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.

static get_image_type(data)

Get the Image type from raw data.

Parameters

data (bytes) – Raw MBI image data.

Return type

int

Returns

Image type

static 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.

static 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.

static 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

static 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.

static 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
key_store: Optional[spsdk.image.keystore.KeyStore]
load_address: Optional[int]
trust_zone: spsdk.image.trustzone.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_MixinKeyStore

Bases: spsdk.image.mbi.mbi_mixin.Mbi_Mixin

Master Boot Image KeyStore class.

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]
key_store: Optional[spsdk.image.keystore.KeyStore]
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 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: spsdk.image.mbi.mbi_mixin.Mbi_Mixin

Master Boot Image load address class.

NEEDED_MEMBERS: Dict[str, Any] = {'load_address': 0}
VALIDATION_SCHEMAS: List[str] = ['load_addr']
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_MixinManifest

Bases: spsdk.image.mbi.mbi_mixin.Mbi_MixinTrustZoneMandatory

Master Boot Image Manifest class.

NEEDED_MEMBERS: Dict[str, Any] = {'cert_block': None, 'family': 'Unknown', 'manifest': None}
PRE_PARSED: List[str] = ['cert_block']
VALIDATION_SCHEMAS: List[str] = ['trust_zone', 'firmware_version']
cert_block: Optional[Union[spsdk.utils.crypto.cert_blocks.CertBlockV1, spsdk.utils.crypto.cert_blocks.CertBlockV21]]
family: str
firmware_version: Optional[int]
manifest: Optional[spsdk.image.mbi.mbi_mixin.MasterBootImageManifest]
manifest_class

alias of spsdk.image.mbi.mbi_mixin.MasterBootImageManifest

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

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

class spsdk.image.mbi.mbi_mixin.Mbi_MixinManifestDigest

Bases: spsdk.image.mbi.mbi_mixin.Mbi_MixinManifest

Master Boot Image Manifest class for devices supporting ImageDigest functionality.

VALIDATION_SCHEMAS: List[str] = ['trust_zone', 'firmware_version', 'digest_hash_algo']
class spsdk.image.mbi.mbi_mixin.Mbi_MixinManifestMcxNx

Bases: spsdk.image.mbi.mbi_mixin.Mbi_MixinManifest

Master Boot Image Manifest class for mcxn9xx device.

manifest: Optional[spsdk.image.mbi.mbi_mixin.MasterBootImageManifestMcxNx]
manifest_class

alias of spsdk.image.mbi.mbi_mixin.MasterBootImageManifestMcxNx

class spsdk.image.mbi.mbi_mixin.Mbi_MixinNoSignature

Bases: spsdk.image.mbi.mbi_mixin.Mbi_Mixin

Master Boot Image No Signature.

NEEDED_MEMBERS: Dict[str, Any] = {'no_signature': False}
VALIDATION_SCHEMAS: List[str] = ['no_signature']
mix_load_from_config(config)

Load configuration from dictionary.

Parameters

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

Return type

None

no_signature: Optional[bool]
class spsdk.image.mbi.mbi_mixin.Mbi_MixinRelocTable

Bases: spsdk.image.mbi.mbi_mixin.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[spsdk.image.mbi.mbi_mixin.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.

get_app_data()

Fold the application data.

Return type

bytes

Returns

Whole application data.

get_app_length()

Compute full application length.

Return type

int

Returns

Length of application with relocated data.

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: spsdk.image.mbi.mbi_mixin.Mbi_Mixin

Master Boot Image Trust Zone class.

NEEDED_MEMBERS: Dict[str, Any] = {'family': 'Unknown', 'trust_zone': <TrustZone: type: 0 (TrustZone enabled with default settings)}
PRE_PARSED: List[str] = ['cert_block']
VALIDATION_SCHEMAS: List[str] = ['trust_zone']
cert_block: Optional[Union[spsdk.utils.crypto.cert_blocks.CertBlockV1, spsdk.utils.crypto.cert_blocks.CertBlockV21]]
family: str
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

search_paths: Optional[List[str]]
trust_zone: spsdk.image.trustzone.TrustZone
class spsdk.image.mbi.mbi_mixin.Mbi_MixinTrustZoneMandatory

Bases: spsdk.image.mbi.mbi_mixin.Mbi_MixinTrustZone

Master Boot Image Trust Zone class for LPC55s3x family.

cert_block: Optional[Union[spsdk.utils.crypto.cert_blocks.CertBlockV1, spsdk.utils.crypto.cert_blocks.CertBlockV21]]
family: str
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

search_paths: Optional[List[str]]
trust_zone: spsdk.image.trustzone.TrustZone
class spsdk.image.mbi.mbi_mixin.MultipleImageEntry(img, dst_addr, flags=1)

Bases: object

The class represents an entry in relocation table.

It also contains a corresponding image (binary)

Constructor.

Parameters
  • img (bytes) – binary image data

  • dst_addr (int) – destination address

  • flags (int) – see LTI constants

Raises
  • SPSDKError – If invalid destination address

  • SPSDKError – Other section types (INIT) are not supported

LTI_LOAD = 1
property dst_addr: int

Destination address.

Return type

int

export_entry()

Export relocation table entry in binary form.

Return type

bytes

export_image()

Binary image aligned to the 4-bytes boundary.

Return type

bytes

property flags: int

Flags, currently not used.

Return type

int

property image: bytes

Binary image data.

Return type

bytes

property is_load: bool

True if entry represents LOAD section.

Return type

bool

static parse(data)

Parse relocation table entry from binary form.

Return type

MultipleImageEntry

property size: int

Size of the image (not aligned).

Return type

int

property src_addr: int

Source address; this value is calculated automatically when building the image.

Return type

int

class spsdk.image.mbi.mbi_mixin.MultipleImageTable

Bases: object

The class allows to merge several images into single image and add relocation table.

It can be used for multicore images (one image for each core) or trustzone images (merging secure and non-secure image)

Initialize the Multiple Image Table.

add_entry(entry)

Add entry into relocation table.

Parameters

entry (MultipleImageEntry) – to add

Return type

None

property entries: Sequence[spsdk.image.mbi.mbi_mixin.MultipleImageEntry]

List of all entries.

Return type

Sequence[MultipleImageEntry]

export(start_addr)

Export.

Parameters

start_addr (int) – start address where the images are exported; the value matches source address for the first image

Return type

bytes

Returns

images with relocation table

Raises

SPSDKError – If there is no entry for export

property header_version: int

Format version of the structure for the header.

Return type

int

static parse(data)

Parse binary to get the Multiple application table.

Parameters

data (bytes) – Data bytes where the application is looked for

Raises

SPSDKParsingError – The application table parsing fails.

Return type

Optional[MultipleImageTable]

Returns

Multiple application table if detected.

reloc_table(start_addr)

Relocate table.

Parameters

start_addr (int) – start address of the relocation table

Return type

bytes

Returns

export relocation table in binary form

Image Exceptions

Module provides exceptions for PFR module.

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

Bases: spsdk.exceptions.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.AHABTags

Bases: spsdk.utils.easy_enum.Enum

AHAB container related tags.

BLOB = 129
CONTAINER_HEADER = 135
SIGNATURE_BLOCK = 144
CERTIFICATE_UUID = 160
CERTIFICATE_NON_UUID = 175
SRK_TABLE = 215
SIGNATURE = 216
SRK_RECORD = 225
class spsdk.image.ahab.ahab_container.AHABCoreId

Bases: spsdk.utils.easy_enum.Enum

AHAB cored IDs.

UNDEFINED = 0
CORTEX_M33 = 1
CORTEX_M4 = 2
CORTEX_M7 = 2
CORTEX_A55 = 2
CORTEX_M4_1 = 3
CORTEX_A53 = 4
CORTEX_A35 = 4
CORTEX_A72 = 5
SECO = 6
HDMI_TX = 7
HDMI_RX = 8
V2X_1 = 9
V2X_2 = 10
spsdk.image.ahab.ahab_container.get_key_by_val(dictionary, val)

Get Dictionary key by its value or default.

Parameters
  • dictionary (Dict) – Dictionary to search in.

  • val (Any) – Value to search

Raises

SPSDKValueError – In case that dictionary doesn’t contains the value.

Return type

Any

Returns

Key.

class spsdk.image.ahab.ahab_container.ImageArrayEntry(parent, image=None, image_offset=0, load_address=0, entry_point=0, flags=0, image_meta_data=0, image_hash=None, image_iv=None, already_encrypted_image=False)

Bases: spsdk.image.ahab.ahab_abstract_interfaces.Container

Class representing image array entry as part of image array in the AHAB container.

Image Array Entry content:

+-----+---------------------------------------------------------------+
|Off  |    Byte 3    |    Byte 2    |      Byte 1    |     Byte 0     |
+-----+---------------------------------------------------------------+
|0x00 |                        Image Offset                           |
+-----+---------------------------------------------------------------+
|0x04 |                        Image Size                             |
+-----+---------------------------------------------------------------+
|0x08 |                                                               |
|-----+                        Load Address (64 bits)                 |
|0x0C |                                                               |
+-----+---------------------------------------------------------------+
|0x10 |                                                               |
|-----+                        Entry Point (64 bits)                  |
|0x14 |                                                               |
+-----+---------------------------------------------------------------+
|0x18 |                        Flags                                  |
+-----+---------------------------------------------------------------+
|0x1C |                        Image meta data                        |
+-----+---------------------------------------------------------------+
|0x20 |                                                               |
|-----+                        Hash (512 bits)                        |
|.... |                                                               |
+-----+---------------------------------------------------------------+
|0x60 |                        IV (256 bits)                          |
+-----+---------------------------------------------------------------+

Class object initializer.

Parameters
  • parent (AHABContainer) – Parent AHAB Container object.

  • image (Optional[bytes]) – Image in bytes.

  • image_offset (int) – Offset in bytes from start of container to beginning of image.

  • load_address (int) – Address the image is written to in memory (absolute address in system memory map).

  • entry_point (int) – Entry point of image (absolute address). Only valid for executable image types. For other image types the value is irrelevant.

  • flags (int) – flags.

  • image_meta_data (int) – image meta-data.

  • image_hash (Optional[bytes]) – SHA of image (512 bits) in big endian. Left aligned and padded with zeroes for hash sizes below 512 bits.

  • image_iv (Optional[bytes]) – SHA256 of plain text image (256 bits) in big endian.

  • already_encrypted_image (bool) – The input image is already encrypted. Used only for encrypted images.

IMAGE_OFFSET_LEN = 4
IMAGE_SIZE_LEN = 4
LOAD_ADDRESS_LEN = 8
ENTRY_POINT_ADDRESS_LEN = 8
FLAGS_LEN = 4
IMAGE_META_DATA_LEN = 4
HASH_LEN = 64
IV_LEN = 32
FLAGS_TYPE_OFFSET = 0
FLAGS_TYPE_SIZE = 4
FLAGS_TYPES = {'data': 4, 'data_fast_boot_image': 11, 'dcd_image': 5, 'executable': 3, 'executable_fast_boot_image': 10, 'provisioning_data': 9, 'provisioning_image': 7, 'seco': 6}
FLAGS_CORE_ID_OFFSET = 4
FLAGS_CORE_ID_SIZE = 4
FLAGS_HASH_OFFSET = 8
FLAGS_HASH_SIZE = 3
FLAGS_IS_ENCRYPTED_OFFSET = 11
FLAGS_IS_ENCRYPTED_SIZE = 1
FLAGS_BOOT_FLAGS_OFFSET = 16
FLAGS_BOOT_FLAGS_SIZE = 15
METADATA_START_CPU_ID_OFFSET = 0
METADATA_START_CPU_ID_SIZE = 10
METADATA_MU_CPU_ID_OFFSET = 10
METADATA_MU_CPU_ID_SIZE = 10
METADATA_START_PARTITION_ID_OFFSET = 20
METADATA_START_PARTITION_ID_SIZE = 8
IMAGE_ALIGNMENTS = {'nand_2k': 2048, 'nand_4k': 4096, 'nor': 1024, 'serial_downloader': 512}
property image_offset: int

Image offset.

Return type

int

property image_offset_real: int

Real offset in Bootable image.

Return type

int

property image: bytes

Image data for this Image array entry.

The class decide by flags if encrypted of plain data has been returned.

Raises

SPSDKError – Invalid Image - Image is not encrypted yet.

Return type

bytes

Returns

Image bytes.

classmethod format()

Format of binary representation.

Return type

str

update_fields()

Updates the image fields in container based on provided image.

Return type

None

static create_meta(start_cpu_id=0, mu_cpu_id=0, start_partition_id=0)

Create meta data field.

Parameters
  • start_cpu_id (int) – ID of CPU to start, defaults to 0

  • mu_cpu_id (int) – ID of MU for selected CPU to start, defaults to 0

  • start_partition_id (int) – ID of partition to start, defaults to 0

Return type

int

Returns

Image meta data field.

static create_flags(image_type='executable', core_id=1, hash_type=1, is_encrypted=False, boot_flags=0)

Create flags field.

Parameters
  • image_type (str) – Type of image, defaults to “executable”

  • core_id (AHABCoreId) – Core ID, defaults to “cortex-m33”

  • hash_type (EnumHashAlgorithm) – Hash type, defaults to sha256

  • is_encrypted (bool) – Is image encrypted, defaults to False

  • boot_flags (int) – Boot flags controlling the SCFW boot, defaults to 0

Return type

int

Returns

Image flags data field.

static get_hash_from_flags(flags)

Get Hash algorithm name from flags.

Parameters

flags (int) – Value of flags.

Return type

EnumHashAlgorithm

Returns

Hash name.

property flags_image_type: str

Get Image type name from flags.

Return type

str

Returns

Image type name

property flags_core_id: int

Get Core ID from flags.

Return type

int

Returns

Core ID

property flags_is_encrypted: bool

Get Is encrypted property from flags.

Return type

bool

Returns

True if is encrypted, false otherwise

property flags_boot_flags: int

Get boot flags property from flags.

Return type

int

Returns

Boot flags

property metadata_start_cpu_id: int

Get CPU ID property from Meta data.

Return type

int

Returns

Start CPU ID

property metadata_mu_cpu_id: int

Get Start CPU Memory Unit ID property from Meta data.

Return type

int

Returns

Start CPU MU ID

property metadata_start_partition_id: int

Get Start Partition ID property from Meta data.

Return type

int

Returns

Start Partition ID

export()

Serializes container object into bytes in little endian.

The hash and IV are kept in big endian form.

Return type

bytes

Returns

bytes representing container content.

validate()

Validate object data.

Raises

SPSDKValueError – Invalid any value of Image Array entry

Return type

None

classmethod parse(data, parent)

Parse input binary chunk to the container object.

Parameters
  • parent (AHABContainer) – Parent AHABContainer object.

  • data (bytes) – Binary data with Image Array Entry block to parse.

Raises
  • SPSDKLengthError – If invalid length of image is detected.

  • SPSDKValueError – Invalid hash for image.

Return type

Self

Returns

Object recreated from the binary data.

static load_from_config(parent, config)

Converts the configuration option into an AHAB image array entry object.

“config” content of container configurations.

Parameters
  • parent (AHABContainer) – Parent AHABContainer object.

  • config (Dict[str, Any]) – Configuration of ImageArray.

Return type

ImageArrayEntry

Returns

Container Header Image Array Entry object.

create_config(index, image_index, data_path)

Create configuration of the AHAB Image data blob.

Parameters
  • index (int) – Container index.

  • image_index (int) – Data Image index.

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

Return type

Dict[str, Any]

Returns

Configuration dictionary.

get_valid_alignment()

Get valid alignment for AHAB container and memory target.

Return type

int

Returns

AHAB valid alignment

get_valid_offset(original_offset)

Get valid offset for AHAB container.

Parameters

original_offset (int) – Offset that should be updated to valid one

Return type

int

Returns

AHAB valid offset

class spsdk.image.ahab.ahab_container.SRKRecord(src_key=None, signing_algorithm='rsa', hash_type=1, key_size=0, srk_flags=0, crypto_param1=b'', crypto_param2=b'')

Bases: spsdk.image.ahab.ahab_abstract_interfaces.HeaderContainerInversed

Class representing SRK (Super Root Key) record as part of SRK table in the AHAB container.

The class holds information about RSA/ECDSA signing algorithms.

SRK Record:

+-----+---------------------------------------------------------------+
|Off  |    Byte 3    |    Byte 2      |    Byte 1    |     Byte 0     |
+-----+---------------------------------------------------------------+
|0x00 |    Tag       |         Length of SRK         | Signing Algo   |
+-----+---------------------------------------------------------------+
|0x04 |    Hash Algo | Key Size/Curve |    Not Used  |   SRK Flags    |
+-----+---------------------------------------------------------------+
|0x08 | RSA modulus len / ECDSA X len | RSA exponent len / ECDSA Y len|
+-----+---------------------------------------------------------------+
|0x0C | RSA modulus (big endian) / ECDSA X (big endian)               |
+-----+---------------------------------------------------------------+
|...  | RSA exponent (big endian) / ECDSA Y (big endian)              |
+-----+---------------------------------------------------------------+

Class object initializer.

Parameters
  • src_key (Optional[PublicKey]) – Optional source public key used to create the SRKRecord

  • signing_algorithm (str) – signing algorithm type.

  • hash_type (EnumHashAlgorithm) – hash algorithm type.

  • key_size (int) – key (curve) size.

  • srk_flags (int) – flags.

  • crypto_param1 (bytes) – RSA modulus (big endian) or ECDSA X (big endian)

  • crypto_param2 (bytes) – RSA exponent (big endian) or ECDSA Y (big endian)

TAG = 225
VERSION = [33, 39, 40]
VERSION_ALGORITHMS = {'ecdsa': 39, 'rsa': 33, 'sm2': 40}
HASH_ALGORITHM = {1: 0, 2: 1, 3: 2, 5: 3}
ECC_KEY_TYPE = {EccCurve.SECP256R1: 1, EccCurve.SECP384R1: 2, EccCurve.SECP521R1: 3}
RSA_KEY_TYPE = {2048: 5, 4096: 7}
SM2_KEY_TYPE = 8
KEY_SIZES = {1: (32, 32), 2: (48, 48), 3: (66, 66), 5: (128, 128), 7: (256, 256), 8: (32, 32)}
FLAGS_CA_MASK = 128
classmethod format()

Format of binary representation.

Return type

str

update_fields()

Update all fields depended on input values.

Return type

None

export()

Export one SRK record, little big endian format.

The crypto parameters (X/Y for ECDSA or modulus/exponent) are kept in big endian form.

Return type

bytes

Returns

bytes representing container content.

validate()

Validate object data.

Raises

SPSDKValueError – Invalid any value of Image Array entry

Return type

None

static create_from_key(public_key, srk_flags=0)

Create instance from key data.

Parameters
  • public_key (PublicKey) – Loaded public key.

  • srk_flags (int) – SRK flags for key.

Raises

SPSDKValueError – Unsupported keys size is detected.

Return type

SRKRecord

classmethod parse(data)

Parse input binary chunk to the container object.

Parameters

data (bytes) – Binary data with SRK record block to parse.

Raises

SPSDKLengthError – Invalid length of SRK record data block.

Return type

Self

Returns

SRK record recreated from the binary data.

get_key_name()

Get text key name in SRK record.

Return type

str

Returns

Key name.

get_public_key(encoding=SPSDKEncoding.PEM)

Store the SRK public key as a file.

Parameters

encoding (SPSDKEncoding) – Public key encoding style, default is PEM.

Raises

SPSDKError – Unsupported public key

Return type

bytes

class spsdk.image.ahab.ahab_container.SRKTable(srk_records=None)

Bases: spsdk.image.ahab.ahab_abstract_interfaces.HeaderContainerInversed

Class representing SRK (Super Root Key) table in the AHAB container as part of signature block.

SRK Table:

+-----+---------------------------------------------------------------+
|Off  |    Byte 3    |    Byte 2      |    Byte 1    |     Byte 0     |
+-----+---------------------------------------------------------------+
|0x00 |    Tag       |         Length of SRK Table   |     Version    |
+-----+---------------------------------------------------------------+
|0x04 |    SRK Record 1                                               |
+-----+---------------------------------------------------------------+
|...  |    SRK Record 2                                               |
+-----+---------------------------------------------------------------+
|...  |    SRK Record 3                                               |
+-----+---------------------------------------------------------------+
|...  |    SRK Record 4                                               |
+-----+---------------------------------------------------------------+

Class object initializer.

Parameters

srk_records (Optional[List[SRKRecord]]) – list of SRKRecord objects.

TAG = 215
VERSION = 66
SRK_RECORDS_CNT = 4
clear()

Clear the SRK Table Object.

Return type

None

add_record(public_key, srk_flags=0)

Add SRK table record.

Parameters
  • public_key (PublicKey) – Loaded public key.

  • srk_flags (int) – SRK flags for key.

Return type

None

update_fields()

Update all fields depended on input values.

Return type

None

compute_srk_hash()

Computes a SHA256 out of all SRK records.

Return type

bytes

Returns

SHA256 computed over SRK records.

get_source_keys()

Return list of source public keys.

Either from the src_key field or recreate them. :rtype: List[PublicKey] :return: List of public keys.

export()

Serializes container object into bytes in little endian.

Return type

bytes

Returns

bytes representing container content.

validate(data)

Validate object data.

Parameters

data (Dict[str, Any]) – Additional validation data.

Raises

SPSDKValueError – Invalid any value of Image Array entry

Return type

None

classmethod parse(data)

Parse input binary chunk to the container object.

Parameters

data (bytes) – Binary data with SRK table block to parse.

Raises

SPSDKLengthError – Invalid length of SRK table data block.

Return type

Self

Returns

Object recreated from the binary data.

create_config(index, data_path)

Create configuration of the AHAB Image SRK Table.

Parameters
  • index (int) – Container Index.

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

Return type

Dict[str, Any]

Returns

Configuration dictionary.

static load_from_config(config, search_paths=None)

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.

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

Return type

SRKTable

Returns

SRK Table object.

class spsdk.image.ahab.ahab_container.ContainerSignature(signature_data=None, signature_provider=None)

Bases: spsdk.image.ahab.ahab_abstract_interfaces.HeaderContainer

Class representing the signature in AHAB container as part of the signature block.

Signature:

+-----+--------------+--------------+----------------+----------------+
|Off  |    Byte 3    |    Byte 2    |      Byte 1    |     Byte 0     |
+-----+--------------+--------------+----------------+----------------+
|0x00 |    Tag       | Length (MSB) | Length (LSB)   |     Version    |
+-----+--------------+--------------+----------------+----------------+
|0x04 |                        Reserved                               |
+-----+---------------------------------------------------------------+
|0x08 |                      Signature Data                           |
+-----+---------------------------------------------------------------+

Class object initializer.

Parameters
  • signature_data (Optional[bytes]) – signature.

  • signature_provider (Optional[SignatureProvider]) – Signature provider use to sign the image.

TAG = 216
VERSION = 0
property signature_data: bytes

Get the signature data.

Return type

bytes

Returns

signature data.

classmethod format()

Format of binary representation.

Return type

str

sign(data_to_sign)

Sign the data_to_sign and store signature into class.

Parameters

data_to_sign (bytes) – Data to be signed by store private key

Raises

SPSDKError – Missing private key or raw signature data.

Return type

None

export()

Export signature data that is part of Signature Block.

Return type

bytes

Returns

bytes representing container signature content.

validate()

Validate object data.

Raises

SPSDKValueError – Invalid any value of Image Array entry

Return type

None

classmethod parse(data)

Parse input binary chunk to the container object.

Parameters

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

Return type

Self

Returns

Object recreated from the binary data.

static load_from_config(config, search_paths=None)

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.

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

Return type

ContainerSignature

Returns

Container signature object.

class spsdk.image.ahab.ahab_container.Certificate(permissions=0, uuid=None, public_key=None, signature_provider=None)

Bases: spsdk.image.ahab.ahab_abstract_interfaces.HeaderContainer

Class representing certificate in the AHAB container as part of the signature block.

The Certificate comes in two forms - with and without UUID.

Certificate format 1:

+-----+--------------+--------------+----------------+----------------+
|Off  |    Byte 3    |    Byte 2    |      Byte 1    |     Byte 0     |
+-----+--------------+--------------+----------------+----------------+
|0x00 |    Tag       | Length (MSB) | Length (LSB)   |     Version    |
+-----+--------------+--------------+----------------+----------------+
|0x04 | Permissions  | Perm (invert)|      Signature offset           |
+-----+--------------+--------------+---------------------------------+
|0x08 |                        Public Key                             |
+-----+---------------------------------------------------------------+
|...  |                        Signature                              |
+-----+---------------------------------------------------------------+

Certificate format 2:

+-----+--------------+--------------+----------------+----------------+
|Off  |    Byte 3    |    Byte 2    |      Byte 1    |     Byte 0     |
+-----+--------------+--------------+----------------+----------------+
|0x00 |    Tag       | Length (MSB) | Length (LSB)   |     Version    |
+-----+--------------+--------------+----------------+----------------+
|0x04 | Permissions  | Perm (invert)|      Signature offset           |
+-----+--------------+--------------+---------------------------------+
|0x08 |                            UUID                               |
+-----+---------------------------------------------------------------+
|...  |                        Public Key                             |
+-----+---------------------------------------------------------------+
|...  |                        Signature                              |
+-----+---------------------------------------------------------------+

Class object initializer.

Parameters
  • permissions (int) – used to indicate what a certificate can be used for.

  • uuid (Optional[bytes]) – optional 128-bit unique identifier.

  • public_key (Optional[SRKRecord]) – public Key. SRK record entry describing the key.

  • signature_provider (Optional[SignatureProvider]) – Signature provider for certificate. Signature is calculated over all data from beginning of the certificate up to, but not including the signature.

TAG = [160, 175]
UUID_LEN = 16
UUID_OFFSET = 8
VERSION = 0
PERM_NXP = {'hdcp_fuses': 32, 'hdmi_debug': 4, 'life_cycle': 16, 'secure_enclave_debug': 2}
PERM_OEM = {'container': 1, 'life_cycle': 16, 'monotonic_counter': 32, 'phbc_debug': 2, 'soc_debug_domain_1': 4, 'soc_debug_domain_2': 8}
PERM_SIZE = 8
classmethod format()

Format of binary representation.

Return type

str

static create_permissions(permissions)

Create integer representation of permission field.

Parameters

permissions (List[str]) – List of string permissions.

Return type

int

Returns

Integer representation of permissions.

property permission_to_sign_container: bool

Certificate has permission to sign container.

Return type

bool

create_config_permissions(srk_set)

Create list of string representation of permission field.

Parameters

srk_set (str) – SRK set to get proper string values.

Return type

List[str]

Returns

List of string representation of permissions.

get_signature_data()

Returns binary data to be signed.

The certificate block must be properly initialized, so the data are valid for signing. There is signed whole certificate block without signature part.

Raises

SPSDKValueError – if Signature Block or SRK Table is missing.

Return type

bytes

Returns

bytes representing data to be signed.

update_fields()

Update all fields depended on input values.

Return type

None

export()

Export container certificate object into bytes.

Return type

bytes

Returns

bytes representing container content.

validate()

Validate object data.

Raises

SPSDKValueError – Invalid any value of Image Array entry

Return type

None

classmethod parse(data)

Parse input binary chunk to the container object.

Parameters

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

Raises

SPSDKValueError – Certificate permissions are invalid.

Return type

Self

Returns

Object recreated from the binary data.

create_config(index, data_path, srk_set='oem')

Create configuration of the AHAB Image Certificate.

Parameters
  • index (int) – Container Index.

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

  • srk_set (str) – SRK set to know how to create certificate permissions.

Return type

Dict[str, Any]

Returns

Configuration dictionary.

static load_from_config(config, search_paths=None)

Converts the configuration option into an AHAB image signature block certificate object.

“config” content of container configurations.

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

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

Return type

Certificate

Returns

Certificate object.

static get_validation_schemas()

Get list of validation schemas.

Return type

List[Dict[str, Any]]

Returns

Validation list of schemas.

static generate_config_template()

Generate AHAB configuration template.

Return type

str

Returns

Certificate configuration templates.

class spsdk.image.ahab.ahab_container.Blob(flags=128, size=0, algorithm=3, mode=0, dek=None, dek_keyblob=None, key_identifier=0)

Bases: spsdk.image.ahab.ahab_abstract_interfaces.HeaderContainer

The Blob object used in Signature Container.

Blob (DEK) content:

+-----+--------------+--------------+----------------+----------------+
|Off  |    Byte 3    |    Byte 2    |      Byte 1    |     Byte 0     |
+-----+--------------+--------------+----------------+----------------+
|0x00 |    Tag       | Length (MSB) | Length (LSB)   |     Version    |
+-----+--------------+--------------+----------------+----------------+
|0x04 |    Mode      | Algorithm    |      Size      |     Flags      |
+-----+--------------+--------------+----------------+----------------+
|0x08 |                        Wrapped Key                            |
+-----+--------------+--------------+----------------+----------------+

Class object initializer.

Parameters
  • flags (int) – Keyblob flags

  • size (int) – key size [128,192,256]

  • dek (Optional[bytes]) – DEK key

  • mode (int) – DEK BLOB mode

  • algorithm (KeyBlobEncryptionAlgorithm) – Encryption algorithm

  • dek_keyblob (Optional[bytes]) – DEK keyblob

  • key_identifier (int) – Key identifier. Must be same as it was used for keyblob generation

TAG = 129
VERSION = 0
FLAGS = 128
SUPPORTED_KEY_SIZES = [128, 192, 256]
static compute_keyblob_size(key_size)

Compute Keyblob size.

Parameters

key_size (int) – Input AES key size in bits

Return type

int

Returns

Keyblob size in bytes.

classmethod format()

Format of binary representation.

Return type

str

export()

Export Signature Block Blob.

Return type

bytes

Returns

bytes representing Signature Block Blob.

validate()

Validate object data.

Raises

SPSDKValueError – Invalid any value of AHAB Blob

Return type

None

classmethod parse(data)

Parse input binary chunk to the container object.

Parameters

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

Return type

Self

Returns

Object recreated from the binary data.

create_config(index, data_path)

Create configuration of the AHAB Image Blob.

Parameters
  • index (int) – Container Index.

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

Return type

Dict[str, Any]

Returns

Configuration dictionary.

static load_from_config(config, search_paths=None)

Converts the configuration option into an AHAB image signature block blob object.

“config” content of container configurations.

Parameters
  • config (Dict[str, Any]) – Blob configuration

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

Raises

SPSDKValueError – Invalid configuration - Invalid DEK KeyBlob

Return type

Blob

Returns

Blob object.

encrypt_data(iv, data)

Encrypt data.

Parameters
  • iv (bytes) – Initial vector 128 bits length

  • data (bytes) – Data to encrypt

Raises

SPSDKError – Missing DEK, unsupported algorithm

Return type

bytes

Returns

Encrypted data

decrypt_data(iv, encrypted_data)

Encrypt data.

Parameters
  • iv (bytes) – Initial vector 128 bits length

  • encrypted_data (bytes) – Data to decrypt

Raises

SPSDKError – Missing DEK, unsupported algorithm

Return type

bytes

Returns

Plain data

class spsdk.image.ahab.ahab_container.SignatureBlock(srk_table=None, container_signature=None, certificate=None, blob=None)

Bases: spsdk.image.ahab.ahab_abstract_interfaces.HeaderContainer

Class representing signature block in the AHAB container.

Signature Block:

+---------------+----------------+----------------+----------------+-----+
|    Byte 3     |     Byte 2     |      Byte 1    |     Byte 0     | Fix |
|---------------+----------------+----------------+----------------+ len |
|      Tag      |              Length             |    Version     |     |
|---------------+---------------------------------+----------------+     |
|       SRK Table Offset         |         Certificate Offset      |     |
|--------------------------------+---------------------------------+     |
|          Blob Offset           |          Signature Offset       |     |
|--------------------------------+---------------------------------+     |
|              Key identifier in case that Blob is present         |     |
+------------------------------------------------------------------+-----+ Starting offset
|                             SRK Table                            |     |
+------------------------------------------------------------------+-----+ Padding length
|                          64 bit alignment                        |     |
+------------------------------------------------------------------+-----+ Starting offset
|                              Signature                           |     |
+------------------------------------------------------------------+-----+ Padding length
|                          64 bit alignment                        |     |
+------------------------------------------------------------------+-----+ Starting offset
|                              Certificate                         |     |
+------------------------------------------------------------------+-----+ Padding length
|                          64 bit alignment                        |     |
+------------------------------------------------------------------+-----+ Starting offset
|                              Blob                                |     |
+------------------------------------------------------------------+-----+

Class object initializer.

Parameters
  • srk_table (Optional[SRKTable]) – SRK table.

  • container_signature (Optional[ContainerSignature]) – container signature.

  • certificate (Optional[Certificate]) – container certificate.

  • blob (Optional[Blob]) – container blob.

TAG = 144
VERSION = 0
classmethod format()

Format of binary representation.

Return type

str

update_fields()

Update all fields depended on input values.

Return type

None

export()

Export Signature block.

Raises

SPSDKLengthError – if exported data length doesn’t match container length.

Return type

bytes

Returns

bytes signature block content.

validate(data)

Validate object data.

Parameters

data (Dict[str, Any]) – Additional validation data.

Raises

SPSDKValueError – Invalid any value of Image Array entry

Return type

None

classmethod parse(data)

Parse input binary chunk to the container object.

Parameters

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

Return type

Self

Returns

Object recreated from the binary data.

static load_from_config(config, search_paths=None)

Converts the configuration option into an AHAB Signature block object.

“config” content of container configurations.

Parameters
  • config (Dict[str, Any]) – array of AHAB signature block configuration dictionaries.

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

Return type

SignatureBlock

Returns

AHAB Signature block object.

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

Bases: spsdk.image.ahab.ahab_abstract_interfaces.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 (Optional[SignatureBlock]) – signature block.

TAG = 0
VERSION = 0
FLAGS_SRK_SET_OFFSET = 0
FLAGS_SRK_SET_SIZE = 2
FLAGS_SRK_SET_VAL = {'none': 0, 'nxp': 1, 'oem': 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: str

SRK set flag in string representation.

Return type

str

Returns

Name of SRK Set flag.

property flag_used_srk_id: int

Used SRK ID flag.

Return type

int

Returns

Index of Used SRK ID.

property flag_srk_revoke_mask: str

SRK Revoke mask flag.

Return type

str

Returns

SRK revoke mask in HEX.

property image_array_len: int

Get image array length if available.

Return type

int

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               |                |
|   +---+-----------+---------+--------+------------+----------------+
| 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 |                                           |
+---+---+-------------------------------------------+
Raises

SPSDKValueError – if Signature Block or SRK Table is missing.

Return type

bytes

Returns

bytes representing data to be signed.

validate(data)

Validate object data.

Parameters

data (Dict[str, Any]) – Additional validation data.

Raises

SPSDKValueError – Invalid any value of Image Array entry

Return type

None

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(parent, flags=0, fuse_version=0, sw_version=0, image_array=None, signature_block=None, container_offset=0)

Bases: spsdk.image.ahab.ahab_container.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.

Parent

Parent AHABImage object.

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 (Optional[List[ImageArrayEntry]]) – array of image entries, must be number of images long.

  • signature_block (Optional[SignatureBlock]) – signature block.

TAG = 135
search_paths: List[str]
property image_array_len: int

Get image array length if available.

Return type

int

Returns

Length of image array.

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.

validate(data)

Validate object data.

Parameters

data (Dict[str, Any]) – Additional validation data.

Raises

SPSDKValueError – Invalid any value of Image Array entry

Return type

None

classmethod parse(data, parent, container_id)

Parse input binary chunk to the container object.

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

  • parent (AHABImage) – AHABImage object.

  • container_id (int) – AHAB container ID.

Return type

Self

Returns

Object recreated from the binary data.

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.

static load_from_config(parent, config, container_ix)

Converts the configuration option into an AHAB image object.

“config” content of container configurations.

Parameters
  • parent (AHABImage) – AHABImage object.

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

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

Return type

AHABContainer

Returns

AHAB Container object.

image_info()

Get Image info object.

Return type

BinaryImage

Returns

AHAB Container Info object.

class spsdk.image.ahab.ahab_container.AHABImage(family, revision='latest', target_memory='nor', ahab_containers=None, search_paths=None)

Bases: object

Class representing an AHAB image.

The image consists of multiple AHAB containers.

AHAB Image constructor.

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

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

  • target_memory (str) – Target memory for AHAB image [serial_downloader, nor, nand], defaults to “nor”

  • ahab_containers (Optional[List[AHABContainer]]) – _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.

TARGET_MEMORIES = ['serial_downloader', 'nor', 'nand_4k', 'nand_2k']
add_container(container)

Add new container into AHAB Image.

The order of the added images is important. :type container: AHABContainer :param container: New AHAB Container to be added. :raises SPSDKLengthError: The container count in image is overflowed.

Return type

None

clear()

Clear list of containers.

Return type

None

update_fields(update_offsets=True)

Automatically updates all volatile fields in every AHAB container.

Parameters

update_offsets (bool) – Update also offsets for serial_downloader.

Return type

None

get_containers_size()

Get maximal containers size.

In fact get the offset where could be stored first data.

Return type

int

Returns

Size of containers.

get_first_data_image_address()

Get first data image address.

Return type

int

Returns

Address of first data image.

export()

Export AHAB Image.

Raises
  • SPSDKValueError – mismatch between number of containers and offsets.

  • SPSDKValueError – number of images mismatch.

Return type

bytes

Returns

bytes AHAB Image.

image_info()

Get Image info object.

Return type

BinaryImage

validate()

Validate object data.

Raises
  • SPSDKValueError – Invalid any value of Image Array entry.

  • SPSDKError – In case of Binary Image validation fail.

Return type

None

static load_from_config(config, search_paths=None)

Converts the configuration option into an AHAB image object.

“config” content array of containers configurations.

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

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

Raises
  • SPSDKValueError – if the count of AHAB containers is invalid.

  • SPSDKParsingError – Cannot parse input binary AHAB container.

Return type

AHABImage

Returns

Initialized AHAB Image.

parse(binary)

Parse input binary chunk to the container object.

Raises

SPSDKError – No AHAB container found in binary data.

Return type

None

static get_supported_families()

Get all supported families for AHAB container.

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 generate_config_template(family)

Generate AHAB configuration template.

Parameters

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

Return type

Dict[str, Any]

Returns

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

create_config(data_path)

Create configuration of the AHAB Image.

Parameters

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

Return type

Dict[str, Any]

Returns

Configuration dictionary.

create_srk_hash_blhost_script(container_ix=0)

Create BLHOST script to load SRK hash into fuses.

Parameters

container_ix (int) – Container index.

Raises
  • SPSDKValueError – Invalid input value - Non existing container or unsupported type.

  • SPSDKError – Invalid SRK hash.

Return type

str

Returns

Script used by BLHOST to load SRK hash.

AHAB Container Interface

AHAB abstract classes.

class spsdk.image.ahab.ahab_abstract_interfaces.Container

Bases: spsdk.utils.abstract.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.HeaderContainer(tag, length, version)

Bases: spsdk.image.ahab.ahab_abstract_interfaces.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 = 0
VERSION = 0
classmethod format()

Format of binary representation.

Return type

str

validate_header()

Validates 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

None

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.

Raises
  • SPSDKLengthError – If containers length is larger than data length.

  • SPSDKParsingError – If containers header value doesn’t match.

Return type

None

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

Bases: spsdk.image.ahab.ahab_abstract_interfaces.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

Bootable image

This module contains Bootable image related code.

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

Bases: spsdk.utils.abstract.BaseClass

Bootable Image class.

Bootable Image constructor.

Parameters
  • family (str) – Chip family.

  • mem_type (str) – Used memory type.

  • revision (str) – Chip silicon revision.

Raises

SPSDKValueError – Invalid family.

DATABASE = <spsdk.utils.database.Database object>
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 (str) – Used memory type.

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

Return type

str

Returns

Validation schema.

classmethod get_memory_type_config(family, mem_type, revision='latest')

Return dictionary with configuration for specific memory type.

Raises

SPSDKKeyError – If memory type does not exist in database

Return type

Dict[str, Any]

Returns

Dictionary with configuration.

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, revision='latest')

Return list of supported memory types.

Return type

List[str]

Returns

List of supported families.

classmethod 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 (str) – 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.

image_info()

Create Binary image of bootable image.

Return type

BinaryImage

Returns

BinaryImage object of bootable image.

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[str]) – Used memory type.

  • revision (str) – Chip silicon revision.

Return type

Self

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

Bootable image segments

This module contains Bootable image related code.

class spsdk.image.bootable_image.segments.Segment(raw_block=None)

Bases: spsdk.utils.abstract.BaseClass

Base Bootable Image Segment class.

Segment initialization, at least raw data are stored.

Parameters

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

CFG_NAME: Optional[str] = None
IMAGE_PATTERNS = [<spsdk.utils.misc.BinaryPattern object>, <spsdk.utils.misc.BinaryPattern object>]
NAME = 'Base'
SIZE = -1
classmethod cfg_key()

Configuration key name.

Return type

str

create_config(path)

Create configuration including store the data to specified path.

Parameters

path (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

classmethod load_from_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

Self

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

Parse binary block into Segment object.

Parameters
  • binary (bytes) – binary image.

  • family (str) – Chip family.

  • mem_type (str) – Used memory type.

  • revision (str) – Optional Chip family revision.

Raises

SPSDKParsingError – If given binary block size is not equal to block size in header

Return type

Self

class spsdk.image.bootable_image.segments.SegmentAhab(raw_block=None, ahab=None)

Bases: spsdk.image.bootable_image.segments.Segment

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

Segment initialization, at least raw data are stored.

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

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

NAME = 'ahab_container'
create_config(path)

Create configuration including store the data to specified path.

Parameters

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

Return type

Union[str, int]

Returns

Value of segment to configuration file

classmethod load_from_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

Self

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

Parse binary block into Segment object.

Parameters
  • binary (bytes) – binary image.

  • family (str) – Chip family.

  • mem_type (str) – Used memory type.

  • revision (str) – Optional Chip family revision.

Return type

Self

class spsdk.image.bootable_image.segments.SegmentBeeHeader0(raw_block=None)

Bases: spsdk.image.bootable_image.segments.Segment

Bootable Image BEE encryption header 0 Segment class.

Segment initialization, at least raw data are stored.

Parameters

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

NAME = 'bee_header_0'
SIZE = 512
class spsdk.image.bootable_image.segments.SegmentBeeHeader1(raw_block=None)

Bases: spsdk.image.bootable_image.segments.Segment

Bootable Image BEE encryption header 1 Segment class.

Segment initialization, at least raw data are stored.

Parameters

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

NAME = 'bee_header_1'
SIZE = 512
class spsdk.image.bootable_image.segments.SegmentFcb(raw_block=None, fcb=None)

Bases: spsdk.image.bootable_image.segments.Segment

Bootable Image FCB Segment class.

Segment initialization, at least raw data are stored.

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

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

NAME = 'fcb'
SIZE = 512
create_config(path)

Create configuration including store the data to specified path.

Parameters

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

Return type

Union[str, int]

Returns

Value of segment to configuration file

classmethod load_from_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

Self

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

Parse binary block into Segment object.

Parameters
  • binary (bytes) – binary image.

  • family (str) – Chip family.

  • mem_type (str) – Used memory type.

  • revision (str) – Optional Chip family revision.

Raises

SPSDKParsingError – If given binary block size is not equal to block size in header

Return type

Self

class spsdk.image.bootable_image.segments.SegmentHab(raw_block=None, hab=None)

Bases: spsdk.image.bootable_image.segments.Segment

Bootable Image High Assurance Boot(HAB) Segment class.

Segment initialization, at least raw data are stored.

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

  • hab (Optional[HabContainer]) – High Assurance Boot class.

NAME = 'hab_container'
classmethod load_from_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

Self

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

Parse binary block into Segment object.

Parameters
  • binary (bytes) – binary image.

  • family (str) – Chip family.

  • mem_type (str) – Used memory type.

  • revision (str) – Optional Chip family revision.

Return type

Self

class spsdk.image.bootable_image.segments.SegmentImageVersion(raw_block=None)

Bases: spsdk.image.bootable_image.segments.Segment

Bootable Image Image version Segment class.

Segment initialization, at least raw data are stored.

Parameters

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

NAME = 'image_version'
SIZE = 4
create_config(path)

Create configuration including store the data to specified path.

Parameters

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

Return type

Union[str, int]

Returns

Value of segment to configuration file

classmethod load_from_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

Self

class spsdk.image.bootable_image.segments.SegmentImageVersionAntiPole(raw_block=None)

Bases: spsdk.image.bootable_image.segments.Segment

Bootable Image Image version with antipole value Segment class.

Segment initialization, at least raw data are stored.

Parameters

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

CFG_NAME: Optional[str] = 'image_version'
NAME = 'image_version_ap'
SIZE = 4
create_config(path)

Create configuration including store the data to specified path.

Parameters

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

Return type

Union[str, int]

Returns

Value of segment to configuration file

classmethod load_from_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

Self

class spsdk.image.bootable_image.segments.SegmentKeyBlob(raw_block=None)

Bases: spsdk.image.bootable_image.segments.Segment

Bootable Image KeyBlob Segment class.

Segment initialization, at least raw data are stored.

Parameters

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

NAME = 'keyblob'
SIZE = 256
class spsdk.image.bootable_image.segments.SegmentKeyStore(raw_block=None)

Bases: spsdk.image.bootable_image.segments.Segment

Bootable Image KeyStore Segment class.

Segment initialization, at least raw data are stored.

Parameters

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

NAME = 'keystore'
SIZE = 2048
class spsdk.image.bootable_image.segments.SegmentMbi(raw_block=None, mbi=None)

Bases: spsdk.image.bootable_image.segments.Segment

Bootable Image Master Boot Image(MBI) Segment class.

Segment initialization, at least raw data are stored.

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

  • mbi (Optional[MasterBootImage]) – Master boot image class.

NAME = 'mbi'
create_config(path)

Create configuration including store the data to specified path.

Parameters

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

Return type

Union[str, int]

Returns

Value of segment to configuration file

classmethod load_from_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

Self

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

Parse binary block into Segment object.

Parameters
  • binary (bytes) – binary image.

  • family (str) – Chip family.

  • mem_type (str) – Used memory type.

  • revision (str) – Optional Chip family revision.

Return type

Self

class spsdk.image.bootable_image.segments.SegmentXmcd(raw_block=None, xmcd=None)

Bases: spsdk.image.bootable_image.segments.Segment

Bootable Image XMCD Segment class.

Segment initialization, at least raw data are stored.

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

  • xmcd (Optional[XMCD]) – XMCD class.

NAME = 'xmcd'
SIZE = 512
create_config(path)

Create configuration including store the data to specified path.

Parameters

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

Return type

Union[str, int]

Returns

Value of segment to configuration file

classmethod load_from_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

Self

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

Parse binary block into Segment object.

Parameters
  • binary (bytes) – binary image.

  • family (str) – Chip family.

  • mem_type (str) – Used memory type.

  • revision (str) – Optional Chip family revision.

Raises

SPSDKParsingError – If given binary block size is not equal to block size in header

Return type

Self

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[str, 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: spsdk.image.segments_base.SegmentBase

FCB (Flash Configuration Block).

FCB Constructor.

Parameters
  • family (str) – Chip family.

  • mem_type (str) – Used memory type.

  • revision (str) – Optional Chip family revision.

Raises

SPSDKValueError – Unsupported family.

TAG = b'FCFB'
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 (str) – Used memory type.

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

Return type

str

Returns

Template of FCB Block.

static get_database()

Get the devices database.

Return type

Database

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

Create the validation schema.

Parameters
  • family (str) – Family description.

  • mem_type (str) – 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='Unknown', 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 (str) – Used memory type.

  • revision (str) – Optional Chip family revision.

Raises

SPSDKError – If given binary block contains wrong FCB tag

Return type

Self

property registers: spsdk.utils.registers.Registers

Registers of segment.

Return type

Registers

HAB - High Assurance Boot

This module contains HAB related code.

HAB CSF Builder

Builder of CST segments.

class spsdk.image.hab.csf_builder.CsfBuildDirector(builder)

Bases: object

CSF command build director.

CSF build director class constructor.

Parameters

builder (CsfBuilder) – CSF builder

build_csf()

Build individual CSF commands.

Return type

None

property builder: spsdk.image.hab.csf_builder.CsfBuilder

CSF builder property.

Return type

CsfBuilder

class spsdk.image.hab.csf_builder.CsfBuilder(bd_config, csf_offset, hab_image, search_paths=None, timestamp=None)

Bases: object

Csf command builder.

CSF builder class constructor.

Parameters
  • bd_config (ImageConfig) – Loaded image configuration

  • csf_offset (int) – CSF segment offset

  • hab_image (HabBinaryImage) – Hab binary image

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

  • timestamp (Optional[datetime]) – Signature timestamp

append_command(command)

Append command to list of commands and update header length.

Parameters

command (SecCommand) – Command to be appended

Return type

None

build_authenticate_csfk()

Build authenticate CSFK command.

Return type

None

build_authenticate_data()

Build authenticate data command.

Return type

None

build_csf_header()

Build CSF header command.

Return type

None

build_csf_install_csfk()

Build CSF install CSFK command.

Return type

None

build_csf_install_srk()

Build CSF install SRK command.

Return type

None

build_decrypt_data()

Build install Secret key command.

Return type

None

build_install_key_csfk()

Build install key CSFK command.

Return type

None

build_install_secret_key()

Build install Secret key command.

Raises

SPSDKError – Incorrect version is used

Return type

None

build_set_engine()

Build set engine command.

Return type

None

build_unlock_engine()

Build unlock engine command.

Return type

None

finish()

Finish command creation.

Return type

None

get_command(command_id, raise_exc=True)

Get command by command id.

Parameters
  • command_id (int) – Command ID to be retrieved

  • raise_exc (bool) – If set and section is not found, the error is raised

Raises

SPSDKKeyError – If command does not exist

Return type

Optional[SecCommand]

get_padding_hab_image()

Get HAB image with initial padding.

Return type

HabBinaryImage

property keyblob_address: int

Keyblob address property.

Return type

int

reset()

Reset builder into its initial state.

Return type

None

class spsdk.image.hab.csf_builder.ImageBlock(base_address, start, size)

Bases: object

Single image block.

base_address: int
size: int
start: int
class spsdk.image.hab.csf_builder.SecCommand

Bases: abc.ABC

Sec command abstract class.

Command abstract class constructor.

CMD_INDEX: int
CONFIGURATION_PARAMS: Dict[str, Any]
abstract build_command()

Build command with given properties.

Return type

None

classmethod check_config_section_params(section_data)

Check if options contains only accepted arguments.

Parameters

section_data (SectionConfig) – Section data to be checked

Raises
  • SPSDKError – If mandatory parameter is not present

  • SPSDKError – If unexpected key is present

Return type

None

property cmd: Union[spsdk.image.commands.CmdBase, spsdk.image.header.Header]

Command property.

Raises

SPSDKAttributeError – If command is not set

Return type

Union[CmdBase, Header]

static generate_random_bytes(length)

Generate random bytes.

Parameters

length (int) – Length of random bytes

Raises

SPSDKError – If length of bytes is not as expected

Return type

bytes

Returns

Generated random bytes

abstract static load_from_config(config, search_paths=None)

Load configuration into the command.

Parameters
  • config (SectionConfig) – Section config

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

Return type

SecCommand

Returns

Loaded command instance

class spsdk.image.hab.csf_builder.SecCsfAuthenticateCsf(private_key, key_pass=None)

Bases: spsdk.image.hab.csf_builder.SecCommand

Authenticate CSFK command.

Authenticate CSFK class constructor.

Parameters
  • version – Header version

  • certificate – Certificate

  • private_key (Optional[bytes]) – Private key used for authentication

  • data – Command data to be signed

  • key_pass (Optional[str]) – Key for decryption of private key

CMD_INDEX: int = 24
CONFIGURATION_PARAMS: Dict[str, Any] = {'AuthenticateCsf_KeyPass': False, 'AuthenticateCsf_PrivateKeyFile': False}
SIGNED_DATA_SIZE = 768
build_command()

Build command with given properties.

Return type

None

property certificate: spsdk.crypto.certificate.Certificate

Certificate.

Return type

Certificate

property engine: Optional[spsdk.image.commands.EnumEngine]

Engine.

Return type

Optional[EnumEngine]

static load_from_config(config, search_paths=None)

Load configuration into the command.

Parameters
  • config (SectionConfig) – Section config

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

Return type

SecCsfAuthenticateCsf

sign(data, timestamp)

Sign data and update command signature.

Parameters
  • data (bytes) – Data to be signed

  • timestamp (datetime) – Signature timestamp

Return type

None

property version: int

Image version.

Return type

int

class spsdk.image.hab.csf_builder.SecCsfAuthenticateData(engine, engine_config, verification_index, private_key, key_pass=None)

Bases: spsdk.image.hab.csf_builder.SecCommand

Authenticate data command.

Authenticate data class constructor.

Parameters
  • engine (EnumEngine) – Engine plugin tag

  • engine_config (int) – Engine configuration index

  • verification_index (int) – Target index

Raises
  • SPSDKValueError – Invalid combination of input parameters.

  • SPSDKValueError – Verification index is not defined.

  • SPSDKValueError – Key index is not a valid value.

CMD_INDEX: int = 26
CONFIGURATION_PARAMS: Dict[str, Any] = {'AuthenticateData_Engine': True, 'AuthenticateData_EngineConfiguration': True, 'AuthenticateData_KeyPass': False, 'AuthenticateData_PrivateKeyFile': False, 'AuthenticateData_VerificationIndex': True}
KEY_IDX_AUT_DAT_FAST_AUTH = 0
KEY_IDX_AUT_DAT_MAX = 5
KEY_IDX_AUT_DAT_MIN = 2
property blocks: List[spsdk.image.hab.csf_builder.ImageBlock]

Blocks to be signed property.

Return type

List[ImageBlock]

build_command()

Build command with given properties.

Return type

None

property certificate: spsdk.crypto.certificate.Certificate

Certificate.

Return type

Certificate

static load_from_config(config, search_paths=None)

Load configuration into the command.

Parameters
  • config (SectionConfig) – Section config

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

Return type

SecCsfAuthenticateData

sign(data, base_data_address, timestamp=None)

Sign data and update command signature.

Parameters
  • data (bytes) – Data to be signed

  • base_data_address (int) – Base address of the generated data

  • timestamp (Optional[datetime]) – Signature timestamp

Return type

None

property version: int

Image version.

Return type

int

class spsdk.image.hab.csf_builder.SecCsfHeader(version, engine, engine_config, hash_algorithm=None, certificate_format=None, signature_format=None)

Bases: spsdk.image.hab.csf_builder.SecCommand

CSF header command.

CSF header class constructor.

Parameters
  • version (Union[int, str]) – Header version

  • engine (EnumEngine) – Engine plugin tag

  • engine_config (int) – Engine configuration index

  • hash_algorithm (Optional[EnumAlgorithm]) – Hash algorithm type

  • certificate_format (Optional[EnumCertFormat]) – Certificate format tag

  • signature_format (Optional[str]) – Signature format

Raises
  • SPSDKValueError – Invalid combination of input parameters.

  • SPSDKValueError – Invalid signature format.

CMD_INDEX: int = 20
CONFIGURATION_PARAMS: Dict[str, Any] = {'Header_CertificateFormat': False, 'Header_Engine': True, 'Header_EngineConfiguration': True, 'Header_HashAlgorithm': False, 'Header_SignatureFormat': True, 'Header_Version': True}
build_command()

Build command with given properties.

Return type

None

static load_from_config(config, search_paths=None)

Load configuration into the command.

Parameters
  • config (SectionConfig) – Section config

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

Return type

SecCsfHeader

class spsdk.image.hab.csf_builder.SecCsfInstallCsfk(csfk_file_path, certificate_format=None)

Bases: spsdk.image.hab.csf_builder.SecCommand

Install CSFK command.

Install CSF class constructor.

Parameters
  • csfk_file_path (str) – Path to CSFK file

  • version – Header version

  • certificate_format (Optional[EnumCertFormat]) – Certificate format

Raises

SPSDKValueError – Invalid combination of input parameters.

CMD_INDEX: int = 22
CONFIGURATION_PARAMS: Dict[str, Any] = {'InstallCSFK_CertificateFormat': False, 'InstallCSFK_File': True}
build_command()

Build command with given properties.

Return type

None

static load_from_config(config, search_paths=None)

Load configuration into the command.

Parameters
  • config (SectionConfig) – Section config

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

Return type

SecCsfInstallCsfk

property version: int

Image version.

Return type

int

class spsdk.image.hab.csf_builder.SecCsfInstallKey(certificate_path, source_index, target_index)

Bases: spsdk.image.hab.csf_builder.SecCommand

Install key command.

Install key class constructor.

Parameters
  • certificate_path (str) – Path to certificate

  • version – Header version

  • source_index (int) – Source index

  • target_index (int) – Target index

CMD_INDEX: int = 25
CONFIGURATION_PARAMS: Dict[str, Any] = {'InstallKey_File': True, 'InstallKey_TargetIndex': True, 'InstallKey_VerificationIndex': True}
build_command()

Build command with given properties.

Return type

None

static load_from_config(config, search_paths=None)

Load configuration into the command.

Parameters
  • config (SectionConfig) – Section config

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

Return type

SecCsfInstallKey

property version: int

Image version.

Return type

int

class spsdk.image.hab.csf_builder.SecCsfInstallSrk(srk_table, source_index)

Bases: spsdk.image.hab.csf_builder.SecCommand

Install SRK command.

Install SRK class constructor.

Parameters
  • srk_table (bytes) – SRK table

  • source_index (int) – Source index

Raises
  • SPSDKError – Srk table is not defined .

  • SPSDKError – Source index is not defined .

CMD_INDEX: int = 21
CONFIGURATION_PARAMS: Dict[str, Any] = {'InstallSRK_SourceIndex': True, 'InstallSRK_Table': True}
build_command()

Build command with given properties.

Return type

None

static load_from_config(config, search_paths=None)

Load configuration into the command.

Parameters
  • config (SectionConfig) – Section config

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

Return type

SecCsfInstallSrk

class spsdk.image.hab.csf_builder.SecDecryptData(verification_index, mac_len, nonce=None, engine=None, engine_config=None)

Bases: spsdk.image.hab.csf_builder.SecCommand

Set engine command.

Decrypt data class constructor.

Parameters
  • verification_index (int) – Target index

  • mac_len (Optional[int]) – Number of mac bytes

  • nonce (Optional[bytes]) – Nonce binary

  • engine (Optional[EnumEngine]) – Engine plugin tag

  • engine_config (Optional[int]) – Engine configuration index

Raises

SPSDKValueError – Invalid combination of input parameters.

CMD_INDEX: int = 28
CONFIGURATION_PARAMS: Dict[str, Any] = {'Decrypt_Engine': False, 'Decrypt_EngineConfiguration': False, 'Decrypt_MacBytes': False, 'Decrypt_Nonce': False, 'Decrypt_VerifyIndex': True}
property blocks: Optional[List[spsdk.image.hab.csf_builder.ImageBlock]]

Blocks to be encrypted property.

Return type

Optional[List[ImageBlock]]

build_command()

Build command with given properties.

Return type

None

property dek: bytes

Data encryption key.

Return type

bytes

encrypt(data)

Encrypt data and return mac and encrypted data.

Raises

SPSDKError – Invalid length of encrypted data.

Return type

Tuple[bytes, bytes]

static load_from_config(config, search_paths=None)

Load configuration into the command.

Parameters
  • config (SectionConfig) – Section config

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

Return type

SecDecryptData

class spsdk.image.hab.csf_builder.SecInstallSecretKey(secret_key, source_index, target_index)

Bases: spsdk.image.hab.csf_builder.SecCommand

Set engine command.

Set install secret key class constructor.

Parameters
  • hash_algorithm – Hash algorithm type

  • engine – Engine plugin tag

  • engine_config – Engine configuration index

Raises
  • SPSDKValueError – Source index not specified.

  • SPSDKValueError – Source index is not lower or equal to 3.

  • SPSDKValueError – Target index not specified.

CMD_INDEX: int = 27
CONFIGURATION_PARAMS: Dict[str, Any] = {'SecretKey_Length': False, 'SecretKey_Name': True, 'SecretKey_ReuseDek': False, 'SecretKey_TargetIndex': True, 'SecretKey_VerifyIndex': False}
build_command()

Build command with given properties.

Return type

None

static load_from_config(config, search_paths=None)

Load configuration into the command.

Parameters
  • config (SectionConfig) – Section config

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

Return type

SecInstallSecretKey

property location: int

Start address of DEK key.

Return type

int

static save_secret_key(secret_key_path, secret_key)

Save given sectret key into file.

Parameters
  • secret_key_path (str) – Path to file with secret key

  • secret_key (bytes) – Secret key to be saved

Return type

None

class spsdk.image.hab.csf_builder.SecSetEngine(hash_algorithm=None, engine=None, engine_cfg=None)

Bases: spsdk.image.hab.csf_builder.SecCommand

Set engine command.

Set engine class constructor.

Parameters
  • hash_algorithm (Optional[EnumAlgorithm]) – Hash algorithm type

  • engine (Optional[EnumEngine]) – Engine plugin tag

  • engine_config – Engine configuration index

CMD_INDEX: int = 31
CONFIGURATION_PARAMS: Dict[str, Any] = {'SetEngine_Engine': False, 'SetEngine_EngineConfiguration': False, 'SetEngine_HashAlgorithm': False}
build_command()

Build command with given properties.

Return type

None

static load_from_config(config, search_paths=None)

Load configuration into the command.

Parameters
  • config (SectionConfig) – Section config

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

Return type

SecSetEngine

class spsdk.image.hab.csf_builder.SecUnlock(unlock_engine, features)

Bases: spsdk.image.hab.csf_builder.SecCommand

Unlock engine command.

Unlock class constructor.

Parameters
  • unlock_engine (str) – Unlock engine type: can be aither SNVS or CAAM

  • features (Optional[int]) – Features

Raises

SPSDKKeyError – Unknown engine.

CMD_INDEX: int = 33
CONFIGURATION_PARAMS: Dict[str, Any] = {'Unlock_Engine': True, 'Unlock_Features': False}
ENGINE_CLASSES = {'CAAM': <class 'spsdk.image.commands.CmdUnlockCAAM'>, 'SNVS': <class 'spsdk.image.commands.CmdUnlockSNVS'>}
UNLOCK_FEARTURES = {'LP SWR': 1, 'ZMK WRITE': 2}
build_command()

Build command with given properties.

Return type

None

static load_from_config(config, search_paths=None)

Load configuration into the command.

Parameters
  • config (SectionConfig) – Section config

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

Raises

SPSDKKeyError – Unknown features.

Return type

SecCommand

HAB Config Parser

Parser of BD configuration.

class spsdk.image.hab.config_parser.CaseInsensitiveDict(dict=None, /, **kwargs)

Bases: collections.UserDict

Case insensitive dictionary.

class spsdk.image.hab.config_parser.ConfigOptions(flags, start_address, ivt_offset, initial_load_size, entrypoint_address, signature_timestamp=None, dcd_file_path=None, xmcd_file_path=None)

Bases: object

Dataclass holding configuration options.

dcd_file_path: Optional[str] = None
entrypoint_address: int
flags: int
initial_load_size: int
ivt_offset: int
static parse(options)

Parse config options from dictionary.

Parameters

options (Dict[str, Any]) – Options to be parsed

Raises

SPSDKKeyError – If unexpected key is present

Return type

ConfigOptions

signature_timestamp: Optional[datetime.datetime] = None
start_address: int
xmcd_file_path: Optional[str] = None
class spsdk.image.hab.config_parser.ImageConfig(elf_file, options, sections)

Bases: object

Represent parsed image configuration including options and sections.

elf_file: str
get_section(section_index)

Get config section by section id.

Parameters

section_index (int) – Section with index to be retrieved

Return type

Optional[SectionConfig]

options: spsdk.image.hab.config_parser.ConfigOptions
static parse(data)

Parse config from dictionary.

Parameters

data (Dict[str, Any]) – Configuration data to be parsed.

Return type

ImageConfig

sections: List[spsdk.image.hab.config_parser.SectionConfig]
class spsdk.image.hab.config_parser.SectionConfig(index, options)

Bases: object

Dataclass holding single section data.

index: int
options: spsdk.image.hab.config_parser.CaseInsensitiveDict
static parse(section)

Parse config section from dictionary.

Parameters

section (Dict[str, Any]) – Section to be parsed

Return type

SectionConfig

HAB Binary Image

HAB Binary Image extension.

class spsdk.image.hab.hab_binary_image.HabBinaryImage

Bases: spsdk.utils.images.BinaryImage

HAB binary image.

HAB Binary Image Constructor.

BDT_OFFSET = 32
CSF_SIZE = 8192
DCD_OFFSET = 64
IVT_OFFSET = 0
KEYBLOB_SIZE = 512
XMCD_OFFSET = 64
add_hab_segment(segment_name, binary, offset_override=None)

Create binary image and add it into parent image.

Parameters
  • segment_name (HabSegment) – Segment to be added

  • binary (bytes) – Segment binary

  • offset_override (Optional[int]) – Segment offset in the parent image

Return type

BinaryImage

Returns

Created bootable image

align_segment(segment_name, alignment=16)

Align HAB segment.

Parameters
  • segment_name (HabSegment) – Segment to be aligned

  • alignment (int) – Alignement length

Return type

None

get_hab_segment(segment_name)

Get HAB segment.

Parameters

segment_name (HabSegment) – Segment to be added

Raises

SPSDKKeyError – If HAB segment not found.

Return type

BinaryImage

Returns

Segment as binary image

class spsdk.image.hab.hab_binary_image.HabSegment(value)

Bases: str, enum.Enum

Enum definition for HAB segments.

APP = 'app'
BDT = 'bdt'
CSF = 'csf'
DCD = 'dcd'
IVT = 'ivt'
XMCD = 'xmcd'

HAB Container

This module contains HAB related code.

class spsdk.image.hab.hab_container.HabContainer(hab_image)

Bases: object

Hab container.

HAB Constructor.

Parameters

binary_image – Binary image with required segments.

IVT_VERSION = 64
property app_segment: Optional[bytes]

APP segment binary.

Return type

Optional[bytes]

property bdt_segment: Optional[bytes]

BDT segment binary.

Return type

Optional[bytes]

property csf_segment: Optional[bytes]

APP segment binary.

Return type

Optional[bytes]

property dcd_segment: Optional[bytes]

DCD segment binary.

Return type

Optional[bytes]

export(pattern=None)

Export into binary.

Return type

bytes

classmethod generate_config_template()

Generate configuration template.

Return type

str

Returns

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

classmethod get_validation_schemas()

Create the list of validation schemas.

Return type

List[Dict[str, Any]]

Returns

List of validation schemas.

property ivt_segment: Optional[bytes]

IVT segment binary.

Return type

Optional[bytes]

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

property xmcd_segment: Optional[bytes]

XMCD segment binary.

Return type

Optional[bytes]

XMCD

This module contains XMCD (External Memory Configuration Data) related code.