blob: 9a9225f99a4f94958cefe8dee726b39ec6d57a92 [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
9IMAGE_MAGIC = 0x96f3b83c
10IMAGE_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
24TLV_HEADER_SIZE = 4
25
Fabio Utzige08f0872017-06-28 18:12:16 -030026# Sizes of the image trailer, depending on flash write size.
David Brown23f91ad2017-05-16 11:38:17 -060027trailer_sizes = {
Fabio Utzige08f0872017-06-28 18:12:16 -030028 write_size: 128 * 3 * write_size + 8 * 2 + 16
29 for write_size in [1, 2, 4, 8]
30}
David Brown23f91ad2017-05-16 11:38:17 -060031
32boot_magic = bytes([
33 0x77, 0xc2, 0x95, 0xf3,
34 0x60, 0xd2, 0xef, 0x7f,
35 0x35, 0x52, 0x50, 0x0f,
36 0x2c, 0xb6, 0x79, 0x80, ])
37
38class TLV():
39 def __init__(self):
40 self.buf = bytearray()
41
42 def add(self, kind, payload):
43 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
44 buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
45 self.buf += buf
46 self.buf += payload
47
48 def get(self):
49 return bytes(self.buf)
50
51class Image():
52 @classmethod
David Brown2c21f712017-06-08 10:03:42 -060053 def load(cls, path, included_header=False, **kwargs):
David Brown23f91ad2017-05-16 11:38:17 -060054 """Load an image from a given file"""
55 with open(path, 'rb') as f:
56 payload = f.read()
57 obj = cls(**kwargs)
58 obj.payload = payload
David Brown2c21f712017-06-08 10:03:42 -060059
60 # Add the image header if needed.
61 if not included_header and obj.header_size > 0:
62 obj.payload = (b'\000' * obj.header_size) + obj.payload
63
David Brown23f91ad2017-05-16 11:38:17 -060064 obj.check()
65 return obj
66
67 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE, pad=0):
68 self.version = version or versmod.decode_version("0")
69 self.header_size = header_size or IMAGE_HEADER_SIZE
70 self.pad = pad
71
72 def __repr__(self):
73 return "<Image version={}, header_size={}, pad={}, payloadlen=0x{:x}>".format(
74 self.version,
75 self.header_size,
76 self.pad,
77 len(self.payload))
78
79 def save(self, path):
80 with open(path, 'wb') as f:
81 f.write(self.payload)
82
83 def check(self):
84 """Perform some sanity checking of the image."""
85 # If there is a header requested, make sure that the image
86 # starts with all zeros.
87 if self.header_size > 0:
88 if any(v != 0 for v in self.payload[0:self.header_size]):
89 raise Exception("Padding requested, but image does not start with zeros")
90
91 def sign(self, key):
92 self.add_header(key)
93
94 tlv = TLV()
95
96 # Note that ecdsa wants to do the hashing itself, which means
97 # we get to hash it twice.
98 sha = hashlib.sha256()
99 sha.update(self.payload)
100 digest = sha.digest()
101
102 tlv.add('SHA256', digest)
103
David Brown0f0c6a82017-06-08 09:26:24 -0600104 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600105 pub = key.get_public_bytes()
106 sha = hashlib.sha256()
107 sha.update(pub)
108 pubbytes = sha.digest()
109 tlv.add('KEYHASH', pubbytes)
110
David Brown0f0c6a82017-06-08 09:26:24 -0600111 sig = key.sign(self.payload)
112 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600113
114 self.payload += tlv.get()
115
116 def add_header(self, key):
117 """Install the image header.
118
119 The key is needed to know the type of signature, and
120 approximate the size of the signature."""
121
David Brown0f0c6a82017-06-08 09:26:24 -0600122 flags = 0
David Brown23f91ad2017-05-16 11:38:17 -0600123 tlvsz = 0
David Brown0f0c6a82017-06-08 09:26:24 -0600124 if key is not None:
David Brown0f0c6a82017-06-08 09:26:24 -0600125 tlvsz += TLV_HEADER_SIZE + key.sig_len()
David Brown23f91ad2017-05-16 11:38:17 -0600126
David Brown43cda332017-09-01 09:53:23 -0600127 tlvsz += 4 + hashlib.sha256().digest_size
David Brown23f91ad2017-05-16 11:38:17 -0600128 tlvsz += 4 + hashlib.sha256().digest_size
129
130 fmt = ('<' +
131 # type ImageHdr struct {
132 'I' + # Magic uint32
133 'H' + # TlvSz uint16
134 'B' + # KeyId uint8
135 'B' + # Pad1 uint8
136 'H' + # HdrSz uint16
137 'H' + # Pad2 uint16
138 'I' + # ImgSz uint32
139 'I' + # Flags uint32
140 'BBHI' + # Vers ImageVersion
141 'I' # Pad3 uint32
142 ) # }
143 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
144 header = struct.pack(fmt,
145 IMAGE_MAGIC,
146 tlvsz, # TlvSz
147 0, # KeyId (TODO: allow other ids)
148 0, # Pad1
149 self.header_size,
150 0, # Pad2
151 len(self.payload) - self.header_size, # ImageSz
152 flags, # Flags
153 self.version.major,
154 self.version.minor or 0,
155 self.version.revision or 0,
156 self.version.build or 0,
157 0) # Pad3
158 self.payload = bytearray(self.payload)
159 self.payload[:len(header)] = header
160
161 def pad_to(self, size, align):
162 """Pad the image to the given size, with the given flash alignment."""
163 tsize = trailer_sizes[align]
164 padding = size - (len(self.payload) + tsize)
165 if padding < 0:
166 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
167 len(self.payload), tsize, size)
168 raise Exception(msg)
Fabio Utzige08f0872017-06-28 18:12:16 -0300169 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600170 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300171 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600172 self.payload += pbytes