blob: ad156a10872d2b1d160390829f22db10e7c1190f [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,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030052 'RSA3072': 0x23,
Fabio Utzig06b77b82018-08-23 16:01:16 -030053 'ENCRSA2048': 0x30,
54 'ENCKW128': 0x31,
David Vinczeda8c9192019-03-26 17:17:41 +010055 'DEPENDENCY': 0x40
Fabio Utzig06b77b82018-08-23 16:01:16 -030056}
David Brown23f91ad2017-05-16 11:38:17 -060057
David Brownf5b33d82017-09-01 10:58:27 -060058TLV_INFO_SIZE = 4
59TLV_INFO_MAGIC = 0x6907
David Brown23f91ad2017-05-16 11:38:17 -060060
David Brown23f91ad2017-05-16 11:38:17 -060061boot_magic = bytes([
62 0x77, 0xc2, 0x95, 0xf3,
63 0x60, 0xd2, 0xef, 0x7f,
64 0x35, 0x52, 0x50, 0x0f,
65 0x2c, 0xb6, 0x79, 0x80, ])
66
Mark Schultea66c6872018-09-26 17:24:40 -070067STRUCT_ENDIAN_DICT = {
68 'little': '<',
69 'big': '>'
70}
71
David Brown23f91ad2017-05-16 11:38:17 -060072class TLV():
Mark Schultea66c6872018-09-26 17:24:40 -070073 def __init__(self, endian):
David Brown23f91ad2017-05-16 11:38:17 -060074 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -070075 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -060076
77 def add(self, kind, payload):
78 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
Mark Schultea66c6872018-09-26 17:24:40 -070079 e = STRUCT_ENDIAN_DICT[self.endian]
80 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -060081 self.buf += buf
82 self.buf += payload
83
84 def get(self):
Mark Schultea66c6872018-09-26 17:24:40 -070085 e = STRUCT_ENDIAN_DICT[self.endian]
86 header = struct.pack(e + 'HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
David Brownf5b33d82017-09-01 10:58:27 -060087 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -060088
Fabio Utzig7c00acd2019-01-07 09:54:20 -020089
David Brown23f91ad2017-05-16 11:38:17 -060090class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +010091
Fabio Utzig7c00acd2019-01-07 09:54:20 -020092 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
93 pad_header=False, pad=False, align=1, slot_size=0,
94 max_sectors=DEFAULT_MAX_SECTORS, overwrite_only=False,
95 endian="little"):
David Brown23f91ad2017-05-16 11:38:17 -060096 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -020097 self.header_size = header_size
98 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -060099 self.pad = pad
Fabio Utzig263d4392018-06-05 10:37:35 -0300100 self.align = align
101 self.slot_size = slot_size
102 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700103 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700104 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200105 self.base_addr = None
106 self.payload = []
David Brown23f91ad2017-05-16 11:38:17 -0600107
108 def __repr__(self):
Fabio Utzig263d4392018-06-05 10:37:35 -0300109 return "<Image version={}, header_size={}, base_addr={}, \
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700110 align={}, slot_size={}, max_sectors={}, overwrite_only={}, \
Mark Schultea66c6872018-09-26 17:24:40 -0700111 endian={} format={}, payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300112 self.version,
113 self.header_size,
114 self.base_addr if self.base_addr is not None else "N/A",
115 self.align,
116 self.slot_size,
117 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700118 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700119 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300120 self.__class__.__name__,
121 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600122
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200123 def load(self, path):
124 """Load an image from a given file"""
125 ext = os.path.splitext(path)[1][1:].lower()
126 if ext == INTEL_HEX_EXT:
127 ih = IntelHex(path)
128 self.payload = ih.tobinarray()
129 self.base_addr = ih.minaddr()
130 else:
131 with open(path, 'rb') as f:
132 self.payload = f.read()
133
134 # Add the image header if needed.
135 if self.pad_header and self.header_size > 0:
136 if self.base_addr:
137 # Adjust base_addr for new header
138 self.base_addr -= self.header_size
139 self.payload = (b'\000' * self.header_size) + self.payload
140
141 self.check()
142
143 def save(self, path):
144 """Save an image from a given file"""
145 if self.pad:
146 self.pad_to(self.slot_size)
147
148 ext = os.path.splitext(path)[1][1:].lower()
149 if ext == INTEL_HEX_EXT:
150 # input was in binary format, but HEX needs to know the base addr
151 if self.base_addr is None:
152 raise Exception("Input file does not provide a base address")
153 h = IntelHex()
154 h.frombytes(bytes=self.payload, offset=self.base_addr)
155 h.tofile(path, 'hex')
156 else:
157 with open(path, 'wb') as f:
158 f.write(self.payload)
159
David Brown23f91ad2017-05-16 11:38:17 -0600160 def check(self):
161 """Perform some sanity checking of the image."""
162 # If there is a header requested, make sure that the image
163 # starts with all zeros.
164 if self.header_size > 0:
165 if any(v != 0 for v in self.payload[0:self.header_size]):
166 raise Exception("Padding requested, but image does not start with zeros")
Fabio Utzig263d4392018-06-05 10:37:35 -0300167 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700168 tsize = self._trailer_size(self.align, self.max_sectors,
169 self.overwrite_only)
Fabio Utzig263d4392018-06-05 10:37:35 -0300170 padding = self.slot_size - (len(self.payload) + tsize)
171 if padding < 0:
172 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
173 len(self.payload), tsize, self.slot_size)
174 raise Exception(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600175
David Vinczeda8c9192019-03-26 17:17:41 +0100176 def create(self, key, enckey, dependencies=None):
177 if dependencies is None:
178 dependencies_num = 0
179 protected_tlv_size = 0
180 else:
181 # Size of a Dependency TLV = Header ('BBH') + Payload('IBBHI')
182 # = 16 Bytes
183 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
184 protected_tlv_size = (dependencies_num * 16) + TLV_INFO_SIZE
185
186 self.add_header(enckey, protected_tlv_size)
David Brown23f91ad2017-05-16 11:38:17 -0600187
Mark Schultea66c6872018-09-26 17:24:40 -0700188 tlv = TLV(self.endian)
David Brown23f91ad2017-05-16 11:38:17 -0600189
David Vinczeda8c9192019-03-26 17:17:41 +0100190 if protected_tlv_size != 0:
191 for i in range(dependencies_num):
192 e = STRUCT_ENDIAN_DICT[self.endian]
193 payload = struct.pack(
194 e + 'I'+'BBHI',
195 int(dependencies[DEP_IMAGES_KEY][i]),
196 dependencies[DEP_VERSIONS_KEY][i].major,
197 dependencies[DEP_VERSIONS_KEY][i].minor,
198 dependencies[DEP_VERSIONS_KEY][i].revision,
199 dependencies[DEP_VERSIONS_KEY][i].build
200 )
201 tlv.add('DEPENDENCY', payload)
202 # Full TLV size needs to be calculated in advance, because the
203 # header will be protected as well
204 tlv_header_size = 4
205 payload_digest_size = 32
206 keyhash_size = 32
207 cipherkey_size = 32
208
209 full_size = TLV_INFO_SIZE + len(tlv.buf) + tlv_header_size \
210 + payload_digest_size
211 if key is not None:
212 full_size += tlv_header_size + keyhash_size \
213 + tlv_header_size + key.sig_len()
214 if enckey is not None:
215 full_size += tlv_header_size + cipherkey_size
216 tlv_header = struct.pack(e + 'HH', TLV_INFO_MAGIC, full_size)
217 self.payload += tlv_header + bytes(tlv.buf)
218
David Brown23f91ad2017-05-16 11:38:17 -0600219 # Note that ecdsa wants to do the hashing itself, which means
220 # we get to hash it twice.
221 sha = hashlib.sha256()
222 sha.update(self.payload)
223 digest = sha.digest()
224
225 tlv.add('SHA256', digest)
226
David Brown0f0c6a82017-06-08 09:26:24 -0600227 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600228 pub = key.get_public_bytes()
229 sha = hashlib.sha256()
230 sha.update(pub)
231 pubbytes = sha.digest()
232 tlv.add('KEYHASH', pubbytes)
233
David Brown47b77c52017-11-16 15:10:22 -0700234 sig = key.sign(bytes(self.payload))
David Brown0f0c6a82017-06-08 09:26:24 -0600235 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600236
Fabio Utzig06b77b82018-08-23 16:01:16 -0300237 if enckey is not None:
238 plainkey = os.urandom(16)
239 cipherkey = enckey._get_public().encrypt(
240 plainkey, padding.OAEP(
241 mgf=padding.MGF1(algorithm=hashes.SHA256()),
242 algorithm=hashes.SHA256(),
243 label=None))
244 tlv.add('ENCRSA2048', cipherkey)
245
246 nonce = bytes([0] * 16)
247 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
248 backend=default_backend())
249 encryptor = cipher.encryptor()
250 img = bytes(self.payload[self.header_size:])
251 self.payload[self.header_size:] = encryptor.update(img) + \
252 encryptor.finalize()
253
David Vinczeda8c9192019-03-26 17:17:41 +0100254 self.payload += tlv.get()[protected_tlv_size:]
David Brown23f91ad2017-05-16 11:38:17 -0600255
David Vinczeda8c9192019-03-26 17:17:41 +0100256 def add_header(self, enckey, protected_tlv_size):
Fabio Utzigcd284062018-11-30 11:05:45 -0200257 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600258
David Brown0f0c6a82017-06-08 09:26:24 -0600259 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300260 if enckey is not None:
261 flags |= IMAGE_F['ENCRYPTED']
David Brown23f91ad2017-05-16 11:38:17 -0600262
Mark Schultea66c6872018-09-26 17:24:40 -0700263 e = STRUCT_ENDIAN_DICT[self.endian]
264 fmt = (e +
David Vinczeda8c9192019-03-26 17:17:41 +0100265 # type ImageHdr struct {
266 'I' + # Magic uint32
267 'I' + # LoadAddr uint32
268 'H' + # HdrSz uint16
269 'H' + # PTLVSz uint16
270 'I' + # ImgSz uint32
271 'I' + # Flags uint32
272 'BBHI' + # Vers ImageVersion
273 'I' # Pad1 uint32
274 ) # }
David Brown23f91ad2017-05-16 11:38:17 -0600275 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
276 header = struct.pack(fmt,
277 IMAGE_MAGIC,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300278 0, # LoadAddr
David Brown23f91ad2017-05-16 11:38:17 -0600279 self.header_size,
David Vinczeda8c9192019-03-26 17:17:41 +0100280 protected_tlv_size, # TLV Info header + Dependency TLVs
David Brown23f91ad2017-05-16 11:38:17 -0600281 len(self.payload) - self.header_size, # ImageSz
282 flags, # Flags
283 self.version.major,
284 self.version.minor or 0,
285 self.version.revision or 0,
286 self.version.build or 0,
David Vinczeda8c9192019-03-26 17:17:41 +0100287 0) # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600288 self.payload = bytearray(self.payload)
289 self.payload[:len(header)] = header
290
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700291 def _trailer_size(self, write_size, max_sectors, overwrite_only):
Fabio Utzig519285f2018-06-04 11:11:53 -0300292 # NOTE: should already be checked by the argument parser
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700293 if overwrite_only:
294 return 8 * 2 + 16
295 else:
296 if write_size not in set([1, 2, 4, 8]):
297 raise Exception("Invalid alignment: {}".format(write_size))
298 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
299 return m * 3 * write_size + 8 * 2 + 16
Fabio Utzig519285f2018-06-04 11:11:53 -0300300
Fabio Utzig263d4392018-06-05 10:37:35 -0300301 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600302 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700303 tsize = self._trailer_size(self.align, self.max_sectors,
304 self.overwrite_only)
David Brown23f91ad2017-05-16 11:38:17 -0600305 padding = size - (len(self.payload) + tsize)
Fabio Utzige08f0872017-06-28 18:12:16 -0300306 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600307 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300308 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600309 self.payload += pbytes