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

info()

String representation of the IMX Boot Image v2.

Return type

str

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

info()

String representation of the i.MX Boot Image v3a.

Return type

str

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

info()

String representation of the IMX Boot Image v3b.

Return type

str

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

info()

String representation of the i.MX Boot Image v4.

Return type

str

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

info()

String representation of the IMX Boot Image.

Return type

str

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

info()

Text info about the instance.

Raises

NotImplementedError – Derived class has to implement this method

Return type

str

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, 4096)
IVT_OFFSET_NOR_FLASH = 4096
IVT_OFFSET_OTHER = 1024
NON_XIP_APP_OFFSET = 4096
VERSIONS = (64, 65, 66, 67)
XIP_APP_OFFSET = 8192
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 (bytes) – CSF private key; decrypted binary data in PEM format

  • img_cert (bytes) – IMG certificate

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

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 (bytes) – CSF private key; decrypted binary data in PEM format

  • img_cert (bytes) – IMG certificate

  • img_priv_key (bytes) – 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(2022, 9, 16, 14, 46, 22, 69861, tzinfo=datetime.timezone.utc), dbg_info=<spsdk.utils.misc.DebugInfo object>)

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

  • dbg_info (DebugInfo) – optional instance to provide info about exported data

Raises
  • SPSDKError – If the image is not encrypted

  • SPSDKError – If padding is present

  • SPSDKError – If invalid alignment of application

Return type

bytes

Returns

bytes

property fcb: spsdk.image.segments.AbstractFCB

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

Return type

AbstractFCB

property hab_encrypted: bool

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

Return type

bool

info()

Text info about the instance.

Return type

str

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

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

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

info()

String representation of the IMX Kernel Image.

Return type

None

classmethod parse(data)

Parse.

Return type

None

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_pem_data=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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export to binary form (serialization).

Parameters

dbg_info (DebugInfo) – debug information about exported data

Return type

bytes

Returns

binary representation of the command

property flags: int

Flag of Authenticate data command.

Return type

int

info()

Text description of the command.

Return type

str

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

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

Parameters
  • data (bytes) – being parsed

  • offset (int) – current position to read from data

Return type

CmdAuthData

Returns

parse command

parse_cmd_data(data, offset)

Parse additional command data from binary data.

Parameters
  • data (bytes) – to be parsed

  • offset (int) – start position in data to parse

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: object

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.BaseClass]

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

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

Return type

Optional[BaseClass]

export(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export to binary form (serialization).

Parameters

dbg_info (DebugInfo) – debug information about exported data

Return type

bytes

Returns

binary representation of the command

info()

Text representation of the command.

Return type

str

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

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

Parameters
  • data (bytes) – being parsed

  • offset (int) – current position to readd from data

Return type

CmdBase

Returns

parse command

Raises

NotImplementedError – Derived class has to implement this method

parse_cmd_data(data, offset)

Parse additional command data from binary data.

Parameters
  • data (bytes) – to be parsed

  • offset (int) – start position in data to parse

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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export to binary form (serialization).

Parameters

dbg_info (DebugInfo) – debug information about exported data

Return type

bytes

Returns

binary representation of the command

info()

Text description of the command.

Return type

str

property num_bytes: int

Number of bytes.

Return type

int

property ops: int

Operation of Check data command.

Return type

int

classmethod parse(data, offset=0)

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

Parameters
  • data (bytes) – being parsed

  • offset (int) – current position to readd from data

Return type

CmdCheckData

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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export to binary form (serialization).

Parameters

dbg_info (DebugInfo) – debug information about exported data

Return type

bytes

Returns

binary representation of the command

info()

Text description of the command.

Return type

str

classmethod parse(data, offset=0)

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

Parameters
  • data (bytes) – being parsed

  • offset (int) – current position to readd from data

Return type

CmdInitialize

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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export to binary form (serialization).

Parameters

dbg_info (DebugInfo) – debug information about exported data

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

info()

Text description of the command.

Return type

str

property needs_cmd_data_reference: bool

Whether the command contains a reference to an additional data.

Return type

bool

classmethod parse(data, offset=0)

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

Parameters
  • data (bytes) – being parsed

  • offset (int) – current position to read from data

Return type

CmdBase

Returns

parse command

parse_cmd_data(data, offset)

Parse additional command data from binary data.

Parameters
  • data (bytes) – to be parsed

  • offset (int) – start position in data to parse

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.

info()

Text description of the command.

Return type

str

classmethod parse(data, offset=0)

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

Parameters
  • data (bytes) – being parsed

  • offset (int) – current position to readd from data

Return type

CmdNop

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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export to binary form (serialization).

Parameters

dbg_info (DebugInfo) – debug information about exported data

Return type

bytes

Returns

binary representation of the command

property hash_algorithm: spsdk.image.secret.EnumAlgorithm

Type of hash algorithm.

Return type

EnumAlgorithm

info()

Text description of the command.

Return type

str

property itm: int

Item of Set command.

Return type

int

classmethod parse(data, offset=0)

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

Parameters
  • data (bytes) – being parsed

  • offset (int) – current position to readd from data

Return type

CmdSet

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)

info()

Text description of the command.

Return type

str

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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export to binary form (serialization).

Parameters

dbg_info (DebugInfo) – debug information about exported data

Return type

bytes

Returns

binary representation of the command

info()

Text description of the command.

Return type

str

static need_uid(engine, features)

Return True if given Engine and Feature requires UID.

Return type

bool

classmethod parse(data, offset=0)

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

Parameters
  • data (bytes) – being parsed

  • offset (int) – current position to readd from data

Return type

CmdUnlockAbstract

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
info()

Text description of the command.

Return type

str

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
info()

Text description of the command.

Return type

str

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
info()

Text description of the command.

Return type

str

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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export to binary form (serialization).

Parameters

dbg_info (DebugInfo) – debug information about exported data

Return type

bytes

Returns

binary representation of the command

info()

Text description of the command.

Return type

str

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

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

Parameters
  • data (bytes) – being parsed

  • offset (int) – current position to readd from data

Return type

CmdWriteData

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

Parse CSF/DCD command.

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

  • offset (int) – to start parsing

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

Create Header from binary data.

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

  • offset (int) – to start reading binary data

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

Return type

Header

Returns

parsed instance

Raises
  • UnparsedException – 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
exception spsdk.image.header.CorruptedException

Bases: Exception

Corrupted Exception.

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

Bases: object

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

info()

Text representation of the header.

Return type

str

classmethod parse(data, offset=0, required_tag=None)

Parse header.

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

  • offset (int) – Offset of input data

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

Return type

Header

Returns

Header object

Raises

UnparsedException – 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, …

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

Parse header.

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

  • offset (int) – Offset of input data

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

Raises

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

Return type

Header

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
exception spsdk.image.header.UnparsedException

Bases: Exception

Unparsed Exception.

Secret Module

Commands and responses used by SDP module.

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

Bases: object

Base SPSDK class.

Constructor.

Parameters
  • tag (SegTag) – section TAG

  • version (int) – format version

export(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Serialization to binary form.

Parameters

dbg_info (DebugInfo) – optional instance allowing to debug exported data; provides commented export

Return type

bytes

Returns

binary representation of the instance

Raises

NotImplementedError – Derived class has to implement this method

info()

Description about the instance.

Raises

NotImplementedError – Derived class has to implement this method

Return type

str

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

Certificate structure for bootable image.

Initialize the certificate structure for bootable image.

export(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export.

Return type

bytes

info()

String representation of the CertificateImg.

Return type

str

classmethod parse(data, offset=0)

Parse.

Return type

CertificateImg

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

Structure that holds initial parameter for AES encryption/description.

  • 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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export instance into binary form (serialization).

Parameters

dbg_info (DebugInfo) – optional instance providing debug info about exported content

Return type

bytes

Returns

binary form

info()

Text info about the instance.

Return type

str

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

Parse binary data and creates the instance (deserialization).

Parameters
  • data (bytes) – being parsed

  • offset (int) – to start parse the data

Return type

MAC

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

info()

String representation of the Secret Key Blob.

Return type

str

classmethod parse(data, offset=0)

Parse of Secret Key Blob.

Return type

SecretKeyBlob

property size: int

Size of Secret Key Blob.

Return type

int

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

Bases: spsdk.image.secret.BaseClass

Class representing a signature.

Initialize the signature.

property data: bytes

Signature data.

Return type

bytes

export(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export.

Return type

bytes

info()

String representation of the signature.

Return type

str

classmethod parse(data, offset=0)

Parse.

Return type

Signature

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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Serialization to binary form.

Parameters

dbg_info (DebugInfo) – optional instance allowing to debug exported data; provides commented export

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

info()

Description about the instance.

Raises

NotImplementedError – Derived class has to implement this method

Return type

str

classmethod parse(data, offset=0)

Pick up the right implementation of an SRK item.

Parameters
  • data (bytes) – The bytes array of SRK segment

  • offset (int) – The offset of input data

Return type

SrkItem

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.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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export.

Return type

bytes

hashed_entry()

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

Return type

SrkItemHash

info()

String representation of SrkItemHash.

Return type

str

classmethod parse(data, offset=0)

Parse SRK table item data.

Parameters
  • data (bytes) – The bytes array of SRK segment

  • offset (int) – The offset of input data

Return type

SrkItemHash

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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

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

info()

String representation of SrkItemRSA.

Return type

str

property key_length: int

Key length of Item in SRK Table.

Return type

int

classmethod parse(data, offset=0)

Parse SRK table item data.

Parameters
  • data (bytes) – The bytes array of SRK segment

  • offset (int) – The offset of input data

Return type

SrkItemRSA

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

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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export into binary form (serialization).

Parameters

dbg_info (DebugInfo) – optional instance allowing to debug exported content

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

info()

Text info about the instance.

Return type

str

classmethod parse(data, offset=0)

Parse of SRK table.

Return type

SrkTable

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 is disabled.

Return type

bool

export(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export to binary representation (serialization).

Parameters

dbg_info (DebugInfo) – instance allowing to debug output

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

info()

String representation of the BaseSegment.

Raises

NotImplementedError – Derived class has to implement this method

Return type

str

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

BaseSegment

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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export into binary form.

Parameters

dbg_info (DebugInfo) – instance allowing to debug output

Return type

bytes

Returns

binary representation used in the bootable image

export_header()

Export FCB header info binary form.

Return type

bytes

info()

String representation of the FlexSPIConfBlockFCB.

Return type

str

classmethod parse(data)

Parse binary data and creates instance of the class.

Parameters

data (bytes) – data to be parsed

Return type

FlexSPIConfBlockFCB

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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export to binary form (serialization).

Parameters

dbg_info (DebugInfo) – instance allowing to debug output format

Return type

bytes

Returns

binary representation

info()

Return text description of the instance.

Return type

str

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

info()

String representation of the SegAPP.

Return type

str

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

info()

String representation of the SegBDS3a.

Return type

str

classmethod parse(data)

Parse segment from bytes array.

Parameters

data (bytes) – The bytes array of BDS3a segment

Return type

SegBDS3a

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

info()

String representation of the SegBDS3b.

Return type

str

classmethod parse(data)

Parse segment from bytes array.

Parameters

data (bytes) – The bytes array of BDS3b segment

Return type

SegBDS3b

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

info()

String representation of the SegBDT.

Return type

str

classmethod parse(data)

Parse segment from bytes array.

Parameters

data (bytes) – The bytes array of BDT segment

Return type

SegBDT

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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Serialization to binary representation.

Parameters

dbg_info (DebugInfo) – instance allowing to provide debug info about exported data

Return type

bytes

Returns

binary representation of the region (serialization).

info()
Return type

str

Returns

test description of the instance.

classmethod parse(data, offset=0, decrypt_keys=None)

De-serialization.

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

  • offset (int) – to start parsing the data

  • 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

SegBEE

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

info()

String representation of the SegBIC1.

Return type

str

classmethod parse(data)

Parse segment from bytes array.

Parameters

data (bytes) – The bytes array of BIC1 segment

Return type

SegBIC1

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

info()

String representation of the SegBIM.

Return type

str

classmethod parse(data)

Parse segment from bytes array.

Parameters

data (bytes) – The bytes array of BootImage segment

Return type

SegBIM

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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Export segment as bytes array (serialization).

Parameters

dbg_info (DebugInfo) – optional list of strings to produce debug information about exported data

Return type

bytes

Returns

bytes

info()

String representation of the SegCSF.

Return type

str

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

Iterator of all MAC sections.

Return type

Iterator[MAC]

classmethod parse(data, offset=0)

Parse segment from bytes array.

Parameters
  • data (bytes) – The bytes array of CSF segment

  • offset (int) – to start parsing the data

Raises
Return type

SegCSF

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

info()

String representation of the SegDCD.

Return type

str

classmethod parse(data)

Parse segment from bytes array.

Parameters

data (bytes) – The bytes array of DCD segment

Raises

CorruptedException – Exception caused by corrupted data

Return type

SegDCD

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

Raises

SyntaxError – if input format is not valid

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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

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

info()

String representation of the SegIDS3a.

Return type

str

classmethod parse(data)

Parse segment from bytes array.

Parameters

data (bytes) – The bytes array of IDS3a segment

Return type

SegIDS3a

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

info()

String representation of the SegIDS3b.

Return type

str

classmethod parse(data)

Parse segment from bytes array.

Parameters

data (bytes) – The bytes array of IDS3b segment

Return type

SegIDS3b

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

info()

String representation of the SegIVT2.

Return type

str

classmethod parse(data)

Parse segment from bytes array.

Parameters

data (bytes) – The bytes array of IVT2 segment

Return type

SegIVT2

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

info()

String representation of the SegIVT3a.

Return type

str

classmethod parse(data)

Parse segment from bytes array.

Parameters

data (bytes) – The bytes array of IVT3a segment

Return type

SegIVT3a

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

info()

String representation of the SegIVT3b.

Return type

str

classmethod parse(data)

Parse segment from bytes array.

Parameters

data (bytes) – The bytes array of IVT3b segment

Return type

SegIVT3b

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

info()

String representation of the SegSIGB.

Return type

str

classmethod parse(data)

Parse segment from bytes array.

Parameters

data (bytes) – The bytes array of SignatureBlock segment

Return type

SegSIGB

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

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

get_latest_revision(family=None)

Return latest revision for given family.

Return type

str

get_revisions(family=None)

Return a list of revisions for given family.

Return type

list

static get_supported_families()

Return list of supported families.

Return type

List[str]

Returns

List of supported families.

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_config_file()

Load data from TZ config file.

Return type

dict

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 = 32
DISABLED = 64
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.

export()
Return type

bytes

Returns

binary representation of the region (serialization).

info()

Info method.

Return type

str

Returns

text description of the instance.

Raises

NotImplementedError – Derived class has to implement this method

classmethod parse(data, offset=0)

Deserialization.

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

  • offset (int) – to start parsing the data

Return type

Any

Returns

instance created from binary data; this method returns just 0

Raises

SPSDKError – If size of the data is not sufficient

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

info()
Return type

str

Returns

test description of the instance.

classmethod parse(data, offset=0)

Deserialization.

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

  • offset (int) – to start parsing the data

Return type

BeeFacRegion

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

info()
Return type

str

Returns

test description of the instance.

classmethod parse(data, offset=0)

Deserialization.

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

  • offset (int) – to start parsing the data

Return type

BeeKIB

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

info()
Return type

str

Returns

test description of the instance.

classmethod parse(data, offset=0)

Deserialization.

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

  • offset (int) – to start parsing the data

Return type

BeeProtectRegionBlock

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 = 1024
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(dbg_info=<spsdk.utils.misc.DebugInfo object>)

Serialization to binary representation.

Parameters

dbg_info (DebugInfo) – instance allowing to provide debug info about exported data

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.

info()
Return type

str

Returns

test description of the instance.

classmethod parse(data, offset=0, sw_key=b'')

Deserialization.

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

  • offset (int) – to start parsing the data

  • sw_key (bytes) – SW key used to decrypt the EKIB data (the key is marked as SW_GP2 on RT10xx)

Return type

BeeRegionHeader

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

info()

Information about key store in text form.

Return type

str

property key_source: spsdk.image.keystore.KeySourceType

Device key source.

Return type

KeySourceType

Master Boot Image

Master Boot Image.

class spsdk.image.mbimg.MasterBootImage

Bases: object

Master Boot Image Interface.

Initialization of MBI.

IMAGE_TYPE = (0, 'Plain Image (either XIP or Load-to-RAM)')
property app_len: int

Application data length.

Return type

int

Returns

Application data length.

collect_data: Any
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

parse(data)

Parse the final image to individual fields.

Parameters

data (bytes) – Final Image in bytes.

Raises

NotImplementedError – Derived class has to implement this method

Return type

None

post_encrypt: Any
sign: Any
property total_len: int

Compute final application data length.

Return type

int

Returns

Final image data length.

validate()

Validate the setting of image.

Return type

None

class spsdk.image.mbimg.Mbi_CrcExtXipLpc55s3x(app=None, trust_zone=None, firmware_version=0)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinTrustZoneMandatory, spsdk.image.mbi_mixin.Mbi_MixinFwVersion, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZone, spsdk.image.mbi_mixin.Mbi_ExportMixinCrcSign

Master Boot CRC XiP Image for LPC55s3x family.

Constructor for Master Boot CRC XiP Image stored in external memory for LPC55s3x family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

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

  • firmware_version (int) – Firmware version of image, defaults to 0

IMAGE_TYPE: Tuple[int, str] = (5, 'Plain CRC XIP Image')
search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_CrcRam(app=None, trust_zone=None, load_addr=None)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinTrustZone, spsdk.image.mbi_mixin.Mbi_MixinLoadAddress, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZone, spsdk.image.mbi_mixin.Mbi_ExportMixinCrcSign

Master Boot CRC RAM Image for LPC55xxx family.

Constructor for Master Boot CRC XiP Image for LPC55xxx family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

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

  • load_addr (Optional[int]) – Load/Execution address in RAM of image, defaults to 0

IMAGE_TYPE: Tuple[int, str] = (2, 'Plain CRC Load-to-RAM Image')
search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_CrcRamLpc55s3x(app=None, trust_zone=None, load_addr=0, firmware_version=0)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinTrustZoneMandatory, spsdk.image.mbi_mixin.Mbi_MixinLoadAddress, spsdk.image.mbi_mixin.Mbi_MixinFwVersion, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZone, spsdk.image.mbi_mixin.Mbi_ExportMixinCrcSign

Master Boot CRC RAM Image for LPC55s3x family.

Constructor for Master Boot Signed RAM Image for LPC55s3x family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

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

  • load_addr (int) – Load/Execution address in RAM of image, defaults to 0

  • firmware_version (int) – Firmware version of image, defaults to 0

IMAGE_TYPE: Tuple[int, str] = (2, 'Plain CRC Load-to-RAM Image')
search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_CrcRamRtxxx(app=None, app_table=None, trust_zone=None, load_addr=None, hwk=False)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinRelocTable, spsdk.image.mbi_mixin.Mbi_MixinLoadAddress, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinTrustZone, spsdk.image.mbi_mixin.Mbi_MixinHwKey, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZone, spsdk.image.mbi_mixin.Mbi_ExportMixinCrcSign

Master Boot CRC RAM Image for RTxxx family.

Constructor for Master Boot CRC RAM Image for RTxxx family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

  • app_table (Optional[MultipleImageTable]) – Application table for additional application binaries, defaults to None

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

  • load_addr (Optional[int]) – Load/Execution address in RAM of image, defaults to 0

  • hwk (bool) – Enable HW user mode keys, defaults to false

IMAGE_TYPE: Tuple[int, str] = (2, 'Plain CRC Load-to-RAM Image')
search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_CrcXip(app=None, trust_zone=None)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinTrustZone, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZone, spsdk.image.mbi_mixin.Mbi_ExportMixinCrcSign

Master Boot CRC XiP Image for LPC55xxx family.

Constructor for Master Boot CRC XiP Image for LPC55xxx family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

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

IMAGE_TYPE: Tuple[int, str] = (5, 'Plain CRC XIP Image')
search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_CrcXipLpc55s3x(app=None, trust_zone=None, firmware_version=0)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinTrustZoneMandatory, spsdk.image.mbi_mixin.Mbi_MixinFwVersion, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZone, spsdk.image.mbi_mixin.Mbi_ExportMixinCrcSign

Master Boot CRC XiP Image for LPC55s3x family.

Constructor for Master Boot CRC XiP Image for LPC55s3x family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

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

  • firmware_version (int) – Firmware version of image, defaults to 0

IMAGE_TYPE: Tuple[int, str] = (5, 'Plain CRC XIP Image')
search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_CrcXipRtxxx(app=None, trust_zone=None, load_addr=None, hwk=False)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinLoadAddress, spsdk.image.mbi_mixin.Mbi_MixinTrustZone, spsdk.image.mbi_mixin.Mbi_MixinHwKey, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZone, spsdk.image.mbi_mixin.Mbi_ExportMixinCrcSign

Master Boot CRC XiP Image for RTxxx.

Constructor for Master Boot CRC XiP Image for RTxxx family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

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

  • load_addr (Optional[int]) – Load/Execution address in RAM of image, defaults to 0

  • hwk (bool) – Enable HW user mode keys, defaults to false

IMAGE_TYPE: Tuple[int, str] = (5, 'Plain CRC XIP Image')
search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_EncryptedRamRtxxx(app=None, app_table=None, trust_zone=None, load_addr=None, cert_block=None, priv_key_data=None, hmac_key=None, key_store=None, ctr_init_vector=None, hwk=False)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinRelocTable, spsdk.image.mbi_mixin.Mbi_MixinLoadAddress, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinTrustZone, spsdk.image.mbi_mixin.Mbi_MixinCertBlockV2, spsdk.image.mbi_mixin.Mbi_MixinHwKey, spsdk.image.mbi_mixin.Mbi_MixinKeyStore, spsdk.image.mbi_mixin.Mbi_MixinHmacMandatory, spsdk.image.mbi_mixin.Mbi_MixinCtrInitVector, spsdk.image.mbi_mixin.Mbi_ExportMixinRsaSign, spsdk.image.mbi_mixin.Mbi_ExportMixinHmacKeyStoreFinalize

Master Boot Encrypted RAM Image for RTxxx family.

Constructor for Master Boot Encrypted RAM Image for RTxxx family..

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

  • app_table (Optional[MultipleImageTable]) – Application table for additional application binaries, defaults to None

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

  • load_addr (Optional[int]) – Load/Execution address in RAM of image, defaults to 0

  • cert_block (Optional[CertBlockV2]) – Certification block of image, defaults to None

  • priv_key_data (Optional[bytes]) – Private key used to sign image, defaults to None

  • hwk (bool) – Enable HW user mode keys, defaults to false

  • key_store (Optional[KeyStore]) – Optional KeyStore object for image, defaults to None

  • hmac_key (Union[bytes, str, None]) – HMAC key of image, defaults to None

  • ctr_init_vector (Optional[bytes]) – Counter initialization vector of image, defaults to None

IMAGE_TYPE: Tuple[int, str] = (3, 'Encrypted Load-to-RAM Image')
collect_data()

Collect basic data to create image.

Return type

bytes

Returns

Collected raw image.

encrypt(raw_image)

Encrypt image if needed.

Parameters

raw_image (bytes) – Input raw image to encrypt.

Return type

bytes

Returns

Encrypted image.

post_encrypt(image)

Optionally do some post encrypt image updates.

Parameters

image (bytes) – Encrypted image.

Return type

bytes

Returns

Updated encrypted image.

search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_PlainExtXipSignedLpc55s3x(app=None, firmware_version=0, cert_block=None, manifest=None, signature_provider=None)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinCertBlockV31, spsdk.image.mbi_mixin.Mbi_MixinManifest, spsdk.image.mbi_mixin.Mbi_MixinFwVersion, spsdk.image.mbi_mixin.Mbi_ExportMixinAppCertBlockManifest, spsdk.image.mbi_mixin.Mbi_ExportMixinEccSign

Master Boot Signed XIP Image stored in external memory for LPC55s3x family.

Constructor for Master Boot Signed XIP Image for LPC55s3x family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

  • firmware_version (int) – Firmware version of image, defaults to 0

  • cert_block (Optional[CertBlockV31]) – Certification block of image, defaults to None

  • manifest (Optional[MasterBootImageManifest]) – Manifest of image, defaults to None

  • signature_provider (Optional[SignatureProvider]) – Signature provider to sign final image, defaults to None

IMAGE_TYPE: Tuple[int, str] = (4, 'Plain Signed XIP Image')
search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_PlainRamLpc55s3x(app=None, trust_zone=None, load_addr=0, firmware_version=0)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinTrustZoneMandatory, spsdk.image.mbi_mixin.Mbi_MixinLoadAddress, spsdk.image.mbi_mixin.Mbi_MixinFwVersion, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZone

Master Boot Plain RAM Image for LPC55s3x family.

Constructor for Master Boot Plain RAM Image for LPC55s3x family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

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

  • load_addr (int) – Load/Execution address in RAM of image, defaults to 0

  • firmware_version (int) – Firmware version of image, defaults to 0

search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_PlainRamRtxxx(app=None, trust_zone=None, load_addr=None, hwk=False)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinTrustZone, spsdk.image.mbi_mixin.Mbi_MixinLoadAddress, spsdk.image.mbi_mixin.Mbi_MixinHwKey, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZone

Master Boot Plain Image for RTxxx.

Constructor for Master Boot Plain XiP Image for RTxxx family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

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

  • load_addr (Optional[int]) – Load/Execution address in RAM of image, defaults to 0

  • hwk (bool) – Enable HW user mode keys, defaults to false

search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_PlainSignedRamRtxxx(app=None, app_table=None, trust_zone=None, load_addr=None, cert_block=None, priv_key_data=None, hmac_key=None, key_store=None, hwk=False)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinRelocTable, spsdk.image.mbi_mixin.Mbi_MixinLoadAddress, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinTrustZone, spsdk.image.mbi_mixin.Mbi_MixinCertBlockV2, spsdk.image.mbi_mixin.Mbi_MixinHmacMandatory, spsdk.image.mbi_mixin.Mbi_MixinKeyStore, spsdk.image.mbi_mixin.Mbi_MixinHwKey, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZoneCertBlock, spsdk.image.mbi_mixin.Mbi_ExportMixinRsaSign, spsdk.image.mbi_mixin.Mbi_ExportMixinHmacKeyStoreFinalize

Master Boot Plain Signed RAM Image for RTxxx family.

Constructor for Master Boot Plain Signed RAM Image for RTxxx family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

  • app_table (Optional[MultipleImageTable]) – Application table for additional application binaries, defaults to None

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

  • load_addr (Optional[int]) – Load/Execution address in RAM of image, defaults to 0

  • cert_block (Optional[CertBlockV2]) – Certification block of image, defaults to None

  • priv_key_data (Optional[bytes]) – Private key used to sign image, defaults to None

  • hmac_key (Union[bytes, str, None]) – HMAC key of image, defaults to None

  • key_store (Optional[KeyStore]) – Optional KeyStore object for image, defaults to None

  • hwk (bool) – Enable HW user mode keys, defaults to false

IMAGE_TYPE: Tuple[int, str] = (1, 'Plain Signed Load-to-RAM Image')
property app_len: int

Application data length.

Return type

int

Returns

Application data length.

search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_PlainSignedXipRtxxx(app=None, trust_zone=None, load_addr=None, cert_block=None, priv_key_data=None, hwk=False)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinLoadAddress, spsdk.image.mbi_mixin.Mbi_MixinTrustZone, spsdk.image.mbi_mixin.Mbi_MixinCertBlockV2, spsdk.image.mbi_mixin.Mbi_MixinHwKey, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZoneCertBlock, spsdk.image.mbi_mixin.Mbi_ExportMixinRsaSign

Master Boot Plain Signed XiP Image for RTxxx family.

Constructor for Master Boot Plain Signed XiP Image for RTxxx family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

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

  • load_addr (Optional[int]) – Load/Execution address in RAM of image, defaults to 0

  • cert_block (Optional[CertBlockV2]) – Certification block of image, defaults to None

  • priv_key_data (Optional[bytes]) – Private key used to sign image, defaults to None

  • hwk (bool) – Enable HW user mode keys, defaults to false

IMAGE_TYPE: Tuple[int, str] = (4, 'Plain Signed XIP Image')
search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_PlainXip(app=None, trust_zone=None)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinTrustZone, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZone

Master Boot Plain XiP Image for LPC55xxx family.

Constructor for Master Boot Plain XiP Image for LPC55xxx family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

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

search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_PlainXipRtxxx(app=None, trust_zone=None, hwk=False)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinTrustZone, spsdk.image.mbi_mixin.Mbi_MixinHwKey, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZone

Master Boot Plain XiP Image for RTxxx.

Constructor for Master Boot Plain XiP Image for RTxxx family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

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

  • hwk (bool) – Enable HW user mode keys, defaults to false

search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_PlainXipSignedLpc55s3x(app=None, firmware_version=0, cert_block=None, manifest=None, signature_provider=None)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinCertBlockV31, spsdk.image.mbi_mixin.Mbi_MixinManifest, spsdk.image.mbi_mixin.Mbi_MixinFwVersion, spsdk.image.mbi_mixin.Mbi_ExportMixinAppCertBlockManifest, spsdk.image.mbi_mixin.Mbi_ExportMixinEccSign

Master Boot Signed XIP Image for LPC55s3x family.

Constructor for Master Boot Signed XIP Image for LPC55s3x family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

  • firmware_version (int) – Firmware version of image, defaults to 0

  • cert_block (Optional[CertBlockV31]) – Certification block of image, defaults to None

  • manifest (Optional[MasterBootImageManifest]) – Manifest of image, defaults to None

  • signature_provider (Optional[SignatureProvider]) – Signature provider to sign final image, defaults to None

IMAGE_TYPE: Tuple[int, str] = (4, 'Plain Signed XIP Image')
search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_SignedRam(app=None, trust_zone=None, load_addr=None, cert_block=None, priv_key_data=None)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinTrustZone, spsdk.image.mbi_mixin.Mbi_MixinLoadAddress, spsdk.image.mbi_mixin.Mbi_MixinCertBlockV2, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZoneCertBlock, spsdk.image.mbi_mixin.Mbi_ExportMixinRsaSign

Master Boot Signed RAM Image for LPC55xxx family.

Constructor for Master Boot Signed XiP Image for LPC55xxx family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

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

  • load_addr (Optional[int]) – Load/Execution address in RAM of image, defaults to 0

  • cert_block (Optional[CertBlockV2]) – Certification block of image, defaults to None

  • priv_key_data (Optional[bytes]) – Private key used to sign image, defaults to None

IMAGE_TYPE: Tuple[int, str] = (4, 'Plain Signed XIP Image')
search_paths: Optional[List[str]]
class spsdk.image.mbimg.Mbi_SignedXip(app=None, trust_zone=None, cert_block=None, priv_key_data=None)

Bases: spsdk.image.mbimg.MasterBootImage, spsdk.image.mbi_mixin.Mbi_MixinApp, spsdk.image.mbi_mixin.Mbi_MixinIvt, spsdk.image.mbi_mixin.Mbi_MixinTrustZone, spsdk.image.mbi_mixin.Mbi_MixinCertBlockV2, spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZoneCertBlock, spsdk.image.mbi_mixin.Mbi_ExportMixinRsaSign

Master Boot Signed XiP Image for LPC55xxx family.

Constructor for Master Boot Signed XiP Image for LPC55xxx family.

Parameters
  • app (Optional[bytes]) – Application image data, defaults to None

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

  • cert_block (Optional[CertBlockV2]) – Certification block of image, defaults to None

  • priv_key_data (Optional[bytes]) – Private key used to sign image, defaults to None

IMAGE_TYPE: Tuple[int, str] = (4, 'Plain Signed XIP Image')
search_paths: Optional[List[str]]
spsdk.image.mbimg.get_all_mbi_classes()

Get all Master Boot Image supported classes.

Return type

List[Type[MasterBootImage]]

Returns

List with all MBI Classes.

spsdk.image.mbimg.get_mbi_class(config)

Get Master Boot Image class.

Raises

SPSDKUnsupportedImageType – The invalid configuration.

Return type

Type[MasterBootImage]

Returns

MBI Class.

spsdk.image.mbimg.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.mbimg.mbi_generate_config_templates(family)

Generate all possible configuration for selected family.

Parameters

family (str) – Family description.

Raises

SPSDKError – [description]

Return type

Dict[str, str]

Returns

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

spsdk.image.mbimg.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_mixin.MasterBootImageManifest(firmware_version, trust_zone, sign_hash_len=None)

Bases: object

MasterBootImage Manifest used in LPC55s3x.

Initialize MBI Manifest object.

Parameters
  • firmware_version (int) – firmware version

  • sign_hash_len (Optional[int]) – length of hash used for singing, defaults to None

  • trust_zone (TrustZone) – TrustZone instance, defaults to None

DIGEST_PRESENT_FLAG = 2147483648
FORMAT = '<4s4L'
FORMAT_VERSION = 65536
MAGIC = b'imgm'
export()

Serialize MBI Manifest.

Return type

bytes

class spsdk.image.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.

encrypt(raw_image)

Encrypt image if needed.

Parameters

raw_image (bytes) – Input raw image to encrypt.

Return type

bytes

Returns

Encrypted image.

finalize(image)

Finalize the image for export.

This part could add HMAC/KeyStore etc.

Parameters

image (bytes) – Input image.

Return type

bytes

Returns

Finalized image suitable for export.

post_encrypt(image)

Optionally do some post encrypt image updates.

Parameters

image (bytes) – Encrypted image.

Return type

bytes

Returns

Updated encrypted image.

sign(image)

Sign image (by signature or CRC).

Parameters

image (bytes) – Image to sign.

Return type

bytes

Returns

Optionally signed image.

class spsdk.image.mbi_mixin.Mbi_ExportMixinAppCertBlockManifest

Bases: spsdk.image.mbi_mixin.Mbi_ExportMixin

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

app: Optional[bytes]
app_len: Any
cert_block: Optional[spsdk.utils.crypto.cert_blocks.CertBlockV31]
collect_data()

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

Return type

bytes

Returns

Image with updated IVT and added Certification Block with Manifest.

get_app_data: Callable
manifest: Optional[spsdk.image.mbi_mixin.MasterBootImageManifest]
total_len: Any
update_ivt: Callable
class spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZone

Bases: spsdk.image.mbi_mixin.Mbi_ExportMixin

Export Mixin to handle simple application data and TrustZone.

app: Optional[bytes]
collect_data()

Collect application data and TrustZone including update IVT.

Return type

bytes

Returns

Image with updated IVT and added TrustZone.

get_app_data: Callable
total_len: Any
tz: spsdk.image.trustzone.TrustZone
update_ivt: Callable
class spsdk.image.mbi_mixin.Mbi_ExportMixinAppTrustZoneCertBlock

Bases: spsdk.image.mbi_mixin.Mbi_ExportMixin

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

app: Optional[bytes]
app_len: Any
cert_block: Optional[spsdk.utils.crypto.cert_blocks.CertBlockV2]
collect_data()

Collect application data and TrustZone including update IVT.

Return type

bytes

Returns

Image with updated IVT and added TrustZone.

get_app_data: Callable
total_len: Any
tz: spsdk.image.trustzone.TrustZone
update_ivt: Callable
class spsdk.image.mbi_mixin.Mbi_ExportMixinCrcSign

Bases: spsdk.image.mbi_mixin.Mbi_ExportMixin

Export Mixin to handle sign by CRC.

IVT_CRC_CERTIFICATE_OFFSET: int
sign(image)

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

Parameters

image (bytes) – Input raw image.

Return type

bytes

Returns

Image enriched by CRC in IVT table.

update_crc_val_cert_offset: Callable
class spsdk.image.mbi_mixin.Mbi_ExportMixinEccSign

Bases: spsdk.image.mbi_mixin.Mbi_ExportMixin

Export Mixin to handle sign by ECC.

no_signature: Optional[bool]
sign(image)

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

Parameters

image (bytes) – Input raw image.

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_mixin.Mbi_ExportMixinHmacKeyStoreFinalize

Bases: spsdk.image.mbi_mixin.Mbi_ExportMixin

Export Mixin to handle finalize by HMAC and optionally KeyStore.

HMAC_OFFSET: int
compute_hmac: Callable
finalize(image)

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

Parameters

image (bytes) – Input image.

Return type

bytes

Returns

Finalized image suitable for export.

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

Bases: spsdk.image.mbi_mixin.Mbi_ExportMixin

Export Mixin to handle sign by RSA.

priv_key_data: Optional[bytes]
sign(image)

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

Parameters

image (bytes) – Input raw image.

Return type

bytes

Returns

Image enriched by RSA signature at end of image.

class spsdk.image.mbi_mixin.Mbi_ExportMixinSignDigestFinalize

Bases: spsdk.image.mbi_mixin.Mbi_ExportMixin

Export Mixin to handle finalize by Signature digest.

attach_sign_digest: Optional[str]
finalize(image)

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

Parameters

image (bytes) – Input image.

Return type

bytes

Returns

Finalized image suitable for export.

class spsdk.image.mbi_mixin.Mbi_Mixin

Bases: object

Base class for Master BOtt Image Mixin classes.

NEEDED_MEMBERS: List[str] = []
VALIDATION_SCHEMAS: List[str] = []
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_mixin.Mbi_MixinApp

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image Trust Zone class.

NEEDED_MEMBERS: List[str] = ['app']
VALIDATION_SCHEMAS: List[str] = ['app']
app: Optional[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_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_mixin.Mbi_MixinCertBlockV2

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image certification block V2 class.

NEEDED_MEMBERS: List[str] = ['cert_block', 'priv_key_data']
VALIDATION_SCHEMAS: List[str] = ['cert_prv_key']
cert_block: Optional[spsdk.utils.crypto.cert_blocks.CertBlockV2]
classmethod mix_get_extra_validation_schemas()

Get additional validation schemas - directly from Certificate block object.

Return type

List[Dict[str, Any]]

Returns

Certificate block schemas.

mix_len()

Get length of Certificate Block V2.

Return type

int

Returns

Length of Certificate Block V2.

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 – Configuration of Certificate block v2 is invalid.

Return type

None

priv_key_data: Optional[bytes]
search_paths: Optional[List[str]]
class spsdk.image.mbi_mixin.Mbi_MixinCertBlockV31

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image certification block V3.1 class.

NEEDED_MEMBERS: List[str] = ['cert_block', 'signature_provider']
VALIDATION_SCHEMAS: List[str] = ['use_isk', 'signing_cert_prv_key', 'signing_root_prv_key', 'signing_prv_key_lpc55s3x']
cert_block: Optional[spsdk.utils.crypto.cert_blocks.CertBlockV31]
classmethod mix_get_extra_validation_schemas()

Get additional validation schemas - directly from Certificate block object.

Return type

List[Dict[str, Any]]

Returns

Certificate block schemas.

mix_len()

Get length of Certificate Block V3.1.

Return type

int

Returns

Length of Certificate Block V3.1.

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 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_mixin.Mbi_MixinCtrInitVector

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image initial vector for encryption counter.

NEEDED_MEMBERS: List[str] = ['ctr_init_vector']
VALIDATION_SCHEMAS: List[str] = ['ctr_init_vector']
ctr_init_vector: bytes
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.

raise SPSDKError: Invalid HW key enabled member type.

Return type

None

store_ctr_init_vector(ctr_iv=None)

Stores the Counter init vector, if not specified the random value is used.

param ctr_iv: Counter Initial Vector.

Return type

None

class spsdk.image.mbi_mixin.Mbi_MixinFwVersion

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image FirmWare Version class.

NEEDED_MEMBERS: List[str] = ['firmware_version', 'firmware_version_to_image_type']
VALIDATION_SCHEMAS: List[str] = ['firmware_version']
firmware_version: Optional[int]
firmware_version_to_image_type: bool = True
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_mixin.Mbi_MixinHmac

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image HMAC class.

HMAC_OFFSET = 64
HMAC_SIZE = 32
NEEDED_MEMBERS: List[str] = ['hmac_key']
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.

hmac_key: Optional[bytes]
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_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_mixin.Mbi_MixinHmacMandatory

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

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image HW key user modes enable class.

NEEDED_MEMBERS: List[str] = ['user_hw_key_enabled']
VALIDATION_SCHEMAS: List[str] = ['hw_key']
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.

raise SPSDKError: Invalid HW key enabled member type.

Return type

None

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

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image SubType class.

class Mbi_ImageSubType

Bases: spsdk.utils.easy_enum.Enum

List of supported subtypes.

MAIN = 0
NEEDED_MEMBERS: List[str] = ['image_subtype']
VALIDATION_SCHEMAS: List[str] = ['image_subtype']
image_subtype: Optional[int]
mix_load_from_config(config)

Load configuration from dictionary.

Parameters

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

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_mixin.Mbi_MixinIvt

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image Interrupt Vector table class.

IMAGE_TYPE: Tuple[int, str]
IVT_CRC_CERTIFICATE_OFFSET = 40
IVT_IMAGE_FLAGS_OFFSET = 36
IVT_IMAGE_LENGTH_OFFSET = 32
IVT_LOAD_ADDR_OFFSET = 52
app_table: Optional[spsdk.image.mbi_mixin.MultipleImageTable]
create_flags()

Create flags of image.

Return type

int

Returns

Image type flags

firmware_version: Optional[int]
firmware_version_to_image_type: bool
image_subtype: Optional[int]
key_store: Optional[spsdk.image.keystore.KeyStore]
load_address: Optional[int]
tz: 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_mixin.Mbi_MixinKeyStore

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image KeyStore class.

NEEDED_MEMBERS: List[str] = ['key_store', 'hmac_key']
VALIDATION_SCHEMAS: List[str] = ['key_store']
hmac_key: Optional[bytes]
key_store: Optional[spsdk.image.keystore.KeyStore]
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_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_mixin.Mbi_MixinLoadAddress

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image load address class.

NEEDED_MEMBERS: List[str] = ['load_address']
VALIDATION_SCHEMAS: List[str] = ['load_addr']
load_address: Optional[int]
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_mixin.Mbi_MixinManifest

Bases: spsdk.image.mbi_mixin.Mbi_MixinTrustZoneMandatory

Master Boot Image Manifest class.

NEEDED_MEMBERS: List[str] = ['manifest', 'firmware_version']
VALIDATION_SCHEMAS: List[str] = ['tz', 'family', 'firmware_version', 'sign_hash_len']
firmware_version: Optional[int]
manifest: Optional[spsdk.image.mbi_mixin.MasterBootImageManifest]
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_validate()

Validate the setting of image.

Raises

SPSDKError – The manifest configuration is invalid.

Return type

None

class spsdk.image.mbi_mixin.Mbi_MixinNXPImage

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image ‘Image Type Changer’ to NXP Image type.

IMAGE_TYPE: Tuple[int, str]
NEEDED_MEMBERS: List[str] = ['IMAGE_TYPE']
SIGNED_XIP_NXP_IMAGE = (8, 'Plain Signed XIP Image NXP Key')
VALIDATION_SCHEMAS: List[str] = ['nxp_image']
change_to_nxp_image()

Calling this changed to NXP image.

Return type

None

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_mixin.Mbi_MixinNoSignature

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image No Signature.

NEEDED_MEMBERS: List[str] = ['no_signature']
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_mixin.Mbi_MixinRelocTable

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image Relocation table class.

NEEDED_MEMBERS: List[str] = ['app_table', 'app']
VALIDATION_SCHEMAS: List[str] = ['app_table']
app: Optional[bytes]
app_table: Optional[spsdk.image.mbi_mixin.MultipleImageTable]
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_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_mixin.Mbi_MixinSignDigest

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image Signature Digest.

NEEDED_MEMBERS: List[str] = ['attach_sign_digest']
SIGN_DIGEST_VALUES: Dict[str, int] = {'sha256': 32, 'sha384': 48}
VALIDATION_SCHEMAS: List[str] = ['attach_sign_digest', 'use_isk', 'elliptic_curves']
attach_sign_digest: Optional[str]
get_sign_digest()

Get sign digest type from signature provider.

Return type

Optional[str]

Returns

Type of signature digest.

mix_len()

Get length of Signature digest block.

Return type

int

Returns

Length of Signature digest 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.

raise SPSDKError: Invalid HW key enabled member type.

Return type

None

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

Bases: spsdk.image.mbi_mixin.Mbi_Mixin

Master Boot Image Trust Zone class.

NEEDED_MEMBERS: List[str] = ['tz']
VALIDATION_SCHEMAS: List[str] = ['tz', 'family']
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

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

Bases: spsdk.image.mbi_mixin.Mbi_MixinTrustZone

Master Boot Image Trust Zone class for LPC55s3x family.

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]]
tz: spsdk.image.trustzone.TrustZone
class spsdk.image.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

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

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

str

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)

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. 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, 'dcd_image': 5, 'executable': 3, '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
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='cortex-m33', hash_type='sha256', is_encrypted=False, boot_flags=0)

Create flags field.

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

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

  • hash_type (str) – 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

str

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

get_image_data()

Get the image data block.

Those are image data that is described by Image Array Entry. :rtype: bytes :return: Image data in bytes.

static parse(parent, binary, offset=0)

Parse input binary chunk to the container object.

Parameters
  • parent (AHABContainer) – Parent AHABContainer object.

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

  • offset (int) – Offset to Image Array Entry block data, default is 0.

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

  • SPSDKValueError – Invalid hash for image.

Return type

ImageArrayEntry

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

CommentedMap

Returns

Configuration dictionary.

class spsdk.image.ahab.ahab_container.SRKRecord(signing_algorithm='rsa', hash_type='sha256', 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 encryption 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
  • signing_algorithm (str) – signing algorithm type.

  • hash_type (str) – 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]
VERSION_ALGORITHMS = {'ecdsa': 39, 'rsa': 33}
HASH_ALGORITHM = {'sha256': 0, 'sha384': 1, 'sha512': 2}
ECC_KEY_TYPE = {'prime256v1': 1, 'secp256r1': 1, 'secp384r1': 2, 'secp521r1': 3}
RSA_KEY_TYPE = {2048: 5, 4096: 7}
KEY_SIZES = {1: (32, 32), 2: (48, 48), 3: (64, 64), 5: (128, 128), 7: (256, 256)}
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, hash_type='sha256', srk_flags=0)

Create instance from key data.

Parameters
  • public_key (Union[RSAPublicKey, EllipticCurvePublicKey]) – Loaded public key.

  • hash_type (str) – HASH type for the key, defaults to “sha256”

  • srk_flags (int) – SRK flags for key.

Return type

SRKRecord

static parse(binary, offset=0)

Parse input binary chunk to the container object.

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

  • offset (int) – Offset to SRK record block data, default is 0.

Raises

SPSDKLengthError – Invalid length of SRK record data block.

Return type

SRKRecord

Returns

SRK record recreated from the binary data.

get_key_name()

Get text key name in SRK record.

Return type

str

Returns

Key name.

store_public_key(filename, encoding=Encoding.PEM)

Store the SRK public key as a file.

Parameters
  • filename (str) – Filename path of new public key.

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

Return type

None

class spsdk.image.ahab.ahab_container.SRKTable(parent, 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
  • parent (SignatureBlock) – AHAB Signature Block parent object.

  • 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, hash_type='sha256')

Add SRK table record.

Parameters
  • public_key (Union[RSAPublicKey, EllipticCurvePublicKey]) – Loaded public key.

  • hash_type (str) – HASH type for the key, defaults to “sha256”

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.

export()

Serializes container object into bytes in little endian.

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 parse(parent, binary, offset=0)

Parse input binary chunk to the container object.

Parameters
  • parent (SignatureBlock) – AHAB Signature Block parent object.

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

  • offset (int) – Offset to SRK table block data, default is 0.

Raises

SPSDKLengthError – Invalid length of SRK table data block.

Return type

SRKTable

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

CommentedMap

Returns

Configuration dictionary.

static load_from_config(parent, config)

Converts the configuration option into an AHAB image object.

“config” content of container configurations.

Parameters
  • parent (SignatureBlock) – AHAB Signature Block parent object.

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

Return type

SRKTable

Returns

SRK Table object.

class spsdk.image.ahab.ahab_container.ContainerSignature(signature_data=None, signing_key=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.

  • signing_key (Union[RSAPrivateKey, EllipticCurvePrivateKey, None]) – Key use to sign the image.

TAG = 216
VERSION = 0
property signature_data: bytes

Get the signature data.

Return type

bytes

Returns

signature data.

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

static parse(binary, offset=0)

Parse input binary chunk to the container object.

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

  • offset (int) – Offset to Container signature block data, default is 0.

Return type

ContainerSignature

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, signing_key=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.

  • signing_key (Union[RSAPrivateKey, EllipticCurvePrivateKey, None]) – signing key 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
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.

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.

self_sign()

Sign self by the signature key and store result into _signature field.

Return type

None

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

static parse(binary, offset=0)

Parse input binary chunk to the container object.

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

  • offset (int) – Offset to Certificate block data, default is 0.

Raises

SPSDKValueError – Certificate permissions are invalid.

Return type

Certificate

Returns

Object recreated from the binary data.

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

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

CommentedMap

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.

class spsdk.image.ahab.ahab_container.Blob(flags=0, size=0, wrapped_key=None)

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
  • size (int) – key size ID.

  • wrapped_key (Optional[bytes]) – wrapped key.

TAG = 129
VERSION = 0
MODE = 102
ALGORITHM = 85
FLAGS = 128
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

static parse(binary, offset=0)

Parse input binary chunk to the container object.

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

  • offset (int) – Offset to Blob block data, default is 0.

Return type

Blob

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

CommentedMap

Returns

Configuration dictionary.

static load_from_config(config)

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

“config” content of container configurations.

Parameters

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

Return type

Blob

Returns

Blob object.

class spsdk.image.ahab.ahab_container.SignatureBlock(parent=None, 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       |     |
|--------------------------------+---------------------------------+     |
|                             Reserved                             |     |
+------------------------------------------------------------------+-----+ 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
  • parent (Optional[AHABContainer]) – AHAB Container parent object.

  • 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
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()

Validate object data.

Raises

SPSDKValueError – Invalid any value of Image Array entry

Return type

None

static parse(parent, binary, offset=0)

Parse input binary chunk to the container object.

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

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

  • offset (int) – Offset to Signature block data, default is 0.

Return type

SignatureBlock

Returns

Object recreated from the binary data.

static load_from_config(parent, config)

Converts the configuration option into an AHAB Signature block object.

“config” content of container configurations.

Parameters
  • parent (AHABContainer) – AHABContainer object.

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

Return type

SignatureBlock

Returns

AHAB Signature block object.

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_abstract_interfaces.HeaderContainer

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

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

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                 |
+---+---+-----------+---------+--------+------------+
| S |   |    tag    | length  | length | version    |
| i |   +-----------+---------+--------+------------+
| g |   |                  flags                    |
| n |   +---------------------+---------------------+
| a |   |  srk table offset   | certificate offset  |
| t |   +---------------------+---------------------+
| 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.

header_export()

Export container header into bytes.

Return type

bytes

Returns

bytes representing container header content including the signature block.

export()

Export the binary images into one chunk on respective offsets.

The fist image starts at offset 0. To append the serialized images to the serialized container header, the container header must be padded with extra zeros to have the images at proper offset.

If the container has no images, the serializer returns empty binary.

Raises

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

Return type

bytes

Returns

images exported into single binary

validate()

Validate object data.

Raises

SPSDKValueError – Invalid any value of Image Array entry

Return type

None

static parse(parent, binary, offset=0)

Parse input binary chunk to the container object.

Parameters
  • parent (AHABImage) – AHABImage object.

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

  • offset (int) – Offset to Container block data, default is 0.

Return type

AHABContainer

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

CommentedMap

Returns

Configuration dictionary.

static load_from_config(parent, config)

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.

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', image_type='xip', 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”

  • image_type (str) – Type of image [xip, non_xip, serial_downloader], defaults to “xip”

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

IMAGE_TYPES = ['xip', 'non_xip', 'serial_downloader']
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. :raise SPSDKLengthError: The container count in image is overflowed.

Return type

None

clear()

Clear list of containers.

Return type

None

update_fields()

Automatically updates all volatile fields in every AHAB container.

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.

Raises

SPSDKValueError – if the count of AHAB containers is invalid.

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

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

CommentedMap

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: abc.ABC

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

validate()

Validates the container properties…

i.e. tag e <0; 255>, otherwise an exception is raised.

Return type

None

export()

Exports container to final bytes array.

Return type

bytes

Returns

Bytes representation of container object.

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
validate()

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

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