blob: 34bed7b3d4534a1660f3eaaf736025ba8b4a3824 [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 Utzig4a5477a2019-05-27 15:45:08 -030022from enum import Enum
Carles Cufi37d052f2018-01-30 16:40:10 +010023from intelhex import IntelHex
David Brown23f91ad2017-05-16 11:38:17 -060024import hashlib
25import struct
Carles Cufi37d052f2018-01-30 16:40:10 +010026import os.path
Fabio Utzig06b77b82018-08-23 16:01:16 -030027from cryptography.hazmat.primitives.asymmetric import padding
28from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
29from cryptography.hazmat.backends import default_backend
30from cryptography.hazmat.primitives import hashes
Fabio Utzig4a5477a2019-05-27 15:45:08 -030031from cryptography.exceptions import InvalidSignature
David Brown23f91ad2017-05-16 11:38:17 -060032
David Brown72e7a512017-09-01 11:08:23 -060033IMAGE_MAGIC = 0x96f3b83d
David Brown23f91ad2017-05-16 11:38:17 -060034IMAGE_HEADER_SIZE = 32
Carles Cufi37d052f2018-01-30 16:40:10 +010035BIN_EXT = "bin"
36INTEL_HEX_EXT = "hex"
Fabio Utzig519285f2018-06-04 11:11:53 -030037DEFAULT_MAX_SECTORS = 128
Fabio Utzig649d80f2019-09-12 10:26:23 -030038MAX_ALIGN = 8
David Vinczeda8c9192019-03-26 17:17:41 +010039DEP_IMAGES_KEY = "images"
40DEP_VERSIONS_KEY = "versions"
David Brown23f91ad2017-05-16 11:38:17 -060041
42# Image header flags.
43IMAGE_F = {
44 'PIC': 0x0000001,
Fabio Utzig06b77b82018-08-23 16:01:16 -030045 'NON_BOOTABLE': 0x0000010,
46 'ENCRYPTED': 0x0000004,
47}
David Brown23f91ad2017-05-16 11:38:17 -060048
49TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060050 'KEYHASH': 0x01,
David Brown27648b82017-08-31 10:40:29 -060051 'SHA256': 0x10,
52 'RSA2048': 0x20,
53 'ECDSA224': 0x21,
Fabio Utzig06b77b82018-08-23 16:01:16 -030054 'ECDSA256': 0x22,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030055 'RSA3072': 0x23,
Fabio Utzig8101d1f2019-05-09 15:03:22 -030056 'ED25519': 0x24,
Fabio Utzig06b77b82018-08-23 16:01:16 -030057 'ENCRSA2048': 0x30,
58 'ENCKW128': 0x31,
David Vinczeda8c9192019-03-26 17:17:41 +010059 'DEPENDENCY': 0x40
Fabio Utzig06b77b82018-08-23 16:01:16 -030060}
David Brown23f91ad2017-05-16 11:38:17 -060061
Fabio Utzig4a5477a2019-05-27 15:45:08 -030062TLV_SIZE = 4
David Brownf5b33d82017-09-01 10:58:27 -060063TLV_INFO_SIZE = 4
64TLV_INFO_MAGIC = 0x6907
David Brown23f91ad2017-05-16 11:38:17 -060065
David Brown23f91ad2017-05-16 11:38:17 -060066boot_magic = bytes([
67 0x77, 0xc2, 0x95, 0xf3,
68 0x60, 0xd2, 0xef, 0x7f,
69 0x35, 0x52, 0x50, 0x0f,
70 0x2c, 0xb6, 0x79, 0x80, ])
71
Mark Schultea66c6872018-09-26 17:24:40 -070072STRUCT_ENDIAN_DICT = {
73 'little': '<',
74 'big': '>'
75}
76
Fabio Utzig4a5477a2019-05-27 15:45:08 -030077VerifyResult = Enum('VerifyResult',
78 """
79 OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH
80 INVALID_SIGNATURE
81 """)
82
83
David Brown23f91ad2017-05-16 11:38:17 -060084class TLV():
Mark Schultea66c6872018-09-26 17:24:40 -070085 def __init__(self, endian):
David Brown23f91ad2017-05-16 11:38:17 -060086 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -070087 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -060088
89 def add(self, kind, payload):
90 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
Mark Schultea66c6872018-09-26 17:24:40 -070091 e = STRUCT_ENDIAN_DICT[self.endian]
92 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -060093 self.buf += buf
94 self.buf += payload
95
96 def get(self):
Mark Schultea66c6872018-09-26 17:24:40 -070097 e = STRUCT_ENDIAN_DICT[self.endian]
98 header = struct.pack(e + 'HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
David Brownf5b33d82017-09-01 10:58:27 -060099 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -0600100
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200101
David Brown23f91ad2017-05-16 11:38:17 -0600102class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +0100103
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200104 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
105 pad_header=False, pad=False, align=1, slot_size=0,
106 max_sectors=DEFAULT_MAX_SECTORS, overwrite_only=False,
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000107 endian="little", load_addr=0):
David Brown23f91ad2017-05-16 11:38:17 -0600108 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200109 self.header_size = header_size
110 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -0600111 self.pad = pad
Fabio Utzig263d4392018-06-05 10:37:35 -0300112 self.align = align
113 self.slot_size = slot_size
114 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700115 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700116 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200117 self.base_addr = None
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000118 self.load_addr = 0 if load_addr is None else load_addr
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200119 self.payload = []
Fabio Utzig649d80f2019-09-12 10:26:23 -0300120 self.enckey = None
David Brown23f91ad2017-05-16 11:38:17 -0600121
122 def __repr__(self):
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000123 return "<Image version={}, header_size={}, base_addr={}, load_addr={}, \
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700124 align={}, slot_size={}, max_sectors={}, overwrite_only={}, \
Mark Schultea66c6872018-09-26 17:24:40 -0700125 endian={} format={}, payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300126 self.version,
127 self.header_size,
128 self.base_addr if self.base_addr is not None else "N/A",
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000129 self.load_addr,
Fabio Utzig263d4392018-06-05 10:37:35 -0300130 self.align,
131 self.slot_size,
132 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700133 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700134 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300135 self.__class__.__name__,
136 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600137
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200138 def load(self, path):
139 """Load an image from a given file"""
140 ext = os.path.splitext(path)[1][1:].lower()
141 if ext == INTEL_HEX_EXT:
142 ih = IntelHex(path)
143 self.payload = ih.tobinarray()
144 self.base_addr = ih.minaddr()
145 else:
146 with open(path, 'rb') as f:
147 self.payload = f.read()
148
149 # Add the image header if needed.
150 if self.pad_header and self.header_size > 0:
151 if self.base_addr:
152 # Adjust base_addr for new header
153 self.base_addr -= self.header_size
154 self.payload = (b'\000' * self.header_size) + self.payload
155
156 self.check()
157
158 def save(self, path):
159 """Save an image from a given file"""
160 if self.pad:
161 self.pad_to(self.slot_size)
162
163 ext = os.path.splitext(path)[1][1:].lower()
164 if ext == INTEL_HEX_EXT:
165 # input was in binary format, but HEX needs to know the base addr
166 if self.base_addr is None:
167 raise Exception("Input file does not provide a base address")
168 h = IntelHex()
169 h.frombytes(bytes=self.payload, offset=self.base_addr)
170 h.tofile(path, 'hex')
171 else:
172 with open(path, 'wb') as f:
173 f.write(self.payload)
174
David Brown23f91ad2017-05-16 11:38:17 -0600175 def check(self):
176 """Perform some sanity checking of the image."""
177 # If there is a header requested, make sure that the image
178 # starts with all zeros.
179 if self.header_size > 0:
180 if any(v != 0 for v in self.payload[0:self.header_size]):
181 raise Exception("Padding requested, but image does not start with zeros")
Fabio Utzig263d4392018-06-05 10:37:35 -0300182 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700183 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig649d80f2019-09-12 10:26:23 -0300184 self.overwrite_only, self.enckey)
Fabio Utzig263d4392018-06-05 10:37:35 -0300185 padding = self.slot_size - (len(self.payload) + tsize)
186 if padding < 0:
187 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
188 len(self.payload), tsize, self.slot_size)
189 raise Exception(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600190
David Vinczeda8c9192019-03-26 17:17:41 +0100191 def create(self, key, enckey, dependencies=None):
Fabio Utzig649d80f2019-09-12 10:26:23 -0300192 self.enckey = enckey
193
David Vinczeda8c9192019-03-26 17:17:41 +0100194 if dependencies is None:
195 dependencies_num = 0
196 protected_tlv_size = 0
197 else:
198 # Size of a Dependency TLV = Header ('BBH') + Payload('IBBHI')
199 # = 16 Bytes
200 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
201 protected_tlv_size = (dependencies_num * 16) + TLV_INFO_SIZE
202
203 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600204
Mark Schultea66c6872018-09-26 17:24:40 -0700205 tlv = TLV(self.endian)
David Brown23f91ad2017-05-16 11:38:17 -0600206
David Vinczeda8c9192019-03-26 17:17:41 +0100207 if protected_tlv_size != 0:
208 for i in range(dependencies_num):
209 e = STRUCT_ENDIAN_DICT[self.endian]
210 payload = struct.pack(
David Brownbd7925e2019-07-29 11:11:32 -0600211 e + 'B3x'+'BBHI',
David Vinczeda8c9192019-03-26 17:17:41 +0100212 int(dependencies[DEP_IMAGES_KEY][i]),
213 dependencies[DEP_VERSIONS_KEY][i].major,
214 dependencies[DEP_VERSIONS_KEY][i].minor,
215 dependencies[DEP_VERSIONS_KEY][i].revision,
216 dependencies[DEP_VERSIONS_KEY][i].build
217 )
218 tlv.add('DEPENDENCY', payload)
219 # Full TLV size needs to be calculated in advance, because the
220 # header will be protected as well
221 tlv_header_size = 4
222 payload_digest_size = 32
223 keyhash_size = 32
224 cipherkey_size = 32
225
226 full_size = TLV_INFO_SIZE + len(tlv.buf) + tlv_header_size \
227 + payload_digest_size
228 if key is not None:
229 full_size += tlv_header_size + keyhash_size \
230 + tlv_header_size + key.sig_len()
231 if enckey is not None:
232 full_size += tlv_header_size + cipherkey_size
233 tlv_header = struct.pack(e + 'HH', TLV_INFO_MAGIC, full_size)
234 self.payload += tlv_header + bytes(tlv.buf)
235
David Brown23f91ad2017-05-16 11:38:17 -0600236 # Note that ecdsa wants to do the hashing itself, which means
237 # we get to hash it twice.
238 sha = hashlib.sha256()
239 sha.update(self.payload)
240 digest = sha.digest()
241
242 tlv.add('SHA256', digest)
243
David Brown0f0c6a82017-06-08 09:26:24 -0600244 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600245 pub = key.get_public_bytes()
246 sha = hashlib.sha256()
247 sha.update(pub)
248 pubbytes = sha.digest()
249 tlv.add('KEYHASH', pubbytes)
250
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300251 # `sign` expects the full image payload (sha256 done internally),
252 # while `sign_digest` expects only the digest of the payload
253
254 if hasattr(key, 'sign'):
255 sig = key.sign(bytes(self.payload))
256 else:
257 sig = key.sign_digest(digest)
David Brown0f0c6a82017-06-08 09:26:24 -0600258 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600259
Fabio Utzig06b77b82018-08-23 16:01:16 -0300260 if enckey is not None:
261 plainkey = os.urandom(16)
262 cipherkey = enckey._get_public().encrypt(
263 plainkey, padding.OAEP(
264 mgf=padding.MGF1(algorithm=hashes.SHA256()),
265 algorithm=hashes.SHA256(),
266 label=None))
267 tlv.add('ENCRSA2048', cipherkey)
268
269 nonce = bytes([0] * 16)
270 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
271 backend=default_backend())
272 encryptor = cipher.encryptor()
273 img = bytes(self.payload[self.header_size:])
274 self.payload[self.header_size:] = encryptor.update(img) + \
275 encryptor.finalize()
276
David Vinczeda8c9192019-03-26 17:17:41 +0100277 self.payload += tlv.get()[protected_tlv_size:]
David Brown23f91ad2017-05-16 11:38:17 -0600278
David Vinczeda8c9192019-03-26 17:17:41 +0100279 def add_header(self, enckey, protected_tlv_size):
Fabio Utzigcd284062018-11-30 11:05:45 -0200280 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600281
David Brown0f0c6a82017-06-08 09:26:24 -0600282 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300283 if enckey is not None:
284 flags |= IMAGE_F['ENCRYPTED']
David Brown23f91ad2017-05-16 11:38:17 -0600285
Mark Schultea66c6872018-09-26 17:24:40 -0700286 e = STRUCT_ENDIAN_DICT[self.endian]
287 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100288 # type ImageHdr struct {
289 'I' + # Magic uint32
290 'I' + # LoadAddr uint32
291 'H' + # HdrSz uint16
292 'H' + # PTLVSz uint16
293 'I' + # ImgSz uint32
294 'I' + # Flags uint32
295 'BBHI' + # Vers ImageVersion
296 'I' # Pad1 uint32
297 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600298 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
299 header = struct.pack(fmt,
300 IMAGE_MAGIC,
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000301 self.load_addr,
David Brown23f91ad2017-05-16 11:38:17 -0600302 self.header_size,
David Vinczeda8c9192019-03-26 17:17:41 +0100303 protected_tlv_size, # TLV Info header + Dependency TLVs
David Brown23f91ad2017-05-16 11:38:17 -0600304 len(self.payload) - self.header_size, # ImageSz
305 flags, # Flags
306 self.version.major,
307 self.version.minor or 0,
308 self.version.revision or 0,
309 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100310 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600311 self.payload = bytearray(self.payload)
312 self.payload[:len(header)] = header
313
Fabio Utzig649d80f2019-09-12 10:26:23 -0300314 def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey):
Fabio Utzig519285f2018-06-04 11:11:53 -0300315 # NOTE: should already be checked by the argument parser
Fabio Utzig649d80f2019-09-12 10:26:23 -0300316 magic_size = 16
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700317 if overwrite_only:
Fabio Utzig649d80f2019-09-12 10:26:23 -0300318 return MAX_ALIGN * 2 + magic_size
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700319 else:
320 if write_size not in set([1, 2, 4, 8]):
321 raise Exception("Invalid alignment: {}".format(write_size))
322 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
Fabio Utzig649d80f2019-09-12 10:26:23 -0300323 trailer = m * 3 * write_size # status area
324 if enckey is not None:
325 trailer += 16 * 2 # encryption keys
326 trailer += MAX_ALIGN * 4 # magic_ok/copy_done/swap_info/swap_size
327 trailer += magic_size
328 return trailer
Fabio Utzig519285f2018-06-04 11:11:53 -0300329
Fabio Utzig263d4392018-06-05 10:37:35 -0300330 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600331 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700332 tsize = self._trailer_size(self.align, self.max_sectors,
Fabio Utzig649d80f2019-09-12 10:26:23 -0300333 self.overwrite_only, self.enckey)
David Brown23f91ad2017-05-16 11:38:17 -0600334 padding = size - (len(self.payload) + tsize)
Fabio Utzige08f0872017-06-28 18:12:16 -0300335 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600336 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300337 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600338 self.payload += pbytes
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300339
340 @staticmethod
341 def verify(imgfile, key):
342 with open(imgfile, "rb") as f:
343 b = f.read()
344
345 magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
Marek Pietae9555102019-08-08 16:08:16 +0200346 version = struct.unpack('BBHI', b[20:28])
347
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300348 if magic != IMAGE_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200349 return VerifyResult.INVALID_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300350
351 tlv_info = b[header_size+img_size:header_size+img_size+TLV_INFO_SIZE]
352 magic, tlv_tot = struct.unpack('HH', tlv_info)
353 if magic != TLV_INFO_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200354 return VerifyResult.INVALID_TLV_INFO_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300355
356 sha = hashlib.sha256()
357 sha.update(b[:header_size+img_size])
358 digest = sha.digest()
359
360 tlv_off = header_size + img_size
361 tlv_end = tlv_off + tlv_tot
362 tlv_off += TLV_INFO_SIZE # skip tlv info
363 while tlv_off < tlv_end:
364 tlv = b[tlv_off:tlv_off+TLV_SIZE]
365 tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
366 if tlv_type == TLV_VALUES["SHA256"]:
367 off = tlv_off + TLV_SIZE
368 if digest == b[off:off+tlv_len]:
369 if key is None:
Marek Pietae9555102019-08-08 16:08:16 +0200370 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300371 else:
Marek Pietae9555102019-08-08 16:08:16 +0200372 return VerifyResult.INVALID_HASH, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300373 elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
374 off = tlv_off + TLV_SIZE
375 tlv_sig = b[off:off+tlv_len]
376 payload = b[:header_size+img_size]
377 try:
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300378 if hasattr(key, 'verify'):
379 key.verify(tlv_sig, payload)
380 else:
381 key.verify_digest(tlv_sig, digest)
Marek Pietae9555102019-08-08 16:08:16 +0200382 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300383 except InvalidSignature:
384 # continue to next TLV
385 pass
386 tlv_off += TLV_SIZE + tlv_len
Marek Pietae9555102019-08-08 16:08:16 +0200387 return VerifyResult.INVALID_SIGNATURE, None