blob: 7a6111da2baf6fbb3962a68475a6bd4151da3e9f [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
David Brown23f91ad2017-05-16 11:38:17 -060025
David Brown72e7a512017-09-01 11:08:23 -060026IMAGE_MAGIC = 0x96f3b83d
David Brown23f91ad2017-05-16 11:38:17 -060027IMAGE_HEADER_SIZE = 32
Carles Cufi37d052f2018-01-30 16:40:10 +010028BIN_EXT = "bin"
29INTEL_HEX_EXT = "hex"
Fabio Utzig519285f2018-06-04 11:11:53 -030030DEFAULT_MAX_SECTORS = 128
David Brown23f91ad2017-05-16 11:38:17 -060031
32# Image header flags.
33IMAGE_F = {
34 'PIC': 0x0000001,
David Brown43cda332017-09-01 09:53:23 -060035 'NON_BOOTABLE': 0x0000010, }
David Brown23f91ad2017-05-16 11:38:17 -060036
37TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060038 'KEYHASH': 0x01,
David Brown27648b82017-08-31 10:40:29 -060039 'SHA256': 0x10,
40 'RSA2048': 0x20,
41 'ECDSA224': 0x21,
42 'ECDSA256': 0x22, }
David Brown23f91ad2017-05-16 11:38:17 -060043
David Brownf5b33d82017-09-01 10:58:27 -060044TLV_INFO_SIZE = 4
45TLV_INFO_MAGIC = 0x6907
David Brown23f91ad2017-05-16 11:38:17 -060046
David Brown23f91ad2017-05-16 11:38:17 -060047boot_magic = bytes([
48 0x77, 0xc2, 0x95, 0xf3,
49 0x60, 0xd2, 0xef, 0x7f,
50 0x35, 0x52, 0x50, 0x0f,
51 0x2c, 0xb6, 0x79, 0x80, ])
52
Mark Schultea66c6872018-09-26 17:24:40 -070053STRUCT_ENDIAN_DICT = {
54 'little': '<',
55 'big': '>'
56}
57
David Brown23f91ad2017-05-16 11:38:17 -060058class TLV():
Mark Schultea66c6872018-09-26 17:24:40 -070059 def __init__(self, endian):
David Brown23f91ad2017-05-16 11:38:17 -060060 self.buf = bytearray()
Mark Schultea66c6872018-09-26 17:24:40 -070061 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -060062
63 def add(self, kind, payload):
64 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
Mark Schultea66c6872018-09-26 17:24:40 -070065 e = STRUCT_ENDIAN_DICT[self.endian]
66 buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload))
David Brown23f91ad2017-05-16 11:38:17 -060067 self.buf += buf
68 self.buf += payload
69
70 def get(self):
Mark Schultea66c6872018-09-26 17:24:40 -070071 e = STRUCT_ENDIAN_DICT[self.endian]
72 header = struct.pack(e + 'HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
David Brownf5b33d82017-09-01 10:58:27 -060073 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -060074
75class Image():
76 @classmethod
Fabio Utzig44588ef2018-06-12 16:49:00 -070077 def load(cls, path, pad_header=False, **kwargs):
David Brown23f91ad2017-05-16 11:38:17 -060078 """Load an image from a given file"""
Carles Cufi37d052f2018-01-30 16:40:10 +010079 ext = os.path.splitext(path)[1][1:].lower()
80 if ext == INTEL_HEX_EXT:
81 cls = HexImage
82 else:
83 cls = BinImage
84
David Brown23f91ad2017-05-16 11:38:17 -060085 obj = cls(**kwargs)
Carles Cufi37d052f2018-01-30 16:40:10 +010086 obj.payload, obj.base_addr = obj.load(path)
David Brown2c21f712017-06-08 10:03:42 -060087
88 # Add the image header if needed.
Fabio Utzig44588ef2018-06-12 16:49:00 -070089 if pad_header and obj.header_size > 0:
Mark Schulte884be202018-07-09 14:39:53 -070090 if obj.base_addr:
91 # Adjust base_addr for new header
92 obj.base_addr -= obj.header_size
David Brown2c21f712017-06-08 10:03:42 -060093 obj.payload = (b'\000' * obj.header_size) + obj.payload
94
David Brown23f91ad2017-05-16 11:38:17 -060095 obj.check()
96 return obj
97
Fabio Utzig263d4392018-06-05 10:37:35 -030098 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE, pad=0,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -070099 align=1, slot_size=0, max_sectors=DEFAULT_MAX_SECTORS,
Mark Schultea66c6872018-09-26 17:24:40 -0700100 overwrite_only=False, endian="little"):
David Brown23f91ad2017-05-16 11:38:17 -0600101 self.version = version or versmod.decode_version("0")
102 self.header_size = header_size or IMAGE_HEADER_SIZE
103 self.pad = pad
Fabio Utzig263d4392018-06-05 10:37:35 -0300104 self.align = align
105 self.slot_size = slot_size
106 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700107 self.overwrite_only = overwrite_only
Mark Schultea66c6872018-09-26 17:24:40 -0700108 self.endian = endian
David Brown23f91ad2017-05-16 11:38:17 -0600109
110 def __repr__(self):
Fabio Utzig263d4392018-06-05 10:37:35 -0300111 return "<Image version={}, header_size={}, base_addr={}, \
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700112 align={}, slot_size={}, max_sectors={}, overwrite_only={}, \
Mark Schultea66c6872018-09-26 17:24:40 -0700113 endian={} format={}, payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300114 self.version,
115 self.header_size,
116 self.base_addr if self.base_addr is not None else "N/A",
117 self.align,
118 self.slot_size,
119 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700120 self.overwrite_only,
Mark Schultea66c6872018-09-26 17:24:40 -0700121 self.endian,
Fabio Utzig263d4392018-06-05 10:37:35 -0300122 self.__class__.__name__,
123 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600124
David Brown23f91ad2017-05-16 11:38:17 -0600125 def check(self):
126 """Perform some sanity checking of the image."""
127 # If there is a header requested, make sure that the image
128 # starts with all zeros.
129 if self.header_size > 0:
130 if any(v != 0 for v in self.payload[0:self.header_size]):
131 raise Exception("Padding requested, but image does not start with zeros")
Fabio Utzig263d4392018-06-05 10:37:35 -0300132 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700133 tsize = self._trailer_size(self.align, self.max_sectors,
134 self.overwrite_only)
Fabio Utzig263d4392018-06-05 10:37:35 -0300135 padding = self.slot_size - (len(self.payload) + tsize)
136 if padding < 0:
137 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
138 len(self.payload), tsize, self.slot_size)
139 raise Exception(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600140
141 def sign(self, key):
142 self.add_header(key)
143
Mark Schultea66c6872018-09-26 17:24:40 -0700144 tlv = TLV(self.endian)
David Brown23f91ad2017-05-16 11:38:17 -0600145
146 # Note that ecdsa wants to do the hashing itself, which means
147 # we get to hash it twice.
148 sha = hashlib.sha256()
149 sha.update(self.payload)
150 digest = sha.digest()
151
152 tlv.add('SHA256', digest)
153
David Brown0f0c6a82017-06-08 09:26:24 -0600154 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600155 pub = key.get_public_bytes()
156 sha = hashlib.sha256()
157 sha.update(pub)
158 pubbytes = sha.digest()
159 tlv.add('KEYHASH', pubbytes)
160
David Brown47b77c52017-11-16 15:10:22 -0700161 sig = key.sign(bytes(self.payload))
David Brown0f0c6a82017-06-08 09:26:24 -0600162 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600163
164 self.payload += tlv.get()
165
166 def add_header(self, key):
167 """Install the image header.
168
169 The key is needed to know the type of signature, and
170 approximate the size of the signature."""
171
David Brown0f0c6a82017-06-08 09:26:24 -0600172 flags = 0
David Brown23f91ad2017-05-16 11:38:17 -0600173
Mark Schultea66c6872018-09-26 17:24:40 -0700174 e = STRUCT_ENDIAN_DICT[self.endian]
175 fmt = (e +
David Brown23f91ad2017-05-16 11:38:17 -0600176 # type ImageHdr struct {
177 'I' + # Magic uint32
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300178 'I' + # LoadAddr uint32
David Brown23f91ad2017-05-16 11:38:17 -0600179 'H' + # HdrSz uint16
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300180 'H' + # Pad1 uint16
David Brown23f91ad2017-05-16 11:38:17 -0600181 'I' + # ImgSz uint32
182 'I' + # Flags uint32
183 'BBHI' + # Vers ImageVersion
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300184 'I' # Pad2 uint32
David Brown23f91ad2017-05-16 11:38:17 -0600185 ) # }
186 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
187 header = struct.pack(fmt,
188 IMAGE_MAGIC,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300189 0, # LoadAddr
David Brown23f91ad2017-05-16 11:38:17 -0600190 self.header_size,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300191 0, # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600192 len(self.payload) - self.header_size, # ImageSz
193 flags, # Flags
194 self.version.major,
195 self.version.minor or 0,
196 self.version.revision or 0,
197 self.version.build or 0,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300198 0) # Pad2
David Brown23f91ad2017-05-16 11:38:17 -0600199 self.payload = bytearray(self.payload)
200 self.payload[:len(header)] = header
201
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700202 def _trailer_size(self, write_size, max_sectors, overwrite_only):
Fabio Utzig519285f2018-06-04 11:11:53 -0300203 # NOTE: should already be checked by the argument parser
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700204 if overwrite_only:
205 return 8 * 2 + 16
206 else:
207 if write_size not in set([1, 2, 4, 8]):
208 raise Exception("Invalid alignment: {}".format(write_size))
209 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
210 return m * 3 * write_size + 8 * 2 + 16
Fabio Utzig519285f2018-06-04 11:11:53 -0300211
Fabio Utzig263d4392018-06-05 10:37:35 -0300212 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600213 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700214 tsize = self._trailer_size(self.align, self.max_sectors,
215 self.overwrite_only)
David Brown23f91ad2017-05-16 11:38:17 -0600216 padding = size - (len(self.payload) + tsize)
Fabio Utzige08f0872017-06-28 18:12:16 -0300217 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600218 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300219 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600220 self.payload += pbytes
Carles Cufi37d052f2018-01-30 16:40:10 +0100221
Fabio Utzig263d4392018-06-05 10:37:35 -0300222
Carles Cufi37d052f2018-01-30 16:40:10 +0100223class HexImage(Image):
224
225 def load(self, path):
226 ih = IntelHex(path)
227 return ih.tobinarray(), ih.minaddr()
228
229 def save(self, path):
230 h = IntelHex()
231 h.frombytes(bytes = self.payload, offset = self.base_addr)
232 h.tofile(path, 'hex')
233
234class BinImage(Image):
235
236 def load(self, path):
237 with open(path, 'rb') as f:
238 return f.read(), None
239
240 def save(self, path):
241 with open(path, 'wb') as f:
242 f.write(self.payload)