blob: 20f8e757d1abae6bca353ea6cf060d1e6a370b0b [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
David Vinczeda8c9192019-03-26 17:17:41 +010038DEP_IMAGES_KEY = "images"
39DEP_VERSIONS_KEY = "versions"
David Brown23f91ad2017-05-16 11:38:17 -060040
41# Image header flags.
42IMAGE_F = {
43 'PIC': 0x0000001,
Fabio Utzig06b77b82018-08-23 16:01:16 -030044 'NON_BOOTABLE': 0x0000010,
45 'ENCRYPTED': 0x0000004,
46}
David Brown23f91ad2017-05-16 11:38:17 -060047
48TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060049 'KEYHASH': 0x01,
David Brown27648b82017-08-31 10:40:29 -060050 'SHA256': 0x10,
51 'RSA2048': 0x20,
52 'ECDSA224': 0x21,
Fabio Utzig06b77b82018-08-23 16:01:16 -030053 'ECDSA256': 0x22,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030054 'RSA3072': 0x23,
Fabio Utzig06b77b82018-08-23 16:01:16 -030055 'ENCRSA2048': 0x30,
56 'ENCKW128': 0x31,
David Vinczeda8c9192019-03-26 17:17:41 +010057 'DEPENDENCY': 0x40
Fabio Utzig06b77b82018-08-23 16:01:16 -030058}
David Brown23f91ad2017-05-16 11:38:17 -060059
Fabio Utzig4a5477a2019-05-27 15:45:08 -030060TLV_SIZE = 4
David Brownf5b33d82017-09-01 10:58:27 -060061TLV_INFO_SIZE = 4
62TLV_INFO_MAGIC = 0x6907
David Brown23f91ad2017-05-16 11:38:17 -060063
David Brown23f91ad2017-05-16 11:38:17 -060064boot_magic = bytes([
65 0x77, 0xc2, 0x95, 0xf3,
66 0x60, 0xd2, 0xef, 0x7f,
67 0x35, 0x52, 0x50, 0x0f,
68 0x2c, 0xb6, 0x79, 0x80, ])
69
Mark Schultea66c6872018-09-26 17:24:40 -070070STRUCT_ENDIAN_DICT = {
71 'little': '<',
72 'big': '>'
73}
74
Fabio Utzig4a5477a2019-05-27 15:45:08 -030075VerifyResult = Enum('VerifyResult',
76 """
77 OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH
78 INVALID_SIGNATURE
79 """)
80
81
David Brown23f91ad2017-05-16 11:38:17 -060082class TLV():
Mark Schultea66c6872018-09-26 17:24:40 -070083 def __init__(self, endian):
David Brown23f91ad2017-05-16 11:38:17 -060084 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -070085 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -060086
87 def add(self, kind, payload):
88 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
Mark Schultea66c6872018-09-26 17:24:40 -070089 e = STRUCT_ENDIAN_DICT[self.endian]
90 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -060091 self.buf += buf
92 self.buf += payload
93
94 def get(self):
Mark Schultea66c6872018-09-26 17:24:40 -070095 e = STRUCT_ENDIAN_DICT[self.endian]
96 header = struct.pack(e + 'HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
David Brownf5b33d82017-09-01 10:58:27 -060097 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -060098
Fabio Utzig7c00acd2019-01-07 09:54:20 -020099
David Brown23f91ad2017-05-16 11:38:17 -0600100class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +0100101
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200102 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
103 pad_header=False, pad=False, align=1, slot_size=0,
104 max_sectors=DEFAULT_MAX_SECTORS, overwrite_only=False,
105 endian="little"):
David Brown23f91ad2017-05-16 11:38:17 -0600106 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200107 self.header_size = header_size
108 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -0600109 self.pad = pad
Fabio Utzig263d4392018-06-05 10:37:35 -0300110 self.align = align
111 self.slot_size = slot_size
112 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700113 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700114 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200115 self.base_addr = None
116 self.payload = []
David Brown23f91ad2017-05-16 11:38:17 -0600117
118 def __repr__(self):
Fabio Utzig263d4392018-06-05 10:37:35 -0300119 return "<Image version={}, header_size={}, base_addr={}, \
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700120 align={}, slot_size={}, max_sectors={}, overwrite_only={}, \
Mark Schultea66c6872018-09-26 17:24:40 -0700121 endian={} format={}, payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300122 self.version,
123 self.header_size,
124 self.base_addr if self.base_addr is not None else "N/A",
125 self.align,
126 self.slot_size,
127 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700128 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700129 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300130 self.__class__.__name__,
131 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600132
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200133 def load(self, path):
134 """Load an image from a given file"""
135 ext = os.path.splitext(path)[1][1:].lower()
136 if ext == INTEL_HEX_EXT:
137 ih = IntelHex(path)
138 self.payload = ih.tobinarray()
139 self.base_addr = ih.minaddr()
140 else:
141 with open(path, 'rb') as f:
142 self.payload = f.read()
143
144 # Add the image header if needed.
145 if self.pad_header and self.header_size > 0:
146 if self.base_addr:
147 # Adjust base_addr for new header
148 self.base_addr -= self.header_size
149 self.payload = (b'\000' * self.header_size) + self.payload
150
151 self.check()
152
153 def save(self, path):
154 """Save an image from a given file"""
155 if self.pad:
156 self.pad_to(self.slot_size)
157
158 ext = os.path.splitext(path)[1][1:].lower()
159 if ext == INTEL_HEX_EXT:
160 # input was in binary format, but HEX needs to know the base addr
161 if self.base_addr is None:
162 raise Exception("Input file does not provide a base address")
163 h = IntelHex()
164 h.frombytes(bytes=self.payload, offset=self.base_addr)
165 h.tofile(path, 'hex')
166 else:
167 with open(path, 'wb') as f:
168 f.write(self.payload)
169
David Brown23f91ad2017-05-16 11:38:17 -0600170 def check(self):
171 """Perform some sanity checking of the image."""
172 # If there is a header requested, make sure that the image
173 # starts with all zeros.
174 if self.header_size > 0:
175 if any(v != 0 for v in self.payload[0:self.header_size]):
176 raise Exception("Padding requested, but image does not start with zeros")
Fabio Utzig263d4392018-06-05 10:37:35 -0300177 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700178 tsize = self._trailer_size(self.align, self.max_sectors,
179 self.overwrite_only)
Fabio Utzig263d4392018-06-05 10:37:35 -0300180 padding = self.slot_size - (len(self.payload) + tsize)
181 if padding < 0:
182 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
183 len(self.payload), tsize, self.slot_size)
184 raise Exception(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600185
David Vinczeda8c9192019-03-26 17:17:41 +0100186 def create(self, key, enckey, dependencies=None):
187 if dependencies is None:
188 dependencies_num = 0
189 protected_tlv_size = 0
190 else:
191 # Size of a Dependency TLV = Header ('BBH') + Payload('IBBHI')
192 # = 16 Bytes
193 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
194 protected_tlv_size = (dependencies_num * 16) + TLV_INFO_SIZE
195
196 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600197
Mark Schultea66c6872018-09-26 17:24:40 -0700198 tlv = TLV(self.endian)
David Brown23f91ad2017-05-16 11:38:17 -0600199
David Vinczeda8c9192019-03-26 17:17:41 +0100200 if protected_tlv_size != 0:
201 for i in range(dependencies_num):
202 e = STRUCT_ENDIAN_DICT[self.endian]
203 payload = struct.pack(
204 e + 'I'+'BBHI',
205 int(dependencies[DEP_IMAGES_KEY][i]),
206 dependencies[DEP_VERSIONS_KEY][i].major,
207 dependencies[DEP_VERSIONS_KEY][i].minor,
208 dependencies[DEP_VERSIONS_KEY][i].revision,
209 dependencies[DEP_VERSIONS_KEY][i].build
210 )
211 tlv.add('DEPENDENCY', payload)
212 # Full TLV size needs to be calculated in advance, because the
213 # header will be protected as well
214 tlv_header_size = 4
215 payload_digest_size = 32
216 keyhash_size = 32
217 cipherkey_size = 32
218
219 full_size = TLV_INFO_SIZE + len(tlv.buf) + tlv_header_size \
220 + payload_digest_size
221 if key is not None:
222 full_size += tlv_header_size + keyhash_size \
223 + tlv_header_size + key.sig_len()
224 if enckey is not None:
225 full_size += tlv_header_size + cipherkey_size
226 tlv_header = struct.pack(e + 'HH', TLV_INFO_MAGIC, full_size)
227 self.payload += tlv_header + bytes(tlv.buf)
228
David Brown23f91ad2017-05-16 11:38:17 -0600229 # Note that ecdsa wants to do the hashing itself, which means
230 # we get to hash it twice.
231 sha = hashlib.sha256()
232 sha.update(self.payload)
233 digest = sha.digest()
234
235 tlv.add('SHA256', digest)
236
David Brown0f0c6a82017-06-08 09:26:24 -0600237 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600238 pub = key.get_public_bytes()
239 sha = hashlib.sha256()
240 sha.update(pub)
241 pubbytes = sha.digest()
242 tlv.add('KEYHASH', pubbytes)
243
David Brown47b77c52017-11-16 15:10:22 -0700244 sig = key.sign(bytes(self.payload))
David Brown0f0c6a82017-06-08 09:26:24 -0600245 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600246
Fabio Utzig06b77b82018-08-23 16:01:16 -0300247 if enckey is not None:
248 plainkey = os.urandom(16)
249 cipherkey = enckey._get_public().encrypt(
250 plainkey, padding.OAEP(
251 mgf=padding.MGF1(algorithm=hashes.SHA256()),
252 algorithm=hashes.SHA256(),
253 label=None))
254 tlv.add('ENCRSA2048', cipherkey)
255
256 nonce = bytes([0] * 16)
257 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
258 backend=default_backend())
259 encryptor = cipher.encryptor()
260 img = bytes(self.payload[self.header_size:])
261 self.payload[self.header_size:] = encryptor.update(img) + \
262 encryptor.finalize()
263
David Vinczeda8c9192019-03-26 17:17:41 +0100264 self.payload += tlv.get()[protected_tlv_size:]
David Brown23f91ad2017-05-16 11:38:17 -0600265
David Vinczeda8c9192019-03-26 17:17:41 +0100266 def add_header(self, enckey, protected_tlv_size):
Fabio Utzigcd284062018-11-30 11:05:45 -0200267 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600268
David Brown0f0c6a82017-06-08 09:26:24 -0600269 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300270 if enckey is not None:
271 flags |= IMAGE_F['ENCRYPTED']
David Brown23f91ad2017-05-16 11:38:17 -0600272
Mark Schultea66c6872018-09-26 17:24:40 -0700273 e = STRUCT_ENDIAN_DICT[self.endian]
274 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100275 # type ImageHdr struct {
276 'I' + # Magic uint32
277 'I' + # LoadAddr uint32
278 'H' + # HdrSz uint16
279 'H' + # PTLVSz uint16
280 'I' + # ImgSz uint32
281 'I' + # Flags uint32
282 'BBHI' + # Vers ImageVersion
283 'I' # Pad1 uint32
284 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600285 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
286 header = struct.pack(fmt,
287 IMAGE_MAGIC,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300288 0, # LoadAddr
David Brown23f91ad2017-05-16 11:38:17 -0600289 self.header_size,
David Vinczeda8c9192019-03-26 17:17:41 +0100290 protected_tlv_size, # TLV Info header + Dependency TLVs
David Brown23f91ad2017-05-16 11:38:17 -0600291 len(self.payload) - self.header_size, # ImageSz
292 flags, # Flags
293 self.version.major,
294 self.version.minor or 0,
295 self.version.revision or 0,
296 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100297 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600298 self.payload = bytearray(self.payload)
299 self.payload[:len(header)] = header
300
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700301 def _trailer_size(self, write_size, max_sectors, overwrite_only):
Fabio Utzig519285f2018-06-04 11:11:53 -0300302 # NOTE: should already be checked by the argument parser
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700303 if overwrite_only:
304 return 8 * 2 + 16
305 else:
306 if write_size not in set([1, 2, 4, 8]):
307 raise Exception("Invalid alignment: {}".format(write_size))
308 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
309 return m * 3 * write_size + 8 * 2 + 16
Fabio Utzig519285f2018-06-04 11:11:53 -0300310
Fabio Utzig263d4392018-06-05 10:37:35 -0300311 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600312 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700313 tsize = self._trailer_size(self.align, self.max_sectors,
314 self.overwrite_only)
David Brown23f91ad2017-05-16 11:38:17 -0600315 padding = size - (len(self.payload) + tsize)
Fabio Utzige08f0872017-06-28 18:12:16 -0300316 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600317 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300318 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600319 self.payload += pbytes
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300320
321 @staticmethod
322 def verify(imgfile, key):
323 with open(imgfile, "rb") as f:
324 b = f.read()
325
326 magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
327 if magic != IMAGE_MAGIC:
328 return VerifyResult.INVALID_MAGIC
329
330 tlv_info = b[header_size+img_size:header_size+img_size+TLV_INFO_SIZE]
331 magic, tlv_tot = struct.unpack('HH', tlv_info)
332 if magic != TLV_INFO_MAGIC:
333 return VerifyResult.INVALID_TLV_INFO_MAGIC
334
335 sha = hashlib.sha256()
336 sha.update(b[:header_size+img_size])
337 digest = sha.digest()
338
339 tlv_off = header_size + img_size
340 tlv_end = tlv_off + tlv_tot
341 tlv_off += TLV_INFO_SIZE # skip tlv info
342 while tlv_off < tlv_end:
343 tlv = b[tlv_off:tlv_off+TLV_SIZE]
344 tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
345 if tlv_type == TLV_VALUES["SHA256"]:
346 off = tlv_off + TLV_SIZE
347 if digest == b[off:off+tlv_len]:
348 if key is None:
349 return VerifyResult.OK
350 else:
351 return VerifyResult.INVALID_HASH
352 elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
353 off = tlv_off + TLV_SIZE
354 tlv_sig = b[off:off+tlv_len]
355 payload = b[:header_size+img_size]
356 try:
357 key.verify(tlv_sig, payload)
358 return VerifyResult.OK
359 except InvalidSignature:
360 # continue to next TLV
361 pass
362 tlv_off += TLV_SIZE + tlv_len
363 return VerifyResult.INVALID_SIGNATURE