blob: acb1794d166e23349fa7cb92ee76095a2faf8f3e [file] [log] [blame]
Carles Cufi37d052f2018-01-30 16:40:10 +01001# Copyright 2018 Nordic Semiconductor ASA
David Brown1314bf32017-12-20 11:10:55 -07002# Copyright 2017 Linaro Limited
David Vincze1a7a6902020-02-18 15:05:16 +01003# Copyright 2019-2020 Arm Limited
David Brown1314bf32017-12-20 11:10:55 -07004#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
David Brown23f91ad2017-05-16 11:38:17 -060017"""
18Image signing and management.
19"""
20
21from . import version as versmod
David Vincze71b8f982020-03-17 19:08:12 +010022from .boot_record import create_sw_component_data
Fabio Utzig9a492d52020-01-15 11:31:52 -030023import click
Fabio Utzig4a5477a2019-05-27 15:45:08 -030024from enum import Enum
Carles Cufi37d052f2018-01-30 16:40:10 +010025from intelhex import IntelHex
David Brown23f91ad2017-05-16 11:38:17 -060026import hashlib
27import struct
Carles Cufi37d052f2018-01-30 16:40:10 +010028import os.path
Fabio Utzig960b4c52020-04-02 13:07:12 -030029from .keys import rsa, ecdsa, x25519
Fabio Utzig7a3b2602019-10-22 09:56:44 -030030from cryptography.hazmat.primitives.asymmetric import ec, padding
Fabio Utzig960b4c52020-04-02 13:07:12 -030031from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
Fabio Utzig06b77b82018-08-23 16:01:16 -030032from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Fabio Utzig7a3b2602019-10-22 09:56:44 -030033from cryptography.hazmat.primitives.kdf.hkdf import HKDF
34from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
Fabio Utzig06b77b82018-08-23 16:01:16 -030035from cryptography.hazmat.backends import default_backend
Fabio Utzig7a3b2602019-10-22 09:56:44 -030036from cryptography.hazmat.primitives import hashes, hmac
Fabio Utzig4a5477a2019-05-27 15:45:08 -030037from cryptography.exceptions import InvalidSignature
David Brown23f91ad2017-05-16 11:38:17 -060038
David Brown72e7a512017-09-01 11:08:23 -060039IMAGE_MAGIC = 0x96f3b83d
David Brown23f91ad2017-05-16 11:38:17 -060040IMAGE_HEADER_SIZE = 32
Carles Cufi37d052f2018-01-30 16:40:10 +010041BIN_EXT = "bin"
42INTEL_HEX_EXT = "hex"
Fabio Utzig519285f2018-06-04 11:11:53 -030043DEFAULT_MAX_SECTORS = 128
Fabio Utzig649d80f2019-09-12 10:26:23 -030044MAX_ALIGN = 8
David Vinczeda8c9192019-03-26 17:17:41 +010045DEP_IMAGES_KEY = "images"
46DEP_VERSIONS_KEY = "versions"
David Vincze71b8f982020-03-17 19:08:12 +010047MAX_SW_TYPE_LENGTH = 12 # Bytes
David Brown23f91ad2017-05-16 11:38:17 -060048
49# Image header flags.
50IMAGE_F = {
51 'PIC': 0x0000001,
Fabio Utzig06b77b82018-08-23 16:01:16 -030052 'NON_BOOTABLE': 0x0000010,
David Vincze1e0c5442020-04-07 14:12:33 +020053 'RAM_LOAD': 0x0000020,
Fabio Utzig06b77b82018-08-23 16:01:16 -030054 'ENCRYPTED': 0x0000004,
55}
David Brown23f91ad2017-05-16 11:38:17 -060056
57TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060058 'KEYHASH': 0x01,
David Vinczedde178d2020-03-26 20:06:01 +010059 'PUBKEY': 0x02,
David Brown27648b82017-08-31 10:40:29 -060060 'SHA256': 0x10,
61 'RSA2048': 0x20,
62 'ECDSA224': 0x21,
Fabio Utzig06b77b82018-08-23 16:01:16 -030063 'ECDSA256': 0x22,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030064 'RSA3072': 0x23,
Fabio Utzig8101d1f2019-05-09 15:03:22 -030065 'ED25519': 0x24,
Fabio Utzig06b77b82018-08-23 16:01:16 -030066 'ENCRSA2048': 0x30,
67 'ENCKW128': 0x31,
Fabio Utzig7a3b2602019-10-22 09:56:44 -030068 'ENCEC256': 0x32,
Fabio Utzig960b4c52020-04-02 13:07:12 -030069 'ENCX25519': 0x33,
David Vincze1a7a6902020-02-18 15:05:16 +010070 'DEPENDENCY': 0x40,
71 'SEC_CNT': 0x50,
David Vincze71b8f982020-03-17 19:08:12 +010072 'BOOT_RECORD': 0x60,
Fabio Utzig06b77b82018-08-23 16:01:16 -030073}
David Brown23f91ad2017-05-16 11:38:17 -060074
Fabio Utzig4a5477a2019-05-27 15:45:08 -030075TLV_SIZE = 4
David Brownf5b33d82017-09-01 10:58:27 -060076TLV_INFO_SIZE = 4
77TLV_INFO_MAGIC = 0x6907
Fabio Utzig510fddb2019-09-12 12:15:36 -030078TLV_PROT_INFO_MAGIC = 0x6908
David Brown23f91ad2017-05-16 11:38:17 -060079
David Brown23f91ad2017-05-16 11:38:17 -060080boot_magic = bytes([
81 0x77, 0xc2, 0x95, 0xf3,
82 0x60, 0xd2, 0xef, 0x7f,
83 0x35, 0x52, 0x50, 0x0f,
84 0x2c, 0xb6, 0x79, 0x80, ])
85
Mark Schultea66c6872018-09-26 17:24:40 -070086STRUCT_ENDIAN_DICT = {
87 'little': '<',
88 'big': '>'
89}
90
Fabio Utzig4a5477a2019-05-27 15:45:08 -030091VerifyResult = Enum('VerifyResult',
92 """
93 OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH
94 INVALID_SIGNATURE
95 """)
96
97
David Brown23f91ad2017-05-16 11:38:17 -060098class TLV():
Fabio Utzig510fddb2019-09-12 12:15:36 -030099 def __init__(self, endian, magic=TLV_INFO_MAGIC):
100 self.magic = magic
David Brown23f91ad2017-05-16 11:38:17 -0600101 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -0700102 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -0600103
Fabio Utzig510fddb2019-09-12 12:15:36 -0300104 def __len__(self):
105 return TLV_INFO_SIZE + len(self.buf)
106
David Brown23f91ad2017-05-16 11:38:17 -0600107 def add(self, kind, payload):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300108 """
109 Add a TLV record. Kind should be a string found in TLV_VALUES above.
110 """
Mark Schultea66c6872018-09-26 17:24:40 -0700111 e = STRUCT_ENDIAN_DICT[self.endian]
112 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -0600113 self.buf += buf
114 self.buf += payload
115
116 def get(self):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300117 if len(self.buf) == 0:
118 return bytes()
Mark Schultea66c6872018-09-26 17:24:40 -0700119 e = STRUCT_ENDIAN_DICT[self.endian]
Fabio Utzig510fddb2019-09-12 12:15:36 -0300120 header = struct.pack(e + 'HH', self.magic, len(self))
David Brownf5b33d82017-09-01 10:58:27 -0600121 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -0600122
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200123
David Brown23f91ad2017-05-16 11:38:17 -0600124class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +0100125
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200126 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100127 pad_header=False, pad=False, confirm=False, align=1,
128 slot_size=0, max_sectors=DEFAULT_MAX_SECTORS,
129 overwrite_only=False, endian="little", load_addr=0,
130 erased_val=None, save_enctlv=False, security_counter=None):
David Brown23f91ad2017-05-16 11:38:17 -0600131 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200132 self.header_size = header_size
133 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -0600134 self.pad = pad
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100135 self.confirm = confirm
Fabio Utzig263d4392018-06-05 10:37:35 -0300136 self.align = align
137 self.slot_size = slot_size
138 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700139 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700140 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200141 self.base_addr = None
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000142 self.load_addr = 0 if load_addr is None else load_addr
Fabio Utzigcb080732020-02-07 12:01:39 -0300143 self.erased_val = 0xff if erased_val is None else int(erased_val, 0)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200144 self.payload = []
Fabio Utzig649d80f2019-09-12 10:26:23 -0300145 self.enckey = None
Fabio Utzig9a492d52020-01-15 11:31:52 -0300146 self.save_enctlv = save_enctlv
147 self.enctlv_len = 0
David Brown23f91ad2017-05-16 11:38:17 -0600148
David Vincze1a7a6902020-02-18 15:05:16 +0100149 if security_counter == 'auto':
150 # Security counter has not been explicitly provided,
151 # generate it from the version number
152 self.security_counter = ((self.version.major << 24)
153 + (self.version.minor << 16)
154 + self.version.revision)
155 else:
156 self.security_counter = security_counter
157
David Brown23f91ad2017-05-16 11:38:17 -0600158 def __repr__(self):
David Vincze1a7a6902020-02-18 15:05:16 +0100159 return "<Image version={}, header_size={}, security_counter={}, \
160 base_addr={}, load_addr={}, align={}, slot_size={}, \
161 max_sectors={}, overwrite_only={}, endian={} format={}, \
162 payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300163 self.version,
164 self.header_size,
David Vincze1a7a6902020-02-18 15:05:16 +0100165 self.security_counter,
Fabio Utzig263d4392018-06-05 10:37:35 -0300166 self.base_addr if self.base_addr is not None else "N/A",
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000167 self.load_addr,
Fabio Utzig263d4392018-06-05 10:37:35 -0300168 self.align,
169 self.slot_size,
170 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700171 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700172 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300173 self.__class__.__name__,
174 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600175
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200176 def load(self, path):
177 """Load an image from a given file"""
178 ext = os.path.splitext(path)[1][1:].lower()
Fabio Utzig1f508922020-01-15 11:37:51 -0300179 try:
180 if ext == INTEL_HEX_EXT:
181 ih = IntelHex(path)
182 self.payload = ih.tobinarray()
183 self.base_addr = ih.minaddr()
184 else:
185 with open(path, 'rb') as f:
186 self.payload = f.read()
187 except FileNotFoundError:
188 raise click.UsageError("Input file not found")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200189
190 # Add the image header if needed.
191 if self.pad_header and self.header_size > 0:
192 if self.base_addr:
193 # Adjust base_addr for new header
194 self.base_addr -= self.header_size
Fabio Utzig9117fde2019-10-17 11:11:46 -0300195 self.payload = bytes([self.erased_val] * self.header_size) + \
196 self.payload
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200197
Fabio Utzig9a492d52020-01-15 11:31:52 -0300198 self.check_header()
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200199
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300200 def save(self, path, hex_addr=None):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200201 """Save an image from a given file"""
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200202 ext = os.path.splitext(path)[1][1:].lower()
203 if ext == INTEL_HEX_EXT:
204 # input was in binary format, but HEX needs to know the base addr
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300205 if self.base_addr is None and hex_addr is None:
Fabio Utzig1f508922020-01-15 11:37:51 -0300206 raise click.UsageError("No address exists in input file "
207 "neither was it provided by user")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200208 h = IntelHex()
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300209 if hex_addr is not None:
210 self.base_addr = hex_addr
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200211 h.frombytes(bytes=self.payload, offset=self.base_addr)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300212 if self.pad:
Fabio Utzig2269f472019-10-17 11:14:33 -0300213 trailer_size = self._trailer_size(self.align, self.max_sectors,
214 self.overwrite_only,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300215 self.enckey,
216 self.save_enctlv,
217 self.enctlv_len)
Fabio Utzig2269f472019-10-17 11:14:33 -0300218 trailer_addr = (self.base_addr + self.slot_size) - trailer_size
219 padding = bytes([self.erased_val] *
220 (trailer_size - len(boot_magic))) + boot_magic
221 h.puts(trailer_addr, padding)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200222 h.tofile(path, 'hex')
223 else:
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300224 if self.pad:
225 self.pad_to(self.slot_size)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200226 with open(path, 'wb') as f:
227 f.write(self.payload)
228
Fabio Utzig9a492d52020-01-15 11:31:52 -0300229 def check_header(self):
Fabio Utzigf5556c32019-10-23 11:00:27 -0300230 if self.header_size > 0 and not self.pad_header:
David Brown23f91ad2017-05-16 11:38:17 -0600231 if any(v != 0 for v in self.payload[0:self.header_size]):
Fabio Utzig9a492d52020-01-15 11:31:52 -0300232 raise click.UsageError("Header padding was not requested and "
233 "image does not start with zeros")
234
235 def check_trailer(self):
Fabio Utzig263d4392018-06-05 10:37:35 -0300236 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700237 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300238 self.overwrite_only, self.enckey,
239 self.save_enctlv, self.enctlv_len)
Fabio Utzig263d4392018-06-05 10:37:35 -0300240 padding = self.slot_size - (len(self.payload) + tsize)
241 if padding < 0:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300242 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds " \
243 "requested size 0x{:x}".format(
244 len(self.payload), tsize, self.slot_size)
245 raise click.UsageError(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600246
Fabio Utzig960b4c52020-04-02 13:07:12 -0300247 def ecies_hkdf(self, enckey, plainkey):
248 if isinstance(enckey, ecdsa.ECDSA256P1Public):
249 newpk = ec.generate_private_key(ec.SECP256R1(), default_backend())
250 shared = newpk.exchange(ec.ECDH(), enckey._get_public())
251 else:
252 newpk = X25519PrivateKey.generate()
253 shared = newpk.exchange(enckey._get_public())
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300254 derived_key = HKDF(
255 algorithm=hashes.SHA256(), length=48, salt=None,
256 info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared)
257 encryptor = Cipher(algorithms.AES(derived_key[:16]),
258 modes.CTR(bytes([0] * 16)),
259 backend=default_backend()).encryptor()
260 cipherkey = encryptor.update(plainkey) + encryptor.finalize()
261 mac = hmac.HMAC(derived_key[16:], hashes.SHA256(),
262 backend=default_backend())
263 mac.update(cipherkey)
264 ciphermac = mac.finalize()
Fabio Utzig960b4c52020-04-02 13:07:12 -0300265 if isinstance(enckey, ecdsa.ECDSA256P1Public):
266 pubk = newpk.public_key().public_bytes(
267 encoding=Encoding.X962,
268 format=PublicFormat.UncompressedPoint)
269 else:
270 pubk = newpk.public_key().public_bytes(
271 encoding=Encoding.Raw,
272 format=PublicFormat.Raw)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300273 return cipherkey, ciphermac, pubk
274
David Vinczedde178d2020-03-26 20:06:01 +0100275 def create(self, key, public_key_format, enckey, dependencies=None,
276 sw_type=None):
Fabio Utzig649d80f2019-09-12 10:26:23 -0300277 self.enckey = enckey
278
David Vincze71b8f982020-03-17 19:08:12 +0100279 # Calculate the hash of the public key
280 if key is not None:
281 pub = key.get_public_bytes()
282 sha = hashlib.sha256()
283 sha.update(pub)
284 pubbytes = sha.digest()
285 else:
286 pubbytes = bytes(hashlib.sha256().digest_size)
287
David Vincze1a7a6902020-02-18 15:05:16 +0100288 protected_tlv_size = 0
289
290 if self.security_counter is not None:
291 # Size of the security counter TLV: header ('HH') + payload ('I')
292 # = 4 + 4 = 8 Bytes
293 protected_tlv_size += TLV_SIZE + 4
294
David Vincze71b8f982020-03-17 19:08:12 +0100295 if sw_type is not None:
296 if len(sw_type) > MAX_SW_TYPE_LENGTH:
297 msg = "'{}' is too long ({} characters) for sw_type. Its " \
298 "maximum allowed length is 12 characters.".format(
299 sw_type, len(sw_type))
300 raise click.UsageError(msg)
301
302 image_version = (str(self.version.major) + '.'
303 + str(self.version.minor) + '.'
304 + str(self.version.revision))
305
306 # The image hash is computed over the image header, the image
307 # itself and the protected TLV area. However, the boot record TLV
308 # (which is part of the protected area) should contain this hash
309 # before it is even calculated. For this reason the script fills
310 # this field with zeros and the bootloader will insert the right
311 # value later.
312 digest = bytes(hashlib.sha256().digest_size)
313
314 # Create CBOR encoded boot record
315 boot_record = create_sw_component_data(sw_type, image_version,
316 "SHA256", digest,
317 pubbytes)
318
319 protected_tlv_size += TLV_SIZE + len(boot_record)
320
David Vincze1a7a6902020-02-18 15:05:16 +0100321 if dependencies is not None:
322 # Size of a Dependency TLV = Header ('HH') + Payload('IBBHI')
323 # = 4 + 12 = 16 Bytes
David Vinczeda8c9192019-03-26 17:17:41 +0100324 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
David Vincze1a7a6902020-02-18 15:05:16 +0100325 protected_tlv_size += (dependencies_num * 16)
326
327 if protected_tlv_size != 0:
328 # Add the size of the TLV info header
329 protected_tlv_size += TLV_INFO_SIZE
David Vinczeda8c9192019-03-26 17:17:41 +0100330
Fabio Utzig510fddb2019-09-12 12:15:36 -0300331 # At this point the image is already on the payload, this adds
332 # the header to the payload as well
David Vinczeda8c9192019-03-26 17:17:41 +0100333 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600334
Fabio Utzig510fddb2019-09-12 12:15:36 -0300335 prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC)
David Brown23f91ad2017-05-16 11:38:17 -0600336
Fabio Utzig510fddb2019-09-12 12:15:36 -0300337 # Protected TLVs must be added first, because they are also included
338 # in the hash calculation
339 protected_tlv_off = None
David Vinczeda8c9192019-03-26 17:17:41 +0100340 if protected_tlv_size != 0:
David Vincze1a7a6902020-02-18 15:05:16 +0100341
342 e = STRUCT_ENDIAN_DICT[self.endian]
343
344 if self.security_counter is not None:
345 payload = struct.pack(e + 'I', self.security_counter)
346 prot_tlv.add('SEC_CNT', payload)
347
David Vincze71b8f982020-03-17 19:08:12 +0100348 if sw_type is not None:
349 prot_tlv.add('BOOT_RECORD', boot_record)
350
David Vincze1a7a6902020-02-18 15:05:16 +0100351 if dependencies is not None:
352 for i in range(dependencies_num):
353 payload = struct.pack(
354 e + 'B3x'+'BBHI',
355 int(dependencies[DEP_IMAGES_KEY][i]),
356 dependencies[DEP_VERSIONS_KEY][i].major,
357 dependencies[DEP_VERSIONS_KEY][i].minor,
358 dependencies[DEP_VERSIONS_KEY][i].revision,
359 dependencies[DEP_VERSIONS_KEY][i].build
360 )
361 prot_tlv.add('DEPENDENCY', payload)
David Vinczeda8c9192019-03-26 17:17:41 +0100362
Fabio Utzig510fddb2019-09-12 12:15:36 -0300363 protected_tlv_off = len(self.payload)
364 self.payload += prot_tlv.get()
365
366 tlv = TLV(self.endian)
David Vinczeda8c9192019-03-26 17:17:41 +0100367
David Brown23f91ad2017-05-16 11:38:17 -0600368 # Note that ecdsa wants to do the hashing itself, which means
369 # we get to hash it twice.
370 sha = hashlib.sha256()
371 sha.update(self.payload)
372 digest = sha.digest()
373
374 tlv.add('SHA256', digest)
375
David Brown0f0c6a82017-06-08 09:26:24 -0600376 if key is not None:
David Vinczedde178d2020-03-26 20:06:01 +0100377 if public_key_format == 'hash':
378 tlv.add('KEYHASH', pubbytes)
379 else:
380 tlv.add('PUBKEY', pub)
David Brown43cda332017-09-01 09:53:23 -0600381
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300382 # `sign` expects the full image payload (sha256 done internally),
383 # while `sign_digest` expects only the digest of the payload
384
385 if hasattr(key, 'sign'):
386 sig = key.sign(bytes(self.payload))
387 else:
388 sig = key.sign_digest(digest)
David Brown0f0c6a82017-06-08 09:26:24 -0600389 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600390
Fabio Utzig510fddb2019-09-12 12:15:36 -0300391 # At this point the image was hashed + signed, we can remove the
392 # protected TLVs from the payload (will be re-added later)
393 if protected_tlv_off is not None:
394 self.payload = self.payload[:protected_tlv_off]
395
Fabio Utzig06b77b82018-08-23 16:01:16 -0300396 if enckey is not None:
397 plainkey = os.urandom(16)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300398
399 if isinstance(enckey, rsa.RSAPublic):
400 cipherkey = enckey._get_public().encrypt(
401 plainkey, padding.OAEP(
402 mgf=padding.MGF1(algorithm=hashes.SHA256()),
403 algorithm=hashes.SHA256(),
404 label=None))
Fabio Utzig9a492d52020-01-15 11:31:52 -0300405 self.enctlv_len = len(cipherkey)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300406 tlv.add('ENCRSA2048', cipherkey)
Fabio Utzig960b4c52020-04-02 13:07:12 -0300407 elif isinstance(enckey, (ecdsa.ECDSA256P1Public,
408 x25519.X25519Public)):
409 cipherkey, mac, pubk = self.ecies_hkdf(enckey, plainkey)
Fabio Utzig9a492d52020-01-15 11:31:52 -0300410 enctlv = pubk + mac + cipherkey
411 self.enctlv_len = len(enctlv)
Fabio Utzig960b4c52020-04-02 13:07:12 -0300412 if isinstance(enckey, ecdsa.ECDSA256P1Public):
413 tlv.add('ENCEC256', enctlv)
414 else:
415 tlv.add('ENCX25519', enctlv)
Fabio Utzig06b77b82018-08-23 16:01:16 -0300416
417 nonce = bytes([0] * 16)
418 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
419 backend=default_backend())
420 encryptor = cipher.encryptor()
421 img = bytes(self.payload[self.header_size:])
Fabio Utzig510fddb2019-09-12 12:15:36 -0300422 self.payload[self.header_size:] = \
423 encryptor.update(img) + encryptor.finalize()
Fabio Utzig06b77b82018-08-23 16:01:16 -0300424
Fabio Utzig510fddb2019-09-12 12:15:36 -0300425 self.payload += prot_tlv.get()
426 self.payload += tlv.get()
David Brown23f91ad2017-05-16 11:38:17 -0600427
Fabio Utzig9a492d52020-01-15 11:31:52 -0300428 self.check_trailer()
429
David Vinczeda8c9192019-03-26 17:17:41 +0100430 def add_header(self, enckey, protected_tlv_size):
Fabio Utzigcd284062018-11-30 11:05:45 -0200431 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600432
David Brown0f0c6a82017-06-08 09:26:24 -0600433 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300434 if enckey is not None:
435 flags |= IMAGE_F['ENCRYPTED']
David Vincze1e0c5442020-04-07 14:12:33 +0200436 if self.load_addr != 0:
437 # Indicates that this image should be loaded into RAM
438 # instead of run directly from flash.
439 flags |= IMAGE_F['RAM_LOAD']
David Brown23f91ad2017-05-16 11:38:17 -0600440
Mark Schultea66c6872018-09-26 17:24:40 -0700441 e = STRUCT_ENDIAN_DICT[self.endian]
442 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100443 # type ImageHdr struct {
444 'I' + # Magic uint32
445 'I' + # LoadAddr uint32
446 'H' + # HdrSz uint16
447 'H' + # PTLVSz uint16
448 'I' + # ImgSz uint32
449 'I' + # Flags uint32
450 'BBHI' + # Vers ImageVersion
451 'I' # Pad1 uint32
452 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600453 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
454 header = struct.pack(fmt,
455 IMAGE_MAGIC,
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000456 self.load_addr,
David Brown23f91ad2017-05-16 11:38:17 -0600457 self.header_size,
Fabio Utzig510fddb2019-09-12 12:15:36 -0300458 protected_tlv_size, # TLV Info header + Protected TLVs
459 len(self.payload) - self.header_size, # ImageSz
460 flags,
David Brown23f91ad2017-05-16 11:38:17 -0600461 self.version.major,
462 self.version.minor or 0,
463 self.version.revision or 0,
464 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100465 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600466 self.payload = bytearray(self.payload)
467 self.payload[:len(header)] = header
468
Fabio Utzig9a492d52020-01-15 11:31:52 -0300469 def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey,
470 save_enctlv, enctlv_len):
Fabio Utzig519285f2018-06-04 11:11:53 -0300471 # NOTE: should already be checked by the argument parser
Fabio Utzig649d80f2019-09-12 10:26:23 -0300472 magic_size = 16
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700473 if overwrite_only:
Fabio Utzig649d80f2019-09-12 10:26:23 -0300474 return MAX_ALIGN * 2 + magic_size
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700475 else:
476 if write_size not in set([1, 2, 4, 8]):
Fabio Utzig1f508922020-01-15 11:37:51 -0300477 raise click.BadParameter("Invalid alignment: {}".format(
478 write_size))
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700479 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
Fabio Utzig649d80f2019-09-12 10:26:23 -0300480 trailer = m * 3 * write_size # status area
481 if enckey is not None:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300482 if save_enctlv:
483 # TLV saved by the bootloader is aligned
484 keylen = (int((enctlv_len - 1) / MAX_ALIGN) + 1) * MAX_ALIGN
485 else:
486 keylen = 16
487 trailer += keylen * 2 # encryption keys
Fabio Utzig88282802019-10-17 11:17:18 -0300488 trailer += MAX_ALIGN * 4 # image_ok/copy_done/swap_info/swap_size
Fabio Utzig649d80f2019-09-12 10:26:23 -0300489 trailer += magic_size
490 return trailer
Fabio Utzig519285f2018-06-04 11:11:53 -0300491
Fabio Utzig263d4392018-06-05 10:37:35 -0300492 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600493 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700494 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300495 self.overwrite_only, self.enckey,
496 self.save_enctlv, self.enctlv_len)
David Brown23f91ad2017-05-16 11:38:17 -0600497 padding = size - (len(self.payload) + tsize)
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100498 pbytes = bytearray([self.erased_val] * padding)
499 pbytes += bytearray([self.erased_val] * (tsize - len(boot_magic)))
500 if self.confirm and not self.overwrite_only:
501 pbytes[-MAX_ALIGN] = 0x01 # image_ok = 0x01
Fabio Utzige08f0872017-06-28 18:12:16 -0300502 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600503 self.payload += pbytes
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300504
505 @staticmethod
506 def verify(imgfile, key):
507 with open(imgfile, "rb") as f:
508 b = f.read()
509
510 magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
Marek Pietae9555102019-08-08 16:08:16 +0200511 version = struct.unpack('BBHI', b[20:28])
512
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300513 if magic != IMAGE_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200514 return VerifyResult.INVALID_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300515
516 tlv_info = b[header_size+img_size:header_size+img_size+TLV_INFO_SIZE]
517 magic, tlv_tot = struct.unpack('HH', tlv_info)
518 if magic != TLV_INFO_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200519 return VerifyResult.INVALID_TLV_INFO_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300520
521 sha = hashlib.sha256()
522 sha.update(b[:header_size+img_size])
523 digest = sha.digest()
524
525 tlv_off = header_size + img_size
526 tlv_end = tlv_off + tlv_tot
527 tlv_off += TLV_INFO_SIZE # skip tlv info
528 while tlv_off < tlv_end:
529 tlv = b[tlv_off:tlv_off+TLV_SIZE]
530 tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
531 if tlv_type == TLV_VALUES["SHA256"]:
532 off = tlv_off + TLV_SIZE
533 if digest == b[off:off+tlv_len]:
534 if key is None:
Marek Pietae9555102019-08-08 16:08:16 +0200535 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300536 else:
Marek Pietae9555102019-08-08 16:08:16 +0200537 return VerifyResult.INVALID_HASH, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300538 elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
539 off = tlv_off + TLV_SIZE
540 tlv_sig = b[off:off+tlv_len]
541 payload = b[:header_size+img_size]
542 try:
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300543 if hasattr(key, 'verify'):
544 key.verify(tlv_sig, payload)
545 else:
546 key.verify_digest(tlv_sig, digest)
Marek Pietae9555102019-08-08 16:08:16 +0200547 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300548 except InvalidSignature:
549 # continue to next TLV
550 pass
551 tlv_off += TLV_SIZE + tlv_len
Marek Pietae9555102019-08-08 16:08:16 +0200552 return VerifyResult.INVALID_SIGNATURE, None