blob: ff137a52e808856502a61077bbe07ad37372577d [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,
Tamas Ban861835c2019-05-13 08:59:38 +010039 'RSA3072': 0x23,
David Vinczedb32b212019-04-16 17:43:57 +020040 'SEC_CNT': 0x50, }
Tamas Banf70ef8c2017-12-19 15:35:09 +000041
42TLV_INFO_SIZE = 4
43TLV_INFO_MAGIC = 0x6907
Tamas Banf70ef8c2017-12-19 15:35:09 +000044
45# Sizes of the image trailer, depending on flash write size.
46trailer_sizes = {
47 write_size: 128 * 3 * write_size + 8 * 2 + 16
48 for write_size in [1, 2, 4, 8]
49}
50
Gabor Kertesz33e9b232018-09-12 15:38:41 +020051boot_magic = bytearray([
Tamas Banf70ef8c2017-12-19 15:35:09 +000052 0x77, 0xc2, 0x95, 0xf3,
53 0x60, 0xd2, 0xef, 0x7f,
54 0x35, 0x52, 0x50, 0x0f,
55 0x2c, 0xb6, 0x79, 0x80, ])
56
57class TLV():
58 def __init__(self):
59 self.buf = bytearray()
60
61 def add(self, kind, payload):
62 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
63 buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
64 self.buf += buf
65 self.buf += payload
66
67 def get(self):
68 header = struct.pack('<HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
69 return header + bytes(self.buf)
70
71class Image():
72 @classmethod
73 def load(cls, path, included_header=False, **kwargs):
74 """Load an image from a given file"""
75 with open(path, 'rb') as f:
76 payload = f.read()
77 obj = cls(**kwargs)
78 obj.payload = payload
79
80 # Add the image header if needed.
81 if not included_header and obj.header_size > 0:
82 obj.payload = (b'\000' * obj.header_size) + obj.payload
83
84 obj.check()
85 return obj
86
David Vinczedb32b212019-04-16 17:43:57 +020087 def __init__(self, version, header_size=IMAGE_HEADER_SIZE, security_cnt=0,
88 pad=0):
Oliver Swede21440442018-07-10 09:31:32 +010089 self.version = version
Tamas Banf70ef8c2017-12-19 15:35:09 +000090 self.header_size = header_size or IMAGE_HEADER_SIZE
David Vinczedb32b212019-04-16 17:43:57 +020091 self.security_cnt = security_cnt
Tamas Banf70ef8c2017-12-19 15:35:09 +000092 self.pad = pad
93
94 def __repr__(self):
David Vinczedb32b212019-04-16 17:43:57 +020095 return "<Image version={}, header_size={}, security_counter={}, \
96 pad={}, payloadlen=0x{:x}>".format(
Tamas Banf70ef8c2017-12-19 15:35:09 +000097 self.version,
98 self.header_size,
David Vinczedb32b212019-04-16 17:43:57 +020099 self.security_cnt,
Tamas Banf70ef8c2017-12-19 15:35:09 +0000100 self.pad,
101 len(self.payload))
102
103 def save(self, path):
104 with open(path, 'wb') as f:
105 f.write(self.payload)
106
107 def check(self):
108 """Perform some sanity checking of the image."""
109 # If there is a header requested, make sure that the image
110 # starts with all zeros.
111 if self.header_size > 0:
Gabor Kertesz33e9b232018-09-12 15:38:41 +0200112 if any(v != 0 and v != b'\000' for v in self.payload[0:self.header_size]):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000113 raise Exception("Padding requested, but image does not start with zeros")
114
Oliver Swede05e5ded2018-07-19 16:40:49 +0100115 def sign(self, key, ramLoadAddress):
David Vinczedb32b212019-04-16 17:43:57 +0200116 # Size of the security counter TLV:
117 # header ('BBH') + payload ('I') = 8 Bytes
118 protected_tlv_size = TLV_INFO_SIZE + 8
119
120 self.add_header(key, protected_tlv_size, ramLoadAddress)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000121
122 tlv = TLV()
123
David Vinczedb32b212019-04-16 17:43:57 +0200124 payload = struct.pack('I', self.security_cnt)
125 tlv.add('SEC_CNT', payload)
126 # Full TLV size needs to be calculated in advance, because the
127 # header will be protected as well
128 full_size = (TLV_INFO_SIZE + len(tlv.buf) + TLV_HEADER_SIZE
129 + PAYLOAD_DIGEST_SIZE)
130 if key is not None:
131 full_size += (TLV_HEADER_SIZE + KEYHASH_SIZE
132 + TLV_HEADER_SIZE + key.sig_len())
133 tlv_header = struct.pack('HH', TLV_INFO_MAGIC, full_size)
134 self.payload += tlv_header + bytes(tlv.buf)
135
Tamas Banf70ef8c2017-12-19 15:35:09 +0000136 sha = hashlib.sha256()
137 sha.update(self.payload)
138 digest = sha.digest()
139
140 tlv.add('SHA256', digest)
141
142 if key is not None:
143 pub = key.get_public_bytes()
144 sha = hashlib.sha256()
145 sha.update(pub)
146 pubbytes = sha.digest()
147 tlv.add('KEYHASH', pubbytes)
148
149 sig = key.sign(self.payload)
150 tlv.add(key.sig_tlv(), sig)
151
David Vinczedb32b212019-04-16 17:43:57 +0200152 self.payload += tlv.get()[protected_tlv_size:]
Tamas Banf70ef8c2017-12-19 15:35:09 +0000153
David Vinczedb32b212019-04-16 17:43:57 +0200154 def add_header(self, key, protected_tlv_size, ramLoadAddress):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000155 """Install the image header.
156
157 The key is needed to know the type of signature, and
158 approximate the size of the signature."""
159
160 flags = 0
Oliver Swede05e5ded2018-07-19 16:40:49 +0100161 if ramLoadAddress is not None:
162 # add the load address flag to the header to indicate that an SRAM
163 # load address macro has been defined
164 flags |= IMAGE_F["RAM_LOAD"]
Tamas Banf70ef8c2017-12-19 15:35:09 +0000165
166 fmt = ('<' +
167 # type ImageHdr struct {
David Vinczedb32b212019-04-16 17:43:57 +0200168 'I' + # Magic uint32
169 'I' + # LoadAddr uint32
170 'H' + # HdrSz uint16
171 'H' + # PTLVSz uint16
172 'I' + # ImgSz uint32
173 'I' + # Flags uint32
174 'BBHI' + # Vers ImageVersion
175 'I' # Pad1 uint32
Tamas Banf70ef8c2017-12-19 15:35:09 +0000176 ) # }
177 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
178 header = struct.pack(fmt,
179 IMAGE_MAGIC,
Oliver Swede05e5ded2018-07-19 16:40:49 +0100180 0 if (ramLoadAddress is None) else ramLoadAddress, # LoadAddr
Tamas Banf70ef8c2017-12-19 15:35:09 +0000181 self.header_size,
David Vinczedb32b212019-04-16 17:43:57 +0200182 protected_tlv_size, # TLV info header + security counter TLV
Tamas Banf70ef8c2017-12-19 15:35:09 +0000183 len(self.payload) - self.header_size, # ImageSz
184 flags, # Flags
185 self.version.major,
186 self.version.minor or 0,
187 self.version.revision or 0,
188 self.version.build or 0,
David Vinczedb32b212019-04-16 17:43:57 +0200189 0) # Pad1
Tamas Banf70ef8c2017-12-19 15:35:09 +0000190 self.payload = bytearray(self.payload)
191 self.payload[:len(header)] = header
192
193 def pad_to(self, size, align):
194 """Pad the image to the given size, with the given flash alignment."""
195 tsize = trailer_sizes[align]
196 padding = size - (len(self.payload) + tsize)
197 if padding < 0:
198 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
199 len(self.payload), tsize, size)
200 raise Exception(msg)
201 pbytes = b'\xff' * padding
202 pbytes += b'\xff' * (tsize - len(boot_magic))
203 pbytes += boot_magic
David Vinczedb32b212019-04-16 17:43:57 +0200204 self.payload += pbytes