blob: bd1bf5de4eed49c1d7e939eca6405873ae975f26 [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
Tamas Banf70ef8c2017-12-19 15:35:09 +000029
30# Image header flags.
31IMAGE_F = {
32 'PIC': 0x0000001,
Oliver Swede05e5ded2018-07-19 16:40:49 +010033 'NON_BOOTABLE': 0x0000010,
34 'RAM_LOAD': 0x0000020, }
Tamas Banf70ef8c2017-12-19 15:35:09 +000035TLV_VALUES = {
36 'KEYHASH': 0x01,
Tamas Ban581034a2017-12-19 19:54:37 +000037 'SHA256' : 0x10,
David Vinczedb32b212019-04-16 17:43:57 +020038 'RSA2048': 0x20,
39 'SEC_CNT': 0x50, }
Tamas Banf70ef8c2017-12-19 15:35:09 +000040
41TLV_INFO_SIZE = 4
42TLV_INFO_MAGIC = 0x6907
Tamas Banf70ef8c2017-12-19 15:35:09 +000043
44# Sizes of the image trailer, depending on flash write size.
45trailer_sizes = {
46 write_size: 128 * 3 * write_size + 8 * 2 + 16
47 for write_size in [1, 2, 4, 8]
48}
49
Gabor Kertesz33e9b232018-09-12 15:38:41 +020050boot_magic = bytearray([
Tamas Banf70ef8c2017-12-19 15:35:09 +000051 0x77, 0xc2, 0x95, 0xf3,
52 0x60, 0xd2, 0xef, 0x7f,
53 0x35, 0x52, 0x50, 0x0f,
54 0x2c, 0xb6, 0x79, 0x80, ])
55
56class TLV():
57 def __init__(self):
58 self.buf = bytearray()
59
60 def add(self, kind, payload):
61 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
62 buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
63 self.buf += buf
64 self.buf += payload
65
66 def get(self):
67 header = struct.pack('<HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
68 return header + bytes(self.buf)
69
70class Image():
71 @classmethod
72 def load(cls, path, included_header=False, **kwargs):
73 """Load an image from a given file"""
74 with open(path, 'rb') as f:
75 payload = f.read()
76 obj = cls(**kwargs)
77 obj.payload = payload
78
79 # Add the image header if needed.
80 if not included_header and obj.header_size > 0:
81 obj.payload = (b'\000' * obj.header_size) + obj.payload
82
83 obj.check()
84 return obj
85
David Vinczedb32b212019-04-16 17:43:57 +020086 def __init__(self, version, header_size=IMAGE_HEADER_SIZE, security_cnt=0,
87 pad=0):
Oliver Swede21440442018-07-10 09:31:32 +010088 self.version = version
Tamas Banf70ef8c2017-12-19 15:35:09 +000089 self.header_size = header_size or IMAGE_HEADER_SIZE
David Vinczedb32b212019-04-16 17:43:57 +020090 self.security_cnt = security_cnt
Tamas Banf70ef8c2017-12-19 15:35:09 +000091 self.pad = pad
92
93 def __repr__(self):
David Vinczedb32b212019-04-16 17:43:57 +020094 return "<Image version={}, header_size={}, security_counter={}, \
95 pad={}, payloadlen=0x{:x}>".format(
Tamas Banf70ef8c2017-12-19 15:35:09 +000096 self.version,
97 self.header_size,
David Vinczedb32b212019-04-16 17:43:57 +020098 self.security_cnt,
Tamas Banf70ef8c2017-12-19 15:35:09 +000099 self.pad,
100 len(self.payload))
101
102 def save(self, path):
103 with open(path, 'wb') as f:
104 f.write(self.payload)
105
106 def check(self):
107 """Perform some sanity checking of the image."""
108 # If there is a header requested, make sure that the image
109 # starts with all zeros.
110 if self.header_size > 0:
Gabor Kertesz33e9b232018-09-12 15:38:41 +0200111 if any(v != 0 and v != b'\000' for v in self.payload[0:self.header_size]):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000112 raise Exception("Padding requested, but image does not start with zeros")
113
Oliver Swede05e5ded2018-07-19 16:40:49 +0100114 def sign(self, key, ramLoadAddress):
David Vinczedb32b212019-04-16 17:43:57 +0200115 # Size of the security counter TLV:
116 # header ('BBH') + payload ('I') = 8 Bytes
117 protected_tlv_size = TLV_INFO_SIZE + 8
118
119 self.add_header(key, protected_tlv_size, ramLoadAddress)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000120
121 tlv = TLV()
122
David Vinczedb32b212019-04-16 17:43:57 +0200123 payload = struct.pack('I', self.security_cnt)
124 tlv.add('SEC_CNT', payload)
125 # Full TLV size needs to be calculated in advance, because the
126 # header will be protected as well
127 full_size = (TLV_INFO_SIZE + len(tlv.buf) + TLV_HEADER_SIZE
128 + PAYLOAD_DIGEST_SIZE)
129 if key is not None:
130 full_size += (TLV_HEADER_SIZE + KEYHASH_SIZE
131 + TLV_HEADER_SIZE + key.sig_len())
132 tlv_header = struct.pack('HH', TLV_INFO_MAGIC, full_size)
133 self.payload += tlv_header + bytes(tlv.buf)
134
Tamas Banf70ef8c2017-12-19 15:35:09 +0000135 sha = hashlib.sha256()
136 sha.update(self.payload)
137 digest = sha.digest()
138
139 tlv.add('SHA256', digest)
140
141 if key is not None:
142 pub = key.get_public_bytes()
143 sha = hashlib.sha256()
144 sha.update(pub)
145 pubbytes = sha.digest()
146 tlv.add('KEYHASH', pubbytes)
147
148 sig = key.sign(self.payload)
149 tlv.add(key.sig_tlv(), sig)
150
David Vinczedb32b212019-04-16 17:43:57 +0200151 self.payload += tlv.get()[protected_tlv_size:]
Tamas Banf70ef8c2017-12-19 15:35:09 +0000152
David Vinczedb32b212019-04-16 17:43:57 +0200153 def add_header(self, key, protected_tlv_size, ramLoadAddress):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000154 """Install the image header.
155
156 The key is needed to know the type of signature, and
157 approximate the size of the signature."""
158
159 flags = 0
Oliver Swede05e5ded2018-07-19 16:40:49 +0100160 if ramLoadAddress is not None:
161 # add the load address flag to the header to indicate that an SRAM
162 # load address macro has been defined
163 flags |= IMAGE_F["RAM_LOAD"]
Tamas Banf70ef8c2017-12-19 15:35:09 +0000164
165 fmt = ('<' +
166 # type ImageHdr struct {
David Vinczedb32b212019-04-16 17:43:57 +0200167 'I' + # Magic uint32
168 'I' + # LoadAddr uint32
169 'H' + # HdrSz uint16
170 'H' + # PTLVSz uint16
171 'I' + # ImgSz uint32
172 'I' + # Flags uint32
173 'BBHI' + # Vers ImageVersion
174 'I' # Pad1 uint32
Tamas Banf70ef8c2017-12-19 15:35:09 +0000175 ) # }
176 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
177 header = struct.pack(fmt,
178 IMAGE_MAGIC,
Oliver Swede05e5ded2018-07-19 16:40:49 +0100179 0 if (ramLoadAddress is None) else ramLoadAddress, # LoadAddr
Tamas Banf70ef8c2017-12-19 15:35:09 +0000180 self.header_size,
David Vinczedb32b212019-04-16 17:43:57 +0200181 protected_tlv_size, # TLV info header + security counter TLV
Tamas Banf70ef8c2017-12-19 15:35:09 +0000182 len(self.payload) - self.header_size, # ImageSz
183 flags, # Flags
184 self.version.major,
185 self.version.minor or 0,
186 self.version.revision or 0,
187 self.version.build or 0,
David Vinczedb32b212019-04-16 17:43:57 +0200188 0) # Pad1
Tamas Banf70ef8c2017-12-19 15:35:09 +0000189 self.payload = bytearray(self.payload)
190 self.payload[:len(header)] = header
191
192 def pad_to(self, size, align):
193 """Pad the image to the given size, with the given flash alignment."""
194 tsize = trailer_sizes[align]
195 padding = size - (len(self.payload) + tsize)
196 if padding < 0:
197 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
198 len(self.payload), tsize, size)
199 raise Exception(msg)
200 pbytes = b'\xff' * padding
201 pbytes += b'\xff' * (tsize - len(boot_magic))
202 pbytes += boot_magic
David Vinczedb32b212019-04-16 17:43:57 +0200203 self.payload += pbytes