azuresphere_imagemetadata 0.0.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. azuresphere_imagemetadata/LICENSE +21 -0
  2. azuresphere_imagemetadata/README.md +24 -0
  3. azuresphere_imagemetadata/__init__.py +12 -0
  4. azuresphere_imagemetadata/certificates/app_test_sign.pfx +0 -0
  5. azuresphere_imagemetadata/certificates/tp_app_test_sign.cer +14 -0
  6. azuresphere_imagemetadata/guid_utils.py +35 -0
  7. azuresphere_imagemetadata/image.py +44 -0
  8. azuresphere_imagemetadata/image_manifest.py +239 -0
  9. azuresphere_imagemetadata/image_metadata.py +254 -0
  10. azuresphere_imagemetadata/metadata_headers/__init__.py +4 -0
  11. azuresphere_imagemetadata/metadata_headers/image_metadata.py +62 -0
  12. azuresphere_imagemetadata/metadata_headers/image_metadata_section.py +51 -0
  13. azuresphere_imagemetadata/metadata_sections/__init__.py +4 -0
  14. azuresphere_imagemetadata/metadata_sections/abi.py +153 -0
  15. azuresphere_imagemetadata/metadata_sections/compression.py +108 -0
  16. azuresphere_imagemetadata/metadata_sections/debug.py +65 -0
  17. azuresphere_imagemetadata/metadata_sections/identity.py +269 -0
  18. azuresphere_imagemetadata/metadata_sections/image_policy.py +108 -0
  19. azuresphere_imagemetadata/metadata_sections/internal/__init__.py +4 -0
  20. azuresphere_imagemetadata/metadata_sections/internal/capabilities.py +187 -0
  21. azuresphere_imagemetadata/metadata_sections/internal/onebl.py +82 -0
  22. azuresphere_imagemetadata/metadata_sections/metadata.py +38 -0
  23. azuresphere_imagemetadata/metadata_sections/metadata_id.py +84 -0
  24. azuresphere_imagemetadata/metadata_sections/not_implemented.py +25 -0
  25. azuresphere_imagemetadata/metadata_sections/required_offset.py +54 -0
  26. azuresphere_imagemetadata/metadata_sections/revocation.py +57 -0
  27. azuresphere_imagemetadata/metadata_sections/signature.py +97 -0
  28. azuresphere_imagemetadata/metadata_sections/temporary_image.py +97 -0
  29. azuresphere_imagemetadata/metadata_sections/utils.py +93 -0
  30. azuresphere_imagemetadata/signing/__init__.py +4 -0
  31. azuresphere_imagemetadata/signing/app_development.py +78 -0
  32. azuresphere_imagemetadata/signing/der_encoded.py +89 -0
  33. azuresphere_imagemetadata/signing/signing_info.py +102 -0
  34. azuresphere_imagemetadata-0.0.5.dist-info/METADATA +58 -0
  35. azuresphere_imagemetadata-0.0.5.dist-info/RECORD +37 -0
  36. azuresphere_imagemetadata-0.0.5.dist-info/WHEEL +5 -0
  37. azuresphere_imagemetadata-0.0.5.dist-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ Copyright (c) Microsoft Corporation.
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,24 @@
1
+ # Microsoft Azure Sphere Image Metadata for Python
2
+
3
+ Microsoft Azure Sphere Image Metadata for Python enables users to interact with an Azure Sphere Image.
4
+
5
+
6
+ ## Installation
7
+
8
+ You can find Microsoft Azure Sphere Image Metadata for Python on [PyPi](https://pypi.org/project/azuresphere_imagemetadata/).
9
+
10
+ 1. If you haven't already, [install and/or upgrade the pip](https://pip.pypa.io/en/stable/installing/)
11
+ of your Python environment to a recent version.
12
+ 2. Run `pip install azuresphere-imagemetadata`.
13
+
14
+ ## Usage
15
+
16
+ Before using Microsoft Azure Sphere Image Metadata for Python, you must install the Azure Sphere SDK.
17
+
18
+ - To install the Azure Sphere SDK on Windows, follow the [Windows Quickstart](https://learn.microsoft.com/azure-sphere/install/install-sdk?pivots=cli).
19
+ - To install the Azure Sphere SDK on Linux, follow the [Linux Quickstart](https://learn.microsoft.com/azure-sphere/install/install-sdk-linux?pivots=cli-linux).
20
+
21
+ ## Supported host operating systems
22
+
23
+ - Windows 10 and 11
24
+ - Ubuntu 18.04, 20.04, 22.04
@@ -0,0 +1,12 @@
1
+ # --------------------------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See LICENSE in the project root for license information.
4
+ # --------------------------------------------------------------------------------------------
5
+ from importlib.metadata import version, PackageNotFoundError
6
+
7
+ try:
8
+ __version__ = version("azuresphere_imagemetadata")
9
+ VERSION = __version__
10
+ except PackageNotFoundError:
11
+ # package is not installed
12
+ pass
@@ -0,0 +1,14 @@
1
+ -----BEGIN CERTIFICATE-----
2
+ MIICLTCCAdOgAwIBAgIJAMCRCPSaH6lwMAoGCCqGSM49BAMCMHMxCzAJBgNVBAYT
3
+ AlVTMRMwEQYDVQQIDApXYXNoaW5ndG9uMRAwDgYDVQQHDAdSZWRtb25kMR4wHAYD
4
+ VQQKDBVNaWNyb3NvZnQgQ29ycG9yYXRpb24xHTAbBgNVBAMMFEFwcCBUZXN0IFNp
5
+ Z25pbmcgS2V5MB4XDTE3MDQxMjE3MTY1OFoXDTI3MDQxMDE3MTY1OFowczELMAkG
6
+ A1UEBhMCVVMxEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1JlZG1vbmQx
7
+ HjAcBgNVBAoMFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjEdMBsGA1UEAwwUQXBwIFRl
8
+ c3QgU2lnbmluZyBLZXkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATt8jPADTEU
9
+ HY8/VjNDQMzYwWn7Z+LsVkv4pe9Yaxw/e8GIyiCHAebXx3VqEyY4/pjJoCAHQD3l
10
+ xCLmp+gmpL0ko1AwTjAdBgNVHQ4EFgQUY7CP8Pj32XhY4zObUHBS+h3MnoswHwYD
11
+ VR0jBBgwFoAUY7CP8Pj32XhY4zObUHBS+h3MnoswDAYDVR0TBAUwAwEB/zAKBggq
12
+ hkjOPQQDAgNIADBFAiAE/4dlH3mJzDGHkNzcBHs3AuOVwXk9tB74Ovf7qKyCWAIh
13
+ ALxSrGD9N2kWyYb78DlUlQFbJ6uECIZbgSnjc+/OnnsA
14
+ -----END CERTIFICATE-----
@@ -0,0 +1,35 @@
1
+ # --------------------------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See LICENSE in the project root for license information.
4
+ # --------------------------------------------------------------------------------------------
5
+
6
+ """
7
+ Provides helper functions for working with Azure Sphere GUIDs.
8
+ Azure Sphere GUIDs have historically incorrectly ordered bytes.
9
+ """
10
+
11
+
12
+ def format_guid_as_string(guid):
13
+ """
14
+ Formats a GUID as a string observing the same format as dotnet code.
15
+ """
16
+ return f"{guid[0:8]}-{guid[8:12]}-{guid[12:16]}-{guid[16:20]}-{guid[20:32]}"
17
+
18
+
19
+ def to_guid(guid_bytes: bytes):
20
+ """
21
+ Correctly orders a guid stored in an image package e.g. image/component uids.
22
+ """
23
+ guid = [0] * 16
24
+
25
+ for i in range(0, 4):
26
+ guid[i] = guid_bytes[3 - i]
27
+
28
+ guid[4] = guid_bytes[5]
29
+ guid[5] = guid_bytes[4]
30
+ guid[6] = guid_bytes[7]
31
+ guid[7] = guid_bytes[6]
32
+
33
+ guid[8:] = guid_bytes[8:]
34
+
35
+ return bytearray(guid).hex()
@@ -0,0 +1,44 @@
1
+ # --------------------------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See LICENSE in the project root for license information.
4
+ # --------------------------------------------------------------------------------------------
5
+
6
+ from .image_metadata import ImageMetadata
7
+ from .signing.app_development import AppDevelopmentSigner
8
+ from .signing.der_encoded import DEREncodedSignature
9
+
10
+
11
+ class Image:
12
+ def __init__(self, data=None):
13
+ self.signature = None
14
+ self.data = data
15
+ self.metadata = ImageMetadata(None)
16
+ if data is not None:
17
+ self.deserialize(data)
18
+
19
+ def as_bytes(self, signer=AppDevelopmentSigner(), include_signature=False):
20
+ new_data = self.data + self.metadata.serialize()
21
+ if include_signature:
22
+ if self.signature is None:
23
+ self.signature = DEREncodedSignature.to_stored_signature(
24
+ signer.sign_data(new_data)
25
+ )
26
+ return new_data + self.signature
27
+ return new_data
28
+
29
+ def deserialize(self, data):
30
+ try:
31
+ self.metadata = ImageMetadata(data)
32
+ except Exception as e:
33
+ print(f"Metadata parsing failed: {e}")
34
+ # metadata parsing could not correctly find the metadata
35
+ return
36
+
37
+ self.data = data[: self.metadata.start_of_metadata]
38
+ self.signature = data[self.metadata.end_of_metadata :]
39
+
40
+ if len(self.signature) != self.metadata.signature_size:
41
+ raise Exception("Signature size mismatch")
42
+
43
+ def serialize(self, signer=AppDevelopmentSigner(), include_signature=True):
44
+ return self.as_bytes(signer, include_signature)
@@ -0,0 +1,239 @@
1
+ # --------------------------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See LICENSE in the project root for license information.
4
+ # --------------------------------------------------------------------------------------------
5
+
6
+ import struct
7
+ from datetime import datetime, timezone
8
+ from .metadata_sections.abi import ABIIdentity
9
+ from .image_metadata import ImageMetadata
10
+ from .guid_utils import to_guid, format_guid_as_string
11
+ from .metadata_sections.identity import ImageType
12
+
13
+
14
+ class PartitionType:
15
+ Invalid = 0
16
+ Firmware = 1
17
+ Backups = 2
18
+ Applications = 4
19
+ LogStorage = 5
20
+ NWConfig = 6
21
+ BootloaderOne = 7
22
+ BootloaderOneBackup = 8
23
+ LocatorTable = 9
24
+ LocatorTableBackup = 10
25
+ BlockHashes = 11
26
+ BlockHashesBackup = 12
27
+ BootManifest = 13
28
+ BootManifestBackup = 14
29
+ TelemetryStorage = 15
30
+ LastValidPhysicalPartition = 15
31
+ MaxPhysicalLayout = 16383
32
+ # All layouts above 2^14 - 1 are virtual layouts that do not describe physical flash data, but
33
+ # rather describe flash policy.
34
+ EC_RuntimeProtectedRange = 16384
35
+ MaxVirtualLayout = 65535
36
+
37
+ @staticmethod
38
+ def get_name(value):
39
+ if value == PartitionType.Invalid:
40
+ return "invalid"
41
+ if value == PartitionType.Firmware:
42
+ return "firmware"
43
+ if value == PartitionType.Backups:
44
+ return "backups"
45
+ if value == PartitionType.Applications:
46
+ return "applications"
47
+ if value == PartitionType.LogStorage:
48
+ return "log_storage"
49
+ if value == PartitionType.NWConfig:
50
+ return "nw_config"
51
+ if value == PartitionType.BootloaderOne:
52
+ return "bootloader_one"
53
+ if value == PartitionType.BootloaderOneBackup:
54
+ return "bootloader_one_backup"
55
+ if value == PartitionType.LocatorTable:
56
+ return "locator_table"
57
+ if value == PartitionType.LocatorTableBackup:
58
+ return "locator_table_backup"
59
+ if value == PartitionType.BlockHashes:
60
+ return "block_hashes"
61
+ if value == PartitionType.BlockHashesBackup:
62
+ return "block_hashes_backup"
63
+ if value == PartitionType.BootManifest:
64
+ return "boot_manifest"
65
+ if value == PartitionType.BootManifestBackup:
66
+ return "boot_manifest_backup"
67
+ if value == PartitionType.TelemetryStorage:
68
+ return "telemetry_storage"
69
+ raise Exception("Unknown partition type: " + str(value))
70
+
71
+
72
+ class ManifestHeader:
73
+ """
74
+ Manifest header
75
+ Only V3 is supported. Earlier versions will raise an exception.
76
+ """
77
+
78
+ VERSION1 = 1
79
+ VERSION2 = 2
80
+ VERSION3 = 3
81
+ MAX_COUNT_ABI_IDENTITIES = 2
82
+
83
+ def __init__(self, data):
84
+ if data is None:
85
+ self.version = ManifestHeader.VERSION3
86
+ self.image_count = 0
87
+ self.manifest_header_size = 0
88
+ self.manifest_entry_size = 0
89
+ self.build_date = 0
90
+ self.manifest_version = 0
91
+ else:
92
+ self.deserialize(data)
93
+
94
+ @staticmethod
95
+ def size():
96
+ """
97
+ Returns the size of the ManifestHeader in bytes.
98
+ """
99
+ return 16
100
+
101
+ def deserialize(self, data):
102
+ """
103
+ Deserializes the ManifestHeader from the provided data.
104
+ """
105
+ self.version = struct.unpack("<H", data[0:2])[0]
106
+
107
+ if self.version != ManifestHeader.VERSION3:
108
+ raise Exception("Unsupported manifest version: " + str(self.version))
109
+
110
+ self.image_count = struct.unpack("<H", data[2:4])[0]
111
+ self.manifest_header_size = struct.unpack("<H", data[4:6])[0]
112
+ self.manifest_entry_size = struct.unpack("<H", data[6:8])[0]
113
+ self.build_date = struct.unpack("<Q", data[8:16])[0]
114
+
115
+ def __str__(self):
116
+ LOCAL_TIMEZONE = datetime.now(timezone.utc).astimezone().tzinfo
117
+ local = datetime.fromtimestamp(self.build_date, LOCAL_TIMEZONE)
118
+ return f"ManifestHeader: version={self.version}, image_count={self.image_count}, manifest_header_size={self.manifest_header_size}, manifest_entry_size={self.manifest_entry_size}, build_date={local.strftime('%d/%m/%Y %H:%M:%S')}"
119
+
120
+
121
+ class ManifestEntry:
122
+ """Manifest entry"""
123
+
124
+ UID_SIZE = 16
125
+
126
+ def __init__(self, data):
127
+ self.image_uid_raw = None
128
+ self.component_uid_raw = None
129
+ self.image_type = 0
130
+ self.partition_type = 0
131
+ self.image_file_size = 0
132
+ self.uncompressed_image_size = 0
133
+ self.provides = []
134
+ self.depends = []
135
+ if data is not None:
136
+ self.deserialize(data)
137
+
138
+ @property
139
+ def image_uid(self):
140
+ """
141
+ Returns the image uuid as a string.
142
+ """
143
+ return format_guid_as_string(to_guid(self.image_uid_raw))
144
+
145
+ @property
146
+ def component_uid(self):
147
+ """
148
+ Returns the component uuid as a string.
149
+ """
150
+ return format_guid_as_string(to_guid(self.component_uid_raw))
151
+
152
+ def deserialize(self, data):
153
+ """
154
+ Deserializes the ManifestEntry from the provided data.
155
+ """
156
+ offset = 0
157
+ self.image_uid_raw = data[offset : offset + ManifestEntry.UID_SIZE]
158
+ offset += ManifestEntry.UID_SIZE
159
+ self.component_uid_raw = data[offset : offset + ManifestEntry.UID_SIZE]
160
+ offset += ManifestEntry.UID_SIZE
161
+ self.image_type = struct.unpack("<H", data[offset : offset + 2])[0]
162
+ offset += 2
163
+ self.partition_type = struct.unpack("<H", data[offset : offset + 2])[0]
164
+ offset += 2
165
+ self.image_file_size = struct.unpack("<I", data[offset : offset + 4])[0]
166
+ offset += 4
167
+ self.uncompressed_image_size = struct.unpack("<I", data[offset : offset + 4])[0]
168
+ offset += 4
169
+
170
+ for _ in range(0, ManifestHeader.MAX_COUNT_ABI_IDENTITIES):
171
+ self.provides += [ABIIdentity(data[offset : offset + ABIIdentity.size()])]
172
+ offset += ABIIdentity.size()
173
+
174
+ for _ in range(0, ManifestHeader.MAX_COUNT_ABI_IDENTITIES):
175
+ self.depends += [ABIIdentity(data[offset : offset + ABIIdentity.size()])]
176
+ offset += ABIIdentity.size()
177
+
178
+ def __str__(self):
179
+ provides_string = ", ".join([str(p) for p in self.provides])
180
+ depends_string = ", ".join([str(d) for d in self.depends])
181
+ return f"ManifestEntry: image_uid={self.image_uid}, component_uid={self.component_uid}, image_type={ImageType.get_name(self.image_type)}, partition_type={self.partition_type}, image_file_size={self.image_file_size}, uncompressed_image_size={self.uncompressed_image_size}, provides=[{provides_string}], depends=[{depends_string}]"
182
+
183
+
184
+ class ImageManifest:
185
+ """
186
+ An ImageManifest lists the images and any dependencies for a recovery folder.
187
+
188
+ The manifest is structured as follows:
189
+ - ManifestHeader
190
+ - ManifestEntry (repeated header.image_count times)
191
+ """
192
+
193
+ def __init__(self, data):
194
+ self.header = None
195
+ self.entries = []
196
+ if data is not None:
197
+ self.deserialize(data)
198
+
199
+ def deserialize(self, data):
200
+ """
201
+ Deserializes the ImageManifest from the provided data.
202
+ """
203
+ offset = 0
204
+ self.header = ManifestHeader(data[offset : offset + ManifestHeader.size()])
205
+ offset += ManifestHeader.size()
206
+ for _ in range(0, self.header.image_count):
207
+ entry = ManifestEntry(
208
+ data[offset : offset + self.header.manifest_entry_size]
209
+ )
210
+ self.entries.append(entry)
211
+ offset += self.header.manifest_entry_size
212
+
213
+ def __str__(self):
214
+ out_lines = []
215
+ out_lines.append(str(self.header))
216
+ for e in self.entries:
217
+ out_lines.append(str(e))
218
+ return "\n".join(out_lines)
219
+
220
+ @staticmethod
221
+ def from_image_metadata(image_metadata: ImageMetadata):
222
+ return ImageManifest(image_metadata.image_data)
223
+
224
+ def str_dotnet(self) -> str:
225
+ """
226
+ Returns a string representation of the manifest using the same formatting as dotnet.
227
+ """
228
+ out_lines = []
229
+ out_lines.append(f"Version: {self.header.version}")
230
+ out_lines.append(
231
+ f"ImageCount: {self.header.image_count}, Number Entries: {len(self.entries)}"
232
+ )
233
+
234
+ for entry in self.entries:
235
+ out_lines.append(
236
+ f"Image type: {ImageType.get_name(entry.image_type)} ({entry.image_type}), Partition: {PartitionType.get_name(entry.partition_type)}, component uid: {entry.component_uid}, image uid: {entry.image_uid}, size: {entry.image_file_size}, uncompressed size: {entry.uncompressed_image_size}"
237
+ )
238
+
239
+ return "\n".join(out_lines) + "\n"
@@ -0,0 +1,254 @@
1
+ # --------------------------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See LICENSE in the project root for license information.
4
+ # --------------------------------------------------------------------------------------------
5
+
6
+ """
7
+ A class that deserialises/parses image metadata given an Azure Sphere image.
8
+ """
9
+
10
+ import struct
11
+ from .metadata_sections.utils import class_from_section_id
12
+ from .metadata_sections.internal.onebl import OneBlInformationSection
13
+ from .metadata_headers.image_metadata import ImageMetadataHeader
14
+ from .metadata_headers.image_metadata_section import ImageMetadataSectionHeader
15
+
16
+
17
+ class ImageMetadata:
18
+ """
19
+ Image metadata contains a header, followed by a number of sections.
20
+ """
21
+
22
+ def __init__(self, data):
23
+ self.sections = []
24
+ self.section_headers = []
25
+ self.header = None
26
+ self.onebl = None
27
+ self.end_of_metadata = 0
28
+ self.start_of_metadata = 0
29
+ self.signature_size = 0
30
+ self.raw_data = bytes()
31
+ if data is not None:
32
+ self.deserialize(data)
33
+
34
+ def deserialize(self, byte_data):
35
+ """
36
+ Image metadata is placed at the end of the file.
37
+ """
38
+ position = 0
39
+ # The image signature is appended to the end of the metadata and is:
40
+ # 64 bytes, if sha256 is used
41
+ # 96 bytes, if sha384 is used
42
+ possible_signature_sizes = [64, 96]
43
+ for possible_signature_size in possible_signature_sizes:
44
+ self.onebl = None # reset onebl on loop as it can be set incorrectly
45
+ minimum_valid_size = (
46
+ possible_signature_size + 4 + ImageMetadataSectionHeader.size()
47
+ )
48
+ metadata_length_offset = possible_signature_size + 4
49
+ onebl_metadata_length_offset = (
50
+ possible_signature_size + 4 + OneBlInformationSection.size()
51
+ )
52
+
53
+ if len(byte_data) < minimum_valid_size:
54
+ continue
55
+
56
+ sig_area_size = possible_signature_size
57
+ end_of_metadata = len(byte_data) - metadata_length_offset
58
+ # length is stored in the four bytes before the signature
59
+ target_length = struct.unpack_from("<I", byte_data, end_of_metadata)[0]
60
+
61
+ if target_length <= 28:
62
+ # This may be a 1BL only section
63
+ if len(byte_data) < minimum_valid_size + OneBlInformationSection.size():
64
+ continue
65
+
66
+ sig_area_size += OneBlInformationSection.size()
67
+
68
+ position = (
69
+ len(byte_data)
70
+ - possible_signature_size
71
+ - OneBlInformationSection.size()
72
+ )
73
+ self.onebl = OneBlInformationSection(
74
+ byte_data[position : position + OneBlInformationSection.size()]
75
+ )
76
+
77
+ end_of_metadata = len(byte_data) - onebl_metadata_length_offset
78
+ position = end_of_metadata
79
+ target_length = struct.unpack_from("<I", byte_data, position)[0]
80
+
81
+ if len(byte_data) < (sig_area_size + target_length):
82
+ # Not enough space, fail
83
+ continue
84
+
85
+ if target_length < ImageMetadataHeader.size():
86
+ # Length too small, fail
87
+ continue
88
+
89
+ header_position = len(byte_data) - sig_area_size - target_length
90
+ self.start_of_metadata = header_position
91
+
92
+ self.image_data = byte_data[0:header_position]
93
+
94
+ header = ImageMetadataHeader(
95
+ byte_data[
96
+ header_position : header_position + ImageMetadataHeader.size()
97
+ ]
98
+ )
99
+
100
+ self.header = header
101
+
102
+ if header.section_count == 0:
103
+ continue
104
+
105
+ section_addr = header_position + ImageMetadataHeader.size()
106
+
107
+ for _ in range(0, header.section_count):
108
+ if section_addr >= end_of_metadata:
109
+ continue
110
+
111
+ section_header_data = byte_data[
112
+ section_addr : section_addr + ImageMetadataSectionHeader.size()
113
+ ]
114
+ section_header = ImageMetadataSectionHeader(section_header_data)
115
+
116
+ self.section_headers += [section_header]
117
+
118
+ if section_header.data_length == 0:
119
+ continue
120
+
121
+ if (
122
+ section_addr
123
+ + ImageMetadataSectionHeader.size()
124
+ + section_header.data_length
125
+ > end_of_metadata
126
+ ):
127
+ continue
128
+
129
+ section_addr += ImageMetadataSectionHeader.size()
130
+
131
+ self.sections += [
132
+ class_from_section_id(section_header.section_id)(
133
+ byte_data[
134
+ section_addr : section_addr + section_header.data_length
135
+ ]
136
+ )
137
+ ]
138
+
139
+ section_addr += section_header.data_length
140
+
141
+ self.end_of_metadata = (
142
+ end_of_metadata + 4
143
+ ) # include the length in the metadata
144
+ self.signature_size = possible_signature_size
145
+ self.raw_data = byte_data[self.start_of_metadata : self.end_of_metadata]
146
+ return
147
+ raise Exception("Invalid metadata")
148
+
149
+ def serialize(self):
150
+ """
151
+ Serialize the image metadata to a byte array.
152
+ """
153
+ header = ImageMetadataHeader()
154
+ header.section_count = len(self.sections)
155
+
156
+ out = header.serialize()
157
+
158
+ for s in self.sections:
159
+ sec_bytes = s.serialize()
160
+ sec_header = ImageMetadataSectionHeader()
161
+ sec_header.section_id = s.section_id
162
+ sec_header.data_length = len(sec_bytes)
163
+ out += sec_header.serialize()
164
+ out += sec_bytes
165
+
166
+ # Add the length of the metadata to the end
167
+ # Include the length of the length field itself (4 bytes)
168
+ out += struct.pack("<I", len(out) + 4)
169
+ return out
170
+
171
+ def add_section(self, section):
172
+ """
173
+ Add a section to the metadata.
174
+ """
175
+ self.sections += [section]
176
+
177
+ def sections_by_name(self, name):
178
+ """
179
+ Returns a list of sections with the given name.
180
+ """
181
+ return [section for section in self.sections if section.name == name]
182
+
183
+ def sections_by_id(self, section_id):
184
+ """
185
+ Returns a list of sections with the given id.
186
+ """
187
+ return [
188
+ section for section in self.sections if section.section_id == section_id
189
+ ]
190
+
191
+ def remove_section(self, section):
192
+ """
193
+ Removes a section from the metadata.
194
+ """
195
+ self.sections = [s for s in self.sections if s != section]
196
+
197
+ def str_dotnet(self) -> str:
198
+ """
199
+ Returns a string representation of the metadata using the same formatting errors as
200
+ the dotnet tool.
201
+ """
202
+ out_lines = []
203
+ # to match dotnet output exactly, each section header has \r\n at the end of it
204
+ # each content line has \r\r\n at the end of it.
205
+ # This is likely a bug in the dotnet code where the lines were split assuming \n
206
+ # as the line ending when infact the line ending was \r\n
207
+ # We will match it for testing purposes.
208
+ for section in self.sections:
209
+ out_lines.append(f" Section: {section.name}\r\n")
210
+
211
+ # the formatting error was not globally applied to all sections,
212
+ # so we need to special case this one
213
+ if section.name == "Required Offset":
214
+ for line in str(section).split("\n"):
215
+ if line.strip() == "":
216
+ continue
217
+ out_lines.append(f" {line}\r\n")
218
+ else:
219
+ for line in str(section).split("\n"):
220
+ if line.strip() == "":
221
+ continue
222
+ out_lines.append(f" {line}\r\r\n")
223
+
224
+ if self.onebl is not None:
225
+ out_lines.append(" Section: 1BL Information\r\n")
226
+ for line in str(self.onebl).split("\n"):
227
+ if line.strip() == "":
228
+ continue
229
+ out_lines.append(f" {line}\r\r\n")
230
+
231
+ out_str = "".join(out_lines)
232
+ return out_str + "\r\n"
233
+
234
+ def __str__(self):
235
+ """
236
+ Returns a correctly formatted string representation of the metadata.
237
+ """
238
+ out_lines = []
239
+ for section in self.sections:
240
+ out_lines.append(f" Section: {section.name}")
241
+
242
+ for line in str(section).split("\n"):
243
+ if line.strip() == "":
244
+ continue
245
+ out_lines.append(f" {line}")
246
+
247
+ if self.onebl is not None:
248
+ out_lines.append(" Section: 1BL Information")
249
+ for line in str(self.onebl).split("\n"):
250
+ if line.strip() == "":
251
+ continue
252
+ out_lines.append(f" {line}")
253
+
254
+ return "\r\n".join(out_lines) + "\r\n"
@@ -0,0 +1,4 @@
1
+ # --------------------------------------------------------------------------------------------
2
+ # Copyright (c) Microsoft Corporation. All rights reserved.
3
+ # Licensed under the MIT License. See LICENSE in the project root for license information.
4
+ # --------------------------------------------------------------------------------------------