blob: 5114bf4c2061dc222a658a41a365e0fe7cdbae85 [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
Salome Thirot0f641972021-05-14 11:19:55 +01003# 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
Kristine Jassmann73c38c62021-02-03 16:56:14 +000046DEFAULT_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,
Salome Thirot0f641972021-05-14 11:19:55 +010054 '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,
Salome Thirot0f641972021-05-14 11:19:55 +010071 '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
Piotr Dymacze026c362023-02-24 12:09:33 +010084TLV_VENDOR_RES_MIN = 0x00a0
85TLV_VENDOR_RES_MAX = 0xfffe
86
Mark Schultea66c6872018-09-26 17:24:40 -070087STRUCT_ENDIAN_DICT = {
88 'little': '<',
89 'big': '>'
90}
91
Fabio Utzig4a5477a2019-05-27 15:45:08 -030092VerifyResult = Enum('VerifyResult',
93 """
94 OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH
95 INVALID_SIGNATURE
96 """)
97
Gustavo Henrique Niheicf120ba2021-11-22 18:44:11 -030098def align_up(num, align):
99 assert (align & (align - 1) == 0) and align != 0
100 return (num + (align - 1)) & ~(align - 1)
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300101
David Brown23f91ad2017-05-16 11:38:17 -0600102class TLV():
Fabio Utzig510fddb2019-09-12 12:15:36 -0300103 def __init__(self, endian, magic=TLV_INFO_MAGIC):
104 self.magic = magic
David Brown23f91ad2017-05-16 11:38:17 -0600105 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -0700106 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -0600107
Fabio Utzig510fddb2019-09-12 12:15:36 -0300108 def __len__(self):
109 return TLV_INFO_SIZE + len(self.buf)
110
David Brown23f91ad2017-05-16 11:38:17 -0600111 def add(self, kind, payload):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300112 """
113 Add a TLV record. Kind should be a string found in TLV_VALUES above.
114 """
Mark Schultea66c6872018-09-26 17:24:40 -0700115 e = STRUCT_ENDIAN_DICT[self.endian]
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200116 if isinstance(kind, int):
Piotr Dymacze026c362023-02-24 12:09:33 +0100117 if not TLV_VENDOR_RES_MIN <= kind <= TLV_VENDOR_RES_MAX:
118 msg = "Invalid custom TLV type value '0x{:04x}', allowed " \
119 "value should be between 0x{:04x} and 0x{:04x}".format(
120 kind, TLV_VENDOR_RES_MIN, TLV_VENDOR_RES_MAX)
121 raise click.UsageError(msg)
122 buf = struct.pack(e + 'HH', kind, len(payload))
Ihor Slabkyy24d93732020-03-10 15:33:57 +0200123 else:
124 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -0600125 self.buf += buf
126 self.buf += payload
127
128 def get(self):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300129 if len(self.buf) == 0:
130 return bytes()
Mark Schultea66c6872018-09-26 17:24:40 -0700131 e = STRUCT_ENDIAN_DICT[self.endian]
Fabio Utzig510fddb2019-09-12 12:15:36 -0300132 header = struct.pack(e + 'HH', self.magic, len(self))
David Brownf5b33d82017-09-01 10:58:27 -0600133 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -0600134
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200135
David Brown23f91ad2017-05-16 11:38:17 -0600136class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +0100137
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200138 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100139 pad_header=False, pad=False, confirm=False, align=1,
140 slot_size=0, max_sectors=DEFAULT_MAX_SECTORS,
141 overwrite_only=False, endian="little", load_addr=0,
Dominik Ermel50820b12020-12-14 13:16:46 +0000142 rom_fixed=None, erased_val=None, save_enctlv=False,
Piotr Mienkowskib6d5cf32022-01-31 01:01:11 +0100143 security_counter=None, max_align=None):
Dominik Ermel50820b12020-12-14 13:16:46 +0000144
145 if load_addr and rom_fixed:
146 raise click.UsageError("Can not set rom_fixed and load_addr at the same time")
147
David Brown23f91ad2017-05-16 11:38:17 -0600148 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200149 self.header_size = header_size
150 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -0600151 self.pad = pad
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100152 self.confirm = confirm
Fabio Utzig263d4392018-06-05 10:37:35 -0300153 self.align = align
154 self.slot_size = slot_size
155 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700156 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700157 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200158 self.base_addr = None
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000159 self.load_addr = 0 if load_addr is None else load_addr
Dominik Ermel50820b12020-12-14 13:16:46 +0000160 self.rom_fixed = rom_fixed
Fabio Utzigcb080732020-02-07 12:01:39 -0300161 self.erased_val = 0xff if erased_val is None else int(erased_val, 0)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200162 self.payload = []
Fabio Utzig649d80f2019-09-12 10:26:23 -0300163 self.enckey = None
Fabio Utzig9a492d52020-01-15 11:31:52 -0300164 self.save_enctlv = save_enctlv
165 self.enctlv_len = 0
Piotr Mienkowskib6d5cf32022-01-31 01:01:11 +0100166 self.max_align = max(DEFAULT_MAX_ALIGN, align) if max_align is None else int(max_align)
David Brown23f91ad2017-05-16 11:38:17 -0600167
Gustavo Henrique Niheicf120ba2021-11-22 18:44:11 -0300168 if self.max_align == DEFAULT_MAX_ALIGN:
169 self.boot_magic = bytes([
170 0x77, 0xc2, 0x95, 0xf3,
171 0x60, 0xd2, 0xef, 0x7f,
172 0x35, 0x52, 0x50, 0x0f,
173 0x2c, 0xb6, 0x79, 0x80, ])
174 else:
175 align_lsb = self.max_align & 0x00ff
176 align_msb = (self.max_align & 0xff00) >> 8
177 self.boot_magic = bytes([
178 align_lsb, align_msb, 0x2d, 0xe1,
179 0x5d, 0x29, 0x41, 0x0b,
180 0x8d, 0x77, 0x67, 0x9c,
181 0x11, 0x0f, 0x1f, 0x8a, ])
182
David Vincze1a7a6902020-02-18 15:05:16 +0100183 if security_counter == 'auto':
184 # Security counter has not been explicitly provided,
185 # generate it from the version number
186 self.security_counter = ((self.version.major << 24)
187 + (self.version.minor << 16)
188 + self.version.revision)
189 else:
190 self.security_counter = security_counter
191
David Brown23f91ad2017-05-16 11:38:17 -0600192 def __repr__(self):
David Vincze1a7a6902020-02-18 15:05:16 +0100193 return "<Image version={}, header_size={}, security_counter={}, \
194 base_addr={}, load_addr={}, align={}, slot_size={}, \
195 max_sectors={}, overwrite_only={}, endian={} format={}, \
196 payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300197 self.version,
198 self.header_size,
David Vincze1a7a6902020-02-18 15:05:16 +0100199 self.security_counter,
Fabio Utzig263d4392018-06-05 10:37:35 -0300200 self.base_addr if self.base_addr is not None else "N/A",
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000201 self.load_addr,
Fabio Utzig263d4392018-06-05 10:37:35 -0300202 self.align,
203 self.slot_size,
204 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700205 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700206 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300207 self.__class__.__name__,
208 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600209
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200210 def load(self, path):
211 """Load an image from a given file"""
212 ext = os.path.splitext(path)[1][1:].lower()
Fabio Utzig1f508922020-01-15 11:37:51 -0300213 try:
214 if ext == INTEL_HEX_EXT:
215 ih = IntelHex(path)
216 self.payload = ih.tobinarray()
217 self.base_addr = ih.minaddr()
218 else:
219 with open(path, 'rb') as f:
220 self.payload = f.read()
221 except FileNotFoundError:
222 raise click.UsageError("Input file not found")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200223
224 # Add the image header if needed.
225 if self.pad_header and self.header_size > 0:
226 if self.base_addr:
227 # Adjust base_addr for new header
228 self.base_addr -= self.header_size
Fabio Utzig9117fde2019-10-17 11:11:46 -0300229 self.payload = bytes([self.erased_val] * self.header_size) + \
230 self.payload
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200231
Fabio Utzig9a492d52020-01-15 11:31:52 -0300232 self.check_header()
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200233
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300234 def save(self, path, hex_addr=None):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200235 """Save an image from a given file"""
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200236 ext = os.path.splitext(path)[1][1:].lower()
237 if ext == INTEL_HEX_EXT:
238 # input was in binary format, but HEX needs to know the base addr
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300239 if self.base_addr is None and hex_addr is None:
Fabio Utzig1f508922020-01-15 11:37:51 -0300240 raise click.UsageError("No address exists in input file "
241 "neither was it provided by user")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200242 h = IntelHex()
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300243 if hex_addr is not None:
244 self.base_addr = hex_addr
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200245 h.frombytes(bytes=self.payload, offset=self.base_addr)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300246 if self.pad:
Fabio Utzig2269f472019-10-17 11:14:33 -0300247 trailer_size = self._trailer_size(self.align, self.max_sectors,
248 self.overwrite_only,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300249 self.enckey,
250 self.save_enctlv,
251 self.enctlv_len)
Fabio Utzig2269f472019-10-17 11:14:33 -0300252 trailer_addr = (self.base_addr + self.slot_size) - trailer_size
Kristine Jassmann73c38c62021-02-03 16:56:14 +0000253 if self.confirm and not self.overwrite_only:
Alexander Mihajlovicf4df58f2022-08-17 15:44:53 +0200254 magic_align_size = align_up(len(self.boot_magic), self.max_align)
Kristine Jassmann73c38c62021-02-03 16:56:14 +0000255 image_ok_idx = -(magic_align_size + self.max_align)
Alexander Mihajlovicf4df58f2022-08-17 15:44:53 +0200256 flag = bytearray([self.erased_val] * self.max_align)
Wouter Cappellec028d452022-01-25 10:25:24 +0100257 flag[0] = 0x01 # image_ok = 0x01
Alexander Mihajlovicf4df58f2022-08-17 15:44:53 +0200258 h.puts(trailer_addr + trailer_size + image_ok_idx, bytes(flag))
Wouter Cappellec028d452022-01-25 10:25:24 +0100259 h.puts(trailer_addr + (trailer_size - len(self.boot_magic)),
260 bytes(self.boot_magic))
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200261 h.tofile(path, 'hex')
262 else:
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300263 if self.pad:
264 self.pad_to(self.slot_size)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200265 with open(path, 'wb') as f:
266 f.write(self.payload)
267
Fabio Utzig9a492d52020-01-15 11:31:52 -0300268 def check_header(self):
Fabio Utzigf5556c32019-10-23 11:00:27 -0300269 if self.header_size > 0 and not self.pad_header:
David Brown23f91ad2017-05-16 11:38:17 -0600270 if any(v != 0 for v in self.payload[0:self.header_size]):
Fabio Utzig9a492d52020-01-15 11:31:52 -0300271 raise click.UsageError("Header padding was not requested and "
272 "image does not start with zeros")
273
274 def check_trailer(self):
Fabio Utzig263d4392018-06-05 10:37:35 -0300275 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700276 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300277 self.overwrite_only, self.enckey,
278 self.save_enctlv, self.enctlv_len)
Fabio Utzig263d4392018-06-05 10:37:35 -0300279 padding = self.slot_size - (len(self.payload) + tsize)
280 if padding < 0:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300281 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds " \
282 "requested size 0x{:x}".format(
283 len(self.payload), tsize, self.slot_size)
284 raise click.UsageError(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600285
Fabio Utzig960b4c52020-04-02 13:07:12 -0300286 def ecies_hkdf(self, enckey, plainkey):
287 if isinstance(enckey, ecdsa.ECDSA256P1Public):
288 newpk = ec.generate_private_key(ec.SECP256R1(), default_backend())
289 shared = newpk.exchange(ec.ECDH(), enckey._get_public())
290 else:
291 newpk = X25519PrivateKey.generate()
292 shared = newpk.exchange(enckey._get_public())
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300293 derived_key = HKDF(
294 algorithm=hashes.SHA256(), length=48, salt=None,
295 info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared)
296 encryptor = Cipher(algorithms.AES(derived_key[:16]),
297 modes.CTR(bytes([0] * 16)),
298 backend=default_backend()).encryptor()
299 cipherkey = encryptor.update(plainkey) + encryptor.finalize()
300 mac = hmac.HMAC(derived_key[16:], hashes.SHA256(),
301 backend=default_backend())
302 mac.update(cipherkey)
303 ciphermac = mac.finalize()
Fabio Utzig960b4c52020-04-02 13:07:12 -0300304 if isinstance(enckey, ecdsa.ECDSA256P1Public):
305 pubk = newpk.public_key().public_bytes(
306 encoding=Encoding.X962,
307 format=PublicFormat.UncompressedPoint)
308 else:
309 pubk = newpk.public_key().public_bytes(
310 encoding=Encoding.Raw,
311 format=PublicFormat.Raw)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300312 return cipherkey, ciphermac, pubk
313
David Vinczedde178d2020-03-26 20:06:01 +0100314 def create(self, key, public_key_format, enckey, dependencies=None,
Andrzej Puzdrowskidfce0be2022-03-28 09:34:15 +0200315 sw_type=None, custom_tlvs=None, encrypt_keylen=128, clear=False, fixed_sig=None, pub_key=None, vector_to_sign=None):
Fabio Utzig649d80f2019-09-12 10:26:23 -0300316 self.enckey = enckey
317
David Vincze71b8f982020-03-17 19:08:12 +0100318 # Calculate the hash of the public key
319 if key is not None:
320 pub = key.get_public_bytes()
321 sha = hashlib.sha256()
322 sha.update(pub)
323 pubbytes = sha.digest()
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +0100324 elif pub_key is not None:
Andrzej Puzdrowskidfce0be2022-03-28 09:34:15 +0200325 if hasattr(pub_key, 'sign'):
Antonio de Angelis284b8fe2022-11-15 13:54:47 +0000326 print(os.path.basename(__file__) + ": sign the payload")
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +0100327 pub = pub_key.get_public_bytes()
328 sha = hashlib.sha256()
329 sha.update(pub)
330 pubbytes = sha.digest()
David Vincze71b8f982020-03-17 19:08:12 +0100331 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
Salome Thirot0f641972021-05-14 11:19:55 +0100395 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
Fabio Utzig08a716d2022-11-18 10:54:07 -0300445 if vector_to_sign == 'payload':
446 # Stop amending data to the image
447 # Just keep data vector which is expected to be signed
448 print(os.path.basename(__file__) + ': export payload')
449 return
450 elif vector_to_sign == 'digest':
451 self.payload = digest
452 print(os.path.basename(__file__) + ': export digest')
453 return
454
Almir Okato3eb50262022-05-09 16:23:50 -0300455 if key is not None or fixed_sig is not None:
456 if public_key_format == 'hash':
457 tlv.add('KEYHASH', pubbytes)
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300458 else:
Almir Okato3eb50262022-05-09 16:23:50 -0300459 tlv.add('PUBKEY', pub)
460
Almir Okato3eb50262022-05-09 16:23:50 -0300461 if key is not None and fixed_sig is None:
462 # `sign` expects the full image payload (sha256 done internally),
463 # while `sign_digest` expects only the digest of the payload
464
465 if hasattr(key, 'sign'):
Antonio de Angelis284b8fe2022-11-15 13:54:47 +0000466 print(os.path.basename(__file__) + ": sign the payload")
Almir Okato3eb50262022-05-09 16:23:50 -0300467 sig = key.sign(bytes(self.payload))
468 else:
Antonio de Angelis284b8fe2022-11-15 13:54:47 +0000469 print(os.path.basename(__file__) + ": sign the digest")
Almir Okato3eb50262022-05-09 16:23:50 -0300470 sig = key.sign_digest(digest)
471 tlv.add(key.sig_tlv(), sig)
472 self.signature = sig
473 elif fixed_sig is not None and key is None:
474 tlv.add(pub_key.sig_tlv(), fixed_sig['value'])
475 self.signature = fixed_sig['value']
476 else:
477 raise click.UsageError("Can not sign using key and provide fixed-signature at the same time")
David Brown23f91ad2017-05-16 11:38:17 -0600478
Fabio Utzig510fddb2019-09-12 12:15:36 -0300479 # At this point the image was hashed + signed, we can remove the
480 # protected TLVs from the payload (will be re-added later)
481 if protected_tlv_off is not None:
482 self.payload = self.payload[:protected_tlv_off]
483
Fabio Utzig06b77b82018-08-23 16:01:16 -0300484 if enckey is not None:
Salome Thirot0f641972021-05-14 11:19:55 +0100485 if encrypt_keylen == 256:
486 plainkey = os.urandom(32)
487 else:
488 plainkey = os.urandom(16)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300489
490 if isinstance(enckey, rsa.RSAPublic):
491 cipherkey = enckey._get_public().encrypt(
492 plainkey, padding.OAEP(
493 mgf=padding.MGF1(algorithm=hashes.SHA256()),
494 algorithm=hashes.SHA256(),
495 label=None))
Fabio Utzig9a492d52020-01-15 11:31:52 -0300496 self.enctlv_len = len(cipherkey)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300497 tlv.add('ENCRSA2048', cipherkey)
Fabio Utzig960b4c52020-04-02 13:07:12 -0300498 elif isinstance(enckey, (ecdsa.ECDSA256P1Public,
499 x25519.X25519Public)):
500 cipherkey, mac, pubk = self.ecies_hkdf(enckey, plainkey)
Fabio Utzig9a492d52020-01-15 11:31:52 -0300501 enctlv = pubk + mac + cipherkey
502 self.enctlv_len = len(enctlv)
Fabio Utzig960b4c52020-04-02 13:07:12 -0300503 if isinstance(enckey, ecdsa.ECDSA256P1Public):
504 tlv.add('ENCEC256', enctlv)
505 else:
506 tlv.add('ENCX25519', enctlv)
Fabio Utzig06b77b82018-08-23 16:01:16 -0300507
Michel Jaouend09aa6b2022-01-07 16:48:58 +0100508 if not clear:
509 nonce = bytes([0] * 16)
510 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
511 backend=default_backend())
512 encryptor = cipher.encryptor()
513 img = bytes(self.payload[self.header_size:])
514 self.payload[self.header_size:] = \
515 encryptor.update(img) + encryptor.finalize()
Fabio Utzig06b77b82018-08-23 16:01:16 -0300516
Fabio Utzig510fddb2019-09-12 12:15:36 -0300517 self.payload += prot_tlv.get()
518 self.payload += tlv.get()
David Brown23f91ad2017-05-16 11:38:17 -0600519
Fabio Utzig9a492d52020-01-15 11:31:52 -0300520 self.check_trailer()
521
Andrzej Puzdrowski160303c2022-03-15 15:41:14 +0100522 def get_signature(self):
523 return self.signature
524
Salome Thirot0f641972021-05-14 11:19:55 +0100525 def add_header(self, enckey, protected_tlv_size, aes_length=128):
Fabio Utzigcd284062018-11-30 11:05:45 -0200526 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600527
David Brown0f0c6a82017-06-08 09:26:24 -0600528 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300529 if enckey is not None:
Salome Thirot0f641972021-05-14 11:19:55 +0100530 if aes_length == 128:
531 flags |= IMAGE_F['ENCRYPTED_AES128']
532 else:
533 flags |= IMAGE_F['ENCRYPTED_AES256']
David Vincze1e0c5442020-04-07 14:12:33 +0200534 if self.load_addr != 0:
535 # Indicates that this image should be loaded into RAM
536 # instead of run directly from flash.
537 flags |= IMAGE_F['RAM_LOAD']
Dominik Ermel50820b12020-12-14 13:16:46 +0000538 if self.rom_fixed:
539 flags |= IMAGE_F['ROM_FIXED']
David Brown23f91ad2017-05-16 11:38:17 -0600540
Mark Schultea66c6872018-09-26 17:24:40 -0700541 e = STRUCT_ENDIAN_DICT[self.endian]
542 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100543 # type ImageHdr struct {
544 'I' + # Magic uint32
545 'I' + # LoadAddr uint32
546 'H' + # HdrSz uint16
547 'H' + # PTLVSz uint16
548 'I' + # ImgSz uint32
549 'I' + # Flags uint32
550 'BBHI' + # Vers ImageVersion
551 'I' # Pad1 uint32
552 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600553 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
554 header = struct.pack(fmt,
555 IMAGE_MAGIC,
Dominik Ermel50820b12020-12-14 13:16:46 +0000556 self.rom_fixed or self.load_addr,
David Brown23f91ad2017-05-16 11:38:17 -0600557 self.header_size,
Fabio Utzig510fddb2019-09-12 12:15:36 -0300558 protected_tlv_size, # TLV Info header + Protected TLVs
559 len(self.payload) - self.header_size, # ImageSz
560 flags,
David Brown23f91ad2017-05-16 11:38:17 -0600561 self.version.major,
562 self.version.minor or 0,
563 self.version.revision or 0,
564 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100565 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600566 self.payload = bytearray(self.payload)
567 self.payload[:len(header)] = header
568
Fabio Utzig9a492d52020-01-15 11:31:52 -0300569 def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey,
570 save_enctlv, enctlv_len):
Fabio Utzig519285f2018-06-04 11:11:53 -0300571 # NOTE: should already be checked by the argument parser
Fabio Utzig649d80f2019-09-12 10:26:23 -0300572 magic_size = 16
Gustavo Henrique Niheicf120ba2021-11-22 18:44:11 -0300573 magic_align_size = align_up(magic_size, self.max_align)
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700574 if overwrite_only:
Kristine Jassmann73c38c62021-02-03 16:56:14 +0000575 return self.max_align * 2 + magic_align_size
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700576 else:
Kristine Jassmann73c38c62021-02-03 16:56:14 +0000577 if write_size not in set([1, 2, 4, 8, 16, 32]):
Fabio Utzig1f508922020-01-15 11:37:51 -0300578 raise click.BadParameter("Invalid alignment: {}".format(
579 write_size))
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700580 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
Fabio Utzig649d80f2019-09-12 10:26:23 -0300581 trailer = m * 3 * write_size # status area
582 if enckey is not None:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300583 if save_enctlv:
584 # TLV saved by the bootloader is aligned
Gustavo Henrique Niheicf120ba2021-11-22 18:44:11 -0300585 keylen = align_up(enctlv_len, self.max_align)
Fabio Utzig9a492d52020-01-15 11:31:52 -0300586 else:
Gustavo Henrique Niheicf120ba2021-11-22 18:44:11 -0300587 keylen = align_up(16, self.max_align)
Fabio Utzig9a492d52020-01-15 11:31:52 -0300588 trailer += keylen * 2 # encryption keys
Kristine Jassmann73c38c62021-02-03 16:56:14 +0000589 trailer += self.max_align * 4 # image_ok/copy_done/swap_info/swap_size
590 trailer += magic_align_size
Fabio Utzig649d80f2019-09-12 10:26:23 -0300591 return trailer
Fabio Utzig519285f2018-06-04 11:11:53 -0300592
Fabio Utzig263d4392018-06-05 10:37:35 -0300593 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600594 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700595 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300596 self.overwrite_only, self.enckey,
597 self.save_enctlv, self.enctlv_len)
David Brown23f91ad2017-05-16 11:38:17 -0600598 padding = size - (len(self.payload) + tsize)
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100599 pbytes = bytearray([self.erased_val] * padding)
Gustavo Henrique Niheicf120ba2021-11-22 18:44:11 -0300600 pbytes += bytearray([self.erased_val] * (tsize - len(self.boot_magic)))
601 pbytes += self.boot_magic
Kristine Jassmann73c38c62021-02-03 16:56:14 +0000602 if self.confirm and not self.overwrite_only:
603 magic_size = 16
Gustavo Henrique Niheicf120ba2021-11-22 18:44:11 -0300604 magic_align_size = align_up(magic_size, self.max_align)
Kristine Jassmann73c38c62021-02-03 16:56:14 +0000605 image_ok_idx = -(magic_align_size + self.max_align)
606 pbytes[image_ok_idx] = 0x01 # image_ok = 0x01
David Brown23f91ad2017-05-16 11:38:17 -0600607 self.payload += pbytes
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300608
609 @staticmethod
610 def verify(imgfile, key):
611 with open(imgfile, "rb") as f:
612 b = f.read()
613
614 magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
Marek Pietae9555102019-08-08 16:08:16 +0200615 version = struct.unpack('BBHI', b[20:28])
616
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300617 if magic != IMAGE_MAGIC:
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200618 return VerifyResult.INVALID_MAGIC, None, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300619
Fabio Utzigd12a8da2021-01-21 08:44:59 -0300620 tlv_off = header_size + img_size
621 tlv_info = b[tlv_off:tlv_off+TLV_INFO_SIZE]
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300622 magic, tlv_tot = struct.unpack('HH', tlv_info)
Fabio Utzigd12a8da2021-01-21 08:44:59 -0300623 if magic == TLV_PROT_INFO_MAGIC:
624 tlv_off += tlv_tot
625 tlv_info = b[tlv_off:tlv_off+TLV_INFO_SIZE]
626 magic, tlv_tot = struct.unpack('HH', tlv_info)
627
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300628 if magic != TLV_INFO_MAGIC:
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200629 return VerifyResult.INVALID_TLV_INFO_MAGIC, None, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300630
631 sha = hashlib.sha256()
Fabio Utzigd12a8da2021-01-21 08:44:59 -0300632 prot_tlv_size = tlv_off
633 sha.update(b[:prot_tlv_size])
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300634 digest = sha.digest()
635
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300636 tlv_end = tlv_off + tlv_tot
637 tlv_off += TLV_INFO_SIZE # skip tlv info
638 while tlv_off < tlv_end:
639 tlv = b[tlv_off:tlv_off+TLV_SIZE]
640 tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
641 if tlv_type == TLV_VALUES["SHA256"]:
642 off = tlv_off + TLV_SIZE
643 if digest == b[off:off+tlv_len]:
644 if key is None:
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200645 return VerifyResult.OK, version, digest
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300646 else:
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200647 return VerifyResult.INVALID_HASH, None, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300648 elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
649 off = tlv_off + TLV_SIZE
650 tlv_sig = b[off:off+tlv_len]
Fabio Utzigd12a8da2021-01-21 08:44:59 -0300651 payload = b[:prot_tlv_size]
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300652 try:
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300653 if hasattr(key, 'verify'):
654 key.verify(tlv_sig, payload)
655 else:
656 key.verify_digest(tlv_sig, digest)
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200657 return VerifyResult.OK, version, digest
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300658 except InvalidSignature:
659 # continue to next TLV
660 pass
661 tlv_off += TLV_SIZE + tlv_len
Casper Meijn2a01f3f2020-08-22 13:51:40 +0200662 return VerifyResult.INVALID_SIGNATURE, None, None