blob: 9701e211827d94aa823795e0dc850b03057b4f15 [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 Vincze1a7a6902020-02-18 15:05:16 +01003# Copyright 2019-2020 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 Vincze1a7a6902020-02-18 15:05:16 +010064 'DEPENDENCY': 0x40,
65 'SEC_CNT': 0x50,
Fabio Utzig06b77b82018-08-23 16:01:16 -030066}
David Brown23f91ad2017-05-16 11:38:17 -060067
Fabio Utzig4a5477a2019-05-27 15:45:08 -030068TLV_SIZE = 4
David Brownf5b33d82017-09-01 10:58:27 -060069TLV_INFO_SIZE = 4
70TLV_INFO_MAGIC = 0x6907
Fabio Utzig510fddb2019-09-12 12:15:36 -030071TLV_PROT_INFO_MAGIC = 0x6908
David Brown23f91ad2017-05-16 11:38:17 -060072
David Brown23f91ad2017-05-16 11:38:17 -060073boot_magic = bytes([
74 0x77, 0xc2, 0x95, 0xf3,
75 0x60, 0xd2, 0xef, 0x7f,
76 0x35, 0x52, 0x50, 0x0f,
77 0x2c, 0xb6, 0x79, 0x80, ])
78
Mark Schultea66c6872018-09-26 17:24:40 -070079STRUCT_ENDIAN_DICT = {
80 'little': '<',
81 'big': '>'
82}
83
Fabio Utzig4a5477a2019-05-27 15:45:08 -030084VerifyResult = Enum('VerifyResult',
85 """
86 OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH
87 INVALID_SIGNATURE
88 """)
89
90
David Brown23f91ad2017-05-16 11:38:17 -060091class TLV():
Fabio Utzig510fddb2019-09-12 12:15:36 -030092 def __init__(self, endian, magic=TLV_INFO_MAGIC):
93 self.magic = magic
David Brown23f91ad2017-05-16 11:38:17 -060094 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -070095 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -060096
Fabio Utzig510fddb2019-09-12 12:15:36 -030097 def __len__(self):
98 return TLV_INFO_SIZE + len(self.buf)
99
David Brown23f91ad2017-05-16 11:38:17 -0600100 def add(self, kind, payload):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300101 """
102 Add a TLV record. Kind should be a string found in TLV_VALUES above.
103 """
Mark Schultea66c6872018-09-26 17:24:40 -0700104 e = STRUCT_ENDIAN_DICT[self.endian]
105 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -0600106 self.buf += buf
107 self.buf += payload
108
109 def get(self):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300110 if len(self.buf) == 0:
111 return bytes()
Mark Schultea66c6872018-09-26 17:24:40 -0700112 e = STRUCT_ENDIAN_DICT[self.endian]
Fabio Utzig510fddb2019-09-12 12:15:36 -0300113 header = struct.pack(e + 'HH', self.magic, len(self))
David Brownf5b33d82017-09-01 10:58:27 -0600114 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -0600115
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200116
David Brown23f91ad2017-05-16 11:38:17 -0600117class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +0100118
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200119 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100120 pad_header=False, pad=False, confirm=False, align=1,
121 slot_size=0, max_sectors=DEFAULT_MAX_SECTORS,
122 overwrite_only=False, endian="little", load_addr=0,
123 erased_val=None, save_enctlv=False, security_counter=None):
David Brown23f91ad2017-05-16 11:38:17 -0600124 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200125 self.header_size = header_size
126 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -0600127 self.pad = pad
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100128 self.confirm = confirm
Fabio Utzig263d4392018-06-05 10:37:35 -0300129 self.align = align
130 self.slot_size = slot_size
131 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700132 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700133 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200134 self.base_addr = None
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000135 self.load_addr = 0 if load_addr is None else load_addr
Fabio Utzigcb080732020-02-07 12:01:39 -0300136 self.erased_val = 0xff if erased_val is None else int(erased_val, 0)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200137 self.payload = []
Fabio Utzig649d80f2019-09-12 10:26:23 -0300138 self.enckey = None
Fabio Utzig9a492d52020-01-15 11:31:52 -0300139 self.save_enctlv = save_enctlv
140 self.enctlv_len = 0
David Brown23f91ad2017-05-16 11:38:17 -0600141
David Vincze1a7a6902020-02-18 15:05:16 +0100142 if security_counter == 'auto':
143 # Security counter has not been explicitly provided,
144 # generate it from the version number
145 self.security_counter = ((self.version.major << 24)
146 + (self.version.minor << 16)
147 + self.version.revision)
148 else:
149 self.security_counter = security_counter
150
David Brown23f91ad2017-05-16 11:38:17 -0600151 def __repr__(self):
David Vincze1a7a6902020-02-18 15:05:16 +0100152 return "<Image version={}, header_size={}, security_counter={}, \
153 base_addr={}, load_addr={}, align={}, slot_size={}, \
154 max_sectors={}, overwrite_only={}, endian={} format={}, \
155 payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300156 self.version,
157 self.header_size,
David Vincze1a7a6902020-02-18 15:05:16 +0100158 self.security_counter,
Fabio Utzig263d4392018-06-05 10:37:35 -0300159 self.base_addr if self.base_addr is not None else "N/A",
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000160 self.load_addr,
Fabio Utzig263d4392018-06-05 10:37:35 -0300161 self.align,
162 self.slot_size,
163 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700164 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700165 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300166 self.__class__.__name__,
167 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600168
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200169 def load(self, path):
170 """Load an image from a given file"""
171 ext = os.path.splitext(path)[1][1:].lower()
Fabio Utzig1f508922020-01-15 11:37:51 -0300172 try:
173 if ext == INTEL_HEX_EXT:
174 ih = IntelHex(path)
175 self.payload = ih.tobinarray()
176 self.base_addr = ih.minaddr()
177 else:
178 with open(path, 'rb') as f:
179 self.payload = f.read()
180 except FileNotFoundError:
181 raise click.UsageError("Input file not found")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200182
183 # Add the image header if needed.
184 if self.pad_header and self.header_size > 0:
185 if self.base_addr:
186 # Adjust base_addr for new header
187 self.base_addr -= self.header_size
Fabio Utzig9117fde2019-10-17 11:11:46 -0300188 self.payload = bytes([self.erased_val] * self.header_size) + \
189 self.payload
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200190
Fabio Utzig9a492d52020-01-15 11:31:52 -0300191 self.check_header()
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200192
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300193 def save(self, path, hex_addr=None):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200194 """Save an image from a given file"""
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200195 ext = os.path.splitext(path)[1][1:].lower()
196 if ext == INTEL_HEX_EXT:
197 # input was in binary format, but HEX needs to know the base addr
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300198 if self.base_addr is None and hex_addr is None:
Fabio Utzig1f508922020-01-15 11:37:51 -0300199 raise click.UsageError("No address exists in input file "
200 "neither was it provided by user")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200201 h = IntelHex()
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300202 if hex_addr is not None:
203 self.base_addr = hex_addr
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200204 h.frombytes(bytes=self.payload, offset=self.base_addr)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300205 if self.pad:
Fabio Utzig2269f472019-10-17 11:14:33 -0300206 trailer_size = self._trailer_size(self.align, self.max_sectors,
207 self.overwrite_only,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300208 self.enckey,
209 self.save_enctlv,
210 self.enctlv_len)
Fabio Utzig2269f472019-10-17 11:14:33 -0300211 trailer_addr = (self.base_addr + self.slot_size) - trailer_size
212 padding = bytes([self.erased_val] *
213 (trailer_size - len(boot_magic))) + boot_magic
214 h.puts(trailer_addr, padding)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200215 h.tofile(path, 'hex')
216 else:
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300217 if self.pad:
218 self.pad_to(self.slot_size)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200219 with open(path, 'wb') as f:
220 f.write(self.payload)
221
Fabio Utzig9a492d52020-01-15 11:31:52 -0300222 def check_header(self):
Fabio Utzigf5556c32019-10-23 11:00:27 -0300223 if self.header_size > 0 and not self.pad_header:
David Brown23f91ad2017-05-16 11:38:17 -0600224 if any(v != 0 for v in self.payload[0:self.header_size]):
Fabio Utzig9a492d52020-01-15 11:31:52 -0300225 raise click.UsageError("Header padding was not requested and "
226 "image does not start with zeros")
227
228 def check_trailer(self):
Fabio Utzig263d4392018-06-05 10:37:35 -0300229 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700230 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300231 self.overwrite_only, self.enckey,
232 self.save_enctlv, self.enctlv_len)
Fabio Utzig263d4392018-06-05 10:37:35 -0300233 padding = self.slot_size - (len(self.payload) + tsize)
234 if padding < 0:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300235 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds " \
236 "requested size 0x{:x}".format(
237 len(self.payload), tsize, self.slot_size)
238 raise click.UsageError(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600239
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300240 def ecies_p256_hkdf(self, enckey, plainkey):
241 newpk = ec.generate_private_key(ec.SECP256R1(), default_backend())
242 shared = newpk.exchange(ec.ECDH(), enckey._get_public())
243 derived_key = HKDF(
244 algorithm=hashes.SHA256(), length=48, salt=None,
245 info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared)
246 encryptor = Cipher(algorithms.AES(derived_key[:16]),
247 modes.CTR(bytes([0] * 16)),
248 backend=default_backend()).encryptor()
249 cipherkey = encryptor.update(plainkey) + encryptor.finalize()
250 mac = hmac.HMAC(derived_key[16:], hashes.SHA256(),
251 backend=default_backend())
252 mac.update(cipherkey)
253 ciphermac = mac.finalize()
254 pubk = newpk.public_key().public_bytes(
255 encoding=Encoding.X962,
256 format=PublicFormat.UncompressedPoint)
257 return cipherkey, ciphermac, pubk
258
David Vinczeda8c9192019-03-26 17:17:41 +0100259 def create(self, key, enckey, dependencies=None):
Fabio Utzig649d80f2019-09-12 10:26:23 -0300260 self.enckey = enckey
261
David Vincze1a7a6902020-02-18 15:05:16 +0100262 protected_tlv_size = 0
263
264 if self.security_counter is not None:
265 # Size of the security counter TLV: header ('HH') + payload ('I')
266 # = 4 + 4 = 8 Bytes
267 protected_tlv_size += TLV_SIZE + 4
268
269 if dependencies is not None:
270 # Size of a Dependency TLV = Header ('HH') + Payload('IBBHI')
271 # = 4 + 12 = 16 Bytes
David Vinczeda8c9192019-03-26 17:17:41 +0100272 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
David Vincze1a7a6902020-02-18 15:05:16 +0100273 protected_tlv_size += (dependencies_num * 16)
274
275 if protected_tlv_size != 0:
276 # Add the size of the TLV info header
277 protected_tlv_size += TLV_INFO_SIZE
David Vinczeda8c9192019-03-26 17:17:41 +0100278
Fabio Utzig510fddb2019-09-12 12:15:36 -0300279 # At this point the image is already on the payload, this adds
280 # the header to the payload as well
David Vinczeda8c9192019-03-26 17:17:41 +0100281 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600282
Fabio Utzig510fddb2019-09-12 12:15:36 -0300283 prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC)
David Brown23f91ad2017-05-16 11:38:17 -0600284
Fabio Utzig510fddb2019-09-12 12:15:36 -0300285 # Protected TLVs must be added first, because they are also included
286 # in the hash calculation
287 protected_tlv_off = None
David Vinczeda8c9192019-03-26 17:17:41 +0100288 if protected_tlv_size != 0:
David Vincze1a7a6902020-02-18 15:05:16 +0100289
290 e = STRUCT_ENDIAN_DICT[self.endian]
291
292 if self.security_counter is not None:
293 payload = struct.pack(e + 'I', self.security_counter)
294 prot_tlv.add('SEC_CNT', payload)
295
296 if dependencies is not None:
297 for i in range(dependencies_num):
298 payload = struct.pack(
299 e + 'B3x'+'BBHI',
300 int(dependencies[DEP_IMAGES_KEY][i]),
301 dependencies[DEP_VERSIONS_KEY][i].major,
302 dependencies[DEP_VERSIONS_KEY][i].minor,
303 dependencies[DEP_VERSIONS_KEY][i].revision,
304 dependencies[DEP_VERSIONS_KEY][i].build
305 )
306 prot_tlv.add('DEPENDENCY', payload)
David Vinczeda8c9192019-03-26 17:17:41 +0100307
Fabio Utzig510fddb2019-09-12 12:15:36 -0300308 protected_tlv_off = len(self.payload)
309 self.payload += prot_tlv.get()
310
311 tlv = TLV(self.endian)
David Vinczeda8c9192019-03-26 17:17:41 +0100312
David Brown23f91ad2017-05-16 11:38:17 -0600313 # Note that ecdsa wants to do the hashing itself, which means
314 # we get to hash it twice.
315 sha = hashlib.sha256()
316 sha.update(self.payload)
317 digest = sha.digest()
318
319 tlv.add('SHA256', digest)
320
David Brown0f0c6a82017-06-08 09:26:24 -0600321 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600322 pub = key.get_public_bytes()
323 sha = hashlib.sha256()
324 sha.update(pub)
325 pubbytes = sha.digest()
326 tlv.add('KEYHASH', pubbytes)
327
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300328 # `sign` expects the full image payload (sha256 done internally),
329 # while `sign_digest` expects only the digest of the payload
330
331 if hasattr(key, 'sign'):
332 sig = key.sign(bytes(self.payload))
333 else:
334 sig = key.sign_digest(digest)
David Brown0f0c6a82017-06-08 09:26:24 -0600335 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600336
Fabio Utzig510fddb2019-09-12 12:15:36 -0300337 # At this point the image was hashed + signed, we can remove the
338 # protected TLVs from the payload (will be re-added later)
339 if protected_tlv_off is not None:
340 self.payload = self.payload[:protected_tlv_off]
341
Fabio Utzig06b77b82018-08-23 16:01:16 -0300342 if enckey is not None:
343 plainkey = os.urandom(16)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300344
345 if isinstance(enckey, rsa.RSAPublic):
346 cipherkey = enckey._get_public().encrypt(
347 plainkey, padding.OAEP(
348 mgf=padding.MGF1(algorithm=hashes.SHA256()),
349 algorithm=hashes.SHA256(),
350 label=None))
Fabio Utzig9a492d52020-01-15 11:31:52 -0300351 self.enctlv_len = len(cipherkey)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300352 tlv.add('ENCRSA2048', cipherkey)
353 elif isinstance(enckey, ecdsa.ECDSA256P1Public):
354 cipherkey, mac, pubk = self.ecies_p256_hkdf(enckey, plainkey)
Fabio Utzig9a492d52020-01-15 11:31:52 -0300355 enctlv = pubk + mac + cipherkey
356 self.enctlv_len = len(enctlv)
357 tlv.add('ENCEC256', enctlv)
Fabio Utzig06b77b82018-08-23 16:01:16 -0300358
359 nonce = bytes([0] * 16)
360 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
361 backend=default_backend())
362 encryptor = cipher.encryptor()
363 img = bytes(self.payload[self.header_size:])
Fabio Utzig510fddb2019-09-12 12:15:36 -0300364 self.payload[self.header_size:] = \
365 encryptor.update(img) + encryptor.finalize()
Fabio Utzig06b77b82018-08-23 16:01:16 -0300366
Fabio Utzig510fddb2019-09-12 12:15:36 -0300367 self.payload += prot_tlv.get()
368 self.payload += tlv.get()
David Brown23f91ad2017-05-16 11:38:17 -0600369
Fabio Utzig9a492d52020-01-15 11:31:52 -0300370 self.check_trailer()
371
David Vinczeda8c9192019-03-26 17:17:41 +0100372 def add_header(self, enckey, protected_tlv_size):
Fabio Utzigcd284062018-11-30 11:05:45 -0200373 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600374
David Brown0f0c6a82017-06-08 09:26:24 -0600375 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300376 if enckey is not None:
377 flags |= IMAGE_F['ENCRYPTED']
David Brown23f91ad2017-05-16 11:38:17 -0600378
Mark Schultea66c6872018-09-26 17:24:40 -0700379 e = STRUCT_ENDIAN_DICT[self.endian]
380 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100381 # type ImageHdr struct {
382 'I' + # Magic uint32
383 'I' + # LoadAddr uint32
384 'H' + # HdrSz uint16
385 'H' + # PTLVSz uint16
386 'I' + # ImgSz uint32
387 'I' + # Flags uint32
388 'BBHI' + # Vers ImageVersion
389 'I' # Pad1 uint32
390 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600391 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
392 header = struct.pack(fmt,
393 IMAGE_MAGIC,
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000394 self.load_addr,
David Brown23f91ad2017-05-16 11:38:17 -0600395 self.header_size,
Fabio Utzig510fddb2019-09-12 12:15:36 -0300396 protected_tlv_size, # TLV Info header + Protected TLVs
397 len(self.payload) - self.header_size, # ImageSz
398 flags,
David Brown23f91ad2017-05-16 11:38:17 -0600399 self.version.major,
400 self.version.minor or 0,
401 self.version.revision or 0,
402 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100403 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600404 self.payload = bytearray(self.payload)
405 self.payload[:len(header)] = header
406
Fabio Utzig9a492d52020-01-15 11:31:52 -0300407 def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey,
408 save_enctlv, enctlv_len):
Fabio Utzig519285f2018-06-04 11:11:53 -0300409 # NOTE: should already be checked by the argument parser
Fabio Utzig649d80f2019-09-12 10:26:23 -0300410 magic_size = 16
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700411 if overwrite_only:
Fabio Utzig649d80f2019-09-12 10:26:23 -0300412 return MAX_ALIGN * 2 + magic_size
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700413 else:
414 if write_size not in set([1, 2, 4, 8]):
Fabio Utzig1f508922020-01-15 11:37:51 -0300415 raise click.BadParameter("Invalid alignment: {}".format(
416 write_size))
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700417 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
Fabio Utzig649d80f2019-09-12 10:26:23 -0300418 trailer = m * 3 * write_size # status area
419 if enckey is not None:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300420 if save_enctlv:
421 # TLV saved by the bootloader is aligned
422 keylen = (int((enctlv_len - 1) / MAX_ALIGN) + 1) * MAX_ALIGN
423 else:
424 keylen = 16
425 trailer += keylen * 2 # encryption keys
Fabio Utzig88282802019-10-17 11:17:18 -0300426 trailer += MAX_ALIGN * 4 # image_ok/copy_done/swap_info/swap_size
Fabio Utzig649d80f2019-09-12 10:26:23 -0300427 trailer += magic_size
428 return trailer
Fabio Utzig519285f2018-06-04 11:11:53 -0300429
Fabio Utzig263d4392018-06-05 10:37:35 -0300430 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600431 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700432 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300433 self.overwrite_only, self.enckey,
434 self.save_enctlv, self.enctlv_len)
David Brown23f91ad2017-05-16 11:38:17 -0600435 padding = size - (len(self.payload) + tsize)
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100436 pbytes = bytearray([self.erased_val] * padding)
437 pbytes += bytearray([self.erased_val] * (tsize - len(boot_magic)))
438 if self.confirm and not self.overwrite_only:
439 pbytes[-MAX_ALIGN] = 0x01 # image_ok = 0x01
Fabio Utzige08f0872017-06-28 18:12:16 -0300440 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600441 self.payload += pbytes
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300442
443 @staticmethod
444 def verify(imgfile, key):
445 with open(imgfile, "rb") as f:
446 b = f.read()
447
448 magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
Marek Pietae9555102019-08-08 16:08:16 +0200449 version = struct.unpack('BBHI', b[20:28])
450
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300451 if magic != IMAGE_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200452 return VerifyResult.INVALID_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300453
454 tlv_info = b[header_size+img_size:header_size+img_size+TLV_INFO_SIZE]
455 magic, tlv_tot = struct.unpack('HH', tlv_info)
456 if magic != TLV_INFO_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200457 return VerifyResult.INVALID_TLV_INFO_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300458
459 sha = hashlib.sha256()
460 sha.update(b[:header_size+img_size])
461 digest = sha.digest()
462
463 tlv_off = header_size + img_size
464 tlv_end = tlv_off + tlv_tot
465 tlv_off += TLV_INFO_SIZE # skip tlv info
466 while tlv_off < tlv_end:
467 tlv = b[tlv_off:tlv_off+TLV_SIZE]
468 tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
469 if tlv_type == TLV_VALUES["SHA256"]:
470 off = tlv_off + TLV_SIZE
471 if digest == b[off:off+tlv_len]:
472 if key is None:
Marek Pietae9555102019-08-08 16:08:16 +0200473 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300474 else:
Marek Pietae9555102019-08-08 16:08:16 +0200475 return VerifyResult.INVALID_HASH, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300476 elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
477 off = tlv_off + TLV_SIZE
478 tlv_sig = b[off:off+tlv_len]
479 payload = b[:header_size+img_size]
480 try:
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300481 if hasattr(key, 'verify'):
482 key.verify(tlv_sig, payload)
483 else:
484 key.verify_digest(tlv_sig, digest)
Marek Pietae9555102019-08-08 16:08:16 +0200485 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300486 except InvalidSignature:
487 # continue to next TLV
488 pass
489 tlv_off += TLV_SIZE + tlv_len
Marek Pietae9555102019-08-08 16:08:16 +0200490 return VerifyResult.INVALID_SIGNATURE, None