blob: 10b2d25ccc09fd31d2916ede621f50f13ad09585 [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,
19 'ECDSA256_SHA256': 0x0000020, }
20
21TLV_VALUES = {
22 'SHA256': 1,
23 'RSA2048': 2,
24 'ECDSA224': 3,
25 'ECDSA256': 4, }
26
27TLV_HEADER_SIZE = 4
28
29# Sizes of the image trailer, depending on image alignment.
30trailer_sizes = {
31 1: 402,
32 2: 788,
33 4: 1560,
34 8: 3104, }
35
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
57 def load(cls, path, **kwargs):
58 """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
63 obj.check()
64 return obj
65
66 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE, pad=0):
67 self.version = version or versmod.decode_version("0")
68 self.header_size = header_size or IMAGE_HEADER_SIZE
69 self.pad = pad
70
71 def __repr__(self):
72 return "<Image version={}, header_size={}, pad={}, payloadlen=0x{:x}>".format(
73 self.version,
74 self.header_size,
75 self.pad,
76 len(self.payload))
77
78 def save(self, path):
79 with open(path, 'wb') as f:
80 f.write(self.payload)
81
82 def check(self):
83 """Perform some sanity checking of the image."""
84 # If there is a header requested, make sure that the image
85 # starts with all zeros.
86 if self.header_size > 0:
87 if any(v != 0 for v in self.payload[0:self.header_size]):
88 raise Exception("Padding requested, but image does not start with zeros")
89
90 def sign(self, key):
91 self.add_header(key)
92
93 tlv = TLV()
94
95 # Note that ecdsa wants to do the hashing itself, which means
96 # we get to hash it twice.
97 sha = hashlib.sha256()
98 sha.update(self.payload)
99 digest = sha.digest()
100
101 tlv.add('SHA256', digest)
102
103 sig = key.sign(self.payload)
104 tlv.add(key.sig_tlv(), sig)
105
106 self.payload += tlv.get()
107
108 def add_header(self, key):
109 """Install the image header.
110
111 The key is needed to know the type of signature, and
112 approximate the size of the signature."""
113
114 flags = IMAGE_F[key.sig_type()]
115 tlvsz = 0
116 tlvsz += TLV_HEADER_SIZE + key.sig_len()
117
118 flags |= IMAGE_F['SHA256']
119 tlvsz += 4 + hashlib.sha256().digest_size
120
121 fmt = ('<' +
122 # type ImageHdr struct {
123 'I' + # Magic uint32
124 'H' + # TlvSz uint16
125 'B' + # KeyId uint8
126 'B' + # Pad1 uint8
127 'H' + # HdrSz uint16
128 'H' + # Pad2 uint16
129 'I' + # ImgSz uint32
130 'I' + # Flags uint32
131 'BBHI' + # Vers ImageVersion
132 'I' # Pad3 uint32
133 ) # }
134 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
135 header = struct.pack(fmt,
136 IMAGE_MAGIC,
137 tlvsz, # TlvSz
138 0, # KeyId (TODO: allow other ids)
139 0, # Pad1
140 self.header_size,
141 0, # Pad2
142 len(self.payload) - self.header_size, # ImageSz
143 flags, # Flags
144 self.version.major,
145 self.version.minor or 0,
146 self.version.revision or 0,
147 self.version.build or 0,
148 0) # Pad3
149 self.payload = bytearray(self.payload)
150 self.payload[:len(header)] = header
151
152 def pad_to(self, size, align):
153 """Pad the image to the given size, with the given flash alignment."""
154 tsize = trailer_sizes[align]
155 padding = size - (len(self.payload) + tsize)
156 if padding < 0:
157 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
158 len(self.payload), tsize, size)
159 raise Exception(msg)
160 pbytes = b'\xff' * padding
161 pbytes += boot_magic
162 pbytes += b'\xff' * (tsize - len(boot_magic))
163 self.payload += pbytes