blob: c36f802a66f8c08a943263bc45059676abc962b4 [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
Carles Cufi37d052f2018-01-30 16:40:10 +010022from intelhex import IntelHex
David Brown23f91ad2017-05-16 11:38:17 -060023import hashlib
24import struct
Carles Cufi37d052f2018-01-30 16:40:10 +010025import os.path
Fabio Utzig06b77b82018-08-23 16:01:16 -030026from cryptography.hazmat.primitives.asymmetric import padding
27from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
28from cryptography.hazmat.backends import default_backend
29from cryptography.hazmat.primitives import hashes
David Brown23f91ad2017-05-16 11:38:17 -060030
David Brown72e7a512017-09-01 11:08:23 -060031IMAGE_MAGIC = 0x96f3b83d
David Brown23f91ad2017-05-16 11:38:17 -060032IMAGE_HEADER_SIZE = 32
Carles Cufi37d052f2018-01-30 16:40:10 +010033BIN_EXT = "bin"
34INTEL_HEX_EXT = "hex"
Fabio Utzig519285f2018-06-04 11:11:53 -030035DEFAULT_MAX_SECTORS = 128
David Vinczeda8c9192019-03-26 17:17:41 +010036DEP_IMAGES_KEY = "images"
37DEP_VERSIONS_KEY = "versions"
David Brown23f91ad2017-05-16 11:38:17 -060038
39# Image header flags.
40IMAGE_F = {
41 'PIC': 0x0000001,
Fabio Utzig06b77b82018-08-23 16:01:16 -030042 'NON_BOOTABLE': 0x0000010,
43 'ENCRYPTED': 0x0000004,
44}
David Brown23f91ad2017-05-16 11:38:17 -060045
46TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060047 'KEYHASH': 0x01,
David Brown27648b82017-08-31 10:40:29 -060048 'SHA256': 0x10,
49 'RSA2048': 0x20,
50 'ECDSA224': 0x21,
Fabio Utzig06b77b82018-08-23 16:01:16 -030051 'ECDSA256': 0x22,
52 'ENCRSA2048': 0x30,
53 'ENCKW128': 0x31,
David Vinczeda8c9192019-03-26 17:17:41 +010054 'DEPENDENCY': 0x40
Fabio Utzig06b77b82018-08-23 16:01:16 -030055}
David Brown23f91ad2017-05-16 11:38:17 -060056
David Brownf5b33d82017-09-01 10:58:27 -060057TLV_INFO_SIZE = 4
58TLV_INFO_MAGIC = 0x6907
David Brown23f91ad2017-05-16 11:38:17 -060059
David Brown23f91ad2017-05-16 11:38:17 -060060boot_magic = bytes([
61 0x77, 0xc2, 0x95, 0xf3,
62 0x60, 0xd2, 0xef, 0x7f,
63 0x35, 0x52, 0x50, 0x0f,
64 0x2c, 0xb6, 0x79, 0x80, ])
65
Mark Schultea66c6872018-09-26 17:24:40 -070066STRUCT_ENDIAN_DICT = {
67 'little': '<',
68 'big': '>'
69}
70
David Brown23f91ad2017-05-16 11:38:17 -060071class TLV():
Mark Schultea66c6872018-09-26 17:24:40 -070072 def __init__(self, endian):
David Brown23f91ad2017-05-16 11:38:17 -060073 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -070074 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -060075
76 def add(self, kind, payload):
77 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
Mark Schultea66c6872018-09-26 17:24:40 -070078 e = STRUCT_ENDIAN_DICT[self.endian]
79 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -060080 self.buf += buf
81 self.buf += payload
82
83 def get(self):
Mark Schultea66c6872018-09-26 17:24:40 -070084 e = STRUCT_ENDIAN_DICT[self.endian]
85 header = struct.pack(e + 'HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
David Brownf5b33d82017-09-01 10:58:27 -060086 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -060087
Fabio Utzig7c00acd2019-01-07 09:54:20 -020088
David Brown23f91ad2017-05-16 11:38:17 -060089class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +010090
Fabio Utzig7c00acd2019-01-07 09:54:20 -020091 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
92 pad_header=False, pad=False, align=1, slot_size=0,
93 max_sectors=DEFAULT_MAX_SECTORS, overwrite_only=False,
94 endian="little"):
David Brown23f91ad2017-05-16 11:38:17 -060095 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -020096 self.header_size = header_size
97 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -060098 self.pad = pad
Fabio Utzig263d4392018-06-05 10:37:35 -030099 self.align = align
100 self.slot_size = slot_size
101 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700102 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700103 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200104 self.base_addr = None
105 self.payload = []
David Brown23f91ad2017-05-16 11:38:17 -0600106
107 def __repr__(self):
Fabio Utzig263d4392018-06-05 10:37:35 -0300108 return "<Image version={}, header_size={}, base_addr={}, \
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700109 align={}, slot_size={}, max_sectors={}, overwrite_only={}, \
Mark Schultea66c6872018-09-26 17:24:40 -0700110 endian={} format={}, payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300111 self.version,
112 self.header_size,
113 self.base_addr if self.base_addr is not None else "N/A",
114 self.align,
115 self.slot_size,
116 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700117 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700118 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300119 self.__class__.__name__,
120 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600121
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200122 def load(self, path):
123 """Load an image from a given file"""
124 ext = os.path.splitext(path)[1][1:].lower()
125 if ext == INTEL_HEX_EXT:
126 ih = IntelHex(path)
127 self.payload = ih.tobinarray()
128 self.base_addr = ih.minaddr()
129 else:
130 with open(path, 'rb') as f:
131 self.payload = f.read()
132
133 # Add the image header if needed.
134 if self.pad_header and self.header_size > 0:
135 if self.base_addr:
136 # Adjust base_addr for new header
137 self.base_addr -= self.header_size
138 self.payload = (b'\000' * self.header_size) + self.payload
139
140 self.check()
141
142 def save(self, path):
143 """Save an image from a given file"""
144 if self.pad:
145 self.pad_to(self.slot_size)
146
147 ext = os.path.splitext(path)[1][1:].lower()
148 if ext == INTEL_HEX_EXT:
149 # input was in binary format, but HEX needs to know the base addr
150 if self.base_addr is None:
151 raise Exception("Input file does not provide a base address")
152 h = IntelHex()
153 h.frombytes(bytes=self.payload, offset=self.base_addr)
154 h.tofile(path, 'hex')
155 else:
156 with open(path, 'wb') as f:
157 f.write(self.payload)
158
David Brown23f91ad2017-05-16 11:38:17 -0600159 def check(self):
160 """Perform some sanity checking of the image."""
161 # If there is a header requested, make sure that the image
162 # starts with all zeros.
163 if self.header_size > 0:
164 if any(v != 0 for v in self.payload[0:self.header_size]):
165 raise Exception("Padding requested, but image does not start with zeros")
Fabio Utzig263d4392018-06-05 10:37:35 -0300166 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700167 tsize = self._trailer_size(self.align, self.max_sectors,
168 self.overwrite_only)
Fabio Utzig263d4392018-06-05 10:37:35 -0300169 padding = self.slot_size - (len(self.payload) + tsize)
170 if padding < 0:
171 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
172 len(self.payload), tsize, self.slot_size)
173 raise Exception(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600174
David Vinczeda8c9192019-03-26 17:17:41 +0100175 def create(self, key, enckey, dependencies=None):
176 if dependencies is None:
177 dependencies_num = 0
178 protected_tlv_size = 0
179 else:
180 # Size of a Dependency TLV = Header ('BBH') + Payload('IBBHI')
181 # = 16 Bytes
182 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
183 protected_tlv_size = (dependencies_num * 16) + TLV_INFO_SIZE
184
185 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600186
Mark Schultea66c6872018-09-26 17:24:40 -0700187 tlv = TLV(self.endian)
David Brown23f91ad2017-05-16 11:38:17 -0600188
David Vinczeda8c9192019-03-26 17:17:41 +0100189 if protected_tlv_size != 0:
190 for i in range(dependencies_num):
191 e = STRUCT_ENDIAN_DICT[self.endian]
192 payload = struct.pack(
193 e + 'I'+'BBHI',
194 int(dependencies[DEP_IMAGES_KEY][i]),
195 dependencies[DEP_VERSIONS_KEY][i].major,
196 dependencies[DEP_VERSIONS_KEY][i].minor,
197 dependencies[DEP_VERSIONS_KEY][i].revision,
198 dependencies[DEP_VERSIONS_KEY][i].build
199 )
200 tlv.add('DEPENDENCY', payload)
201 # Full TLV size needs to be calculated in advance, because the
202 # header will be protected as well
203 tlv_header_size = 4
204 payload_digest_size = 32
205 keyhash_size = 32
206 cipherkey_size = 32
207
208 full_size = TLV_INFO_SIZE + len(tlv.buf) + tlv_header_size \
209 + payload_digest_size
210 if key is not None:
211 full_size += tlv_header_size + keyhash_size \
212 + tlv_header_size + key.sig_len()
213 if enckey is not None:
214 full_size += tlv_header_size + cipherkey_size
215 tlv_header = struct.pack(e + 'HH', TLV_INFO_MAGIC, full_size)
216 self.payload += tlv_header + bytes(tlv.buf)
217
David Brown23f91ad2017-05-16 11:38:17 -0600218 # Note that ecdsa wants to do the hashing itself, which means
219 # we get to hash it twice.
220 sha = hashlib.sha256()
221 sha.update(self.payload)
222 digest = sha.digest()
223
224 tlv.add('SHA256', digest)
225
David Brown0f0c6a82017-06-08 09:26:24 -0600226 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600227 pub = key.get_public_bytes()
228 sha = hashlib.sha256()
229 sha.update(pub)
230 pubbytes = sha.digest()
231 tlv.add('KEYHASH', pubbytes)
232
David Brown47b77c52017-11-16 15:10:22 -0700233 sig = key.sign(bytes(self.payload))
David Brown0f0c6a82017-06-08 09:26:24 -0600234 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600235
Fabio Utzig06b77b82018-08-23 16:01:16 -0300236 if enckey is not None:
237 plainkey = os.urandom(16)
238 cipherkey = enckey._get_public().encrypt(
239 plainkey, padding.OAEP(
240 mgf=padding.MGF1(algorithm=hashes.SHA256()),
241 algorithm=hashes.SHA256(),
242 label=None))
243 tlv.add('ENCRSA2048', cipherkey)
244
245 nonce = bytes([0] * 16)
246 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
247 backend=default_backend())
248 encryptor = cipher.encryptor()
249 img = bytes(self.payload[self.header_size:])
250 self.payload[self.header_size:] = encryptor.update(img) + \
251 encryptor.finalize()
252
David Vinczeda8c9192019-03-26 17:17:41 +0100253 self.payload += tlv.get()[protected_tlv_size:]
David Brown23f91ad2017-05-16 11:38:17 -0600254
David Vinczeda8c9192019-03-26 17:17:41 +0100255 def add_header(self, enckey, protected_tlv_size):
Fabio Utzigcd284062018-11-30 11:05:45 -0200256 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600257
David Brown0f0c6a82017-06-08 09:26:24 -0600258 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300259 if enckey is not None:
260 flags |= IMAGE_F['ENCRYPTED']
David Brown23f91ad2017-05-16 11:38:17 -0600261
Mark Schultea66c6872018-09-26 17:24:40 -0700262 e = STRUCT_ENDIAN_DICT[self.endian]
263 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100264 # type ImageHdr struct {
265 'I' + # Magic uint32
266 'I' + # LoadAddr uint32
267 'H' + # HdrSz uint16
268 'H' + # PTLVSz uint16
269 'I' + # ImgSz uint32
270 'I' + # Flags uint32
271 'BBHI' + # Vers ImageVersion
272 'I' # Pad1 uint32
273 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600274 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
275 header = struct.pack(fmt,
276 IMAGE_MAGIC,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300277 0, # LoadAddr
David Brown23f91ad2017-05-16 11:38:17 -0600278 self.header_size,
David Vinczeda8c9192019-03-26 17:17:41 +0100279 protected_tlv_size, # TLV Info header + Dependency TLVs
David Brown23f91ad2017-05-16 11:38:17 -0600280 len(self.payload) - self.header_size, # ImageSz
281 flags, # Flags
282 self.version.major,
283 self.version.minor or 0,
284 self.version.revision or 0,
285 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100286 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600287 self.payload = bytearray(self.payload)
288 self.payload[:len(header)] = header
289
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700290 def _trailer_size(self, write_size, max_sectors, overwrite_only):
Fabio Utzig519285f2018-06-04 11:11:53 -0300291 # NOTE: should already be checked by the argument parser
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700292 if overwrite_only:
293 return 8 * 2 + 16
294 else:
295 if write_size not in set([1, 2, 4, 8]):
296 raise Exception("Invalid alignment: {}".format(write_size))
297 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
298 return m * 3 * write_size + 8 * 2 + 16
Fabio Utzig519285f2018-06-04 11:11:53 -0300299
Fabio Utzig263d4392018-06-05 10:37:35 -0300300 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600301 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700302 tsize = self._trailer_size(self.align, self.max_sectors,
303 self.overwrite_only)
David Brown23f91ad2017-05-16 11:38:17 -0600304 padding = size - (len(self.payload) + tsize)
Fabio Utzige08f0872017-06-28 18:12:16 -0300305 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600306 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300307 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600308 self.payload += pbytes