blob: 257c89256b2ddb0978c6a7a091c4d9a48437218f [file] [log] [blame]
Carles Cufi37d052f2018-01-30 16:40:10 +01001# Copyright 2018 Nordic Semiconductor ASA
David Vinczeb2a1a482020-09-18 11:54:30 +02002# Copyright 2017-2020 Linaro Limited
David Vincze1a7a6902020-02-18 15:05:16 +01003# Copyright 2019-2020 Arm Limited
David Brown1314bf32017-12-20 11:10:55 -07004#
David Brown79c4fcf2021-01-26 15:04:05 -07005# SPDX-License-Identifier: Apache-2.0
6#
David Brown1314bf32017-12-20 11:10:55 -07007# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18
David Brown23f91ad2017-05-16 11:38:17 -060019"""
20Image signing and management.
21"""
22
23from . import version as versmod
David Vincze71b8f982020-03-17 19:08:12 +010024from .boot_record import create_sw_component_data
Fabio Utzig9a492d52020-01-15 11:31:52 -030025import click
Fabio Utzig4a5477a2019-05-27 15:45:08 -030026from enum import Enum
Carles Cufi37d052f2018-01-30 16:40:10 +010027from intelhex import IntelHex
David Brown23f91ad2017-05-16 11:38:17 -060028import hashlib
29import struct
Carles Cufi37d052f2018-01-30 16:40:10 +010030import os.path
Fabio Utzig960b4c52020-04-02 13:07:12 -030031from .keys import rsa, ecdsa, x25519
Fabio Utzig7a3b2602019-10-22 09:56:44 -030032from cryptography.hazmat.primitives.asymmetric import ec, padding
Fabio Utzig960b4c52020-04-02 13:07:12 -030033from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
Fabio Utzig06b77b82018-08-23 16:01:16 -030034from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Fabio Utzig7a3b2602019-10-22 09:56:44 -030035from cryptography.hazmat.primitives.kdf.hkdf import HKDF
36from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
Fabio Utzig06b77b82018-08-23 16:01:16 -030037from cryptography.hazmat.backends import default_backend
Fabio Utzig7a3b2602019-10-22 09:56:44 -030038from cryptography.hazmat.primitives import hashes, hmac
Fabio Utzig4a5477a2019-05-27 15:45:08 -030039from cryptography.exceptions import InvalidSignature
David Brown23f91ad2017-05-16 11:38:17 -060040
David Brown72e7a512017-09-01 11:08:23 -060041IMAGE_MAGIC = 0x96f3b83d
David Brown23f91ad2017-05-16 11:38:17 -060042IMAGE_HEADER_SIZE = 32
Carles Cufi37d052f2018-01-30 16:40:10 +010043BIN_EXT = "bin"
44INTEL_HEX_EXT = "hex"
Fabio Utzig519285f2018-06-04 11:11:53 -030045DEFAULT_MAX_SECTORS = 128
Fabio Utzig649d80f2019-09-12 10:26:23 -030046MAX_ALIGN = 8
David Vinczeda8c9192019-03-26 17:17:41 +010047DEP_IMAGES_KEY = "images"
48DEP_VERSIONS_KEY = "versions"
David Vincze71b8f982020-03-17 19:08:12 +010049MAX_SW_TYPE_LENGTH = 12 # Bytes
David Brown23f91ad2017-05-16 11:38:17 -060050
51# Image header flags.
52IMAGE_F = {
53 'PIC': 0x0000001,
Dominik Ermel50820b12020-12-14 13:16:46 +000054 'ENCRYPTED': 0x0000004,
Fabio Utzig06b77b82018-08-23 16:01:16 -030055 'NON_BOOTABLE': 0x0000010,
David Vincze1e0c5442020-04-07 14:12:33 +020056 'RAM_LOAD': 0x0000020,
Dominik Ermel50820b12020-12-14 13:16:46 +000057 'ROM_FIXED': 0x0000100,
Fabio Utzig06b77b82018-08-23 16:01:16 -030058}
David Brown23f91ad2017-05-16 11:38:17 -060059
60TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060061 'KEYHASH': 0x01,
David Vinczedde178d2020-03-26 20:06:01 +010062 'PUBKEY': 0x02,
David Brown27648b82017-08-31 10:40:29 -060063 'SHA256': 0x10,
64 'RSA2048': 0x20,
65 'ECDSA224': 0x21,
Fabio Utzig06b77b82018-08-23 16:01:16 -030066 'ECDSA256': 0x22,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030067 'RSA3072': 0x23,
Fabio Utzig8101d1f2019-05-09 15:03:22 -030068 'ED25519': 0x24,
Fabio Utzig06b77b82018-08-23 16:01:16 -030069 'ENCRSA2048': 0x30,
70 'ENCKW128': 0x31,
Fabio Utzig7a3b2602019-10-22 09:56:44 -030071 'ENCEC256': 0x32,
Fabio Utzig960b4c52020-04-02 13:07:12 -030072 'ENCX25519': 0x33,
David Vincze1a7a6902020-02-18 15:05:16 +010073 'DEPENDENCY': 0x40,
74 'SEC_CNT': 0x50,
David Vincze71b8f982020-03-17 19:08:12 +010075 'BOOT_RECORD': 0x60,
Fabio Utzig06b77b82018-08-23 16:01:16 -030076}
David Brown23f91ad2017-05-16 11:38:17 -060077
Fabio Utzig4a5477a2019-05-27 15:45:08 -030078TLV_SIZE = 4
David Brownf5b33d82017-09-01 10:58:27 -060079TLV_INFO_SIZE = 4
80TLV_INFO_MAGIC = 0x6907
Fabio Utzig510fddb2019-09-12 12:15:36 -030081TLV_PROT_INFO_MAGIC = 0x6908
David Brown23f91ad2017-05-16 11:38:17 -060082
David Brown23f91ad2017-05-16 11:38:17 -060083boot_magic = bytes([
84 0x77, 0xc2, 0x95, 0xf3,
85 0x60, 0xd2, 0xef, 0x7f,
86 0x35, 0x52, 0x50, 0x0f,
87 0x2c, 0xb6, 0x79, 0x80, ])
88
Mark Schultea66c6872018-09-26 17:24:40 -070089STRUCT_ENDIAN_DICT = {
90 'little': '<',
91 'big': '>'
92}
93
Fabio Utzig4a5477a2019-05-27 15:45:08 -030094VerifyResult = Enum('VerifyResult',
95 """
96 OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH
97 INVALID_SIGNATURE
98 """)
99
100
David Brown23f91ad2017-05-16 11:38:17 -0600101class TLV():
Fabio Utzig510fddb2019-09-12 12:15:36 -0300102 def __init__(self, endian, magic=TLV_INFO_MAGIC):
103 self.magic = magic
David Brown23f91ad2017-05-16 11:38:17 -0600104 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -0700105 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -0600106
Fabio Utzig510fddb2019-09-12 12:15:36 -0300107 def __len__(self):
108 return TLV_INFO_SIZE + len(self.buf)
109
David Brown23f91ad2017-05-16 11:38:17 -0600110 def add(self, kind, payload):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300111 """
112 Add a TLV record. Kind should be a string found in TLV_VALUES above.
113 """
Mark Schultea66c6872018-09-26 17:24:40 -0700114 e = STRUCT_ENDIAN_DICT[self.endian]
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200115 if isinstance(kind, int):
116 buf = struct.pack(e + 'BBH', kind, 0, len(payload))
117 else:
118 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -0600119 self.buf += buf
120 self.buf += payload
121
122 def get(self):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300123 if len(self.buf) == 0:
124 return bytes()
Mark Schultea66c6872018-09-26 17:24:40 -0700125 e = STRUCT_ENDIAN_DICT[self.endian]
Fabio Utzig510fddb2019-09-12 12:15:36 -0300126 header = struct.pack(e + 'HH', self.magic, len(self))
David Brownf5b33d82017-09-01 10:58:27 -0600127 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -0600128
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200129
David Brown23f91ad2017-05-16 11:38:17 -0600130class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +0100131
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200132 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100133 pad_header=False, pad=False, confirm=False, align=1,
134 slot_size=0, max_sectors=DEFAULT_MAX_SECTORS,
135 overwrite_only=False, endian="little", load_addr=0,
Dominik Ermel50820b12020-12-14 13:16:46 +0000136 rom_fixed=None, erased_val=None, save_enctlv=False,
137 security_counter=None):
138
139 if load_addr and rom_fixed:
140 raise click.UsageError("Can not set rom_fixed and load_addr at the same time")
141
David Brown23f91ad2017-05-16 11:38:17 -0600142 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200143 self.header_size = header_size
144 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -0600145 self.pad = pad
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100146 self.confirm = confirm
Fabio Utzig263d4392018-06-05 10:37:35 -0300147 self.align = align
148 self.slot_size = slot_size
149 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700150 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700151 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200152 self.base_addr = None
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000153 self.load_addr = 0 if load_addr is None else load_addr
Dominik Ermel50820b12020-12-14 13:16:46 +0000154 self.rom_fixed = rom_fixed
Fabio Utzigcb080732020-02-07 12:01:39 -0300155 self.erased_val = 0xff if erased_val is None else int(erased_val, 0)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200156 self.payload = []
Fabio Utzig649d80f2019-09-12 10:26:23 -0300157 self.enckey = None
Fabio Utzig9a492d52020-01-15 11:31:52 -0300158 self.save_enctlv = save_enctlv
159 self.enctlv_len = 0
David Brown23f91ad2017-05-16 11:38:17 -0600160
David Vincze1a7a6902020-02-18 15:05:16 +0100161 if security_counter == 'auto':
162 # Security counter has not been explicitly provided,
163 # generate it from the version number
164 self.security_counter = ((self.version.major << 24)
165 + (self.version.minor << 16)
166 + self.version.revision)
167 else:
168 self.security_counter = security_counter
169
David Brown23f91ad2017-05-16 11:38:17 -0600170 def __repr__(self):
David Vincze1a7a6902020-02-18 15:05:16 +0100171 return "<Image version={}, header_size={}, security_counter={}, \
172 base_addr={}, load_addr={}, align={}, slot_size={}, \
173 max_sectors={}, overwrite_only={}, endian={} format={}, \
174 payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300175 self.version,
176 self.header_size,
David Vincze1a7a6902020-02-18 15:05:16 +0100177 self.security_counter,
Fabio Utzig263d4392018-06-05 10:37:35 -0300178 self.base_addr if self.base_addr is not None else "N/A",
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000179 self.load_addr,
Fabio Utzig263d4392018-06-05 10:37:35 -0300180 self.align,
181 self.slot_size,
182 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700183 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700184 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300185 self.__class__.__name__,
186 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600187
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200188 def load(self, path):
189 """Load an image from a given file"""
190 ext = os.path.splitext(path)[1][1:].lower()
Fabio Utzig1f508922020-01-15 11:37:51 -0300191 try:
192 if ext == INTEL_HEX_EXT:
193 ih = IntelHex(path)
194 self.payload = ih.tobinarray()
195 self.base_addr = ih.minaddr()
196 else:
197 with open(path, 'rb') as f:
198 self.payload = f.read()
199 except FileNotFoundError:
200 raise click.UsageError("Input file not found")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200201
202 # Add the image header if needed.
203 if self.pad_header and self.header_size > 0:
204 if self.base_addr:
205 # Adjust base_addr for new header
206 self.base_addr -= self.header_size
Fabio Utzig9117fde2019-10-17 11:11:46 -0300207 self.payload = bytes([self.erased_val] * self.header_size) + \
208 self.payload
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200209
Fabio Utzig9a492d52020-01-15 11:31:52 -0300210 self.check_header()
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200211
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300212 def save(self, path, hex_addr=None):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200213 """Save an image from a given file"""
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200214 ext = os.path.splitext(path)[1][1:].lower()
215 if ext == INTEL_HEX_EXT:
216 # input was in binary format, but HEX needs to know the base addr
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300217 if self.base_addr is None and hex_addr is None:
Fabio Utzig1f508922020-01-15 11:37:51 -0300218 raise click.UsageError("No address exists in input file "
219 "neither was it provided by user")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200220 h = IntelHex()
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300221 if hex_addr is not None:
222 self.base_addr = hex_addr
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200223 h.frombytes(bytes=self.payload, offset=self.base_addr)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300224 if self.pad:
Fabio Utzig2269f472019-10-17 11:14:33 -0300225 trailer_size = self._trailer_size(self.align, self.max_sectors,
226 self.overwrite_only,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300227 self.enckey,
228 self.save_enctlv,
229 self.enctlv_len)
Fabio Utzig2269f472019-10-17 11:14:33 -0300230 trailer_addr = (self.base_addr + self.slot_size) - trailer_size
Roman Okhrimenko42b32392020-09-18 15:20:45 +0300231 padding = bytearray([self.erased_val] *
232 (trailer_size - len(boot_magic)))
233 if self.confirm and not self.overwrite_only:
234 padding[-MAX_ALIGN] = 0x01 # image_ok = 0x01
235 padding += boot_magic
236 h.puts(trailer_addr, bytes(padding))
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200237 h.tofile(path, 'hex')
238 else:
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300239 if self.pad:
240 self.pad_to(self.slot_size)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200241 with open(path, 'wb') as f:
242 f.write(self.payload)
243
Fabio Utzig9a492d52020-01-15 11:31:52 -0300244 def check_header(self):
Fabio Utzigf5556c32019-10-23 11:00:27 -0300245 if self.header_size > 0 and not self.pad_header:
David Brown23f91ad2017-05-16 11:38:17 -0600246 if any(v != 0 for v in self.payload[0:self.header_size]):
Fabio Utzig9a492d52020-01-15 11:31:52 -0300247 raise click.UsageError("Header padding was not requested and "
248 "image does not start with zeros")
249
250 def check_trailer(self):
Fabio Utzig263d4392018-06-05 10:37:35 -0300251 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700252 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300253 self.overwrite_only, self.enckey,
254 self.save_enctlv, self.enctlv_len)
Fabio Utzig263d4392018-06-05 10:37:35 -0300255 padding = self.slot_size - (len(self.payload) + tsize)
256 if padding < 0:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300257 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds " \
258 "requested size 0x{:x}".format(
259 len(self.payload), tsize, self.slot_size)
260 raise click.UsageError(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600261
Fabio Utzig960b4c52020-04-02 13:07:12 -0300262 def ecies_hkdf(self, enckey, plainkey):
263 if isinstance(enckey, ecdsa.ECDSA256P1Public):
264 newpk = ec.generate_private_key(ec.SECP256R1(), default_backend())
265 shared = newpk.exchange(ec.ECDH(), enckey._get_public())
266 else:
267 newpk = X25519PrivateKey.generate()
268 shared = newpk.exchange(enckey._get_public())
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300269 derived_key = HKDF(
270 algorithm=hashes.SHA256(), length=48, salt=None,
271 info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared)
272 encryptor = Cipher(algorithms.AES(derived_key[:16]),
273 modes.CTR(bytes([0] * 16)),
274 backend=default_backend()).encryptor()
275 cipherkey = encryptor.update(plainkey) + encryptor.finalize()
276 mac = hmac.HMAC(derived_key[16:], hashes.SHA256(),
277 backend=default_backend())
278 mac.update(cipherkey)
279 ciphermac = mac.finalize()
Fabio Utzig960b4c52020-04-02 13:07:12 -0300280 if isinstance(enckey, ecdsa.ECDSA256P1Public):
281 pubk = newpk.public_key().public_bytes(
282 encoding=Encoding.X962,
283 format=PublicFormat.UncompressedPoint)
284 else:
285 pubk = newpk.public_key().public_bytes(
286 encoding=Encoding.Raw,
287 format=PublicFormat.Raw)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300288 return cipherkey, ciphermac, pubk
289
David Vinczedde178d2020-03-26 20:06:01 +0100290 def create(self, key, public_key_format, enckey, dependencies=None,
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200291 sw_type=None, custom_tlvs=None):
Fabio Utzig649d80f2019-09-12 10:26:23 -0300292 self.enckey = enckey
293
David Vincze71b8f982020-03-17 19:08:12 +0100294 # Calculate the hash of the public key
295 if key is not None:
296 pub = key.get_public_bytes()
297 sha = hashlib.sha256()
298 sha.update(pub)
299 pubbytes = sha.digest()
300 else:
301 pubbytes = bytes(hashlib.sha256().digest_size)
302
David Vincze1a7a6902020-02-18 15:05:16 +0100303 protected_tlv_size = 0
304
305 if self.security_counter is not None:
306 # Size of the security counter TLV: header ('HH') + payload ('I')
307 # = 4 + 4 = 8 Bytes
308 protected_tlv_size += TLV_SIZE + 4
309
David Vincze71b8f982020-03-17 19:08:12 +0100310 if sw_type is not None:
311 if len(sw_type) > MAX_SW_TYPE_LENGTH:
312 msg = "'{}' is too long ({} characters) for sw_type. Its " \
313 "maximum allowed length is 12 characters.".format(
314 sw_type, len(sw_type))
315 raise click.UsageError(msg)
316
317 image_version = (str(self.version.major) + '.'
318 + str(self.version.minor) + '.'
319 + str(self.version.revision))
320
321 # The image hash is computed over the image header, the image
322 # itself and the protected TLV area. However, the boot record TLV
323 # (which is part of the protected area) should contain this hash
324 # before it is even calculated. For this reason the script fills
325 # this field with zeros and the bootloader will insert the right
326 # value later.
327 digest = bytes(hashlib.sha256().digest_size)
328
329 # Create CBOR encoded boot record
330 boot_record = create_sw_component_data(sw_type, image_version,
331 "SHA256", digest,
332 pubbytes)
333
334 protected_tlv_size += TLV_SIZE + len(boot_record)
335
David Vincze1a7a6902020-02-18 15:05:16 +0100336 if dependencies is not None:
337 # Size of a Dependency TLV = Header ('HH') + Payload('IBBHI')
338 # = 4 + 12 = 16 Bytes
David Vinczeda8c9192019-03-26 17:17:41 +0100339 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
David Vincze1a7a6902020-02-18 15:05:16 +0100340 protected_tlv_size += (dependencies_num * 16)
341
David Vinczeb2a1a482020-09-18 11:54:30 +0200342 if custom_tlvs is not None:
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200343 for value in custom_tlvs.values():
344 protected_tlv_size += TLV_SIZE + len(value)
345
David Vincze1a7a6902020-02-18 15:05:16 +0100346 if protected_tlv_size != 0:
347 # Add the size of the TLV info header
348 protected_tlv_size += TLV_INFO_SIZE
David Vinczeda8c9192019-03-26 17:17:41 +0100349
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200350 # At this point the image is already on the payload
351 #
352 # This adds the padding if image is not aligned to the 16 Bytes
353 # in encrypted mode
354 if self.enckey is not None:
355 pad_len = len(self.payload) % 16
356 if pad_len > 0:
Fabio Utzigd62631a2021-02-04 19:45:27 -0300357 pad = bytes(16 - pad_len)
358 if isinstance(self.payload, bytes):
359 self.payload += pad
360 else:
361 self.payload.extend(pad)
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200362
363 # This adds the header to the payload as well
David Vinczeda8c9192019-03-26 17:17:41 +0100364 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600365
Fabio Utzig510fddb2019-09-12 12:15:36 -0300366 prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC)
David Brown23f91ad2017-05-16 11:38:17 -0600367
Fabio Utzig510fddb2019-09-12 12:15:36 -0300368 # Protected TLVs must be added first, because they are also included
369 # in the hash calculation
370 protected_tlv_off = None
David Vinczeda8c9192019-03-26 17:17:41 +0100371 if protected_tlv_size != 0:
David Vincze1a7a6902020-02-18 15:05:16 +0100372
373 e = STRUCT_ENDIAN_DICT[self.endian]
374
375 if self.security_counter is not None:
376 payload = struct.pack(e + 'I', self.security_counter)
377 prot_tlv.add('SEC_CNT', payload)
378
David Vincze71b8f982020-03-17 19:08:12 +0100379 if sw_type is not None:
380 prot_tlv.add('BOOT_RECORD', boot_record)
381
David Vincze1a7a6902020-02-18 15:05:16 +0100382 if dependencies is not None:
383 for i in range(dependencies_num):
384 payload = struct.pack(
385 e + 'B3x'+'BBHI',
386 int(dependencies[DEP_IMAGES_KEY][i]),
387 dependencies[DEP_VERSIONS_KEY][i].major,
388 dependencies[DEP_VERSIONS_KEY][i].minor,
389 dependencies[DEP_VERSIONS_KEY][i].revision,
390 dependencies[DEP_VERSIONS_KEY][i].build
391 )
392 prot_tlv.add('DEPENDENCY', payload)
David Vinczeda8c9192019-03-26 17:17:41 +0100393
David Vinczeb2a1a482020-09-18 11:54:30 +0200394 if custom_tlvs is not None:
395 for tag, value in custom_tlvs.items():
396 prot_tlv.add(tag, value)
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200397
Fabio Utzig510fddb2019-09-12 12:15:36 -0300398 protected_tlv_off = len(self.payload)
399 self.payload += prot_tlv.get()
400
401 tlv = TLV(self.endian)
David Vinczeda8c9192019-03-26 17:17:41 +0100402
David Brown23f91ad2017-05-16 11:38:17 -0600403 # Note that ecdsa wants to do the hashing itself, which means
404 # we get to hash it twice.
405 sha = hashlib.sha256()
406 sha.update(self.payload)
407 digest = sha.digest()
408
409 tlv.add('SHA256', digest)
410
David Brown0f0c6a82017-06-08 09:26:24 -0600411 if key is not None:
David Vinczedde178d2020-03-26 20:06:01 +0100412 if public_key_format == 'hash':
413 tlv.add('KEYHASH', pubbytes)
414 else:
415 tlv.add('PUBKEY', pub)
David Brown43cda332017-09-01 09:53:23 -0600416
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300417 # `sign` expects the full image payload (sha256 done internally),
418 # while `sign_digest` expects only the digest of the payload
419
420 if hasattr(key, 'sign'):
421 sig = key.sign(bytes(self.payload))
422 else:
423 sig = key.sign_digest(digest)
David Brown0f0c6a82017-06-08 09:26:24 -0600424 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600425
Fabio Utzig510fddb2019-09-12 12:15:36 -0300426 # At this point the image was hashed + signed, we can remove the
427 # protected TLVs from the payload (will be re-added later)
428 if protected_tlv_off is not None:
429 self.payload = self.payload[:protected_tlv_off]
430
Fabio Utzig06b77b82018-08-23 16:01:16 -0300431 if enckey is not None:
432 plainkey = os.urandom(16)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300433
434 if isinstance(enckey, rsa.RSAPublic):
435 cipherkey = enckey._get_public().encrypt(
436 plainkey, padding.OAEP(
437 mgf=padding.MGF1(algorithm=hashes.SHA256()),
438 algorithm=hashes.SHA256(),
439 label=None))
Fabio Utzig9a492d52020-01-15 11:31:52 -0300440 self.enctlv_len = len(cipherkey)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300441 tlv.add('ENCRSA2048', cipherkey)
Fabio Utzig960b4c52020-04-02 13:07:12 -0300442 elif isinstance(enckey, (ecdsa.ECDSA256P1Public,
443 x25519.X25519Public)):
444 cipherkey, mac, pubk = self.ecies_hkdf(enckey, plainkey)
Fabio Utzig9a492d52020-01-15 11:31:52 -0300445 enctlv = pubk + mac + cipherkey
446 self.enctlv_len = len(enctlv)
Fabio Utzig960b4c52020-04-02 13:07:12 -0300447 if isinstance(enckey, ecdsa.ECDSA256P1Public):
448 tlv.add('ENCEC256', enctlv)
449 else:
450 tlv.add('ENCX25519', enctlv)
Fabio Utzig06b77b82018-08-23 16:01:16 -0300451
452 nonce = bytes([0] * 16)
453 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
454 backend=default_backend())
455 encryptor = cipher.encryptor()
456 img = bytes(self.payload[self.header_size:])
Fabio Utzig510fddb2019-09-12 12:15:36 -0300457 self.payload[self.header_size:] = \
458 encryptor.update(img) + encryptor.finalize()
Fabio Utzig06b77b82018-08-23 16:01:16 -0300459
Fabio Utzig510fddb2019-09-12 12:15:36 -0300460 self.payload += prot_tlv.get()
461 self.payload += tlv.get()
David Brown23f91ad2017-05-16 11:38:17 -0600462
Fabio Utzig9a492d52020-01-15 11:31:52 -0300463 self.check_trailer()
464
David Vinczeda8c9192019-03-26 17:17:41 +0100465 def add_header(self, enckey, protected_tlv_size):
Fabio Utzigcd284062018-11-30 11:05:45 -0200466 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600467
David Brown0f0c6a82017-06-08 09:26:24 -0600468 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300469 if enckey is not None:
470 flags |= IMAGE_F['ENCRYPTED']
David Vincze1e0c5442020-04-07 14:12:33 +0200471 if self.load_addr != 0:
472 # Indicates that this image should be loaded into RAM
473 # instead of run directly from flash.
474 flags |= IMAGE_F['RAM_LOAD']
Dominik Ermel50820b12020-12-14 13:16:46 +0000475 if self.rom_fixed:
476 flags |= IMAGE_F['ROM_FIXED']
David Brown23f91ad2017-05-16 11:38:17 -0600477
Mark Schultea66c6872018-09-26 17:24:40 -0700478 e = STRUCT_ENDIAN_DICT[self.endian]
479 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100480 # type ImageHdr struct {
481 'I' + # Magic uint32
482 'I' + # LoadAddr uint32
483 'H' + # HdrSz uint16
484 'H' + # PTLVSz uint16
485 'I' + # ImgSz uint32
486 'I' + # Flags uint32
487 'BBHI' + # Vers ImageVersion
488 'I' # Pad1 uint32
489 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600490 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
491 header = struct.pack(fmt,
492 IMAGE_MAGIC,
Dominik Ermel50820b12020-12-14 13:16:46 +0000493 self.rom_fixed or self.load_addr,
David Brown23f91ad2017-05-16 11:38:17 -0600494 self.header_size,
Fabio Utzig510fddb2019-09-12 12:15:36 -0300495 protected_tlv_size, # TLV Info header + Protected TLVs
496 len(self.payload) - self.header_size, # ImageSz
497 flags,
David Brown23f91ad2017-05-16 11:38:17 -0600498 self.version.major,
499 self.version.minor or 0,
500 self.version.revision or 0,
501 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100502 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600503 self.payload = bytearray(self.payload)
504 self.payload[:len(header)] = header
505
Fabio Utzig9a492d52020-01-15 11:31:52 -0300506 def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey,
507 save_enctlv, enctlv_len):
Fabio Utzig519285f2018-06-04 11:11:53 -0300508 # NOTE: should already be checked by the argument parser
Fabio Utzig649d80f2019-09-12 10:26:23 -0300509 magic_size = 16
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700510 if overwrite_only:
Fabio Utzig649d80f2019-09-12 10:26:23 -0300511 return MAX_ALIGN * 2 + magic_size
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700512 else:
513 if write_size not in set([1, 2, 4, 8]):
Fabio Utzig1f508922020-01-15 11:37:51 -0300514 raise click.BadParameter("Invalid alignment: {}".format(
515 write_size))
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700516 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
Fabio Utzig649d80f2019-09-12 10:26:23 -0300517 trailer = m * 3 * write_size # status area
518 if enckey is not None:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300519 if save_enctlv:
520 # TLV saved by the bootloader is aligned
521 keylen = (int((enctlv_len - 1) / MAX_ALIGN) + 1) * MAX_ALIGN
522 else:
523 keylen = 16
524 trailer += keylen * 2 # encryption keys
Fabio Utzig88282802019-10-17 11:17:18 -0300525 trailer += MAX_ALIGN * 4 # image_ok/copy_done/swap_info/swap_size
Fabio Utzig649d80f2019-09-12 10:26:23 -0300526 trailer += magic_size
527 return trailer
Fabio Utzig519285f2018-06-04 11:11:53 -0300528
Fabio Utzig263d4392018-06-05 10:37:35 -0300529 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600530 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700531 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300532 self.overwrite_only, self.enckey,
533 self.save_enctlv, self.enctlv_len)
David Brown23f91ad2017-05-16 11:38:17 -0600534 padding = size - (len(self.payload) + tsize)
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100535 pbytes = bytearray([self.erased_val] * padding)
536 pbytes += bytearray([self.erased_val] * (tsize - len(boot_magic)))
537 if self.confirm and not self.overwrite_only:
538 pbytes[-MAX_ALIGN] = 0x01 # image_ok = 0x01
Fabio Utzige08f0872017-06-28 18:12:16 -0300539 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600540 self.payload += pbytes
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300541
542 @staticmethod
543 def verify(imgfile, key):
544 with open(imgfile, "rb") as f:
545 b = f.read()
546
547 magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
Marek Pietae9555102019-08-08 16:08:16 +0200548 version = struct.unpack('BBHI', b[20:28])
549
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300550 if magic != IMAGE_MAGIC:
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200551 return VerifyResult.INVALID_MAGIC, None, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300552
Fabio Utzigd12a8da2021-01-21 08:44:59 -0300553 tlv_off = header_size + img_size
554 tlv_info = b[tlv_off:tlv_off+TLV_INFO_SIZE]
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300555 magic, tlv_tot = struct.unpack('HH', tlv_info)
Fabio Utzigd12a8da2021-01-21 08:44:59 -0300556 if magic == TLV_PROT_INFO_MAGIC:
557 tlv_off += tlv_tot
558 tlv_info = b[tlv_off:tlv_off+TLV_INFO_SIZE]
559 magic, tlv_tot = struct.unpack('HH', tlv_info)
560
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300561 if magic != TLV_INFO_MAGIC:
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200562 return VerifyResult.INVALID_TLV_INFO_MAGIC, None, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300563
564 sha = hashlib.sha256()
Fabio Utzigd12a8da2021-01-21 08:44:59 -0300565 prot_tlv_size = tlv_off
566 sha.update(b[:prot_tlv_size])
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300567 digest = sha.digest()
568
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300569 tlv_end = tlv_off + tlv_tot
570 tlv_off += TLV_INFO_SIZE # skip tlv info
571 while tlv_off < tlv_end:
572 tlv = b[tlv_off:tlv_off+TLV_SIZE]
573 tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
574 if tlv_type == TLV_VALUES["SHA256"]:
575 off = tlv_off + TLV_SIZE
576 if digest == b[off:off+tlv_len]:
577 if key is None:
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200578 return VerifyResult.OK, version, digest
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300579 else:
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200580 return VerifyResult.INVALID_HASH, None, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300581 elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
582 off = tlv_off + TLV_SIZE
583 tlv_sig = b[off:off+tlv_len]
Fabio Utzigd12a8da2021-01-21 08:44:59 -0300584 payload = b[:prot_tlv_size]
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300585 try:
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300586 if hasattr(key, 'verify'):
587 key.verify(tlv_sig, payload)
588 else:
589 key.verify_digest(tlv_sig, digest)
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200590 return VerifyResult.OK, version, digest
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300591 except InvalidSignature:
592 # continue to next TLV
593 pass
594 tlv_off += TLV_SIZE + tlv_len
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200595 return VerifyResult.INVALID_SIGNATURE, None, None