blob: 887ed97186e51373644a098971ade9ed576d3a9f [file] [log] [blame]
Carles Cufi37d052f2018-01-30 16:40:10 +01001# Copyright 2018 Nordic Semiconductor ASA
David Brown1314bf32017-12-20 11:10:55 -07002# Copyright 2017 Linaro Limited
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
David Brown23f91ad2017-05-16 11:38:17 -060016"""
17Image signing and management.
18"""
19
20from . import version as versmod
Carles Cufi37d052f2018-01-30 16:40:10 +010021from intelhex import IntelHex
David Brown23f91ad2017-05-16 11:38:17 -060022import hashlib
23import struct
Carles Cufi37d052f2018-01-30 16:40:10 +010024import os.path
David Brown23f91ad2017-05-16 11:38:17 -060025
David Brown72e7a512017-09-01 11:08:23 -060026IMAGE_MAGIC = 0x96f3b83d
David Brown23f91ad2017-05-16 11:38:17 -060027IMAGE_HEADER_SIZE = 32
Carles Cufi37d052f2018-01-30 16:40:10 +010028BIN_EXT = "bin"
29INTEL_HEX_EXT = "hex"
David Brown23f91ad2017-05-16 11:38:17 -060030
31# Image header flags.
32IMAGE_F = {
33 'PIC': 0x0000001,
David Brown43cda332017-09-01 09:53:23 -060034 'NON_BOOTABLE': 0x0000010, }
David Brown23f91ad2017-05-16 11:38:17 -060035
36TLV_VALUES = {
David Brown43cda332017-09-01 09:53:23 -060037 'KEYHASH': 0x01,
David Brown27648b82017-08-31 10:40:29 -060038 'SHA256': 0x10,
39 'RSA2048': 0x20,
40 'ECDSA224': 0x21,
41 'ECDSA256': 0x22, }
David Brown23f91ad2017-05-16 11:38:17 -060042
David Brownf5b33d82017-09-01 10:58:27 -060043TLV_INFO_SIZE = 4
44TLV_INFO_MAGIC = 0x6907
David Brown23f91ad2017-05-16 11:38:17 -060045
Fabio Utzige08f0872017-06-28 18:12:16 -030046# Sizes of the image trailer, depending on flash write size.
David Brown23f91ad2017-05-16 11:38:17 -060047trailer_sizes = {
Fabio Utzige08f0872017-06-28 18:12:16 -030048 write_size: 128 * 3 * write_size + 8 * 2 + 16
49 for write_size in [1, 2, 4, 8]
50}
David Brown23f91ad2017-05-16 11:38:17 -060051
52boot_magic = bytes([
53 0x77, 0xc2, 0x95, 0xf3,
54 0x60, 0xd2, 0xef, 0x7f,
55 0x35, 0x52, 0x50, 0x0f,
56 0x2c, 0xb6, 0x79, 0x80, ])
57
58class TLV():
59 def __init__(self):
60 self.buf = bytearray()
61
62 def add(self, kind, payload):
63 """Add a TLV record. Kind should be a string found in TLV_VALUES above."""
64 buf = struct.pack('<BBH', TLV_VALUES[kind], 0, len(payload))
65 self.buf += buf
66 self.buf += payload
67
68 def get(self):
David Brownf5b33d82017-09-01 10:58:27 -060069 header = struct.pack('<HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf))
70 return header + bytes(self.buf)
David Brown23f91ad2017-05-16 11:38:17 -060071
72class Image():
73 @classmethod
David Brown2c21f712017-06-08 10:03:42 -060074 def load(cls, path, included_header=False, **kwargs):
David Brown23f91ad2017-05-16 11:38:17 -060075 """Load an image from a given file"""
Carles Cufi37d052f2018-01-30 16:40:10 +010076 ext = os.path.splitext(path)[1][1:].lower()
77 if ext == INTEL_HEX_EXT:
78 cls = HexImage
79 else:
80 cls = BinImage
81
David Brown23f91ad2017-05-16 11:38:17 -060082 obj = cls(**kwargs)
Carles Cufi37d052f2018-01-30 16:40:10 +010083 obj.payload, obj.base_addr = obj.load(path)
David Brown2c21f712017-06-08 10:03:42 -060084
85 # Add the image header if needed.
86 if not included_header and obj.header_size > 0:
87 obj.payload = (b'\000' * obj.header_size) + obj.payload
88
David Brown23f91ad2017-05-16 11:38:17 -060089 obj.check()
90 return obj
91
92 def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE, pad=0):
93 self.version = version or versmod.decode_version("0")
94 self.header_size = header_size or IMAGE_HEADER_SIZE
95 self.pad = pad
96
97 def __repr__(self):
Carles Cufi37d052f2018-01-30 16:40:10 +010098 return "<Image version={}, header_size={}, base_addr={}, pad={}, \
99 format={}, payloadlen=0x{:x}>".format(
David Brown23f91ad2017-05-16 11:38:17 -0600100 self.version,
101 self.header_size,
Carles Cufi37d052f2018-01-30 16:40:10 +0100102 self.base_addr if self.base_addr is not None else "N/A",
David Brown23f91ad2017-05-16 11:38:17 -0600103 self.pad,
Carles Cufi37d052f2018-01-30 16:40:10 +0100104 self.__class__.__name__,
David Brown23f91ad2017-05-16 11:38:17 -0600105 len(self.payload))
106
David Brown23f91ad2017-05-16 11:38:17 -0600107 def check(self):
108 """Perform some sanity checking of the image."""
109 # If there is a header requested, make sure that the image
110 # starts with all zeros.
111 if self.header_size > 0:
112 if any(v != 0 for v in self.payload[0:self.header_size]):
113 raise Exception("Padding requested, but image does not start with zeros")
114
115 def sign(self, key):
116 self.add_header(key)
117
118 tlv = TLV()
119
120 # Note that ecdsa wants to do the hashing itself, which means
121 # we get to hash it twice.
122 sha = hashlib.sha256()
123 sha.update(self.payload)
124 digest = sha.digest()
125
126 tlv.add('SHA256', digest)
127
David Brown0f0c6a82017-06-08 09:26:24 -0600128 if key is not None:
David Brown43cda332017-09-01 09:53:23 -0600129 pub = key.get_public_bytes()
130 sha = hashlib.sha256()
131 sha.update(pub)
132 pubbytes = sha.digest()
133 tlv.add('KEYHASH', pubbytes)
134
David Brown47b77c52017-11-16 15:10:22 -0700135 sig = key.sign(bytes(self.payload))
David Brown0f0c6a82017-06-08 09:26:24 -0600136 tlv.add(key.sig_tlv(), sig)
David Brown23f91ad2017-05-16 11:38:17 -0600137
138 self.payload += tlv.get()
139
140 def add_header(self, key):
141 """Install the image header.
142
143 The key is needed to know the type of signature, and
144 approximate the size of the signature."""
145
David Brown0f0c6a82017-06-08 09:26:24 -0600146 flags = 0
David Brown23f91ad2017-05-16 11:38:17 -0600147
148 fmt = ('<' +
149 # type ImageHdr struct {
150 'I' + # Magic uint32
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300151 'I' + # LoadAddr uint32
David Brown23f91ad2017-05-16 11:38:17 -0600152 'H' + # HdrSz uint16
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300153 'H' + # Pad1 uint16
David Brown23f91ad2017-05-16 11:38:17 -0600154 'I' + # ImgSz uint32
155 'I' + # Flags uint32
156 'BBHI' + # Vers ImageVersion
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300157 'I' # Pad2 uint32
David Brown23f91ad2017-05-16 11:38:17 -0600158 ) # }
159 assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE
160 header = struct.pack(fmt,
161 IMAGE_MAGIC,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300162 0, # LoadAddr
David Brown23f91ad2017-05-16 11:38:17 -0600163 self.header_size,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300164 0, # Pad1
David Brown23f91ad2017-05-16 11:38:17 -0600165 len(self.payload) - self.header_size, # ImageSz
166 flags, # Flags
167 self.version.major,
168 self.version.minor or 0,
169 self.version.revision or 0,
170 self.version.build or 0,
Fabio Utzigb5b59f12018-05-10 07:27:08 -0300171 0) # Pad2
David Brown23f91ad2017-05-16 11:38:17 -0600172 self.payload = bytearray(self.payload)
173 self.payload[:len(header)] = header
174
175 def pad_to(self, size, align):
176 """Pad the image to the given size, with the given flash alignment."""
177 tsize = trailer_sizes[align]
178 padding = size - (len(self.payload) + tsize)
179 if padding < 0:
180 msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format(
181 len(self.payload), tsize, size)
182 raise Exception(msg)
Fabio Utzige08f0872017-06-28 18:12:16 -0300183 pbytes = b'\xff' * padding
David Brown23f91ad2017-05-16 11:38:17 -0600184 pbytes += b'\xff' * (tsize - len(boot_magic))
Fabio Utzige08f0872017-06-28 18:12:16 -0300185 pbytes += boot_magic
David Brown23f91ad2017-05-16 11:38:17 -0600186 self.payload += pbytes
Carles Cufi37d052f2018-01-30 16:40:10 +0100187
188class HexImage(Image):
189
190 def load(self, path):
191 ih = IntelHex(path)
192 return ih.tobinarray(), ih.minaddr()
193
194 def save(self, path):
195 h = IntelHex()
196 h.frombytes(bytes = self.payload, offset = self.base_addr)
197 h.tofile(path, 'hex')
198
199class BinImage(Image):
200
201 def load(self, path):
202 with open(path, 'rb') as f:
203 return f.read(), None
204
205 def save(self, path):
206 with open(path, 'wb') as f:
207 f.write(self.payload)