blob: 358b1f2b6eb7eba14d51292b9f04be95f513d66b [file] [log] [blame]
David Brown23f91ad2017-05-16 11:38:17 -06001"""
2Image signing and management.
3"""
4
5from . import version as versmod
6import hashlib
7import struct
8
David Brown72e7a512017-09-01 11:08:23 -06009IMAGE_MAGIC = 0x96f3b83d
David Brown23f91ad2017-05-16 11:38:17 -060010IMAGE_HEADER_SIZE = 32
11
12# Image header flags.
13IMAGE_F = {
14 'PIC': 0x0000001,
David Brown43cda332017-09-01 09:53:23 -060015 'NON_BOOTABLE': 0x0000010, }
David Brown23f91ad2017-05-16 11:38:17 -060016
17TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060018 'KEYHASH': 0x01,
David Brown27648b82017-08-31 10:40:29 -060019 'SHA256': 0x10,
20 'RSA2048': 0x20,
21 'ECDSA224': 0x21,
22 'ECDSA256': 0x22, }
David Brown23f91ad2017-05-16 11:38:17 -060023
David Brownf5b33d82017-09-01 10:58:27 -060024TLV_INFO_SIZE = 4
25TLV_INFO_MAGIC = 0x6907
David Brown23f91ad2017-05-16 11:38:17 -060026TLV_HEADER_SIZE = 4
27
Fabio Utzige08f0872017-06-28 18:12:16 -030028# Sizes of the image trailer, depending on flash write size.
David Brown23f91ad2017-05-16 11:38:17 -060029trailer_sizes = {
Fabio Utzige08f0872017-06-28 18:12:16 -030030 write_size: 128 * 3 * write_size + 8 * 2 + 16
31 for write_size in [1, 2, 4, 8]
32}
David Brown23f91ad2017-05-16 11:38:17 -060033
34boot_magic = bytes([
35 0x77, 0xc2, 0x95, 0xf3,
36 0x60, 0xd2, 0xef, 0x7f,
37 0x35, 0x52, 0x50, 0x0f,
38 0x2c, 0xb6, 0x79, 0x80, ])
39
40class TLV():
41 def __init__(self):
42 self.buf = bytearray()
43
44 def add(self, kind, payload):
45 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
46 buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
47 self.buf += buf
48 self.buf += payload
49
50 def get(self):
David Brownf5b33d82017-09-01 10:58:27 -060051 header = struct.pack('<HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
52 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -060053
54class Image():
55 @classmethod
David Brown2c21f712017-06-08 10:03:42 -060056 def load(cls, path, included_header=False, **kwargs):
David Brown23f91ad2017-05-16 11:38:17 -060057 """Load an image from a given file"""
58 with open(path, 'rb') as f:
59 payload = f.read()
60 obj = cls(**kwargs)
61 obj.payload = payload
David Brown2c21f712017-06-08 10:03:42 -060062
63 # Add the image header if needed.
64 if not included_header and obj.header_size > 0:
65 obj.payload = (b'\000' * obj.header_size) + obj.payload
66
David Brown23f91ad2017-05-16 11:38:17 -060067 obj.check()
68 return obj
69
70 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE, pad=0):
71 self.version = version or versmod.decode_version("0")
72 self.header_size = header_size or IMAGE_HEADER_SIZE
73 self.pad = pad
74
75 def __repr__(self):
76 return "<Image version={}, header_size={}, pad={}, payloadlen=0x{:x}>".format(
77 self.version,
78 self.header_size,
79 self.pad,
80 len(self.payload))
81
82 def save(self, path):
83 with open(path, 'wb') as f:
84 f.write(self.payload)
85
86 def check(self):
87 """Perform some sanity checking of the image."""
88 # If there is a header requested, make sure that the image
89 # starts with all zeros.
90 if self.header_size > 0:
91 if any(v != 0 for v in self.payload[0:self.header_size]):
92 raise Exception("Padding requested, but image does not start with zeros")
93
94 def sign(self, key):
95 self.add_header(key)
96
97 tlv = TLV()
98
99 # Note that ecdsa wants to do the hashing itself, which means
100 # we get to hash it twice.
101 sha = hashlib.sha256()
102 sha.update(self.payload)
103 digest = sha.digest()
104
105 tlv.add('SHA256', digest)
106
David Brown0f0c6a82017-06-08 09:26:24 -0600107 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600108 pub = key.get_public_bytes()
109 sha = hashlib.sha256()
110 sha.update(pub)
111 pubbytes = sha.digest()
112 tlv.add('KEYHASH', pubbytes)
113
David Brown0f0c6a82017-06-08 09:26:24 -0600114 sig = key.sign(self.payload)
115 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600116
117 self.payload += tlv.get()
118
119 def add_header(self, key):
120 """Install the image header.
121
122 The key is needed to know the type of signature, and
123 approximate the size of the signature."""
124
David Brown0f0c6a82017-06-08 09:26:24 -0600125 flags = 0
David Brown23f91ad2017-05-16 11:38:17 -0600126 tlvsz = 0
David Brown0f0c6a82017-06-08 09:26:24 -0600127 if key is not None:
David Brown0f0c6a82017-06-08 09:26:24 -0600128 tlvsz += TLV_HEADER_SIZE + key.sig_len()
David Brown23f91ad2017-05-16 11:38:17 -0600129
David Brown43cda332017-09-01 09:53:23 -0600130 tlvsz += 4 + hashlib.sha256().digest_size
David Brown23f91ad2017-05-16 11:38:17 -0600131 tlvsz += 4 + hashlib.sha256().digest_size
132
133 fmt = ('<' +
134 # type ImageHdr struct {
135 'I' + # Magic uint32
136 'H' + # TlvSz uint16
137 'B' + # KeyId uint8
138 'B' + # Pad1 uint8
139 'H' + # HdrSz uint16
140 'H' + # Pad2 uint16
141 'I' + # ImgSz uint32
142 'I' + # Flags uint32
143 'BBHI' + # Vers ImageVersion
144 'I' # Pad3 uint32
145 ) # }
146 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
147 header = struct.pack(fmt,
148 IMAGE_MAGIC,
149 tlvsz, # TlvSz
150 0, # KeyId (TODO: allow other ids)
151 0, # Pad1
152 self.header_size,
153 0, # Pad2
154 len(self.payload) - self.header_size, # ImageSz
155 flags, # Flags
156 self.version.major,
157 self.version.minor or 0,
158 self.version.revision or 0,
159 self.version.build or 0,
160 0) # Pad3
161 self.payload = bytearray(self.payload)
162 self.payload[:len(header)] = header
163
164 def pad_to(self, size, align):
165 """Pad the image to the given size, with the given flash alignment."""
166 tsize = trailer_sizes[align]
167 padding = size - (len(self.payload) + tsize)
168 if padding < 0:
169 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
170 len(self.payload), tsize, size)
171 raise Exception(msg)
Fabio Utzige08f0872017-06-28 18:12:16 -0300172 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600173 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300174 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600175 self.payload += pbytes