blob: e2461c22954ec5480fccae47c92030ac5da81f1e [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 Utzig7a3b2602019-10-22 09:56:44 -030027from .keys import rsa, ecdsa
28from cryptography.hazmat.primitives.asymmetric import ec, padding
Fabio Utzig06b77b82018-08-23 16:01:16 -030029from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Fabio Utzig7a3b2602019-10-22 09:56:44 -030030from cryptography.hazmat.primitives.kdf.hkdf import HKDF
31from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
Fabio Utzig06b77b82018-08-23 16:01:16 -030032from cryptography.hazmat.backends import default_backend
Fabio Utzig7a3b2602019-10-22 09:56:44 -030033from cryptography.hazmat.primitives import hashes, hmac
Fabio Utzig4a5477a2019-05-27 15:45:08 -030034from cryptography.exceptions import InvalidSignature
David Brown23f91ad2017-05-16 11:38:17 -060035
David Brown72e7a512017-09-01 11:08:23 -060036IMAGE_MAGIC = 0x96f3b83d
David Brown23f91ad2017-05-16 11:38:17 -060037IMAGE_HEADER_SIZE = 32
Carles Cufi37d052f2018-01-30 16:40:10 +010038BIN_EXT = "bin"
39INTEL_HEX_EXT = "hex"
Fabio Utzig519285f2018-06-04 11:11:53 -030040DEFAULT_MAX_SECTORS = 128
Fabio Utzig649d80f2019-09-12 10:26:23 -030041MAX_ALIGN = 8
David Vinczeda8c9192019-03-26 17:17:41 +010042DEP_IMAGES_KEY = "images"
43DEP_VERSIONS_KEY = "versions"
David Brown23f91ad2017-05-16 11:38:17 -060044
45# Image header flags.
46IMAGE_F = {
47 'PIC': 0x0000001,
Fabio Utzig06b77b82018-08-23 16:01:16 -030048 'NON_BOOTABLE': 0x0000010,
49 'ENCRYPTED': 0x0000004,
50}
David Brown23f91ad2017-05-16 11:38:17 -060051
52TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060053 'KEYHASH': 0x01,
David Brown27648b82017-08-31 10:40:29 -060054 'SHA256': 0x10,
55 'RSA2048': 0x20,
56 'ECDSA224': 0x21,
Fabio Utzig06b77b82018-08-23 16:01:16 -030057 'ECDSA256': 0x22,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030058 'RSA3072': 0x23,
Fabio Utzig8101d1f2019-05-09 15:03:22 -030059 'ED25519': 0x24,
Fabio Utzig06b77b82018-08-23 16:01:16 -030060 'ENCRSA2048': 0x30,
61 'ENCKW128': 0x31,
Fabio Utzig7a3b2602019-10-22 09:56:44 -030062 'ENCEC256': 0x32,
David Vinczeda8c9192019-03-26 17:17:41 +010063 'DEPENDENCY': 0x40
Fabio Utzig06b77b82018-08-23 16:01:16 -030064}
David Brown23f91ad2017-05-16 11:38:17 -060065
Fabio Utzig4a5477a2019-05-27 15:45:08 -030066TLV_SIZE = 4
David Brownf5b33d82017-09-01 10:58:27 -060067TLV_INFO_SIZE = 4
68TLV_INFO_MAGIC = 0x6907
Fabio Utzig510fddb2019-09-12 12:15:36 -030069TLV_PROT_INFO_MAGIC = 0x6908
David Brown23f91ad2017-05-16 11:38:17 -060070
David Brown23f91ad2017-05-16 11:38:17 -060071boot_magic = bytes([
72 0x77, 0xc2, 0x95, 0xf3,
73 0x60, 0xd2, 0xef, 0x7f,
74 0x35, 0x52, 0x50, 0x0f,
75 0x2c, 0xb6, 0x79, 0x80, ])
76
Mark Schultea66c6872018-09-26 17:24:40 -070077STRUCT_ENDIAN_DICT = {
78 'little': '<',
79 'big': '>'
80}
81
Fabio Utzig4a5477a2019-05-27 15:45:08 -030082VerifyResult = Enum('VerifyResult',
83 """
84 OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH
85 INVALID_SIGNATURE
86 """)
87
88
David Brown23f91ad2017-05-16 11:38:17 -060089class TLV():
Fabio Utzig510fddb2019-09-12 12:15:36 -030090 def __init__(self, endian, magic=TLV_INFO_MAGIC):
91 self.magic = magic
David Brown23f91ad2017-05-16 11:38:17 -060092 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -070093 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -060094
Fabio Utzig510fddb2019-09-12 12:15:36 -030095 def __len__(self):
96 return TLV_INFO_SIZE + len(self.buf)
97
David Brown23f91ad2017-05-16 11:38:17 -060098 def add(self, kind, payload):
Fabio Utzig510fddb2019-09-12 12:15:36 -030099 """
100 Add a TLV record. Kind should be a string found in TLV_VALUES above.
101 """
Mark Schultea66c6872018-09-26 17:24:40 -0700102 e = STRUCT_ENDIAN_DICT[self.endian]
103 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -0600104 self.buf += buf
105 self.buf += payload
106
107 def get(self):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300108 if len(self.buf) == 0:
109 return bytes()
Mark Schultea66c6872018-09-26 17:24:40 -0700110 e = STRUCT_ENDIAN_DICT[self.endian]
Fabio Utzig510fddb2019-09-12 12:15:36 -0300111 header = struct.pack(e + 'HH', self.magic, len(self))
David Brownf5b33d82017-09-01 10:58:27 -0600112 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -0600113
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200114
David Brown23f91ad2017-05-16 11:38:17 -0600115class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +0100116
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200117 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
118 pad_header=False, pad=False, align=1, slot_size=0,
119 max_sectors=DEFAULT_MAX_SECTORS, overwrite_only=False,
Fabio Utzig9117fde2019-10-17 11:11:46 -0300120 endian="little", load_addr=0, erased_val=0xff):
David Brown23f91ad2017-05-16 11:38:17 -0600121 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200122 self.header_size = header_size
123 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -0600124 self.pad = pad
Fabio Utzig263d4392018-06-05 10:37:35 -0300125 self.align = align
126 self.slot_size = slot_size
127 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700128 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700129 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200130 self.base_addr = None
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000131 self.load_addr = 0 if load_addr is None else load_addr
Fabio Utzig9117fde2019-10-17 11:11:46 -0300132 self.erased_val = 0xff if erased_val is None else int(erased_val)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200133 self.payload = []
Fabio Utzig649d80f2019-09-12 10:26:23 -0300134 self.enckey = None
David Brown23f91ad2017-05-16 11:38:17 -0600135
136 def __repr__(self):
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000137 return "<Image version={}, header_size={}, base_addr={}, load_addr={}, \
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700138 align={}, slot_size={}, max_sectors={}, overwrite_only={}, \
Mark Schultea66c6872018-09-26 17:24:40 -0700139 endian={} format={}, payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300140 self.version,
141 self.header_size,
142 self.base_addr if self.base_addr is not None else "N/A",
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000143 self.load_addr,
Fabio Utzig263d4392018-06-05 10:37:35 -0300144 self.align,
145 self.slot_size,
146 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700147 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700148 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300149 self.__class__.__name__,
150 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600151
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200152 def load(self, path):
153 """Load an image from a given file"""
154 ext = os.path.splitext(path)[1][1:].lower()
155 if ext == INTEL_HEX_EXT:
156 ih = IntelHex(path)
157 self.payload = ih.tobinarray()
158 self.base_addr = ih.minaddr()
159 else:
160 with open(path, 'rb') as f:
161 self.payload = f.read()
162
163 # Add the image header if needed.
164 if self.pad_header and self.header_size > 0:
165 if self.base_addr:
166 # Adjust base_addr for new header
167 self.base_addr -= self.header_size
Fabio Utzig9117fde2019-10-17 11:11:46 -0300168 self.payload = bytes([self.erased_val] * self.header_size) + \
169 self.payload
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200170
171 self.check()
172
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300173 def save(self, path, hex_addr=None):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200174 """Save an image from a given file"""
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200175 ext = os.path.splitext(path)[1][1:].lower()
176 if ext == INTEL_HEX_EXT:
177 # input was in binary format, but HEX needs to know the base addr
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300178 if self.base_addr is None and hex_addr is None:
179 raise Exception("No address exists in input file neither was "
180 "it provided by user")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200181 h = IntelHex()
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300182 if hex_addr is not None:
183 self.base_addr = hex_addr
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200184 h.frombytes(bytes=self.payload, offset=self.base_addr)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300185 if self.pad:
Fabio Utzig2269f472019-10-17 11:14:33 -0300186 trailer_size = self._trailer_size(self.align, self.max_sectors,
187 self.overwrite_only,
188 self.enckey)
189 trailer_addr = (self.base_addr + self.slot_size) - trailer_size
190 padding = bytes([self.erased_val] *
191 (trailer_size - len(boot_magic))) + boot_magic
192 h.puts(trailer_addr, padding)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200193 h.tofile(path, 'hex')
194 else:
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300195 if self.pad:
196 self.pad_to(self.slot_size)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200197 with open(path, 'wb') as f:
198 f.write(self.payload)
199
David Brown23f91ad2017-05-16 11:38:17 -0600200 def check(self):
201 """Perform some sanity checking of the image."""
202 # If there is a header requested, make sure that the image
203 # starts with all zeros.
Fabio Utzigf5556c32019-10-23 11:00:27 -0300204 if self.header_size > 0 and not self.pad_header:
David Brown23f91ad2017-05-16 11:38:17 -0600205 if any(v != 0 for v in self.payload[0:self.header_size]):
206 raise Exception("Padding requested, but image does not start with zeros")
Fabio Utzig263d4392018-06-05 10:37:35 -0300207 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700208 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig649d80f2019-09-12 10:26:23 -0300209 self.overwrite_only, self.enckey)
Fabio Utzig263d4392018-06-05 10:37:35 -0300210 padding = self.slot_size - (len(self.payload) + tsize)
211 if padding < 0:
212 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
213 len(self.payload), tsize, self.slot_size)
214 raise Exception(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600215
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300216 def ecies_p256_hkdf(self, enckey, plainkey):
217 newpk = ec.generate_private_key(ec.SECP256R1(), default_backend())
218 shared = newpk.exchange(ec.ECDH(), enckey._get_public())
219 derived_key = HKDF(
220 algorithm=hashes.SHA256(), length=48, salt=None,
221 info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared)
222 encryptor = Cipher(algorithms.AES(derived_key[:16]),
223 modes.CTR(bytes([0] * 16)),
224 backend=default_backend()).encryptor()
225 cipherkey = encryptor.update(plainkey) + encryptor.finalize()
226 mac = hmac.HMAC(derived_key[16:], hashes.SHA256(),
227 backend=default_backend())
228 mac.update(cipherkey)
229 ciphermac = mac.finalize()
230 pubk = newpk.public_key().public_bytes(
231 encoding=Encoding.X962,
232 format=PublicFormat.UncompressedPoint)
233 return cipherkey, ciphermac, pubk
234
David Vinczeda8c9192019-03-26 17:17:41 +0100235 def create(self, key, enckey, dependencies=None):
Fabio Utzig649d80f2019-09-12 10:26:23 -0300236 self.enckey = enckey
237
David Vinczeda8c9192019-03-26 17:17:41 +0100238 if dependencies is None:
239 dependencies_num = 0
240 protected_tlv_size = 0
241 else:
242 # Size of a Dependency TLV = Header ('BBH') + Payload('IBBHI')
243 # = 16 Bytes
244 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
245 protected_tlv_size = (dependencies_num * 16) + TLV_INFO_SIZE
246
Fabio Utzig510fddb2019-09-12 12:15:36 -0300247 # At this point the image is already on the payload, this adds
248 # the header to the payload as well
David Vinczeda8c9192019-03-26 17:17:41 +0100249 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600250
Fabio Utzig510fddb2019-09-12 12:15:36 -0300251 prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC)
David Brown23f91ad2017-05-16 11:38:17 -0600252
Fabio Utzig510fddb2019-09-12 12:15:36 -0300253 # Protected TLVs must be added first, because they are also included
254 # in the hash calculation
255 protected_tlv_off = None
David Vinczeda8c9192019-03-26 17:17:41 +0100256 if protected_tlv_size != 0:
257 for i in range(dependencies_num):
258 e = STRUCT_ENDIAN_DICT[self.endian]
259 payload = struct.pack(
David Brownbd7925e2019-07-29 11:11:32 -0600260 e + 'B3x'+'BBHI',
David Vinczeda8c9192019-03-26 17:17:41 +0100261 int(dependencies[DEP_IMAGES_KEY][i]),
262 dependencies[DEP_VERSIONS_KEY][i].major,
263 dependencies[DEP_VERSIONS_KEY][i].minor,
264 dependencies[DEP_VERSIONS_KEY][i].revision,
265 dependencies[DEP_VERSIONS_KEY][i].build
266 )
Fabio Utzig510fddb2019-09-12 12:15:36 -0300267 prot_tlv.add('DEPENDENCY', payload)
David Vinczeda8c9192019-03-26 17:17:41 +0100268
Fabio Utzig510fddb2019-09-12 12:15:36 -0300269 protected_tlv_off = len(self.payload)
270 self.payload += prot_tlv.get()
271
272 tlv = TLV(self.endian)
David Vinczeda8c9192019-03-26 17:17:41 +0100273
David Brown23f91ad2017-05-16 11:38:17 -0600274 # Note that ecdsa wants to do the hashing itself, which means
275 # we get to hash it twice.
276 sha = hashlib.sha256()
277 sha.update(self.payload)
278 digest = sha.digest()
279
280 tlv.add('SHA256', digest)
281
David Brown0f0c6a82017-06-08 09:26:24 -0600282 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600283 pub = key.get_public_bytes()
284 sha = hashlib.sha256()
285 sha.update(pub)
286 pubbytes = sha.digest()
287 tlv.add('KEYHASH', pubbytes)
288
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300289 # `sign` expects the full image payload (sha256 done internally),
290 # while `sign_digest` expects only the digest of the payload
291
292 if hasattr(key, 'sign'):
293 sig = key.sign(bytes(self.payload))
294 else:
295 sig = key.sign_digest(digest)
David Brown0f0c6a82017-06-08 09:26:24 -0600296 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600297
Fabio Utzig510fddb2019-09-12 12:15:36 -0300298 # At this point the image was hashed + signed, we can remove the
299 # protected TLVs from the payload (will be re-added later)
300 if protected_tlv_off is not None:
301 self.payload = self.payload[:protected_tlv_off]
302
Fabio Utzig06b77b82018-08-23 16:01:16 -0300303 if enckey is not None:
304 plainkey = os.urandom(16)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300305
306 if isinstance(enckey, rsa.RSAPublic):
307 cipherkey = enckey._get_public().encrypt(
308 plainkey, padding.OAEP(
309 mgf=padding.MGF1(algorithm=hashes.SHA256()),
310 algorithm=hashes.SHA256(),
311 label=None))
312 tlv.add('ENCRSA2048', cipherkey)
313 elif isinstance(enckey, ecdsa.ECDSA256P1Public):
314 cipherkey, mac, pubk = self.ecies_p256_hkdf(enckey, plainkey)
315 tlv.add('ENCEC256', pubk + mac + cipherkey)
Fabio Utzig06b77b82018-08-23 16:01:16 -0300316
317 nonce = bytes([0] * 16)
318 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
319 backend=default_backend())
320 encryptor = cipher.encryptor()
321 img = bytes(self.payload[self.header_size:])
Fabio Utzig510fddb2019-09-12 12:15:36 -0300322 self.payload[self.header_size:] = \
323 encryptor.update(img) + encryptor.finalize()
Fabio Utzig06b77b82018-08-23 16:01:16 -0300324
Fabio Utzig510fddb2019-09-12 12:15:36 -0300325 self.payload += prot_tlv.get()
326 self.payload += tlv.get()
David Brown23f91ad2017-05-16 11:38:17 -0600327
David Vinczeda8c9192019-03-26 17:17:41 +0100328 def add_header(self, enckey, protected_tlv_size):
Fabio Utzigcd284062018-11-30 11:05:45 -0200329 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600330
David Brown0f0c6a82017-06-08 09:26:24 -0600331 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300332 if enckey is not None:
333 flags |= IMAGE_F['ENCRYPTED']
David Brown23f91ad2017-05-16 11:38:17 -0600334
Mark Schultea66c6872018-09-26 17:24:40 -0700335 e = STRUCT_ENDIAN_DICT[self.endian]
336 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100337 # type ImageHdr struct {
338 'I' + # Magic uint32
339 'I' + # LoadAddr uint32
340 'H' + # HdrSz uint16
341 'H' + # PTLVSz uint16
342 'I' + # ImgSz uint32
343 'I' + # Flags uint32
344 'BBHI' + # Vers ImageVersion
345 'I' # Pad1 uint32
346 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600347 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
348 header = struct.pack(fmt,
349 IMAGE_MAGIC,
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000350 self.load_addr,
David Brown23f91ad2017-05-16 11:38:17 -0600351 self.header_size,
Fabio Utzig510fddb2019-09-12 12:15:36 -0300352 protected_tlv_size, # TLV Info header + Protected TLVs
353 len(self.payload) - self.header_size, # ImageSz
354 flags,
David Brown23f91ad2017-05-16 11:38:17 -0600355 self.version.major,
356 self.version.minor or 0,
357 self.version.revision or 0,
358 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100359 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600360 self.payload = bytearray(self.payload)
361 self.payload[:len(header)] = header
362
Fabio Utzig649d80f2019-09-12 10:26:23 -0300363 def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey):
Fabio Utzig519285f2018-06-04 11:11:53 -0300364 # NOTE: should already be checked by the argument parser
Fabio Utzig649d80f2019-09-12 10:26:23 -0300365 magic_size = 16
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700366 if overwrite_only:
Fabio Utzig649d80f2019-09-12 10:26:23 -0300367 return MAX_ALIGN * 2 + magic_size
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700368 else:
369 if write_size not in set([1, 2, 4, 8]):
370 raise Exception("Invalid alignment: {}".format(write_size))
371 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
Fabio Utzig649d80f2019-09-12 10:26:23 -0300372 trailer = m * 3 * write_size # status area
373 if enckey is not None:
374 trailer += 16 * 2 # encryption keys
Fabio Utzig88282802019-10-17 11:17:18 -0300375 trailer += MAX_ALIGN * 4 # image_ok/copy_done/swap_info/swap_size
Fabio Utzig649d80f2019-09-12 10:26:23 -0300376 trailer += magic_size
377 return trailer
Fabio Utzig519285f2018-06-04 11:11:53 -0300378
Fabio Utzig263d4392018-06-05 10:37:35 -0300379 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600380 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700381 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig649d80f2019-09-12 10:26:23 -0300382 self.overwrite_only, self.enckey)
David Brown23f91ad2017-05-16 11:38:17 -0600383 padding = size - (len(self.payload) + tsize)
Fabio Utzig9117fde2019-10-17 11:11:46 -0300384 pbytes = bytes([self.erased_val] * padding)
385 pbytes += bytes([self.erased_val] * (tsize - len(boot_magic)))
Fabio Utzige08f0872017-06-28 18:12:16 -0300386 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600387 self.payload += pbytes
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300388
389 @staticmethod
390 def verify(imgfile, key):
391 with open(imgfile, "rb") as f:
392 b = f.read()
393
394 magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
Marek Pietae9555102019-08-08 16:08:16 +0200395 version = struct.unpack('BBHI', b[20:28])
396
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300397 if magic != IMAGE_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200398 return VerifyResult.INVALID_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300399
400 tlv_info = b[header_size+img_size:header_size+img_size+TLV_INFO_SIZE]
401 magic, tlv_tot = struct.unpack('HH', tlv_info)
402 if magic != TLV_INFO_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200403 return VerifyResult.INVALID_TLV_INFO_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300404
405 sha = hashlib.sha256()
406 sha.update(b[:header_size+img_size])
407 digest = sha.digest()
408
409 tlv_off = header_size + img_size
410 tlv_end = tlv_off + tlv_tot
411 tlv_off += TLV_INFO_SIZE # skip tlv info
412 while tlv_off < tlv_end:
413 tlv = b[tlv_off:tlv_off+TLV_SIZE]
414 tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
415 if tlv_type == TLV_VALUES["SHA256"]:
416 off = tlv_off + TLV_SIZE
417 if digest == b[off:off+tlv_len]:
418 if key is None:
Marek Pietae9555102019-08-08 16:08:16 +0200419 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300420 else:
Marek Pietae9555102019-08-08 16:08:16 +0200421 return VerifyResult.INVALID_HASH, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300422 elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
423 off = tlv_off + TLV_SIZE
424 tlv_sig = b[off:off+tlv_len]
425 payload = b[:header_size+img_size]
426 try:
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300427 if hasattr(key, 'verify'):
428 key.verify(tlv_sig, payload)
429 else:
430 key.verify_digest(tlv_sig, digest)
Marek Pietae9555102019-08-08 16:08:16 +0200431 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300432 except InvalidSignature:
433 # continue to next TLV
434 pass
435 tlv_off += TLV_SIZE + tlv_len
Marek Pietae9555102019-08-08 16:08:16 +0200436 return VerifyResult.INVALID_SIGNATURE, None