blob: d89ec990f150074e8006835f6cdd4d6b9961a0be [file] [log] [blame]
Tamas Banf70ef8c2017-12-19 15:35:09 +00001# Copyright 2017 Linaro Limited
David Vinczedb32b212019-04-16 17:43:57 +02002# Copyright (c) 2018-2019, Arm Limited.
Tamas Banf70ef8c2017-12-19 15:35:09 +00003#
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
16"""
17Image signing and management.
18"""
19
20from . import version as versmod
David Vincze4b84de52019-09-27 17:40:29 +020021from . import boot_record as br
Tamas Banf70ef8c2017-12-19 15:35:09 +000022import hashlib
23import struct
24
25IMAGE_MAGIC = 0x96f3b83d
26IMAGE_HEADER_SIZE = 32
David Vinczedb32b212019-04-16 17:43:57 +020027TLV_HEADER_SIZE = 4
28PAYLOAD_DIGEST_SIZE = 32 # SHA256 hash
29KEYHASH_SIZE = 32
David Vincze9ec0f542019-07-03 18:09:47 +020030DEP_IMAGES_KEY = "images"
31DEP_VERSIONS_KEY = "versions"
Tamas Banf70ef8c2017-12-19 15:35:09 +000032
33# Image header flags.
34IMAGE_F = {
35 'PIC': 0x0000001,
Oliver Swede05e5ded2018-07-19 16:40:49 +010036 'NON_BOOTABLE': 0x0000010,
37 'RAM_LOAD': 0x0000020, }
Tamas Banf70ef8c2017-12-19 15:35:09 +000038TLV_VALUES = {
39 'KEYHASH': 0x01,
Tamas Ban32d84642019-07-11 08:25:11 +010040 'KEY' : 0x02,
Tamas Ban581034a2017-12-19 19:54:37 +000041 'SHA256' : 0x10,
David Vinczedb32b212019-04-16 17:43:57 +020042 'RSA2048': 0x20,
Tamas Ban861835c2019-05-13 08:59:38 +010043 'RSA3072': 0x23,
David Vincze9ec0f542019-07-03 18:09:47 +020044 'DEPENDENCY': 0x40,
David Vincze4b84de52019-09-27 17:40:29 +020045 'SEC_CNT': 0x50,
46 'BOOT_RECORD': 0x60, }
Tamas Banf70ef8c2017-12-19 15:35:09 +000047
48TLV_INFO_SIZE = 4
49TLV_INFO_MAGIC = 0x6907
Tamas Banf70ef8c2017-12-19 15:35:09 +000050
51# Sizes of the image trailer, depending on flash write size.
52trailer_sizes = {
53 write_size: 128 * 3 * write_size + 8 * 2 + 16
54 for write_size in [1, 2, 4, 8]
55}
56
Gabor Kertesz33e9b232018-09-12 15:38:41 +020057boot_magic = bytearray([
Tamas Banf70ef8c2017-12-19 15:35:09 +000058 0x77, 0xc2, 0x95, 0xf3,
59 0x60, 0xd2, 0xef, 0x7f,
60 0x35, 0x52, 0x50, 0x0f,
61 0x2c, 0xb6, 0x79, 0x80, ])
62
63class TLV():
64 def __init__(self):
65 self.buf = bytearray()
66
67 def add(self, kind, payload):
68 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
69 buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
70 self.buf += buf
71 self.buf += payload
72
73 def get(self):
74 header = struct.pack('<HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
75 return header + bytes(self.buf)
76
77class Image():
78 @classmethod
79 def load(cls, path, included_header=False, **kwargs):
80 """Load an image from a given file"""
81 with open(path, 'rb') as f:
82 payload = f.read()
83 obj = cls(**kwargs)
84 obj.payload = payload
85
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
90 obj.check()
91 return obj
92
David Vinczedb32b212019-04-16 17:43:57 +020093 def __init__(self, version, header_size=IMAGE_HEADER_SIZE, security_cnt=0,
94 pad=0):
Oliver Swede21440442018-07-10 09:31:32 +010095 self.version = version
Tamas Banf70ef8c2017-12-19 15:35:09 +000096 self.header_size = header_size or IMAGE_HEADER_SIZE
David Vinczedb32b212019-04-16 17:43:57 +020097 self.security_cnt = security_cnt
Tamas Banf70ef8c2017-12-19 15:35:09 +000098 self.pad = pad
99
100 def __repr__(self):
David Vinczedb32b212019-04-16 17:43:57 +0200101 return "<Image version={}, header_size={}, security_counter={}, \
102 pad={}, payloadlen=0x{:x}>".format(
Tamas Banf70ef8c2017-12-19 15:35:09 +0000103 self.version,
104 self.header_size,
David Vinczedb32b212019-04-16 17:43:57 +0200105 self.security_cnt,
Tamas Banf70ef8c2017-12-19 15:35:09 +0000106 self.pad,
107 len(self.payload))
108
109 def save(self, path):
110 with open(path, 'wb') as f:
111 f.write(self.payload)
112
113 def check(self):
114 """Perform some sanity checking of the image."""
115 # If there is a header requested, make sure that the image
116 # starts with all zeros.
117 if self.header_size > 0:
Gabor Kertesz33e9b232018-09-12 15:38:41 +0200118 if any(v != 0 and v != b'\000' for v in self.payload[0:self.header_size]):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000119 raise Exception("Padding requested, but image does not start with zeros")
120
David Vincze4b84de52019-09-27 17:40:29 +0200121 def sign(self, sw_type, key, ramLoadAddress, dependencies=None):
122 image_version = (str(self.version.major) + '.'
123 + str(self.version.minor) + '.'
124 + str(self.version.revision))
125
126 # Calculate the hash of the public key
127 if key is not None:
128 pub = key.get_public_bytes()
129 sha = hashlib.sha256()
130 sha.update(pub)
131 pubbytes = sha.digest()
132 else:
133 pubbytes = bytes(KEYHASH_SIZE)
134
135 # The image hash is computed over the image header, the image itself
136 # and the protected TLV area. However, the boot record TLV (which is
137 # part of the protected area) should contain this hash before it is
138 # even calculated. For this reason the script fills this field with
139 # zeros and the bootloader will insert the right value later.
140 image_hash = bytes(PAYLOAD_DIGEST_SIZE)
141
142 # Create CBOR encoded boot record
143 boot_record = br.create_sw_component_data(sw_type, image_version,
144 "SHA256", image_hash,
145 pubbytes)
146
147 # Mandatory protected TLV area: TLV info header
148 # + security counter TLV
149 # + boot record TLV
150 # Size of the security counter TLV: header ('BBH') + payload ('I')
151 # = 8 Bytes
152 protected_tlv_size = TLV_INFO_SIZE + 8 + TLV_HEADER_SIZE \
153 + len(boot_record)
David Vinczedb32b212019-04-16 17:43:57 +0200154
David Vincze9ec0f542019-07-03 18:09:47 +0200155 if dependencies is None:
156 dependencies_num = 0
157 else:
158 # Size of a dependency TLV:
159 # header ('BBH') + payload('IBBHI') = 16 Bytes
160 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
161 protected_tlv_size += (dependencies_num * 16)
162
David Vinczedb32b212019-04-16 17:43:57 +0200163 self.add_header(key, protected_tlv_size, ramLoadAddress)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000164
165 tlv = TLV()
166
David Vinczedb32b212019-04-16 17:43:57 +0200167 payload = struct.pack('I', self.security_cnt)
168 tlv.add('SEC_CNT', payload)
David Vincze4b84de52019-09-27 17:40:29 +0200169 tlv.add('BOOT_RECORD', boot_record)
David Vincze9ec0f542019-07-03 18:09:47 +0200170
171 if dependencies_num != 0:
172 for i in range(dependencies_num):
173 payload = struct.pack(
David Vinczebb6e3b62019-07-31 14:24:05 +0200174 '<'+'B3x'+'BBHI',
David Vincze9ec0f542019-07-03 18:09:47 +0200175 int(dependencies[DEP_IMAGES_KEY][i]),
176 dependencies[DEP_VERSIONS_KEY][i].major,
177 dependencies[DEP_VERSIONS_KEY][i].minor,
178 dependencies[DEP_VERSIONS_KEY][i].revision,
179 dependencies[DEP_VERSIONS_KEY][i].build
180 )
181 tlv.add('DEPENDENCY', payload)
182
David Vinczedb32b212019-04-16 17:43:57 +0200183 # Full TLV size needs to be calculated in advance, because the
184 # header will be protected as well
185 full_size = (TLV_INFO_SIZE + len(tlv.buf) + TLV_HEADER_SIZE
186 + PAYLOAD_DIGEST_SIZE)
187 if key is not None:
Tamas Ban32d84642019-07-11 08:25:11 +0100188 if key.get_public_key_format() == 'hash':
189 tlv_key_data_size = KEYHASH_SIZE
190 else:
191 tlv_key_data_size = len(pub)
192
193 full_size += (TLV_HEADER_SIZE + tlv_key_data_size
David Vinczedb32b212019-04-16 17:43:57 +0200194 + TLV_HEADER_SIZE + key.sig_len())
195 tlv_header = struct.pack('HH', TLV_INFO_MAGIC, full_size)
196 self.payload += tlv_header + bytes(tlv.buf)
197
Tamas Banf70ef8c2017-12-19 15:35:09 +0000198 sha = hashlib.sha256()
199 sha.update(self.payload)
David Vincze4b84de52019-09-27 17:40:29 +0200200 image_hash = sha.digest()
Tamas Banf70ef8c2017-12-19 15:35:09 +0000201
David Vincze4b84de52019-09-27 17:40:29 +0200202 tlv.add('SHA256', image_hash)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000203
204 if key is not None:
Tamas Ban32d84642019-07-11 08:25:11 +0100205 if key.get_public_key_format() == 'hash':
Tamas Ban32d84642019-07-11 08:25:11 +0100206 tlv.add('KEYHASH', pubbytes)
207 else:
208 tlv.add('KEY', pub)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000209
210 sig = key.sign(self.payload)
211 tlv.add(key.sig_tlv(), sig)
212
David Vinczedb32b212019-04-16 17:43:57 +0200213 self.payload += tlv.get()[protected_tlv_size:]
Tamas Banf70ef8c2017-12-19 15:35:09 +0000214
David Vinczedb32b212019-04-16 17:43:57 +0200215 def add_header(self, key, protected_tlv_size, ramLoadAddress):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000216 """Install the image header.
217
218 The key is needed to know the type of signature, and
219 approximate the size of the signature."""
220
221 flags = 0
Oliver Swede05e5ded2018-07-19 16:40:49 +0100222 if ramLoadAddress is not None:
223 # add the load address flag to the header to indicate that an SRAM
224 # load address macro has been defined
225 flags |= IMAGE_F["RAM_LOAD"]
Tamas Banf70ef8c2017-12-19 15:35:09 +0000226
227 fmt = ('<' +
228 # type ImageHdr struct {
David Vinczedb32b212019-04-16 17:43:57 +0200229 'I' + # Magic uint32
230 'I' + # LoadAddr uint32
231 'H' + # HdrSz uint16
232 'H' + # PTLVSz uint16
233 'I' + # ImgSz uint32
234 'I' + # Flags uint32
235 'BBHI' + # Vers ImageVersion
236 'I' # Pad1 uint32
Tamas Banf70ef8c2017-12-19 15:35:09 +0000237 ) # }
238 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
239 header = struct.pack(fmt,
240 IMAGE_MAGIC,
Oliver Swede05e5ded2018-07-19 16:40:49 +0100241 0 if (ramLoadAddress is None) else ramLoadAddress, # LoadAddr
Tamas Banf70ef8c2017-12-19 15:35:09 +0000242 self.header_size,
David Vincze9ec0f542019-07-03 18:09:47 +0200243 protected_tlv_size, # TLV info header + SC TLV (+ DEP. TLVs)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000244 len(self.payload) - self.header_size, # ImageSz
245 flags, # Flags
246 self.version.major,
247 self.version.minor or 0,
248 self.version.revision or 0,
249 self.version.build or 0,
David Vinczedb32b212019-04-16 17:43:57 +0200250 0) # Pad1
Tamas Banf70ef8c2017-12-19 15:35:09 +0000251 self.payload = bytearray(self.payload)
252 self.payload[:len(header)] = header
253
254 def pad_to(self, size, align):
255 """Pad the image to the given size, with the given flash alignment."""
256 tsize = trailer_sizes[align]
257 padding = size - (len(self.payload) + tsize)
258 if padding < 0:
259 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
260 len(self.payload), tsize, size)
261 raise Exception(msg)
262 pbytes = b'\xff' * padding
263 pbytes += b'\xff' * (tsize - len(boot_magic))
264 pbytes += boot_magic
David Vinczedb32b212019-04-16 17:43:57 +0200265 self.payload += pbytes