blob: bd681c7250fa0cb78e5e6f63fcd27269f8366d71 [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 Utzig7a3b2602019-10-22 09:56:44 -030029from .keys import rsa, ecdsa
30from cryptography.hazmat.primitives.asymmetric import ec, padding
Fabio Utzig06b77b82018-08-23 16:01:16 -030031from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Fabio Utzig7a3b2602019-10-22 09:56:44 -030032from cryptography.hazmat.primitives.kdf.hkdf import HKDF
33from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
Fabio Utzig06b77b82018-08-23 16:01:16 -030034from cryptography.hazmat.backends import default_backend
Fabio Utzig7a3b2602019-10-22 09:56:44 -030035from cryptography.hazmat.primitives import hashes, hmac
Fabio Utzig4a5477a2019-05-27 15:45:08 -030036from cryptography.exceptions import InvalidSignature
David Brown23f91ad2017-05-16 11:38:17 -060037
David Brown72e7a512017-09-01 11:08:23 -060038IMAGE_MAGIC = 0x96f3b83d
David Brown23f91ad2017-05-16 11:38:17 -060039IMAGE_HEADER_SIZE = 32
Carles Cufi37d052f2018-01-30 16:40:10 +010040BIN_EXT = "bin"
41INTEL_HEX_EXT = "hex"
Fabio Utzig519285f2018-06-04 11:11:53 -030042DEFAULT_MAX_SECTORS = 128
Fabio Utzig649d80f2019-09-12 10:26:23 -030043MAX_ALIGN = 8
David Vinczeda8c9192019-03-26 17:17:41 +010044DEP_IMAGES_KEY = "images"
45DEP_VERSIONS_KEY = "versions"
David Vincze71b8f982020-03-17 19:08:12 +010046MAX_SW_TYPE_LENGTH = 12 # Bytes
David Brown23f91ad2017-05-16 11:38:17 -060047
48# Image header flags.
49IMAGE_F = {
50 'PIC': 0x0000001,
Fabio Utzig06b77b82018-08-23 16:01:16 -030051 'NON_BOOTABLE': 0x0000010,
52 'ENCRYPTED': 0x0000004,
53}
David Brown23f91ad2017-05-16 11:38:17 -060054
55TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060056 'KEYHASH': 0x01,
David Vinczedde178d2020-03-26 20:06:01 +010057 'PUBKEY': 0x02,
David Brown27648b82017-08-31 10:40:29 -060058 'SHA256': 0x10,
59 'RSA2048': 0x20,
60 'ECDSA224': 0x21,
Fabio Utzig06b77b82018-08-23 16:01:16 -030061 'ECDSA256': 0x22,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030062 'RSA3072': 0x23,
Fabio Utzig8101d1f2019-05-09 15:03:22 -030063 'ED25519': 0x24,
Fabio Utzig06b77b82018-08-23 16:01:16 -030064 'ENCRSA2048': 0x30,
65 'ENCKW128': 0x31,
Fabio Utzig7a3b2602019-10-22 09:56:44 -030066 'ENCEC256': 0x32,
David Vincze1a7a6902020-02-18 15:05:16 +010067 'DEPENDENCY': 0x40,
68 'SEC_CNT': 0x50,
David Vincze71b8f982020-03-17 19:08:12 +010069 'BOOT_RECORD': 0x60,
Fabio Utzig06b77b82018-08-23 16:01:16 -030070}
David Brown23f91ad2017-05-16 11:38:17 -060071
Fabio Utzig4a5477a2019-05-27 15:45:08 -030072TLV_SIZE = 4
David Brownf5b33d82017-09-01 10:58:27 -060073TLV_INFO_SIZE = 4
74TLV_INFO_MAGIC = 0x6907
Fabio Utzig510fddb2019-09-12 12:15:36 -030075TLV_PROT_INFO_MAGIC = 0x6908
David Brown23f91ad2017-05-16 11:38:17 -060076
David Brown23f91ad2017-05-16 11:38:17 -060077boot_magic = bytes([
78 0x77, 0xc2, 0x95, 0xf3,
79 0x60, 0xd2, 0xef, 0x7f,
80 0x35, 0x52, 0x50, 0x0f,
81 0x2c, 0xb6, 0x79, 0x80, ])
82
Mark Schultea66c6872018-09-26 17:24:40 -070083STRUCT_ENDIAN_DICT = {
84 'little': '<',
85 'big': '>'
86}
87
Fabio Utzig4a5477a2019-05-27 15:45:08 -030088VerifyResult = Enum('VerifyResult',
89 """
90 OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH
91 INVALID_SIGNATURE
92 """)
93
94
David Brown23f91ad2017-05-16 11:38:17 -060095class TLV():
Fabio Utzig510fddb2019-09-12 12:15:36 -030096 def __init__(self, endian, magic=TLV_INFO_MAGIC):
97 self.magic = magic
David Brown23f91ad2017-05-16 11:38:17 -060098 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -070099 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -0600100
Fabio Utzig510fddb2019-09-12 12:15:36 -0300101 def __len__(self):
102 return TLV_INFO_SIZE + len(self.buf)
103
David Brown23f91ad2017-05-16 11:38:17 -0600104 def add(self, kind, payload):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300105 """
106 Add a TLV record. Kind should be a string found in TLV_VALUES above.
107 """
Mark Schultea66c6872018-09-26 17:24:40 -0700108 e = STRUCT_ENDIAN_DICT[self.endian]
109 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -0600110 self.buf += buf
111 self.buf += payload
112
113 def get(self):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300114 if len(self.buf) == 0:
115 return bytes()
Mark Schultea66c6872018-09-26 17:24:40 -0700116 e = STRUCT_ENDIAN_DICT[self.endian]
Fabio Utzig510fddb2019-09-12 12:15:36 -0300117 header = struct.pack(e + 'HH', self.magic, len(self))
David Brownf5b33d82017-09-01 10:58:27 -0600118 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -0600119
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200120
David Brown23f91ad2017-05-16 11:38:17 -0600121class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +0100122
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200123 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100124 pad_header=False, pad=False, confirm=False, align=1,
125 slot_size=0, max_sectors=DEFAULT_MAX_SECTORS,
126 overwrite_only=False, endian="little", load_addr=0,
127 erased_val=None, save_enctlv=False, security_counter=None):
David Brown23f91ad2017-05-16 11:38:17 -0600128 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200129 self.header_size = header_size
130 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -0600131 self.pad = pad
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100132 self.confirm = confirm
Fabio Utzig263d4392018-06-05 10:37:35 -0300133 self.align = align
134 self.slot_size = slot_size
135 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700136 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700137 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200138 self.base_addr = None
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000139 self.load_addr = 0 if load_addr is None else load_addr
Fabio Utzigcb080732020-02-07 12:01:39 -0300140 self.erased_val = 0xff if erased_val is None else int(erased_val, 0)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200141 self.payload = []
Fabio Utzig649d80f2019-09-12 10:26:23 -0300142 self.enckey = None
Fabio Utzig9a492d52020-01-15 11:31:52 -0300143 self.save_enctlv = save_enctlv
144 self.enctlv_len = 0
David Brown23f91ad2017-05-16 11:38:17 -0600145
David Vincze1a7a6902020-02-18 15:05:16 +0100146 if security_counter == 'auto':
147 # Security counter has not been explicitly provided,
148 # generate it from the version number
149 self.security_counter = ((self.version.major << 24)
150 + (self.version.minor << 16)
151 + self.version.revision)
152 else:
153 self.security_counter = security_counter
154
David Brown23f91ad2017-05-16 11:38:17 -0600155 def __repr__(self):
David Vincze1a7a6902020-02-18 15:05:16 +0100156 return "<Image version={}, header_size={}, security_counter={}, \
157 base_addr={}, load_addr={}, align={}, slot_size={}, \
158 max_sectors={}, overwrite_only={}, endian={} format={}, \
159 payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300160 self.version,
161 self.header_size,
David Vincze1a7a6902020-02-18 15:05:16 +0100162 self.security_counter,
Fabio Utzig263d4392018-06-05 10:37:35 -0300163 self.base_addr if self.base_addr is not None else "N/A",
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000164 self.load_addr,
Fabio Utzig263d4392018-06-05 10:37:35 -0300165 self.align,
166 self.slot_size,
167 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700168 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700169 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300170 self.__class__.__name__,
171 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600172
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200173 def load(self, path):
174 """Load an image from a given file"""
175 ext = os.path.splitext(path)[1][1:].lower()
Fabio Utzig1f508922020-01-15 11:37:51 -0300176 try:
177 if ext == INTEL_HEX_EXT:
178 ih = IntelHex(path)
179 self.payload = ih.tobinarray()
180 self.base_addr = ih.minaddr()
181 else:
182 with open(path, 'rb') as f:
183 self.payload = f.read()
184 except FileNotFoundError:
185 raise click.UsageError("Input file not found")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200186
187 # Add the image header if needed.
188 if self.pad_header and self.header_size > 0:
189 if self.base_addr:
190 # Adjust base_addr for new header
191 self.base_addr -= self.header_size
Fabio Utzig9117fde2019-10-17 11:11:46 -0300192 self.payload = bytes([self.erased_val] * self.header_size) + \
193 self.payload
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200194
Fabio Utzig9a492d52020-01-15 11:31:52 -0300195 self.check_header()
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200196
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300197 def save(self, path, hex_addr=None):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200198 """Save an image from a given file"""
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200199 ext = os.path.splitext(path)[1][1:].lower()
200 if ext == INTEL_HEX_EXT:
201 # input was in binary format, but HEX needs to know the base addr
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300202 if self.base_addr is None and hex_addr is None:
Fabio Utzig1f508922020-01-15 11:37:51 -0300203 raise click.UsageError("No address exists in input file "
204 "neither was it provided by user")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200205 h = IntelHex()
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300206 if hex_addr is not None:
207 self.base_addr = hex_addr
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200208 h.frombytes(bytes=self.payload, offset=self.base_addr)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300209 if self.pad:
Fabio Utzig2269f472019-10-17 11:14:33 -0300210 trailer_size = self._trailer_size(self.align, self.max_sectors,
211 self.overwrite_only,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300212 self.enckey,
213 self.save_enctlv,
214 self.enctlv_len)
Fabio Utzig2269f472019-10-17 11:14:33 -0300215 trailer_addr = (self.base_addr + self.slot_size) - trailer_size
216 padding = bytes([self.erased_val] *
217 (trailer_size - len(boot_magic))) + boot_magic
218 h.puts(trailer_addr, padding)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200219 h.tofile(path, 'hex')
220 else:
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300221 if self.pad:
222 self.pad_to(self.slot_size)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200223 with open(path, 'wb') as f:
224 f.write(self.payload)
225
Fabio Utzig9a492d52020-01-15 11:31:52 -0300226 def check_header(self):
Fabio Utzigf5556c32019-10-23 11:00:27 -0300227 if self.header_size > 0 and not self.pad_header:
David Brown23f91ad2017-05-16 11:38:17 -0600228 if any(v != 0 for v in self.payload[0:self.header_size]):
Fabio Utzig9a492d52020-01-15 11:31:52 -0300229 raise click.UsageError("Header padding was not requested and "
230 "image does not start with zeros")
231
232 def check_trailer(self):
Fabio Utzig263d4392018-06-05 10:37:35 -0300233 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700234 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300235 self.overwrite_only, self.enckey,
236 self.save_enctlv, self.enctlv_len)
Fabio Utzig263d4392018-06-05 10:37:35 -0300237 padding = self.slot_size - (len(self.payload) + tsize)
238 if padding < 0:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300239 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds " \
240 "requested size 0x{:x}".format(
241 len(self.payload), tsize, self.slot_size)
242 raise click.UsageError(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600243
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300244 def ecies_p256_hkdf(self, enckey, plainkey):
245 newpk = ec.generate_private_key(ec.SECP256R1(), default_backend())
246 shared = newpk.exchange(ec.ECDH(), enckey._get_public())
247 derived_key = HKDF(
248 algorithm=hashes.SHA256(), length=48, salt=None,
249 info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared)
250 encryptor = Cipher(algorithms.AES(derived_key[:16]),
251 modes.CTR(bytes([0] * 16)),
252 backend=default_backend()).encryptor()
253 cipherkey = encryptor.update(plainkey) + encryptor.finalize()
254 mac = hmac.HMAC(derived_key[16:], hashes.SHA256(),
255 backend=default_backend())
256 mac.update(cipherkey)
257 ciphermac = mac.finalize()
258 pubk = newpk.public_key().public_bytes(
259 encoding=Encoding.X962,
260 format=PublicFormat.UncompressedPoint)
261 return cipherkey, ciphermac, pubk
262
David Vinczedde178d2020-03-26 20:06:01 +0100263 def create(self, key, public_key_format, enckey, dependencies=None,
264 sw_type=None):
Fabio Utzig649d80f2019-09-12 10:26:23 -0300265 self.enckey = enckey
266
David Vincze71b8f982020-03-17 19:08:12 +0100267 # Calculate the hash of the public key
268 if key is not None:
269 pub = key.get_public_bytes()
270 sha = hashlib.sha256()
271 sha.update(pub)
272 pubbytes = sha.digest()
273 else:
274 pubbytes = bytes(hashlib.sha256().digest_size)
275
David Vincze1a7a6902020-02-18 15:05:16 +0100276 protected_tlv_size = 0
277
278 if self.security_counter is not None:
279 # Size of the security counter TLV: header ('HH') + payload ('I')
280 # = 4 + 4 = 8 Bytes
281 protected_tlv_size += TLV_SIZE + 4
282
David Vincze71b8f982020-03-17 19:08:12 +0100283 if sw_type is not None:
284 if len(sw_type) > MAX_SW_TYPE_LENGTH:
285 msg = "'{}' is too long ({} characters) for sw_type. Its " \
286 "maximum allowed length is 12 characters.".format(
287 sw_type, len(sw_type))
288 raise click.UsageError(msg)
289
290 image_version = (str(self.version.major) + '.'
291 + str(self.version.minor) + '.'
292 + str(self.version.revision))
293
294 # The image hash is computed over the image header, the image
295 # itself and the protected TLV area. However, the boot record TLV
296 # (which is part of the protected area) should contain this hash
297 # before it is even calculated. For this reason the script fills
298 # this field with zeros and the bootloader will insert the right
299 # value later.
300 digest = bytes(hashlib.sha256().digest_size)
301
302 # Create CBOR encoded boot record
303 boot_record = create_sw_component_data(sw_type, image_version,
304 "SHA256", digest,
305 pubbytes)
306
307 protected_tlv_size += TLV_SIZE + len(boot_record)
308
David Vincze1a7a6902020-02-18 15:05:16 +0100309 if dependencies is not None:
310 # Size of a Dependency TLV = Header ('HH') + Payload('IBBHI')
311 # = 4 + 12 = 16 Bytes
David Vinczeda8c9192019-03-26 17:17:41 +0100312 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
David Vincze1a7a6902020-02-18 15:05:16 +0100313 protected_tlv_size += (dependencies_num * 16)
314
315 if protected_tlv_size != 0:
316 # Add the size of the TLV info header
317 protected_tlv_size += TLV_INFO_SIZE
David Vinczeda8c9192019-03-26 17:17:41 +0100318
Fabio Utzig510fddb2019-09-12 12:15:36 -0300319 # At this point the image is already on the payload, this adds
320 # the header to the payload as well
David Vinczeda8c9192019-03-26 17:17:41 +0100321 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600322
Fabio Utzig510fddb2019-09-12 12:15:36 -0300323 prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC)
David Brown23f91ad2017-05-16 11:38:17 -0600324
Fabio Utzig510fddb2019-09-12 12:15:36 -0300325 # Protected TLVs must be added first, because they are also included
326 # in the hash calculation
327 protected_tlv_off = None
David Vinczeda8c9192019-03-26 17:17:41 +0100328 if protected_tlv_size != 0:
David Vincze1a7a6902020-02-18 15:05:16 +0100329
330 e = STRUCT_ENDIAN_DICT[self.endian]
331
332 if self.security_counter is not None:
333 payload = struct.pack(e + 'I', self.security_counter)
334 prot_tlv.add('SEC_CNT', payload)
335
David Vincze71b8f982020-03-17 19:08:12 +0100336 if sw_type is not None:
337 prot_tlv.add('BOOT_RECORD', boot_record)
338
David Vincze1a7a6902020-02-18 15:05:16 +0100339 if dependencies is not None:
340 for i in range(dependencies_num):
341 payload = struct.pack(
342 e + 'B3x'+'BBHI',
343 int(dependencies[DEP_IMAGES_KEY][i]),
344 dependencies[DEP_VERSIONS_KEY][i].major,
345 dependencies[DEP_VERSIONS_KEY][i].minor,
346 dependencies[DEP_VERSIONS_KEY][i].revision,
347 dependencies[DEP_VERSIONS_KEY][i].build
348 )
349 prot_tlv.add('DEPENDENCY', payload)
David Vinczeda8c9192019-03-26 17:17:41 +0100350
Fabio Utzig510fddb2019-09-12 12:15:36 -0300351 protected_tlv_off = len(self.payload)
352 self.payload += prot_tlv.get()
353
354 tlv = TLV(self.endian)
David Vinczeda8c9192019-03-26 17:17:41 +0100355
David Brown23f91ad2017-05-16 11:38:17 -0600356 # Note that ecdsa wants to do the hashing itself, which means
357 # we get to hash it twice.
358 sha = hashlib.sha256()
359 sha.update(self.payload)
360 digest = sha.digest()
361
362 tlv.add('SHA256', digest)
363
David Brown0f0c6a82017-06-08 09:26:24 -0600364 if key is not None:
David Vinczedde178d2020-03-26 20:06:01 +0100365 if public_key_format == 'hash':
366 tlv.add('KEYHASH', pubbytes)
367 else:
368 tlv.add('PUBKEY', pub)
David Brown43cda332017-09-01 09:53:23 -0600369
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300370 # `sign` expects the full image payload (sha256 done internally),
371 # while `sign_digest` expects only the digest of the payload
372
373 if hasattr(key, 'sign'):
374 sig = key.sign(bytes(self.payload))
375 else:
376 sig = key.sign_digest(digest)
David Brown0f0c6a82017-06-08 09:26:24 -0600377 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600378
Fabio Utzig510fddb2019-09-12 12:15:36 -0300379 # At this point the image was hashed + signed, we can remove the
380 # protected TLVs from the payload (will be re-added later)
381 if protected_tlv_off is not None:
382 self.payload = self.payload[:protected_tlv_off]
383
Fabio Utzig06b77b82018-08-23 16:01:16 -0300384 if enckey is not None:
385 plainkey = os.urandom(16)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300386
387 if isinstance(enckey, rsa.RSAPublic):
388 cipherkey = enckey._get_public().encrypt(
389 plainkey, padding.OAEP(
390 mgf=padding.MGF1(algorithm=hashes.SHA256()),
391 algorithm=hashes.SHA256(),
392 label=None))
Fabio Utzig9a492d52020-01-15 11:31:52 -0300393 self.enctlv_len = len(cipherkey)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300394 tlv.add('ENCRSA2048', cipherkey)
395 elif isinstance(enckey, ecdsa.ECDSA256P1Public):
396 cipherkey, mac, pubk = self.ecies_p256_hkdf(enckey, plainkey)
Fabio Utzig9a492d52020-01-15 11:31:52 -0300397 enctlv = pubk + mac + cipherkey
398 self.enctlv_len = len(enctlv)
399 tlv.add('ENCEC256', enctlv)
Fabio Utzig06b77b82018-08-23 16:01:16 -0300400
401 nonce = bytes([0] * 16)
402 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
403 backend=default_backend())
404 encryptor = cipher.encryptor()
405 img = bytes(self.payload[self.header_size:])
Fabio Utzig510fddb2019-09-12 12:15:36 -0300406 self.payload[self.header_size:] = \
407 encryptor.update(img) + encryptor.finalize()
Fabio Utzig06b77b82018-08-23 16:01:16 -0300408
Fabio Utzig510fddb2019-09-12 12:15:36 -0300409 self.payload += prot_tlv.get()
410 self.payload += tlv.get()
David Brown23f91ad2017-05-16 11:38:17 -0600411
Fabio Utzig9a492d52020-01-15 11:31:52 -0300412 self.check_trailer()
413
David Vinczeda8c9192019-03-26 17:17:41 +0100414 def add_header(self, enckey, protected_tlv_size):
Fabio Utzigcd284062018-11-30 11:05:45 -0200415 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600416
David Brown0f0c6a82017-06-08 09:26:24 -0600417 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300418 if enckey is not None:
419 flags |= IMAGE_F['ENCRYPTED']
David Brown23f91ad2017-05-16 11:38:17 -0600420
Mark Schultea66c6872018-09-26 17:24:40 -0700421 e = STRUCT_ENDIAN_DICT[self.endian]
422 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100423 # type ImageHdr struct {
424 'I' + # Magic uint32
425 'I' + # LoadAddr uint32
426 'H' + # HdrSz uint16
427 'H' + # PTLVSz uint16
428 'I' + # ImgSz uint32
429 'I' + # Flags uint32
430 'BBHI' + # Vers ImageVersion
431 'I' # Pad1 uint32
432 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600433 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
434 header = struct.pack(fmt,
435 IMAGE_MAGIC,
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000436 self.load_addr,
David Brown23f91ad2017-05-16 11:38:17 -0600437 self.header_size,
Fabio Utzig510fddb2019-09-12 12:15:36 -0300438 protected_tlv_size, # TLV Info header + Protected TLVs
439 len(self.payload) - self.header_size, # ImageSz
440 flags,
David Brown23f91ad2017-05-16 11:38:17 -0600441 self.version.major,
442 self.version.minor or 0,
443 self.version.revision or 0,
444 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100445 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600446 self.payload = bytearray(self.payload)
447 self.payload[:len(header)] = header
448
Fabio Utzig9a492d52020-01-15 11:31:52 -0300449 def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey,
450 save_enctlv, enctlv_len):
Fabio Utzig519285f2018-06-04 11:11:53 -0300451 # NOTE: should already be checked by the argument parser
Fabio Utzig649d80f2019-09-12 10:26:23 -0300452 magic_size = 16
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700453 if overwrite_only:
Fabio Utzig649d80f2019-09-12 10:26:23 -0300454 return MAX_ALIGN * 2 + magic_size
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700455 else:
456 if write_size not in set([1, 2, 4, 8]):
Fabio Utzig1f508922020-01-15 11:37:51 -0300457 raise click.BadParameter("Invalid alignment: {}".format(
458 write_size))
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700459 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
Fabio Utzig649d80f2019-09-12 10:26:23 -0300460 trailer = m * 3 * write_size # status area
461 if enckey is not None:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300462 if save_enctlv:
463 # TLV saved by the bootloader is aligned
464 keylen = (int((enctlv_len - 1) / MAX_ALIGN) + 1) * MAX_ALIGN
465 else:
466 keylen = 16
467 trailer += keylen * 2 # encryption keys
Fabio Utzig88282802019-10-17 11:17:18 -0300468 trailer += MAX_ALIGN * 4 # image_ok/copy_done/swap_info/swap_size
Fabio Utzig649d80f2019-09-12 10:26:23 -0300469 trailer += magic_size
470 return trailer
Fabio Utzig519285f2018-06-04 11:11:53 -0300471
Fabio Utzig263d4392018-06-05 10:37:35 -0300472 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600473 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700474 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300475 self.overwrite_only, self.enckey,
476 self.save_enctlv, self.enctlv_len)
David Brown23f91ad2017-05-16 11:38:17 -0600477 padding = size - (len(self.payload) + tsize)
Henrik Brix Andersen0ce958e2020-03-11 14:04:11 +0100478 pbytes = bytearray([self.erased_val] * padding)
479 pbytes += bytearray([self.erased_val] * (tsize - len(boot_magic)))
480 if self.confirm and not self.overwrite_only:
481 pbytes[-MAX_ALIGN] = 0x01 # image_ok = 0x01
Fabio Utzige08f0872017-06-28 18:12:16 -0300482 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600483 self.payload += pbytes
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300484
485 @staticmethod
486 def verify(imgfile, key):
487 with open(imgfile, "rb") as f:
488 b = f.read()
489
490 magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
Marek Pietae9555102019-08-08 16:08:16 +0200491 version = struct.unpack('BBHI', b[20:28])
492
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300493 if magic != IMAGE_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200494 return VerifyResult.INVALID_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300495
496 tlv_info = b[header_size+img_size:header_size+img_size+TLV_INFO_SIZE]
497 magic, tlv_tot = struct.unpack('HH', tlv_info)
498 if magic != TLV_INFO_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200499 return VerifyResult.INVALID_TLV_INFO_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300500
501 sha = hashlib.sha256()
502 sha.update(b[:header_size+img_size])
503 digest = sha.digest()
504
505 tlv_off = header_size + img_size
506 tlv_end = tlv_off + tlv_tot
507 tlv_off += TLV_INFO_SIZE # skip tlv info
508 while tlv_off < tlv_end:
509 tlv = b[tlv_off:tlv_off+TLV_SIZE]
510 tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
511 if tlv_type == TLV_VALUES["SHA256"]:
512 off = tlv_off + TLV_SIZE
513 if digest == b[off:off+tlv_len]:
514 if key is None:
Marek Pietae9555102019-08-08 16:08:16 +0200515 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300516 else:
Marek Pietae9555102019-08-08 16:08:16 +0200517 return VerifyResult.INVALID_HASH, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300518 elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
519 off = tlv_off + TLV_SIZE
520 tlv_sig = b[off:off+tlv_len]
521 payload = b[:header_size+img_size]
522 try:
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300523 if hasattr(key, 'verify'):
524 key.verify(tlv_sig, payload)
525 else:
526 key.verify_digest(tlv_sig, digest)
Marek Pietae9555102019-08-08 16:08:16 +0200527 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300528 except InvalidSignature:
529 # continue to next TLV
530 pass
531 tlv_off += TLV_SIZE + tlv_len
Marek Pietae9555102019-08-08 16:08:16 +0200532 return VerifyResult.INVALID_SIGNATURE, None