blob: 78600dda08b9e020184f0670bf0a2c41f028e558 [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,
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000116 endian="little", load_addr=0):
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 Utzig7c00acd2019-01-07 09:54:20 -0200128 self.payload = []
Fabio Utzig649d80f2019-09-12 10:26:23 -0300129 self.enckey = None
David Brown23f91ad2017-05-16 11:38:17 -0600130
131 def __repr__(self):
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000132 return "<Image version={}, header_size={}, base_addr={}, load_addr={}, \
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700133 align={}, slot_size={}, max_sectors={}, overwrite_only={}, \
Mark Schultea66c6872018-09-26 17:24:40 -0700134 endian={} format={}, payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300135 self.version,
136 self.header_size,
137 self.base_addr if self.base_addr is not None else "N/A",
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000138 self.load_addr,
Fabio Utzig263d4392018-06-05 10:37:35 -0300139 self.align,
140 self.slot_size,
141 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700142 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700143 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300144 self.__class__.__name__,
145 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600146
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200147 def load(self, path):
148 """Load an image from a given file"""
149 ext = os.path.splitext(path)[1][1:].lower()
150 if ext == INTEL_HEX_EXT:
151 ih = IntelHex(path)
152 self.payload = ih.tobinarray()
153 self.base_addr = ih.minaddr()
154 else:
155 with open(path, 'rb') as f:
156 self.payload = f.read()
157
158 # Add the image header if needed.
159 if self.pad_header and self.header_size > 0:
160 if self.base_addr:
161 # Adjust base_addr for new header
162 self.base_addr -= self.header_size
163 self.payload = (b'\000' * self.header_size) + self.payload
164
165 self.check()
166
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300167 def save(self, path, hex_addr=None):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200168 """Save an image from a given file"""
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200169 ext = os.path.splitext(path)[1][1:].lower()
170 if ext == INTEL_HEX_EXT:
171 # input was in binary format, but HEX needs to know the base addr
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300172 if self.base_addr is None and hex_addr is None:
173 raise Exception("No address exists in input file neither was "
174 "it provided by user")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200175 h = IntelHex()
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300176 if hex_addr is not None:
177 self.base_addr = hex_addr
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200178 h.frombytes(bytes=self.payload, offset=self.base_addr)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300179 if self.pad:
180 magic_addr = (self.base_addr + self.slot_size) - \
181 len(boot_magic)
182 h.puts(magic_addr, boot_magic)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200183 h.tofile(path, 'hex')
184 else:
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300185 if self.pad:
186 self.pad_to(self.slot_size)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200187 with open(path, 'wb') as f:
188 f.write(self.payload)
189
David Brown23f91ad2017-05-16 11:38:17 -0600190 def check(self):
191 """Perform some sanity checking of the image."""
192 # If there is a header requested, make sure that the image
193 # starts with all zeros.
194 if self.header_size > 0:
195 if any(v != 0 for v in self.payload[0:self.header_size]):
196 raise Exception("Padding requested, but image does not start with zeros")
Fabio Utzig263d4392018-06-05 10:37:35 -0300197 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700198 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig649d80f2019-09-12 10:26:23 -0300199 self.overwrite_only, self.enckey)
Fabio Utzig263d4392018-06-05 10:37:35 -0300200 padding = self.slot_size - (len(self.payload) + tsize)
201 if padding < 0:
202 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
203 len(self.payload), tsize, self.slot_size)
204 raise Exception(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600205
David Vinczeda8c9192019-03-26 17:17:41 +0100206 def create(self, key, enckey, dependencies=None):
Fabio Utzig649d80f2019-09-12 10:26:23 -0300207 self.enckey = enckey
208
David Vinczeda8c9192019-03-26 17:17:41 +0100209 if dependencies is None:
210 dependencies_num = 0
211 protected_tlv_size = 0
212 else:
213 # Size of a Dependency TLV = Header ('BBH') + Payload('IBBHI')
214 # = 16 Bytes
215 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
216 protected_tlv_size = (dependencies_num * 16) + TLV_INFO_SIZE
217
Fabio Utzig510fddb2019-09-12 12:15:36 -0300218 # At this point the image is already on the payload, this adds
219 # the header to the payload as well
David Vinczeda8c9192019-03-26 17:17:41 +0100220 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600221
Fabio Utzig510fddb2019-09-12 12:15:36 -0300222 prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC)
David Brown23f91ad2017-05-16 11:38:17 -0600223
Fabio Utzig510fddb2019-09-12 12:15:36 -0300224 # Protected TLVs must be added first, because they are also included
225 # in the hash calculation
226 protected_tlv_off = None
David Vinczeda8c9192019-03-26 17:17:41 +0100227 if protected_tlv_size != 0:
228 for i in range(dependencies_num):
229 e = STRUCT_ENDIAN_DICT[self.endian]
230 payload = struct.pack(
David Brownbd7925e2019-07-29 11:11:32 -0600231 e + 'B3x'+'BBHI',
David Vinczeda8c9192019-03-26 17:17:41 +0100232 int(dependencies[DEP_IMAGES_KEY][i]),
233 dependencies[DEP_VERSIONS_KEY][i].major,
234 dependencies[DEP_VERSIONS_KEY][i].minor,
235 dependencies[DEP_VERSIONS_KEY][i].revision,
236 dependencies[DEP_VERSIONS_KEY][i].build
237 )
Fabio Utzig510fddb2019-09-12 12:15:36 -0300238 prot_tlv.add('DEPENDENCY', payload)
David Vinczeda8c9192019-03-26 17:17:41 +0100239
Fabio Utzig510fddb2019-09-12 12:15:36 -0300240 protected_tlv_off = len(self.payload)
241 self.payload += prot_tlv.get()
242
243 tlv = TLV(self.endian)
David Vinczeda8c9192019-03-26 17:17:41 +0100244
David Brown23f91ad2017-05-16 11:38:17 -0600245 # Note that ecdsa wants to do the hashing itself, which means
246 # we get to hash it twice.
247 sha = hashlib.sha256()
248 sha.update(self.payload)
249 digest = sha.digest()
250
251 tlv.add('SHA256', digest)
252
David Brown0f0c6a82017-06-08 09:26:24 -0600253 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600254 pub = key.get_public_bytes()
255 sha = hashlib.sha256()
256 sha.update(pub)
257 pubbytes = sha.digest()
258 tlv.add('KEYHASH', pubbytes)
259
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300260 # `sign` expects the full image payload (sha256 done internally),
261 # while `sign_digest` expects only the digest of the payload
262
263 if hasattr(key, 'sign'):
264 sig = key.sign(bytes(self.payload))
265 else:
266 sig = key.sign_digest(digest)
David Brown0f0c6a82017-06-08 09:26:24 -0600267 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600268
Fabio Utzig510fddb2019-09-12 12:15:36 -0300269 # At this point the image was hashed + signed, we can remove the
270 # protected TLVs from the payload (will be re-added later)
271 if protected_tlv_off is not None:
272 self.payload = self.payload[:protected_tlv_off]
273
Fabio Utzig06b77b82018-08-23 16:01:16 -0300274 if enckey is not None:
275 plainkey = os.urandom(16)
276 cipherkey = enckey._get_public().encrypt(
277 plainkey, padding.OAEP(
278 mgf=padding.MGF1(algorithm=hashes.SHA256()),
279 algorithm=hashes.SHA256(),
280 label=None))
281 tlv.add('ENCRSA2048', cipherkey)
282
283 nonce = bytes([0] * 16)
284 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
285 backend=default_backend())
286 encryptor = cipher.encryptor()
287 img = bytes(self.payload[self.header_size:])
Fabio Utzig510fddb2019-09-12 12:15:36 -0300288 self.payload[self.header_size:] = \
289 encryptor.update(img) + encryptor.finalize()
Fabio Utzig06b77b82018-08-23 16:01:16 -0300290
Fabio Utzig510fddb2019-09-12 12:15:36 -0300291 self.payload += prot_tlv.get()
292 self.payload += tlv.get()
David Brown23f91ad2017-05-16 11:38:17 -0600293
David Vinczeda8c9192019-03-26 17:17:41 +0100294 def add_header(self, enckey, protected_tlv_size):
Fabio Utzigcd284062018-11-30 11:05:45 -0200295 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600296
David Brown0f0c6a82017-06-08 09:26:24 -0600297 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300298 if enckey is not None:
299 flags |= IMAGE_F['ENCRYPTED']
David Brown23f91ad2017-05-16 11:38:17 -0600300
Mark Schultea66c6872018-09-26 17:24:40 -0700301 e = STRUCT_ENDIAN_DICT[self.endian]
302 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100303 # type ImageHdr struct {
304 'I' + # Magic uint32
305 'I' + # LoadAddr uint32
306 'H' + # HdrSz uint16
307 'H' + # PTLVSz uint16
308 'I' + # ImgSz uint32
309 'I' + # Flags uint32
310 'BBHI' + # Vers ImageVersion
311 'I' # Pad1 uint32
312 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600313 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
314 header = struct.pack(fmt,
315 IMAGE_MAGIC,
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000316 self.load_addr,
David Brown23f91ad2017-05-16 11:38:17 -0600317 self.header_size,
Fabio Utzig510fddb2019-09-12 12:15:36 -0300318 protected_tlv_size, # TLV Info header + Protected TLVs
319 len(self.payload) - self.header_size, # ImageSz
320 flags,
David Brown23f91ad2017-05-16 11:38:17 -0600321 self.version.major,
322 self.version.minor or 0,
323 self.version.revision or 0,
324 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100325 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600326 self.payload = bytearray(self.payload)
327 self.payload[:len(header)] = header
328
Fabio Utzig649d80f2019-09-12 10:26:23 -0300329 def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey):
Fabio Utzig519285f2018-06-04 11:11:53 -0300330 # NOTE: should already be checked by the argument parser
Fabio Utzig649d80f2019-09-12 10:26:23 -0300331 magic_size = 16
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700332 if overwrite_only:
Fabio Utzig649d80f2019-09-12 10:26:23 -0300333 return MAX_ALIGN * 2 + magic_size
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700334 else:
335 if write_size not in set([1, 2, 4, 8]):
336 raise Exception("Invalid alignment: {}".format(write_size))
337 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
Fabio Utzig649d80f2019-09-12 10:26:23 -0300338 trailer = m * 3 * write_size # status area
339 if enckey is not None:
340 trailer += 16 * 2 # encryption keys
341 trailer += MAX_ALIGN * 4 # magic_ok/copy_done/swap_info/swap_size
342 trailer += magic_size
343 return trailer
Fabio Utzig519285f2018-06-04 11:11:53 -0300344
Fabio Utzig263d4392018-06-05 10:37:35 -0300345 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600346 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700347 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig649d80f2019-09-12 10:26:23 -0300348 self.overwrite_only, self.enckey)
David Brown23f91ad2017-05-16 11:38:17 -0600349 padding = size - (len(self.payload) + tsize)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300350 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600351 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300352 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600353 self.payload += pbytes
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300354
355 @staticmethod
356 def verify(imgfile, key):
357 with open(imgfile, "rb") as f:
358 b = f.read()
359
360 magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
Marek Pietae9555102019-08-08 16:08:16 +0200361 version = struct.unpack('BBHI', b[20:28])
362
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300363 if magic != IMAGE_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200364 return VerifyResult.INVALID_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300365
366 tlv_info = b[header_size+img_size:header_size+img_size+TLV_INFO_SIZE]
367 magic, tlv_tot = struct.unpack('HH', tlv_info)
368 if magic != TLV_INFO_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200369 return VerifyResult.INVALID_TLV_INFO_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300370
371 sha = hashlib.sha256()
372 sha.update(b[:header_size+img_size])
373 digest = sha.digest()
374
375 tlv_off = header_size + img_size
376 tlv_end = tlv_off + tlv_tot
377 tlv_off += TLV_INFO_SIZE # skip tlv info
378 while tlv_off < tlv_end:
379 tlv = b[tlv_off:tlv_off+TLV_SIZE]
380 tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
381 if tlv_type == TLV_VALUES["SHA256"]:
382 off = tlv_off + TLV_SIZE
383 if digest == b[off:off+tlv_len]:
384 if key is None:
Marek Pietae9555102019-08-08 16:08:16 +0200385 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300386 else:
Marek Pietae9555102019-08-08 16:08:16 +0200387 return VerifyResult.INVALID_HASH, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300388 elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
389 off = tlv_off + TLV_SIZE
390 tlv_sig = b[off:off+tlv_len]
391 payload = b[:header_size+img_size]
392 try:
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300393 if hasattr(key, 'verify'):
394 key.verify(tlv_sig, payload)
395 else:
396 key.verify_digest(tlv_sig, digest)
Marek Pietae9555102019-08-08 16:08:16 +0200397 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300398 except InvalidSignature:
399 # continue to next TLV
400 pass
401 tlv_off += TLV_SIZE + tlv_len
Marek Pietae9555102019-08-08 16:08:16 +0200402 return VerifyResult.INVALID_SIGNATURE, None