blob: 7109446b9c08097e0a553251c7b024b8a1b1d577 [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
Roman Okhrimenko977b3752022-03-31 14:40:48 +03003# Copyright 2019-2021 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
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +030046DEFAULT_MAX_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,
Roman Okhrimenko977b3752022-03-31 14:40:48 +030054 'ENCRYPTED_AES128': 0x0000004,
55 'ENCRYPTED_AES256': 0x0000008,
Fabio Utzig06b77b82018-08-23 16:01:16 -030056 'NON_BOOTABLE': 0x0000010,
David Vincze1e0c5442020-04-07 14:12:33 +020057 'RAM_LOAD': 0x0000020,
Dominik Ermel50820b12020-12-14 13:16:46 +000058 'ROM_FIXED': 0x0000100,
Fabio Utzig06b77b82018-08-23 16:01:16 -030059}
David Brown23f91ad2017-05-16 11:38:17 -060060
61TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060062 'KEYHASH': 0x01,
David Vinczedde178d2020-03-26 20:06:01 +010063 'PUBKEY': 0x02,
David Brown27648b82017-08-31 10:40:29 -060064 'SHA256': 0x10,
65 'RSA2048': 0x20,
66 'ECDSA224': 0x21,
Fabio Utzig06b77b82018-08-23 16:01:16 -030067 'ECDSA256': 0x22,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030068 'RSA3072': 0x23,
Fabio Utzig8101d1f2019-05-09 15:03:22 -030069 'ED25519': 0x24,
Fabio Utzig06b77b82018-08-23 16:01:16 -030070 'ENCRSA2048': 0x30,
Roman Okhrimenko977b3752022-03-31 14:40:48 +030071 'ENCKW': 0x31,
Fabio Utzig7a3b2602019-10-22 09:56:44 -030072 'ENCEC256': 0x32,
Fabio Utzig960b4c52020-04-02 13:07:12 -030073 'ENCX25519': 0x33,
David Vincze1a7a6902020-02-18 15:05:16 +010074 'DEPENDENCY': 0x40,
75 'SEC_CNT': 0x50,
David Vincze71b8f982020-03-17 19:08:12 +010076 'BOOT_RECORD': 0x60,
Fabio Utzig06b77b82018-08-23 16:01:16 -030077}
David Brown23f91ad2017-05-16 11:38:17 -060078
Fabio Utzig4a5477a2019-05-27 15:45:08 -030079TLV_SIZE = 4
David Brownf5b33d82017-09-01 10:58:27 -060080TLV_INFO_SIZE = 4
81TLV_INFO_MAGIC = 0x6907
Fabio Utzig510fddb2019-09-12 12:15:36 -030082TLV_PROT_INFO_MAGIC = 0x6908
David Brown23f91ad2017-05-16 11:38:17 -060083
Mark Schultea66c6872018-09-26 17:24:40 -070084STRUCT_ENDIAN_DICT = {
85 'little': '<',
86 'big': '>'
87}
88
Fabio Utzig4a5477a2019-05-27 15:45:08 -030089VerifyResult = Enum('VerifyResult',
90 """
91 OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH
92 INVALID_SIGNATURE
93 """)
94
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +030095def align_up(num, align):
96 assert (align & (align - 1) == 0) and align != 0
97 return (num + (align - 1)) & ~(align - 1)
Fabio Utzig4a5477a2019-05-27 15:45:08 -030098
David Brown23f91ad2017-05-16 11:38:17 -060099class TLV():
Fabio Utzig510fddb2019-09-12 12:15:36 -0300100 def __init__(self, endian, magic=TLV_INFO_MAGIC):
101 self.magic = magic
David Brown23f91ad2017-05-16 11:38:17 -0600102 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -0700103 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -0600104
Fabio Utzig510fddb2019-09-12 12:15:36 -0300105 def __len__(self):
106 return TLV_INFO_SIZE + len(self.buf)
107
David Brown23f91ad2017-05-16 11:38:17 -0600108 def add(self, kind, payload):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300109 """
110 Add a TLV record. Kind should be a string found in TLV_VALUES above.
111 """
Mark Schultea66c6872018-09-26 17:24:40 -0700112 e = STRUCT_ENDIAN_DICT[self.endian]
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200113 if isinstance(kind, int):
114 buf = struct.pack(e + 'BBH', kind, 0, len(payload))
115 else:
116 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -0600117 self.buf += buf
118 self.buf += payload
119
120 def get(self):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300121 if len(self.buf) == 0:
122 return bytes()
Mark Schultea66c6872018-09-26 17:24:40 -0700123 e = STRUCT_ENDIAN_DICT[self.endian]
Fabio Utzig510fddb2019-09-12 12:15:36 -0300124 header = struct.pack(e + 'HH', self.magic, len(self))
David Brownf5b33d82017-09-01 10:58:27 -0600125 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -0600126
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200127
David Brown23f91ad2017-05-16 11:38:17 -0600128class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +0100129
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200130 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100131 pad_header=False, pad=False, confirm=False, align=1,
132 slot_size=0, max_sectors=DEFAULT_MAX_SECTORS,
133 overwrite_only=False, endian="little", load_addr=0,
Dominik Ermel50820b12020-12-14 13:16:46 +0000134 rom_fixed=None, erased_val=None, save_enctlv=False,
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300135 security_counter=None, max_align=None):
Dominik Ermel50820b12020-12-14 13:16:46 +0000136
137 if load_addr and rom_fixed:
138 raise click.UsageError("Can not set rom_fixed and load_addr at the same time")
139
David Brown23f91ad2017-05-16 11:38:17 -0600140 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200141 self.header_size = header_size
142 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -0600143 self.pad = pad
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100144 self.confirm = confirm
Fabio Utzig263d4392018-06-05 10:37:35 -0300145 self.align = align
146 self.slot_size = slot_size
147 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700148 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700149 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200150 self.base_addr = None
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000151 self.load_addr = 0 if load_addr is None else load_addr
Dominik Ermel50820b12020-12-14 13:16:46 +0000152 self.rom_fixed = rom_fixed
Fabio Utzigcb080732020-02-07 12:01:39 -0300153 self.erased_val = 0xff if erased_val is None else int(erased_val, 0)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200154 self.payload = []
Fabio Utzig649d80f2019-09-12 10:26:23 -0300155 self.enckey = None
Fabio Utzig9a492d52020-01-15 11:31:52 -0300156 self.save_enctlv = save_enctlv
157 self.enctlv_len = 0
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200158 self.hkdf_salt = None
159 self.hkdf_len = 48
160 self.enc_nonce = bytes([0] * 16)
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300161 self.max_align = max(DEFAULT_MAX_ALIGN, align) if max_align is None else int(max_align)
162
163 if self.max_align == DEFAULT_MAX_ALIGN:
164 self.boot_magic = bytes([
165 0x77, 0xc2, 0x95, 0xf3,
166 0x60, 0xd2, 0xef, 0x7f,
167 0x35, 0x52, 0x50, 0x0f,
168 0x2c, 0xb6, 0x79, 0x80, ])
169 else:
170 align_lsb = self.max_align & 0x00ff
171 align_msb = (self.max_align & 0xff00) >> 8
172 self.boot_magic = bytes([
173 align_lsb, align_msb, 0x2d, 0xe1,
174 0x5d, 0x29, 0x41, 0x0b,
175 0x8d, 0x77, 0x67, 0x9c,
176 0x11, 0x0f, 0x1f, 0x8a, ])
David Brown23f91ad2017-05-16 11:38:17 -0600177
David Vincze1a7a6902020-02-18 15:05:16 +0100178 if security_counter == 'auto':
179 # Security counter has not been explicitly provided,
180 # generate it from the version number
181 self.security_counter = ((self.version.major << 24)
182 + (self.version.minor << 16)
183 + self.version.revision)
184 else:
185 self.security_counter = security_counter
186
David Brown23f91ad2017-05-16 11:38:17 -0600187 def __repr__(self):
David Vincze1a7a6902020-02-18 15:05:16 +0100188 return "<Image version={}, header_size={}, security_counter={}, \
189 base_addr={}, load_addr={}, align={}, slot_size={}, \
190 max_sectors={}, overwrite_only={}, endian={} format={}, \
191 payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300192 self.version,
193 self.header_size,
David Vincze1a7a6902020-02-18 15:05:16 +0100194 self.security_counter,
Fabio Utzig263d4392018-06-05 10:37:35 -0300195 self.base_addr if self.base_addr is not None else "N/A",
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000196 self.load_addr,
Fabio Utzig263d4392018-06-05 10:37:35 -0300197 self.align,
198 self.slot_size,
199 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700200 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700201 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300202 self.__class__.__name__,
203 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600204
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200205 def load(self, path):
206 """Load an image from a given file"""
207 ext = os.path.splitext(path)[1][1:].lower()
Fabio Utzig1f508922020-01-15 11:37:51 -0300208 try:
209 if ext == INTEL_HEX_EXT:
210 ih = IntelHex(path)
211 self.payload = ih.tobinarray()
212 self.base_addr = ih.minaddr()
213 else:
214 with open(path, 'rb') as f:
215 self.payload = f.read()
216 except FileNotFoundError:
217 raise click.UsageError("Input file not found")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200218
219 # Add the image header if needed.
220 if self.pad_header and self.header_size > 0:
221 if self.base_addr:
222 # Adjust base_addr for new header
223 self.base_addr -= self.header_size
Fabio Utzig9117fde2019-10-17 11:11:46 -0300224 self.payload = bytes([self.erased_val] * self.header_size) + \
225 self.payload
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200226
Fabio Utzig9a492d52020-01-15 11:31:52 -0300227 self.check_header()
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200228
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300229 def save(self, path, hex_addr=None):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200230 """Save an image from a given file"""
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200231 ext = os.path.splitext(path)[1][1:].lower()
232 if ext == INTEL_HEX_EXT:
233 # input was in binary format, but HEX needs to know the base addr
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300234 if self.base_addr is None and hex_addr is None:
Fabio Utzig1f508922020-01-15 11:37:51 -0300235 raise click.UsageError("No address exists in input file "
236 "neither was it provided by user")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200237 h = IntelHex()
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300238 if hex_addr is not None:
239 self.base_addr = hex_addr
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200240 h.frombytes(bytes=self.payload, offset=self.base_addr)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300241 if self.pad:
Fabio Utzig2269f472019-10-17 11:14:33 -0300242 trailer_size = self._trailer_size(self.align, self.max_sectors,
243 self.overwrite_only,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300244 self.enckey,
245 self.save_enctlv,
246 self.enctlv_len)
Fabio Utzig2269f472019-10-17 11:14:33 -0300247 trailer_addr = (self.base_addr + self.slot_size) - trailer_size
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200248 padding = bytearray([self.erased_val] *
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300249 (trailer_size - len(self.boot_magic)))
Roman Okhrimenko42b32392020-09-18 15:20:45 +0300250 if self.confirm and not self.overwrite_only:
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300251 magic_size = 16
252 magic_align_size = align_up(magic_size, self.max_align)
253 image_ok_idx = -(magic_align_size + self.max_align)
254 flag = bytearray([self.erased_val] * magic_align_size)
255 flag[0] = 0x01 # image_ok = 0x01
256 h.puts(trailer_addr + image_ok_idx, bytes(flag))
257 h.puts(trailer_addr + (trailer_size - len(self.boot_magic)),
258 bytes(self.boot_magic))
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200259 h.tofile(path, 'hex')
260 else:
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300261 if self.pad:
262 self.pad_to(self.slot_size)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200263 with open(path, 'wb') as f:
264 f.write(self.payload)
265
Fabio Utzig9a492d52020-01-15 11:31:52 -0300266 def check_header(self):
Fabio Utzigf5556c32019-10-23 11:00:27 -0300267 if self.header_size > 0 and not self.pad_header:
David Brown23f91ad2017-05-16 11:38:17 -0600268 if any(v != 0 for v in self.payload[0:self.header_size]):
Fabio Utzig9a492d52020-01-15 11:31:52 -0300269 raise click.UsageError("Header padding was not requested and "
270 "image does not start with zeros")
271
272 def check_trailer(self):
Fabio Utzig263d4392018-06-05 10:37:35 -0300273 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700274 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300275 self.overwrite_only, self.enckey,
276 self.save_enctlv, self.enctlv_len)
Fabio Utzig263d4392018-06-05 10:37:35 -0300277 padding = self.slot_size - (len(self.payload) + tsize)
278 if padding < 0:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300279 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds " \
280 "requested size 0x{:x}".format(
281 len(self.payload), tsize, self.slot_size)
282 raise click.UsageError(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600283
Fabio Utzig960b4c52020-04-02 13:07:12 -0300284 def ecies_hkdf(self, enckey, plainkey):
285 if isinstance(enckey, ecdsa.ECDSA256P1Public):
286 newpk = ec.generate_private_key(ec.SECP256R1(), default_backend())
287 shared = newpk.exchange(ec.ECDH(), enckey._get_public())
288 else:
289 newpk = X25519PrivateKey.generate()
290 shared = newpk.exchange(enckey._get_public())
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300291 derived_key = HKDF(
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200292 algorithm=hashes.SHA256(), length=self.hkdf_len, salt=self.hkdf_salt,
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300293 info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared)
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200294 if self.hkdf_salt is not None:
295 key_nonce = derived_key[48:64]
296 self.enc_nonce = derived_key[64:76] + bytes([0] * 4)
297 else:
298 key_nonce = bytes([0] * 16)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300299 encryptor = Cipher(algorithms.AES(derived_key[:16]),
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200300 modes.CTR(key_nonce),
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300301 backend=default_backend()).encryptor()
302 cipherkey = encryptor.update(plainkey) + encryptor.finalize()
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200303 mac = hmac.HMAC(derived_key[16:48], hashes.SHA256(),
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300304 backend=default_backend())
305 mac.update(cipherkey)
306 ciphermac = mac.finalize()
Fabio Utzig960b4c52020-04-02 13:07:12 -0300307 if isinstance(enckey, ecdsa.ECDSA256P1Public):
308 pubk = newpk.public_key().public_bytes(
309 encoding=Encoding.X962,
310 format=PublicFormat.UncompressedPoint)
311 else:
312 pubk = newpk.public_key().public_bytes(
313 encoding=Encoding.Raw,
314 format=PublicFormat.Raw)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300315 return cipherkey, ciphermac, pubk
316
David Vinczedde178d2020-03-26 20:06:01 +0100317 def create(self, key, public_key_format, enckey, dependencies=None,
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300318 sw_type=None, custom_tlvs=None, encrypt_keylen=128, clear=False, use_random_iv=False):
Fabio Utzig649d80f2019-09-12 10:26:23 -0300319 self.enckey = enckey
320
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200321 if use_random_iv:
322 self.hkdf_salt = os.urandom(32)
323 self.hkdf_len += 16 * 2 # 48 for basic scheme + 16 * 2 for random IVs
324
David Vincze71b8f982020-03-17 19:08:12 +0100325 # Calculate the hash of the public key
326 if key is not None:
327 pub = key.get_public_bytes()
328 sha = hashlib.sha256()
329 sha.update(pub)
330 pubbytes = sha.digest()
331 else:
332 pubbytes = bytes(hashlib.sha256().digest_size)
333
David Vincze1a7a6902020-02-18 15:05:16 +0100334 protected_tlv_size = 0
335
336 if self.security_counter is not None:
337 # Size of the security counter TLV: header ('HH') + payload ('I')
338 # = 4 + 4 = 8 Bytes
339 protected_tlv_size += TLV_SIZE + 4
340
David Vincze71b8f982020-03-17 19:08:12 +0100341 if sw_type is not None:
342 if len(sw_type) > MAX_SW_TYPE_LENGTH:
343 msg = "'{}' is too long ({} characters) for sw_type. Its " \
344 "maximum allowed length is 12 characters.".format(
345 sw_type, len(sw_type))
346 raise click.UsageError(msg)
347
348 image_version = (str(self.version.major) + '.'
349 + str(self.version.minor) + '.'
350 + str(self.version.revision))
351
352 # The image hash is computed over the image header, the image
353 # itself and the protected TLV area. However, the boot record TLV
354 # (which is part of the protected area) should contain this hash
355 # before it is even calculated. For this reason the script fills
356 # this field with zeros and the bootloader will insert the right
357 # value later.
358 digest = bytes(hashlib.sha256().digest_size)
359
360 # Create CBOR encoded boot record
361 boot_record = create_sw_component_data(sw_type, image_version,
362 "SHA256", digest,
363 pubbytes)
364
365 protected_tlv_size += TLV_SIZE + len(boot_record)
366
David Vincze1a7a6902020-02-18 15:05:16 +0100367 if dependencies is not None:
368 # Size of a Dependency TLV = Header ('HH') + Payload('IBBHI')
369 # = 4 + 12 = 16 Bytes
David Vinczeda8c9192019-03-26 17:17:41 +0100370 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
David Vincze1a7a6902020-02-18 15:05:16 +0100371 protected_tlv_size += (dependencies_num * 16)
372
David Vinczeb2a1a482020-09-18 11:54:30 +0200373 if custom_tlvs is not None:
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200374 for value in custom_tlvs.values():
375 protected_tlv_size += TLV_SIZE + len(value)
376
David Vincze1a7a6902020-02-18 15:05:16 +0100377 if protected_tlv_size != 0:
378 # Add the size of the TLV info header
379 protected_tlv_size += TLV_INFO_SIZE
David Vinczeda8c9192019-03-26 17:17:41 +0100380
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200381 # At this point the image is already on the payload
382 #
383 # This adds the padding if image is not aligned to the 16 Bytes
384 # in encrypted mode
385 if self.enckey is not None:
386 pad_len = len(self.payload) % 16
387 if pad_len > 0:
Fabio Utzigd62631a2021-02-04 19:45:27 -0300388 pad = bytes(16 - pad_len)
389 if isinstance(self.payload, bytes):
390 self.payload += pad
391 else:
392 self.payload.extend(pad)
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200393
394 # This adds the header to the payload as well
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300395 if encrypt_keylen == 256:
396 self.add_header(enckey, protected_tlv_size, 256)
397 else:
398 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600399
Fabio Utzig510fddb2019-09-12 12:15:36 -0300400 prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC)
David Brown23f91ad2017-05-16 11:38:17 -0600401
Fabio Utzig510fddb2019-09-12 12:15:36 -0300402 # Protected TLVs must be added first, because they are also included
403 # in the hash calculation
404 protected_tlv_off = None
David Vinczeda8c9192019-03-26 17:17:41 +0100405 if protected_tlv_size != 0:
David Vincze1a7a6902020-02-18 15:05:16 +0100406
407 e = STRUCT_ENDIAN_DICT[self.endian]
408
409 if self.security_counter is not None:
410 payload = struct.pack(e + 'I', self.security_counter)
411 prot_tlv.add('SEC_CNT', payload)
412
David Vincze71b8f982020-03-17 19:08:12 +0100413 if sw_type is not None:
414 prot_tlv.add('BOOT_RECORD', boot_record)
415
David Vincze1a7a6902020-02-18 15:05:16 +0100416 if dependencies is not None:
417 for i in range(dependencies_num):
418 payload = struct.pack(
419 e + 'B3x'+'BBHI',
420 int(dependencies[DEP_IMAGES_KEY][i]),
421 dependencies[DEP_VERSIONS_KEY][i].major,
422 dependencies[DEP_VERSIONS_KEY][i].minor,
423 dependencies[DEP_VERSIONS_KEY][i].revision,
424 dependencies[DEP_VERSIONS_KEY][i].build
425 )
426 prot_tlv.add('DEPENDENCY', payload)
David Vinczeda8c9192019-03-26 17:17:41 +0100427
David Vinczeb2a1a482020-09-18 11:54:30 +0200428 if custom_tlvs is not None:
429 for tag, value in custom_tlvs.items():
430 prot_tlv.add(tag, value)
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200431
Fabio Utzig510fddb2019-09-12 12:15:36 -0300432 protected_tlv_off = len(self.payload)
433 self.payload += prot_tlv.get()
434
435 tlv = TLV(self.endian)
David Vinczeda8c9192019-03-26 17:17:41 +0100436
David Brown23f91ad2017-05-16 11:38:17 -0600437 # Note that ecdsa wants to do the hashing itself, which means
438 # we get to hash it twice.
439 sha = hashlib.sha256()
440 sha.update(self.payload)
441 digest = sha.digest()
442
443 tlv.add('SHA256', digest)
444
David Brown0f0c6a82017-06-08 09:26:24 -0600445 if key is not None:
David Vinczedde178d2020-03-26 20:06:01 +0100446 if public_key_format == 'hash':
447 tlv.add('KEYHASH', pubbytes)
448 else:
449 tlv.add('PUBKEY', pub)
David Brown43cda332017-09-01 09:53:23 -0600450
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300451 # `sign` expects the full image payload (sha256 done internally),
452 # while `sign_digest` expects only the digest of the payload
453
454 if hasattr(key, 'sign'):
455 sig = key.sign(bytes(self.payload))
456 else:
457 sig = key.sign_digest(digest)
David Brown0f0c6a82017-06-08 09:26:24 -0600458 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600459
Fabio Utzig510fddb2019-09-12 12:15:36 -0300460 # At this point the image was hashed + signed, we can remove the
461 # protected TLVs from the payload (will be re-added later)
462 if protected_tlv_off is not None:
463 self.payload = self.payload[:protected_tlv_off]
464
Fabio Utzig06b77b82018-08-23 16:01:16 -0300465 if enckey is not None:
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300466 if encrypt_keylen == 256:
467 plainkey = os.urandom(32)
468 else:
469 plainkey = os.urandom(16)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300470
471 if isinstance(enckey, rsa.RSAPublic):
472 cipherkey = enckey._get_public().encrypt(
473 plainkey, padding.OAEP(
474 mgf=padding.MGF1(algorithm=hashes.SHA256()),
475 algorithm=hashes.SHA256(),
476 label=None))
Fabio Utzig9a492d52020-01-15 11:31:52 -0300477 self.enctlv_len = len(cipherkey)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300478 tlv.add('ENCRSA2048', cipherkey)
Fabio Utzig960b4c52020-04-02 13:07:12 -0300479 elif isinstance(enckey, (ecdsa.ECDSA256P1Public,
480 x25519.X25519Public)):
481 cipherkey, mac, pubk = self.ecies_hkdf(enckey, plainkey)
Fabio Utzig9a492d52020-01-15 11:31:52 -0300482 enctlv = pubk + mac + cipherkey
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200483 if self.hkdf_salt is not None:
484 enctlv += self.hkdf_salt
Fabio Utzig9a492d52020-01-15 11:31:52 -0300485 self.enctlv_len = len(enctlv)
Fabio Utzig960b4c52020-04-02 13:07:12 -0300486 if isinstance(enckey, ecdsa.ECDSA256P1Public):
487 tlv.add('ENCEC256', enctlv)
488 else:
489 tlv.add('ENCX25519', enctlv)
Fabio Utzig06b77b82018-08-23 16:01:16 -0300490
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300491 if not clear:
492 nonce = self.enc_nonce
493 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
494 backend=default_backend())
495 encryptor = cipher.encryptor()
496 img = bytes(self.payload[self.header_size:])
497 self.payload[self.header_size:] = \
498 encryptor.update(img) + encryptor.finalize()
Fabio Utzig06b77b82018-08-23 16:01:16 -0300499
Fabio Utzig510fddb2019-09-12 12:15:36 -0300500 self.payload += prot_tlv.get()
501 self.payload += tlv.get()
David Brown23f91ad2017-05-16 11:38:17 -0600502
Fabio Utzig9a492d52020-01-15 11:31:52 -0300503 self.check_trailer()
504
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300505 def add_header(self, enckey, protected_tlv_size, aes_length=128):
Fabio Utzigcd284062018-11-30 11:05:45 -0200506 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600507
David Brown0f0c6a82017-06-08 09:26:24 -0600508 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300509 if enckey is not None:
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300510 if aes_length == 128:
511 flags |= IMAGE_F['ENCRYPTED_AES128']
512 else:
513 flags |= IMAGE_F['ENCRYPTED_AES256']
David Vincze1e0c5442020-04-07 14:12:33 +0200514 if self.load_addr != 0:
515 # Indicates that this image should be loaded into RAM
516 # instead of run directly from flash.
517 flags |= IMAGE_F['RAM_LOAD']
Dominik Ermel50820b12020-12-14 13:16:46 +0000518 if self.rom_fixed:
519 flags |= IMAGE_F['ROM_FIXED']
David Brown23f91ad2017-05-16 11:38:17 -0600520
Mark Schultea66c6872018-09-26 17:24:40 -0700521 e = STRUCT_ENDIAN_DICT[self.endian]
522 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100523 # type ImageHdr struct {
524 'I' + # Magic uint32
525 'I' + # LoadAddr uint32
526 'H' + # HdrSz uint16
527 'H' + # PTLVSz uint16
528 'I' + # ImgSz uint32
529 'I' + # Flags uint32
530 'BBHI' + # Vers ImageVersion
531 'I' # Pad1 uint32
532 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600533 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
534 header = struct.pack(fmt,
535 IMAGE_MAGIC,
Dominik Ermel50820b12020-12-14 13:16:46 +0000536 self.rom_fixed or self.load_addr,
David Brown23f91ad2017-05-16 11:38:17 -0600537 self.header_size,
Fabio Utzig510fddb2019-09-12 12:15:36 -0300538 protected_tlv_size, # TLV Info header + Protected TLVs
539 len(self.payload) - self.header_size, # ImageSz
540 flags,
David Brown23f91ad2017-05-16 11:38:17 -0600541 self.version.major,
542 self.version.minor or 0,
543 self.version.revision or 0,
544 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100545 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600546 self.payload = bytearray(self.payload)
547 self.payload[:len(header)] = header
548
Fabio Utzig9a492d52020-01-15 11:31:52 -0300549 def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey,
550 save_enctlv, enctlv_len):
Fabio Utzig519285f2018-06-04 11:11:53 -0300551 # NOTE: should already be checked by the argument parser
Fabio Utzig649d80f2019-09-12 10:26:23 -0300552 magic_size = 16
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300553 magic_align_size = align_up(magic_size, self.max_align)
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700554 if overwrite_only:
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300555 return self.max_align * 2 + magic_align_size
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700556 else:
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300557 if write_size not in set([1, 2, 4, 8, 16, 32]):
Fabio Utzig1f508922020-01-15 11:37:51 -0300558 raise click.BadParameter("Invalid alignment: {}".format(
559 write_size))
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700560 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
Fabio Utzig649d80f2019-09-12 10:26:23 -0300561 trailer = m * 3 * write_size # status area
562 if enckey is not None:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300563 if save_enctlv:
564 # TLV saved by the bootloader is aligned
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300565 keylen = align_up(enctlv_len, self.max_align)
Fabio Utzig9a492d52020-01-15 11:31:52 -0300566 else:
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300567 keylen = align_up(16, self.max_align)
Fabio Utzig9a492d52020-01-15 11:31:52 -0300568 trailer += keylen * 2 # encryption keys
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300569 trailer += self.max_align * 4 # image_ok/copy_done/swap_info/swap_size
570 trailer += magic_align_size
Fabio Utzig649d80f2019-09-12 10:26:23 -0300571 return trailer
Fabio Utzig519285f2018-06-04 11:11:53 -0300572
Fabio Utzig263d4392018-06-05 10:37:35 -0300573 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600574 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700575 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300576 self.overwrite_only, self.enckey,
577 self.save_enctlv, self.enctlv_len)
David Brown23f91ad2017-05-16 11:38:17 -0600578 padding = size - (len(self.payload) + tsize)
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100579 pbytes = bytearray([self.erased_val] * padding)
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300580 pbytes += bytearray([self.erased_val] * (tsize - len(self.boot_magic)))
581 pbytes += self.boot_magic
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100582 if self.confirm and not self.overwrite_only:
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300583 magic_size = 16
584 magic_align_size = align_up(magic_size, self.max_align)
585 image_ok_idx = -(magic_align_size + self.max_align)
586 pbytes[image_ok_idx] = 0x01 # image_ok = 0x01
David Brown23f91ad2017-05-16 11:38:17 -0600587 self.payload += pbytes
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300588
589 @staticmethod
590 def verify(imgfile, key):
591 with open(imgfile, "rb") as f:
592 b = f.read()
593
594 magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
Marek Pietae9555102019-08-08 16:08:16 +0200595 version = struct.unpack('BBHI', b[20:28])
596
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300597 if magic != IMAGE_MAGIC:
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200598 return VerifyResult.INVALID_MAGIC, None, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300599
Fabio Utzigd12a8da2021-01-21 08:44:59 -0300600 tlv_off = header_size + img_size
601 tlv_info = b[tlv_off:tlv_off+TLV_INFO_SIZE]
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300602 magic, tlv_tot = struct.unpack('HH', tlv_info)
Fabio Utzigd12a8da2021-01-21 08:44:59 -0300603 if magic == TLV_PROT_INFO_MAGIC:
604 tlv_off += tlv_tot
605 tlv_info = b[tlv_off:tlv_off+TLV_INFO_SIZE]
606 magic, tlv_tot = struct.unpack('HH', tlv_info)
607
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300608 if magic != TLV_INFO_MAGIC:
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200609 return VerifyResult.INVALID_TLV_INFO_MAGIC, None, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300610
611 sha = hashlib.sha256()
Fabio Utzigd12a8da2021-01-21 08:44:59 -0300612 prot_tlv_size = tlv_off
613 sha.update(b[:prot_tlv_size])
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300614 digest = sha.digest()
615
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300616 tlv_end = tlv_off + tlv_tot
617 tlv_off += TLV_INFO_SIZE # skip tlv info
618 while tlv_off < tlv_end:
619 tlv = b[tlv_off:tlv_off+TLV_SIZE]
620 tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
621 if tlv_type == TLV_VALUES["SHA256"]:
622 off = tlv_off + TLV_SIZE
623 if digest == b[off:off+tlv_len]:
624 if key is None:
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200625 return VerifyResult.OK, version, digest
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300626 else:
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200627 return VerifyResult.INVALID_HASH, None, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300628 elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
629 off = tlv_off + TLV_SIZE
630 tlv_sig = b[off:off+tlv_len]
Fabio Utzigd12a8da2021-01-21 08:44:59 -0300631 payload = b[:prot_tlv_size]
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300632 try:
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300633 if hasattr(key, 'verify'):
634 key.verify(tlv_sig, payload)
635 else:
636 key.verify_digest(tlv_sig, digest)
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200637 return VerifyResult.OK, version, digest
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300638 except InvalidSignature:
639 # continue to next TLV
640 pass
641 tlv_off += TLV_SIZE + tlv_len
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200642 return VerifyResult.INVALID_SIGNATURE, None, None