blob: efd20d71a6b666ec3ce977736631e5048f7a5781 [file] [log] [blame]
David Brown1314bf32017-12-20 11:10:55 -07001# 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
David Brown23f91ad2017-05-16 11:38:17 -060015"""
16Image signing and management.
17"""
18
19from . import version as versmod
20import hashlib
21import struct
22
David Brown72e7a512017-09-01 11:08:23 -060023IMAGE_MAGIC = 0x96f3b83d
David Brown23f91ad2017-05-16 11:38:17 -060024IMAGE_HEADER_SIZE = 32
25
26# Image header flags.
27IMAGE_F = {
28 'PIC': 0x0000001,
David Brown43cda332017-09-01 09:53:23 -060029 'NON_BOOTABLE': 0x0000010, }
David Brown23f91ad2017-05-16 11:38:17 -060030
31TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060032 'KEYHASH': 0x01,
David Brown27648b82017-08-31 10:40:29 -060033 'SHA256': 0x10,
34 'RSA2048': 0x20,
35 'ECDSA224': 0x21,
36 'ECDSA256': 0x22, }
David Brown23f91ad2017-05-16 11:38:17 -060037
David Brownf5b33d82017-09-01 10:58:27 -060038TLV_INFO_SIZE = 4
39TLV_INFO_MAGIC = 0x6907
David Brown23f91ad2017-05-16 11:38:17 -060040TLV_HEADER_SIZE = 4
41
Fabio Utzige08f0872017-06-28 18:12:16 -030042# Sizes of the image trailer, depending on flash write size.
David Brown23f91ad2017-05-16 11:38:17 -060043trailer_sizes = {
Fabio Utzige08f0872017-06-28 18:12:16 -030044 write_size: 128 * 3 * write_size + 8 * 2 + 16
45 for write_size in [1, 2, 4, 8]
46}
David Brown23f91ad2017-05-16 11:38:17 -060047
48boot_magic = bytes([
49 0x77, 0xc2, 0x95, 0xf3,
50 0x60, 0xd2, 0xef, 0x7f,
51 0x35, 0x52, 0x50, 0x0f,
52 0x2c, 0xb6, 0x79, 0x80, ])
53
54class TLV():
55 def __init__(self):
56 self.buf = bytearray()
57
58 def add(self, kind, payload):
59 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
60 buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
61 self.buf += buf
62 self.buf += payload
63
64 def get(self):
David Brownf5b33d82017-09-01 10:58:27 -060065 header = struct.pack('<HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
66 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -060067
68class Image():
69 @classmethod
David Brown2c21f712017-06-08 10:03:42 -060070 def load(cls, path, included_header=False, **kwargs):
David Brown23f91ad2017-05-16 11:38:17 -060071 """Load an image from a given file"""
72 with open(path, 'rb') as f:
73 payload = f.read()
74 obj = cls(**kwargs)
75 obj.payload = payload
David Brown2c21f712017-06-08 10:03:42 -060076
77 # Add the image header if needed.
78 if not included_header and obj.header_size > 0:
79 obj.payload = (b'\000' * obj.header_size) + obj.payload
80
David Brown23f91ad2017-05-16 11:38:17 -060081 obj.check()
82 return obj
83
84 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE, pad=0):
85 self.version = version or versmod.decode_version("0")
86 self.header_size = header_size or IMAGE_HEADER_SIZE
87 self.pad = pad
88
89 def __repr__(self):
90 return "<Image version={}, header_size={}, pad={}, payloadlen=0x{:x}>".format(
91 self.version,
92 self.header_size,
93 self.pad,
94 len(self.payload))
95
96 def save(self, path):
97 with open(path, 'wb') as f:
98 f.write(self.payload)
99
100 def check(self):
101 """Perform some sanity checking of the image."""
102 # If there is a header requested, make sure that the image
103 # starts with all zeros.
104 if self.header_size > 0:
105 if any(v != 0 for v in self.payload[0:self.header_size]):
106 raise Exception("Padding requested, but image does not start with zeros")
107
108 def sign(self, key):
109 self.add_header(key)
110
111 tlv = TLV()
112
113 # Note that ecdsa wants to do the hashing itself, which means
114 # we get to hash it twice.
115 sha = hashlib.sha256()
116 sha.update(self.payload)
117 digest = sha.digest()
118
119 tlv.add('SHA256', digest)
120
David Brown0f0c6a82017-06-08 09:26:24 -0600121 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600122 pub = key.get_public_bytes()
123 sha = hashlib.sha256()
124 sha.update(pub)
125 pubbytes = sha.digest()
126 tlv.add('KEYHASH', pubbytes)
127
David Brown47b77c52017-11-16 15:10:22 -0700128 sig = key.sign(bytes(self.payload))
David Brown0f0c6a82017-06-08 09:26:24 -0600129 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600130
131 self.payload += tlv.get()
132
133 def add_header(self, key):
134 """Install the image header.
135
136 The key is needed to know the type of signature, and
137 approximate the size of the signature."""
138
David Brown0f0c6a82017-06-08 09:26:24 -0600139 flags = 0
David Brown23f91ad2017-05-16 11:38:17 -0600140 tlvsz = 0
David Brown0f0c6a82017-06-08 09:26:24 -0600141 if key is not None:
David Brown0f0c6a82017-06-08 09:26:24 -0600142 tlvsz += TLV_HEADER_SIZE + key.sig_len()
David Brown23f91ad2017-05-16 11:38:17 -0600143
David Brown43cda332017-09-01 09:53:23 -0600144 tlvsz += 4 + hashlib.sha256().digest_size
David Brown23f91ad2017-05-16 11:38:17 -0600145 tlvsz += 4 + hashlib.sha256().digest_size
146
147 fmt = ('<' +
148 # type ImageHdr struct {
149 'I' + # Magic uint32
150 'H' + # TlvSz uint16
151 'B' + # KeyId uint8
152 'B' + # Pad1 uint8
153 'H' + # HdrSz uint16
154 'H' + # Pad2 uint16
155 'I' + # ImgSz uint32
156 'I' + # Flags uint32
157 'BBHI' + # Vers ImageVersion
158 'I' # Pad3 uint32
159 ) # }
160 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
161 header = struct.pack(fmt,
162 IMAGE_MAGIC,
163 tlvsz, # TlvSz
164 0, # KeyId (TODO: allow other ids)
165 0, # Pad1
166 self.header_size,
167 0, # Pad2
168 len(self.payload) - self.header_size, # ImageSz
169 flags, # Flags
170 self.version.major,
171 self.version.minor or 0,
172 self.version.revision or 0,
173 self.version.build or 0,
174 0) # Pad3
175 self.payload = bytearray(self.payload)
176 self.payload[:len(header)] = header
177
178 def pad_to(self, size, align):
179 """Pad the image to the given size, with the given flash alignment."""
180 tsize = trailer_sizes[align]
181 padding = size - (len(self.payload) + tsize)
182 if padding < 0:
183 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
184 len(self.payload), tsize, size)
185 raise Exception(msg)
Fabio Utzige08f0872017-06-28 18:12:16 -0300186 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600187 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300188 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600189 self.payload += pbytes