blob: 13b0b3baf99fb7299bb9ffb49631234c94d8038f [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 Utzig8101d1f2019-05-09 15:03:22 -030055 'ED25519': 0x24,
Fabio Utzig06b77b82018-08-23 16:01:16 -030056 'ENCRSA2048': 0x30,
57 'ENCKW128': 0x31,
David Vinczeda8c9192019-03-26 17:17:41 +010058 'DEPENDENCY': 0x40
Fabio Utzig06b77b82018-08-23 16:01:16 -030059}
David Brown23f91ad2017-05-16 11:38:17 -060060
Fabio Utzig4a5477a2019-05-27 15:45:08 -030061TLV_SIZE = 4
David Brownf5b33d82017-09-01 10:58:27 -060062TLV_INFO_SIZE = 4
63TLV_INFO_MAGIC = 0x6907
David Brown23f91ad2017-05-16 11:38:17 -060064
David Brown23f91ad2017-05-16 11:38:17 -060065boot_magic = bytes([
66 0x77, 0xc2, 0x95, 0xf3,
67 0x60, 0xd2, 0xef, 0x7f,
68 0x35, 0x52, 0x50, 0x0f,
69 0x2c, 0xb6, 0x79, 0x80, ])
70
Mark Schultea66c6872018-09-26 17:24:40 -070071STRUCT_ENDIAN_DICT = {
72 'little': '<',
73 'big': '>'
74}
75
Fabio Utzig4a5477a2019-05-27 15:45:08 -030076VerifyResult = Enum('VerifyResult',
77 """
78 OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH
79 INVALID_SIGNATURE
80 """)
81
82
David Brown23f91ad2017-05-16 11:38:17 -060083class TLV():
Mark Schultea66c6872018-09-26 17:24:40 -070084 def __init__(self, endian):
David Brown23f91ad2017-05-16 11:38:17 -060085 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -070086 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -060087
88 def add(self, kind, payload):
89 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
Mark Schultea66c6872018-09-26 17:24:40 -070090 e = STRUCT_ENDIAN_DICT[self.endian]
91 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -060092 self.buf += buf
93 self.buf += payload
94
95 def get(self):
Mark Schultea66c6872018-09-26 17:24:40 -070096 e = STRUCT_ENDIAN_DICT[self.endian]
97 header = struct.pack(e + 'HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
David Brownf5b33d82017-09-01 10:58:27 -060098 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -060099
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200100
David Brown23f91ad2017-05-16 11:38:17 -0600101class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +0100102
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200103 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
104 pad_header=False, pad=False, align=1, slot_size=0,
105 max_sectors=DEFAULT_MAX_SECTORS, overwrite_only=False,
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000106 endian="little", load_addr=0):
David Brown23f91ad2017-05-16 11:38:17 -0600107 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200108 self.header_size = header_size
109 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -0600110 self.pad = pad
Fabio Utzig263d4392018-06-05 10:37:35 -0300111 self.align = align
112 self.slot_size = slot_size
113 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700114 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700115 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200116 self.base_addr = None
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000117 self.load_addr = 0 if load_addr is None else load_addr
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200118 self.payload = []
David Brown23f91ad2017-05-16 11:38:17 -0600119
120 def __repr__(self):
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000121 return "<Image version={}, header_size={}, base_addr={}, load_addr={}, \
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700122 align={}, slot_size={}, max_sectors={}, overwrite_only={}, \
Mark Schultea66c6872018-09-26 17:24:40 -0700123 endian={} format={}, payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300124 self.version,
125 self.header_size,
126 self.base_addr if self.base_addr is not None else "N/A",
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000127 self.load_addr,
Fabio Utzig263d4392018-06-05 10:37:35 -0300128 self.align,
129 self.slot_size,
130 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700131 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700132 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300133 self.__class__.__name__,
134 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600135
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200136 def load(self, path):
137 """Load an image from a given file"""
138 ext = os.path.splitext(path)[1][1:].lower()
139 if ext == INTEL_HEX_EXT:
140 ih = IntelHex(path)
141 self.payload = ih.tobinarray()
142 self.base_addr = ih.minaddr()
143 else:
144 with open(path, 'rb') as f:
145 self.payload = f.read()
146
147 # Add the image header if needed.
148 if self.pad_header and self.header_size > 0:
149 if self.base_addr:
150 # Adjust base_addr for new header
151 self.base_addr -= self.header_size
152 self.payload = (b'\000' * self.header_size) + self.payload
153
154 self.check()
155
156 def save(self, path):
157 """Save an image from a given file"""
158 if self.pad:
159 self.pad_to(self.slot_size)
160
161 ext = os.path.splitext(path)[1][1:].lower()
162 if ext == INTEL_HEX_EXT:
163 # input was in binary format, but HEX needs to know the base addr
164 if self.base_addr is None:
165 raise Exception("Input file does not provide a base address")
166 h = IntelHex()
167 h.frombytes(bytes=self.payload, offset=self.base_addr)
168 h.tofile(path, 'hex')
169 else:
170 with open(path, 'wb') as f:
171 f.write(self.payload)
172
David Brown23f91ad2017-05-16 11:38:17 -0600173 def check(self):
174 """Perform some sanity checking of the image."""
175 # If there is a header requested, make sure that the image
176 # starts with all zeros.
177 if self.header_size > 0:
178 if any(v != 0 for v in self.payload[0:self.header_size]):
179 raise Exception("Padding requested, but image does not start with zeros")
Fabio Utzig263d4392018-06-05 10:37:35 -0300180 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700181 tsize = self._trailer_size(self.align, self.max_sectors,
182 self.overwrite_only)
Fabio Utzig263d4392018-06-05 10:37:35 -0300183 padding = self.slot_size - (len(self.payload) + tsize)
184 if padding < 0:
185 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
186 len(self.payload), tsize, self.slot_size)
187 raise Exception(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600188
David Vinczeda8c9192019-03-26 17:17:41 +0100189 def create(self, key, enckey, dependencies=None):
190 if dependencies is None:
191 dependencies_num = 0
192 protected_tlv_size = 0
193 else:
194 # Size of a Dependency TLV = Header ('BBH') + Payload('IBBHI')
195 # = 16 Bytes
196 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
197 protected_tlv_size = (dependencies_num * 16) + TLV_INFO_SIZE
198
199 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600200
Mark Schultea66c6872018-09-26 17:24:40 -0700201 tlv = TLV(self.endian)
David Brown23f91ad2017-05-16 11:38:17 -0600202
David Vinczeda8c9192019-03-26 17:17:41 +0100203 if protected_tlv_size != 0:
204 for i in range(dependencies_num):
205 e = STRUCT_ENDIAN_DICT[self.endian]
206 payload = struct.pack(
David Brownbd7925e2019-07-29 11:11:32 -0600207 e + 'B3x'+'BBHI',
David Vinczeda8c9192019-03-26 17:17:41 +0100208 int(dependencies[DEP_IMAGES_KEY][i]),
209 dependencies[DEP_VERSIONS_KEY][i].major,
210 dependencies[DEP_VERSIONS_KEY][i].minor,
211 dependencies[DEP_VERSIONS_KEY][i].revision,
212 dependencies[DEP_VERSIONS_KEY][i].build
213 )
214 tlv.add('DEPENDENCY', payload)
215 # Full TLV size needs to be calculated in advance, because the
216 # header will be protected as well
217 tlv_header_size = 4
218 payload_digest_size = 32
219 keyhash_size = 32
220 cipherkey_size = 32
221
222 full_size = TLV_INFO_SIZE + len(tlv.buf) + tlv_header_size \
223 + payload_digest_size
224 if key is not None:
225 full_size += tlv_header_size + keyhash_size \
226 + tlv_header_size + key.sig_len()
227 if enckey is not None:
228 full_size += tlv_header_size + cipherkey_size
229 tlv_header = struct.pack(e + 'HH', TLV_INFO_MAGIC, full_size)
230 self.payload += tlv_header + bytes(tlv.buf)
231
David Brown23f91ad2017-05-16 11:38:17 -0600232 # Note that ecdsa wants to do the hashing itself, which means
233 # we get to hash it twice.
234 sha = hashlib.sha256()
235 sha.update(self.payload)
236 digest = sha.digest()
237
238 tlv.add('SHA256', digest)
239
David Brown0f0c6a82017-06-08 09:26:24 -0600240 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600241 pub = key.get_public_bytes()
242 sha = hashlib.sha256()
243 sha.update(pub)
244 pubbytes = sha.digest()
245 tlv.add('KEYHASH', pubbytes)
246
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300247 # `sign` expects the full image payload (sha256 done internally),
248 # while `sign_digest` expects only the digest of the payload
249
250 if hasattr(key, 'sign'):
251 sig = key.sign(bytes(self.payload))
252 else:
253 sig = key.sign_digest(digest)
David Brown0f0c6a82017-06-08 09:26:24 -0600254 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600255
Fabio Utzig06b77b82018-08-23 16:01:16 -0300256 if enckey is not None:
257 plainkey = os.urandom(16)
258 cipherkey = enckey._get_public().encrypt(
259 plainkey, padding.OAEP(
260 mgf=padding.MGF1(algorithm=hashes.SHA256()),
261 algorithm=hashes.SHA256(),
262 label=None))
263 tlv.add('ENCRSA2048', cipherkey)
264
265 nonce = bytes([0] * 16)
266 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
267 backend=default_backend())
268 encryptor = cipher.encryptor()
269 img = bytes(self.payload[self.header_size:])
270 self.payload[self.header_size:] = encryptor.update(img) + \
271 encryptor.finalize()
272
David Vinczeda8c9192019-03-26 17:17:41 +0100273 self.payload += tlv.get()[protected_tlv_size:]
David Brown23f91ad2017-05-16 11:38:17 -0600274
David Vinczeda8c9192019-03-26 17:17:41 +0100275 def add_header(self, enckey, protected_tlv_size):
Fabio Utzigcd284062018-11-30 11:05:45 -0200276 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600277
David Brown0f0c6a82017-06-08 09:26:24 -0600278 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300279 if enckey is not None:
280 flags |= IMAGE_F['ENCRYPTED']
David Brown23f91ad2017-05-16 11:38:17 -0600281
Mark Schultea66c6872018-09-26 17:24:40 -0700282 e = STRUCT_ENDIAN_DICT[self.endian]
283 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100284 # type ImageHdr struct {
285 'I' + # Magic uint32
286 'I' + # LoadAddr uint32
287 'H' + # HdrSz uint16
288 'H' + # PTLVSz uint16
289 'I' + # ImgSz uint32
290 'I' + # Flags uint32
291 'BBHI' + # Vers ImageVersion
292 'I' # Pad1 uint32
293 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600294 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
295 header = struct.pack(fmt,
296 IMAGE_MAGIC,
Håkon Øye Amundsendf8c8912019-08-26 12:15:28 +0000297 self.load_addr,
David Brown23f91ad2017-05-16 11:38:17 -0600298 self.header_size,
David Vinczeda8c9192019-03-26 17:17:41 +0100299 protected_tlv_size, # TLV Info header + Dependency TLVs
David Brown23f91ad2017-05-16 11:38:17 -0600300 len(self.payload) - self.header_size, # ImageSz
301 flags, # Flags
302 self.version.major,
303 self.version.minor or 0,
304 self.version.revision or 0,
305 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100306 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600307 self.payload = bytearray(self.payload)
308 self.payload[:len(header)] = header
309
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700310 def _trailer_size(self, write_size, max_sectors, overwrite_only):
Fabio Utzig519285f2018-06-04 11:11:53 -0300311 # NOTE: should already be checked by the argument parser
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700312 if overwrite_only:
313 return 8 * 2 + 16
314 else:
315 if write_size not in set([1, 2, 4, 8]):
316 raise Exception("Invalid alignment: {}".format(write_size))
317 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
318 return m * 3 * write_size + 8 * 2 + 16
Fabio Utzig519285f2018-06-04 11:11:53 -0300319
Fabio Utzig263d4392018-06-05 10:37:35 -0300320 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600321 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700322 tsize = self._trailer_size(self.align, self.max_sectors,
323 self.overwrite_only)
David Brown23f91ad2017-05-16 11:38:17 -0600324 padding = size - (len(self.payload) + tsize)
Fabio Utzige08f0872017-06-28 18:12:16 -0300325 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600326 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300327 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600328 self.payload += pbytes
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300329
330 @staticmethod
331 def verify(imgfile, key):
332 with open(imgfile, "rb") as f:
333 b = f.read()
334
335 magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
Marek Pietae9555102019-08-08 16:08:16 +0200336 version = struct.unpack('BBHI', b[20:28])
337
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300338 if magic != IMAGE_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200339 return VerifyResult.INVALID_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300340
341 tlv_info = b[header_size+img_size:header_size+img_size+TLV_INFO_SIZE]
342 magic, tlv_tot = struct.unpack('HH', tlv_info)
343 if magic != TLV_INFO_MAGIC:
Marek Pietae9555102019-08-08 16:08:16 +0200344 return VerifyResult.INVALID_TLV_INFO_MAGIC, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300345
346 sha = hashlib.sha256()
347 sha.update(b[:header_size+img_size])
348 digest = sha.digest()
349
350 tlv_off = header_size + img_size
351 tlv_end = tlv_off + tlv_tot
352 tlv_off += TLV_INFO_SIZE # skip tlv info
353 while tlv_off < tlv_end:
354 tlv = b[tlv_off:tlv_off+TLV_SIZE]
355 tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
356 if tlv_type == TLV_VALUES["SHA256"]:
357 off = tlv_off + TLV_SIZE
358 if digest == b[off:off+tlv_len]:
359 if key is None:
Marek Pietae9555102019-08-08 16:08:16 +0200360 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300361 else:
Marek Pietae9555102019-08-08 16:08:16 +0200362 return VerifyResult.INVALID_HASH, None
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300363 elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
364 off = tlv_off + TLV_SIZE
365 tlv_sig = b[off:off+tlv_len]
366 payload = b[:header_size+img_size]
367 try:
Fabio Utzig8101d1f2019-05-09 15:03:22 -0300368 if hasattr(key, 'verify'):
369 key.verify(tlv_sig, payload)
370 else:
371 key.verify_digest(tlv_sig, digest)
Marek Pietae9555102019-08-08 16:08:16 +0200372 return VerifyResult.OK, version
Fabio Utzig4a5477a2019-05-27 15:45:08 -0300373 except InvalidSignature:
374 # continue to next TLV
375 pass
376 tlv_off += TLV_SIZE + tlv_len
Marek Pietae9555102019-08-08 16:08:16 +0200377 return VerifyResult.INVALID_SIGNATURE, None