blob: f8309b323328912f84a0bdb1328cac2edabacc6e [file] [log] [blame]
Tamas Banf70ef8c2017-12-19 15:35:09 +00001# Copyright 2017 Linaro Limited
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""
16Image signing and management.
17"""
18
19from . import version as versmod
20import hashlib
21import struct
22
23IMAGE_MAGIC = 0x96f3b83d
24IMAGE_HEADER_SIZE = 32
25
26# Image header flags.
27IMAGE_F = {
28 'PIC': 0x0000001,
29 'NON_BOOTABLE': 0x0000010, }
30
31TLV_VALUES = {
32 'KEYHASH': 0x01,
Tamas Ban581034a2017-12-19 19:54:37 +000033 'SHA256' : 0x10,
34 'RSA2048': 0x20, }
Tamas Banf70ef8c2017-12-19 15:35:09 +000035
36TLV_INFO_SIZE = 4
37TLV_INFO_MAGIC = 0x6907
38TLV_HEADER_SIZE = 4
39
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
82 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE, pad=0):
83 self.version = version or versmod.decode_version("0")
84 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
106 def sign(self, key):
107 self.add_header(key)
108
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
129 def add_header(self, key):
130 """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
136 tlvsz = 0
137 if key is not None:
138 tlvsz += TLV_HEADER_SIZE + key.sig_len()
139
140 tlvsz += 4 + hashlib.sha256().digest_size
141 tlvsz += 4 + hashlib.sha256().digest_size
142
143 fmt = ('<' +
144 # type ImageHdr struct {
145 'I' + # Magic uint32
146 'H' + # TlvSz uint16
147 'B' + # KeyId uint8
148 'B' + # Pad1 uint8
149 'H' + # HdrSz uint16
150 'H' + # Pad2 uint16
151 'I' + # ImgSz uint32
152 'I' + # Flags uint32
153 'BBHI' + # Vers ImageVersion
154 'I' # Pad3 uint32
155 ) # }
156 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
157 header = struct.pack(fmt,
158 IMAGE_MAGIC,
159 tlvsz, # TlvSz
160 0, # KeyId (TODO: allow other ids)
161 0, # Pad1
162 self.header_size,
163 0, # Pad2
164 len(self.payload) - self.header_size, # ImageSz
165 flags, # Flags
166 self.version.major,
167 self.version.minor or 0,
168 self.version.revision or 0,
169 self.version.build or 0,
170 0) # Pad3
171 self.payload = bytearray(self.payload)
172 self.payload[:len(header)] = header
173
174 def pad_to(self, size, align):
175 """Pad the image to the given size, with the given flash alignment."""
176 tsize = trailer_sizes[align]
177 padding = size - (len(self.payload) + tsize)
178 if padding < 0:
179 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
180 len(self.payload), tsize, size)
181 raise Exception(msg)
182 pbytes = b'\xff' * padding
183 pbytes += b'\xff' * (tsize - len(boot_magic))
184 pbytes += boot_magic
185 self.payload += pbytes