blob: e6ae581ad7bd6a7b12abdb221a59f299d723bed4 [file] [log] [blame]
Carles Cufi37d052f2018-01-30 16:40:10 +01001# Copyright 2018 Nordic Semiconductor ASA
David Brown1314bf32017-12-20 11:10:55 -07002# Copyright 2017 Linaro Limited
David Vinczeda8c9192019-03-26 17:17:41 +01003# Copyright 2019 Arm Limited
David Brown1314bf32017-12-20 11:10:55 -07004#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
David Brown23f91ad2017-05-16 11:38:17 -060017"""
18Image signing and management.
19"""
20
21from . import version as versmod
Fabio Utzig4a5477a2019-05-27 15:45:08 -030022from enum import Enum
Carles Cufi37d052f2018-01-30 16:40:10 +010023from intelhex import IntelHex
David Brown23f91ad2017-05-16 11:38:17 -060024import hashlib
25import struct
Carles Cufi37d052f2018-01-30 16:40:10 +010026import os.path
Fabio Utzig06b77b82018-08-23 16:01:16 -030027from cryptography.hazmat.primitives.asymmetric import padding
28from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
29from cryptography.hazmat.backends import default_backend
30from cryptography.hazmat.primitives import hashes
Fabio Utzig4a5477a2019-05-27 15:45:08 -030031from cryptography.exceptions import InvalidSignature
David Brown23f91ad2017-05-16 11:38:17 -060032
David Brown72e7a512017-09-01 11:08:23 -060033IMAGE_MAGIC = 0x96f3b83d
David Brown23f91ad2017-05-16 11:38:17 -060034IMAGE_HEADER_SIZE = 32
Carles Cufi37d052f2018-01-30 16:40:10 +010035BIN_EXT = "bin"
36INTEL_HEX_EXT = "hex"
Fabio Utzig519285f2018-06-04 11:11:53 -030037DEFAULT_MAX_SECTORS = 128
Fabio Utzig649d80f2019-09-12 10:26:23 -030038MAX_ALIGN = 8
David Vinczeda8c9192019-03-26 17:17:41 +010039DEP_IMAGES_KEY = "images"
40DEP_VERSIONS_KEY = "versions"
David Brown23f91ad2017-05-16 11:38:17 -060041
42# Image header flags.
43IMAGE_F = {
44 'PIC': 0x0000001,
Fabio Utzig06b77b82018-08-23 16:01:16 -030045 'NON_BOOTABLE': 0x0000010,
46 'ENCRYPTED': 0x0000004,
47}
David Brown23f91ad2017-05-16 11:38:17 -060048
49TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060050 'KEYHASH': 0x01,
David Brown27648b82017-08-31 10:40:29 -060051 'SHA256': 0x10,
52 'RSA2048': 0x20,
53 'ECDSA224': 0x21,
Fabio Utzig06b77b82018-08-23 16:01:16 -030054 'ECDSA256': 0x22,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030055 'RSA3072': 0x23,
Fabio Utzig8101d1f2019-05-09 15:03:22 -030056 'ED25519': 0x24,
Fabio Utzig06b77b82018-08-23 16:01:16 -030057 'ENCRSA2048': 0x30,
58 'ENCKW128': 0x31,
David Vinczeda8c9192019-03-26 17:17:41 +010059 'DEPENDENCY': 0x40
Fabio Utzig06b77b82018-08-23 16:01:16 -030060}
David Brown23f91ad2017-05-16 11:38:17 -060061
Fabio Utzig4a5477a2019-05-27 15:45:08 -030062TLV_SIZE = 4
David Brownf5b33d82017-09-01 10:58:27 -060063TLV_INFO_SIZE = 4
64TLV_INFO_MAGIC = 0x6907
Fabio Utzig510fddb2019-09-12 12:15:36 -030065TLV_PROT_INFO_MAGIC = 0x6908
David Brown23f91ad2017-05-16 11:38:17 -060066
David Brown23f91ad2017-05-16 11:38:17 -060067boot_magic = bytes([
68 0x77, 0xc2, 0x95, 0xf3,
69 0x60, 0xd2, 0xef, 0x7f,
70 0x35, 0x52, 0x50, 0x0f,
71 0x2c, 0xb6, 0x79, 0x80, ])
72
Mark Schultea66c6872018-09-26 17:24:40 -070073STRUCT_ENDIAN_DICT = {
74 'little': '<',
75 'big': '>'
76}
77
Fabio Utzig4a5477a2019-05-27 15:45:08 -030078VerifyResult = Enum('VerifyResult',
79 """
80 OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH
81 INVALID_SIGNATURE
82 """)
83
84
David Brown23f91ad2017-05-16 11:38:17 -060085class TLV():
Fabio Utzig510fddb2019-09-12 12:15:36 -030086 def __init__(self, endian, magic=TLV_INFO_MAGIC):
87 self.magic = magic
David Brown23f91ad2017-05-16 11:38:17 -060088 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -070089 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -060090
Fabio Utzig510fddb2019-09-12 12:15:36 -030091 def __len__(self):
92 return TLV_INFO_SIZE + len(self.buf)
93
David Brown23f91ad2017-05-16 11:38:17 -060094 def add(self, kind, payload):
Fabio Utzig510fddb2019-09-12 12:15:36 -030095 """
96 Add a TLV record. Kind should be a string found in TLV_VALUES above.
97 """
Mark Schultea66c6872018-09-26 17:24:40 -070098 e = STRUCT_ENDIAN_DICT[self.endian]
99 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -0600100 self.buf += buf
101 self.buf += payload
102
103 def get(self):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300104 if len(self.buf) == 0:
105 return bytes()
Mark Schultea66c6872018-09-26 17:24:40 -0700106 e = STRUCT_ENDIAN_DICT[self.endian]
Fabio Utzig510fddb2019-09-12 12:15:36 -0300107 header = struct.pack(e + 'HH', self.magic, len(self))
David Brownf5b33d82017-09-01 10:58:27 -0600108 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -0600109
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200110
David Brown23f91ad2017-05-16 11:38:17 -0600111class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +0100112
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200113 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
114 pad_header=False, pad=False, align=1, slot_size=0,
115 max_sectors=DEFAULT_MAX_SECTORS, overwrite_only=False,
Fabio Utzig9117fde2019-10-17 11:11:46 -0300116 endian="little", load_addr=0, erased_val=0xff):
David Brown23f91ad2017-05-16 11:38:17 -0600117 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200118 self.header_size = header_size
119 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -0600120 self.pad = pad
Fabio Utzig263d4392018-06-05 10:37:35 -0300121 self.align = align
122 self.slot_size = slot_size
123 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700124 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700125 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200126 self.base_addr = None
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000127 self.load_addr = 0 if load_addr is None else load_addr
Fabio Utzig9117fde2019-10-17 11:11:46 -0300128 self.erased_val = 0xff if erased_val is None else int(erased_val)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200129 self.payload = []
Fabio Utzig649d80f2019-09-12 10:26:23 -0300130 self.enckey = None
David Brown23f91ad2017-05-16 11:38:17 -0600131
132 def __repr__(self):
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000133 return "<Image version={}, header_size={}, base_addr={}, load_addr={}, \
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700134 align={}, slot_size={}, max_sectors={}, overwrite_only={}, \
Mark Schultea66c6872018-09-26 17:24:40 -0700135 endian={} format={}, payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300136 self.version,
137 self.header_size,
138 self.base_addr if self.base_addr is not None else "N/A",
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000139 self.load_addr,
Fabio Utzig263d4392018-06-05 10:37:35 -0300140 self.align,
141 self.slot_size,
142 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700143 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700144 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300145 self.__class__.__name__,
146 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600147
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200148 def load(self, path):
149 """Load an image from a given file"""
150 ext = os.path.splitext(path)[1][1:].lower()
151 if ext == INTEL_HEX_EXT:
152 ih = IntelHex(path)
153 self.payload = ih.tobinarray()
154 self.base_addr = ih.minaddr()
155 else:
156 with open(path, 'rb') as f:
157 self.payload = f.read()
158
159 # Add the image header if needed.
160 if self.pad_header and self.header_size > 0:
161 if self.base_addr:
162 # Adjust base_addr for new header
163 self.base_addr -= self.header_size
Fabio Utzig9117fde2019-10-17 11:11:46 -0300164 self.payload = bytes([self.erased_val] * self.header_size) + \
165 self.payload
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200166
167 self.check()
168
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300169 def save(self, path, hex_addr=None):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200170 """Save an image from a given file"""
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200171 ext = os.path.splitext(path)[1][1:].lower()
172 if ext == INTEL_HEX_EXT:
173 # input was in binary format, but HEX needs to know the base addr
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300174 if self.base_addr is None and hex_addr is None:
175 raise Exception("No address exists in input file neither was "
176 "it provided by user")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200177 h = IntelHex()
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300178 if hex_addr is not None:
179 self.base_addr = hex_addr
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200180 h.frombytes(bytes=self.payload, offset=self.base_addr)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300181 if self.pad:
182 magic_addr = (self.base_addr + self.slot_size) - \
183 len(boot_magic)
184 h.puts(magic_addr, boot_magic)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200185 h.tofile(path, 'hex')
186 else:
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300187 if self.pad:
188 self.pad_to(self.slot_size)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200189 with open(path, 'wb') as f:
190 f.write(self.payload)
191
David Brown23f91ad2017-05-16 11:38:17 -0600192 def check(self):
193 """Perform some sanity checking of the image."""
194 # If there is a header requested, make sure that the image
195 # starts with all zeros.
196 if self.header_size > 0:
197 if any(v != 0 for v in self.payload[0:self.header_size]):
198 raise Exception("Padding requested, but image does not start with zeros")
Fabio Utzig263d4392018-06-05 10:37:35 -0300199 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700200 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig649d80f2019-09-12 10:26:23 -0300201 self.overwrite_only, self.enckey)
Fabio Utzig263d4392018-06-05 10:37:35 -0300202 padding = self.slot_size - (len(self.payload) + tsize)
203 if padding < 0:
204 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
205 len(self.payload), tsize, self.slot_size)
206 raise Exception(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600207
David Vinczeda8c9192019-03-26 17:17:41 +0100208 def create(self, key, enckey, dependencies=None):
Fabio Utzig649d80f2019-09-12 10:26:23 -0300209 self.enckey = enckey
210
David Vinczeda8c9192019-03-26 17:17:41 +0100211 if dependencies is None:
212 dependencies_num = 0
213 protected_tlv_size = 0
214 else:
215 # Size of a Dependency TLV = Header ('BBH') + Payload('IBBHI')
216 # = 16 Bytes
217 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
218 protected_tlv_size = (dependencies_num * 16) + TLV_INFO_SIZE
219
Fabio Utzig510fddb2019-09-12 12:15:36 -0300220 # At this point the image is already on the payload, this adds
221 # the header to the payload as well
David Vinczeda8c9192019-03-26 17:17:41 +0100222 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600223
Fabio Utzig510fddb2019-09-12 12:15:36 -0300224 prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC)
David Brown23f91ad2017-05-16 11:38:17 -0600225
Fabio Utzig510fddb2019-09-12 12:15:36 -0300226 # Protected TLVs must be added first, because they are also included
227 # in the hash calculation
228 protected_tlv_off = None
David Vinczeda8c9192019-03-26 17:17:41 +0100229 if protected_tlv_size != 0:
230 for i in range(dependencies_num):
231 e = STRUCT_ENDIAN_DICT[self.endian]
232 payload = struct.pack(
David Brownbd7925e2019-07-29 11:11:32 -0600233 e + 'B3x'+'BBHI',
David Vinczeda8c9192019-03-26 17:17:41 +0100234 int(dependencies[DEP_IMAGES_KEY][i]),
235 dependencies[DEP_VERSIONS_KEY][i].major,
236 dependencies[DEP_VERSIONS_KEY][i].minor,
237 dependencies[DEP_VERSIONS_KEY][i].revision,
238 dependencies[DEP_VERSIONS_KEY][i].build
239 )
Fabio Utzig510fddb2019-09-12 12:15:36 -0300240 prot_tlv.add('DEPENDENCY', payload)
David Vinczeda8c9192019-03-26 17:17:41 +0100241
Fabio Utzig510fddb2019-09-12 12:15:36 -0300242 protected_tlv_off = len(self.payload)
243 self.payload += prot_tlv.get()
244
245 tlv = TLV(self.endian)
David Vinczeda8c9192019-03-26 17:17:41 +0100246
David Brown23f91ad2017-05-16 11:38:17 -0600247 # Note that ecdsa wants to do the hashing itself, which means
248 # we get to hash it twice.
249 sha = hashlib.sha256()
250 sha.update(self.payload)
251 digest = sha.digest()
252
253 tlv.add('SHA256', digest)
254
David Brown0f0c6a82017-06-08 09:26:24 -0600255 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600256 pub = key.get_public_bytes()
257 sha = hashlib.sha256()
258 sha.update(pub)
259 pubbytes = sha.digest()
260 tlv.add('KEYHASH', pubbytes)
261
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300262 # `sign` expects the full image payload (sha256 done internally),
263 # while `sign_digest` expects only the digest of the payload
264
265 if hasattr(key, 'sign'):
266 sig = key.sign(bytes(self.payload))
267 else:
268 sig = key.sign_digest(digest)
David Brown0f0c6a82017-06-08 09:26:24 -0600269 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600270
Fabio Utzig510fddb2019-09-12 12:15:36 -0300271 # At this point the image was hashed + signed, we can remove the
272 # protected TLVs from the payload (will be re-added later)
273 if protected_tlv_off is not None:
274 self.payload = self.payload[:protected_tlv_off]
275
Fabio Utzig06b77b82018-08-23 16:01:16 -0300276 if enckey is not None:
277 plainkey = os.urandom(16)
278 cipherkey = enckey._get_public().encrypt(
279 plainkey, padding.OAEP(
280 mgf=padding.MGF1(algorithm=hashes.SHA256()),
281 algorithm=hashes.SHA256(),
282 label=None))
283 tlv.add('ENCRSA2048', cipherkey)
284
285 nonce = bytes([0] * 16)
286 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
287 backend=default_backend())
288 encryptor = cipher.encryptor()
289 img = bytes(self.payload[self.header_size:])
Fabio Utzig510fddb2019-09-12 12:15:36 -0300290 self.payload[self.header_size:] = \
291 encryptor.update(img) + encryptor.finalize()
Fabio Utzig06b77b82018-08-23 16:01:16 -0300292
Fabio Utzig510fddb2019-09-12 12:15:36 -0300293 self.payload += prot_tlv.get()
294 self.payload += tlv.get()
David Brown23f91ad2017-05-16 11:38:17 -0600295
David Vinczeda8c9192019-03-26 17:17:41 +0100296 def add_header(self, enckey, protected_tlv_size):
Fabio Utzigcd284062018-11-30 11:05:45 -0200297 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600298
David Brown0f0c6a82017-06-08 09:26:24 -0600299 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300300 if enckey is not None:
301 flags |= IMAGE_F['ENCRYPTED']
David Brown23f91ad2017-05-16 11:38:17 -0600302
Mark Schultea66c6872018-09-26 17:24:40 -0700303 e = STRUCT_ENDIAN_DICT[self.endian]
304 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100305 # type ImageHdr struct {
306 'I' + # Magic uint32
307 'I' + # LoadAddr uint32
308 'H' + # HdrSz uint16
309 'H' + # PTLVSz uint16
310 'I' + # ImgSz uint32
311 'I' + # Flags uint32
312 'BBHI' + # Vers ImageVersion
313 'I' # Pad1 uint32
314 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600315 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
316 header = struct.pack(fmt,
317 IMAGE_MAGIC,
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000318 self.load_addr,
David Brown23f91ad2017-05-16 11:38:17 -0600319 self.header_size,
Fabio Utzig510fddb2019-09-12 12:15:36 -0300320 protected_tlv_size, # TLV Info header + Protected TLVs
321 len(self.payload) - self.header_size, # ImageSz
322 flags,
David Brown23f91ad2017-05-16 11:38:17 -0600323 self.version.major,
324 self.version.minor or 0,
325 self.version.revision or 0,
326 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100327 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600328 self.payload = bytearray(self.payload)
329 self.payload[:len(header)] = header
330
Fabio Utzig649d80f2019-09-12 10:26:23 -0300331 def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey):
Fabio Utzig519285f2018-06-04 11:11:53 -0300332 # NOTE: should already be checked by the argument parser
Fabio Utzig649d80f2019-09-12 10:26:23 -0300333 magic_size = 16
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700334 if overwrite_only:
Fabio Utzig649d80f2019-09-12 10:26:23 -0300335 return MAX_ALIGN * 2 + magic_size
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700336 else:
337 if write_size not in set([1, 2, 4, 8]):
338 raise Exception("Invalid alignment: {}".format(write_size))
339 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
Fabio Utzig649d80f2019-09-12 10:26:23 -0300340 trailer = m * 3 * write_size # status area
341 if enckey is not None:
342 trailer += 16 * 2 # encryption keys
343 trailer += MAX_ALIGN * 4 # magic_ok/copy_done/swap_info/swap_size
344 trailer += magic_size
345 return trailer
Fabio Utzig519285f2018-06-04 11:11:53 -0300346
Fabio Utzig263d4392018-06-05 10:37:35 -0300347 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600348 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700349 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig649d80f2019-09-12 10:26:23 -0300350 self.overwrite_only, self.enckey)
David Brown23f91ad2017-05-16 11:38:17 -0600351 padding = size - (len(self.payload) + tsize)
Fabio Utzig9117fde2019-10-17 11:11:46 -0300352 pbytes = bytes([self.erased_val] * padding)
353 pbytes += bytes([self.erased_val] * (tsize - len(boot_magic)))
Fabio Utzige08f0872017-06-28 18:12:16 -0300354 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600355 self.payload += pbytes
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300356
357 @staticmethod
358 def verify(imgfile, key):
359 with open(imgfile, "rb") as f:
360 b = f.read()
361
362 magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
Marek Pietae9555102019-08-08 16:08:16 +0200363 version = struct.unpack('BBHI', b[20:28])
364
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300365 if magic != IMAGE_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200366 return VerifyResult.INVALID_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300367
368 tlv_info = b[header_size+img_size:header_size+img_size+TLV_INFO_SIZE]
369 magic, tlv_tot = struct.unpack('HH', tlv_info)
370 if magic != TLV_INFO_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200371 return VerifyResult.INVALID_TLV_INFO_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300372
373 sha = hashlib.sha256()
374 sha.update(b[:header_size+img_size])
375 digest = sha.digest()
376
377 tlv_off = header_size + img_size
378 tlv_end = tlv_off + tlv_tot
379 tlv_off += TLV_INFO_SIZE # skip tlv info
380 while tlv_off < tlv_end:
381 tlv = b[tlv_off:tlv_off+TLV_SIZE]
382 tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
383 if tlv_type == TLV_VALUES["SHA256"]:
384 off = tlv_off + TLV_SIZE
385 if digest == b[off:off+tlv_len]:
386 if key is None:
Marek Pietae9555102019-08-08 16:08:16 +0200387 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300388 else:
Marek Pietae9555102019-08-08 16:08:16 +0200389 return VerifyResult.INVALID_HASH, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300390 elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
391 off = tlv_off + TLV_SIZE
392 tlv_sig = b[off:off+tlv_len]
393 payload = b[:header_size+img_size]
394 try:
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300395 if hasattr(key, 'verify'):
396 key.verify(tlv_sig, payload)
397 else:
398 key.verify_digest(tlv_sig, digest)
Marek Pietae9555102019-08-08 16:08:16 +0200399 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300400 except InvalidSignature:
401 # continue to next TLV
402 pass
403 tlv_off += TLV_SIZE + tlv_len
Marek Pietae9555102019-08-08 16:08:16 +0200404 return VerifyResult.INVALID_SIGNATURE, None