blob: d6899ef76a0b2e144c6c779eea13d521dbc51b44 [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 Vinczeda8c9192019-03-26 17:17:41 +01003# Copyright 2019 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
Fabio Utzig9a492d52020-01-15 11:31:52 -030022import click
Fabio Utzig4a5477a2019-05-27 15:45:08 -030023from enum import Enum
Carles Cufi37d052f2018-01-30 16:40:10 +010024from intelhex import IntelHex
David Brown23f91ad2017-05-16 11:38:17 -060025import hashlib
26import struct
Carles Cufi37d052f2018-01-30 16:40:10 +010027import os.path
Fabio Utzig7a3b2602019-10-22 09:56:44 -030028from .keys import rsa, ecdsa
29from cryptography.hazmat.primitives.asymmetric import ec, padding
Fabio Utzig06b77b82018-08-23 16:01:16 -030030from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Fabio Utzig7a3b2602019-10-22 09:56:44 -030031from cryptography.hazmat.primitives.kdf.hkdf import HKDF
32from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
Fabio Utzig06b77b82018-08-23 16:01:16 -030033from cryptography.hazmat.backends import default_backend
Fabio Utzig7a3b2602019-10-22 09:56:44 -030034from cryptography.hazmat.primitives import hashes, hmac
Fabio Utzig4a5477a2019-05-27 15:45:08 -030035from cryptography.exceptions import InvalidSignature
David Brown23f91ad2017-05-16 11:38:17 -060036
David Brown72e7a512017-09-01 11:08:23 -060037IMAGE_MAGIC = 0x96f3b83d
David Brown23f91ad2017-05-16 11:38:17 -060038IMAGE_HEADER_SIZE = 32
Carles Cufi37d052f2018-01-30 16:40:10 +010039BIN_EXT = "bin"
40INTEL_HEX_EXT = "hex"
Fabio Utzig519285f2018-06-04 11:11:53 -030041DEFAULT_MAX_SECTORS = 128
Fabio Utzig649d80f2019-09-12 10:26:23 -030042MAX_ALIGN = 8
David Vinczeda8c9192019-03-26 17:17:41 +010043DEP_IMAGES_KEY = "images"
44DEP_VERSIONS_KEY = "versions"
David Brown23f91ad2017-05-16 11:38:17 -060045
46# Image header flags.
47IMAGE_F = {
48 'PIC': 0x0000001,
Fabio Utzig06b77b82018-08-23 16:01:16 -030049 'NON_BOOTABLE': 0x0000010,
50 'ENCRYPTED': 0x0000004,
51}
David Brown23f91ad2017-05-16 11:38:17 -060052
53TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060054 'KEYHASH': 0x01,
David Brown27648b82017-08-31 10:40:29 -060055 'SHA256': 0x10,
56 'RSA2048': 0x20,
57 'ECDSA224': 0x21,
Fabio Utzig06b77b82018-08-23 16:01:16 -030058 'ECDSA256': 0x22,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030059 'RSA3072': 0x23,
Fabio Utzig8101d1f2019-05-09 15:03:22 -030060 'ED25519': 0x24,
Fabio Utzig06b77b82018-08-23 16:01:16 -030061 'ENCRSA2048': 0x30,
62 'ENCKW128': 0x31,
Fabio Utzig7a3b2602019-10-22 09:56:44 -030063 'ENCEC256': 0x32,
David Vinczeda8c9192019-03-26 17:17:41 +010064 'DEPENDENCY': 0x40
Fabio Utzig06b77b82018-08-23 16:01:16 -030065}
David Brown23f91ad2017-05-16 11:38:17 -060066
Fabio Utzig4a5477a2019-05-27 15:45:08 -030067TLV_SIZE = 4
David Brownf5b33d82017-09-01 10:58:27 -060068TLV_INFO_SIZE = 4
69TLV_INFO_MAGIC = 0x6907
Fabio Utzig510fddb2019-09-12 12:15:36 -030070TLV_PROT_INFO_MAGIC = 0x6908
David Brown23f91ad2017-05-16 11:38:17 -060071
David Brown23f91ad2017-05-16 11:38:17 -060072boot_magic = bytes([
73 0x77, 0xc2, 0x95, 0xf3,
74 0x60, 0xd2, 0xef, 0x7f,
75 0x35, 0x52, 0x50, 0x0f,
76 0x2c, 0xb6, 0x79, 0x80, ])
77
Mark Schultea66c6872018-09-26 17:24:40 -070078STRUCT_ENDIAN_DICT = {
79 'little': '<',
80 'big': '>'
81}
82
Fabio Utzig4a5477a2019-05-27 15:45:08 -030083VerifyResult = Enum('VerifyResult',
84 """
85 OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH
86 INVALID_SIGNATURE
87 """)
88
89
David Brown23f91ad2017-05-16 11:38:17 -060090class TLV():
Fabio Utzig510fddb2019-09-12 12:15:36 -030091 def __init__(self, endian, magic=TLV_INFO_MAGIC):
92 self.magic = magic
David Brown23f91ad2017-05-16 11:38:17 -060093 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -070094 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -060095
Fabio Utzig510fddb2019-09-12 12:15:36 -030096 def __len__(self):
97 return TLV_INFO_SIZE + len(self.buf)
98
David Brown23f91ad2017-05-16 11:38:17 -060099 def add(self, kind, payload):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300100 """
101 Add a TLV record. Kind should be a string found in TLV_VALUES above.
102 """
Mark Schultea66c6872018-09-26 17:24:40 -0700103 e = STRUCT_ENDIAN_DICT[self.endian]
104 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -0600105 self.buf += buf
106 self.buf += payload
107
108 def get(self):
Fabio Utzig510fddb2019-09-12 12:15:36 -0300109 if len(self.buf) == 0:
110 return bytes()
Mark Schultea66c6872018-09-26 17:24:40 -0700111 e = STRUCT_ENDIAN_DICT[self.endian]
Fabio Utzig510fddb2019-09-12 12:15:36 -0300112 header = struct.pack(e + 'HH', self.magic, len(self))
David Brownf5b33d82017-09-01 10:58:27 -0600113 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -0600114
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200115
David Brown23f91ad2017-05-16 11:38:17 -0600116class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +0100117
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200118 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
119 pad_header=False, pad=False, align=1, slot_size=0,
120 max_sectors=DEFAULT_MAX_SECTORS, overwrite_only=False,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300121 endian="little", load_addr=0, erased_val=0xff,
122 save_enctlv=False):
David Brown23f91ad2017-05-16 11:38:17 -0600123 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200124 self.header_size = header_size
125 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -0600126 self.pad = pad
Fabio Utzig263d4392018-06-05 10:37:35 -0300127 self.align = align
128 self.slot_size = slot_size
129 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700130 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700131 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200132 self.base_addr = None
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000133 self.load_addr = 0 if load_addr is None else load_addr
Fabio Utzig9117fde2019-10-17 11:11:46 -0300134 self.erased_val = 0xff if erased_val is None else int(erased_val)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200135 self.payload = []
Fabio Utzig649d80f2019-09-12 10:26:23 -0300136 self.enckey = None
Fabio Utzig9a492d52020-01-15 11:31:52 -0300137 self.save_enctlv = save_enctlv
138 self.enctlv_len = 0
David Brown23f91ad2017-05-16 11:38:17 -0600139
140 def __repr__(self):
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000141 return "<Image version={}, header_size={}, base_addr={}, load_addr={}, \
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700142 align={}, slot_size={}, max_sectors={}, overwrite_only={}, \
Mark Schultea66c6872018-09-26 17:24:40 -0700143 endian={} format={}, payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300144 self.version,
145 self.header_size,
146 self.base_addr if self.base_addr is not None else "N/A",
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000147 self.load_addr,
Fabio Utzig263d4392018-06-05 10:37:35 -0300148 self.align,
149 self.slot_size,
150 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700151 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700152 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300153 self.__class__.__name__,
154 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600155
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200156 def load(self, path):
157 """Load an image from a given file"""
158 ext = os.path.splitext(path)[1][1:].lower()
Fabio Utzig1f508922020-01-15 11:37:51 -0300159 try:
160 if ext == INTEL_HEX_EXT:
161 ih = IntelHex(path)
162 self.payload = ih.tobinarray()
163 self.base_addr = ih.minaddr()
164 else:
165 with open(path, 'rb') as f:
166 self.payload = f.read()
167 except FileNotFoundError:
168 raise click.UsageError("Input file not found")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200169
170 # Add the image header if needed.
171 if self.pad_header and self.header_size > 0:
172 if self.base_addr:
173 # Adjust base_addr for new header
174 self.base_addr -= self.header_size
Fabio Utzig9117fde2019-10-17 11:11:46 -0300175 self.payload = bytes([self.erased_val] * self.header_size) + \
176 self.payload
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200177
Fabio Utzig9a492d52020-01-15 11:31:52 -0300178 self.check_header()
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200179
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300180 def save(self, path, hex_addr=None):
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200181 """Save an image from a given file"""
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200182 ext = os.path.splitext(path)[1][1:].lower()
183 if ext == INTEL_HEX_EXT:
184 # input was in binary format, but HEX needs to know the base addr
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300185 if self.base_addr is None and hex_addr is None:
Fabio Utzig1f508922020-01-15 11:37:51 -0300186 raise click.UsageError("No address exists in input file "
187 "neither was it provided by user")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200188 h = IntelHex()
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300189 if hex_addr is not None:
190 self.base_addr = hex_addr
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200191 h.frombytes(bytes=self.payload, offset=self.base_addr)
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300192 if self.pad:
Fabio Utzig2269f472019-10-17 11:14:33 -0300193 trailer_size = self._trailer_size(self.align, self.max_sectors,
194 self.overwrite_only,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300195 self.enckey,
196 self.save_enctlv,
197 self.enctlv_len)
Fabio Utzig2269f472019-10-17 11:14:33 -0300198 trailer_addr = (self.base_addr + self.slot_size) - trailer_size
199 padding = bytes([self.erased_val] *
200 (trailer_size - len(boot_magic))) + boot_magic
201 h.puts(trailer_addr, padding)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200202 h.tofile(path, 'hex')
203 else:
Fabio Utzigedbabcf2019-10-11 13:03:37 -0300204 if self.pad:
205 self.pad_to(self.slot_size)
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200206 with open(path, 'wb') as f:
207 f.write(self.payload)
208
Fabio Utzig9a492d52020-01-15 11:31:52 -0300209 def check_header(self):
Fabio Utzigf5556c32019-10-23 11:00:27 -0300210 if self.header_size > 0 and not self.pad_header:
David Brown23f91ad2017-05-16 11:38:17 -0600211 if any(v != 0 for v in self.payload[0:self.header_size]):
Fabio Utzig9a492d52020-01-15 11:31:52 -0300212 raise click.UsageError("Header padding was not requested and "
213 "image does not start with zeros")
214
215 def check_trailer(self):
Fabio Utzig263d4392018-06-05 10:37:35 -0300216 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700217 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300218 self.overwrite_only, self.enckey,
219 self.save_enctlv, self.enctlv_len)
Fabio Utzig263d4392018-06-05 10:37:35 -0300220 padding = self.slot_size - (len(self.payload) + tsize)
221 if padding < 0:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300222 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds " \
223 "requested size 0x{:x}".format(
224 len(self.payload), tsize, self.slot_size)
225 raise click.UsageError(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600226
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300227 def ecies_p256_hkdf(self, enckey, plainkey):
228 newpk = ec.generate_private_key(ec.SECP256R1(), default_backend())
229 shared = newpk.exchange(ec.ECDH(), enckey._get_public())
230 derived_key = HKDF(
231 algorithm=hashes.SHA256(), length=48, salt=None,
232 info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared)
233 encryptor = Cipher(algorithms.AES(derived_key[:16]),
234 modes.CTR(bytes([0] * 16)),
235 backend=default_backend()).encryptor()
236 cipherkey = encryptor.update(plainkey) + encryptor.finalize()
237 mac = hmac.HMAC(derived_key[16:], hashes.SHA256(),
238 backend=default_backend())
239 mac.update(cipherkey)
240 ciphermac = mac.finalize()
241 pubk = newpk.public_key().public_bytes(
242 encoding=Encoding.X962,
243 format=PublicFormat.UncompressedPoint)
244 return cipherkey, ciphermac, pubk
245
David Vinczeda8c9192019-03-26 17:17:41 +0100246 def create(self, key, enckey, dependencies=None):
Fabio Utzig649d80f2019-09-12 10:26:23 -0300247 self.enckey = enckey
248
David Vinczeda8c9192019-03-26 17:17:41 +0100249 if dependencies is None:
250 dependencies_num = 0
251 protected_tlv_size = 0
252 else:
253 # Size of a Dependency TLV = Header ('BBH') + Payload('IBBHI')
254 # = 16 Bytes
255 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
256 protected_tlv_size = (dependencies_num * 16) + TLV_INFO_SIZE
257
Fabio Utzig510fddb2019-09-12 12:15:36 -0300258 # At this point the image is already on the payload, this adds
259 # the header to the payload as well
David Vinczeda8c9192019-03-26 17:17:41 +0100260 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600261
Fabio Utzig510fddb2019-09-12 12:15:36 -0300262 prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC)
David Brown23f91ad2017-05-16 11:38:17 -0600263
Fabio Utzig510fddb2019-09-12 12:15:36 -0300264 # Protected TLVs must be added first, because they are also included
265 # in the hash calculation
266 protected_tlv_off = None
David Vinczeda8c9192019-03-26 17:17:41 +0100267 if protected_tlv_size != 0:
268 for i in range(dependencies_num):
269 e = STRUCT_ENDIAN_DICT[self.endian]
270 payload = struct.pack(
David Brownbd7925e2019-07-29 11:11:32 -0600271 e + 'B3x'+'BBHI',
David Vinczeda8c9192019-03-26 17:17:41 +0100272 int(dependencies[DEP_IMAGES_KEY][i]),
273 dependencies[DEP_VERSIONS_KEY][i].major,
274 dependencies[DEP_VERSIONS_KEY][i].minor,
275 dependencies[DEP_VERSIONS_KEY][i].revision,
276 dependencies[DEP_VERSIONS_KEY][i].build
277 )
Fabio Utzig510fddb2019-09-12 12:15:36 -0300278 prot_tlv.add('DEPENDENCY', payload)
David Vinczeda8c9192019-03-26 17:17:41 +0100279
Fabio Utzig510fddb2019-09-12 12:15:36 -0300280 protected_tlv_off = len(self.payload)
281 self.payload += prot_tlv.get()
282
283 tlv = TLV(self.endian)
David Vinczeda8c9192019-03-26 17:17:41 +0100284
David Brown23f91ad2017-05-16 11:38:17 -0600285 # Note that ecdsa wants to do the hashing itself, which means
286 # we get to hash it twice.
287 sha = hashlib.sha256()
288 sha.update(self.payload)
289 digest = sha.digest()
290
291 tlv.add('SHA256', digest)
292
David Brown0f0c6a82017-06-08 09:26:24 -0600293 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600294 pub = key.get_public_bytes()
295 sha = hashlib.sha256()
296 sha.update(pub)
297 pubbytes = sha.digest()
298 tlv.add('KEYHASH', pubbytes)
299
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300300 # `sign` expects the full image payload (sha256 done internally),
301 # while `sign_digest` expects only the digest of the payload
302
303 if hasattr(key, 'sign'):
304 sig = key.sign(bytes(self.payload))
305 else:
306 sig = key.sign_digest(digest)
David Brown0f0c6a82017-06-08 09:26:24 -0600307 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600308
Fabio Utzig510fddb2019-09-12 12:15:36 -0300309 # At this point the image was hashed + signed, we can remove the
310 # protected TLVs from the payload (will be re-added later)
311 if protected_tlv_off is not None:
312 self.payload = self.payload[:protected_tlv_off]
313
Fabio Utzig06b77b82018-08-23 16:01:16 -0300314 if enckey is not None:
315 plainkey = os.urandom(16)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300316
317 if isinstance(enckey, rsa.RSAPublic):
318 cipherkey = enckey._get_public().encrypt(
319 plainkey, padding.OAEP(
320 mgf=padding.MGF1(algorithm=hashes.SHA256()),
321 algorithm=hashes.SHA256(),
322 label=None))
Fabio Utzig9a492d52020-01-15 11:31:52 -0300323 self.enctlv_len = len(cipherkey)
Fabio Utzig7a3b2602019-10-22 09:56:44 -0300324 tlv.add('ENCRSA2048', cipherkey)
325 elif isinstance(enckey, ecdsa.ECDSA256P1Public):
326 cipherkey, mac, pubk = self.ecies_p256_hkdf(enckey, plainkey)
Fabio Utzig9a492d52020-01-15 11:31:52 -0300327 enctlv = pubk + mac + cipherkey
328 self.enctlv_len = len(enctlv)
329 tlv.add('ENCEC256', enctlv)
Fabio Utzig06b77b82018-08-23 16:01:16 -0300330
331 nonce = bytes([0] * 16)
332 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
333 backend=default_backend())
334 encryptor = cipher.encryptor()
335 img = bytes(self.payload[self.header_size:])
Fabio Utzig510fddb2019-09-12 12:15:36 -0300336 self.payload[self.header_size:] = \
337 encryptor.update(img) + encryptor.finalize()
Fabio Utzig06b77b82018-08-23 16:01:16 -0300338
Fabio Utzig510fddb2019-09-12 12:15:36 -0300339 self.payload += prot_tlv.get()
340 self.payload += tlv.get()
David Brown23f91ad2017-05-16 11:38:17 -0600341
Fabio Utzig9a492d52020-01-15 11:31:52 -0300342 self.check_trailer()
343
David Vinczeda8c9192019-03-26 17:17:41 +0100344 def add_header(self, enckey, protected_tlv_size):
Fabio Utzigcd284062018-11-30 11:05:45 -0200345 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600346
David Brown0f0c6a82017-06-08 09:26:24 -0600347 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300348 if enckey is not None:
349 flags |= IMAGE_F['ENCRYPTED']
David Brown23f91ad2017-05-16 11:38:17 -0600350
Mark Schultea66c6872018-09-26 17:24:40 -0700351 e = STRUCT_ENDIAN_DICT[self.endian]
352 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100353 # type ImageHdr struct {
354 'I' + # Magic uint32
355 'I' + # LoadAddr uint32
356 'H' + # HdrSz uint16
357 'H' + # PTLVSz uint16
358 'I' + # ImgSz uint32
359 'I' + # Flags uint32
360 'BBHI' + # Vers ImageVersion
361 'I' # Pad1 uint32
362 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600363 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
364 header = struct.pack(fmt,
365 IMAGE_MAGIC,
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000366 self.load_addr,
David Brown23f91ad2017-05-16 11:38:17 -0600367 self.header_size,
Fabio Utzig510fddb2019-09-12 12:15:36 -0300368 protected_tlv_size, # TLV Info header + Protected TLVs
369 len(self.payload) - self.header_size, # ImageSz
370 flags,
David Brown23f91ad2017-05-16 11:38:17 -0600371 self.version.major,
372 self.version.minor or 0,
373 self.version.revision or 0,
374 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100375 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600376 self.payload = bytearray(self.payload)
377 self.payload[:len(header)] = header
378
Fabio Utzig9a492d52020-01-15 11:31:52 -0300379 def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey,
380 save_enctlv, enctlv_len):
Fabio Utzig519285f2018-06-04 11:11:53 -0300381 # NOTE: should already be checked by the argument parser
Fabio Utzig649d80f2019-09-12 10:26:23 -0300382 magic_size = 16
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700383 if overwrite_only:
Fabio Utzig649d80f2019-09-12 10:26:23 -0300384 return MAX_ALIGN * 2 + magic_size
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700385 else:
386 if write_size not in set([1, 2, 4, 8]):
Fabio Utzig1f508922020-01-15 11:37:51 -0300387 raise click.BadParameter("Invalid alignment: {}".format(
388 write_size))
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700389 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
Fabio Utzig649d80f2019-09-12 10:26:23 -0300390 trailer = m * 3 * write_size # status area
391 if enckey is not None:
Fabio Utzig9a492d52020-01-15 11:31:52 -0300392 if save_enctlv:
393 # TLV saved by the bootloader is aligned
394 keylen = (int((enctlv_len - 1) / MAX_ALIGN) + 1) * MAX_ALIGN
395 else:
396 keylen = 16
397 trailer += keylen * 2 # encryption keys
Fabio Utzig88282802019-10-17 11:17:18 -0300398 trailer += MAX_ALIGN * 4 # image_ok/copy_done/swap_info/swap_size
Fabio Utzig649d80f2019-09-12 10:26:23 -0300399 trailer += magic_size
400 return trailer
Fabio Utzig519285f2018-06-04 11:11:53 -0300401
Fabio Utzig263d4392018-06-05 10:37:35 -0300402 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600403 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700404 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig9a492d52020-01-15 11:31:52 -0300405 self.overwrite_only, self.enckey,
406 self.save_enctlv, self.enctlv_len)
David Brown23f91ad2017-05-16 11:38:17 -0600407 padding = size - (len(self.payload) + tsize)
Fabio Utzig9117fde2019-10-17 11:11:46 -0300408 pbytes = bytes([self.erased_val] * padding)
409 pbytes += bytes([self.erased_val] * (tsize - len(boot_magic)))
Fabio Utzige08f0872017-06-28 18:12:16 -0300410 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600411 self.payload += pbytes
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300412
413 @staticmethod
414 def verify(imgfile, key):
415 with open(imgfile, "rb") as f:
416 b = f.read()
417
418 magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
Marek Pietae9555102019-08-08 16:08:16 +0200419 version = struct.unpack('BBHI', b[20:28])
420
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300421 if magic != IMAGE_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200422 return VerifyResult.INVALID_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300423
424 tlv_info = b[header_size+img_size:header_size+img_size+TLV_INFO_SIZE]
425 magic, tlv_tot = struct.unpack('HH', tlv_info)
426 if magic != TLV_INFO_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200427 return VerifyResult.INVALID_TLV_INFO_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300428
429 sha = hashlib.sha256()
430 sha.update(b[:header_size+img_size])
431 digest = sha.digest()
432
433 tlv_off = header_size + img_size
434 tlv_end = tlv_off + tlv_tot
435 tlv_off += TLV_INFO_SIZE # skip tlv info
436 while tlv_off < tlv_end:
437 tlv = b[tlv_off:tlv_off+TLV_SIZE]
438 tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
439 if tlv_type == TLV_VALUES["SHA256"]:
440 off = tlv_off + TLV_SIZE
441 if digest == b[off:off+tlv_len]:
442 if key is None:
Marek Pietae9555102019-08-08 16:08:16 +0200443 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300444 else:
Marek Pietae9555102019-08-08 16:08:16 +0200445 return VerifyResult.INVALID_HASH, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300446 elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
447 off = tlv_off + TLV_SIZE
448 tlv_sig = b[off:off+tlv_len]
449 payload = b[:header_size+img_size]
450 try:
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300451 if hasattr(key, 'verify'):
452 key.verify(tlv_sig, payload)
453 else:
454 key.verify_digest(tlv_sig, digest)
Marek Pietae9555102019-08-08 16:08:16 +0200455 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300456 except InvalidSignature:
457 # continue to next TLV
458 pass
459 tlv_off += TLV_SIZE + tlv_len
Marek Pietae9555102019-08-08 16:08:16 +0200460 return VerifyResult.INVALID_SIGNATURE, None