blob: ea318f707c37ee068f63d6fb9ac20eb0b2e441ab [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
David Brown2c21f712017-06-08 10:03:42 -060069 def load(cls, path, included_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.
81 if not included_header and obj.header_size > 0:
82 obj.payload = (b'\000' * obj.header_size) + obj.payload
83
David Brown23f91ad2017-05-16 11:38:17 -060084 obj.check()
85 return obj
86
Fabio Utzig263d4392018-06-05 10:37:35 -030087 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE, pad=0,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -070088 align=1, slot_size=0, max_sectors=DEFAULT_MAX_SECTORS,
89 overwrite_only=False):
David Brown23f91ad2017-05-16 11:38:17 -060090 self.version = version or versmod.decode_version("0")
91 self.header_size = header_size or IMAGE_HEADER_SIZE
92 self.pad = pad
Fabio Utzig263d4392018-06-05 10:37:35 -030093 self.align = align
94 self.slot_size = slot_size
95 self.max_sectors = max_sectors
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -070096 self.overwrite_only = overwrite_only
David Brown23f91ad2017-05-16 11:38:17 -060097
98 def __repr__(self):
Fabio Utzig263d4392018-06-05 10:37:35 -030099 return "<Image version={}, header_size={}, base_addr={}, \
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700100 align={}, slot_size={}, max_sectors={}, overwrite_only={}, \
101 format={}, payloadlen=0x{:x}>".format(
Fabio Utzig263d4392018-06-05 10:37:35 -0300102 self.version,
103 self.header_size,
104 self.base_addr if self.base_addr is not None else "N/A",
105 self.align,
106 self.slot_size,
107 self.max_sectors,
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700108 self.overwrite_only,
Fabio Utzig263d4392018-06-05 10:37:35 -0300109 self.__class__.__name__,
110 len(self.payload))
David Brown23f91ad2017-05-16 11:38:17 -0600111
David Brown23f91ad2017-05-16 11:38:17 -0600112 def check(self):
113 """Perform some sanity checking of the image."""
114 # If there is a header requested, make sure that the image
115 # starts with all zeros.
116 if self.header_size > 0:
117 if any(v != 0 for v in self.payload[0:self.header_size]):
118 raise Exception("Padding requested, but image does not start with zeros")
Fabio Utzig263d4392018-06-05 10:37:35 -0300119 if self.slot_size > 0:
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700120 tsize = self._trailer_size(self.align, self.max_sectors,
121 self.overwrite_only)
Fabio Utzig263d4392018-06-05 10:37:35 -0300122 padding = self.slot_size - (len(self.payload) + tsize)
123 if padding < 0:
124 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
125 len(self.payload), tsize, self.slot_size)
126 raise Exception(msg)
David Brown23f91ad2017-05-16 11:38:17 -0600127
128 def sign(self, key):
129 self.add_header(key)
130
131 tlv = TLV()
132
133 # Note that ecdsa wants to do the hashing itself, which means
134 # we get to hash it twice.
135 sha = hashlib.sha256()
136 sha.update(self.payload)
137 digest = sha.digest()
138
139 tlv.add('SHA256', digest)
140
David Brown0f0c6a82017-06-08 09:26:24 -0600141 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600142 pub = key.get_public_bytes()
143 sha = hashlib.sha256()
144 sha.update(pub)
145 pubbytes = sha.digest()
146 tlv.add('KEYHASH', pubbytes)
147
David Brown47b77c52017-11-16 15:10:22 -0700148 sig = key.sign(bytes(self.payload))
David Brown0f0c6a82017-06-08 09:26:24 -0600149 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600150
151 self.payload += tlv.get()
152
153 def add_header(self, key):
154 """Install the image header.
155
156 The key is needed to know the type of signature, and
157 approximate the size of the signature."""
158
David Brown0f0c6a82017-06-08 09:26:24 -0600159 flags = 0
David Brown23f91ad2017-05-16 11:38:17 -0600160
161 fmt = ('<' +
162 # type ImageHdr struct {
163 'I' + # Magic uint32
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300164 'I' + # LoadAddr uint32
David Brown23f91ad2017-05-16 11:38:17 -0600165 'H' + # HdrSz uint16
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300166 'H' + # Pad1 uint16
David Brown23f91ad2017-05-16 11:38:17 -0600167 'I' + # ImgSz uint32
168 'I' + # Flags uint32
169 'BBHI' + # Vers ImageVersion
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300170 'I' # Pad2 uint32
David Brown23f91ad2017-05-16 11:38:17 -0600171 ) # }
172 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
173 header = struct.pack(fmt,
174 IMAGE_MAGIC,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300175 0, # LoadAddr
David Brown23f91ad2017-05-16 11:38:17 -0600176 self.header_size,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300177 0, # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600178 len(self.payload) - self.header_size, # ImageSz
179 flags, # Flags
180 self.version.major,
181 self.version.minor or 0,
182 self.version.revision or 0,
183 self.version.build or 0,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300184 0) # Pad2
David Brown23f91ad2017-05-16 11:38:17 -0600185 self.payload = bytearray(self.payload)
186 self.payload[:len(header)] = header
187
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700188 def _trailer_size(self, write_size, max_sectors, overwrite_only):
Fabio Utzig519285f2018-06-04 11:11:53 -0300189 # NOTE: should already be checked by the argument parser
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700190 if overwrite_only:
191 return 8 * 2 + 16
192 else:
193 if write_size not in set([1, 2, 4, 8]):
194 raise Exception("Invalid alignment: {}".format(write_size))
195 m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
196 return m * 3 * write_size + 8 * 2 + 16
Fabio Utzig519285f2018-06-04 11:11:53 -0300197
Fabio Utzig263d4392018-06-05 10:37:35 -0300198 def pad_to(self, size):
David Brown23f91ad2017-05-16 11:38:17 -0600199 """Pad the image to the given size, with the given flash alignment."""
Fabio Utzigdcf0c9b2018-06-11 12:27:49 -0700200 tsize = self._trailer_size(self.align, self.max_sectors,
201 self.overwrite_only)
David Brown23f91ad2017-05-16 11:38:17 -0600202 padding = size - (len(self.payload) + tsize)
Fabio Utzige08f0872017-06-28 18:12:16 -0300203 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600204 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300205 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600206 self.payload += pbytes
Carles Cufi37d052f2018-01-30 16:40:10 +0100207
Fabio Utzig263d4392018-06-05 10:37:35 -0300208
Carles Cufi37d052f2018-01-30 16:40:10 +0100209class HexImage(Image):
210
211 def load(self, path):
212 ih = IntelHex(path)
213 return ih.tobinarray(), ih.minaddr()
214
215 def save(self, path):
216 h = IntelHex()
217 h.frombytes(bytes = self.payload, offset = self.base_addr)
218 h.tofile(path, 'hex')
219
220class BinImage(Image):
221
222 def load(self, path):
223 with open(path, 'rb') as f:
224 return f.read(), None
225
226 def save(self, path):
227 with open(path, 'wb') as f:
228 f.write(self.payload)