blob: cb97a350b8ff86c0ec4c788ae97a6d83be78c685 [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
21import hashlib
22import struct
23
24IMAGE_MAGIC = 0x96f3b83d
25IMAGE_HEADER_SIZE = 32
David Vinczedb32b212019-04-16 17:43:57 +020026TLV_HEADER_SIZE = 4
27PAYLOAD_DIGEST_SIZE = 32 # SHA256 hash
28KEYHASH_SIZE = 32
David Vincze9ec0f542019-07-03 18:09:47 +020029DEP_IMAGES_KEY = "images"
30DEP_VERSIONS_KEY = "versions"
Tamas Banf70ef8c2017-12-19 15:35:09 +000031
32# Image header flags.
33IMAGE_F = {
34 'PIC': 0x0000001,
Oliver Swede05e5ded2018-07-19 16:40:49 +010035 'NON_BOOTABLE': 0x0000010,
36 'RAM_LOAD': 0x0000020, }
Tamas Banf70ef8c2017-12-19 15:35:09 +000037TLV_VALUES = {
38 'KEYHASH': 0x01,
Tamas Ban32d84642019-07-11 08:25:11 +010039 'KEY' : 0x02,
Tamas Ban581034a2017-12-19 19:54:37 +000040 'SHA256' : 0x10,
David Vinczedb32b212019-04-16 17:43:57 +020041 'RSA2048': 0x20,
Tamas Ban861835c2019-05-13 08:59:38 +010042 'RSA3072': 0x23,
David Vincze9ec0f542019-07-03 18:09:47 +020043 'DEPENDENCY': 0x40,
David Vinczedb32b212019-04-16 17:43:57 +020044 'SEC_CNT': 0x50, }
Tamas Banf70ef8c2017-12-19 15:35:09 +000045
46TLV_INFO_SIZE = 4
47TLV_INFO_MAGIC = 0x6907
Tamas Banf70ef8c2017-12-19 15:35:09 +000048
49# Sizes of the image trailer, depending on flash write size.
50trailer_sizes = {
51 write_size: 128 * 3 * write_size + 8 * 2 + 16
52 for write_size in [1, 2, 4, 8]
53}
54
Gabor Kertesz33e9b232018-09-12 15:38:41 +020055boot_magic = bytearray([
Tamas Banf70ef8c2017-12-19 15:35:09 +000056 0x77, 0xc2, 0x95, 0xf3,
57 0x60, 0xd2, 0xef, 0x7f,
58 0x35, 0x52, 0x50, 0x0f,
59 0x2c, 0xb6, 0x79, 0x80, ])
60
61class TLV():
62 def __init__(self):
63 self.buf = bytearray()
64
65 def add(self, kind, payload):
66 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
67 buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
68 self.buf += buf
69 self.buf += payload
70
71 def get(self):
72 header = struct.pack('<HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
73 return header + bytes(self.buf)
74
75class Image():
76 @classmethod
77 def load(cls, path, included_header=False, **kwargs):
78 """Load an image from a given file"""
79 with open(path, 'rb') as f:
80 payload = f.read()
81 obj = cls(**kwargs)
82 obj.payload = payload
83
84 # Add the image header if needed.
85 if not included_header and obj.header_size > 0:
86 obj.payload = (b'\000' * obj.header_size) + obj.payload
87
88 obj.check()
89 return obj
90
David Vinczedb32b212019-04-16 17:43:57 +020091 def __init__(self, version, header_size=IMAGE_HEADER_SIZE, security_cnt=0,
92 pad=0):
Oliver Swede21440442018-07-10 09:31:32 +010093 self.version = version
Tamas Banf70ef8c2017-12-19 15:35:09 +000094 self.header_size = header_size or IMAGE_HEADER_SIZE
David Vinczedb32b212019-04-16 17:43:57 +020095 self.security_cnt = security_cnt
Tamas Banf70ef8c2017-12-19 15:35:09 +000096 self.pad = pad
97
98 def __repr__(self):
David Vinczedb32b212019-04-16 17:43:57 +020099 return "<Image version={}, header_size={}, security_counter={}, \
100 pad={}, payloadlen=0x{:x}>".format(
Tamas Banf70ef8c2017-12-19 15:35:09 +0000101 self.version,
102 self.header_size,
David Vinczedb32b212019-04-16 17:43:57 +0200103 self.security_cnt,
Tamas Banf70ef8c2017-12-19 15:35:09 +0000104 self.pad,
105 len(self.payload))
106
107 def save(self, path):
108 with open(path, 'wb') as f:
109 f.write(self.payload)
110
111 def check(self):
112 """Perform some sanity checking of the image."""
113 # If there is a header requested, make sure that the image
114 # starts with all zeros.
115 if self.header_size > 0:
Gabor Kertesz33e9b232018-09-12 15:38:41 +0200116 if any(v != 0 and v != b'\000' for v in self.payload[0:self.header_size]):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000117 raise Exception("Padding requested, but image does not start with zeros")
118
David Vincze9ec0f542019-07-03 18:09:47 +0200119 def sign(self, key, ramLoadAddress, dependencies=None):
David Vinczedb32b212019-04-16 17:43:57 +0200120 # Size of the security counter TLV:
121 # header ('BBH') + payload ('I') = 8 Bytes
122 protected_tlv_size = TLV_INFO_SIZE + 8
123
David Vincze9ec0f542019-07-03 18:09:47 +0200124 if dependencies is None:
125 dependencies_num = 0
126 else:
127 # Size of a dependency TLV:
128 # header ('BBH') + payload('IBBHI') = 16 Bytes
129 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
130 protected_tlv_size += (dependencies_num * 16)
131
David Vinczedb32b212019-04-16 17:43:57 +0200132 self.add_header(key, protected_tlv_size, ramLoadAddress)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000133
134 tlv = TLV()
135
David Vinczedb32b212019-04-16 17:43:57 +0200136 payload = struct.pack('I', self.security_cnt)
137 tlv.add('SEC_CNT', payload)
David Vincze9ec0f542019-07-03 18:09:47 +0200138
139 if dependencies_num != 0:
140 for i in range(dependencies_num):
141 payload = struct.pack(
David Vinczebb6e3b62019-07-31 14:24:05 +0200142 '<'+'B3x'+'BBHI',
David Vincze9ec0f542019-07-03 18:09:47 +0200143 int(dependencies[DEP_IMAGES_KEY][i]),
144 dependencies[DEP_VERSIONS_KEY][i].major,
145 dependencies[DEP_VERSIONS_KEY][i].minor,
146 dependencies[DEP_VERSIONS_KEY][i].revision,
147 dependencies[DEP_VERSIONS_KEY][i].build
148 )
149 tlv.add('DEPENDENCY', payload)
150
David Vinczedb32b212019-04-16 17:43:57 +0200151 # Full TLV size needs to be calculated in advance, because the
152 # header will be protected as well
153 full_size = (TLV_INFO_SIZE + len(tlv.buf) + TLV_HEADER_SIZE
154 + PAYLOAD_DIGEST_SIZE)
155 if key is not None:
Tamas Ban32d84642019-07-11 08:25:11 +0100156 pub = key.get_public_bytes()
157 if key.get_public_key_format() == 'hash':
158 tlv_key_data_size = KEYHASH_SIZE
159 else:
160 tlv_key_data_size = len(pub)
161
162 full_size += (TLV_HEADER_SIZE + tlv_key_data_size
David Vinczedb32b212019-04-16 17:43:57 +0200163 + TLV_HEADER_SIZE + key.sig_len())
164 tlv_header = struct.pack('HH', TLV_INFO_MAGIC, full_size)
165 self.payload += tlv_header + bytes(tlv.buf)
166
Tamas Banf70ef8c2017-12-19 15:35:09 +0000167 sha = hashlib.sha256()
168 sha.update(self.payload)
169 digest = sha.digest()
170
171 tlv.add('SHA256', digest)
172
173 if key is not None:
Tamas Ban32d84642019-07-11 08:25:11 +0100174 if key.get_public_key_format() == 'hash':
175 sha = hashlib.sha256()
176 sha.update(pub)
177 pubbytes = sha.digest()
178 tlv.add('KEYHASH', pubbytes)
179 else:
180 tlv.add('KEY', pub)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000181
182 sig = key.sign(self.payload)
183 tlv.add(key.sig_tlv(), sig)
184
David Vinczedb32b212019-04-16 17:43:57 +0200185 self.payload += tlv.get()[protected_tlv_size:]
Tamas Banf70ef8c2017-12-19 15:35:09 +0000186
David Vinczedb32b212019-04-16 17:43:57 +0200187 def add_header(self, key, protected_tlv_size, ramLoadAddress):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000188 """Install the image header.
189
190 The key is needed to know the type of signature, and
191 approximate the size of the signature."""
192
193 flags = 0
Oliver Swede05e5ded2018-07-19 16:40:49 +0100194 if ramLoadAddress is not None:
195 # add the load address flag to the header to indicate that an SRAM
196 # load address macro has been defined
197 flags |= IMAGE_F["RAM_LOAD"]
Tamas Banf70ef8c2017-12-19 15:35:09 +0000198
199 fmt = ('<' +
200 # type ImageHdr struct {
David Vinczedb32b212019-04-16 17:43:57 +0200201 'I' + # Magic uint32
202 'I' + # LoadAddr uint32
203 'H' + # HdrSz uint16
204 'H' + # PTLVSz uint16
205 'I' + # ImgSz uint32
206 'I' + # Flags uint32
207 'BBHI' + # Vers ImageVersion
208 'I' # Pad1 uint32
Tamas Banf70ef8c2017-12-19 15:35:09 +0000209 ) # }
210 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
211 header = struct.pack(fmt,
212 IMAGE_MAGIC,
Oliver Swede05e5ded2018-07-19 16:40:49 +0100213 0 if (ramLoadAddress is None) else ramLoadAddress, # LoadAddr
Tamas Banf70ef8c2017-12-19 15:35:09 +0000214 self.header_size,
David Vincze9ec0f542019-07-03 18:09:47 +0200215 protected_tlv_size, # TLV info header + SC TLV (+ DEP. TLVs)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000216 len(self.payload) - self.header_size, # ImageSz
217 flags, # Flags
218 self.version.major,
219 self.version.minor or 0,
220 self.version.revision or 0,
221 self.version.build or 0,
David Vinczedb32b212019-04-16 17:43:57 +0200222 0) # Pad1
Tamas Banf70ef8c2017-12-19 15:35:09 +0000223 self.payload = bytearray(self.payload)
224 self.payload[:len(header)] = header
225
226 def pad_to(self, size, align):
227 """Pad the image to the given size, with the given flash alignment."""
228 tsize = trailer_sizes[align]
229 padding = size - (len(self.payload) + tsize)
230 if padding < 0:
231 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
232 len(self.payload), tsize, size)
233 raise Exception(msg)
234 pbytes = b'\xff' * padding
235 pbytes += b'\xff' * (tsize - len(boot_magic))
236 pbytes += boot_magic
David Vinczedb32b212019-04-16 17:43:57 +0200237 self.payload += pbytes