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