blob: 3ccd86f995a215720b588db9223ad1f6cb439e71 [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
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
David Brown23f91ad2017-05-16 11:38:17 -060016"""
17Image signing and management.
18"""
19
20from . import version as versmod
Carles Cufi37d052f2018-01-30 16:40:10 +010021from intelhex import IntelHex
David Brown23f91ad2017-05-16 11:38:17 -060022import hashlib
23import struct
Carles Cufi37d052f2018-01-30 16:40:10 +010024import os.path
Fabio Utzig06b77b82018-08-23 16:01:16 -030025from cryptography.hazmat.primitives.asymmetric import padding
26from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
27from cryptography.hazmat.backends import default_backend
28from cryptography.hazmat.primitives import hashes
David Brown23f91ad2017-05-16 11:38:17 -060029
David Brown72e7a512017-09-01 11:08:23 -060030IMAGE_MAGIC = 0x96f3b83d
David Brown23f91ad2017-05-16 11:38:17 -060031IMAGE_HEADER_SIZE = 32
Carles Cufi37d052f2018-01-30 16:40:10 +010032BIN_EXT = "bin"
33INTEL_HEX_EXT = "hex"
Fabio Utzig519285f2018-06-04 11:11:53 -030034DEFAULT_MAX_SECTORS = 128
David Brown23f91ad2017-05-16 11:38:17 -060035
36# Image header flags.
37IMAGE_F = {
38 'PIC': 0x0000001,
Fabio Utzig06b77b82018-08-23 16:01:16 -030039 'NON_BOOTABLE': 0x0000010,
40 'ENCRYPTED': 0x0000004,
41}
David Brown23f91ad2017-05-16 11:38:17 -060042
43TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060044 'KEYHASH': 0x01,
David Brown27648b82017-08-31 10:40:29 -060045 'SHA256': 0x10,
46 'RSA2048': 0x20,
47 'ECDSA224': 0x21,
Fabio Utzig06b77b82018-08-23 16:01:16 -030048 'ECDSA256': 0x22,
49 'ENCRSA2048': 0x30,
50 'ENCKW128': 0x31,
51}
David Brown23f91ad2017-05-16 11:38:17 -060052
David Brownf5b33d82017-09-01 10:58:27 -060053TLV_INFO_SIZE = 4
54TLV_INFO_MAGIC = 0x6907
David Brown23f91ad2017-05-16 11:38:17 -060055
David Brown23f91ad2017-05-16 11:38:17 -060056boot_magic = bytes([
57 0x77, 0xc2, 0x95, 0xf3,
58 0x60, 0xd2, 0xef, 0x7f,
59 0x35, 0x52, 0x50, 0x0f,
60 0x2c, 0xb6, 0x79, 0x80, ])
61
Mark Schultea66c6872018-09-26 17:24:40 -070062STRUCT_ENDIAN_DICT = {
63 'little': '<',
64 'big': '>'
65}
66
David Brown23f91ad2017-05-16 11:38:17 -060067class TLV():
Mark Schultea66c6872018-09-26 17:24:40 -070068 def __init__(self, endian):
David Brown23f91ad2017-05-16 11:38:17 -060069 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -070070 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -060071
72 def add(self, kind, payload):
73 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
Mark Schultea66c6872018-09-26 17:24:40 -070074 e = STRUCT_ENDIAN_DICT[self.endian]
75 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -060076 self.buf += buf
77 self.buf += payload
78
79 def get(self):
Mark Schultea66c6872018-09-26 17:24:40 -070080 e = STRUCT_ENDIAN_DICT[self.endian]
81 header = struct.pack(e + 'HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
David Brownf5b33d82017-09-01 10:58:27 -060082 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -060083
Fabio Utzig7c00acd2019-01-07 09:54:20 -020084
David Brown23f91ad2017-05-16 11:38:17 -060085class Image():
Carles Cufi37d052f2018-01-30 16:40:10 +010086
Fabio Utzig7c00acd2019-01-07 09:54:20 -020087 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE,
88 pad_header=False, pad=False, align=1, slot_size=0,
89 max_sectors=DEFAULT_MAX_SECTORS, overwrite_only=False,
90 endian="little"):
David Brown23f91ad2017-05-16 11:38:17 -060091 self.version = version or versmod.decode_version("0")
Fabio Utzig7c00acd2019-01-07 09:54:20 -020092 self.header_size = header_size
93 self.pad_header = pad_header
David Brown23f91ad2017-05-16 11:38:17 -060094 self.pad = pad
Fabio Utzig263d4392018-06-05 10:37:35 -030095 self.align = align
96 self.slot_size = slot_size
97 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -070098 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -070099 self.endian = endian
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200100 self.base_addr = None
101 self.payload = []
David Brown23f91ad2017-05-16 11:38:17 -0600102
103 def __repr__(self):
Fabio Utzig263d4392018-06-05 10:37:35 -0300104 return "<Image version={}, header_size={}, base_addr={}, \
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700105 align={}, slot_size={}, max_sectors={}, overwrite_only={}, \
Mark Schultea66c6872018-09-26 17:24:40 -0700106 endian={} format={}, payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300107 self.version,
108 self.header_size,
109 self.base_addr if self.base_addr is not None else "N/A",
110 self.align,
111 self.slot_size,
112 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700113 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700114 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300115 self.__class__.__name__,
116 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600117
Fabio Utzig7c00acd2019-01-07 09:54:20 -0200118 def load(self, path):
119 """Load an image from a given file"""
120 ext = os.path.splitext(path)[1][1:].lower()
121 if ext == INTEL_HEX_EXT:
122 ih = IntelHex(path)
123 self.payload = ih.tobinarray()
124 self.base_addr = ih.minaddr()
125 else:
126 with open(path, 'rb') as f:
127 self.payload = f.read()
128
129 # Add the image header if needed.
130 if self.pad_header and self.header_size > 0:
131 if self.base_addr:
132 # Adjust base_addr for new header
133 self.base_addr -= self.header_size
134 self.payload = (b'\000' * self.header_size) + self.payload
135
136 self.check()
137
138 def save(self, path):
139 """Save an image from a given file"""
140 if self.pad:
141 self.pad_to(self.slot_size)
142
143 ext = os.path.splitext(path)[1][1:].lower()
144 if ext == INTEL_HEX_EXT:
145 # input was in binary format, but HEX needs to know the base addr
146 if self.base_addr is None:
147 raise Exception("Input file does not provide a base address")
148 h = IntelHex()
149 h.frombytes(bytes=self.payload, offset=self.base_addr)
150 h.tofile(path, 'hex')
151 else:
152 with open(path, 'wb') as f:
153 f.write(self.payload)
154
David Brown23f91ad2017-05-16 11:38:17 -0600155 def check(self):
156 """Perform some sanity checking of the image."""
157 # If there is a header requested, make sure that the image
158 # starts with all zeros.
159 if self.header_size > 0:
160 if any(v != 0 for v in self.payload[0:self.header_size]):
161 raise Exception("Padding requested, but image does not start with zeros")
Fabio Utzig263d4392018-06-05 10:37:35 -0300162 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700163 tsize = self._trailer_size(self.align, self.max_sectors,
164 self.overwrite_only)
Fabio Utzig263d4392018-06-05 10:37:35 -0300165 padding = self.slot_size - (len(self.payload) + tsize)
166 if padding < 0:
167 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
168 len(self.payload), tsize, self.slot_size)
169 raise Exception(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600170
Fabio Utzig06b77b82018-08-23 16:01:16 -0300171 def create(self, key, enckey):
Fabio Utzigcd284062018-11-30 11:05:45 -0200172 self.add_header(enckey)
David Brown23f91ad2017-05-16 11:38:17 -0600173
Mark Schultea66c6872018-09-26 17:24:40 -0700174 tlv = TLV(self.endian)
David Brown23f91ad2017-05-16 11:38:17 -0600175
176 # Note that ecdsa wants to do the hashing itself, which means
177 # we get to hash it twice.
178 sha = hashlib.sha256()
179 sha.update(self.payload)
180 digest = sha.digest()
181
182 tlv.add('SHA256', digest)
183
David Brown0f0c6a82017-06-08 09:26:24 -0600184 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600185 pub = key.get_public_bytes()
186 sha = hashlib.sha256()
187 sha.update(pub)
188 pubbytes = sha.digest()
189 tlv.add('KEYHASH', pubbytes)
190
David Brown47b77c52017-11-16 15:10:22 -0700191 sig = key.sign(bytes(self.payload))
David Brown0f0c6a82017-06-08 09:26:24 -0600192 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600193
Fabio Utzig06b77b82018-08-23 16:01:16 -0300194 if enckey is not None:
195 plainkey = os.urandom(16)
196 cipherkey = enckey._get_public().encrypt(
197 plainkey, padding.OAEP(
198 mgf=padding.MGF1(algorithm=hashes.SHA256()),
199 algorithm=hashes.SHA256(),
200 label=None))
201 tlv.add('ENCRSA2048', cipherkey)
202
203 nonce = bytes([0] * 16)
204 cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce),
205 backend=default_backend())
206 encryptor = cipher.encryptor()
207 img = bytes(self.payload[self.header_size:])
208 self.payload[self.header_size:] = encryptor.update(img) + \
209 encryptor.finalize()
210
David Brown23f91ad2017-05-16 11:38:17 -0600211 self.payload += tlv.get()
212
Fabio Utzigcd284062018-11-30 11:05:45 -0200213 def add_header(self, enckey):
214 """Install the image header."""
David Brown23f91ad2017-05-16 11:38:17 -0600215
David Brown0f0c6a82017-06-08 09:26:24 -0600216 flags = 0
Fabio Utzig06b77b82018-08-23 16:01:16 -0300217 if enckey is not None:
218 flags |= IMAGE_F['ENCRYPTED']
David Brown23f91ad2017-05-16 11:38:17 -0600219
Mark Schultea66c6872018-09-26 17:24:40 -0700220 e = STRUCT_ENDIAN_DICT[self.endian]
221 fmt = (e +
David Brown23f91ad2017-05-16 11:38:17 -0600222 # type ImageHdr struct {
223 'I' + # Magic uint32
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300224 'I' + # LoadAddr uint32
David Brown23f91ad2017-05-16 11:38:17 -0600225 'H' + # HdrSz uint16
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300226 'H' + # Pad1 uint16
David Brown23f91ad2017-05-16 11:38:17 -0600227 'I' + # ImgSz uint32
228 'I' + # Flags uint32
229 'BBHI' + # Vers ImageVersion
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300230 'I' # Pad2 uint32
David Brown23f91ad2017-05-16 11:38:17 -0600231 ) # }
232 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
233 header = struct.pack(fmt,
234 IMAGE_MAGIC,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300235 0, # LoadAddr
David Brown23f91ad2017-05-16 11:38:17 -0600236 self.header_size,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300237 0, # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600238 len(self.payload) - self.header_size, # ImageSz
239 flags, # Flags
240 self.version.major,
241 self.version.minor or 0,
242 self.version.revision or 0,
243 self.version.build or 0,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300244 0) # Pad2
David Brown23f91ad2017-05-16 11:38:17 -0600245 self.payload = bytearray(self.payload)
246 self.payload[:len(header)] = header
247
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700248 def _trailer_size(self, write_size, max_sectors, overwrite_only):
Fabio Utzig519285f2018-06-04 11:11:53 -0300249 # NOTE: should already be checked by the argument parser
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700250 if overwrite_only:
251 return 8 * 2 + 16
252 else:
253 if write_size not in set([1, 2, 4, 8]):
254 raise Exception("Invalid alignment: {}".format(write_size))
255 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
256 return m * 3 * write_size + 8 * 2 + 16
Fabio Utzig519285f2018-06-04 11:11:53 -0300257
Fabio Utzig263d4392018-06-05 10:37:35 -0300258 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600259 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700260 tsize = self._trailer_size(self.align, self.max_sectors,
261 self.overwrite_only)
David Brown23f91ad2017-05-16 11:38:17 -0600262 padding = size - (len(self.payload) + tsize)
Fabio Utzige08f0872017-06-28 18:12:16 -0300263 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600264 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300265 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600266 self.payload += pbytes