blob: f64ad4cbe751cfd86ce3768954821eb6358a998a [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 Ban581034a2017-12-19 19:54:37 +000039 'SHA256' : 0x10,
David Vinczedb32b212019-04-16 17:43:57 +020040 'RSA2048': 0x20,
Tamas Ban861835c2019-05-13 08:59:38 +010041 'RSA3072': 0x23,
David Vincze9ec0f542019-07-03 18:09:47 +020042 'DEPENDENCY': 0x40,
David Vinczedb32b212019-04-16 17:43:57 +020043 'SEC_CNT': 0x50, }
Tamas Banf70ef8c2017-12-19 15:35:09 +000044
45TLV_INFO_SIZE = 4
46TLV_INFO_MAGIC = 0x6907
Tamas Banf70ef8c2017-12-19 15:35:09 +000047
48# Sizes of the image trailer, depending on flash write size.
49trailer_sizes = {
50 write_size: 128 * 3 * write_size + 8 * 2 + 16
51 for write_size in [1, 2, 4, 8]
52}
53
Gabor Kertesz33e9b232018-09-12 15:38:41 +020054boot_magic = bytearray([
Tamas Banf70ef8c2017-12-19 15:35:09 +000055 0x77, 0xc2, 0x95, 0xf3,
56 0x60, 0xd2, 0xef, 0x7f,
57 0x35, 0x52, 0x50, 0x0f,
58 0x2c, 0xb6, 0x79, 0x80, ])
59
60class TLV():
61 def __init__(self):
62 self.buf = bytearray()
63
64 def add(self, kind, payload):
65 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
66 buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
67 self.buf += buf
68 self.buf += payload
69
70 def get(self):
71 header = struct.pack('<HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
72 return header + bytes(self.buf)
73
74class Image():
75 @classmethod
76 def load(cls, path, included_header=False, **kwargs):
77 """Load an image from a given file"""
78 with open(path, 'rb') as f:
79 payload = f.read()
80 obj = cls(**kwargs)
81 obj.payload = payload
82
83 # Add the image header if needed.
84 if not included_header and obj.header_size > 0:
85 obj.payload = (b'\000' * obj.header_size) + obj.payload
86
87 obj.check()
88 return obj
89
David Vinczedb32b212019-04-16 17:43:57 +020090 def __init__(self, version, header_size=IMAGE_HEADER_SIZE, security_cnt=0,
91 pad=0):
Oliver Swede21440442018-07-10 09:31:32 +010092 self.version = version
Tamas Banf70ef8c2017-12-19 15:35:09 +000093 self.header_size = header_size or IMAGE_HEADER_SIZE
David Vinczedb32b212019-04-16 17:43:57 +020094 self.security_cnt = security_cnt
Tamas Banf70ef8c2017-12-19 15:35:09 +000095 self.pad = pad
96
97 def __repr__(self):
David Vinczedb32b212019-04-16 17:43:57 +020098 return "<Image version={}, header_size={}, security_counter={}, \
99 pad={}, payloadlen=0x{:x}>".format(
Tamas Banf70ef8c2017-12-19 15:35:09 +0000100 self.version,
101 self.header_size,
David Vinczedb32b212019-04-16 17:43:57 +0200102 self.security_cnt,
Tamas Banf70ef8c2017-12-19 15:35:09 +0000103 self.pad,
104 len(self.payload))
105
106 def save(self, path):
107 with open(path, 'wb') as f:
108 f.write(self.payload)
109
110 def check(self):
111 """Perform some sanity checking of the image."""
112 # If there is a header requested, make sure that the image
113 # starts with all zeros.
114 if self.header_size > 0:
Gabor Kertesz33e9b232018-09-12 15:38:41 +0200115 if any(v != 0 and v != b'\000' for v in self.payload[0:self.header_size]):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000116 raise Exception("Padding requested, but image does not start with zeros")
117
David Vincze9ec0f542019-07-03 18:09:47 +0200118 def sign(self, key, ramLoadAddress, dependencies=None):
David Vinczedb32b212019-04-16 17:43:57 +0200119 # Size of the security counter TLV:
120 # header ('BBH') + payload ('I') = 8 Bytes
121 protected_tlv_size = TLV_INFO_SIZE + 8
122
David Vincze9ec0f542019-07-03 18:09:47 +0200123 if dependencies is None:
124 dependencies_num = 0
125 else:
126 # Size of a dependency TLV:
127 # header ('BBH') + payload('IBBHI') = 16 Bytes
128 dependencies_num = len(dependencies[DEP_IMAGES_KEY])
129 protected_tlv_size += (dependencies_num * 16)
130
David Vinczedb32b212019-04-16 17:43:57 +0200131 self.add_header(key, protected_tlv_size, ramLoadAddress)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000132
133 tlv = TLV()
134
David Vinczedb32b212019-04-16 17:43:57 +0200135 payload = struct.pack('I', self.security_cnt)
136 tlv.add('SEC_CNT', payload)
David Vincze9ec0f542019-07-03 18:09:47 +0200137
138 if dependencies_num != 0:
139 for i in range(dependencies_num):
140 payload = struct.pack(
David Vinczebb6e3b62019-07-31 14:24:05 +0200141 '<'+'B3x'+'BBHI',
David Vincze9ec0f542019-07-03 18:09:47 +0200142 int(dependencies[DEP_IMAGES_KEY][i]),
143 dependencies[DEP_VERSIONS_KEY][i].major,
144 dependencies[DEP_VERSIONS_KEY][i].minor,
145 dependencies[DEP_VERSIONS_KEY][i].revision,
146 dependencies[DEP_VERSIONS_KEY][i].build
147 )
148 tlv.add('DEPENDENCY', payload)
149
David Vinczedb32b212019-04-16 17:43:57 +0200150 # Full TLV size needs to be calculated in advance, because the
151 # header will be protected as well
152 full_size = (TLV_INFO_SIZE + len(tlv.buf) + TLV_HEADER_SIZE
153 + PAYLOAD_DIGEST_SIZE)
154 if key is not None:
155 full_size += (TLV_HEADER_SIZE + KEYHASH_SIZE
156 + TLV_HEADER_SIZE + key.sig_len())
157 tlv_header = struct.pack('HH', TLV_INFO_MAGIC, full_size)
158 self.payload += tlv_header + bytes(tlv.buf)
159
Tamas Banf70ef8c2017-12-19 15:35:09 +0000160 sha = hashlib.sha256()
161 sha.update(self.payload)
162 digest = sha.digest()
163
164 tlv.add('SHA256', digest)
165
166 if key is not None:
167 pub = key.get_public_bytes()
168 sha = hashlib.sha256()
169 sha.update(pub)
170 pubbytes = sha.digest()
171 tlv.add('KEYHASH', pubbytes)
172
173 sig = key.sign(self.payload)
174 tlv.add(key.sig_tlv(), sig)
175
David Vinczedb32b212019-04-16 17:43:57 +0200176 self.payload += tlv.get()[protected_tlv_size:]
Tamas Banf70ef8c2017-12-19 15:35:09 +0000177
David Vinczedb32b212019-04-16 17:43:57 +0200178 def add_header(self, key, protected_tlv_size, ramLoadAddress):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000179 """Install the image header.
180
181 The key is needed to know the type of signature, and
182 approximate the size of the signature."""
183
184 flags = 0
Oliver Swede05e5ded2018-07-19 16:40:49 +0100185 if ramLoadAddress is not None:
186 # add the load address flag to the header to indicate that an SRAM
187 # load address macro has been defined
188 flags |= IMAGE_F["RAM_LOAD"]
Tamas Banf70ef8c2017-12-19 15:35:09 +0000189
190 fmt = ('<' +
191 # type ImageHdr struct {
David Vinczedb32b212019-04-16 17:43:57 +0200192 'I' + # Magic uint32
193 'I' + # LoadAddr uint32
194 'H' + # HdrSz uint16
195 'H' + # PTLVSz uint16
196 'I' + # ImgSz uint32
197 'I' + # Flags uint32
198 'BBHI' + # Vers ImageVersion
199 'I' # Pad1 uint32
Tamas Banf70ef8c2017-12-19 15:35:09 +0000200 ) # }
201 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
202 header = struct.pack(fmt,
203 IMAGE_MAGIC,
Oliver Swede05e5ded2018-07-19 16:40:49 +0100204 0 if (ramLoadAddress is None) else ramLoadAddress, # LoadAddr
Tamas Banf70ef8c2017-12-19 15:35:09 +0000205 self.header_size,
David Vincze9ec0f542019-07-03 18:09:47 +0200206 protected_tlv_size, # TLV info header + SC TLV (+ DEP. TLVs)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000207 len(self.payload) - self.header_size, # ImageSz
208 flags, # Flags
209 self.version.major,
210 self.version.minor or 0,
211 self.version.revision or 0,
212 self.version.build or 0,
David Vinczedb32b212019-04-16 17:43:57 +0200213 0) # Pad1
Tamas Banf70ef8c2017-12-19 15:35:09 +0000214 self.payload = bytearray(self.payload)
215 self.payload[:len(header)] = header
216
217 def pad_to(self, size, align):
218 """Pad the image to the given size, with the given flash alignment."""
219 tsize = trailer_sizes[align]
220 padding = size - (len(self.payload) + tsize)
221 if padding < 0:
222 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
223 len(self.payload), tsize, size)
224 raise Exception(msg)
225 pbytes = b'\xff' * padding
226 pbytes += b'\xff' * (tsize - len(boot_magic))
227 pbytes += boot_magic
David Vinczedb32b212019-04-16 17:43:57 +0200228 self.payload += pbytes