blob: 94ed820a877fe065f568f0eb2eb849369c5afc5e [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 Utzig9a492d52020-01-15 11:31:52 -030022import click
Fabio Utzig4a5477a2019-05-27 15:45:08 -030023from enum import Enum
Carles Cufi37d052f2018-01-30 16:40:10 +010024from intelhex import IntelHex
David Brown23f91ad2017-05-16 11:38:17 -060025import hashlib
26import struct
Carles Cufi37d052f2018-01-30 16:40:10 +010027import os.path
Fabio Utzig7a3b2602019-10-22 09:56:44 -030028from .keys import rsa, ecdsa
29from cryptography.hazmat.primitives.asymmetric import ec, padding
Fabio Utzig06b77b82018-08-23 16:01:16 -030030from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Fabio Utzig7a3b2602019-10-22 09:56:44 -030031from cryptography.hazmat.primitives.kdf.hkdf import HKDF
32from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
Fabio Utzig06b77b82018-08-23 16:01:16 -030033from cryptography.hazmat.backends import default_backend
Fabio Utzig7a3b2602019-10-22 09:56:44 -030034from cryptography.hazmat.primitives import hashes, hmac
Fabio Utzig4a5477a2019-05-27 15:45:08 -030035from cryptography.exceptions import InvalidSignature
David Brown23f91ad2017-05-16 11:38:17 -060036
David Brown72e7a512017-09-01 11:08:23 -060037IMAGE_MAGIC = 0x96f3b83d
David Brown23f91ad2017-05-16 11:38:17 -060038IMAGE_HEADER_SIZE = 32
Carles Cufi37d052f2018-01-30 16:40:10 +010039BIN_EXT = "bin"
40INTEL_HEX_EXT = "hex"
Fabio Utzig519285f2018-06-04 11:11:53 -030041DEFAULT_MAX_SECTORS = 128
Fabio Utzig649d80f2019-09-12 10:26:23 -030042MAX_ALIGN = 8
David Vinczeda8c9192019-03-26 17:17:41 +010043DEP_IMAGES_KEY = "images"
44DEP_VERSIONS_KEY = "versions"
David Brown23f91ad2017-05-16 11:38:17 -060045
46# Image header flags.
47IMAGE_F = {
48 'PIC': 0x0000001,
Fabio Utzig06b77b82018-08-23 16:01:16 -030049 'NON_BOOTABLE': 0x0000010,
50 'ENCRYPTED': 0x0000004,
51}
David Brown23f91ad2017-05-16 11:38:17 -060052
53TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060054 'KEYHASH': 0x01,
David Brown27648b82017-08-31 10:40:29 -060055 'SHA256': 0x10,
56 'RSA2048': 0x20,
57 'ECDSA224': 0x21,
Fabio Utzig06b77b82018-08-23 16:01:16 -030058 'ECDSA256': 0x22,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030059 'RSA3072': 0x23,
Fabio Utzig8101d1f2019-05-09 15:03:22 -030060 'ED25519': 0x24,
Fabio Utzig06b77b82018-08-23 16:01:16 -030061 'ENCRSA2048': 0x30,
62 'ENCKW128': 0x31,
Fabio Utzig7a3b2602019-10-22 09:56:44 -030063 'ENCEC256': 0x32,
David Vinczeda8c9192019-03-26 17:17:41 +010064 'DEPENDENCY': 0x40
Fabio Utzig06b77b82018-08-23 16:01:16 -030065}
David Brown23f91ad2017-05-16 11:38:17 -060066
Fabio Utzig4a5477a2019-05-27 15:45:08 -030067TLV_SIZE = 4
David Brownf5b33d82017-09-01 10:58:27 -060068TLV_INFO_SIZE = 4
69TLV_INFO_MAGIC = 0x6907
Fabio Utzig510fddb2019-09-12 12:15:36 -030070TLV_PROT_INFO_MAGIC = 0x6908
David Brown23f91ad2017-05-16 11:38:17 -060071
David Brown23f91ad2017-05-16 11:38:17 -060072boot_magic = bytes([
73 0x77, 0xc2, 0x95, 0xf3,
74 0x60, 0xd2, 0xef, 0x7f,
75 0x35, 0x52, 0x50, 0x0f,
76 0x2c, 0xb6, 0x79, 0x80, ])
77
Mark Schultea66c6872018-09-26 17:24:40 -070078STRUCT_ENDIAN_DICT = {
79 'little': '<',
80 'big': '>'
81}
82
Fabio Utzig4a5477a2019-05-27 15:45:08 -030083VerifyResult = Enum('VerifyResult',
84 """
85 OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH
86 INVALID_SIGNATURE
87 """)
88
89
David Brown23f91ad2017-05-16 11:38:17 -060090class TLV():
Fabio Utzig510fddb2019-09-12 12:15:36 -030091 def __init__(self, endian, magic=TLV_INFO_MAGIC):
92 self.magic = magic
David Brown23f91ad2017-05-16 11:38:17 -060093 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -070094 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -060095
Fabio Utzig510fddb2019-09-12 12:15:36 -030096 def __len__(self):
97 return TLV_INFO_SIZE + len(self.buf)
98
David Brown23f91ad2017-05-16 11:38:17 -060099 def add(self, kind, payload):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300100 """
101 Add a TLV record. Kind should be a string found in TLV_VALUES above.
102 """
Mark Schultea66c6872018-09-26 17:24:40 -0700103 e = STRUCT_ENDIAN_DICT[self.endian]
104 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -0600105 self.buf += buf
106 self.buf += payload
107
108 def get(self):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300109 if len(self.buf) == 0:
110 return bytes()
Mark Schultea66c6872018-09-26 17:24:40 -0700111 e = STRUCT_ENDIAN_DICT[self.endian]
Fabio Utzig510fddb2019-09-12 12:15:36 -0300112 header = struct.pack(e + 'HH', self.magic, len(self))
David Brownf5b33d82017-09-01 10:58:27 -0600113 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -0600114
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200115
David Brown23f91ad2017-05-16 11:38:17 -0600116class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +0100117
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200118 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
119 pad_header=False, pad=False, align=1, slot_size=0,
120 max_sectors=DEFAULT_MAX_SECTORS, overwrite_only=False,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300121 endian="little", load_addr=0, erased_val=0xff,
122 save_enctlv=False):
David Brown23f91ad2017-05-16 11:38:17 -0600123 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200124 self.header_size = header_size
125 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -0600126 self.pad = pad
Fabio Utzig263d4392018-06-05 10:37:35 -0300127 self.align = align
128 self.slot_size = slot_size
129 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700130 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700131 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200132 self.base_addr = None
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000133 self.load_addr = 0 if load_addr is None else load_addr
Fabio Utzig9117fde2019-10-17 11:11:46 -0300134 self.erased_val = 0xff if erased_val is None else int(erased_val)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200135 self.payload = []
Fabio Utzig649d80f2019-09-12 10:26:23 -0300136 self.enckey = None
Fabio Utzig9a492d52020-01-15 11:31:52 -0300137 self.save_enctlv = save_enctlv
138 self.enctlv_len = 0
David Brown23f91ad2017-05-16 11:38:17 -0600139
140 def __repr__(self):
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000141 return "<Image version={}, header_size={}, base_addr={}, load_addr={}, \
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700142 align={}, slot_size={}, max_sectors={}, overwrite_only={}, \
Mark Schultea66c6872018-09-26 17:24:40 -0700143 endian={} format={}, payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300144 self.version,
145 self.header_size,
146 self.base_addr if self.base_addr is not None else "N/A",
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000147 self.load_addr,
Fabio Utzig263d4392018-06-05 10:37:35 -0300148 self.align,
149 self.slot_size,
150 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700151 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700152 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300153 self.__class__.__name__,
154 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600155
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200156 def load(self, path):
157 """Load an image from a given file"""
158 ext = os.path.splitext(path)[1][1:].lower()
159 if ext == INTEL_HEX_EXT:
160 ih = IntelHex(path)
161 self.payload = ih.tobinarray()
162 self.base_addr = ih.minaddr()
163 else:
164 with open(path, 'rb') as f:
165 self.payload = f.read()
166
167 # Add the image header if needed.
168 if self.pad_header and self.header_size > 0:
169 if self.base_addr:
170 # Adjust base_addr for new header
171 self.base_addr -= self.header_size
Fabio Utzig9117fde2019-10-17 11:11:46 -0300172 self.payload = bytes([self.erased_val] * self.header_size) + \
173 self.payload
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200174
Fabio Utzig9a492d52020-01-15 11:31:52 -0300175 self.check_header()
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200176
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300177 def save(self, path, hex_addr=None):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200178 """Save an image from a given file"""
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200179 ext = os.path.splitext(path)[1][1:].lower()
180 if ext == INTEL_HEX_EXT:
181 # input was in binary format, but HEX needs to know the base addr
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300182 if self.base_addr is None and hex_addr is None:
183 raise Exception("No address exists in input file neither was "
184 "it provided by user")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200185 h = IntelHex()
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300186 if hex_addr is not None:
187 self.base_addr = hex_addr
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200188 h.frombytes(bytes=self.payload, offset=self.base_addr)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300189 if self.pad:
Fabio Utzig2269f472019-10-17 11:14:33 -0300190 trailer_size = self._trailer_size(self.align, self.max_sectors,
191 self.overwrite_only,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300192 self.enckey,
193 self.save_enctlv,
194 self.enctlv_len)
Fabio Utzig2269f472019-10-17 11:14:33 -0300195 trailer_addr = (self.base_addr + self.slot_size) - trailer_size
196 padding = bytes([self.erased_val] *
197 (trailer_size - len(boot_magic))) + boot_magic
198 h.puts(trailer_addr, padding)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200199 h.tofile(path, 'hex')
200 else:
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300201 if self.pad:
202 self.pad_to(self.slot_size)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200203 with open(path, 'wb') as f:
204 f.write(self.payload)
205
Fabio Utzig9a492d52020-01-15 11:31:52 -0300206 def check_header(self):
Fabio Utzigf5556c32019-10-23 11:00:27 -0300207 if self.header_size > 0 and not self.pad_header:
David Brown23f91ad2017-05-16 11:38:17 -0600208 if any(v != 0 for v in self.payload[0:self.header_size]):
Fabio Utzig9a492d52020-01-15 11:31:52 -0300209 raise click.UsageError("Header padding was not requested and "
210 "image does not start with zeros")
211
212 def check_trailer(self):
Fabio Utzig263d4392018-06-05 10:37:35 -0300213 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700214 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300215 self.overwrite_only, self.enckey,
216 self.save_enctlv, self.enctlv_len)
Fabio Utzig263d4392018-06-05 10:37:35 -0300217 padding = self.slot_size - (len(self.payload) + tsize)
218 if padding < 0:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300219 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds " \
220 "requested size 0x{:x}".format(
221 len(self.payload), tsize, self.slot_size)
222 raise click.UsageError(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600223
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300224 def ecies_p256_hkdf(self, enckey, plainkey):
225 newpk = ec.generate_private_key(ec.SECP256R1(), default_backend())
226 shared = newpk.exchange(ec.ECDH(), enckey._get_public())
227 derived_key = HKDF(
228 algorithm=hashes.SHA256(), length=48, salt=None,
229 info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared)
230 encryptor = Cipher(algorithms.AES(derived_key[:16]),
231 modes.CTR(bytes([0] * 16)),
232 backend=default_backend()).encryptor()
233 cipherkey = encryptor.update(plainkey) + encryptor.finalize()
234 mac = hmac.HMAC(derived_key[16:], hashes.SHA256(),
235 backend=default_backend())
236 mac.update(cipherkey)
237 ciphermac = mac.finalize()
238 pubk = newpk.public_key().public_bytes(
239 encoding=Encoding.X962,
240 format=PublicFormat.UncompressedPoint)
241 return cipherkey, ciphermac, pubk
242
David Vinczeda8c9192019-03-26 17:17:41 +0100243 def create(self, key, enckey, dependencies=None):
Fabio Utzig649d80f2019-09-12 10:26:23 -0300244 self.enckey = enckey
245
David Vinczeda8c9192019-03-26 17:17:41 +0100246 if dependencies is None:
247 dependencies_num = 0
248 protected_tlv_size = 0
249 else:
250 # Size of a Dependency TLV = Header ('BBH') + Payload('IBBHI')
251 # = 16 Bytes
252 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
253 protected_tlv_size = (dependencies_num * 16) + TLV_INFO_SIZE
254
Fabio Utzig510fddb2019-09-12 12:15:36 -0300255 # At this point the image is already on the payload, this adds
256 # the header to the payload as well
David Vinczeda8c9192019-03-26 17:17:41 +0100257 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600258
Fabio Utzig510fddb2019-09-12 12:15:36 -0300259 prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC)
David Brown23f91ad2017-05-16 11:38:17 -0600260
Fabio Utzig510fddb2019-09-12 12:15:36 -0300261 # Protected TLVs must be added first, because they are also included
262 # in the hash calculation
263 protected_tlv_off = None
David Vinczeda8c9192019-03-26 17:17:41 +0100264 if protected_tlv_size != 0:
265 for i in range(dependencies_num):
266 e = STRUCT_ENDIAN_DICT[self.endian]
267 payload = struct.pack(
David Brownbd7925e2019-07-29 11:11:32 -0600268 e + 'B3x'+'BBHI',
David Vinczeda8c9192019-03-26 17:17:41 +0100269 int(dependencies[DEP_IMAGES_KEY][i]),
270 dependencies[DEP_VERSIONS_KEY][i].major,
271 dependencies[DEP_VERSIONS_KEY][i].minor,
272 dependencies[DEP_VERSIONS_KEY][i].revision,
273 dependencies[DEP_VERSIONS_KEY][i].build
274 )
Fabio Utzig510fddb2019-09-12 12:15:36 -0300275 prot_tlv.add('DEPENDENCY', payload)
David Vinczeda8c9192019-03-26 17:17:41 +0100276
Fabio Utzig510fddb2019-09-12 12:15:36 -0300277 protected_tlv_off = len(self.payload)
278 self.payload += prot_tlv.get()
279
280 tlv = TLV(self.endian)
David Vinczeda8c9192019-03-26 17:17:41 +0100281
David Brown23f91ad2017-05-16 11:38:17 -0600282 # Note that ecdsa wants to do the hashing itself, which means
283 # we get to hash it twice.
284 sha = hashlib.sha256()
285 sha.update(self.payload)
286 digest = sha.digest()
287
288 tlv.add('SHA256', digest)
289
David Brown0f0c6a82017-06-08 09:26:24 -0600290 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600291 pub = key.get_public_bytes()
292 sha = hashlib.sha256()
293 sha.update(pub)
294 pubbytes = sha.digest()
295 tlv.add('KEYHASH', pubbytes)
296
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300297 # `sign` expects the full image payload (sha256 done internally),
298 # while `sign_digest` expects only the digest of the payload
299
300 if hasattr(key, 'sign'):
301 sig = key.sign(bytes(self.payload))
302 else:
303 sig = key.sign_digest(digest)
David Brown0f0c6a82017-06-08 09:26:24 -0600304 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600305
Fabio Utzig510fddb2019-09-12 12:15:36 -0300306 # At this point the image was hashed + signed, we can remove the
307 # protected TLVs from the payload (will be re-added later)
308 if protected_tlv_off is not None:
309 self.payload = self.payload[:protected_tlv_off]
310
Fabio Utzig06b77b82018-08-23 16:01:16 -0300311 if enckey is not None:
312 plainkey = os.urandom(16)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300313
314 if isinstance(enckey, rsa.RSAPublic):
315 cipherkey = enckey._get_public().encrypt(
316 plainkey, padding.OAEP(
317 mgf=padding.MGF1(algorithm=hashes.SHA256()),
318 algorithm=hashes.SHA256(),
319 label=None))
Fabio Utzig9a492d52020-01-15 11:31:52 -0300320 self.enctlv_len = len(cipherkey)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300321 tlv.add('ENCRSA2048', cipherkey)
322 elif isinstance(enckey, ecdsa.ECDSA256P1Public):
323 cipherkey, mac, pubk = self.ecies_p256_hkdf(enckey, plainkey)
Fabio Utzig9a492d52020-01-15 11:31:52 -0300324 enctlv = pubk + mac + cipherkey
325 self.enctlv_len = len(enctlv)
326 tlv.add('ENCEC256', enctlv)
Fabio Utzig06b77b82018-08-23 16:01:16 -0300327
328 nonce = bytes([0] * 16)
329 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
330 backend=default_backend())
331 encryptor = cipher.encryptor()
332 img = bytes(self.payload[self.header_size:])
Fabio Utzig510fddb2019-09-12 12:15:36 -0300333 self.payload[self.header_size:] = \
334 encryptor.update(img) + encryptor.finalize()
Fabio Utzig06b77b82018-08-23 16:01:16 -0300335
Fabio Utzig510fddb2019-09-12 12:15:36 -0300336 self.payload += prot_tlv.get()
337 self.payload += tlv.get()
David Brown23f91ad2017-05-16 11:38:17 -0600338
Fabio Utzig9a492d52020-01-15 11:31:52 -0300339 self.check_trailer()
340
David Vinczeda8c9192019-03-26 17:17:41 +0100341 def add_header(self, enckey, protected_tlv_size):
Fabio Utzigcd284062018-11-30 11:05:45 -0200342 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600343
David Brown0f0c6a82017-06-08 09:26:24 -0600344 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300345 if enckey is not None:
346 flags |= IMAGE_F['ENCRYPTED']
David Brown23f91ad2017-05-16 11:38:17 -0600347
Mark Schultea66c6872018-09-26 17:24:40 -0700348 e = STRUCT_ENDIAN_DICT[self.endian]
349 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100350 # type ImageHdr struct {
351 'I' + # Magic uint32
352 'I' + # LoadAddr uint32
353 'H' + # HdrSz uint16
354 'H' + # PTLVSz uint16
355 'I' + # ImgSz uint32
356 'I' + # Flags uint32
357 'BBHI' + # Vers ImageVersion
358 'I' # Pad1 uint32
359 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600360 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
361 header = struct.pack(fmt,
362 IMAGE_MAGIC,
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000363 self.load_addr,
David Brown23f91ad2017-05-16 11:38:17 -0600364 self.header_size,
Fabio Utzig510fddb2019-09-12 12:15:36 -0300365 protected_tlv_size, # TLV Info header + Protected TLVs
366 len(self.payload) - self.header_size, # ImageSz
367 flags,
David Brown23f91ad2017-05-16 11:38:17 -0600368 self.version.major,
369 self.version.minor or 0,
370 self.version.revision or 0,
371 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100372 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600373 self.payload = bytearray(self.payload)
374 self.payload[:len(header)] = header
375
Fabio Utzig9a492d52020-01-15 11:31:52 -0300376 def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey,
377 save_enctlv, enctlv_len):
Fabio Utzig519285f2018-06-04 11:11:53 -0300378 # NOTE: should already be checked by the argument parser
Fabio Utzig649d80f2019-09-12 10:26:23 -0300379 magic_size = 16
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700380 if overwrite_only:
Fabio Utzig649d80f2019-09-12 10:26:23 -0300381 return MAX_ALIGN * 2 + magic_size
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700382 else:
383 if write_size not in set([1, 2, 4, 8]):
384 raise Exception("Invalid alignment: {}".format(write_size))
385 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
Fabio Utzig649d80f2019-09-12 10:26:23 -0300386 trailer = m * 3 * write_size # status area
387 if enckey is not None:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300388 if save_enctlv:
389 # TLV saved by the bootloader is aligned
390 keylen = (int((enctlv_len - 1) / MAX_ALIGN) + 1) * MAX_ALIGN
391 else:
392 keylen = 16
393 trailer += keylen * 2 # encryption keys
Fabio Utzig88282802019-10-17 11:17:18 -0300394 trailer += MAX_ALIGN * 4 # image_ok/copy_done/swap_info/swap_size
Fabio Utzig649d80f2019-09-12 10:26:23 -0300395 trailer += magic_size
396 return trailer
Fabio Utzig519285f2018-06-04 11:11:53 -0300397
Fabio Utzig263d4392018-06-05 10:37:35 -0300398 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600399 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700400 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300401 self.overwrite_only, self.enckey,
402 self.save_enctlv, self.enctlv_len)
David Brown23f91ad2017-05-16 11:38:17 -0600403 padding = size - (len(self.payload) + tsize)
Fabio Utzig9117fde2019-10-17 11:11:46 -0300404 pbytes = bytes([self.erased_val] * padding)
405 pbytes += bytes([self.erased_val] * (tsize - len(boot_magic)))
Fabio Utzige08f0872017-06-28 18:12:16 -0300406 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600407 self.payload += pbytes
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300408
409 @staticmethod
410 def verify(imgfile, key):
411 with open(imgfile, "rb") as f:
412 b = f.read()
413
414 magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
Marek Pietae9555102019-08-08 16:08:16 +0200415 version = struct.unpack('BBHI', b[20:28])
416
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300417 if magic != IMAGE_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200418 return VerifyResult.INVALID_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300419
420 tlv_info = b[header_size+img_size:header_size+img_size+TLV_INFO_SIZE]
421 magic, tlv_tot = struct.unpack('HH', tlv_info)
422 if magic != TLV_INFO_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200423 return VerifyResult.INVALID_TLV_INFO_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300424
425 sha = hashlib.sha256()
426 sha.update(b[:header_size+img_size])
427 digest = sha.digest()
428
429 tlv_off = header_size + img_size
430 tlv_end = tlv_off + tlv_tot
431 tlv_off += TLV_INFO_SIZE # skip tlv info
432 while tlv_off < tlv_end:
433 tlv = b[tlv_off:tlv_off+TLV_SIZE]
434 tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
435 if tlv_type == TLV_VALUES["SHA256"]:
436 off = tlv_off + TLV_SIZE
437 if digest == b[off:off+tlv_len]:
438 if key is None:
Marek Pietae9555102019-08-08 16:08:16 +0200439 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300440 else:
Marek Pietae9555102019-08-08 16:08:16 +0200441 return VerifyResult.INVALID_HASH, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300442 elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
443 off = tlv_off + TLV_SIZE
444 tlv_sig = b[off:off+tlv_len]
445 payload = b[:header_size+img_size]
446 try:
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300447 if hasattr(key, 'verify'):
448 key.verify(tlv_sig, payload)
449 else:
450 key.verify_digest(tlv_sig, digest)
Marek Pietae9555102019-08-08 16:08:16 +0200451 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300452 except InvalidSignature:
453 # continue to next TLV
454 pass
455 tlv_off += TLV_SIZE + tlv_len
Marek Pietae9555102019-08-08 16:08:16 +0200456 return VerifyResult.INVALID_SIGNATURE, None