blob: b3915e046a2ffdb4a96cfdbf176723422052d52a [file] [log] [blame]
Tamas Banf70ef8c2017-12-19 15:35:09 +00001# Copyright 2017 Linaro Limited
Oliver Swede05e5ded2018-07-19 16:40:49 +01002# Copyright (c) 2018, 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
26
27# Image header flags.
28IMAGE_F = {
29 'PIC': 0x0000001,
Oliver Swede05e5ded2018-07-19 16:40:49 +010030 'NON_BOOTABLE': 0x0000010,
31 'RAM_LOAD': 0x0000020, }
Tamas Banf70ef8c2017-12-19 15:35:09 +000032TLV_VALUES = {
33 'KEYHASH': 0x01,
Tamas Ban581034a2017-12-19 19:54:37 +000034 'SHA256' : 0x10,
35 'RSA2048': 0x20, }
Tamas Banf70ef8c2017-12-19 15:35:09 +000036
37TLV_INFO_SIZE = 4
38TLV_INFO_MAGIC = 0x6907
Tamas Banf70ef8c2017-12-19 15:35:09 +000039
40# Sizes of the image trailer, depending on flash write size.
41trailer_sizes = {
42 write_size: 128 * 3 * write_size + 8 * 2 + 16
43 for write_size in [1, 2, 4, 8]
44}
45
46boot_magic = bytes([
47 0x77, 0xc2, 0x95, 0xf3,
48 0x60, 0xd2, 0xef, 0x7f,
49 0x35, 0x52, 0x50, 0x0f,
50 0x2c, 0xb6, 0x79, 0x80, ])
51
52class TLV():
53 def __init__(self):
54 self.buf = bytearray()
55
56 def add(self, kind, payload):
57 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
58 buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
59 self.buf += buf
60 self.buf += payload
61
62 def get(self):
63 header = struct.pack('<HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
64 return header + bytes(self.buf)
65
66class Image():
67 @classmethod
68 def load(cls, path, included_header=False, **kwargs):
69 """Load an image from a given file"""
70 with open(path, 'rb') as f:
71 payload = f.read()
72 obj = cls(**kwargs)
73 obj.payload = payload
74
75 # Add the image header if needed.
76 if not included_header and obj.header_size > 0:
77 obj.payload = (b'\000' * obj.header_size) + obj.payload
78
79 obj.check()
80 return obj
81
Oliver Swede21440442018-07-10 09:31:32 +010082 def __init__(self, version, header_size=IMAGE_HEADER_SIZE, pad=0):
83 self.version = version
Tamas Banf70ef8c2017-12-19 15:35:09 +000084 self.header_size = header_size or IMAGE_HEADER_SIZE
85 self.pad = pad
86
87 def __repr__(self):
88 return "<Image version={}, header_size={}, pad={}, payloadlen=0x{:x}>".format(
89 self.version,
90 self.header_size,
91 self.pad,
92 len(self.payload))
93
94 def save(self, path):
95 with open(path, 'wb') as f:
96 f.write(self.payload)
97
98 def check(self):
99 """Perform some sanity checking of the image."""
100 # If there is a header requested, make sure that the image
101 # starts with all zeros.
102 if self.header_size > 0:
103 if any(v != 0 for v in self.payload[0:self.header_size]):
104 raise Exception("Padding requested, but image does not start with zeros")
105
Oliver Swede05e5ded2018-07-19 16:40:49 +0100106 def sign(self, key, ramLoadAddress):
107 self.add_header(key, ramLoadAddress)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000108
109 tlv = TLV()
110
Tamas Banf70ef8c2017-12-19 15:35:09 +0000111 sha = hashlib.sha256()
112 sha.update(self.payload)
113 digest = sha.digest()
114
115 tlv.add('SHA256', digest)
116
117 if key is not None:
118 pub = key.get_public_bytes()
119 sha = hashlib.sha256()
120 sha.update(pub)
121 pubbytes = sha.digest()
122 tlv.add('KEYHASH', pubbytes)
123
124 sig = key.sign(self.payload)
125 tlv.add(key.sig_tlv(), sig)
126
127 self.payload += tlv.get()
128
Oliver Swede05e5ded2018-07-19 16:40:49 +0100129 def add_header(self, key, ramLoadAddress):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000130 """Install the image header.
131
132 The key is needed to know the type of signature, and
133 approximate the size of the signature."""
134
135 flags = 0
Oliver Swede05e5ded2018-07-19 16:40:49 +0100136 if ramLoadAddress is not None:
137 # add the load address flag to the header to indicate that an SRAM
138 # load address macro has been defined
139 flags |= IMAGE_F["RAM_LOAD"]
Tamas Banf70ef8c2017-12-19 15:35:09 +0000140
141 fmt = ('<' +
142 # type ImageHdr struct {
143 'I' + # Magic uint32
Oliver Swede285dacd2018-08-08 10:12:47 +0100144 'I' + # LoadAddr uint32
Tamas Banf70ef8c2017-12-19 15:35:09 +0000145 'H' + # HdrSz uint16
Oliver Swede285dacd2018-08-08 10:12:47 +0100146 'H' + # Pad1 uint16
Tamas Banf70ef8c2017-12-19 15:35:09 +0000147 'I' + # ImgSz uint32
148 'I' + # Flags uint32
149 'BBHI' + # Vers ImageVersion
Oliver Swede285dacd2018-08-08 10:12:47 +0100150 'I' # Pad2 uint32
Tamas Banf70ef8c2017-12-19 15:35:09 +0000151 ) # }
152 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
153 header = struct.pack(fmt,
154 IMAGE_MAGIC,
Oliver Swede05e5ded2018-07-19 16:40:49 +0100155 0 if (ramLoadAddress is None) else ramLoadAddress, # LoadAddr
Tamas Banf70ef8c2017-12-19 15:35:09 +0000156 self.header_size,
Oliver Swede285dacd2018-08-08 10:12:47 +0100157 0, # Pad1
Tamas Banf70ef8c2017-12-19 15:35:09 +0000158 len(self.payload) - self.header_size, # ImageSz
159 flags, # Flags
160 self.version.major,
161 self.version.minor or 0,
162 self.version.revision or 0,
163 self.version.build or 0,
Oliver Swede285dacd2018-08-08 10:12:47 +0100164 0) # Pad2
Tamas Banf70ef8c2017-12-19 15:35:09 +0000165 self.payload = bytearray(self.payload)
166 self.payload[:len(header)] = header
167
168 def pad_to(self, size, align):
169 """Pad the image to the given size, with the given flash alignment."""
170 tsize = trailer_sizes[align]
171 padding = size - (len(self.payload) + tsize)
172 if padding < 0:
173 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
174 len(self.payload), tsize, size)
175 raise Exception(msg)
176 pbytes = b'\xff' * padding
177 pbytes += b'\xff' * (tsize - len(boot_magic))
178 pbytes += boot_magic
Oliver Swede21440442018-07-10 09:31:32 +0100179 self.payload += pbytes