blob: d790a75f7e476ae792968a77726e8f1415770cf6 [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
David Vincze61bd1e52019-10-24 16:47:31 +020050TLV_PROT_INFO_MAGIC = 0x6908
Tamas Banf70ef8c2017-12-19 15:35:09 +000051
52# Sizes of the image trailer, depending on flash write size.
53trailer_sizes = {
54 write_size: 128 * 3 * write_size + 8 * 2 + 16
55 for write_size in [1, 2, 4, 8]
56}
57
Gabor Kertesz33e9b232018-09-12 15:38:41 +020058boot_magic = bytearray([
Tamas Banf70ef8c2017-12-19 15:35:09 +000059 0x77, 0xc2, 0x95, 0xf3,
60 0x60, 0xd2, 0xef, 0x7f,
61 0x35, 0x52, 0x50, 0x0f,
62 0x2c, 0xb6, 0x79, 0x80, ])
63
64class TLV():
David Vincze61bd1e52019-10-24 16:47:31 +020065 def __init__(self, magic=TLV_INFO_MAGIC):
66 self.magic = magic
Tamas Banf70ef8c2017-12-19 15:35:09 +000067 self.buf = bytearray()
68
David Vincze61bd1e52019-10-24 16:47:31 +020069 def __len__(self):
70 return TLV_INFO_SIZE + len(self.buf)
71
Tamas Banf70ef8c2017-12-19 15:35:09 +000072 def add(self, kind, payload):
David Vincze61bd1e52019-10-24 16:47:31 +020073 """
74 Add a TLV record. Kind should be a string found in TLV_VALUES above.
75 """
Tamas Banf70ef8c2017-12-19 15:35:09 +000076 buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
77 self.buf += buf
78 self.buf += payload
79
80 def get(self):
David Vincze61bd1e52019-10-24 16:47:31 +020081 if len(self.buf) == 0:
82 return bytes()
83 header = struct.pack('<HH', self.magic, len(self))
Tamas Banf70ef8c2017-12-19 15:35:09 +000084 return header + bytes(self.buf)
85
86class Image():
87 @classmethod
88 def load(cls, path, included_header=False, **kwargs):
89 """Load an image from a given file"""
90 with open(path, 'rb') as f:
91 payload = f.read()
92 obj = cls(**kwargs)
93 obj.payload = payload
94
95 # Add the image header if needed.
96 if not included_header and obj.header_size > 0:
97 obj.payload = (b'\000' * obj.header_size) + obj.payload
98
99 obj.check()
100 return obj
101
David Vinczedb32b212019-04-16 17:43:57 +0200102 def __init__(self, version, header_size=IMAGE_HEADER_SIZE, security_cnt=0,
103 pad=0):
Oliver Swede21440442018-07-10 09:31:32 +0100104 self.version = version
Tamas Banf70ef8c2017-12-19 15:35:09 +0000105 self.header_size = header_size or IMAGE_HEADER_SIZE
David Vinczedb32b212019-04-16 17:43:57 +0200106 self.security_cnt = security_cnt
Tamas Banf70ef8c2017-12-19 15:35:09 +0000107 self.pad = pad
108
109 def __repr__(self):
David Vinczedb32b212019-04-16 17:43:57 +0200110 return "<Image version={}, header_size={}, security_counter={}, \
111 pad={}, payloadlen=0x{:x}>".format(
Tamas Banf70ef8c2017-12-19 15:35:09 +0000112 self.version,
113 self.header_size,
David Vinczedb32b212019-04-16 17:43:57 +0200114 self.security_cnt,
Tamas Banf70ef8c2017-12-19 15:35:09 +0000115 self.pad,
116 len(self.payload))
117
118 def save(self, path):
119 with open(path, 'wb') as f:
120 f.write(self.payload)
121
122 def check(self):
123 """Perform some sanity checking of the image."""
124 # If there is a header requested, make sure that the image
125 # starts with all zeros.
126 if self.header_size > 0:
Gabor Kertesz33e9b232018-09-12 15:38:41 +0200127 if any(v != 0 and v != b'\000' for v in self.payload[0:self.header_size]):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000128 raise Exception("Padding requested, but image does not start with zeros")
129
David Vincze4b84de52019-09-27 17:40:29 +0200130 def sign(self, sw_type, key, ramLoadAddress, dependencies=None):
131 image_version = (str(self.version.major) + '.'
132 + str(self.version.minor) + '.'
133 + str(self.version.revision))
134
135 # Calculate the hash of the public key
136 if key is not None:
137 pub = key.get_public_bytes()
138 sha = hashlib.sha256()
139 sha.update(pub)
140 pubbytes = sha.digest()
141 else:
142 pubbytes = bytes(KEYHASH_SIZE)
143
144 # The image hash is computed over the image header, the image itself
145 # and the protected TLV area. However, the boot record TLV (which is
146 # part of the protected area) should contain this hash before it is
147 # even calculated. For this reason the script fills this field with
148 # zeros and the bootloader will insert the right value later.
149 image_hash = bytes(PAYLOAD_DIGEST_SIZE)
150
151 # Create CBOR encoded boot record
152 boot_record = br.create_sw_component_data(sw_type, image_version,
153 "SHA256", image_hash,
154 pubbytes)
155
156 # Mandatory protected TLV area: TLV info header
157 # + security counter TLV
158 # + boot record TLV
159 # Size of the security counter TLV: header ('BBH') + payload ('I')
160 # = 8 Bytes
161 protected_tlv_size = TLV_INFO_SIZE + 8 + TLV_HEADER_SIZE \
162 + len(boot_record)
David Vinczedb32b212019-04-16 17:43:57 +0200163
David Vincze9ec0f542019-07-03 18:09:47 +0200164 if dependencies is None:
165 dependencies_num = 0
166 else:
167 # Size of a dependency TLV:
168 # header ('BBH') + payload('IBBHI') = 16 Bytes
169 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
170 protected_tlv_size += (dependencies_num * 16)
171
David Vincze61bd1e52019-10-24 16:47:31 +0200172 # At this point the image is already on the payload, this adds
173 # the header to the payload as well
David Vinczedb32b212019-04-16 17:43:57 +0200174 self.add_header(key, protected_tlv_size, ramLoadAddress)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000175
David Vincze61bd1e52019-10-24 16:47:31 +0200176 prot_tlv = TLV(TLV_PROT_INFO_MAGIC)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000177
David Vincze61bd1e52019-10-24 16:47:31 +0200178 # Protected TLVs must be added first, because they are also included
179 # in the hash calculation
David Vinczedb32b212019-04-16 17:43:57 +0200180 payload = struct.pack('I', self.security_cnt)
David Vincze61bd1e52019-10-24 16:47:31 +0200181 prot_tlv.add('SEC_CNT', payload)
182 prot_tlv.add('BOOT_RECORD', boot_record)
David Vincze9ec0f542019-07-03 18:09:47 +0200183
184 if dependencies_num != 0:
185 for i in range(dependencies_num):
186 payload = struct.pack(
David Vinczebb6e3b62019-07-31 14:24:05 +0200187 '<'+'B3x'+'BBHI',
David Vincze9ec0f542019-07-03 18:09:47 +0200188 int(dependencies[DEP_IMAGES_KEY][i]),
189 dependencies[DEP_VERSIONS_KEY][i].major,
190 dependencies[DEP_VERSIONS_KEY][i].minor,
191 dependencies[DEP_VERSIONS_KEY][i].revision,
192 dependencies[DEP_VERSIONS_KEY][i].build
193 )
David Vincze61bd1e52019-10-24 16:47:31 +0200194 prot_tlv.add('DEPENDENCY', payload)
David Vincze9ec0f542019-07-03 18:09:47 +0200195
David Vincze61bd1e52019-10-24 16:47:31 +0200196 self.payload += prot_tlv.get()
David Vinczedb32b212019-04-16 17:43:57 +0200197
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 Vincze61bd1e52019-10-24 16:47:31 +0200202 tlv = TLV()
203
David Vincze4b84de52019-09-27 17:40:29 +0200204 tlv.add('SHA256', image_hash)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000205
206 if key is not None:
Tamas Ban32d84642019-07-11 08:25:11 +0100207 if key.get_public_key_format() == 'hash':
Tamas Ban32d84642019-07-11 08:25:11 +0100208 tlv.add('KEYHASH', pubbytes)
209 else:
210 tlv.add('KEY', pub)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000211
212 sig = key.sign(self.payload)
213 tlv.add(key.sig_tlv(), sig)
214
David Vincze61bd1e52019-10-24 16:47:31 +0200215 self.payload += tlv.get()
Tamas Banf70ef8c2017-12-19 15:35:09 +0000216
David Vinczedb32b212019-04-16 17:43:57 +0200217 def add_header(self, key, protected_tlv_size, ramLoadAddress):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000218 """Install the image header.
219
220 The key is needed to know the type of signature, and
221 approximate the size of the signature."""
222
223 flags = 0
Oliver Swede05e5ded2018-07-19 16:40:49 +0100224 if ramLoadAddress is not None:
225 # add the load address flag to the header to indicate that an SRAM
226 # load address macro has been defined
227 flags |= IMAGE_F["RAM_LOAD"]
Tamas Banf70ef8c2017-12-19 15:35:09 +0000228
229 fmt = ('<' +
230 # type ImageHdr struct {
David Vinczedb32b212019-04-16 17:43:57 +0200231 'I' + # Magic uint32
232 'I' + # LoadAddr uint32
233 'H' + # HdrSz uint16
234 'H' + # PTLVSz uint16
235 'I' + # ImgSz uint32
236 'I' + # Flags uint32
237 'BBHI' + # Vers ImageVersion
238 'I' # Pad1 uint32
Tamas Banf70ef8c2017-12-19 15:35:09 +0000239 ) # }
240 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
241 header = struct.pack(fmt,
242 IMAGE_MAGIC,
Oliver Swede05e5ded2018-07-19 16:40:49 +0100243 0 if (ramLoadAddress is None) else ramLoadAddress, # LoadAddr
Tamas Banf70ef8c2017-12-19 15:35:09 +0000244 self.header_size,
David Vincze61bd1e52019-10-24 16:47:31 +0200245 protected_tlv_size, # TLV info header + Protected TLVs
246 len(self.payload) - self.header_size, # ImageSz
247 flags,
Tamas Banf70ef8c2017-12-19 15:35:09 +0000248 self.version.major,
249 self.version.minor or 0,
250 self.version.revision or 0,
251 self.version.build or 0,
David Vinczedb32b212019-04-16 17:43:57 +0200252 0) # Pad1
Tamas Banf70ef8c2017-12-19 15:35:09 +0000253 self.payload = bytearray(self.payload)
254 self.payload[:len(header)] = header
255
256 def pad_to(self, size, align):
257 """Pad the image to the given size, with the given flash alignment."""
258 tsize = trailer_sizes[align]
259 padding = size - (len(self.payload) + tsize)
260 if padding < 0:
261 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
262 len(self.payload), tsize, size)
263 raise Exception(msg)
264 pbytes = b'\xff' * padding
265 pbytes += b'\xff' * (tsize - len(boot_magic))
266 pbytes += boot_magic
David Vinczedb32b212019-04-16 17:43:57 +0200267 self.payload += pbytes