blob: 1e8d243b9c8745e4e4c8d3827816a51b94e77e87 [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
53class TLV():
54 def __init__(self):
55 self.buf = bytearray()
56
57 def add(self, kind, payload):
58 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
59 buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
60 self.buf += buf
61 self.buf += payload
62
63 def get(self):
David Brownf5b33d82017-09-01 10:58:27 -060064 header = struct.pack('<HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
65 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -060066
67class Image():
68 @classmethod
Fabio Utzig44588ef2018-06-12 16:49:00 -070069 def load(cls, path, pad_header=False, **kwargs):
David Brown23f91ad2017-05-16 11:38:17 -060070 """Load an image from a given file"""
Carles Cufi37d052f2018-01-30 16:40:10 +010071 ext = os.path.splitext(path)[1][1:].lower()
72 if ext == INTEL_HEX_EXT:
73 cls = HexImage
74 else:
75 cls = BinImage
76
David Brown23f91ad2017-05-16 11:38:17 -060077 obj = cls(**kwargs)
Carles Cufi37d052f2018-01-30 16:40:10 +010078 obj.payload, obj.base_addr = obj.load(path)
David Brown2c21f712017-06-08 10:03:42 -060079
80 # Add the image header if needed.
Fabio Utzig44588ef2018-06-12 16:49:00 -070081 if pad_header and obj.header_size > 0:
Mark Schulte884be202018-07-09 14:39:53 -070082 if obj.base_addr:
83 # Adjust base_addr for new header
84 obj.base_addr -= obj.header_size
David Brown2c21f712017-06-08 10:03:42 -060085 obj.payload = (b'\000' * obj.header_size) + obj.payload
86
David Brown23f91ad2017-05-16 11:38:17 -060087 obj.check()
88 return obj
89
Fabio Utzig263d4392018-06-05 10:37:35 -030090 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE, pad=0,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -070091 align=1, slot_size=0, max_sectors=DEFAULT_MAX_SECTORS,
92 overwrite_only=False):
David Brown23f91ad2017-05-16 11:38:17 -060093 self.version = version or versmod.decode_version("0")
94 self.header_size = header_size or IMAGE_HEADER_SIZE
95 self.pad = pad
Fabio Utzig263d4392018-06-05 10:37:35 -030096 self.align = align
97 self.slot_size = slot_size
98 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -070099 self.overwrite_only = overwrite_only
David Brown23f91ad2017-05-16 11:38:17 -0600100
101 def __repr__(self):
Fabio Utzig263d4392018-06-05 10:37:35 -0300102 return "<Image version={}, header_size={}, base_addr={}, \
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700103 align={}, slot_size={}, max_sectors={}, overwrite_only={}, \
104 format={}, payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300105 self.version,
106 self.header_size,
107 self.base_addr if self.base_addr is not None else "N/A",
108 self.align,
109 self.slot_size,
110 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700111 self.overwrite_only,
Fabio Utzig263d4392018-06-05 10:37:35 -0300112 self.__class__.__name__,
113 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600114
David Brown23f91ad2017-05-16 11:38:17 -0600115 def check(self):
116 """Perform some sanity checking of the image."""
117 # If there is a header requested, make sure that the image
118 # starts with all zeros.
119 if self.header_size > 0:
120 if any(v != 0 for v in self.payload[0:self.header_size]):
121 raise Exception("Padding requested, but image does not start with zeros")
Fabio Utzig263d4392018-06-05 10:37:35 -0300122 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700123 tsize = self._trailer_size(self.align, self.max_sectors,
124 self.overwrite_only)
Fabio Utzig263d4392018-06-05 10:37:35 -0300125 padding = self.slot_size - (len(self.payload) + tsize)
126 if padding < 0:
127 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
128 len(self.payload), tsize, self.slot_size)
129 raise Exception(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600130
131 def sign(self, key):
132 self.add_header(key)
133
134 tlv = TLV()
135
136 # Note that ecdsa wants to do the hashing itself, which means
137 # we get to hash it twice.
138 sha = hashlib.sha256()
139 sha.update(self.payload)
140 digest = sha.digest()
141
142 tlv.add('SHA256', digest)
143
David Brown0f0c6a82017-06-08 09:26:24 -0600144 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600145 pub = key.get_public_bytes()
146 sha = hashlib.sha256()
147 sha.update(pub)
148 pubbytes = sha.digest()
149 tlv.add('KEYHASH', pubbytes)
150
David Brown47b77c52017-11-16 15:10:22 -0700151 sig = key.sign(bytes(self.payload))
David Brown0f0c6a82017-06-08 09:26:24 -0600152 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600153
154 self.payload += tlv.get()
155
156 def add_header(self, key):
157 """Install the image header.
158
159 The key is needed to know the type of signature, and
160 approximate the size of the signature."""
161
David Brown0f0c6a82017-06-08 09:26:24 -0600162 flags = 0
David Brown23f91ad2017-05-16 11:38:17 -0600163
164 fmt = ('<' +
165 # type ImageHdr struct {
166 'I' + # Magic uint32
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300167 'I' + # LoadAddr uint32
David Brown23f91ad2017-05-16 11:38:17 -0600168 'H' + # HdrSz uint16
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300169 'H' + # Pad1 uint16
David Brown23f91ad2017-05-16 11:38:17 -0600170 'I' + # ImgSz uint32
171 'I' + # Flags uint32
172 'BBHI' + # Vers ImageVersion
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300173 'I' # Pad2 uint32
David Brown23f91ad2017-05-16 11:38:17 -0600174 ) # }
175 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
176 header = struct.pack(fmt,
177 IMAGE_MAGIC,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300178 0, # LoadAddr
David Brown23f91ad2017-05-16 11:38:17 -0600179 self.header_size,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300180 0, # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600181 len(self.payload) - self.header_size, # ImageSz
182 flags, # Flags
183 self.version.major,
184 self.version.minor or 0,
185 self.version.revision or 0,
186 self.version.build or 0,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300187 0) # Pad2
David Brown23f91ad2017-05-16 11:38:17 -0600188 self.payload = bytearray(self.payload)
189 self.payload[:len(header)] = header
190
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700191 def _trailer_size(self, write_size, max_sectors, overwrite_only):
Fabio Utzig519285f2018-06-04 11:11:53 -0300192 # NOTE: should already be checked by the argument parser
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700193 if overwrite_only:
194 return 8 * 2 + 16
195 else:
196 if write_size not in set([1, 2, 4, 8]):
197 raise Exception("Invalid alignment: {}".format(write_size))
198 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
199 return m * 3 * write_size + 8 * 2 + 16
Fabio Utzig519285f2018-06-04 11:11:53 -0300200
Fabio Utzig263d4392018-06-05 10:37:35 -0300201 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600202 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700203 tsize = self._trailer_size(self.align, self.max_sectors,
204 self.overwrite_only)
David Brown23f91ad2017-05-16 11:38:17 -0600205 padding = size - (len(self.payload) + tsize)
Fabio Utzige08f0872017-06-28 18:12:16 -0300206 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600207 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300208 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600209 self.payload += pbytes
Carles Cufi37d052f2018-01-30 16:40:10 +0100210
Fabio Utzig263d4392018-06-05 10:37:35 -0300211
Carles Cufi37d052f2018-01-30 16:40:10 +0100212class HexImage(Image):
213
214 def load(self, path):
215 ih = IntelHex(path)
216 return ih.tobinarray(), ih.minaddr()
217
218 def save(self, path):
219 h = IntelHex()
220 h.frombytes(bytes = self.payload, offset = self.base_addr)
221 h.tofile(path, 'hex')
222
223class BinImage(Image):
224
225 def load(self, path):
226 with open(path, 'rb') as f:
227 return f.read(), None
228
229 def save(self, path):
230 with open(path, 'wb') as f:
231 f.write(self.payload)