blob: 66e30b4edf04252ebb647764fd603ca011b4fd2b [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"
David Brown23f91ad2017-05-16 11:38:17 -060030
31# Image header flags.
32IMAGE_F = {
33 'PIC': 0x0000001,
David Brown43cda332017-09-01 09:53:23 -060034 'NON_BOOTABLE': 0x0000010, }
David Brown23f91ad2017-05-16 11:38:17 -060035
36TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060037 'KEYHASH': 0x01,
David Brown27648b82017-08-31 10:40:29 -060038 'SHA256': 0x10,
39 'RSA2048': 0x20,
40 'ECDSA224': 0x21,
41 'ECDSA256': 0x22, }
David Brown23f91ad2017-05-16 11:38:17 -060042
David Brownf5b33d82017-09-01 10:58:27 -060043TLV_INFO_SIZE = 4
44TLV_INFO_MAGIC = 0x6907
David Brown23f91ad2017-05-16 11:38:17 -060045TLV_HEADER_SIZE = 4
46
Fabio Utzige08f0872017-06-28 18:12:16 -030047# Sizes of the image trailer, depending on flash write size.
David Brown23f91ad2017-05-16 11:38:17 -060048trailer_sizes = {
Fabio Utzige08f0872017-06-28 18:12:16 -030049 write_size: 128 * 3 * write_size + 8 * 2 + 16
50 for write_size in [1, 2, 4, 8]
51}
David Brown23f91ad2017-05-16 11:38:17 -060052
53boot_magic = bytes([
54 0x77, 0xc2, 0x95, 0xf3,
55 0x60, 0xd2, 0xef, 0x7f,
56 0x35, 0x52, 0x50, 0x0f,
57 0x2c, 0xb6, 0x79, 0x80, ])
58
59class TLV():
60 def __init__(self):
61 self.buf = bytearray()
62
63 def add(self, kind, payload):
64 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
65 buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
66 self.buf += buf
67 self.buf += payload
68
69 def get(self):
David Brownf5b33d82017-09-01 10:58:27 -060070 header = struct.pack('<HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
71 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -060072
73class Image():
74 @classmethod
David Brown2c21f712017-06-08 10:03:42 -060075 def load(cls, path, included_header=False, **kwargs):
David Brown23f91ad2017-05-16 11:38:17 -060076 """Load an image from a given file"""
Carles Cufi37d052f2018-01-30 16:40:10 +010077 ext = os.path.splitext(path)[1][1:].lower()
78 if ext == INTEL_HEX_EXT:
79 cls = HexImage
80 else:
81 cls = BinImage
82
David Brown23f91ad2017-05-16 11:38:17 -060083 obj = cls(**kwargs)
Carles Cufi37d052f2018-01-30 16:40:10 +010084 obj.payload, obj.base_addr = obj.load(path)
David Brown2c21f712017-06-08 10:03:42 -060085
86 # Add the image header if needed.
87 if not included_header and obj.header_size > 0:
88 obj.payload = (b'\000' * obj.header_size) + obj.payload
89
David Brown23f91ad2017-05-16 11:38:17 -060090 obj.check()
91 return obj
92
93 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE, pad=0):
94 self.version = version or versmod.decode_version("0")
95 self.header_size = header_size or IMAGE_HEADER_SIZE
96 self.pad = pad
97
98 def __repr__(self):
Carles Cufi37d052f2018-01-30 16:40:10 +010099 return "<Image version={}, header_size={}, base_addr={}, pad={}, \
100 format={}, payloadlen=0x{:x}>".format(
David Brown23f91ad2017-05-16 11:38:17 -0600101 self.version,
102 self.header_size,
Carles Cufi37d052f2018-01-30 16:40:10 +0100103 self.base_addr if self.base_addr is not None else "N/A",
David Brown23f91ad2017-05-16 11:38:17 -0600104 self.pad,
Carles Cufi37d052f2018-01-30 16:40:10 +0100105 self.__class__.__name__,
David Brown23f91ad2017-05-16 11:38:17 -0600106 len(self.payload))
107
David Brown23f91ad2017-05-16 11:38:17 -0600108 def check(self):
109 """Perform some sanity checking of the image."""
110 # If there is a header requested, make sure that the image
111 # starts with all zeros.
112 if self.header_size > 0:
113 if any(v != 0 for v in self.payload[0:self.header_size]):
114 raise Exception("Padding requested, but image does not start with zeros")
115
116 def sign(self, key):
117 self.add_header(key)
118
119 tlv = TLV()
120
121 # Note that ecdsa wants to do the hashing itself, which means
122 # we get to hash it twice.
123 sha = hashlib.sha256()
124 sha.update(self.payload)
125 digest = sha.digest()
126
127 tlv.add('SHA256', digest)
128
David Brown0f0c6a82017-06-08 09:26:24 -0600129 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600130 pub = key.get_public_bytes()
131 sha = hashlib.sha256()
132 sha.update(pub)
133 pubbytes = sha.digest()
134 tlv.add('KEYHASH', pubbytes)
135
David Brown47b77c52017-11-16 15:10:22 -0700136 sig = key.sign(bytes(self.payload))
David Brown0f0c6a82017-06-08 09:26:24 -0600137 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600138
139 self.payload += tlv.get()
140
141 def add_header(self, key):
142 """Install the image header.
143
144 The key is needed to know the type of signature, and
145 approximate the size of the signature."""
146
David Brown0f0c6a82017-06-08 09:26:24 -0600147 flags = 0
David Brown23f91ad2017-05-16 11:38:17 -0600148 tlvsz = 0
David Brown0f0c6a82017-06-08 09:26:24 -0600149 if key is not None:
David Brown0f0c6a82017-06-08 09:26:24 -0600150 tlvsz += TLV_HEADER_SIZE + key.sig_len()
David Brown23f91ad2017-05-16 11:38:17 -0600151
David Brown43cda332017-09-01 09:53:23 -0600152 tlvsz += 4 + hashlib.sha256().digest_size
David Brown23f91ad2017-05-16 11:38:17 -0600153 tlvsz += 4 + hashlib.sha256().digest_size
154
155 fmt = ('<' +
156 # type ImageHdr struct {
157 'I' + # Magic uint32
158 'H' + # TlvSz uint16
159 'B' + # KeyId uint8
160 'B' + # Pad1 uint8
161 'H' + # HdrSz uint16
162 'H' + # Pad2 uint16
163 'I' + # ImgSz uint32
164 'I' + # Flags uint32
165 'BBHI' + # Vers ImageVersion
166 'I' # Pad3 uint32
167 ) # }
168 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
169 header = struct.pack(fmt,
170 IMAGE_MAGIC,
171 tlvsz, # TlvSz
172 0, # KeyId (TODO: allow other ids)
173 0, # Pad1
174 self.header_size,
175 0, # Pad2
176 len(self.payload) - self.header_size, # ImageSz
177 flags, # Flags
178 self.version.major,
179 self.version.minor or 0,
180 self.version.revision or 0,
181 self.version.build or 0,
182 0) # Pad3
183 self.payload = bytearray(self.payload)
184 self.payload[:len(header)] = header
185
186 def pad_to(self, size, align):
187 """Pad the image to the given size, with the given flash alignment."""
188 tsize = trailer_sizes[align]
189 padding = size - (len(self.payload) + tsize)
190 if padding < 0:
191 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
192 len(self.payload), tsize, size)
193 raise Exception(msg)
Fabio Utzige08f0872017-06-28 18:12:16 -0300194 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600195 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300196 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600197 self.payload += pbytes
Carles Cufi37d052f2018-01-30 16:40:10 +0100198
199class HexImage(Image):
200
201 def load(self, path):
202 ih = IntelHex(path)
203 return ih.tobinarray(), ih.minaddr()
204
205 def save(self, path):
206 h = IntelHex()
207 h.frombytes(bytes = self.payload, offset = self.base_addr)
208 h.tofile(path, 'hex')
209
210class BinImage(Image):
211
212 def load(self, path):
213 with open(path, 'rb') as f:
214 return f.read(), None
215
216 def save(self, path):
217 with open(path, 'wb') as f:
218 f.write(self.payload)