Image Module API#
Module implementing functionality of srktool, dcdgen, mkimage and other similar tools.
Image Classes#
Image.
- class spsdk.image.images.BootImg2(address=0, offset=1024, version=65, plugin=False)#
Bases:
BootImgBase
IMX Boot Image v2.
Initialize boot image object.
- Parameters:
address (
int
) – The start address of img in target memoryoffset (
int
) – The IVT offsetversion (
int
) – The version of boot img formatplugin (
bool
) – if plugin
- APP_ALIGN = 4096#
- CSF_SIZE = 8192#
- HEAD_SIZE = {256: 768, 1024: 3072}#
- add_image(data, img_type=EnumAppType.APP, address=0)#
Add specific image into the main boot image.
- Parameters:
data (
bytes
) – Raw data of imgimg_type (
EnumAppType
) – Type of imgaddress (
int
) – address in RAM
- Raises:
Exception – Raised when the data type is unknown
- Return type:
None
- export()#
Export image as bytes array.
- Return type:
bytes
- Returns:
bytes
- classmethod parse(stream, step=256, size=None)#
Parse image from stream buffer or bytes array.
- Parameters:
stream (
Union
[bytes
,bytearray
,BufferedReader
,BytesIO
]) – The stream buffer or bytes arraystep (
int
) – Image searching stepsize (
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:
- Returns:
BootImg2 object
- property plugin: bool#
Plugin.
- property size: int#
Size of IMX Boot Image v2..
- property version: int#
Version of IMX Boot Image v2.
- class spsdk.image.images.BootImg3a(address=0, offset=1024, version=67)#
Bases:
BootImgBase
i.MX Boot Image v3a.
Initialize boot image object.
- Parameters:
address (
int
) – The start address of img in target memoryoffset (
int
) – The IVT offsetversion (
int
) – The version of boot img format
- APP_ALIGN = 4608#
- COUNT_OF_CONTAINERS = 2#
- CSF_SIZE = 8192#
- HEAD_SIZE = {1024: 50176, 4096: 5120}#
- IMG_AUTO_ALIGN = 16#
- IMG_TYPE_CSF = 1#
- IMG_TYPE_DATA = 4#
- IMG_TYPE_EXEC = 3#
- IMG_TYPE_SCD = 2#
- INITIAL_LOAD_ADDR_AP_ROM = 1114112#
- INITIAL_LOAD_ADDR_FLEXSPI = 134217728#
- INITIAL_LOAD_ADDR_SCU_ROM = 536928256#
- PADDING_VAL = 0#
- SCFW_FLAGS_APP = 20275140#
- SCFW_FLAGS_M4_0 = 4870498#
- SCFW_FLAGS_M4_1 = 5198499#
- SCFW_FLAGS_SCFW = 1#
- SECTOR_SIZE = 512#
- add_image(data, img_type=EnumAppType.APP, address=0)#
Add specific image into the main boot image.
- Parameters:
data (
bytes
) – Raw data of imageimg_type (
EnumAppType
) – Type of imageaddress (
int
) – address in RAM
- Raises:
Exception – raised when data type is unknown
- Return type:
None
- export()#
Export Image as binary blob.
- Return type:
bytes
- classmethod parse(stream, step=256, size=None)#
Parse image from stream buffer or bytes array.
- Parameters:
stream (
Union
[bytes
,bytearray
,BufferedReader
,BytesIO
]) – The stream buffer or bytes arraystep (
int
) – Image searching stepsize (
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:
- Returns:
BootImg3a object
- property plg: bool#
PLG.
- class spsdk.image.images.BootImg3b(address=0, offset=1024, version=67)#
Bases:
BootImgBase
IMX Boot Image v3b.
Initialize boot image object.
- Parameters:
address (
int
) – The start address of img in target memoryoffset (
int
) – The IVT offsetversion (
int
) – The version of boot img format
- APP_ALIGN = 4608#
- COUNT_OF_CONTAINERS = 2#
- CSF_SIZE = 8192#
- HEAD_SIZE = {1024: 50176, 4096: 5120}#
- IMG_AUTO_ALIGN = 16#
- IMG_TYPE_CSF = 1#
- IMG_TYPE_DATA = 4#
- IMG_TYPE_EXEC = 3#
- IMG_TYPE_SCD = 2#
- INITIAL_LOAD_ADDR_AP_ROM = 1114112#
- INITIAL_LOAD_ADDR_FLEXSPI = 134217728#
- INITIAL_LOAD_ADDR_SCU_ROM = 536928256#
- PADDING_VAL = 0#
- SCFW_FLAGS_A53 = 20267028#
- SCFW_FLAGS_A72 = 20267109#
- SCFW_FLAGS_M4_0 = 4870498#
- SCFW_FLAGS_M4_1 = 5198499#
- SCFW_FLAGS_SCFW = 1#
- SECTOR_SIZE = 512#
- add_image(data, img_type=EnumAppType.APP, address=0)#
Add specific image into the main boot image.
- Parameters:
data (
bytes
) – Raw data of imageimg_type (
EnumAppType
) – Type of imageaddress (
int
) – address in RAM
- Raises:
Exception – raised SCFW is not defined before SCD
Exception – raised when there is unknown image type
- Return type:
None
- export()#
Export.
- Return type:
bytes
- classmethod parse(stream, step=256, size=None)#
Parse image from stream buffer or bytes array.
- Parameters:
stream (
Union
[bytes
,bytearray
,BufferedReader
,BytesIO
]) – The stream buffer or bytes arraystep (
int
) – Image searching stepsize (
Optional
[int
]) – parsing size
- Raises:
SPSDKError – When the value is incorrect
SPSDKError – If there is not an i.MX Boot Image
- Return type:
- Returns:
BootImg3b object
- property plg: bool#
PLG.
- class spsdk.image.images.BootImg4(address=0, offset=1024)#
Bases:
BootImgBase
i.MX Boot Image v4.
Initialize boot image object.
- Parameters:
address (
int
) – The start address of image in target memoryoffset (
int
) – The image offset
- add_image(data, img_type, address)#
Add image.
- Raises:
NotImplementedError – Not yet implemented
- Return type:
None
- export()#
Export.
- Return type:
bytes
- classmethod parse(stream, step=256, size=None)#
Parse image from stream buffer or bytes array.
- Parameters:
stream (
Union
[bytes
,bytearray
,BufferedReader
,BytesIO
]) – The stream buffer or bytes arraystep (
int
) – Image searching stepsize (
Optional
[int
]) – parsing size
- Return type:
- Returns:
BootImg4 object
- Raises:
SPSDKError – Raised when the value type is incorrect
SPSDKError – If there is not an i.MX Boot Image
- class spsdk.image.images.BootImg8m(address=0, offset=1024, version=65, plugin=False)#
Bases:
BootImgBase
IMX Boot Image.
Initialize boot image object.
- Parameters:
address (
int
) – The start address of img in target memoryoffset (
int
) – The IVT offsetversion (
int
) – The version of boot img formatplugin (
bool
) – if plugin
- APP_ALIGN = 4096#
- CSF_SIZE = 8192#
- HEAD_SIZE = {256: 768, 1024: 3072}#
- add_image(data, img_type=EnumAppType.APP, address=0)#
Add specific image into the main boot image.
- Parameters:
data (
bytes
) – Raw data of imgimg_type (
EnumAppType
) – Type of imgaddress (
int
) – address in RAM
- Raises:
Exception – raised when data type is unknown
- Return type:
None
- export()#
Export Image as bytes array.
- Return type:
bytes
- Returns:
bytes
- classmethod parse(stream, step=256, size=None)#
Parse image from stream buffer or bytes array.
- Parameters:
stream (
Union
[bytes
,bytearray
,BufferedReader
,BytesIO
]) – The stream buffer or bytes arraystep (
int
) – Image searching stepsize (
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:
- Returns:
BootImg2 object
- property plugin: bool#
Plugin.
- property size: int#
Size of IMX Boot Image.
- property version: int#
Version of IMX Boot Image.
- class spsdk.image.images.BootImgBase(address, offset)#
Bases:
object
IMX Boot Image Base.
Initialize boot image object.
- Parameters:
address (
int
) – The start address of img in target memoryoffset (
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 imageimg_type (
EnumAppType
) – see EnumAppTypeaddress (
int
) – TBD
- Raises:
NotImplementedError – Derived class has to implement this method
- Return type:
None
- export()#
Binary representation of the instance (serialization).
- Raises:
NotImplementedError – Derived class has to implement this method
- Return type:
bytes
- classmethod parse(stream, step=256, size=None)#
Parse of IMX Boot Image Base.
- Raises:
NotImplementedError – Derived class has to implement this method
- Return type:
- class spsdk.image.images.BootImgRT(address, offset=4096, version=64, plugin=False)#
Bases:
BootImgBase
IMX Boot Image v2.
Initialize boot image object.
- Parameters:
address (
int
) – The start address of img in target memory, where the image is executedoffset (
int
) – The IVT offset; use IVT_OFFSET_NOR_FLASH for NOR-FLASH or IVT_OFFSET_OTHERversion (
int
) – The version of boot img format; default value should be usedplugin (
bool
) – Do not use; see self.plugin property
- Raises:
SPSDKError – If invalid IVT offset
SPSDKError – If invalid version
SPSDKError – If Plugin is not supported
- BDT_SIZE = 32#
- BEE_OFFSET = 1024#
- CSF_SIZE = 8192#
- DEK_SIZE = 512#
- FCB_OFFSETS = (0, 1024)#
- IVT_OFFSETS = (0, 1024, 3072, 4096)#
- IVT_OFFSET_NOR_FLASH = 4096#
- IVT_OFFSET_OTHER = 1024#
- IVT_OFFSET_OTHER2 = 3072#
- NON_XIP_APP_OFFSET = 4096#
- VERSIONS = (64, 65, 66, 67)#
- XIP_APP_OFFSET = 8192#
- XMCD_IVT_OFFSET = 64#
- add_csf_encrypted(version, srk_table, src_key_index, csf_cert, csf_priv_key, img_cert, img_priv_key)#
Add CSF with image encryption.
Before calling, application image and address must be assigned
- Parameters:
version (
int
) – CSF segment versionsrk_table (
SrkTable
) – SRK table of root certificates; must contain min 1, max 4 certificatessrc_key_index (
int
) – index of selected SRK key used for authentication, 0..srk_table.len - 1csf_cert (
bytes
) – CSF certificatecsf_priv_key (
PrivateKeyRsa
) – CSF private keyimg_cert (
bytes
) – IMG certificateimg_priv_key (
PrivateKeyRsa
) – IMG private key
- Raises:
SPSDKError – If invalid length of srk table
SPSDKError – If invalid index of srk table
SPSDKError – If application data is not present
- Return type:
None
- add_csf_standard_auth(version, srk_table, src_key_index, csf_cert, csf_priv_key, img_cert, img_priv_key)#
Add CSF with standard authentication.
Before calling, application image and address must be assigned
- Parameters:
version (
int
) – CSF segment versionsrk_table (
SrkTable
) – SRK table of root certificates; must contain min 1, max 4 certificatessrc_key_index (
int
) – index of selected SRK key used for authenticationcsf_cert (
bytes
) – CSF certificatecsf_priv_key (
PrivateKeyRsa
) – CSF private keyimg_cert (
bytes
) – IMG certificateimg_priv_key (
PrivateKeyRsa
) – IMG private key; decrypted binary data in PEM format
- Raises:
SPSDKError – If invalid length of srk table
SPSDKError – If invalid index of selected SRK key
SPSDKError – If application data not present
- Return type:
None
- add_dcd_bin(data)#
Add DCD binary data.
- Parameters:
data (
bytes
) – DCD binary data to be added- Raises:
SPSDKError – If DCD is already present
SPSDKError – If DCD is not enabled
- Return type:
None
- add_image(data, img_type=EnumAppType.APP, address=-1, dek_key=None, nonce=None)#
Add specific image into the main boot image.
- Parameters:
data (
bytes
) – Raw data of imgimg_type (
EnumAppType
) – value must be EnumAppType.APP, no other options supported in this classaddress (
int
) – start address of the application (entry point); Use -1 to detect the address from the imagedek_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 outputnonce (
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_offset: int#
- Returns:
offset in the binary image, where the application starts.
Please mind: the offset include FCB block (even the FCB block is not exported) The offset is 0x2000 for XIP images and 0x1000 for non-XIP images
- property bee: SegBEE#
- Returns:
BEE segment that contains configuration of encrypted XIP.
By default, BEE segment is empty. PRDB regions may be specified only for XIP images.
- property bee_encrypted: bool#
True if BEE encrypted XIP image (with SW keys); False otherwise; see also hab_encrypted.
- property decrypted_app_data: bytes#
Return decrypted binary application data.
Note: dek key, mac and nonce must be assigned for decryption :raises SPSDKError: If application not present :raises SPSDKError: If invalid length of application data :raises SPSDKError: If Mac or nonce or dek not present
- property dek_img_offset: int#
Offset of the DEK key in the image; -1 if DEK key address is available (see dek_ram_address).
- property dek_key: bytes | None#
DEK key for encrypted images; None for non-encrypted images.
- property dek_ram_address: int#
Address of the DEK key in the RAM memory retrieved from the corresponding command.
-1 if the image does not contain command for DEK key installation
- property enabled_csf: SegCSF | None#
Enabled Command Sequence File (CSF) segment; None if CSF is not defined or it is not enabled.
- export(zulu=datetime.datetime(2024, 4, 5, 10, 57, 5, 466765, tzinfo=datetime.timezone.utc))#
Export image as bytes array.
- Parameters:
zulu (
datetime
) – optional UTC datetime; should be used only if you need fixed datetime for the test Note: the parameter is applied to CSF only, so it is not used for unsigned images- Raises:
SPSDKError – If the image is not encrypted
SPSDKError – If padding is present
SPSDKError – If invalid alignment of application
- Return type:
bytes
- Returns:
bytes
- export_bee()#
Export BEE segment.
- Return type:
bytes
- Returns:
binary BEE segment
- Raises:
SPSDKError – if any BEE region is configured for images not located in the FLASH
- export_csf(data, zulu=datetime.datetime(2024, 4, 5, 10, 57, 5, 466759, tzinfo=datetime.timezone.utc))#
Export CSF segment.
- Parameters:
data (
bytes
) – generated binary data used for creating of signaturezulu (
datetime
) – current UTC datetime
- Return type:
bytes
- Returns:
binary CFD segment
- export_dcd()#
Export DCD segment.
- Return type:
bytes
- Returns:
binary DCD segment
- Raises:
SPSDKError – If DCD padding is not set
- export_fcb()#
Export FCB segment.
- Return type:
bytes
- Returns:
binary FCB segment
- Raises:
SPSDKError – If invalid length of data
- property fcb: AbstractFCB#
Flash Configuration(Control) Block, binary data; content depends on FLASH type.
- static get_app_offset(ivt_offset)#
- Return type:
int
- Returns:
offset in the binary image, where the application starts.
Please mind: the offset include FCB block (even the FCB block is not exported) The offset is 0x2000 for XIP images and 0x1000 for non-XIP images
- Parameters:
ivt_offset (
int
) – Offset of IVT segment
- property hab_encrypted: bool#
True if HAB encrypted; False otherwise; see also bee_encrypted.
- property ivt_offset: int#
Offset of the Image Vector Table (IVT) in the image.
- classmethod parse(stream, step=0, size=None)#
Parse bootable RT image from stream buffer or bytes array.
- Parameters:
stream (
Union
[bytes
,bytearray
,BufferedReader
,BytesIO
]) – The stream buffer or bytes arraystep (
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:
- Returns:
BootImgRT object
- property plugin: bool#
Flag whether it is plugin image type; It is not fully supported by SPSDK yet.
Plugin is designed to load a boot image from devices that are not natively supported by boot ROM.
- set_flexspi_fcb(data)#
Set FlexSPI external FLASH configuration.
- Parameters:
data (
Union
[bytes
,FlexSPIConfBlockFCB
]) – FlexSPIConfBlockFCB or binary data representing- Return type:
None
- set_xmcd(data)#
Sets the XMCD block.
- Return type:
None
- property size: int#
Size of the exported binary data.
Please mind, FCB is exported optionally, but it is always included in the size
- property version: int#
Version of the image format; must be from BootImgRT.VERSIONS.
- class spsdk.image.images.KernelImg(address=0, app=None, csf=None, version=65)#
Bases:
object
IMX Kernel Image.
Initialize the IMX Kernel Image.
- IMAGE_MIN_SIZE = 4096#
- property address: int#
Address.
- property app: bytes | None#
APP.
- export()#
Export.
- Return type:
bytes
- property version: int#
Version.
- spsdk.image.images.parse(stream, step=256, size=None)#
Common parser for all versions of i.MX boot images.
- Parameters:
stream (
Union
[bytes
,bytearray
,BufferedReader
,BytesIO
]) – stream buffer to imagestep (
int
) – Image searching stepsize (
Optional
[int
]) – parsing size
- Return type:
- Returns:
the object of boot image
- Raises:
SPSDKError – Raised when the format of string is incorrect
SPSDKError – When not i.MX Boot Image is passed
Image Commands#
Commands for image module.
- class spsdk.image.commands.CmdAuthData(flags=EnumAuthDat.CLR, key_index=1, sig_format=EnumCertFormat.CMS, engine=EnumEngine.ANY, engine_cfg=0, location=0, certificate=None, private_key=None, signature_provider=None)#
Bases:
CmdBase
Authenticate data command.
Initialize the Authenticate data command.
- append(start_address, size)#
Append of Authenticate data command.
- Return type:
None
- clear()#
Clear of Authenticate data command.
- Return type:
None
- property cmd_data_offset: int#
Offset of an additional data (such as signature or MAC, etc) in binary image.
- property cmd_data_reference: MAC | Signature | None#
Reference to an additional data (such as certificate, signature, etc).
None if no reference was assigned;
Value type is command-specific
- property engine: EnumEngine#
Engine.
- export()#
Export to binary form (serialization).
- Return type:
bytes
- Returns:
binary representation of the command
- property flags: EnumAuthDat#
Flag of Authenticate data command.
- property key_index: int#
Key index.
- property needs_cmd_data_reference: bool#
Whether the command contains a reference to an additional data.
- classmethod parse(data)#
Convert binary representation into command (deserialization from binary data).
- Parameters:
data (
bytes
) – being parsed- Return type:
Self
- Returns:
parse command
- parse_cmd_data(data)#
Parse additional command data from binary data.
- Parameters:
data (
bytes
) – to be parsed- Return type:
- 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
]
- 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+datedata (
bytes
) – currently generated binary database_data_addr (
int
) – base address of the generated data
- Raises:
ValueError – When certificate or private key are not assigned
ValueError – When signatures not assigned explicitly
SPSDKError – If incorrect start address
SPSDKError – If incorrect end address
SPSDKError – If incorrect length
- Return type:
bool
- Returns:
True if length of the signature was unchanged, as this may affect content of the CSF section (pointer to data);
- class spsdk.image.commands.CmdBase(tag, param, length=None)#
Bases:
BaseClass
Base class for all commands.
Constructor.
- Parameters:
tag (
CmdTag
) – command tagparam (
int
) – TODOlength (
Optional
[int
]) – of the binary command representation, in bytes
- property cmd_data_offset: int#
Offset of an additional data (such as certificate, signature, etc) in binary image.
- property cmd_data_reference: BaseSecretClass | None#
Reference to a command data (such as certificate, signature, etc).
None if no reference was assigned; Value type is command-specific
- export()#
Export to binary form (serialization).
- Return type:
bytes
- Returns:
binary representation of the command
- property needs_cmd_data_reference: bool#
Whether the command needs a reference to an additional data.
If returns True, the following methods must be implemented: - cmd_data_offset - cmd_data_reference
- classmethod parse(data)#
Convert binary representation into command (deserialization from binary data).
- Parameters:
data (
bytes
) – being parsed- Return type:
Self
- Returns:
parse command
- Raises:
NotImplementedError – Derived class has to implement this method
- parse_cmd_data(data)#
Parse additional command data from binary data.
- Parameters:
data (
bytes
) – to be parsed- Raises:
SPSDKError – If cmd_data is not supported by the command
- Return type:
Any
- property size: int#
Size of command.
- property tag: int#
Command tag.
- class spsdk.image.commands.CmdCheckData(numbytes=4, ops=EnumCheckOps.ALL_SET, address=0, mask=0, count=None)#
Bases:
CmdBase
Check data command.
Initialize the check data command.
- Parameters:
numbytes (
int
) – number of bytesops (
EnumCheckOps
) – type of operationaddress (
int
) – list of tuples: address and valuemask (
int
) – mask valuecount (
Optional
[int
]) – count value
- Raises:
SPSDKError – If incorrect number of bytes
SPSDKError – If incorrect operation
- export()#
Export to binary form (serialization).
- Return type:
bytes
- Returns:
binary representation of the command
- property num_bytes: int#
Number of bytes.
- property ops: EnumCheckOps#
Operation of Check data command.
- classmethod parse(data)#
Convert binary representation into command (deserialization from binary data).
- Parameters:
data (
bytes
) – being parsed- Return type:
Self
- Returns:
parse command
- class spsdk.image.commands.CmdInitialize(engine=EnumEngine.ANY, data=None)#
Bases:
CmdBase
Initialize command.
Initialize the initialize command.
- append(value)#
Appending of Initialize command.
- Raises:
SPSDKError – If value out of range
- Return type:
None
- clear()#
Clear of Initialize command.
- Return type:
None
- property engine: EnumEngine#
Engine.
- export()#
Export to binary form (serialization).
- Return type:
bytes
- Returns:
binary representation of the command
- classmethod parse(data)#
Convert binary representation into command (deserialization from binary data).
- Parameters:
data (
bytes
) – being parsed- Return type:
Self
- Returns:
parse command
- Raises:
SPSDKError – If incorrect length of data
- pop(index)#
Pop of Initialize command.
- Return type:
int
- Returns:
value from the index
- Raises:
SPSDKError – If incorrect length of data
- class spsdk.image.commands.CmdInstallKey(flags=EnumInsKey.CLR, cert_fmt=EnumCertFormat.SRK, hash_alg=EnumAlgorithm.ANY, src_index=0, tgt_index=0, location=0)#
Bases:
CmdBase
Install key command.
Constructor.
- Parameters:
flags (
EnumInsKey
) – from EnumInsKeycert_fmt (
EnumCertFormat
) – format of the certificate; key authentication protocolhash_alg (
EnumAlgorithm
) – hash algorithmsrc_index (
int
) – source key (verification key, KEK) indextgt_index (
int
) – target key indexlocation (
int
) – start address of an additional data such as KEY to be installed; Typically it is relative to CSF start; Might be absolute for DEK key
- property certificate_format: EnumCertFormat#
Certificate format.
- property certificate_ref: CertificateImg | SrkTable | None#
Corresponding certificate referenced by key-location.
- property cmd_data_offset: int#
Offset of an additional data (such as certificate, signature, etc) in binary image.
- property cmd_data_reference: CertificateImg | SrkTable | None#
Reference to an additional data (such as certificate, signature, etc).
None if no reference was assigned; Value type is command-specific
- export()#
Export to binary form (serialization).
- Return type:
bytes
- Returns:
binary representation of the command
- property flags: EnumInsKey#
Flags.
- property hash_algorithm: EnumAlgorithm#
Hash algorithm.
- property needs_cmd_data_reference: bool#
Whether the command contains a reference to an additional data.
- classmethod parse(data)#
Convert binary representation into command (deserialization from binary data).
- Parameters:
data (
bytes
) – being parsed- Return type:
Self
- Returns:
parse command
- parse_cmd_data(data)#
Parse additional command data from binary data.
- Parameters:
data (
bytes
) – to be parsed- Return type:
Union
[CertificateImg
,SrkTable
,None
]- Returns:
parsed data object; command-specific: certificate or SrkTable to be installed
- property source_index: int#
Source key (verification key, KEK) index.
For SRK, it is index of the SRK key (0-3)
For other keys it is index of previously installed target key, typically 0
- property target_index: int#
Target key index.
- class spsdk.image.commands.CmdNop(param=0)#
Bases:
CmdBase
Nop command.
Initialize the nop command.
- classmethod parse(data)#
Convert binary representation into command (deserialization from binary data).
- Parameters:
data (
bytes
) – being parsed- Return type:
Self
- Returns:
parse command
- class spsdk.image.commands.CmdSet(itm=EnumItm.ENG, hash_alg=EnumAlgorithm.ANY, engine=EnumEngine.ANY, engine_cfg=0)#
Bases:
CmdBase
Set command.
Initialize the set command.
- property engine: EnumEngine#
Engine plugin tags.
- export()#
Export to binary form (serialization).
- Return type:
bytes
- Returns:
binary representation of the command
- property hash_algorithm: EnumAlgorithm#
Type of hash algorithm.
- classmethod parse(data)#
Convert binary representation into command (deserialization from binary data).
- Parameters:
data (
bytes
) – being parsed- Return type:
Self
- Returns:
parse command
- class spsdk.image.commands.CmdUnlock(engine=EnumEngine.ANY, features=0, uid=0)#
Bases:
CmdUnlockAbstract
Generic unlock engine command.
Constructor.
- Parameters:
engine (
EnumEngine
) – to be unlockedfeatures (
int
) – mask of features to use by the engineuid (
int
) – Unique ID (if needed)
- class spsdk.image.commands.CmdUnlockAbstract(engine=EnumEngine.ANY, features=0, uid=0)#
Bases:
CmdBase
,ABC
Abstract unlock engine command; the command depends on engine type.
Constructor.
- Parameters:
engine (
EnumEngine
) – to be unlockedfeatures (
int
) – engine specific featuresuid (
int
) – Unique ID required by some engine/feature combinations
- property engine: EnumEngine#
Engine to be unlocked.
The term engine denotes a peripheral involved in one or more of the following functions: - cryptographic computation - security state management - security alarm handling - access control
- export()#
Export to binary form (serialization).
- Return type:
bytes
- Returns:
binary representation of the command
- static need_uid(engine, features)#
Return True if given Engine and Feature requires UID.
- Return type:
bool
- classmethod parse(data)#
Convert binary representation into command (deserialization from binary data).
- Parameters:
data (
bytes
) – being parsed- Return type:
Self
- Returns:
Unlock command
- class spsdk.image.commands.CmdUnlockCAAM(features=0)#
Bases:
CmdUnlockAbstract
Command Unlock for Cryptographic Acceleration and Assurance Module .
Initialize.
- Parameters:
features (
int
) – mask of FEATURE_UNLOCK_x constants, defaults to 0
- FEATURE_UNLOCK_MFG = 4#
- FEATURE_UNLOCK_MID = 1#
- FEATURE_UNLOCK_RNG = 2#
- property unlock_mfg: bool#
Leave Zero is able Master Key write unlocked.
- property unlock_mid: bool#
Leave Job Ring and DECO master ID registers unlocked.
- property unlock_rng: bool#
Leave RNG un-instantiated.
- class spsdk.image.commands.CmdUnlockOCOTP(features=0, uid=0)#
Bases:
CmdUnlockAbstract
Command Unlock for On-Chip One-time programable memory (fuses).
Initialize.
- Parameters:
features (
int
) – mask of FEATURE_UNLOCK_x constants, defaults to 0uid (
int
) – Unique ID required by some engine/feature combinations
- FEATURE_UNLOCK_FLD_RTN = 1#
- FEATURE_UNLOCK_JTAG = 8#
- FEATURE_UNLOCK_SCS = 4#
- FEATURE_UNLOCK_SRK_RVK = 2#
- property unlock_csc: bool#
Leave SCS register unlocked.
- property unlock_fld_rtn: bool#
Leave Field Return activation unlocked.
- property unlock_jtag: bool#
Unlock JTAG using SCS HAB_JDE bit.
- property unlock_srk_rvk: bool#
Leave SRK revocation unlocked.
- class spsdk.image.commands.CmdUnlockSNVS(features=0)#
Bases:
CmdUnlockAbstract
Command Unlock Secure Non-Volatile Storage (SNVS) Engine.
Constructor.
- Parameters:
features (
int
) – mask of FEATURE_UNLOCK_* constants
- FEATURE_UNLOCK_LP_SWR = 1#
- FEATURE_UNLOCK_ZMK_WRITE = 2#
- property unlock_lp_swr: bool#
Leave LP SW reset unlocked.
- property unlock_zmk_write: bool#
Leave Zero is able Master Key write unlocked.
- class spsdk.image.commands.CmdWriteData(numbytes=4, ops=EnumWriteOps.WRITE_VALUE, data=None)#
Bases:
CmdBase
Write data command.
Initialize Write Data command.
- Parameters:
numbytes (
int
) – number of bytes. Must be value: 1, 2 or 4ops (
EnumWriteOps
) – type of write operationdata (
Optional
[Iterable
[Tuple
[int
,int
]]]) – list of tuples: address and value
- Raises:
SPSDKError – When incorrect number of bytes
SPSDKError – When incorrect type of operation
- append(address, value)#
Append of Write data command.
- Return type:
None
- clear()#
Clear of Write data command.
- Return type:
None
- export()#
Export to binary form (serialization).
- Return type:
bytes
- Returns:
binary representation of the command
- property num_bytes: int#
Number of bytes being written by the command.
- property ops: EnumWriteOps#
Type of write operation.
- classmethod parse(data)#
Convert binary representation into command (deserialization from binary data).
- Parameters:
data (
bytes
) – being parsed- Return type:
Self
- Returns:
parse command
- pop(index)#
Pop of Write data command.
- Return type:
List
[int
]
- class spsdk.image.commands.EnumAuthDat(tag, label, description=None)#
Bases:
SpsdkEnum
Flags for Authenticate Data commands.
- ABS = (1, 'ABS', 'Absolute signature address')#
- CLR = (0, 'CLR', 'No flags set')#
- class spsdk.image.commands.EnumCAAM(tag, label, description=None)#
Bases:
SpsdkEnum
CAAM Engine Configuration.
- DEFAULT = (0, 'DEFAULT')#
- DSC_SWAP16 = (128, 'DSC_SWAP16')#
- DSC_SWAP8 = (64, 'DSC_SWAP8')#
- IN_SWAP16 = (2, 'IN_SWAP16')#
- IN_SWAP8 = (1, 'IN_SWAP8')#
- OUT_SWAP16 = (16, 'OUT_SWAP16')#
- OUT_SWAP8 = (8, 'OUT_SWAP8')#
- class spsdk.image.commands.EnumCertFormat(tag, label, description=None)#
Bases:
SpsdkEnum
Certificate format tags.
- AEAD = (163, 'AEAD', 'Proprietary AEAD MAC format')#
- BLOB = (187, 'BLOB', 'SHW-specific wrapped key format')#
- CMS = (197, 'CMS', 'CMS/PKCS#7 signature format')#
- SRK = (3, 'SRK', 'SRK certificate format')#
- X509 = (9, 'X509', 'X.509v3 certificate format')#
- class spsdk.image.commands.EnumCheckOps(tag, label, description=None)#
Bases:
SpsdkEnum
Enum definition for ‘par’ parameter of Check Data command.
- ALL_CLEAR = (0, 'ALL_CLEAR', 'All bits clear')#
- ALL_SET = (1, 'ALL_SET', 'All bits set')#
- ANY_CLEAR = (2, 'ANY_CLEAR', 'Any bit clear')#
- ANY_SET = (3, 'ANY_SET', 'Any bit set')#
- class spsdk.image.commands.EnumEngine(tag, label, description=None)#
Bases:
SpsdkEnum
Engine plugin tags.
- ANY = (0, 'ANY', 'First compatible engine will be selected (no engine configuration parameters are allowed)')#
- CAAM = (29, 'CAAM', 'Cryptographic Acceleration and Assurance Module')#
- CSU = (10, 'CSU', 'Central Security Unit')#
- DCP = (27, 'DCP', 'Data Co-Processor')#
- DTCP = (34, 'DTCP', 'DTCP co-processor')#
- HDCP = (36, 'HDCP', 'HDCP co-processor')#
- OCOTP = (33, 'OCOTP', 'Fuse controller')#
- ROM = (54, 'ROM', 'Protected ROM area')#
- RTIC = (5, 'RTIC', 'Run-time integrity checker')#
- SAHARA = (6, 'SAHARA', 'Crypto accelerator')#
- SCC = (3, 'ANY', 'Security controller')#
- SNVS = (30, 'SNVS', 'Secure Non-Volatile Storage')#
- SRTC = (12, 'SRTC', 'Secure clock')#
- SW = (255, 'SW', 'Software engine')#
- class spsdk.image.commands.EnumInsKey(tag, label, description=None)#
Bases:
SpsdkEnum
Flags for Install Key commands.
- ABS = (1, 'ABS', 'Absolute certificate address')#
- CFG = (8, 'CFG', 'Key binds to Configuration')#
- CID = (64, 'CID', 'Key binds to Caller ID')#
- CLR = (0, 'CLR', 'No flags set')#
- CSF = (2, 'CSF', 'Install CSF key')#
- DAT = (4, 'DAT', 'Key binds to Data Type')#
- FID = (16, 'FID', 'Key binds to Fabrication UID')#
- HSH = (128, 'HSH', 'Certificate hash present')#
- MID = (32, 'MID', 'Key binds to Manufacturing ID')#
- class spsdk.image.commands.EnumItm(tag, label, description=None)#
Bases:
SpsdkEnum
Engine configuration flags of Set command.
- ENG = (3, 'ENG', 'Preferred engine for a given algorithm')#
- MID = (1, 'MID', 'Manufacturing ID (MID) fuse locations')#
- class spsdk.image.commands.EnumWriteOps(tag, label, description=None)#
Bases:
SpsdkEnum
Enum definition for ‘flags’ control flags in ‘par’ parameter of Write Data command.
- CLEAR_BITMASK = (2, 'CLEAR_BITMASK', 'Clear bitmask')#
- SET_BITMASK = (3, 'SET_BITMASK', 'Set bitmask')#
- WRITE_CLEAR_BITS = (1, 'WRITE_CLEAR_BITS', 'Write clear bits')#
- WRITE_VALUE = (0, 'WRITE_VALUE', 'Write value')#
- exception spsdk.image.commands.ExpectedSignatureOrMACError(desc=None)#
Bases:
SPSDKError
CmdAuthData additional data block: expected Signature or MAC object.
Initialize the base SPSDK Exception.
- spsdk.image.commands.parse_command(data)#
Parse CSF/DCD command.
- Parameters:
data (
bytes
) – binary data to be parsed- Return type:
- Returns:
instance of the command
- Raises:
SPSDKError – If the command is not valid
Image Headers#
Header.
- class spsdk.image.header.CmdHeader(tag, param=0, length=None)#
Bases:
Header
Command header.
Constructor.
- Parameters:
tag (
Union
[CmdTag
,int
]) – command tagparam (
int
) – TODOlength (
Optional
[int
]) – of the command binary section, in bytes
- Raises:
SPSDKError – If invalid command tag
- classmethod parse(data, required_tag=None)#
Create Header from binary data.
- Parameters:
data (
bytes
) – binary data to convert into headerrequired_tag (
Optional
[int
]) – CmdTag, None if not required
- Return type:
Self
- Returns:
parsed instance
- Raises:
SPSDKParsingError – If required header tag does not match
SPSDKError – If invalid tag
- property tag: int#
Command tag.
- class spsdk.image.header.CmdTag(tag, label, description=None)#
Bases:
SpsdkEnum
CSF/DCD Command Tag.
- AUT_DAT = (202, 'AUT_DAT', 'Authenticate Data')#
- CHK_DAT = (207, 'CHK_DAT', 'Check Data')#
- INIT = (180, 'INIT', 'Initialize')#
- INS_KEY = (190, 'INS_KEY', 'Install Key')#
- NOP = (192, 'NOP', 'No Operation (NOP)')#
- SET = (177, 'SET', 'Set')#
- UNLK = (178, 'UNLK', 'Unlock')#
- WRT_DAT = (204, 'WRT_DAT', 'Write Data')#
- class spsdk.image.header.Header(tag=0, param=0, length=None)#
Bases:
BaseClass
Header element type.
Constructor.
- Parameters:
tag (
int
) – section tagparam (
int
) – TODOlength (
Optional
[int
]) – length of the segment or command; if not specified, size of the header is used
- Raises:
SPSDKError – If invalid length
- FORMAT = '>BHB'#
- SIZE = 4#
- export()#
Binary representation of the header.
- Return type:
bytes
- classmethod parse(data, required_tag=None)#
Parse header.
- Parameters:
data (
bytes
) – Raw data as bytes or bytearrayrequired_tag (
Optional
[int
]) – Check header TAG if specified value or ignore if is None
- Return type:
Self
- Returns:
Header object
- Raises:
SPSDKParsingError – if required header tag does not match
- property size: int#
Header size in bytes.
- property tag: int#
- Returns:
section tag: command tag or segment tag, …
- property tag_name: str#
Returns the header’s tag name.
- class spsdk.image.header.Header2(tag=0, param=0, length=None)#
Bases:
Header
Header element type.
Constructor.
- Parameters:
tag (
int
) – section tagparam (
int
) – TODOlength (
Optional
[int
]) – length of the segment or command; if not specified, size of the header is used
- Raises:
SPSDKError – If invalid length
- FORMAT = '<BHB'#
- export()#
Binary representation of the header.
- Return type:
bytes
- classmethod parse(data, required_tag=None)#
Parse header.
- Parameters:
data (
bytes
) – Raw data as bytes or bytearrayrequired_tag (
Optional
[int
]) – Check header TAG if specified value or ignore if is None
- Raises:
SPSDKParsingError – Raises an error if required tag is empty or not valid
- Return type:
Self
- Returns:
Header2 object
- class spsdk.image.header.SegTag(tag, label, description=None)#
Bases:
SpsdkEnum
Segments Tag.
- BIC1 = (135, 'BIC1', 'Boot Images Container')#
- CRT = (215, 'CRT', 'Certificate')#
- CSF = (212, 'CSF', 'Command Sequence File Data')#
- DCD = (210, 'DCD', 'Device Configuration Data')#
- EVT = (219, 'EVT', 'Event')#
- IVT2 = (209, 'IVT2', 'Image Vector Table (Version 2)')#
- IVT3 = (222, 'IVT3', 'Image Vector Table (Version 3)')#
- MAC = (172, 'MAC', 'Message Authentication Code')#
- RVT = (221, 'RVT', 'ROM Vector Table')#
- SIG = (216, 'SIG', 'Signature')#
- SIGB = (144, 'SIGB', 'Signature block')#
- WRP = (129, 'WRP', 'Wrapped Key')#
- XMCD = (192, 'XMCD', 'External Memory Configuration Data')#
Secret Module#
Commands and responses used by SDP module.
- class spsdk.image.secret.BaseSecretClass(tag, version=64)#
Bases:
BaseClass
Base SPSDK class.
Constructor.
- Parameters:
tag (
SegTag
) – section TAGversion (
int
) – format version
- property size: int#
Size of the exported binary data.
- Raises:
NotImplementedError – Derived class has to implement this method
- property version: int#
Format version.
- property version_major: int#
Major format version.
- property version_minor: int#
Minor format version.
- class spsdk.image.secret.CertificateImg(version=64, data=None)#
Bases:
BaseSecretClass
Certificate structure for bootable image.
Initialize the certificate structure for bootable image.
- export()#
Export.
- Return type:
bytes
- classmethod parse(data)#
Parse.
- Return type:
Self
- property size: int#
Size of Certificate structure for bootable image.
- class spsdk.image.secret.EnumAlgorithm(tag, label, description=None)#
Bases:
SpsdkEnum
Algorithm types.
- AES = (85, 'AES', 'AES algorithm ID')#
- ANY = (0, 'ANY', 'Algorithm type ANY')#
- BLOB = (113, 'BLOB', 'SHW-specific key wrap')#
- CCM = (102, 'CCM', 'Counter with CBC-MAC')#
- CIPHER = (5, 'CIPHER', 'Cipher algorithm type')#
- EC = (4, 'EC', 'Elliptic curve arithmetic')#
- ECDSA = (39, 'ECDSA', 'NIST ECDSA signature algorithm')#
- F = (3, 'F', 'Finite field arithmetic')#
- HASH = (1, 'HASH', 'Hash algorithm type')#
- MODE = (6, 'MODE', 'Cipher/hash modes')#
- PKCS1 = (33, 'PKCS1', 'PKCS#1 RSA signature algorithm')#
- SHA1 = (17, 'SHA1', 'SHA-1 algorithm ID')#
- SHA256 = (23, 'SHA256', 'SHA-256 algorithm ID')#
- SHA512 = (27, 'SHA512', 'SHA-512 algorithm ID')#
- SIG = (2, 'SIG', 'Signature algorithm type')#
- WRAP = (7, 'WRAP', 'Key wrap algorithm type')#
- class spsdk.image.secret.EnumSRK(tag, label, description=None)#
Bases:
SpsdkEnum
Entry type in the System Root Key Table.
- KEY_HASH = (238, 'KEY_HASH', 'Any key: hash only')#
- KEY_PUBLIC = (225, 'KEY_PUBLIC', 'Public key type: data present')#
- class spsdk.image.secret.MAC(version=64, nonce_len=0, mac_len=16, data=None)#
Bases:
BaseSecretClass
Structure that holds initial parameter for AES encryption/decryption.
nonce - initialization vector for AEAD AES128 decryption
mac - message authentication code to verify the decryption was successful
Constructor.
- Parameters:
version (
int
) – format version, should be 0x4xnonce_len (
int
) – number of NONCE bytesmac_len (
int
) – number of MAC bytesdata (
Optional
[bytes
]) – nonce and mac bytes joined together
- AES128_BLK_LEN = 16#
- property data: bytes#
NONCE and MAC bytes joined together.
- export()#
Export instance into binary form (serialization).
- Return type:
bytes
- Returns:
binary form
- property mac: bytes#
MAC bytes for the encryption/decryption.
- property nonce: bytes#
NONCE bytes for the encryption/decryption.
- classmethod parse(data)#
Parse binary data and creates the instance (deserialization).
- Parameters:
data (
bytes
) – being parsed- Return type:
Self
- Returns:
the instance
- property size: int#
Size of binary representation in bytes.
- update_aead_encryption_params(nonce, mac)#
Update AEAD encryption parameters for encrypted image.
- Parameters:
nonce (
bytes
) – initialization vector, length depends on image size,mac (
bytes
) – message authentication code used to authenticate decrypted data, 16 bytes
- Raises:
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:
SRKException
This SRK public key algorithm is not yet implemented.
Initialize the base SPSDK Exception.
- exception spsdk.image.secret.NotImplementedSRKItem(desc=None)#
Bases:
SRKException
This type of SRK table item is not implemented.
Initialize the base SPSDK Exception.
- exception spsdk.image.secret.NotImplementedSRKPublicKeyType(desc=None)#
Bases:
SRKException
This SRK public key algorithm is not yet implemented.
Initialize the base SPSDK Exception.
- exception spsdk.image.secret.SRKException(desc=None)#
Bases:
SPSDKError
SRK table processing exceptions.
Initialize the base SPSDK Exception.
- class spsdk.image.secret.SecretKeyBlob(mode, algorithm, flag)#
Bases:
object
Secret Key Blob.
Initialize Secret Key Blob.
- property blob: bytes#
Data of Secret Key Blob.
- export()#
Export of Secret Key Blob.
- Return type:
bytes
- classmethod parse(data)#
Parse of Secret Key Blob.
- Return type:
Self
- property size: int#
Size of Secret Key Blob.
- class spsdk.image.secret.Signature(version=64, data=None)#
Bases:
BaseSecretClass
Class representing a signature.
Initialize the signature.
- property data: bytes#
Signature data.
- export()#
Export.
- Return type:
bytes
- classmethod parse(data)#
Parse.
- Return type:
Self
- property size: int#
Size of a signature.
- class spsdk.image.secret.SrkItem#
Bases:
object
Base class for items in the SRK Table, see SrkTable class.
We do not inherit from BaseClass because our header parameter is an algorithm identifier, not a version number.
- export()#
Serialization to binary form.
- Return type:
bytes
- Returns:
binary representation of the instance
- Raises:
NotImplementedError – Derived class has to implement this method
- classmethod from_certificate(cert)#
Pick up the right implementation of an SRK item.
- Return type:
- 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:
- classmethod parse(data)#
Pick up the right implementation of an SRK item.
- Parameters:
data (
bytes
) – The bytes array of SRK segment- Return type:
Self
- Returns:
SrkItem: One of the SrkItem subclasses
- Raises:
NotImplementedSRKPublicKeyType – Unsupported key algorithm
NotImplementedSRKItem – Unsupported tag
- sha256()#
Export SHA256 hash of the original data.
- Raises:
NotImplementedError – Derived class has to implement this method
- Return type:
bytes
- property size: int#
Size of the exported binary data.
- Raises:
NotImplementedError – Derived class has to implement this method
- class spsdk.image.secret.SrkItemEcc(key_size, x_coordinate, y_coordinate, flag=0)#
Bases:
SrkItem
ECC public key in SRK Table, see SrkTable class.
Initialize the srk table item.
- ECC_KEY_TYPE = {EccCurve.SECP256R1: 75, EccCurve.SECP384R1: 77, EccCurve.SECP521R1: 78}#
- property algorithm: int#
Algorithm.
- export()#
Export.
- Return type:
bytes
- property flag: int#
Flag.
- classmethod from_certificate(cert)#
Create SrkItemEcc from certificate.
- Return type:
- hashed_entry()#
This SRK item should be replaced with an incomplete entry with its digest.
- Return type:
- classmethod parse(data)#
Parse SRK table item data.
- Parameters:
data (
bytes
) – The bytes array of SRK segment- Return type:
Self
- Returns:
SrkItemEcc: SrkItemEcc object
- sha256()#
Export SHA256 hash of the data.
- Return type:
bytes
- property size: int#
Size of an SRK item.
- class spsdk.image.secret.SrkItemHash(algorithm, digest)#
Bases:
SrkItem
Hashed stub of some public key.
This is a valid entry of the SRK table, it represents some public key of unknown algorithm. Can only provide its hashed value of itself.
Build the stub entry with public key hash only.
- Parameters:
algorithm (
int
) – int: Hash algorithm, only SHA256 nowdigest (
bytes
) – bytes: Hash digest value
- Raises:
SPSDKError – If incorrect algorithm
- property algorithm: int#
Hashing algorithm used.
- export()#
Export.
- Return type:
bytes
- hashed_entry()#
This SRK item should be replaced with an incomplete entry with its digest.
- Return type:
- classmethod parse(data)#
Parse SRK table item data.
- Parameters:
data (
bytes
) – The bytes array of SRK segment- Return type:
Self
- Returns:
SrkItemHash: SrkItemHash object
- Raises:
NotImplementedSRKItem – Unknown tag
- sha256()#
Export SHA256 hash of the original data.
- Return type:
bytes
- property size: int#
Size of an SRK item.
- class spsdk.image.secret.SrkItemRSA(modulus, exponent, flag=0)#
Bases:
SrkItem
RSA public key in SRK Table, see SrkTable class.
Initialize the srk table item.
- property algorithm: int#
Algorithm.
- export()#
Export.
- Return type:
bytes
- property flag: int#
Flag.
- classmethod from_certificate(cert)#
Create SRKItemRSA from certificate.
- Return type:
- hashed_entry()#
This SRK item should be replaced with an incomplete entry with its digest.
- Return type:
- property key_length: int#
Key length of Item in SRK Table.
- classmethod parse(data)#
Parse SRK table item data.
- Parameters:
data (
bytes
) – The bytes array of SRK segment- Return type:
Self
- Returns:
SrkItemRSA: SrkItemRSA object
- sha256()#
Export SHA256 hash of the data.
- Return type:
bytes
- property size: int#
Size of an SRK item.
- class spsdk.image.secret.SrkTable(version=64)#
Bases:
BaseSecretClass
SRK table.
Initialize SRT Table.
- Parameters:
version (
int
) – format version
- export()#
Export into binary form (serialization).
- Return type:
bytes
- Returns:
binary representation of the instance
- export_fuses()#
SRK items in binary form, see SRK_fuses.bin file.
- Return type:
bytes
- get_fuse(index)#
Retrieve fuse value for the given index.
- Parameters:
index (
int
) – of the fuse, 0-7- Return type:
int
- Returns:
value of the specified fuse; the value is in format, that cane be used as parameter for SDP efuse_read_once or efuse_write_once
- Raises:
SPSDKError – If incorrect index of the fuse
SPSDKError – If incorrect length of SRK items
- classmethod parse(data)#
Parse of SRK table.
- Return type:
Self
- property size: int#
Size of SRK table.
Data Segments#
Segments within image module.
- class spsdk.image.segments.AbstractFCB#
Bases:
BaseSegment
Abstract class, predecessor for all FCB classes.
Constructor.
- TAG = b'FCB'#
- property enabled: bool#
Whether FCB is enabled. Note: it is not generated to output if disabled.
- export()#
Export to binary representation (serialization).
- Return type:
bytes
- Returns:
binary representation
- Raises:
NotImplementedError – Derived class has to implement this method
- property space: int#
Return length (in bytes) of the exported data including padding (if any).
- class spsdk.image.segments.BaseSegment#
Bases:
ABC
Base segment.
Initialize the base segment.
- PADDING_VALUE = 0#
- export()#
Export interface.
- Raises:
NotImplementedError – Derived class has to implement this method
- Return type:
bytes
- property padding_len: int#
Length of padding data in bytes (zero for no padding).
- classmethod parse(data)#
Parse interfaces.
- Raises:
NotImplementedError – Derived class has to implement this method
- Return type:
Self
- property size: int#
Size of base segment.
- property space: int#
Return length (in bytes) of the exported data including padding (if any).
Please mind, padding is exported optionally.
- class spsdk.image.segments.FlexSPIConfBlockFCB#
Bases:
AbstractFCB
Flex SPI configuration block; FCB.
Initialize FlexSPIConfBlockFCB.
- FORMAT = '<6BH7I5I4B2I4I6I4H'#
- TAG = b'FCFB'#
- VERSION = b'V\x01\x00\x00'#
- export()#
Export into binary form.
- Return type:
bytes
- Returns:
binary representation used in the bootable image
- export_header()#
Export FCB header info binary form.
- Return type:
bytes
- classmethod parse(data)#
Parse binary data and creates instance of the class.
- Parameters:
data (
bytes
) – data to be parsed- Return type:
Self
- Returns:
instance of the class representing the data
- Raises:
SPSDKError – If data are not valid Flex SPI configuration block
- property size: int#
Length of the binary exported data without padding.
- class spsdk.image.segments.PaddingFCB(size, padding_value=0, enabled=True)#
Bases:
AbstractFCB
Padding FCB.
Constructor.
- Parameters:
size (
int
) – of the exported paddingpadding_value (
int
) – byte value used as padding; 0 by defaultenabled (
bool
) – whether enabled
- Raises:
SPSDKError – If invalid size of the exported padding
SPSDKError – If invalid padding
- export()#
Export to binary form (serialization).
- Return type:
bytes
- Returns:
binary representation
- property size: int#
Return size of the exported data in bytes.
- class spsdk.image.segments.SegAPP(data=None)#
Bases:
BaseSegment
APP segment.
Initialize APP segment.
- Parameters:
data (
Optional
[bytes
]) – application binary data
- property data: bytes | None#
Application binary data.
- export()#
Export segment as bytes array.
- Return type:
bytes
- Returns:
bytes
- property size: int#
Size of APP segment.
- class spsdk.image.segments.SegBDS3a#
Bases:
BaseSegment
BDS3a segment.
Initialize BDS3a segment.
- FORMAT = '<4L'#
- HEADER_SIZE = 16#
- IMAGES_MAX_COUNT = 6#
- SIZE = 256#
- export()#
Export segment as bytes array.
- Return type:
bytes
- Returns:
bytes
- property header_size: int#
Header’s size of BDS3a segment.
- classmethod parse(data)#
Parse segment from bytes array.
- Parameters:
data (
bytes
) – The bytes array of BDS3a segment- Return type:
Self
- Returns:
SegBDS3a object
- property size: int#
Size of BDS3a segment.
- class spsdk.image.segments.SegBDS3b#
Bases:
BaseSegment
BDS3b segment.
Initialize BDS3b segment.
- FORMAT = '<4L'#
- HEADER_SIZE = 16#
- IMAGES_MAX_COUNT = 4#
- SIZE = 240#
- export()#
Export segment as bytes array.
- Return type:
bytes
- Returns:
bytes
- property header_size: int#
Size of header of BDS3b segment.
- classmethod parse(data)#
Parse segment from bytes array.
- Parameters:
data (
bytes
) – The bytes array of BDS3b segment- Return type:
Self
- Returns:
SegBDS3b object
- property size: int#
Size of BDS3b segment.
- class spsdk.image.segments.SegBDT(app_start=0, app_length=0, plugin=0)#
Bases:
BaseSegment
Boot Data Table segment.
Initialize BDT segment.
- Parameters:
app_start (
int
) – first address of the applicationapp_length (
int
) – length of the applicationplugin (
int
) – 0 .. 2
- FORMAT = '<3L'#
- SIZE = 12#
- export()#
Export segment as bytes array.
- Return type:
bytes
- Returns:
bytes
- classmethod parse(data)#
Parse segment from bytes array.
- Parameters:
data (
bytes
) – The bytes array of BDT segment- Return type:
Self
- Returns:
SegBDT object
- property plugin: int#
Plugin.
- property size: int#
Size of the exported binary data (without padding).
- class spsdk.image.segments.SegBEE(regions, max_facs=3)#
Bases:
BaseSegment
BEE keys and regions segment.
Constructor.
- Parameters:
regions (
Sequence
[BeeRegionHeader
]) – list of regionsmax_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 sizedata (
bytes
) – to be encrypted
- Return type:
bytes
- Returns:
encrypted data, aligned to block size; blocks outside any FAC region kept untouched
- Raises:
SPSDKError – If invalid start address
- export()#
Serialization to binary representation.
- Return type:
bytes
- Returns:
binary representation of the region (serialization).
- classmethod parse(data, decrypt_keys=None)#
De-serialization.
- Parameters:
data (
bytes
) – binary data to be parseddecrypt_keys (
Optional
[List
[bytes
]]) – list of SW_GP keys used to decrypt EKIB The number of keys must match number of regions to be parsed
- Return type:
Self
- Returns:
instance created from binary data
- property size: int#
- Returns:
size of the exported binary data in bytes.
- update()#
Updates internal fields of the instance.
- Return type:
None
- validate()#
Validates settings of the instance.
- Raises:
SPSDKError – If number of FAC regions exceeds the limit
- Return type:
None
- class spsdk.image.segments.SegBIC1(version=0)#
Bases:
BaseSegment
Boot Images Container segment.
Initialize Boot Images Container segment.
- Parameters:
version (
int
) – The version of Header for Boot Images Container
- FORMAT = '<LH2B2H'#
- MAX_NUM_IMGS = 6#
- SIZE = 808#
- export()#
Export segment as bytes array.
- Return type:
bytes
- Returns:
bytes
- classmethod parse(data)#
Parse segment from bytes array.
- Parameters:
data (
bytes
) – The bytes array of BIC1 segment- Return type:
Self
- Returns:
SegBIC1 object
- property size: int#
Size.
- validate()#
Validate segment.
- Return type:
None
- property version: int#
Version of Boot Images Container segment.
- class spsdk.image.segments.SegBIM#
Bases:
BaseSegment
BootImage segment.
Initialize BootImage segment.
- FORMAT = '<2L2Q2L'#
- SIZE = 128#
- export()#
Export segment as bytes array.
- Return type:
bytes
- Returns:
bytes
- classmethod parse(data)#
Parse segment from bytes array.
- Parameters:
data (
bytes
) – The bytes array of BootImage segment- Return type:
Self
- Returns:
SegBootImage object
- property size: int#
Size of BootImage segment.
- class spsdk.image.segments.SegCSF(version=64, enabled=False)#
Bases:
BaseSegment
Command Sequence File (CSF), signature block for Secure Boot.
A script of commands used to guide image authentication and device configuration operations.
Initialize CSF segment.
- append_command(cmd)#
Append CSF command to the segment.
- Parameters:
cmd (
CmdBase
) – to be added- Raises:
SPSDKError – If invalid command
- Return type:
None
- clear_commands()#
Removes= all commands.
- Return type:
None
- export()#
Export segment as bytes array (serialization).
- Return type:
bytes
- Returns:
bytes
- classmethod parse(data)#
Parse segment from bytes array.
- Parameters:
data (
bytes
) – The bytes array of CSF segment- Raises:
SPSDKCorruptedException – When there is unknown command
SPSDKCorruptedException – When command can not be parsed
- Return type:
Self
- Returns:
SegCSF instance
- property size: int#
Size of the binary representation of the segment; 0 is not enabled.
- property space: int#
Size of the binary representation of the segment including padding; 0 is not enabled.
- update(reset_cmddata_offsets)#
Update the offsets for the export.
- Parameters:
reset_cmddata_offsets (
bool
) – True to reset all cmd-data offsets, if cmd-data not specified in the command; False to avoid any reset; Note: reset should be done during parsing process as the data are incomplete- Return type:
None
- update_signatures(zulu, data, base_data_addr)#
Update signatures in all CmdAuthData commands.
- Parameters:
zulu (
datetime
) – current UTC time+datedata (
bytes
) – currently generated binary data; empty to create “fake” signature to update size of the segmentbase_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.
- class spsdk.image.segments.SegDCD(param=65, enabled=False)#
Bases:
BaseSegment
Device configuration data (DCD) segment.
IC configuration data, usually is used to configure DDR/SDRAM memory. Typically this is optional
Initialize DCD segment.
- append(cmd)#
Appending of Device configuration data (DCD) segment.
- Return type:
None
- clear()#
Clear of Device configuration data (DCD) segment.
- Return type:
None
- 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
- classmethod parse(data)#
Parse segment from bytes array.
- Parameters:
data (
bytes
) – The bytes array of DCD segment- Raises:
SPSDKCorruptedException – Exception caused by corrupted data
- Return type:
Self
- Returns:
SegDCD object
- classmethod parse_txt(text)#
Parse segment from text file.
- Parameters:
text (
str
) – The string with DCD commands- Return type:
- Returns:
SegDCD object
- property size: int#
Size of Device configuration data (DCD) segment.
- property space: int#
Add space.
- class spsdk.image.segments.SegDcdBuilder#
Bases:
object
Builder to create SegDCD from text input.
Initialize SegDcdBuilder.
- class spsdk.image.segments.SegFCB#
Bases:
AbstractFCB
,ABC
FCB.
Initialize FCB segment.
- FINGERPRINT = b'NFCB'#
- SIZE = 1024#
- property crc: int#
Cyclic redundancy check.
- export()#
Export to binary form.
- Return type:
bytes
- class spsdk.image.segments.SegIDS3a#
Bases:
BaseSegment
IDS3a segment.
Initialize IDS3a segment.
- FORMAT = '<3Q4L'#
- SIZE = 40#
- export()#
Export segment as bytes array.
- Return type:
bytes
- Returns:
bytes
- classmethod parse(data)#
Parse segment from bytes array.
- Parameters:
data (
bytes
) – The bytes array of IDS3a segment- Return type:
Self
- Returns:
SegIDS3a object
- property size: int#
Size of IDS3a segment.
- class spsdk.image.segments.SegIDS3b#
Bases:
BaseSegment
IDS3b segment.
Initialize IDS3b segment.
- FORMAT = '<3Q2L'#
- SIZE = 32#
- export()#
Export segment as bytes array.
- Return type:
bytes
- Returns:
bytes
- classmethod parse(data)#
Parse segment from bytes array.
- Parameters:
data (
bytes
) – The bytes array of IDS3b segment- Return type:
Self
- Returns:
SegIDS3b object
- property size: int#
Size of IDS3b segment.
- class spsdk.image.segments.SegIVT2(version)#
Bases:
BaseSegment
Image Vector Table, IVT2 segment.
Initialize IVT2 segment.
- Parameters:
version (
int
) – The version of IVT and Image format
- FORMAT = '<7L'#
- SIZE = 32#
- export()#
Export to binary representation (serialization).
- Return type:
bytes
- Returns:
segment exported as binary data
- classmethod parse(data)#
Parse segment from bytes array.
- Parameters:
data (
bytes
) – The bytes array of IVT2 segment- Return type:
Self
- Returns:
SegIVT2 object
- property size: int#
Size of the binary data.
- validate()#
Validate settings of the segment.
- Raises:
SPSDKError – If there is configuration problem
- Return type:
None
- property version: int#
The version of IVT and Image format.
- class spsdk.image.segments.SegIVT3a(param)#
Bases:
BaseSegment
IVT3a segment.
Initialize IVT segment.
- Parameters:
param (
int
) – The version of IVT and Image format
- FORMAT = '<1L5Q'#
- SIZE = 48#
- export()#
Export segment as bytes array.
- Return type:
bytes
- Returns:
bytes
- classmethod parse(data)#
Parse segment from bytes array.
- Parameters:
data (
bytes
) – The bytes array of IVT3a segment- Return type:
Self
- Returns:
SegIVT3a object
- property size: int#
Size of IVT3a segment.
- validate()#
Validation of IVT3a segment.
- Return type:
None
- class spsdk.image.segments.SegIVT3b(version)#
Bases:
BaseSegment
IVT3b segment.
Initialize IVT segment.
- Parameters:
version (
int
) – The version of IVT and Image format
- FORMAT = '<1L7Q'#
- SIZE = 64#
- export()#
Export segment as bytes array.
- Return type:
bytes
- Returns:
bytes
- classmethod parse(data)#
Parse segment from bytes array.
- Parameters:
data (
bytes
) – The bytes array of IVT3b segment- Return type:
Self
- Returns:
SegIVT3b object
- property size: int#
Size of IVT3b segment.
:return size
- validate()#
Validation of IVT3b segment.
- Return type:
None
- class spsdk.image.segments.SegSIGB(version=0)#
Bases:
BaseSegment
SignatureBlock segment.
Initialize SignatureBlock segment.
- FORMAT = '<4HL'#
- SIZE = 16#
- export()#
Export segment as bytes array.
- Return type:
bytes
- Returns:
bytes
- classmethod parse(data)#
Parse segment from bytes array.
- Parameters:
data (
bytes
) – The bytes array of SignatureBlock segment- Return type:
Self
- Returns:
SegSigBlk object
- property size: int#
Size of Signature Block segment.
- property version: int#
Version of Signature Block segment.
- class spsdk.image.segments.SegXMCD(header, config_data)#
Bases:
BaseSegment
External Memory Configuration Data Segment.
Initialize XMCD Segment.
- Parameters:
header (
XMCDHeader
) – XMCD Headerconfig_data (
bytes
) – XMCD configuration data
- TAG = 192#
- export()#
Export segment as bytes (serialization).
- Return type:
bytes
- classmethod parse(data)#
Parse XMCD from binary data.
- Return type:
Self
- class spsdk.image.segments.XMCDHeader(interface=0, instance=0, block_type=0, block_size=4)#
Bases:
object
External Memory Configuration Data Header.
Initialize XMCD Header.
- Parameters:
interface (
int
) – Type of the XMCD instance (0 - FlexSPI, 1 - SEMC), defaults to 0instance (
int
) – Number of the interface instance, defaults to 0block_type (
int
) – Type of XMCD data (0 - Simplified, 1 - Full), defaults to 0block_size (
int
) – XMCD data block size, defaults to 4
- Raises:
SPSDKValueError – If the given interface is not supported
SPSDKValueError – If the given blovk type is not supported
- FORMAT = '<4B'#
- SIZE = 4#
- TAG = 12#
- property config_data_size: int#
Size of XMCD config data blob.
- export()#
Export segment’s header as bytes (serialization).
- Return type:
bytes
- classmethod parse(data)#
Parse XMCD Header from binary data.
- Return type:
Self
Image Segments#
This module contains generic implementation of image segment.
- class spsdk.image.segments_base.SegmentBase(family, revision)#
Bases:
BaseClass
Base class for image segment.
Segment base Constructor.
- Parameters:
family (
str
) – Chip family.revision (
str
) – Optional Chip family revision.
- Raises:
SPSDKValueError – Unsupported family.
- FEATURE = 'unknown'#
- abstract create_config()#
Create current configuration YAML.
- Return type:
str
- Returns:
Configuration of segment.
- export()#
Export block binary.
- Return type:
bytes
- Returns:
Binary representation of segment.
- classmethod get_memory_types(family, revision='latest')#
Get memory types data from database.
- Parameters:
family (
str
) – Chip family.revision (
str
) – Optional Chip family revision.
- Return type:
Dict
- classmethod get_supported_families()#
Return list of supported families.
- Return type:
List
- Returns:
List of supported families.
- classmethod get_supported_memory_types(family, revision='latest')#
Get list of supported memory types data from database.
- Parameters:
family (
str
) – Chip family.revision (
str
) – Optional Chip family revision.
- Return type:
List
[str
]
- abstract static load_from_config(config)#
Load configuration file.
- Parameters:
config (
Dict
) – Segment configuration file.- Return type:
Any
- Returns:
Segment object.
TrustZone#
Module provides support for TrustZone configuration data.
- class spsdk.image.trustzone.TrustZone(family='Unknown', revision='latest', tz_type=TrustZoneType.ENABLED, customizations=None, raw_data=None)#
Bases:
object
Provide creation of binary data to set up the TrustZone engine in CM-33.
Initialize the trustzone.
- classmethod custom(family, customizations, revision='latest')#
Alternate constructor for CUSTOM type of TrustZone.
- Return type:
- classmethod disabled()#
Alternate constructor for DISABLED type of TrustZone.
- Return type:
- Returns:
TrustZone object
- classmethod enabled()#
Alternate constructor for ENABLED type of TrustZone.
- Return type:
- Returns:
TrustZone object
- export()#
Return the TrustZone data as bytes.
- Return type:
bytes
- classmethod from_binary(family, raw_data, revision='latest')#
Alternate constructor using existing binary data.
- Return type:
- classmethod from_config(config_data)#
Alternate constructor using configuration data.
- Raises:
SPSDKError – Invalid configuration file.
- Return type:
- Returns:
TrustZone class instance.
- classmethod generate_config_template(family, revision='latest')#
Generate configuration for selected family.
- Parameters:
family (
str
) – Family description.revision (
str
) – Chip revision specification, as default, latest is used.
- Raises:
SPSDKError – Revision is not supported.
- Return type:
Dict
[str
,str
]- Returns:
Dictionary of individual templates (key is name of template, value is template itself).
- classmethod get_preset_data_size(family, revision='latest')#
Get size of preset data in binary form.
- Parameters:
family (
str
) – Family description.revision (
str
) – Chip revision specification, as default, latest is used.
- Raises:
SPSDKValueError – Family or revision is not supported.
- Return type:
int
- Returns:
Size of TZ data.
- static get_supported_families()#
Return list of supported families.
- Return type:
List
[str
]
- classmethod get_validation_schemas(family, revision='latest')#
Create the validation schema.
- Parameters:
family (
str
) – Family description.revision (
str
) – Chip revision specification, as default, latest is used.
- Raises:
SPSDKError – Family or revision is not supported.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
List of validation schemas.
- classmethod get_validation_schemas_family()#
Create the validation schema just for supported families.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
List of validation schemas for TZ supported families.
- static validate_custom_data(data, customizations)#
Check whether all register names in custom data are valid (present in presets).
- Return type:
bool
- class spsdk.image.trustzone.TrustZoneType(tag, label, description=None)#
Bases:
SpsdkEnum
Enum defining various types of TrustZone types.
- CUSTOM = (1, 'CUSTOM', 'TrustZone enabled with custom settings')#
- DISABLED = (2, 'DISABLED', 'Disabled')#
- ENABLED = (0, 'ENABLED', 'TrustZone enabled with default settings')#
Support for BEE encryption for RT10xx devices#
Contains support for BEE encryption.
- class spsdk.image.bee.BeeBaseClass#
Bases:
object
BEE base class.
- classmethod check_data_to_parse(data)#
Deserialization.
- Parameters:
data (
bytes
) – binary data to be parsed- Raises:
SPSDKError – If size of the data is not sufficient
- Return type:
None
- export()#
- Return type:
bytes
- Returns:
binary representation of the region (serialization).
- classmethod get_size()#
- Return type:
int
- Returns:
size of the exported binary data in bytes.
- property size: int#
- Returns:
size of the exported binary data in bytes.
- update()#
Updates internal fields of the instance.
- Return type:
None
- validate()#
Validates the configuration of the instance.
It is recommended to call the method before export and after parsing.
- Return type:
None
- class spsdk.image.bee.BeeFacRegion(start=0, length=0, protected_level=0)#
Bases:
BeeBaseClass
BEE Factory Access Control (FAC) region.
Constructor.
- Parameters:
start (
int
) – Start address of one FAC region, align at 1KB boundary; 32-bit numberlength (
int
) – Length of one FAC region, align at 1KB boundary; 32-bit numberprotected_level (
int
) – Protected level: 0/1/2/3; 32-bit number
- property end_addr: int#
- Returns:
end address of the region (which is last address of the region + 1).
- export()#
Exports the binary representation.
- Return type:
bytes
- classmethod parse(data)#
Deserialization.
- Parameters:
data (
bytes
) – binary data to be parsed- Return type:
Self
- Returns:
instance created from binary data
- Raises:
SPSDKError – If reserved area is non-zero
- validate()#
Validates the configuration of the instance.
- Return type:
None
- class spsdk.image.bee.BeeKIB(kib_key=None, kib_iv=None)#
Bases:
BeeBaseClass
BEE Key block.
Contains keys used to encrypt PRDB content.
Constructor.
- Parameters:
kib_key (
Optional
[bytes
]) – AES keykib_iv (
Optional
[bytes
]) – AES initialization vector
- export()#
Exports binary representation of the region (serialization).
- Return type:
bytes
- classmethod parse(data)#
Deserialization.
- Parameters:
data (
bytes
) – binary data to be parsed- Return type:
Self
- Returns:
instance created from binary data
- validate()#
Validates settings of the instance.
- Raises:
SPSDKError – If invalid length of kib key
SPSDKError – If invalid length of kib iv
- Return type:
None
- class spsdk.image.bee.BeeNxp(headers, input_image, base_address)#
Bases:
object
BeeNxp class.
Constructor.
- Parameters:
headers (
List
[Optional
[BeeRegionHeader
]]) – list of BEE Region Headersinput_image (
bytes
) – Input image to be encryptedbase_address (
int
) – Base address of the image
- static check_overlaps(bee_headers, start_addr)#
Check for overlaps in regions.
- Parameters:
bee_headers (
List
[Optional
[BeeRegionHeader
]]) – List of BeeRegionHeaderstart_addr (
int
) – start address of a region to be checked
- Raises:
SPSDKOverlapError – if the address is inside any region
- Return type:
None
- export_headers()#
Export BEE headers.
- Return type:
List
[Optional
[bytes
]]- Returns:
BEE region headers
- export_image()#
Export encrypted binary image.
- Return type:
bytes
- Returns:
encrypted image
- static generate_config_template()#
Generate BEE configuration template.
- Return type:
str
- Returns:
Dictionary of individual templates (key is name of template, value is template itself).
- static get_supported_families()#
Get all supported families for BEE.
- Return type:
List
[str
]- Returns:
List of supported families.
- static get_validation_schemas()#
Get list of validation schemas.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
Validation list of schemas.
- static load_from_config(config, search_paths=None)#
Converts the configuration into an BEE image object.
“config” contains dictionary of configurations.
- Raises:
SPSDKError – if the count of BEE engines is invalid.
- Parameters:
config (
Dict
[str
,Any
]) – Configuration dictionary.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
- Returns:
initialized BeeNxp object.
- class spsdk.image.bee.BeeProtectRegionBlock(encr_mode=BeeProtectRegionBlockAesMode.CTR, lock_options=0, counter=None)#
Bases:
BeeBaseClass
BEE protect region block (PRDB).
Constructor.
- Parameters:
encr_mode (
BeeProtectRegionBlockAesMode
) – AES encryption modelock_options (
int
) – Lock options; 32-bit numbercounter (
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 encryptionstart_addr (
int
) – start address of the datadata (
bytes
) – binary block to be encrypted; the block size must be BEE_ENCR_BLOCK_SIZE
- Return type:
bytes
- Returns:
encrypted block if it is inside any FAC region; untouched block if it is not in any FAC region
- Raises:
SPSDKError – When incorrect length of binary block
SPSDKError – When encryption mode different from AES/CTR provided
SPSDKError – When invalid length of key
SPSDKError – When invalid range of region
- export()#
- Return type:
bytes
- Returns:
binary representation of the region (serialization).
- property fac_count: int#
- Returns:
number of Factory Access Control regions.
- classmethod get_size()#
- Return type:
int
- Returns:
size of the exported binary data in bytes.
- is_inside_region(start_addr)#
Returns true if the start address lies within any FAC region.
- Parameters:
start_addr (
int
) – start address of the data- Return type:
bool
- classmethod parse(data)#
Deserialization.
- Parameters:
data (
bytes
) – binary data to be parsed- Return type:
Self
- Returns:
instance created from binary data
- Raises:
SPSDKError – If format does not match
- update()#
Updates start and end address of the encryption region.
- Return type:
None
- validate()#
Validates settings of the instance.
- Return type:
None
- class spsdk.image.bee.BeeProtectRegionBlockAesMode(tag, label, description=None)#
Bases:
SpsdkEnum
AES mode selection for BEE PRDB encryption.
- CTR = (1, 'CTR')#
- ECB = (0, 'ECB')#
- class spsdk.image.bee.BeeRegionHeader(prdb=None, sw_key=None, kib=None)#
Bases:
BeeBaseClass
BEE keys and regions header.
Constructor.
- Parameters:
prdb (
Optional
[BeeProtectRegionBlock
]) – protect region block; None to use defaultsw_key (
Optional
[bytes
]) – key used to encrypt KIB contentkib (
Optional
[BeeKIB
]) – keys block; None to use default
- PRDB_OFFSET = 128#
- SIZE = 512#
- add_fac(fac)#
Append FAC region.
- Parameters:
fac (
BeeFacRegion
) – to be added- Return type:
None
- encrypt_block(start_addr, data)#
Encrypt block located in any FAC region.
- Parameters:
start_addr (
int
) – start address of the datadata (
bytes
) – binary block to be encrypted; the block size must be BEE_ENCR_BLOCK_SIZE
- Return type:
bytes
- Returns:
encrypted block if it is inside any FAC region; untouched block if it is not in any FAC region
- export()#
Serialization to binary representation.
- Return type:
bytes
- Returns:
binary representation of the region (serialization).
- property fac_regions: Sequence[BeeFacRegion]#
- Returns:
lift of Factory Access Control regions.
- classmethod get_size()#
- Return type:
int
- Returns:
size of the exported binary data in bytes.
- is_inside_region(start_addr)#
Returns true if the start address lies within any FAC region.
- Parameters:
start_addr (
int
) – start address of the data- Return type:
bool
- classmethod parse(data, sw_key=b'')#
Deserialization.
- Parameters:
data (
bytes
) – binary data to be parsedsw_key (
bytes
) – SW key used to decrypt the EKIB data
- Return type:
Self
- Returns:
instance created from binary data
- Raises:
SPSDKError – If invalid sw key
- sw_key_fuses()#
- Return type:
Sequence
[int
]- Returns:
sequence of fuse values for SW key to be burned into processor.
The result is ordered, first value should be burned to the lowest address.
- update()#
Updates internal fields of the instance.
- Return type:
None
- validate()#
Validates settings of the instance.
- Raises:
SPSDKError – If settings invalid
- Return type:
None
Support for KeyStore used in MasterBootImage#
Module provides support for KeyStore used in MasterBootImage.
- class spsdk.image.keystore.KeySourceType(tag, label, description=None)#
Bases:
SpsdkEnum
Device key source.
- KEYSTORE = (1, 'KEYSTORE', 'Device keys stored in KeyStore')#
- OTP = (0, 'OTP', 'Device keys stored in OTP')#
- class spsdk.image.keystore.KeyStore(key_source, key_store=None)#
Bases:
object
Provide info about KeyStore for MaterBootImage.
Initialize Keystore.
- Parameters:
key_source (
KeySourceType
) – device key sourcekey_store (
Optional
[bytes
]) – initial content of the key store in the bootable image; None if empty
- Raises:
SPSDKError – If invalid key-store size
SPSDKError – KeyStore can be initialized only if key_source == KEYSTORE
- KEY_STORE_SIZE = 1424#
- OTFAD_KEY_SIZE = 16#
- OTP_MASTER_KEY_SIZE = 32#
- SBKEK_SIZE = 32#
- static derive_enc_image_key(master_key)#
Derive “enc_image_key” from master key.
- Parameters:
master_key (
bytes
) – stored in OTP- Return type:
bytes
- Returns:
key used to decrypt encrypted images during boot
- Raises:
SPSDKError – If invalid length of master key
- static derive_hmac_key(hmac_key)#
Derive HMAC from master or user key.
- Parameters:
hmac_key (
bytes
) – either master-key (for key_source == OTP) or user key (for key_source == KEYSTORE)- Return type:
bytes
- Returns:
key used for image header authentication in LoadToRam images
- Raises:
SPSDKError – If invalid length of hmac key
- static derive_otfad_kek_key(master_key, otfad_input)#
Derive OTFAD KEK key from master key and OTFAD input.
- Parameters:
master_key (
bytes
) – 32 bytes key, stored in OTPotfad_input (
bytes
) – 16 bytes input, stored in OTP
- Return type:
bytes
- Returns:
OTFAD encryption key for FLASH encryption/decryption
- Raises:
SPSDKError – If invalid length of master key
SPSDKError – If invalid length of input
- static derive_sb_kek_key(master_key)#
Derive SBKEK key from master key.
- Parameters:
master_key (
bytes
) – 32 bytes key, stored in OTP- Return type:
bytes
- Returns:
encryption key to handle SB2 file (update capsule)
- Raises:
SPSDKError – If invalid length of master key
- export()#
Binary key store content; empty bytes for empty key-store.
- Return type:
bytes
- property key_source: KeySourceType#
Device key source.
Master Boot Image#
Master Boot Image.
- class spsdk.image.mbi.mbi.MasterBootImage(**kwargs)#
Bases:
object
Master Boot Image Interface.
Initialization of MBI.
- Parameters:
kwargs (
Dict
[str
,Any
]) – Various input parameters based on used dynamic class.
- IMAGE_TYPE = (0, 'Plain Image (either XIP or Load-to-RAM)')#
-
app:
Optional
[bytes
]#
- property app_len: int#
Compute application data length.
- Returns:
Final image data length.
-
app_table:
Optional
[MultipleImageTable
]#
-
cert_block:
Union
[CertBlockV1
,CertBlockV21
,CertBlockVx
,None
]#
-
collect_data:
Callable
[[],BinaryImage
]#
- create_config(output_folder)#
Create configuration file and its data files from the MBI class.
- Parameters:
output_folder (
str
) – Output folder to store the parsed data- Return type:
Dict
[str
,Any
]- Returns:
Configuration dictionary.
-
disassemble_image:
Callable
[[bytes
],None
]#
-
encrypt:
Callable
[[BinaryImage
,bool
],BinaryImage
]#
- export()#
Export final bootable image.
- Return type:
bytes
- Returns:
Bootable Image in bytes.
- export_image()#
Export final bootable image.
- Return type:
- Returns:
Bootable Image in Binary Image format.
-
finalize:
Callable
[[BinaryImage
,bool
],BinaryImage
]#
- classmethod get_image_type(device, data)#
Get image type from MBI data and family.
- Parameters:
device (
str
) – device family to be fetched from DBdata (
bytes
) – MBI raw data
- Return type:
int
- Returns:
Image type int representation
- classmethod get_validation_schemas()#
Create the validation schema for current image type.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
Validation schema.
- classmethod hash()#
Unique identifier for MasterBootImage class based on mixins.
- Return type:
str
- Returns:
Acronym for each MBI base class separated by “-”
- load_from_config(config, search_paths=None)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
None
- static parse(family, data, dek=None)#
Parse the final image to individual fields.
- Parameters:
family (
str
) – Device familydata (
bytes
) – Final Image in bytesdek (
Optional
[str
]) – The decryption key for encrypted images
- Raises:
SPSDKParsingError – Cannot determinate the decoding class
- Return type:
- Returns:
MBI parsed class
-
post_encrypt:
Callable
[[BinaryImage
,bool
],BinaryImage
]#
- property rkth: bytes | None#
Get Root Key Table Hash from certificate block if present.
- Returns:
Root Key Table Hash as hex string.
-
sign:
Callable
[[BinaryImage
,bool
],BinaryImage
]#
- property total_len: int#
Compute Master Boot Image data length.
- Returns:
Final image data length.
- property total_length_for_cert_block: int#
Compute Master Boot Image data length.
- Returns:
Final image data length.
- validate()#
Validate the setting of image.
- Return type:
None
- spsdk.image.mbi.mbi.create_mbi_class(name, family)#
Create Master Boot image class.
- Parameters:
name (
str
) – Name of Classfamily (
str
) – Name of chip family
- Return type:
Type
[MasterBootImage
]- Returns:
Master Boot Image class
- spsdk.image.mbi.mbi.get_all_mbi_classes()#
Get all Master Boot Image supported classes.
- Return type:
List
[Type
[MasterBootImage
]]- Returns:
List with all MBI Classes.
- spsdk.image.mbi.mbi.get_mbi_class(config)#
Get Master Boot Image class.
- Raises:
SPSDKUnsupportedImageType – The invalid configuration.
- Return type:
Type
[MasterBootImage
]- Returns:
MBI Class.
- spsdk.image.mbi.mbi.get_mbi_classes(family)#
Get all Master Boot Image supported classes for chip family.
- Parameters:
family (
str
) – Chip family.- Raises:
SPSDKValueError – The invalid family.
- Return type:
Dict
[str
,Tuple
[Type
[MasterBootImage
],str
,str
]]- Returns:
Dictionary with key like image name and values are Tuple with it’s MBI Class and target and authentication type.
- spsdk.image.mbi.mbi.mbi_generate_config_templates(family)#
Generate all possible configuration for selected family.
- Parameters:
family (
str
) – Family description.- Return type:
Dict
[str
,str
]- Returns:
Dictionary of individual templates (key is name of template, value is template itself).
- spsdk.image.mbi.mbi.mbi_get_supported_families()#
Get supported families by MBI.
- Return type:
List
[str
]- Returns:
List of supported family names.
Master Boot Image - miscellaneous functions#
Misc.
- exception spsdk.image.misc.NotEnoughBytesException(desc=None)#
Bases:
RawDataException
Read_raw_data could not read enough data.
Initialize the base SPSDK Exception.
- exception spsdk.image.misc.RawDataException(desc=None)#
Bases:
SPSDKError
Raw data read failed.
Initialize the base SPSDK Exception.
- exception spsdk.image.misc.StreamReadFailed(desc=None)#
Bases:
RawDataException
Read_raw_data could not read stream.
Initialize the base SPSDK Exception.
- spsdk.image.misc.dict_diff(main, mod)#
Return a difference between two dictionaries if key is not present in main, it’s skipped.
- Return type:
dict
- spsdk.image.misc.hexdump_fmt(data, tab=4, length=16, sep=':')#
Dump some potentially larger data in hex.
- Return type:
str
- spsdk.image.misc.modulus_fmt(modulus, tab=4, length=15, sep=':')#
Modulus format.
- Return type:
str
- spsdk.image.misc.read_raw_data(stream, length, index=None, no_seek=False)#
Read raw data.
- Return type:
bytes
- spsdk.image.misc.read_raw_segment(buffer, segment_tag, index=None)#
Read raw segment.
- Return type:
bytes
Master Boot Image - mixin classes#
Master Boot Image.
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixin#
Bases:
object
Base MBI Export Mixin class.
- collect_data()#
Collect basic data to create image.
- Return type:
- Returns:
Collected raw image.
- disassemble_image(image)#
Disassemble image to individual parts from image.
- Parameters:
image (
bytes
) – Image.- Return type:
None
- encrypt(image, revert=False)#
Encrypt image if needed.
- Parameters:
image (
BinaryImage
) – Input raw image to encrypt.revert (
bool
) – Revert the operation if possible.
- Return type:
- Returns:
Encrypted image.
- finalize(image, revert=False)#
Finalize the image for export.
This part could add HMAC/KeyStore etc.
- Parameters:
image (
BinaryImage
) – Input image.revert (
bool
) – Revert the operation if possible.
- Return type:
- Returns:
Finalized image suitable for export.
- post_encrypt(image, revert=False)#
Optionally do some post encrypt image updates.
- Parameters:
image (
BinaryImage
) – Encrypted image.revert (
bool
) – Revert the operation if possible.
- Return type:
- Returns:
Updated encrypted image.
- sign(image, revert=False)#
Sign image (by signature or CRC).
- Parameters:
image (
BinaryImage
) – Image to sign.revert (
bool
) – Revert the operation if possible.
- Return type:
- Returns:
Optionally signed image.
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinApp#
Bases:
Mbi_ExportMixin
Export Mixin to handle simple application data.
-
app:
Optional
[bytes
]#
- collect_data()#
Collect application data including update IVT.
- Return type:
- Returns:
Image with updated IVT.
-
total_len:
Any
#
-
update_ivt:
Callable
[[bytes
,int
,int
],bytes
]#
-
app:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppBca#
Bases:
Mbi_ExportMixin
Export Mixin to handle simple application data with BCA.
-
IMG_BCA_OFFSET:
int
#
-
IMG_DATA_START:
int
#
-
IMG_DIGEST_OFFSET:
int
#
-
IMG_DUKB_BLOCK_OFFSET:
int
#
-
IMG_ISK_HASH_OFFSET:
int
#
-
IMG_ISK_OFFSET:
int
#
-
IMG_SIGNATURE_OFFSET:
int
#
-
IMG_WPC_BLOCK_OFFSET:
int
#
-
app:
Optional
[bytes
]#
- collect_data()#
Collect application data and TrustZone including update IVT.
- Return type:
- Returns:
Image with updated IVT and added TrustZone.
- disassemble_image(image)#
Disassemble image to individual parts from image.
- Parameters:
image (
bytes
) – Image.- Return type:
None
-
total_len:
int
#
-
update_bca:
Callable
[[bytes
,int
],bytes
]#
-
IMG_BCA_OFFSET:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppCertBlockManifest#
Bases:
Mbi_ExportMixin
Export Mixin to handle simple application data, Certification block and Manifest.
-
app:
Optional
[bytes
]#
-
app_len:
int
#
-
cert_block:
Union
[CertBlockV1
,CertBlockV21
,None
]#
-
clean_ivt:
Callable
[[bytes
],bytes
]#
- collect_data()#
Collect application data, Certification Block and Manifest including update IVT.
- Raises:
SPSDKError – When either application data or certification block or manifest is missing
- Return type:
- Returns:
Image with updated IVT and added Certification Block with Manifest.
-
data_to_sign:
Optional
[bytes
]#
- disassemble_image(image)#
Disassemble image to individual parts from image.
- Parameters:
image (
bytes
) – Image.- Return type:
None
-
disassembly_app_data:
Callable
[[bytes
],bytes
]#
- finalize(image, revert=False)#
Finalize the image for export by adding HMAC a optionally KeyStore.
- Parameters:
image (
BinaryImage
) – Input image.revert (
bool
) – Revert the operation if possible.
- Return type:
- Returns:
Finalized image suitable for export.
-
manifest:
Optional
[TypeVar
(T_Manifest
,MasterBootImageManifest
,MasterBootImageManifestDigest
,MasterBootImageManifestCrc
)]#
-
total_len:
int
#
-
update_ivt:
Callable
[[bytes
,int
,int
],bytes
]#
-
app:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTrustZone#
Bases:
Mbi_ExportMixin
Export Mixin to handle simple application data and TrustZone.
-
app:
Optional
[bytes
]#
-
app_table:
MultipleImageTable
#
-
clean_ivt:
Callable
[[bytes
],bytes
]#
- collect_data()#
Collect application data and TrustZone including update IVT.
- Return type:
- Returns:
Image with updated IVT and added TrustZone.
- disassemble_image(image)#
Disassemble image to individual parts from image.
- Parameters:
image (
bytes
) – Image.- Return type:
None
-
disassembly_app_data:
Callable
[[bytes
],bytes
]#
-
total_len:
Any
#
-
update_ivt:
Callable
[[bytes
,int
,int
],bytes
]#
-
app:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTrustZoneCertBlock#
Bases:
Mbi_ExportMixin
Export Mixin to handle simple application data, TrustZone and Certification block.
-
app:
Optional
[bytes
]#
-
app_len:
int
#
-
app_table:
MultipleImageTable
#
-
cert_block:
Union
[CertBlockV1
,CertBlockV21
,None
]#
-
clean_ivt:
Callable
[[bytes
],bytes
]#
- collect_data()#
Collect application data and TrustZone including update IVT.
- Return type:
- Returns:
Image with updated IVT and added TrustZone.
- disassemble_image(image)#
Disassemble image to individual parts from image.
- Parameters:
image (
bytes
) – Image.- Return type:
None
-
disassembly_app_data:
Callable
[[bytes
],bytes
]#
-
total_len:
int
#
-
total_length_for_cert_block:
int
#
-
update_ivt:
Callable
[[bytes
,int
,int
],bytes
]#
-
app:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTrustZoneCertBlockEncrypt#
Bases:
Mbi_ExportMixin
Export Mixin to handle simple application data, TrustZone and Certification block.
-
HMAC_OFFSET:
int
#
-
app:
Optional
[bytes
]#
-
app_len:
int
#
-
app_table:
MultipleImageTable
#
-
cert_block:
Union
[CertBlockV1
,CertBlockV21
,None
]#
-
clean_ivt:
Callable
[[bytes
],bytes
]#
- collect_data()#
Collect application data and TrustZone including update IVT.
- Return type:
- Returns:
Image with updated IVT and added TrustZone.
-
ctr_init_vector:
bytes
#
- disassemble_image(image)#
Disassemble image to individual parts from image.
- Parameters:
image (
bytes
) – Image.- Return type:
None
-
disassembly_app_data:
Callable
[[bytes
],bytes
]#
- encrypt(image, revert=False)#
Encrypt image if needed.
- Parameters:
image (
BinaryImage
) – Input raw image to encrypt.revert (
bool
) – Revert the operation if possible.
- Return type:
- Returns:
Encrypted image.
-
family:
str
#
-
hmac_key:
Optional
[bytes
]#
- property img_len: int#
Image length of encrypted legacy image.
- post_encrypt(image, revert=False)#
Optionally do some post encrypt image updates.
- Parameters:
image (
BinaryImage
) – Encrypted image.revert (
bool
) – Revert the operation if possible.
- Return type:
- Returns:
Updated encrypted image.
-
total_len:
int
#
-
update_ivt:
Callable
[[bytes
,int
,int
],bytes
]#
-
HMAC_OFFSET:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinCrcSign#
Bases:
Mbi_ExportMixin
Export Mixin to handle sign by CRC.
-
IVT_CRC_CERTIFICATE_OFFSET:
int
#
- sign(image, revert=False)#
Do simple calculation of CRC and return updated image with it.
- Parameters:
image (
BinaryImage
) – Input raw image.revert (
bool
) – Revert the operation if possible.
- Return type:
- Returns:
Image enriched by CRC in IVT table.
-
update_crc_val_cert_offset:
Callable
[[bytes
,int
],bytes
]#
-
IVT_CRC_CERTIFICATE_OFFSET:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinEccSign#
Bases:
Mbi_ExportMixin
Export Mixin to handle sign by ECC.
-
cert_block:
Union
[CertBlockV1
,CertBlockV21
,None
]#
-
data_to_sign:
Optional
[bytes
]#
-
no_signature:
Optional
[bool
]#
- sign(image, revert=False)#
Do calculation of ECC signature and return updated image with it.
- Parameters:
image (
BinaryImage
) – Input raw image.revert (
bool
) – Revert the operation if possible.
- Return type:
- Returns:
Image enriched by ECC signature at end of image.
-
signature_provider:
Optional
[SignatureProvider
]#
-
cert_block:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinEccSignVx#
Bases:
Mbi_ExportMixin
Export Mixin to handle sign by ECC.
-
IMG_BCA_OFFSET:
int
#
-
IMG_DATA_START:
int
#
-
IMG_DIGEST_OFFSET:
int
#
-
IMG_DIGEST_SIZE:
int
#
-
IMG_ISK_HASH_OFFSET:
int
#
-
IMG_ISK_HASH_SIZE:
int
#
-
IMG_ISK_OFFSET:
int
#
-
IMG_SIGNED_HEADER_END:
int
#
-
add_hash:
bool
#
-
app:
Optional
[bytes
]#
-
cert_block:
CertBlockVx
#
-
no_signature:
Optional
[bool
]#
- sign(image, revert=False)#
Do calculation of ECC signature and digest and return updated image with it.
- Parameters:
image (
BinaryImage
) – Input raw image.revert (
bool
) – Revert the operation if possible.
- Return type:
- Returns:
Image enriched by ECC signature and SHA256 digest.
-
signature_provider:
Optional
[SignatureProvider
]#
-
IMG_BCA_OFFSET:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinHmacKeyStoreFinalize#
Bases:
Mbi_ExportMixin
Export Mixin to handle finalize by HMAC and optionally KeyStore.
-
HMAC_OFFSET:
int
#
-
HMAC_SIZE:
int
#
-
compute_hmac:
Callable
[[bytes
],bytes
]#
- finalize(image, revert=False)#
Finalize the image for export by adding HMAC a optionally KeyStore.
- Parameters:
image (
BinaryImage
) – Input image.revert (
bool
) – Revert the operation if possible.
- Return type:
- Returns:
Finalized image suitable for export.
-
HMAC_OFFSET:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinRsaSign#
Bases:
Mbi_ExportMixin
Export Mixin to handle sign by RSA.
-
cert_block:
Union
[CertBlockV1
,CertBlockV21
,None
]#
-
no_signature:
Optional
[bool
]#
- sign(image, revert=False)#
Do calculation of RSA signature and return updated image with it.
- Parameters:
image (
BinaryImage
) – Input raw image.revert (
bool
) – Revert the operation if possible.
- Return type:
- Returns:
Image enriched by RSA signature at end of image.
-
signature_provider:
Optional
[SignatureProvider
]#
-
cert_block:
- class spsdk.image.mbi.mbi_mixin.Mbi_Mixin#
Bases:
object
Base class for Master BOtt Image Mixin classes.
-
COUNT_IN_LEGACY_CERT_BLOCK_LEN:
bool
= True#
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {}#
-
PRE_PARSED:
List
[str
] = []#
-
VALIDATION_SCHEMAS:
List
[str
] = []#
- mix_app_len()#
Compute application data length of individual mixin.
- Return type:
int
- Returns:
Application data length of atomic Mixin.
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- classmethod mix_get_extra_validation_schemas()#
Get extra-non standard validation schemas from mixin.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
List of additional validation schemas.
- mix_len()#
Compute length of individual mixin.
- Return type:
int
- Returns:
Length of atomic Mixin.
- mix_load_from_config(config)#
Load configuration of mixin from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
- Parameters:
data (
bytes
) – Final Image in bytes.- Return type:
None
- mix_validate()#
Validate the setting of image.
- Return type:
None
-
COUNT_IN_LEGACY_CERT_BLOCK_LEN:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinApp#
Bases:
Mbi_Mixin
Master Boot Image App class.
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'_app': b'', 'app_ext_memory_align': 4096}#
-
VALIDATION_SCHEMAS:
List
[str
] = ['app']#
- property app: bytes#
Application data.
-
app_ext_memory_align:
int
#
- load_binary_image_file(path)#
Load binary image from file (S19,HEX,BIN).
- Parameters:
path (
str
) – File path- Raises:
SPSDKError – If invalid data file is detected.
- Return type:
None
- mix_app_len()#
Compute application data length of individual mixin.
- Return type:
int
- Returns:
Application data length of atomic Mixin.
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- mix_len()#
Get size of plain input application image.
- Return type:
int
- Returns:
Length of application.
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
-
search_paths:
Optional
[List
[str
]]#
-
NEEDED_MEMBERS:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinBca#
Bases:
Mbi_Mixin
Master Boot Image Boot Configuration Area.
- IMG_BCA_FW_VERSION_OFFSET = 996#
- IMG_BCA_IMAGE_LENGTH_OFFSET = 992#
- IMG_BCA_OFFSET = 960#
- IMG_DATA_START = 3072#
- IMG_DIGEST_OFFSET = 864#
- IMG_DIGEST_SIZE = 32#
- IMG_DUKB_BLOCK_OFFSET = 2048#
- IMG_DUKB_BLOCK_SIZE = 1024#
- IMG_FCB_OFFSET = 1024#
- IMG_FCB_SIZE = 16#
- IMG_ISK_HASH_OFFSET = 1184#
- IMG_ISK_HASH_SIZE = 128#
- IMG_ISK_OFFSET = 1040#
- IMG_SIGNATURE_OFFSET = 896#
- IMG_SIGNED_HEADER_END = 1024#
- IMG_WPC_BLOCK_OFFSET = 1312#
- IMG_WPC_BLOCK_SIZE = 736#
-
VALIDATION_SCHEMAS:
List
[str
] = ['firmware_version']#
-
firmware_version:
Optional
[int
]#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- mix_len()#
Length of the image.
- Return type:
int
- Returns:
length in bytes
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
- Parameters:
data (
bytes
) – Final Image in bytes.- Return type:
None
- update_bca(app_data, total_len)#
Update BCA table in application image.
- Parameters:
app_data (
bytes
) – Application data that should be modified.total_len (
int
) – Total length of bootable image
- Return type:
bytes
- Returns:
Updated whole application image
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinCertBlockV1#
Bases:
Mbi_Mixin
Master Boot Image certification block V1 class.
-
HMAC_SIZE:
int
#
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'cert_block': None, 'signature_provider': None}#
-
VALIDATION_SCHEMAS:
List
[str
] = ['cert_block_v1', 'signature_provider']#
-
cert_block:
Optional
[CertBlockV1
]#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- mix_len()#
Get length of Certificate Block V1.
- Return type:
int
- Returns:
Length of Certificate Block V1.
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
- Parameters:
data (
bytes
) – Final Image in bytes.- Return type:
None
- mix_validate()#
Validate the setting of image.
- Raises:
SPSDKError – Configuration of Certificate block v1 is invalid.
- Return type:
None
-
search_paths:
Optional
[List
[str
]]#
-
signature_provider:
Optional
[SignatureProvider
]#
-
total_len:
Any
#
-
HMAC_SIZE:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinCertBlockV21#
Bases:
Mbi_Mixin
Master Boot Image certification block V3.1 class.
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'cert_block': None, 'signature_provider': None}#
-
VALIDATION_SCHEMAS:
List
[str
] = ['cert_block_v21', 'signature_provider']#
-
cert_block:
Optional
[CertBlockV21
]#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- mix_len()#
Get length of Certificate Block V2.1.
- Return type:
int
- Returns:
Length of Certificate Block V2.1.
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
- Parameters:
data (
bytes
) – Final Image in bytes.- Return type:
None
- mix_validate()#
Validate the setting of image.
- Raises:
SPSDKError – The configuration of Certificate v3.1 is invalid.
- Return type:
None
-
search_paths:
Optional
[List
[str
]]#
-
signature_provider:
Optional
[SignatureProvider
]#
-
NEEDED_MEMBERS:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinCertBlockVx#
Bases:
Mbi_Mixin
Master Boot Image certification block for MC55xx class.
-
IMG_ISK_OFFSET:
int
#
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'cert_block': None, 'signature_provider': None}#
-
VALIDATION_SCHEMAS:
List
[str
] = ['cert_block_vX', 'signature_provider']#
-
add_hash:
bool
#
-
cert_block:
CertBlockVx
#
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
- Parameters:
data (
bytes
) – Final Image in bytes.- Return type:
None
- mix_validate()#
Validate the setting of image.
- Raises:
SPSDKError – The configuration of certificate block is invalid.
- Return type:
None
-
search_paths:
Optional
[List
[str
]]#
-
signature_provider:
Optional
[SignatureProvider
]#
-
IMG_ISK_OFFSET:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinCtrInitVector#
Bases:
Mbi_Mixin
Master Boot Image initial vector for encryption counter.
-
HMAC_SIZE:
int
#
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'_ctr_init_vector': b'NB/\xfbl\x8c2i\xee\xf9\xf0\x8b\x06\xf6\xaf\x7f'}#
-
PRE_PARSED:
List
[str
] = ['cert_block']#
-
VALIDATION_SCHEMAS:
List
[str
] = ['ctr_init_vector']#
-
cert_block:
Union
[CertBlockV1
,CertBlockV21
,None
]#
- property ctr_init_vector: bytes | None#
Counter init vector.
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
- Parameters:
data (
bytes
) – Final Image in bytes.- Return type:
None
- mix_validate()#
Validate the setting of image.
raise SPSDKError: Invalid HW key enabled member type.
- Return type:
None
-
search_paths:
Optional
[List
[str
]]#
-
HMAC_SIZE:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinFwVersion#
Bases:
Mbi_Mixin
Master Boot Image FirmWare Version class.
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'manifest': None}#
-
VALIDATION_SCHEMAS:
List
[str
] = ['firmware_version']#
-
firmware_version:
Optional
[int
]#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
-
NEEDED_MEMBERS:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinHmac#
Bases:
Mbi_Mixin
Master Boot Image HMAC class.
-
COUNT_IN_LEGACY_CERT_BLOCK_LEN:
bool
= False#
- HMAC_OFFSET = 64#
- HMAC_SIZE = 32#
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'_hmac_key': None}#
-
VALIDATION_SCHEMAS:
List
[str
] = ['hmac']#
- compute_hmac(data)#
Compute HMAC hash.
- Parameters:
data (
bytes
) – Data to be hashed.- Return type:
bytes
- Returns:
Result HMAC hash of input data.
-
dek:
Optional
[str
]#
- property hmac_key: bytes | None#
HMAC key in bytes.
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- mix_len()#
Get length of HMAC block.
- Return type:
int
- Returns:
Length of HMAC block.
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
- Parameters:
data (
bytes
) – Final Image in bytes.- Return type:
None
- mix_validate()#
Validate the setting of image.
raise SPSDKError: Invalid HW key enabled member type.
- Return type:
None
-
search_paths:
Optional
[List
[str
]]#
-
COUNT_IN_LEGACY_CERT_BLOCK_LEN:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinHmacMandatory#
Bases:
Mbi_MixinHmac
Master Boot Image HMAC class (Mandatory use).
-
VALIDATION_SCHEMAS:
List
[str
] = ['hmac_mandatory']#
- mix_validate()#
Validate the setting of image.
raise SPSDKError: Invalid HW key enabled member type.
- Return type:
None
-
VALIDATION_SCHEMAS:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinHwKey#
Bases:
Mbi_Mixin
Master Boot Image HW key user modes enable class.
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'user_hw_key_enabled': False}#
-
VALIDATION_SCHEMAS:
List
[str
] = ['hw_key']#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
- Parameters:
data (
bytes
) – Final Image in bytes.- Return type:
None
- mix_validate()#
Validate the setting of image.
raise SPSDKError: Invalid HW key enabled member type.
- Return type:
None
-
user_hw_key_enabled:
Optional
[bool
]#
-
NEEDED_MEMBERS:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinImageSubType#
Bases:
Mbi_Mixin
Master Boot Image SubType class.
- class Mbi_ImageSubTypeKw45xx(tag, label, description=None)#
Bases:
SpsdkEnum
Supported MAIN and NBU subtypes for KW45xx and K32W1xx.
- MAIN = (0, 'MAIN', 'Default (main) application image')#
- NBU = (1, 'NBU', 'NBU (Narrowband Unit) image')#
- class Mbi_ImageSubTypeMcxn9xx(tag, label, description=None)#
Bases:
SpsdkEnum
Supported MAIN and NBU subtypes for MCXN9xx.
- MAIN = (0, 'MAIN', 'Default (main) application image')#
- RECOVERY = (1, 'RECOVERY', 'Recovery image')#
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'image_subtype': 0}#
-
VALIDATION_SCHEMAS:
List
[str
] = ['image_subtype']#
-
image_subtype:
Optional
[int
]#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.mb_xip_384_384_recovery_crctest- Return type:
Dict
[str
,Any
]
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
- Parameters:
data (
bytes
) – Final Image in bytes.- Return type:
None
- set_image_subtype(image_subtype)#
Convert string value to int by enum table and store to class.
- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinImageVersion#
Bases:
Mbi_Mixin
Master Boot Image Image Version class.
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'image_version': 0}#
-
VALIDATION_SCHEMAS:
List
[str
] = ['image_version']#
-
image_version:
Optional
[int
]#
-
image_version_to_image_type:
bool
= True#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
- Parameters:
data (
bytes
) – Final Image in bytes.- Return type:
None
-
NEEDED_MEMBERS:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinIvt#
Bases:
Mbi_Mixin
Master Boot Image Interrupt Vector table class.
-
IMAGE_TYPE:
Tuple
[int
,str
]#
- IVT_CRC_CERTIFICATE_OFFSET = 40#
- IVT_IMAGE_FLAGS_IMAGE_TYPE_MASK = 63#
- IVT_IMAGE_FLAGS_IMG_VER_MASK = 65535#
- IVT_IMAGE_FLAGS_IMG_VER_SHIFT = 16#
- IVT_IMAGE_FLAGS_OFFSET = 36#
- IVT_IMAGE_FLAGS_SUB_TYPE_MASK = 3#
- IVT_IMAGE_FLAGS_SUB_TYPE_SHIFT = 6#
- IVT_IMAGE_FLAGS_TZ_TYPE_MASK = 3#
- IVT_IMAGE_FLAGS_TZ_TYPE_SHIFT = 13#
- IVT_IMAGE_LENGTH_OFFSET = 32#
- IVT_LOAD_ADDR_OFFSET = 52#
-
app_table:
Optional
[MultipleImageTable
]#
- static check_total_length(data)#
Check total length field from raw data.
- Parameters:
data (
bytes
) – Raw MBI image data.- Raises:
SPSDKParsingError – Insufficient length of image has been detected.
- Return type:
None
- clean_ivt(app_data)#
Clean IVT table from added information.
- Parameters:
app_data (
bytes
) – Application data that should be cleaned.- Return type:
bytes
- Returns:
Cleaned application image
- create_flags()#
Create flags of image.
- Return type:
int
- Returns:
Image type flags
- static get_app_table_presented(data)#
Get the Multiple Application table present flag from raw data.
- Parameters:
data (
bytes
) – Raw MBI image data.- Return type:
int
- Returns:
Multiple Application table is included or not.
- static get_cert_block_offset(data)#
Get the certificate block offset from raw data.
During getting of flags, the length is also validated.
- Parameters:
data (
bytes
) – Raw MBI image data.- Return type:
int
- Returns:
Certificate block offset
- static get_flags(data)#
Get the Image flags from raw data.
During getting of flags, the length is also validated.
- Parameters:
data (
bytes
) – Raw MBI image data.- Return type:
int
- Returns:
Image Flags
- static get_hw_key_enabled(data)#
Get the HW key enabled setting from raw data.
- Parameters:
data (
bytes
) – Raw MBI image data.- Return type:
bool
- Returns:
HW key enabled or not.
- static get_image_type(data)#
Get the Image type from raw data.
- Parameters:
data (
bytes
) – Raw MBI image data.- Return type:
int
- Returns:
Image type
- static get_image_version(data)#
Get the Image firmware version from raw data.
- Parameters:
data (
bytes
) – Raw MBI image data.- Return type:
int
- Returns:
Firmware version.
- static get_key_store_presented(data)#
Get the KeyStore present flag from raw data.
- Parameters:
data (
bytes
) – Raw MBI image data.- Return type:
int
- Returns:
KeyStore is included or not.
- static get_load_address(data)#
Get the load address from raw data.
During getting of flags, the length is also validated.
- Parameters:
data (
bytes
) – Raw MBI image data.- Return type:
int
- Returns:
Load address
- static get_sub_type(data)#
Get the Image sub type from raw data.
- Parameters:
data (
bytes
) – Raw MBI image data.- Return type:
int
- Returns:
Image sub type.
- static get_tz_type(data)#
Get the Image TrustZone type settings from raw data.
- Parameters:
data (
bytes
) – Raw MBI image data.- Return type:
int
- Returns:
TrustZone type.
-
image_subtype:
Optional
[int
]#
-
image_version:
Optional
[int
]#
-
image_version_to_image_type:
bool
#
-
load_address:
Optional
[int
]#
- 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 imagecrc_val_cert_offset (
int
) – CRC value or Certification block offset
- Return type:
bytes
- Returns:
Updated whole application image
-
user_hw_key_enabled:
Optional
[bool
]#
-
IMAGE_TYPE:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinKeyStore#
Bases:
Mbi_Mixin
Master Boot Image KeyStore class.
-
COUNT_IN_LEGACY_CERT_BLOCK_LEN:
bool
= False#
-
HMAC_OFFSET:
int
#
-
HMAC_SIZE:
int
#
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'_hmac_key': None, 'key_store': None}#
-
VALIDATION_SCHEMAS:
List
[str
] = ['key_store']#
-
hmac_key:
Optional
[bytes
]#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- mix_len()#
Get length of KeyStore block.
- Return type:
int
- Returns:
Length of KeyStore block.
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
- Parameters:
data (
bytes
) – Final Image in bytes.- Return type:
None
- mix_validate()#
Validate the setting of image.
raise SPSDKError: Invalid HW key enabled member type.
- Return type:
None
-
search_paths:
Optional
[List
[str
]]#
-
COUNT_IN_LEGACY_CERT_BLOCK_LEN:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinLoadAddress#
Bases:
Mbi_Mixin
Master Boot Image load address class.
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'load_address': 0}#
-
VALIDATION_SCHEMAS:
List
[str
] = ['load_addr']#
-
load_address:
Optional
[int
]#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
- Parameters:
data (
bytes
) – Final Image in bytes.- Return type:
None
-
NEEDED_MEMBERS:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinManifest#
Bases:
Mbi_MixinTrustZoneMandatory
Master Boot Image Manifest class.
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'cert_block': None, 'family': 'Unknown', 'manifest': None}#
-
PRE_PARSED:
List
[str
] = ['cert_block']#
-
VALIDATION_SCHEMAS:
List
[str
] = ['trust_zone', 'firmware_version']#
-
cert_block:
Union
[CertBlockV1
,CertBlockV21
,None
]#
-
family:
str
#
-
firmware_version:
Optional
[int
]#
-
manifest:
Optional
[MasterBootImageManifest
]#
- manifest_class#
alias of
MasterBootImageManifest
- mix_len()#
Get length of Manifest block.
- Return type:
int
- Returns:
Length of Manifest block.
- mix_parse(data)#
Parse the binary to individual fields.
- Parameters:
data (
bytes
) – Final Image in bytes.- Return type:
None
- mix_validate()#
Validate the setting of image.
- Raises:
SPSDKError – The manifest configuration is invalid.
- Return type:
None
-
NEEDED_MEMBERS:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinManifestCrc#
Bases:
Mbi_MixinManifest
Master Boot Image Manifest class with CRC.
-
manifest:
Optional
[MasterBootImageManifestCrc
]#
- manifest_class#
alias of
MasterBootImageManifestCrc
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
-
manifest:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinManifestDigest#
Bases:
Mbi_MixinManifest
Master Boot Image Manifest class for devices supporting ImageDigest functionality.
-
VALIDATION_SCHEMAS:
List
[str
] = ['trust_zone', 'firmware_version', 'digest_hash_algo']#
-
manifest:
Optional
[MasterBootImageManifestDigest
]#
- manifest_class#
alias of
MasterBootImageManifestDigest
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- mix_len()#
Get length of Manifest block.
- Return type:
int
- Returns:
Length of Manifest block.
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
-
VALIDATION_SCHEMAS:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinNoSignature#
Bases:
Mbi_Mixin
Master Boot Image No Signature.
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'no_signature': False}#
-
VALIDATION_SCHEMAS:
List
[str
] = ['no_signature']#
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
-
no_signature:
Optional
[bool
]#
-
NEEDED_MEMBERS:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinRelocTable#
Bases:
Mbi_Mixin
Master Boot Image Relocation table class.
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'_app': None, 'app_table': None}#
-
VALIDATION_SCHEMAS:
List
[str
] = ['app_table']#
-
app:
Optional
[bytes
]#
-
app_table:
Optional
[MultipleImageTable
]#
- disassembly_app_data(data)#
Disassembly Application data to application and optionally Multiple Application Table.
- Return type:
bytes
- Returns:
Application data without Multiple Application Table which will be stored in class.
- mix_app_len()#
Compute application data length of individual mixin.
- Return type:
int
- Returns:
Application data length of atomic Mixin.
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- mix_len()#
Get length of additional binaries block.
- Return type:
int
- Returns:
Length of additional binaries block.
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_validate()#
Validate the setting of image.
- Raises:
SPSDKError – Application table configuration is invalid.
- Return type:
None
-
search_paths:
Optional
[List
[str
]]#
-
NEEDED_MEMBERS:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinTrustZone#
Bases:
Mbi_Mixin
Master Boot Image Trust Zone class.
-
NEEDED_MEMBERS:
Dict
[str
,Any
] = {'family': 'Unknown', 'trust_zone': <TrustZone: type: TrustZoneType.ENABLED (TrustZone enabled with default settings)}#
-
PRE_PARSED:
List
[str
] = ['cert_block']#
-
VALIDATION_SCHEMAS:
List
[str
] = ['trust_zone']#
-
cert_block:
Union
[CertBlockV1
,CertBlockV21
,None
]#
-
family:
str
#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str
) – Output folder to store files.- Return type:
Dict
[str
,Any
]
- mix_len()#
Get length of TrustZone array.
- Return type:
int
- Returns:
Length of TrustZone.
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
- Parameters:
data (
bytes
) – Final Image in bytes.- Return type:
None
-
search_paths:
Optional
[List
[str
]]#
-
NEEDED_MEMBERS:
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinTrustZoneMandatory#
Bases:
Mbi_MixinTrustZone
Master Boot Image Trust Zone class for devices where is Trustzone mandatory.
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Dict
[str
,Any
]) – Dictionary with configuration fields.- Return type:
None
- mix_validate()#
Validate the setting of image.
- Raises:
SPSDKError – The TrustZone configuration is invalid.
- Return type:
None
Image Exceptions#
Module provides exceptions for PFR module.
- exception spsdk.image.exceptions.SPSDKSegmentNotPresent(desc=None)#
Bases:
SPSDKError
The segment is missing in the image.
Initialize the base SPSDK Exception.
- exception spsdk.image.exceptions.SPSDKUnsupportedImageType(desc=None)#
Bases:
SPSDKError
The specified Image type is not supported.
Initialize the base SPSDK Exception.
AHAB Container#
Implementation of raw AHAB container support.
This module represents a generic AHAB container implementation. You can set the containers values at will. From this perspective, consult with your reference manual of your device for allowed values.
- class spsdk.image.ahab.ahab_container.AHABTags(tag, label, description=None)#
Bases:
SpsdkEnum
AHAB container related tags.
- BLOB = (129, 'Blob (Wrapped Data Encryption Key).')#
- CONTAINER_HEADER = (135, 'Container header.')#
- SIGNATURE_BLOCK = (144, 'Signature block.')#
- CERTIFICATE_UUID = (160, 'Certificate with UUID.')#
- CERTIFICATE_NON_UUID = (175, 'Certificate without UUID.')#
- SRK_TABLE = (215, 'SRK table.')#
- SIGNATURE = (216, 'Signature part of signature block.')#
- SRK_RECORD = (225, 'SRK record.')#
- class spsdk.image.ahab.ahab_container.AHABCoreId(tag, label, description=None)#
Bases:
SpsdkEnum
AHAB cored IDs.
- UNDEFINED = (0, 'undefined', 'Undefined core')#
- CORTEX_M33 = (1, 'cortex-m33', 'Cortex M33')#
- CORTEX_M4 = (2, 'cortex-m4', 'Cortex M4')#
- CORTEX_M7 = (2, 'cortex-m7', 'Cortex M7')#
- CORTEX_A55 = (2, 'cortex-a55', 'Cortex A55')#
- CORTEX_M4_1 = (3, 'cortex-m4_1', 'Cortex M4 alternative')#
- CORTEX_A53 = (4, 'cortex-a53', 'Cortex A53')#
- CORTEX_A35 = (4, 'cortex-a35', 'Cortex A35')#
- CORTEX_A72 = (5, 'cortex-a72', 'Cortex A72')#
- SECO = (6, 'seco', 'EL enclave')#
- HDMI_TX = (7, 'hdmi-tx', 'HDMI Tx')#
- HDMI_RX = (8, 'hdmi-rx', 'HDMI Rx')#
- V2X_1 = (9, 'v2x-1', 'V2X 1')#
- V2X_2 = (10, 'v2x-2', 'V2X 2')#
- spsdk.image.ahab.ahab_container.get_key_by_val(dictionary, val)#
Get Dictionary key by its value or default.
- Parameters:
dictionary (
Dict
) – Dictionary to search in.val (
Any
) – Value to search
- Raises:
SPSDKValueError – In case that dictionary doesn’t contains the value.
- Return type:
Any
- Returns:
Key.
- class spsdk.image.ahab.ahab_container.ImageArrayEntry(parent, image=None, image_offset=0, load_address=0, entry_point=0, flags=0, image_meta_data=0, image_hash=None, image_iv=None, already_encrypted_image=False)#
Bases:
Container
Class representing image array entry as part of image array in the AHAB container.
Image Array Entry content:
+-----+---------------------------------------------------------------+ |Off | Byte 3 | Byte 2 | Byte 1 | Byte 0 | +-----+---------------------------------------------------------------+ |0x00 | Image Offset | +-----+---------------------------------------------------------------+ |0x04 | Image Size | +-----+---------------------------------------------------------------+ |0x08 | | |-----+ Load Address (64 bits) | |0x0C | | +-----+---------------------------------------------------------------+ |0x10 | | |-----+ Entry Point (64 bits) | |0x14 | | +-----+---------------------------------------------------------------+ |0x18 | Flags | +-----+---------------------------------------------------------------+ |0x1C | Image meta data | +-----+---------------------------------------------------------------+ |0x20 | | |-----+ Hash (512 bits) | |.... | | +-----+---------------------------------------------------------------+ |0x60 | IV (256 bits) | +-----+---------------------------------------------------------------+
Class object initializer.
- Parameters:
parent (
AHABContainer
) – Parent AHAB Container object.image (
Optional
[bytes
]) – Image in bytes.image_offset (
int
) – Offset in bytes from start of container to beginning of image.load_address (
int
) – Address the image is written to in memory (absolute address in system memory map).entry_point (
int
) – Entry point of image (absolute address). Only valid for executable image types. For other image types the value is irrelevant.flags (
int
) – flags.image_meta_data (
int
) – image meta-data.image_hash (
Optional
[bytes
]) – SHA of image (512 bits) in big endian. Left aligned and padded with zeroes for hash sizes below 512 bits.image_iv (
Optional
[bytes
]) – SHA256 of plain text image (256 bits) in big endian.already_encrypted_image (
bool
) – The input image is already encrypted. Used only for encrypted images.
- IMAGE_OFFSET_LEN = 4#
- IMAGE_SIZE_LEN = 4#
- LOAD_ADDRESS_LEN = 8#
- ENTRY_POINT_ADDRESS_LEN = 8#
- FLAGS_LEN = 4#
- IMAGE_META_DATA_LEN = 4#
- HASH_LEN = 64#
- IV_LEN = 32#
- FLAGS_TYPE_OFFSET = 0#
- FLAGS_TYPE_SIZE = 4#
- FLAGS_TYPES = {'csf': 1, 'data': 4, 'dcd_image': 5, 'dek_validation_fcb_chk': 8, 'executable': 3, 'executable_fast_boot_image': 10, 'provisioning_data': 9, 'provisioning_image': 7, 'scd': 2, 'seco': 6, 'v2x_dummy': 14, 'v2x_primary': 11, 'v2x_rom_patch': 13, 'v2x_secondary': 12}#
- FLAGS_CORE_ID_OFFSET = 4#
- FLAGS_CORE_ID_SIZE = 4#
- FLAGS_HASH_OFFSET = 8#
- FLAGS_HASH_SIZE = 3#
- FLAGS_IS_ENCRYPTED_OFFSET = 11#
- FLAGS_IS_ENCRYPTED_SIZE = 1#
- FLAGS_BOOT_FLAGS_OFFSET = 16#
- FLAGS_BOOT_FLAGS_SIZE = 15#
- METADATA_START_CPU_ID_OFFSET = 0#
- METADATA_START_CPU_ID_SIZE = 10#
- METADATA_MU_CPU_ID_OFFSET = 10#
- METADATA_MU_CPU_ID_SIZE = 10#
- METADATA_START_PARTITION_ID_OFFSET = 20#
- METADATA_START_PARTITION_ID_SIZE = 8#
- IMAGE_ALIGNMENTS = {'nand_2k': 2048, 'nand_4k': 4096, 'nor': 1024, 'serial_downloader': 512}#
- property image_offset: int#
Image offset.
- property image_offset_real: int#
Real offset in Bootable image.
- property image: bytes#
Image data for this Image array entry.
The class decide by flags if encrypted of plain data has been returned.
- Raises:
SPSDKError – Invalid Image - Image is not encrypted yet.
- Returns:
Image bytes.
- classmethod format()#
Format of binary representation.
- Return type:
str
- update_fields()#
Updates the image fields in container based on provided image.
- Return type:
None
- static create_meta(start_cpu_id=0, mu_cpu_id=0, start_partition_id=0)#
Create meta data field.
- Parameters:
start_cpu_id (
int
) – ID of CPU to start, defaults to 0mu_cpu_id (
int
) – ID of MU for selected CPU to start, defaults to 0start_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=AHABCoreId.CORTEX_M33, hash_type=EnumHashAlgorithm.SHA256, is_encrypted=False, boot_flags=0)#
Create flags field.
- Parameters:
image_type (
str
) – Type of image, defaults to “executable”core_id (
AHABCoreId
) – Core ID, defaults to “cortex-m33”hash_type (
EnumHashAlgorithm
) – Hash type, defaults to sha256is_encrypted (
bool
) – Is image encrypted, defaults to Falseboot_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:
- Returns:
Hash name.
- property flags_image_type: str#
Get Image type name from flags.
- Returns:
Image type name
- property flags_core_id: int#
Get Core ID from flags.
- Returns:
Core ID
- property flags_is_encrypted: bool#
Get Is encrypted property from flags.
- Returns:
True if is encrypted, false otherwise
- property flags_boot_flags: int#
Get boot flags property from flags.
- Returns:
Boot flags
- property metadata_start_cpu_id: int#
Get CPU ID property from Meta data.
- Returns:
Start CPU ID
- property metadata_mu_cpu_id: int#
Get Start CPU Memory Unit ID property from Meta data.
- Returns:
Start CPU MU ID
- property metadata_start_partition_id: int#
Get Start Partition ID property from Meta data.
- Returns:
Start Partition ID
- export()#
Serializes container object into bytes in little endian.
The hash and IV are kept in big endian form.
- Return type:
bytes
- Returns:
bytes representing container content.
- validate()#
Validate object data.
- Raises:
SPSDKValueError – Invalid any value of Image Array entry
- Return type:
None
- classmethod parse(data, parent)#
Parse input binary chunk to the container object.
- Parameters:
parent (
AHABContainer
) – Parent AHABContainer object.data (
bytes
) – Binary data with Image Array Entry block to parse.
- Raises:
SPSDKLengthError – If invalid length of image is detected.
SPSDKValueError – Invalid hash for image.
- Return type:
Self
- Returns:
Object recreated from the binary data.
- static load_from_config(parent, config)#
Converts the configuration option into an AHAB image array entry object.
“config” content of container configurations.
- Parameters:
parent (
AHABContainer
) – Parent AHABContainer object.config (
Dict
[str
,Any
]) – Configuration of ImageArray.
- Return type:
- Returns:
Container Header Image Array Entry object.
- create_config(index, image_index, data_path)#
Create configuration of the AHAB Image data blob.
- Parameters:
index (
int
) – Container index.image_index (
int
) – Data Image index.data_path (
str
) – Path to store the data files of configuration.
- Return type:
Dict
[str
,Any
]- Returns:
Configuration dictionary.
- get_valid_alignment()#
Get valid alignment for AHAB container and memory target.
- Return type:
int
- Returns:
AHAB valid alignment
- get_valid_offset(original_offset)#
Get valid offset for AHAB container.
- Parameters:
original_offset (
int
) – Offset that should be updated to valid one- Return type:
int
- Returns:
AHAB valid offset
- class spsdk.image.ahab.ahab_container.SRKRecord(src_key=None, signing_algorithm='rsa_pss', hash_type=EnumHashAlgorithm.SHA256, key_size=0, srk_flags=0, crypto_param1=b'', crypto_param2=b'')#
Bases:
HeaderContainerInversed
Class representing SRK (Super Root Key) record as part of SRK table in the AHAB container.
The class holds information about RSA/ECDSA signing algorithms.
SRK Record:
+-----+---------------------------------------------------------------+ |Off | Byte 3 | Byte 2 | Byte 1 | Byte 0 | +-----+---------------------------------------------------------------+ |0x00 | Tag | Length of SRK | Signing Algo | +-----+---------------------------------------------------------------+ |0x04 | Hash Algo | Key Size/Curve | Not Used | SRK Flags | +-----+---------------------------------------------------------------+ |0x08 | RSA modulus len / ECDSA X len | RSA exponent len / ECDSA Y len| +-----+---------------------------------------------------------------+ |0x0C | RSA modulus (big endian) / ECDSA X (big endian) | +-----+---------------------------------------------------------------+ |... | RSA exponent (big endian) / ECDSA Y (big endian) | +-----+---------------------------------------------------------------+
Class object initializer.
- Parameters:
src_key (
Optional
[PublicKey
]) – Optional source public key used to create the SRKRecordsigning_algorithm (
str
) – signing algorithm type.hash_type (
EnumHashAlgorithm
) – hash algorithm type.key_size (
int
) – key (curve) size.srk_flags (
int
) – flags.crypto_param1 (
bytes
) – RSA modulus (big endian) or ECDSA X (big endian)crypto_param2 (
bytes
) – RSA exponent (big endian) or ECDSA Y (big endian)
- TAG = 225#
- VERSION = [33, 34, 39, 40]#
- VERSION_ALGORITHMS = {'ecdsa': 39, 'rsa': 33, 'rsa_pss': 34, 'sm2': 40}#
- HASH_ALGORITHM = {EnumHashAlgorithm(tag=1, label='sha256', description='SHA256'): 0, EnumHashAlgorithm(tag=2, label='sha384', description='SHA384'): 1, EnumHashAlgorithm(tag=3, label='sha512', description='SHA512'): 2, EnumHashAlgorithm(tag=5, label='sm3', description='SM3'): 3}#
- ECC_KEY_TYPE = {EccCurve.SECP256R1: 1, EccCurve.SECP384R1: 2, EccCurve.SECP521R1: 3}#
- RSA_KEY_TYPE = {2048: 5, 4096: 7}#
- SM2_KEY_TYPE = 8#
- KEY_SIZES = {1: (32, 32), 2: (48, 48), 3: (66, 66), 5: (256, 4), 7: (512, 4), 8: (32, 32)}#
- FLAGS_CA_MASK = 128#
- classmethod format()#
Format of binary representation.
- Return type:
str
- update_fields()#
Update all fields depended on input values.
- Return type:
None
- export()#
Export one SRK record, little big endian format.
The crypto parameters (X/Y for ECDSA or modulus/exponent) are kept in big endian form.
- Return type:
bytes
- Returns:
bytes representing container content.
- validate()#
Validate object data.
- Raises:
SPSDKValueError – Invalid any value of Image Array entry
- Return type:
None
- static create_from_key(public_key, srk_flags=0)#
Create instance from key data.
- Parameters:
public_key (
PublicKey
) – Loaded public key.srk_flags (
int
) – SRK flags for key.
- Raises:
SPSDKValueError – Unsupported keys size is detected.
- Return type:
- classmethod parse(data)#
Parse input binary chunk to the container object.
- Parameters:
data (
bytes
) – Binary data with SRK record block to parse.- Raises:
SPSDKLengthError – Invalid length of SRK record data block.
- Return type:
Self
- Returns:
SRK record recreated from the binary data.
- get_key_name()#
Get text key name in SRK record.
- Return type:
str
- Returns:
Key name.
- get_public_key(encoding=SPSDKEncoding.PEM)#
Store the SRK public key as a file.
- Parameters:
encoding (
SPSDKEncoding
) – Public key encoding style, default is PEM.- Raises:
SPSDKError – Unsupported public key
- Return type:
bytes
- class spsdk.image.ahab.ahab_container.SRKTable(srk_records=None)#
Bases:
HeaderContainerInversed
Class representing SRK (Super Root Key) table in the AHAB container as part of signature block.
SRK Table:
+-----+---------------------------------------------------------------+ |Off | Byte 3 | Byte 2 | Byte 1 | Byte 0 | +-----+---------------------------------------------------------------+ |0x00 | Tag | Length of SRK Table | Version | +-----+---------------------------------------------------------------+ |0x04 | SRK Record 1 | +-----+---------------------------------------------------------------+ |... | SRK Record 2 | +-----+---------------------------------------------------------------+ |... | SRK Record 3 | +-----+---------------------------------------------------------------+ |... | SRK Record 4 | +-----+---------------------------------------------------------------+
Class object initializer.
- Parameters:
srk_records (
Optional
[List
[SRKRecord
]]) – list of SRKRecord objects.
- TAG = 215#
- VERSION = 66#
- SRK_RECORDS_CNT = 4#
- clear()#
Clear the SRK Table Object.
- Return type:
None
- add_record(public_key, srk_flags=0)#
Add SRK table record.
- Parameters:
public_key (
PublicKey
) – Loaded public key.srk_flags (
int
) – SRK flags for key.
- Return type:
None
- update_fields()#
Update all fields depended on input values.
- Return type:
None
- compute_srk_hash()#
Computes a SHA256 out of all SRK records.
- Return type:
bytes
- Returns:
SHA256 computed over SRK records.
- get_source_keys()#
Return list of source public keys.
Either from the src_key field or recreate them. :rtype:
List
[PublicKey
] :return: List of public keys.
- export()#
Serializes container object into bytes in little endian.
- Return type:
bytes
- Returns:
bytes representing container content.
- validate(data)#
Validate object data.
- Parameters:
data (
Dict
[str
,Any
]) – Additional validation data.- Raises:
SPSDKValueError – Invalid any value of Image Array entry
- Return type:
None
- classmethod parse(data)#
Parse input binary chunk to the container object.
- Parameters:
data (
bytes
) – Binary data with SRK table block to parse.- Raises:
SPSDKLengthError – Invalid length of SRK table data block.
- Return type:
Self
- Returns:
Object recreated from the binary data.
- create_config(index, data_path)#
Create configuration of the AHAB Image SRK Table.
- Parameters:
index (
int
) – Container Index.data_path (
str
) – Path to store the data files of configuration.
- Return type:
Dict
[str
,Any
]- Returns:
Configuration dictionary.
- static load_from_config(config, search_paths=None)#
Converts the configuration option into an AHAB image object.
“config” content of container configurations.
- Parameters:
config (
Dict
[str
,Any
]) – array of AHAB containers configuration dictionaries.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
- Returns:
SRK Table object.
- class spsdk.image.ahab.ahab_container.ContainerSignature(signature_data=None, signature_provider=None)#
Bases:
HeaderContainer
Class representing the signature in AHAB container as part of the signature block.
Signature:
+-----+--------------+--------------+----------------+----------------+ |Off | Byte 3 | Byte 2 | Byte 1 | Byte 0 | +-----+--------------+--------------+----------------+----------------+ |0x00 | Tag | Length (MSB) | Length (LSB) | Version | +-----+--------------+--------------+----------------+----------------+ |0x04 | Reserved | +-----+---------------------------------------------------------------+ |0x08 | Signature Data | +-----+---------------------------------------------------------------+
Class object initializer.
- Parameters:
signature_data (
Optional
[bytes
]) – signature.signature_provider (
Optional
[SignatureProvider
]) – Signature provider use to sign the image.
- TAG = 216#
- VERSION = 0#
- property signature_data: bytes#
Get the signature data.
- Returns:
signature data.
- classmethod format()#
Format of binary representation.
- Return type:
str
- sign(data_to_sign)#
Sign the data_to_sign and store signature into class.
- Parameters:
data_to_sign (
bytes
) – Data to be signed by store private key- Raises:
SPSDKError – Missing private key or raw signature data.
- Return type:
None
- export()#
Export signature data that is part of Signature Block.
- Return type:
bytes
- Returns:
bytes representing container signature content.
- validate()#
Validate object data.
- Raises:
SPSDKValueError – Invalid any value of Image Array entry
- Return type:
None
- classmethod parse(data)#
Parse input binary chunk to the container object.
- Parameters:
data (
bytes
) – Binary data with Container signature block to parse.- Return type:
Self
- Returns:
Object recreated from the binary data.
- static load_from_config(config, search_paths=None)#
Converts the configuration option into an AHAB image object.
“config” content of container configurations.
- Parameters:
config (
Dict
[str
,Any
]) – array of AHAB containers configuration dictionaries.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
- Returns:
Container signature object.
- class spsdk.image.ahab.ahab_container.Certificate(permissions=0, uuid=None, public_key=None, signature_provider=None)#
Bases:
HeaderContainer
Class representing certificate in the AHAB container as part of the signature block.
The Certificate comes in two forms - with and without UUID.
Certificate format 1:
+-----+--------------+--------------+----------------+----------------+ |Off | Byte 3 | Byte 2 | Byte 1 | Byte 0 | +-----+--------------+--------------+----------------+----------------+ |0x00 | Tag | Length (MSB) | Length (LSB) | Version | +-----+--------------+--------------+----------------+----------------+ |0x04 | Permissions | Perm (invert)| Signature offset | +-----+--------------+--------------+---------------------------------+ |0x08 | Public Key | +-----+---------------------------------------------------------------+ |... | Signature | +-----+---------------------------------------------------------------+
Certificate format 2:
+-----+--------------+--------------+----------------+----------------+ |Off | Byte 3 | Byte 2 | Byte 1 | Byte 0 | +-----+--------------+--------------+----------------+----------------+ |0x00 | Tag | Length (MSB) | Length (LSB) | Version | +-----+--------------+--------------+----------------+----------------+ |0x04 | Permissions | Perm (invert)| Signature offset | +-----+--------------+--------------+---------------------------------+ |0x08 | UUID | +-----+---------------------------------------------------------------+ |... | Public Key | +-----+---------------------------------------------------------------+ |... | Signature | +-----+---------------------------------------------------------------+
Class object initializer.
- Parameters:
permissions (
int
) – used to indicate what a certificate can be used for.uuid (
Optional
[bytes
]) – optional 128-bit unique identifier.public_key (
Optional
[SRKRecord
]) – public Key. SRK record entry describing the key.signature_provider (
Optional
[SignatureProvider
]) – Signature provider for certificate. Signature is calculated over all data from beginning of the certificate up to, but not including the signature.
- TAG = [160, 175]#
- UUID_LEN = 16#
- UUID_OFFSET = 8#
- VERSION = 0#
- PERM_NXP = {'hdcp_fuses': 32, 'hdmi_debug': 4, 'life_cycle': 16, 'secure_enclave_debug': 2}#
- PERM_OEM = {'container': 1, 'life_cycle': 16, 'monotonic_counter': 32, 'phbc_debug': 2, 'soc_debug_domain_1': 4, 'soc_debug_domain_2': 8}#
- PERM_SIZE = 8#
- classmethod format()#
Format of binary representation.
- Return type:
str
- static create_permissions(permissions)#
Create integer representation of permission field.
- Parameters:
permissions (
List
[str
]) – List of string permissions.- Return type:
int
- Returns:
Integer representation of permissions.
- property permission_to_sign_container: bool#
Certificate has permission to sign container.
- create_config_permissions(srk_set)#
Create list of string representation of permission field.
- Parameters:
srk_set (
str
) – SRK set to get proper string values.- Return type:
List
[str
]- Returns:
List of string representation of permissions.
- get_signature_data()#
Returns binary data to be signed.
The certificate block must be properly initialized, so the data are valid for signing. There is signed whole certificate block without signature part.
- Raises:
SPSDKValueError – if Signature Block or SRK Table is missing.
- Return type:
bytes
- Returns:
bytes representing data to be signed.
- update_fields()#
Update all fields depended on input values.
- Return type:
None
- export()#
Export container certificate object into bytes.
- Return type:
bytes
- Returns:
bytes representing container content.
- validate()#
Validate object data.
- Raises:
SPSDKValueError – Invalid any value of Image Array entry
- Return type:
None
- classmethod parse(data)#
Parse input binary chunk to the container object.
- Parameters:
data (
bytes
) – Binary data with Certificate block to parse.- Raises:
SPSDKValueError – Certificate permissions are invalid.
- Return type:
Self
- Returns:
Object recreated from the binary data.
- create_config(index, data_path, srk_set='oem')#
Create configuration of the AHAB Image Certificate.
- Parameters:
index (
int
) – Container Index.data_path (
str
) – Path to store the data files of configuration.srk_set (
str
) – SRK set to know how to create certificate permissions.
- Return type:
Dict
[str
,Any
]- Returns:
Configuration dictionary.
- static load_from_config(config, search_paths=None)#
Converts the configuration option into an AHAB image signature block certificate object.
“config” content of container configurations.
- Parameters:
config (
Dict
[str
,Any
]) – array of AHAB containers configuration dictionaries.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
- Returns:
Certificate object.
- static get_validation_schemas()#
Get list of validation schemas.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
Validation list of schemas.
- static generate_config_template()#
Generate AHAB configuration template.
- Return type:
str
- Returns:
Certificate configuration templates.
- class spsdk.image.ahab.ahab_container.Blob(flags=128, size=0, algorithm=KeyBlobEncryptionAlgorithm.AES_CBC, mode=0, dek=None, dek_keyblob=None, key_identifier=0)#
Bases:
HeaderContainer
The Blob object used in Signature Container.
Blob (DEK) content:
+-----+--------------+--------------+----------------+----------------+ |Off | Byte 3 | Byte 2 | Byte 1 | Byte 0 | +-----+--------------+--------------+----------------+----------------+ |0x00 | Tag | Length (MSB) | Length (LSB) | Version | +-----+--------------+--------------+----------------+----------------+ |0x04 | Mode | Algorithm | Size | Flags | +-----+--------------+--------------+----------------+----------------+ |0x08 | Wrapped Key | +-----+--------------+--------------+----------------+----------------+
Class object initializer.
- Parameters:
flags (
int
) – Keyblob flagssize (
int
) – key size [128,192,256]dek (
Optional
[bytes
]) – DEK keymode (
int
) – DEK BLOB modealgorithm (
KeyBlobEncryptionAlgorithm
) – Encryption algorithmdek_keyblob (
Optional
[bytes
]) – DEK keyblobkey_identifier (
int
) – Key identifier. Must be same as it was used for keyblob generation
- TAG = 129#
- VERSION = 0#
- FLAGS = 128#
- SUPPORTED_KEY_SIZES = [128, 192, 256]#
- static compute_keyblob_size(key_size)#
Compute Keyblob size.
- Parameters:
key_size (
int
) – Input AES key size in bits- Return type:
int
- Returns:
Keyblob size in bytes.
- classmethod format()#
Format of binary representation.
- Return type:
str
- export()#
Export Signature Block Blob.
- Return type:
bytes
- Returns:
bytes representing Signature Block Blob.
- validate()#
Validate object data.
- Raises:
SPSDKValueError – Invalid any value of AHAB Blob
- Return type:
None
- classmethod parse(data)#
Parse input binary chunk to the container object.
- Parameters:
data (
bytes
) – Binary data with Blob block to parse.- Return type:
Self
- Returns:
Object recreated from the binary data.
- create_config(index, data_path)#
Create configuration of the AHAB Image Blob.
- Parameters:
index (
int
) – Container Index.data_path (
str
) – Path to store the data files of configuration.
- Return type:
Dict
[str
,Any
]- Returns:
Configuration dictionary.
- static load_from_config(config, search_paths=None)#
Converts the configuration option into an AHAB image signature block blob object.
“config” content of container configurations.
- Parameters:
config (
Dict
[str
,Any
]) – Blob configurationsearch_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Raises:
SPSDKValueError – Invalid configuration - Invalid DEK KeyBlob
- Return type:
- Returns:
Blob object.
- encrypt_data(iv, data)#
Encrypt data.
- Parameters:
iv (
bytes
) – Initial vector 128 bits lengthdata (
bytes
) – Data to encrypt
- Raises:
SPSDKError – Missing DEK, unsupported algorithm
- Return type:
bytes
- Returns:
Encrypted data
- decrypt_data(iv, encrypted_data)#
Encrypt data.
- Parameters:
iv (
bytes
) – Initial vector 128 bits lengthencrypted_data (
bytes
) – Data to decrypt
- Raises:
SPSDKError – Missing DEK, unsupported algorithm
- Return type:
bytes
- Returns:
Plain data
- class spsdk.image.ahab.ahab_container.SignatureBlock(srk_table=None, container_signature=None, certificate=None, blob=None)#
Bases:
HeaderContainer
Class representing signature block in the AHAB container.
Signature Block:
+---------------+----------------+----------------+----------------+-----+ | Byte 3 | Byte 2 | Byte 1 | Byte 0 | Fix | |---------------+----------------+----------------+----------------+ len | | Tag | Length | Version | | |---------------+---------------------------------+----------------+ | | SRK Table Offset | Certificate Offset | | |--------------------------------+---------------------------------+ | | Blob Offset | Signature Offset | | |--------------------------------+---------------------------------+ | | Key identifier in case that Blob is present | | +------------------------------------------------------------------+-----+ Starting offset | SRK Table | | +------------------------------------------------------------------+-----+ Padding length | 64 bit alignment | | +------------------------------------------------------------------+-----+ Starting offset | Signature | | +------------------------------------------------------------------+-----+ Padding length | 64 bit alignment | | +------------------------------------------------------------------+-----+ Starting offset | Certificate | | +------------------------------------------------------------------+-----+ Padding length | 64 bit alignment | | +------------------------------------------------------------------+-----+ Starting offset | Blob | | +------------------------------------------------------------------+-----+
Class object initializer.
- Parameters:
srk_table (
Optional
[SRKTable
]) – SRK table.container_signature (
Optional
[ContainerSignature
]) – container signature.certificate (
Optional
[Certificate
]) – container certificate.blob (
Optional
[Blob
]) – container blob.
- TAG = 144#
- VERSION = 0#
- classmethod format()#
Format of binary representation.
- Return type:
str
- update_fields()#
Update all fields depended on input values.
- Return type:
None
- export()#
Export Signature block.
- Raises:
SPSDKLengthError – if exported data length doesn’t match container length.
- Return type:
bytes
- Returns:
bytes signature block content.
- validate(data)#
Validate object data.
- Parameters:
data (
Dict
[str
,Any
]) – Additional validation data.- Raises:
SPSDKValueError – Invalid any value of Image Array entry
- Return type:
None
- classmethod parse(data)#
Parse input binary chunk to the container object.
- Parameters:
data (
bytes
) – Binary data with Signature block to parse.- Return type:
Self
- Returns:
Object recreated from the binary data.
- static load_from_config(config, search_paths=None)#
Converts the configuration option into an AHAB Signature block object.
“config” content of container configurations.
- Parameters:
config (
Dict
[str
,Any
]) – array of AHAB signature block configuration dictionaries.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
- Returns:
AHAB Signature block object.
- class spsdk.image.ahab.ahab_container.AHABContainerBase(flags=0, fuse_version=0, sw_version=0, signature_block=None)#
Bases:
HeaderContainer
Class representing AHAB container base class (common for Signed messages and AHAB Image).
Container header:
+---------------+----------------+----------------+----------------+ | Byte 3 | Byte 2 | Byte 1 | Byte 0 | +---------------+----------------+----------------+----------------+ | Tag | Length | Version | +---------------+---------------------------------+----------------+ | Flags | +---------------+----------------+---------------------------------+ | # of images | Fuse version | SW version | +---------------+----------------+---------------------------------+ | Reserved | Signature Block Offset | +--------------------------------+---------------------------------+ | Payload (Signed Message or Image Array) | +------------------------------------------------------------------+ | Signature block | +------------------------------------------------------------------+
Class object initializer.
- Parameters:
flags (
int
) – flags.fuse_version (
int
) – value must be equal to or greater than the version stored in the fuses to allow loading this container.sw_version (
int
) – used by PHBC (Privileged Host Boot Companion) to select between multiple images with same fuse version field.signature_block (
Optional
[SignatureBlock
]) – signature block.
- TAG = 0#
- VERSION = 0#
- FLAGS_SRK_SET_OFFSET = 0#
- FLAGS_SRK_SET_SIZE = 2#
- FLAGS_SRK_SET_VAL = {'none': 0, 'nxp': 1, 'oem': 2}#
- FLAGS_USED_SRK_ID_OFFSET = 4#
- FLAGS_USED_SRK_ID_SIZE = 2#
- FLAGS_SRK_REVOKE_MASK_OFFSET = 8#
- FLAGS_SRK_REVOKE_MASK_SIZE = 4#
- set_flags(srk_set='none', used_srk_id=0, srk_revoke_mask=0)#
Set the flags value.
- Parameters:
srk_set (
str
) – Super Root Key (SRK) set, defaults to “none”used_srk_id (
int
) – Which key from SRK set is being used, defaults to 0srk_revoke_mask (
int
) – SRK revoke mask, defaults to 0
- Return type:
None
- property flag_srk_set: str#
SRK set flag in string representation.
- Returns:
Name of SRK Set flag.
- property flag_used_srk_id: int#
Used SRK ID flag.
- Returns:
Index of Used SRK ID.
- property flag_srk_revoke_mask: str#
SRK Revoke mask flag.
- Returns:
SRK revoke mask in HEX.
- property image_array_len: int#
Get image array length if available.
- Returns:
Length of image array.
- header_length()#
Length of AHAB Container header.
- Return type:
int
- Returns:
Length in bytes of AHAB Container header.
- classmethod format()#
Format of binary representation.
- Return type:
str
- update_fields()#
Updates all volatile information in whole container structure.
- Raises:
SPSDKError – When inconsistent image array length is detected.
- Return type:
None
- get_signature_data()#
Returns binary data to be signed.
The container must be properly initialized, so the data are valid for signing, i.e. the offsets, lengths etc. must be set prior invoking this method, otherwise improper data will be signed.
The whole container gets serialized first. Afterwards the binary data is sliced so only data for signing get’s returned. The signature data length is evaluated based on offsets, namely the signature block offset, the container signature offset and the container signature fixed data length.
Signature data structure:
+---------------------------------------------------+----------------+ | Container header | | +---+---+-----------+---------+--------+------------+ Data | | S | | tag | length | length | version | | | i | +-----------+---------+--------+------------+ | | g | | flags | to | | n | +---------------------+---------------------+ | | a | | srk table offset | certificate offset | | | t | +---------------------+---------------------+ Sign | | u | | blob offset | signature offset | | | r | +---------------------+---------------------+ | | e | | SRK Table | | | +---+-----------+---------+--------+------------+----------------+ | B | S | tag | length | length | version | Signature data | | l | i +-----------+---------+--------+------------+ fixed length | | o | g | Reserved | | | c | n +-------------------------------------------+----------------+ | k | a | Signature data | | | t | | | | u | | | | r | | | | e | | +---+---+-------------------------------------------+
- Raises:
SPSDKValueError – if Signature Block or SRK Table is missing.
- Return type:
bytes
- Returns:
bytes representing data to be signed.
- validate(data)#
Validate object data.
- Parameters:
data (
Dict
[str
,Any
]) – Additional validation data.- Raises:
SPSDKValueError – Invalid any value of Image Array entry
- Return type:
None
- load_from_config_generic(config)#
Converts the configuration option into an AHAB image object.
“config” content of container configurations.
- Parameters:
config (
Dict
[str
,Any
]) – array of AHAB containers configuration dictionaries.- Return type:
None
- class spsdk.image.ahab.ahab_container.AHABContainer(parent, flags=0, fuse_version=0, sw_version=0, image_array=None, signature_block=None, container_offset=0)#
Bases:
AHABContainerBase
Class representing AHAB container.
Container header:
+---------------+----------------+----------------+----------------+ | Byte 3 | Byte 2 | Byte 1 | Byte 0 | +---------------+----------------+----------------+----------------+ | Tag | Length | Version | +---------------+---------------------------------+----------------+ | Flags | +---------------+----------------+---------------------------------+ | # of images | Fuse version | SW version | +---------------+----------------+---------------------------------+ | Reserved | Signature Block Offset | +----+---------------------------+---------------------------------+ | I |image0: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV | + m |-------------------------------------------------------------+ | g |image1: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV | + . |-------------------------------------------------------------+ | A |... | | r |... | | r | | + a |-------------------------------------------------------------+ | y |imageN: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV | +----+-------------------------------------------------------------+ | Signature block | +------------------------------------------------------------------+ | | | | | | +------------------------------------------------------------------+ | Data block_0 | +------------------------------------------------------------------+ | | | | +------------------------------------------------------------------+ | Data block_n | +------------------------------------------------------------------+
Class object initializer.
- Parent:
Parent AHABImage object.
- Parameters:
flags (
int
) – flags.fuse_version (
int
) – value must be equal to or greater than the version stored in the fuses to allow loading this container.sw_version (
int
) – used by PHBC (Privileged Host Boot Companion) to select between multiple images with same fuse version field.image_array (
Optional
[List
[ImageArrayEntry
]]) – array of image entries, must be number of images long.signature_block (
Optional
[SignatureBlock
]) – signature block.
- TAG = 135#
- property image_array_len: int#
Get image array length if available.
- Returns:
Length of image array.
- header_length()#
Length of AHAB Container header.
- Return type:
int
- Returns:
Length in bytes of AHAB Container header.
- update_fields()#
Updates all volatile information in whole container structure.
- Raises:
SPSDKError – When inconsistent image array length is detected.
- Return type:
None
- decrypt_data()#
Decrypt all images if possible.
- Return type:
None
- export()#
Export container header into bytes.
- Return type:
bytes
- Returns:
bytes representing container header content including the signature block.
- validate(data)#
Validate object data.
- Parameters:
data (
Dict
[str
,Any
]) – Additional validation data.- Raises:
SPSDKValueError – Invalid any value of Image Array entry
- Return type:
None
- classmethod parse(data, parent, container_id)#
Parse input binary chunk to the container object.
- Parameters:
data (
bytes
) – Binary data with Container block to parse.parent (
AHABImage
) – AHABImage object.container_id (
int
) – AHAB container ID.
- Return type:
Self
- Returns:
Object recreated from the binary data.
- create_config(index, data_path)#
Create configuration of the AHAB Image.
- Parameters:
index (
int
) – Container index.data_path (
str
) – Path to store the data files of configuration.
- Return type:
Dict
[str
,Any
]- Returns:
Configuration dictionary.
- static load_from_config(parent, config, container_ix)#
Converts the configuration option into an AHAB image object.
“config” content of container configurations.
- Parameters:
parent (
AHABImage
) – AHABImage object.config (
Dict
[str
,Any
]) – array of AHAB containers configuration dictionaries.container_ix (
int
) – Container index that is loaded.
- Return type:
- Returns:
AHAB Container object.
- image_info()#
Get Image info object.
- Return type:
- Returns:
AHAB Container Info object.
- class spsdk.image.ahab.ahab_container.AHABImage(family, revision='latest', target_memory='nor', ahab_containers=None, search_paths=None)#
Bases:
object
Class representing an AHAB image.
The image consists of multiple AHAB containers.
AHAB Image constructor.
- Parameters:
family (
str
) – Name of device family.revision (
str
) – Device silicon revision, defaults to “latest”target_memory (
str
) – Target memory for AHAB image [serial_downloader, nor, nand], defaults to “nor”ahab_containers (
Optional
[List
[AHABContainer
]]) – _description_, defaults to Nonesearch_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Raises:
SPSDKValueError – Invalid input configuration.
- TARGET_MEMORIES = ['serial_downloader', 'nor', 'nand_4k', 'nand_2k']#
- add_container(container)#
Add new container into AHAB Image.
The order of the added images is important. :type container:
AHABContainer
:param container: New AHAB Container to be added. :raises SPSDKLengthError: The container count in image is overflowed.- Return type:
None
- clear()#
Clear list of containers.
- Return type:
None
- update_fields(update_offsets=True)#
Automatically updates all volatile fields in every AHAB container.
- Parameters:
update_offsets (
bool
) – Update also offsets for serial_downloader.- Return type:
None
- get_containers_size()#
Get maximal containers size.
In fact get the offset where could be stored first data.
- Return type:
int
- Returns:
Size of containers.
- get_first_data_image_address()#
Get first data image address.
- Return type:
int
- Returns:
Address of first data image.
- export()#
Export AHAB Image.
- Raises:
SPSDKValueError – mismatch between number of containers and offsets.
SPSDKValueError – number of images mismatch.
- Return type:
bytes
- Returns:
bytes AHAB Image.
- image_info()#
Get Image info object.
- Return type:
- validate()#
Validate object data.
- Raises:
SPSDKValueError – Invalid any value of Image Array entry.
SPSDKError – In case of Binary Image validation fail.
- Return type:
None
- static load_from_config(config, search_paths=None)#
Converts the configuration option into an AHAB image object.
“config” content array of containers configurations.
- Parameters:
config (
Dict
[str
,Any
]) – array of AHAB containers configuration dictionaries.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Raises:
SPSDKValueError – if the count of AHAB containers is invalid.
SPSDKParsingError – Cannot parse input binary AHAB container.
- Return type:
- Returns:
Initialized AHAB Image.
- parse(binary)#
Parse input binary chunk to the container object.
- Raises:
SPSDKError – No AHAB container found in binary data.
- Return type:
None
- static get_supported_families()#
Get all supported families for AHAB container.
- Return type:
List
[str
]- Returns:
List of supported families.
- static get_validation_schemas()#
Get list of validation schemas.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
Validation list of schemas.
- static generate_config_template(family)#
Generate AHAB configuration template.
- Parameters:
family (
str
) – Family for which the template should be generated.- Return type:
Dict
[str
,Any
]- Returns:
Dictionary of individual templates (key is name of template, value is template itself).
- create_config(data_path)#
Create configuration of the AHAB Image.
- Parameters:
data_path (
str
) – Path to store the data files of configuration.- Return type:
Dict
[str
,Any
]- Returns:
Configuration dictionary.
- create_srk_hash_blhost_script(container_ix=0)#
Create BLHOST script to load SRK hash into fuses.
- Parameters:
container_ix (
int
) – Container index.- Raises:
SPSDKValueError – Invalid input value - Non existing container or unsupported type.
SPSDKError – Invalid SRK hash.
- Return type:
str
- Returns:
Script used by BLHOST to load SRK hash.
AHAB Utilities#
AHAB utils module.
- spsdk.image.ahab.utils.ahab_update_keyblob(family, binary, keyblob, container_id, mem_type)#
Update keyblob in AHAB image.
- Parameters:
family (
str
) – MCU familybinary (
str
) – Path to AHAB image binarykeyblob (
str
) – Path to keyblobcontainer_id (
int
) – Index of the container to be updatedmem_type (
Optional
[str
]) – Memory type used for bootable image
- Raises:
SPSDKError – In case the container id not present
SPSDKError – In case the AHAB image does not contain blob
SPSDKError – In case the length of keyblobs don’t match
- Return type:
None
AHAB Container Interface#
AHAB abstract classes.
- class spsdk.image.ahab.ahab_abstract_interfaces.Container#
Bases:
BaseClass
Base class for any container.
- classmethod fixed_length()#
Returns the length of a container which is fixed.
i.e. part of a container holds fixed values, whereas some entries have variable length.
- Return type:
int
- export()#
Serialize object into bytes array.
- Return type:
bytes
- classmethod parse(data)#
Deserialize object from bytes array.
- Return type:
Self
- classmethod format()#
Returns the container data format as defined by struct package.
The base returns only endianness (LITTLE_ENDIAN).
- Return type:
str
- class spsdk.image.ahab.ahab_abstract_interfaces.HeaderContainer(tag, length, version)#
Bases:
Container
A container with first byte defined as header - tag, length and version.
Every “container” in AHAB consists of a header - tag, length and version.
The only exception is the ‘image array’ or ‘image array entry’ respectively which has no header at all and SRK record, which has ‘signing algorithm’ instead of version. But this can be considered as a sort of SRK record ‘version’.
Class object initialized.
- Parameters:
tag (
int
) – container tag.length (
int
) – container length.version (
int
) – container version.
- TAG = 0#
- VERSION = 0#
- classmethod format()#
Format of binary representation.
- Return type:
str
- validate_header()#
Validates the header of container properties…
i.e. tag e <0; 255>, otherwise an exception is raised. :raises SPSDKValueError: Any MAndatory field has invalid value.
- Return type:
None
- classmethod parse_head(binary)#
Parse binary data to get head members.
- Parameters:
binary (
bytes
) – Binary data.- Raises:
SPSDKLengthError – Binary data length is not enough.
- Return type:
Tuple
[int
,int
,int
]- Returns:
Tuple with TAG, LENGTH, VERSION
- classmethod check_container_head(binary)#
Compares the data length and container length.
This is just a helper function used throughout the code.
- Parameters:
binary (
bytes
) – Binary input data.- Raises:
SPSDKLengthError – If containers length is larger than data length.
SPSDKParsingError – If containers header value doesn’t match.
- Return type:
None
- class spsdk.image.ahab.ahab_abstract_interfaces.HeaderContainerInversed(tag, length, version)#
Bases:
HeaderContainer
A container with first byte defined as header - tag, length and version.
It same as “HeaderContainer” only the tag/length/version are in reverse order in binary form.
Class object initialized.
- Parameters:
tag (
int
) – container tag.length (
int
) – container length.version (
int
) – container version.
- classmethod parse_head(binary)#
Parse binary data to get head members.
- Parameters:
binary (
bytes
) – Binary data.- Raises:
SPSDKLengthError – Binary data length is not enough.
- Return type:
Tuple
[int
,int
,int
]- Returns:
Tuple with TAG, LENGTH, VERSION
Signed Messages#
Implementation of raw AHAB container support.
This module represents a generic AHAB container implementation. You can set the containers values at will. From this perspective, consult with your reference manual of your device for allowed values.
- class spsdk.image.ahab.signed_msg.Message(cert_ver=0, permissions=0, issue_date=None, cmd=0, unique_id=None)#
Bases:
Container
Class representing the Signed message.
- Message::
Off
Byte 3
Byte 2
Byte 1
Byte 0
0x00
Message header
0x10
Message payload
- Message header::
Off
Byte 3
Byte 2
Byte 1
Byte 0
0x00
Cert version
Permission
Issue date
0x04
Reserved
Command
Reserved
0x08
Unique ID (Lower 32 bits)
0x0c
Unique ID (Upper 32 bits)
The message header is common for all signed messages.
Message used to sign and send to device with EdgeLock.
- Parameters:
cert_ver (
int
) – Certificate version, defaults to 0permissions (
int
) – Certificate permission, to be used in future The stated permission must allow the operation requested by the signed message , defaults to 0issue_date (
Optional
[int
]) – Issue date, defaults to None (Current date will be applied)cmd (
int
) – Message command ID, defaults to 0unique_id (
Optional
[bytes
]) – UUID of device (least 64 bits is used), defaults to None
- PAYLOAD_LENGTH = 0#
- TAG = 0#
- UNIQUE_ID_LEN = 8#
- abstract create_config()#
Create configuration of the Signed Message.
- Return type:
Dict
[str
,Any
]- Returns:
Configuration dictionary.
- export()#
Exports message into to bytes array.
- Return type:
bytes
- Returns:
Bytes representation of message object.
- abstract export_payload()#
Exports message payload to bytes array.
- Return type:
bytes
- Returns:
Bytes representation of message payload.
- classmethod format()#
Format of binary representation.
- Return type:
str
- classmethod get_message_class(cmd)#
Get the dedicated message class for command.
- Return type:
Type
[Self
]
- static load_from_config(config, search_paths=None)#
Converts the configuration option into an message object.
“config” content of container configurations.
- Parameters:
config (
Dict
[str
,Any
]) – Message configuration dictionaries.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
- Returns:
Message object.
- static load_from_config_generic(config)#
Converts the general configuration option into an message object.
“config” content of container configurations.
- Parameters:
config (
Dict
[str
,Any
]) – Message configuration dictionaries.- Return type:
Tuple
[int
,int
,Optional
[int
],bytes
]- Returns:
Message object.
- classmethod parse(data)#
Parse input binary to the signed message object.
- Parameters:
data (
bytes
) – Binary data with Container block to parse.- Return type:
Self
- Returns:
Object recreated from the binary data.
- abstract parse_payload(data)#
Parse payload.
- Parameters:
data (
bytes
) – Binary data with Payload to parse.- Return type:
None
- property payload_len: int#
Message payload length in bytes.
- validate()#
Validate general message properties.
- Return type:
None
- class spsdk.image.ahab.signed_msg.MessageCommands(tag, label, description=None)#
Bases:
SpsdkEnum
Signed messages commands.
- KEYSTORE_REPROVISIONING_ENABLE_REQ = (63, 'KEYSTORE_REPROVISIONING_ENABLE_REQ', 'Key store reprovisioning enable')#
- KEY_EXCHANGE_REQ = (71, 'KEY_EXCHANGE_REQ', 'Key exchange signed message content')#
- RETURN_LIFECYCLE_UPDATE_REQ = (160, 'RETURN_LIFECYCLE_UPDATE_REQ', 'Return lifecycle update request.')#
- WRITE_SEC_FUSE_REQ = (145, 'WRITE_SEC_FUSE_REQ', 'Write secure fuse request.')#
- class spsdk.image.ahab.signed_msg.MessageKeyExchange(cert_ver=0, permissions=0, issue_date=None, unique_id=None, key_store_id=0, key_exchange_algorithm=KeyExchangeAlgorithm.HKDF_SHA256, salt_flags=0, derived_key_grp=0, derived_key_size_bits=0, derived_key_type=DerivedKeyType.AES, derived_key_lifetime=LifeTime.PERSISTENT, derived_key_usage=None, derived_key_permitted_algorithm=KeyDerivationAlgorithm.HKDF_SHA256, derived_key_lifecycle=LifeCycle.OPEN, derived_key_id=0, private_key_id=0, input_peer_public_key_digest=b'', input_user_fixed_info_digest=b'')#
Bases:
Message
Key exchange request message class representation.
Key exchange signed message class init.
- Parameters:
cert_ver (
int
) – Certificate version, defaults to 0permissions (
int
) – Certificate permission, to be used in future The stated permission must allow the operation requested by the signed message , defaults to 0issue_date (
Optional
[int
]) – Issue date, defaults to None (Current date will be applied)unique_id (
Optional
[bytes
]) – UUID of device (least 64 bits is used), defaults to Nonekey_store_id (
int
) – Key store ID where to store the derived key. It must be the key store ID related to the key management handle set in the command API, defaults to 0key_exchange_algorithm (
KeyExchangeAlgorithm
) –Algorithm used by the key exchange process:
HKDF SHA256 0x09020109HKDF SHA384 0x0902010A, defaults to HKDF_SHA256salt_flags (
int
) –Bit field indicating the requested operations:
Bit 0: Salt in step #1 (HKDF-extract) of HMAC based two-step key derivation process:- 0: Use zeros salt;- 1:Use peer public key hash as salt;Bit 1: In case of ELE import, salt used to derive OEM_IMPORT_WRAP_SK and OEM_IMPORT_CMAC_SK:- 0: Zeros string;- 1: Device SRKH.Bit 2 to 15: Reserved, defaults to 0derived_key_grp (
int
) – Derived key group. 100 groups are available per key store. It must be a value in the range [0; 99]. Keys belonging to the same group can be managed through the Manage key group command, defaults to 0derived_key_size_bits (
int
) – Derived key size bits attribute, defaults to 0derived_key_type (
DerivedKeyType
) –Key type
Value
Key size in bits
AES
0x2400
128/192/256
HMAC
0x1100
224/256/384/512
OEM_IMPORT_MK_SK*
0x9200
128/192/256
, defaults to AES
derived_key_lifetime (
LifeTime
) –Derived key lifetime attribute
VOLATILE 0x00 Standard volatile key.PERSISTENT 0x01 Standard persistent key.PERMANENT 0xFF Standard permanent key., defaults to PERSISTENTderived_key_usage (
Optional
[List
[DerivedKeyUsage
]]) –Derived key usage attribute.
Cache 0x00000004 Permission to cache the key in the ELE internal secure memory.This usage is set by default by ELE FW for all keys generated or imported.Encrypt 0x00000100 Permission to encrypt a message with the key. It could be cipherencryption, AEAD encryption or asymmetric encryption operation.Decrypt 0x00000200 Permission to decrypt a message with the key. It could becipher decryption, AEAD decryption or asymmetric decryption operation.Sign message 0x00000400 Permission to sign a message with the key. It could bea MAC generation or an asymmetric message signature operation.Verify message 0x00000800 Permission to verify a message signature with the key.It could be a MAC verification or an asymmetric message signatureverification operation.Sign hash 0x00001000 Permission to sign a hashed message with the keywith an asymmetric signature operation. Setting this permission automaticallysets the Sign Message usage.Verify hash 0x00002000 Permission to verify a hashed message signature withthe key with an asymmetric signature verification operation.Setting this permission automatically sets the Verify Message usage.Derive 0x00004000 Permission to derive other keys from this key., defaults to 0derived_key_permitted_algorithm (
KeyDerivationAlgorithm
) –Derived key permitted algorithm attribute
HKDF SHA256 (HMAC two-step) 0x08000109HKDF SHA384 (HMAC two-step) 0x0800010A, defaults to HKDF_SHA256derived_key_lifecycle (
LifeCycle
) –Derived key lifecycle attribute
CURRENT 0x00 Key is usable in current lifecycle.OPEN 0x01 Key is usable in open lifecycle.CLOSED 0x02 Key is usable in closed lifecycle.CLOSED and LOCKED 0x04 Key is usable in closed and locked lifecycle., defaults to OPENderived_key_id (
int
) –Derived key ID attribute. It could be:
- Wanted key identifier of the generated key: only supported by persistent
and permanent keys;
- 0x00000000 to let the FW chose the key identifier: supported by all
keys (all persistence levels). , defaults to 0
private_key_id (
int
) – Identifier in the ELE key storage of the private key to use with the peer public key during the key agreement process, defaults to 0input_peer_public_key_digest (
bytes
) – Input peer public key digest buffer. The algorithm used to generate the digest must be SHA256, defaults to list(8)input_user_fixed_info_digest (
bytes
) – Input user fixed info digest buffer. The algorithm used to generate the digest must be SHA256, defaults to list(8)
- class DerivedKeyType(tag, label, description=None)#
Bases:
SpsdkEnum
Derived Key Type valid values.
- AES = (9216, 'AES SHA256', 'Possible bit widths: 128/192/256')#
- HMAC = (4352, 'HMAC SHA384', 'Possible bit widths: 224/256/384/512')#
- OEM_IMPORT_MK_SK = (37376, 'OEM_IMPORT_MK_SK', 'Possible bit widths: 128/192/256')#
- class DerivedKeyUsage(tag, label, description=None)#
Bases:
SpsdkEnum
Derived Key Usage valid values.
- CACHE = (4, 'Cache', 'Permission to cache the key in the ELE internal secure memory. This usage is set by default by ELE FW for all keys generated or imported.')#
- DECRYPT = (512, 'Decrypt', 'Permission to decrypt a message with the key. It could be cipher decryption, AEAD decryption or asymmetric decryption operation.')#
- DERIVE = (16384, 'Derive', 'Permission to derive other keys from this key.')#
- ENCRYPT = (256, 'Encrypt', 'Permission to encrypt a message with the key. It could be cipher encryption, AEAD encryption or asymmetric encryption operation.')#
- SIGN_HASH = (4096, 'Sign hash', 'Permission to sign a hashed message with the key with an asymmetric signature operation. Setting this permission automatically sets the Sign Message usage.')#
- SIGN_MSG = (1024, 'Sign message', 'Permission to sign a message with the key. It could be a MAC generation or an asymmetric message signature operation.')#
- VERIFY_HASH = (8192, 'Sign message', 'Permission to verify a hashed message signature with the key with an asymmetric signature verification operation. Setting this permission automatically sets the Verify Message usage.')#
- VERIFY_MSG = (2048, 'Verify message', 'Permission to verify a message signature with the key. It could be a MAC verification or an asymmetric message signature verification operation.')#
- class KeyDerivationAlgorithm(tag, label, description=None)#
Bases:
SpsdkEnum
Key Derivation Algorithm valid values.
- HKDF_SHA256 = (134217993, 'HKDF SHA256', 'HKDF SHA256 (HMAC two-step)')#
- HKDF_SHA384 = (134217994, 'HKDF SHA384', 'HKDF SHA384 (HMAC two-step)')#
- class KeyExchangeAlgorithm(tag, label, description=None)#
Bases:
SpsdkEnum
Key Exchange Algorithm valid values.
- HKDF_SHA256 = (151126281, 'HKDF SHA256')#
- HKDF_SHA384 = (151126282, 'HKDF SHA384')#
- class LifeCycle(tag, label, description=None)#
Bases:
SpsdkEnum
Chip life cycle valid values.
- CLOSED = (2, 'CLOSED')#
- CURRENT = (0, 'CURRENT', 'Current device lifecycle')#
- LOCKED = (4, 'LOCKED')#
- OPEN = (1, 'OPEN')#
- class LifeTime(tag, label, description=None)#
Bases:
SpsdkEnum
Edgelock Enclave life time valid values.
- PERMANENT = (255, 'PERMANENT', 'Standard permanent key')#
- PERSISTENT = (1, 'PERSISTENT', 'Standard persistent key')#
- VOLATILE = (0, 'VOLATILE', 'Standard volatile key')#
- PAYLOAD_FORMAT = '<BBHLLHHHHLLLLLL32s32s'#
- PAYLOAD_LENGTH = 108#
- PAYLOAD_VERSION = 7#
- TAG = 71#
- create_config()#
Create configuration of the Signed Message.
- Return type:
Dict
[str
,Any
]- Returns:
Configuration dictionary.
- export_payload()#
Exports message payload to bytes array.
- Return type:
bytes
- Returns:
Bytes representation of message payload.
- static load_from_config(config, search_paths=None)#
Converts the configuration option into an message object.
“config” content of container configurations.
- Parameters:
config (
Dict
[str
,Any
]) – Message configuration dictionaries.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Raises:
SPSDKError – Invalid configuration detected.
- Return type:
- Returns:
Message object.
- parse_payload(data)#
Parse payload.
- Parameters:
data (
bytes
) – Binary data with Payload to parse.- Return type:
None
- validate()#
Validate general message properties.
- Return type:
None
- class spsdk.image.ahab.signed_msg.MessageKeyStoreReprovisioningEnable(cert_ver=0, permissions=0, issue_date=None, unique_id=None, monotonic_counter=0, user_sab_id=0)#
Bases:
Message
Key store reprovisioning enable request message class representation.
Key store reprovisioning enable signed message class init.
- Parameters:
cert_ver (
int
) – Certificate version, defaults to 0permissions (
int
) – Certificate permission, to be used in future The stated permission must allow the operation requested by the signed message , defaults to 0issue_date (
Optional
[int
]) – Issue date, defaults to None (Current date will be applied)unique_id (
Optional
[bytes
]) – UUID of device (least 64 bits is used), defaults to Nonemonotonic_counter (
int
) – Monotonic counter value, defaults to 0user_sab_id (
int
) – User SAB id, defaults to 0
- FLAGS = 0#
- PAYLOAD_FORMAT = '<BBHLL'#
- PAYLOAD_LENGTH = 12#
- TAG = 63#
- TARGET = 0#
- create_config()#
Create configuration of the Signed Message.
- Return type:
Dict
[str
,Any
]- Returns:
Configuration dictionary.
- export_payload()#
Exports message payload to bytes array.
- Return type:
bytes
- Returns:
Bytes representation of message payload.
- static load_from_config(config, search_paths=None)#
Converts the configuration option into an message object.
“config” content of container configurations.
- Parameters:
config (
Dict
[str
,Any
]) – Message configuration dictionaries.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Raises:
SPSDKError – Invalid configuration detected.
- Return type:
- Returns:
Message object.
- parse_payload(data)#
Parse payload.
- Parameters:
data (
bytes
) – Binary data with Payload to parse.- Return type:
None
- validate()#
Validate general message properties.
- Return type:
None
- class spsdk.image.ahab.signed_msg.MessageReturnLifeCycle(cert_ver=0, permissions=0, issue_date=None, unique_id=None, life_cycle=0)#
Bases:
Message
Return life cycle request message class representation.
Message used to sign and send to device with EdgeLock.
- Parameters:
cert_ver (
int
) – Certificate version, defaults to 0permissions (
int
) – Certificate permission, to be used in future The stated permission must allow the operation requested by the signed message , defaults to 0issue_date (
Optional
[int
]) – Issue date, defaults to None (Current date will be applied)unique_id (
Optional
[bytes
]) – UUID of device (least 64 bits is used), defaults to Nonelife_cycle (
int
) – Requested life cycle, defaults to 0
- PAYLOAD_LENGTH = 4#
- TAG = 160#
- create_config()#
Create configuration of the Signed Message.
- Return type:
Dict
[str
,Any
]- Returns:
Configuration dictionary.
- export_payload()#
Exports message payload to bytes array.
- Return type:
bytes
- Returns:
Bytes representation of message payload.
- static load_from_config(config, search_paths=None)#
Converts the configuration option into an message object.
“config” content of container configurations.
- Parameters:
config (
Dict
[str
,Any
]) – Message configuration dictionaries.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Raises:
SPSDKError – Invalid configuration detected.
- Return type:
- Returns:
Message object.
- parse_payload(data)#
Parse payload.
- Parameters:
data (
bytes
) – Binary data with Payload to parse.- Return type:
None
- validate()#
Validate general message properties.
- Return type:
None
- class spsdk.image.ahab.signed_msg.MessageWriteSecureFuse(cert_ver=0, permissions=0, issue_date=None, unique_id=None, fuse_id=0, length=0, flags=0, data=None)#
Bases:
Message
Write secure fuse request message class representation.
Message used to sign and send to device with EdgeLock.
- Parameters:
cert_ver (
int
) – Certificate version, defaults to 0permissions (
int
) – Certificate permission, to be used in future The stated permission must allow the operation requested by the signed message , defaults to 0issue_date (
Optional
[int
]) – Issue date, defaults to None (Current date will be applied)unique_id (
Optional
[bytes
]) – UUID of device (least 64 bits is used), defaults to Nonefuse_id (
int
) – Fuse ID, defaults to 0length (
int
) – Fuse length, defaults to 0flags (
int
) – Fuse flags, defaults to 0data (
Optional
[List
[int
]]) – List of fuse values
- PAYLOAD_FORMAT = '<HBB'#
- TAG = 145#
- create_config()#
Create configuration of the Signed Message.
- Return type:
Dict
[str
,Any
]- Returns:
Configuration dictionary.
- export_payload()#
Exports message payload to bytes array.
- Return type:
bytes
- Returns:
Bytes representation of message payload.
- static load_from_config(config, search_paths=None)#
Converts the configuration option into an message object.
“config” content of container configurations.
- Parameters:
config (
Dict
[str
,Any
]) – Message configuration dictionaries.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Raises:
SPSDKError – Invalid configuration detected.
- Return type:
- Returns:
Message object.
- parse_payload(data)#
Parse payload.
- Parameters:
data (
bytes
) – Binary data with Payload to parse.- Return type:
None
- property payload_len: int#
Message payload length in bytes.
- validate()#
Validate general message properties.
- Return type:
None
- class spsdk.image.ahab.signed_msg.SignedMessage(flags=0, fuse_version=0, sw_version=0, message=None, signature_block=None, encrypt_iv=None)#
Bases:
AHABContainerBase
Class representing the Signed message.
Signed Message:
+-----+--------------+--------------+----------------+----------------+ |Off | Byte 3 | Byte 2 | Byte 1 | Byte 0 | +-----+--------------+--------------+----------------+----------------+ |0x00 | Tag | Length (MSB) | Length (LSB) | Version | +-----+--------------+--------------+----------------+----------------+ |0x04 | Flags | +-----+--------------+--------------+---------------------------------+ |0x08 | Reserved | Fuse version | Software version | +-----+--------------+--------------+---------------------------------+ |0x10 | Message descriptor | +-----+---------------------------------------------------------------+ |0x34 | Message header | +-----+---------------------------------------------------------------+ |0x44 | Message payload | +-----+---------------------------------------------------------------+ |0xXX | Signature Block | +-----+---------------------------------------------------------------+
- Message descriptor::
Off
Byte 3
Byte 2
Byte 1
Byte 0
0x00
Reserved
Flags
0x04
IV (256 bits)
Class object initializer.
- Parameters:
flags (
int
) – flags.fuse_version (
int
) – value must be equal to or greater than the version stored in the fuses to allow loading this container.sw_version (
int
) – used by PHBC (Privileged Host Boot Companion) to select between multiple images with same fuse version field.message (
Optional
[Message
]) – Message command to be signed.signature_block (
Optional
[SignatureBlock
]) – signature block.encrypt_iv (
Optional
[bytes
]) – Encryption Initial Vector - if defined the encryption is used.
- ENCRYPT_IV_LEN = 32#
- TAG = 137#
- create_config(data_path)#
Create configuration of the Signed Message.
- Parameters:
data_path (
str
) – Path to store the data files of configuration.- Return type:
Dict
[str
,Any
]- Returns:
Configuration dictionary.
- export()#
Export the signed image into one chunk.
- Raises:
SPSDKValueError – if the number of images doesn’t correspond the the number of entries in image array info.
- Return type:
bytes
- Returns:
images exported into single binary
- classmethod format()#
Format of binary representation.
- Return type:
str
- static generate_config_template(family, message=None)#
Generate AHAB configuration template.
- Parameters:
family (
str
) – Family for which the template should be generated.message (
Optional
[MessageCommands
]) – Generate the template just for one message type, if not used , its generated for all messages
- Return type:
Dict
[str
,Any
]- Returns:
Dictionary of individual templates (key is name of template, value is template itself).
- static get_validation_schemas()#
Get list of validation schemas.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
Validation list of schemas.
- image_info()#
Get Image info object.
- Return type:
- Returns:
Signed Message Info object.
- static load_from_config(config, search_paths=None)#
Converts the configuration option into an Signed message object.
“config” content of container configurations.
- Parameters:
config (
Dict
[str
,Any
]) – Signed Message configuration dictionaries.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
- Returns:
Message object.
- classmethod parse(data)#
Parse input binary to the signed message object.
- Parameters:
data (
bytes
) – Binary data with Container block to parse.- Return type:
Self
- Returns:
Object recreated from the binary data.
- update_fields()#
Updates all volatile information in whole container structure.
- Raises:
SPSDKError – When inconsistent image array length is detected.
- Return type:
None
- validate(data)#
Validate object data.
- Parameters:
data (
Dict
[str
,Any
]) – Additional validation data.- Raises:
SPSDKValueError – Invalid any value of Image Array entry
- Return type:
None
Bootable image#
This module contains Bootable image related code.
- class spsdk.image.bootable_image.bimg.BootableImage(family, mem_type, revision='latest')#
Bases:
BaseClass
Bootable Image class.
Bootable Image constructor.
- Parameters:
family (
str
) – Chip family.mem_type (
str
) – Used memory type.revision (
str
) – Chip silicon revision.
- Raises:
SPSDKValueError – Invalid family.
- export()#
Export bootable image.
- Return type:
bytes
- Returns:
Complete binary of bootable image.
- classmethod generate_config_template(family, mem_type, revision='latest')#
Get validation schema for the family.
- Parameters:
family (
str
) – Chip familymem_type (
str
) – Used memory type.revision (
str
) – Chip revision specification, as default, latest is used.
- Return type:
str
- Returns:
Validation schema.
- classmethod get_memory_type_config(family, mem_type, revision='latest')#
Return dictionary with configuration for specific memory type.
- Raises:
SPSDKKeyError – If memory type does not exist in database
- Return type:
Dict
[str
,Any
]- Returns:
Dictionary with configuration.
- classmethod get_supported_families()#
Get list of all supported families by bootable image.
- Return type:
List
[str
]- Returns:
List of families.
- classmethod get_supported_memory_types(family=None, revision='latest')#
Return list of supported memory types.
- Return type:
List
[str
]- Returns:
List of supported families.
- classmethod get_supported_revisions(family)#
Return list of supported revisions.
- Return type:
List
[str
]- Returns:
List of supported revisions.
- static get_validation_schemas(family, mem_type, revision='latest')#
Get validation schema for the family.
- Parameters:
family (
str
) – Chip familymem_type (
str
) – Used memory type.revision (
str
) – Chip revision specification, as default, latest is used.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
List of validation schema dictionaries.
- static get_validation_schemas_family()#
Create the validation schema just for supported families.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
List of validation schemas for Bootable Image supported families.
- image_info()#
Create Binary image of bootable image.
- Return type:
- Returns:
BinaryImage object of bootable image.
- static load_from_config(config, search_paths=None)#
Load bootable image from configuration.
- Parameters:
config (
Dict
) – Configuration of Bootable image.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
- classmethod parse(binary, family=None, mem_type=None, revision='latest')#
Parse binary into bootable image object.
- Parameters:
binary (
bytes
) – Bootable image binary.family (
Optional
[str
]) – Chip family.mem_type (
Optional
[str
]) – Used memory type.revision (
str
) – Chip silicon revision.
- Return type:
Self
- store_config(output)#
Store bootable image into configuration and binary blocks.
- Parameters:
output (
str
) – Path to output folder to store bootable image configuration.- Return type:
None
Bootable image segments#
This module contains Bootable image related code.
- class spsdk.image.bootable_image.segments.Segment(raw_block=None)#
Bases:
BaseClass
Base Bootable Image Segment class.
Segment initialization, at least raw data are stored.
- Parameters:
raw_block (
Optional
[bytes
]) – Raw data of segment.
-
CFG_NAME:
Optional
[str
] = None#
- IMAGE_PATTERNS = ['zeros', 'ones']#
- NAME = 'Base'#
- SIZE = -1#
- classmethod cfg_key()#
Configuration key name.
- Return type:
str
- create_config(path)#
Create configuration including store the data to specified path.
- Parameters:
path (
str
) – Path where the information should be stored- Return type:
Union
[str
,int
]- Returns:
Value of segment to configuration file
- export()#
Serialize object into bytes array.
- Return type:
bytes
- Returns:
Raw binary block of segment
- classmethod load_from_config(config, search_paths=None)#
Load segment from configuration.
- Parameters:
config (
Dict
[str
,Any
]) – Configuration of Segment.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
Self
- classmethod parse(binary, family='Unknown', mem_type='Unknown', revision='latest')#
Parse binary block into Segment object.
- Parameters:
binary (
bytes
) – binary image.family (
str
) – Chip family.mem_type (
str
) – Used memory type.revision (
str
) – Optional Chip family revision.
- Raises:
SPSDKParsingError – If given binary block size is not equal to block size in header
- Return type:
Self
- class spsdk.image.bootable_image.segments.SegmentAhab(raw_block=None, ahab=None)#
Bases:
Segment
Bootable Image Advanced High Assurance Boot(HAB) Segment class.
Segment initialization, at least raw data are stored.
- Parameters:
raw_block (
Optional
[bytes
]) – Raw data of segment.ahab (
Optional
[AHABImage
]) – Advanced High Assurance Boot class.
- NAME = 'ahab_container'#
- create_config(path)#
Create configuration including store the data to specified path.
- Parameters:
path (
str
) – Path where the information should be stored- Return type:
Union
[str
,int
]- Returns:
Value of segment to configuration file
- classmethod load_from_config(config, search_paths=None)#
Load segment from configuration.
- Parameters:
config (
Dict
[str
,Any
]) – Configuration of Segment.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
Self
- classmethod parse(binary, family='Unknown', mem_type='Unknown', revision='latest')#
Parse binary block into Segment object.
- Parameters:
binary (
bytes
) – binary image.family (
str
) – Chip family.mem_type (
str
) – Used memory type.revision (
str
) – Optional Chip family revision.
- Return type:
Self
- class spsdk.image.bootable_image.segments.SegmentBeeHeader0(raw_block=None)#
Bases:
Segment
Bootable Image BEE encryption header 0 Segment class.
Segment initialization, at least raw data are stored.
- Parameters:
raw_block (
Optional
[bytes
]) – Raw data of segment.
- NAME = 'bee_header_0'#
- SIZE = 512#
- class spsdk.image.bootable_image.segments.SegmentBeeHeader1(raw_block=None)#
Bases:
Segment
Bootable Image BEE encryption header 1 Segment class.
Segment initialization, at least raw data are stored.
- Parameters:
raw_block (
Optional
[bytes
]) – Raw data of segment.
- NAME = 'bee_header_1'#
- SIZE = 512#
- class spsdk.image.bootable_image.segments.SegmentFcb(raw_block=None, fcb=None)#
Bases:
Segment
Bootable Image FCB Segment class.
Segment initialization, at least raw data are stored.
- Parameters:
raw_block (
Optional
[bytes
]) – Raw data of segment.fcb (
Optional
[FCB
]) – FCB class.
- NAME = 'fcb'#
- SIZE = 512#
- create_config(path)#
Create configuration including store the data to specified path.
- Parameters:
path (
str
) – Path where the information should be stored- Return type:
Union
[str
,int
]- Returns:
Value of segment to configuration file
- classmethod load_from_config(config, search_paths=None)#
Load segment from configuration.
- Parameters:
config (
Dict
[str
,Any
]) – Configuration of Segment.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
Self
- classmethod parse(binary, family='Unknown', mem_type='Unknown', revision='latest')#
Parse binary block into Segment object.
- Parameters:
binary (
bytes
) – binary image.family (
str
) – Chip family.mem_type (
str
) – Used memory type.revision (
str
) – Optional Chip family revision.
- Raises:
SPSDKParsingError – If given binary block size is not equal to block size in header
- Return type:
Self
- class spsdk.image.bootable_image.segments.SegmentHab(raw_block=None, hab=None)#
Bases:
Segment
Bootable Image High Assurance Boot(HAB) Segment class.
Segment initialization, at least raw data are stored.
- Parameters:
raw_block (
Optional
[bytes
]) – Raw data of segment.hab (
Optional
[HabContainer
]) – High Assurance Boot class.
- NAME = 'hab_container'#
- classmethod load_from_config(config, search_paths=None)#
Load segment from configuration.
- Parameters:
config (
Dict
[str
,Any
]) – Configuration of Segment.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
Self
- classmethod parse(binary, family='Unknown', mem_type='Unknown', revision='latest')#
Parse binary block into Segment object.
- Parameters:
binary (
bytes
) – binary image.family (
str
) – Chip family.mem_type (
str
) – Used memory type.revision (
str
) – Optional Chip family revision.
- Return type:
Self
- class spsdk.image.bootable_image.segments.SegmentImageVersion(raw_block=None)#
Bases:
Segment
Bootable Image Image version Segment class.
Segment initialization, at least raw data are stored.
- Parameters:
raw_block (
Optional
[bytes
]) – Raw data of segment.
- NAME = 'image_version'#
- SIZE = 4#
- create_config(path)#
Create configuration including store the data to specified path.
- Parameters:
path (
str
) – Path where the information should be stored- Return type:
Union
[str
,int
]- Returns:
Value of segment to configuration file
- classmethod load_from_config(config, search_paths=None)#
Load segment from configuration.
- Parameters:
config (
Dict
[str
,Any
]) – Configuration of Segment.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
Self
- class spsdk.image.bootable_image.segments.SegmentImageVersionAntiPole(raw_block=None)#
Bases:
Segment
Bootable Image Image version with antipole value Segment class.
Segment initialization, at least raw data are stored.
- Parameters:
raw_block (
Optional
[bytes
]) – Raw data of segment.
-
CFG_NAME:
Optional
[str
] = 'image_version'#
- NAME = 'image_version_ap'#
- SIZE = 4#
- create_config(path)#
Create configuration including store the data to specified path.
- Parameters:
path (
str
) – Path where the information should be stored- Return type:
Union
[str
,int
]- Returns:
Value of segment to configuration file
- classmethod load_from_config(config, search_paths=None)#
Load segment from configuration.
- Parameters:
config (
Dict
[str
,Any
]) – Configuration of Segment.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
Self
- class spsdk.image.bootable_image.segments.SegmentKeyBlob(raw_block=None)#
Bases:
Segment
Bootable Image KeyBlob Segment class.
Segment initialization, at least raw data are stored.
- Parameters:
raw_block (
Optional
[bytes
]) – Raw data of segment.
- NAME = 'keyblob'#
- SIZE = 256#
- class spsdk.image.bootable_image.segments.SegmentKeyStore(raw_block=None)#
Bases:
Segment
Bootable Image KeyStore Segment class.
Segment initialization, at least raw data are stored.
- Parameters:
raw_block (
Optional
[bytes
]) – Raw data of segment.
- NAME = 'keystore'#
- SIZE = 2048#
- class spsdk.image.bootable_image.segments.SegmentMbi(raw_block=None, mbi=None)#
Bases:
Segment
Bootable Image Master Boot Image(MBI) Segment class.
Segment initialization, at least raw data are stored.
- Parameters:
raw_block (
Optional
[bytes
]) – Raw data of segment.mbi (
Optional
[MasterBootImage
]) – Master boot image class.
- NAME = 'mbi'#
- create_config(path)#
Create configuration including store the data to specified path.
- Parameters:
path (
str
) – Path where the information should be stored- Return type:
Union
[str
,int
]- Returns:
Value of segment to configuration file
- classmethod load_from_config(config, search_paths=None)#
Load segment from configuration.
- Parameters:
config (
Dict
[str
,Any
]) – Configuration of Segment.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
Self
- classmethod parse(binary, family='Unknown', mem_type='Unknown', revision='latest')#
Parse binary block into Segment object.
- Parameters:
binary (
bytes
) – binary image.family (
str
) – Chip family.mem_type (
str
) – Used memory type.revision (
str
) – Optional Chip family revision.
- Return type:
Self
- class spsdk.image.bootable_image.segments.SegmentXmcd(raw_block=None, xmcd=None)#
Bases:
Segment
Bootable Image XMCD Segment class.
Segment initialization, at least raw data are stored.
- Parameters:
raw_block (
Optional
[bytes
]) – Raw data of segment.xmcd (
Optional
[XMCD
]) – XMCD class.
- NAME = 'xmcd'#
- SIZE = 512#
- create_config(path)#
Create configuration including store the data to specified path.
- Parameters:
path (
str
) – Path where the information should be stored- Return type:
Union
[str
,int
]- Returns:
Value of segment to configuration file
- classmethod load_from_config(config, search_paths=None)#
Load segment from configuration.
- Parameters:
config (
Dict
[str
,Any
]) – Configuration of Segment.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
Self
- classmethod parse(binary, family='Unknown', mem_type='Unknown', revision='latest')#
Parse binary block into Segment object.
- Parameters:
binary (
bytes
) – binary image.family (
str
) – Chip family.mem_type (
str
) – Used memory type.revision (
str
) – Optional Chip family revision.
- Raises:
SPSDKParsingError – If given binary block size is not equal to block size in header
- Return type:
Self
FCB - Flash Configuration Block#
This module contains FCB (Flash Configuration Block) related code.
- class spsdk.image.fcb.fcb.FCB(family, mem_type, revision='latest')#
Bases:
SegmentBase
FCB (Flash Configuration Block).
FCB Constructor.
- Parameters:
family (
str
) – Chip family.mem_type (
str
) – Used memory type.revision (
str
) – Optional Chip family revision.
- Raises:
SPSDKValueError – Unsupported family.
- FEATURE = 'fcb'#
- SIZE = 512#
- TAG = b'FCFB'#
- create_config()#
Create current configuration YAML.
- Return type:
str
- Returns:
Configuration of FCB Block.
- static generate_config_template(family, mem_type, revision='latest')#
Generate configuration for selected family.
- Parameters:
family (
str
) – Family description.mem_type (
str
) – Used memory type.revision (
str
) – Chip revision specification, as default, latest is used.
- Return type:
str
- Returns:
Template of FCB Block.
- classmethod get_validation_schemas(family, mem_type, revision='latest')#
Create the validation schema.
- Parameters:
family (
str
) – Family description.mem_type (
str
) – Used memory type.revision (
str
) – Chip revision specification, as default, latest is used.
- Raises:
SPSDKError – Family or revision is not supported.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
List of validation schemas.
- static get_validation_schemas_family()#
Create the validation schema just for supported families.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
List of validation schemas for FCB supported families.
- static load_from_config(config)#
Load configuration file of FCB.
- Parameters:
config (
Dict
) – FCB configuration file.- Return type:
- Returns:
FCB object.
- classmethod parse(binary, offset=0, family='Unknown', mem_type='Unknown', revision='latest')#
Parse binary block into FCB object.
- Parameters:
binary (
bytes
) – binary image.offset (
int
) – Offset of FCB in binary image.family (
str
) – Chip family.mem_type (
str
) – Used memory type.revision (
str
) – Optional Chip family revision.
- Raises:
SPSDKError – If given binary block contains wrong FCB tag
- Return type:
Self
HAB - High Assurance Boot#
This module contains HAB related code.
HAB Container#
This module contains HAB container related code.
- class spsdk.image.hab.hab_container.HabContainer(flags, ivt_offset, start_address, segments, image_pattern='zeros')#
Bases:
object
Hab container.
HAB container initialization.
- Parameters:
flags (
int
) – Flagsivt_offset (
int
) – IVT offset valuestart_address (
int
) – Start address valuesegments (
HabSegments
) – Segments listimage_pattern (
str
) – Image pattern used to fill empty spaces
- property app_segment: AppHabSegment#
APP segment object.
- property bdt_segment: BdtHabSegment#
BDT segment object.
- property csf_segment: CsfHabSegment | None#
CSF segment object if exists, None otherwise.
- property dcd_segment: DcdHabSegment | None#
DCD segment object if exists, None otherwise.
- export()#
Export into binary.
- Return type:
bytes
- export_padding()#
Get into binary including initial padding.
- Return type:
bytes
- classmethod generate_config_template()#
Generate configuration template.
- Return type:
str
- Returns:
Dictionary of individual templates (key is name of template, value is template itself).
- get_segment(segment)#
Get container’s segment.
- Parameters:
segment (
HabSegment
) – Segment enum- Return type:
Optional
[HabSegmentBase
]
- classmethod get_validation_schemas()#
Create the list of validation schemas.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
List of validation schemas.
- image_info(padding=False)#
Create Binary image of HAB container.
- Return type:
- Returns:
BinaryImage object of HAB container.
- property is_authenticated: bool#
Returns true if container is authenticated, false otherwise.
- property is_encrypted: bool#
Returns true if container is encrypted, false otherwise.
- property ivt_segment: IvtHabSegment#
IVT segment object.
- classmethod load_configuration(config_path, external_files=None, search_paths=None)#
Load the BD or YAML Configuration.
- Parameters:
config_path (
str
) – Path to configuration file either BD or YAML formatted.external_files (
Optional
[List
[str
]]) – Optional list of external files for BD processingsearch_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
Dict
- Returns:
Dictionary with parsed configuration.
- classmethod load_from_config(config, search_paths=None)#
Load the HAB container object from parsed bd_data configuration.
- Parameters:
config (
Dict
[str
,Any
]) – Image configurationsearch_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type:
Self
- classmethod parse(data)#
Parse existing binary into HAB container object.
- Parameters:
data (
bytes
) – Binary to be parsed- Return type:
Self
- classmethod transform_bd_configuration(config)#
Transform configuration from flat structure to BD structure.
- Parameters:
config (
Dict
[Any
,Any
]) – Parsed configuration from BD parser- Return type:
Dict
[Any
,Any
]- Returns:
Transformed configuration
- classmethod transform_configuration(config)#
Transform configuration from BD parser to flat YAML structure.
- Parameters:
config (
Dict
[Any
,Any
]) – Parsed configuration from BD parser- Return type:
Dict
[Any
,Any
]- Returns:
Transformed configuration
- update_csf()#
Update the CSF segment including signing and encryption.
- Return type:
None
- property xmcd_segment: XmcdHabSegment | None#
XMCD segment object if exists, None otherwise.
XMCD#
This module contains XMCD (External Memory Configuration Data) related code.
- class spsdk.image.xmcd.xmcd.ConfigurationBlockType(tag, label, description=None)#
Bases:
SpsdkEnum
Support configuration blocks Enum.
- FULL = (1, 'full', 'Full configuration')#
- SIMPLIFIED = (0, 'simplified', 'Simplified configuration')#
- class spsdk.image.xmcd.xmcd.MemoryType(tag, label, description=None)#
Bases:
SpsdkEnum
Support memory types Enum.
- FLEXSPI_RAM = (0, 'flexspi_ram', 'FlexSPI RAM')#
- SEMC_SDRAM = (1, 'semc_sdram', 'SEMC SDRAM')#
- class spsdk.image.xmcd.xmcd.XMCD(family, mem_type, config_type, revision='latest')#
Bases:
SegmentBase
XMCD (External Memory Configuration Data).
XMCD Constructor.
- Parameters:
family (
str
) – Chip family.config_type (
ConfigurationBlockType
) – Configuration block type: simplified | full.revision (
str
) – Optional Chip family revision.
- Raises:
SPSDKValueError – Unsupported family.
- FEATURE = 'xmcd'#
- classmethod calculate_crc(data)#
Calculate XMCD CRC value.
- Parameters:
data (
bytes
) – Data to be used for calculation.- Return type:
bytes
- property config_type: ConfigurationBlockType#
Configuration type. It can be either simplified or full.
- create_config()#
Create current configuration YAML.
- Raises:
SPSDKError – Registers are not loaded in the object.
- Return type:
str
- Returns:
Configuration of XMCD Block.
- static generate_config_template(family, mem_type, config_type, revision='latest')#
Generate configuration for selected family.
- Parameters:
family (
str
) – Family description.mem_type (
MemoryType
) – Used memory type.config_type (
ConfigurationBlockType
) – Config type: either simplified or full.revision (
str
) – Chip revision specification, as default, latest is used.
- Return type:
str
- Returns:
Template of XMCD Block.
- classmethod get_supported_configuration_types(family, mem_type, revision='latest')#
Return list of supported memory interfaces.
- Return type:
List
[str
]- Returns:
List of supported family interfaces.
- classmethod get_validation_schemas(family, mem_type, config_type, revision='latest')#
Create the validation schema.
- Parameters:
family (
str
) – Family description.mem_type (
MemoryType
) – Used memory type.config_type (
ConfigurationBlockType
) – Config type: either simplified or full.revision (
str
) – Chip revision specification, as default, latest is used.
- Raises:
SPSDKError – Family or revision is not supported.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
List of validation schemas.
- static get_validation_schemas_family()#
Create the validation schema just for supported families.
- Return type:
List
[Dict
[str
,Any
]]- Returns:
List of validation schemas for XMCD supported families.
- static load_from_config(config)#
Load configuration file of XMCD.
- Parameters:
config (
Dict
) – XMCD configuration file.- Raises:
SPSDKKeyError – If XMCD settings do not contain required key
- Return type:
- Returns:
XMCD object.
- static load_registers(family, mem_type, config_type, revision, filter_reg=None)#
Load all registers of segment.
- Parameters:
family (
str
) – Family description.mem_type (
MemoryType
) – Used memory type.config_type (
ConfigurationBlockType
) – Config type: either simplified or full.revision (
str
) – Chip revision specification, as default, latest is used.filter_reg (
Optional
[List
[str
]]) – List of register names that should be filtered out.
- Raises:
SPSDKValueError – If option_size has invalid value(only 0 or 1 are allowed)
- Return type:
- property mem_type: MemoryType#
Memory type.
- classmethod parse(binary, offset=0, family='Unknown', revision='latest')#
Parse binary block into XMCD object.
- Parameters:
binary (
bytes
) – binary image.offset (
int
) – Offset of XMCD in binary image.family (
str
) – Chip family.revision (
str
) – Optional Chip family revision.
- Raises:
SPSDKError – If given binary block size is not equal to block size in header
- Return type:
Self