Carles Cufi | 37d052f | 2018-01-30 16:40:10 +0100 | [diff] [blame] | 1 | # Copyright 2018 Nordic Semiconductor ASA |
David Brown | 1314bf3 | 2017-12-20 11:10:55 -0700 | [diff] [blame] | 2 | # Copyright 2017 Linaro Limited |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 3 | # Copyright 2019 Arm Limited |
David Brown | 1314bf3 | 2017-12-20 11:10:55 -0700 | [diff] [blame] | 4 | # |
| 5 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | # you may not use this file except in compliance with the License. |
| 7 | # You may obtain a copy of the License at |
| 8 | # |
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | # |
| 11 | # Unless required by applicable law or agreed to in writing, software |
| 12 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | # See the License for the specific language governing permissions and |
| 15 | # limitations under the License. |
| 16 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 17 | """ |
| 18 | Image signing and management. |
| 19 | """ |
| 20 | |
| 21 | from . import version as versmod |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 22 | from enum import Enum |
Carles Cufi | 37d052f | 2018-01-30 16:40:10 +0100 | [diff] [blame] | 23 | from intelhex import IntelHex |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 24 | import hashlib |
| 25 | import struct |
Carles Cufi | 37d052f | 2018-01-30 16:40:10 +0100 | [diff] [blame] | 26 | import os.path |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 27 | from cryptography.hazmat.primitives.asymmetric import padding |
| 28 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes |
| 29 | from cryptography.hazmat.backends import default_backend |
| 30 | from cryptography.hazmat.primitives import hashes |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 31 | from cryptography.exceptions import InvalidSignature |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 32 | |
David Brown | 72e7a51 | 2017-09-01 11:08:23 -0600 | [diff] [blame] | 33 | IMAGE_MAGIC = 0x96f3b83d |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 34 | IMAGE_HEADER_SIZE = 32 |
Carles Cufi | 37d052f | 2018-01-30 16:40:10 +0100 | [diff] [blame] | 35 | BIN_EXT = "bin" |
| 36 | INTEL_HEX_EXT = "hex" |
Fabio Utzig | 519285f | 2018-06-04 11:11:53 -0300 | [diff] [blame] | 37 | DEFAULT_MAX_SECTORS = 128 |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 38 | DEP_IMAGES_KEY = "images" |
| 39 | DEP_VERSIONS_KEY = "versions" |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 40 | |
| 41 | # Image header flags. |
| 42 | IMAGE_F = { |
| 43 | 'PIC': 0x0000001, |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 44 | 'NON_BOOTABLE': 0x0000010, |
| 45 | 'ENCRYPTED': 0x0000004, |
| 46 | } |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 47 | |
| 48 | TLV_VALUES = { |
David Brown | 43cda33 | 2017-09-01 09:53:23 -0600 | [diff] [blame] | 49 | 'KEYHASH': 0x01, |
David Brown | 27648b8 | 2017-08-31 10:40:29 -0600 | [diff] [blame] | 50 | 'SHA256': 0x10, |
| 51 | 'RSA2048': 0x20, |
| 52 | 'ECDSA224': 0x21, |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 53 | 'ECDSA256': 0x22, |
Fabio Utzig | 19fd79a | 2019-05-08 18:20:39 -0300 | [diff] [blame] | 54 | 'RSA3072': 0x23, |
Fabio Utzig | 8101d1f | 2019-05-09 15:03:22 -0300 | [diff] [blame] | 55 | 'ED25519': 0x24, |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 56 | 'ENCRSA2048': 0x30, |
| 57 | 'ENCKW128': 0x31, |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 58 | 'DEPENDENCY': 0x40 |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 59 | } |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 60 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 61 | TLV_SIZE = 4 |
David Brown | f5b33d8 | 2017-09-01 10:58:27 -0600 | [diff] [blame] | 62 | TLV_INFO_SIZE = 4 |
| 63 | TLV_INFO_MAGIC = 0x6907 |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 64 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 65 | boot_magic = bytes([ |
| 66 | 0x77, 0xc2, 0x95, 0xf3, |
| 67 | 0x60, 0xd2, 0xef, 0x7f, |
| 68 | 0x35, 0x52, 0x50, 0x0f, |
| 69 | 0x2c, 0xb6, 0x79, 0x80, ]) |
| 70 | |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 71 | STRUCT_ENDIAN_DICT = { |
| 72 | 'little': '<', |
| 73 | 'big': '>' |
| 74 | } |
| 75 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 76 | VerifyResult = Enum('VerifyResult', |
| 77 | """ |
| 78 | OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH |
| 79 | INVALID_SIGNATURE |
| 80 | """) |
| 81 | |
| 82 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 83 | class TLV(): |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 84 | def __init__(self, endian): |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 85 | self.buf = bytearray() |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 86 | self.endian = endian |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 87 | |
| 88 | def add(self, kind, payload): |
| 89 | """Add a TLV record. Kind should be a string found in TLV_VALUES above.""" |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 90 | e = STRUCT_ENDIAN_DICT[self.endian] |
| 91 | buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload)) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 92 | self.buf += buf |
| 93 | self.buf += payload |
| 94 | |
| 95 | def get(self): |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 96 | e = STRUCT_ENDIAN_DICT[self.endian] |
| 97 | header = struct.pack(e + 'HH', TLV_INFO_MAGIC, TLV_INFO_SIZE + len(self.buf)) |
David Brown | f5b33d8 | 2017-09-01 10:58:27 -0600 | [diff] [blame] | 98 | return header + bytes(self.buf) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 99 | |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 100 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 101 | class Image(): |
Carles Cufi | 37d052f | 2018-01-30 16:40:10 +0100 | [diff] [blame] | 102 | |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 103 | def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE, |
| 104 | pad_header=False, pad=False, align=1, slot_size=0, |
| 105 | max_sectors=DEFAULT_MAX_SECTORS, overwrite_only=False, |
| 106 | endian="little"): |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 107 | self.version = version or versmod.decode_version("0") |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 108 | self.header_size = header_size |
| 109 | self.pad_header = pad_header |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 110 | self.pad = pad |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 111 | self.align = align |
| 112 | self.slot_size = slot_size |
| 113 | self.max_sectors = max_sectors |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 114 | self.overwrite_only = overwrite_only |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 115 | self.endian = endian |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 116 | self.base_addr = None |
| 117 | self.payload = [] |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 118 | |
| 119 | def __repr__(self): |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 120 | return "<Image version={}, header_size={}, base_addr={}, \ |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 121 | align={}, slot_size={}, max_sectors={}, overwrite_only={}, \ |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 122 | endian={} format={}, payloadlen=0x{:x}>".format( |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 123 | self.version, |
| 124 | self.header_size, |
| 125 | self.base_addr if self.base_addr is not None else "N/A", |
| 126 | self.align, |
| 127 | self.slot_size, |
| 128 | self.max_sectors, |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 129 | self.overwrite_only, |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 130 | self.endian, |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 131 | self.__class__.__name__, |
| 132 | len(self.payload)) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 133 | |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 134 | def load(self, path): |
| 135 | """Load an image from a given file""" |
| 136 | ext = os.path.splitext(path)[1][1:].lower() |
| 137 | if ext == INTEL_HEX_EXT: |
| 138 | ih = IntelHex(path) |
| 139 | self.payload = ih.tobinarray() |
| 140 | self.base_addr = ih.minaddr() |
| 141 | else: |
| 142 | with open(path, 'rb') as f: |
| 143 | self.payload = f.read() |
| 144 | |
| 145 | # Add the image header if needed. |
| 146 | if self.pad_header and self.header_size > 0: |
| 147 | if self.base_addr: |
| 148 | # Adjust base_addr for new header |
| 149 | self.base_addr -= self.header_size |
| 150 | self.payload = (b'\000' * self.header_size) + self.payload |
| 151 | |
| 152 | self.check() |
| 153 | |
| 154 | def save(self, path): |
| 155 | """Save an image from a given file""" |
| 156 | if self.pad: |
| 157 | self.pad_to(self.slot_size) |
| 158 | |
| 159 | ext = os.path.splitext(path)[1][1:].lower() |
| 160 | if ext == INTEL_HEX_EXT: |
| 161 | # input was in binary format, but HEX needs to know the base addr |
| 162 | if self.base_addr is None: |
| 163 | raise Exception("Input file does not provide a base address") |
| 164 | h = IntelHex() |
| 165 | h.frombytes(bytes=self.payload, offset=self.base_addr) |
| 166 | h.tofile(path, 'hex') |
| 167 | else: |
| 168 | with open(path, 'wb') as f: |
| 169 | f.write(self.payload) |
| 170 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 171 | def check(self): |
| 172 | """Perform some sanity checking of the image.""" |
| 173 | # If there is a header requested, make sure that the image |
| 174 | # starts with all zeros. |
| 175 | if self.header_size > 0: |
| 176 | if any(v != 0 for v in self.payload[0:self.header_size]): |
| 177 | raise Exception("Padding requested, but image does not start with zeros") |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 178 | if self.slot_size > 0: |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 179 | tsize = self._trailer_size(self.align, self.max_sectors, |
| 180 | self.overwrite_only) |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 181 | padding = self.slot_size - (len(self.payload) + tsize) |
| 182 | if padding < 0: |
| 183 | msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format( |
| 184 | len(self.payload), tsize, self.slot_size) |
| 185 | raise Exception(msg) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 186 | |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 187 | def create(self, key, enckey, dependencies=None): |
| 188 | if dependencies is None: |
| 189 | dependencies_num = 0 |
| 190 | protected_tlv_size = 0 |
| 191 | else: |
| 192 | # Size of a Dependency TLV = Header ('BBH') + Payload('IBBHI') |
| 193 | # = 16 Bytes |
| 194 | dependencies_num = len(dependencies[DEP_IMAGES_KEY]) |
| 195 | protected_tlv_size = (dependencies_num * 16) + TLV_INFO_SIZE |
| 196 | |
| 197 | self.add_header(enckey, protected_tlv_size) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 198 | |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 199 | tlv = TLV(self.endian) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 200 | |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 201 | if protected_tlv_size != 0: |
| 202 | for i in range(dependencies_num): |
| 203 | e = STRUCT_ENDIAN_DICT[self.endian] |
| 204 | payload = struct.pack( |
David Brown | bd7925e | 2019-07-29 11:11:32 -0600 | [diff] [blame^] | 205 | e + 'B3x'+'BBHI', |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 206 | int(dependencies[DEP_IMAGES_KEY][i]), |
| 207 | dependencies[DEP_VERSIONS_KEY][i].major, |
| 208 | dependencies[DEP_VERSIONS_KEY][i].minor, |
| 209 | dependencies[DEP_VERSIONS_KEY][i].revision, |
| 210 | dependencies[DEP_VERSIONS_KEY][i].build |
| 211 | ) |
| 212 | tlv.add('DEPENDENCY', payload) |
| 213 | # Full TLV size needs to be calculated in advance, because the |
| 214 | # header will be protected as well |
| 215 | tlv_header_size = 4 |
| 216 | payload_digest_size = 32 |
| 217 | keyhash_size = 32 |
| 218 | cipherkey_size = 32 |
| 219 | |
| 220 | full_size = TLV_INFO_SIZE + len(tlv.buf) + tlv_header_size \ |
| 221 | + payload_digest_size |
| 222 | if key is not None: |
| 223 | full_size += tlv_header_size + keyhash_size \ |
| 224 | + tlv_header_size + key.sig_len() |
| 225 | if enckey is not None: |
| 226 | full_size += tlv_header_size + cipherkey_size |
| 227 | tlv_header = struct.pack(e + 'HH', TLV_INFO_MAGIC, full_size) |
| 228 | self.payload += tlv_header + bytes(tlv.buf) |
| 229 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 230 | # Note that ecdsa wants to do the hashing itself, which means |
| 231 | # we get to hash it twice. |
| 232 | sha = hashlib.sha256() |
| 233 | sha.update(self.payload) |
| 234 | digest = sha.digest() |
| 235 | |
| 236 | tlv.add('SHA256', digest) |
| 237 | |
David Brown | 0f0c6a8 | 2017-06-08 09:26:24 -0600 | [diff] [blame] | 238 | if key is not None: |
David Brown | 43cda33 | 2017-09-01 09:53:23 -0600 | [diff] [blame] | 239 | pub = key.get_public_bytes() |
| 240 | sha = hashlib.sha256() |
| 241 | sha.update(pub) |
| 242 | pubbytes = sha.digest() |
| 243 | tlv.add('KEYHASH', pubbytes) |
| 244 | |
Fabio Utzig | 8101d1f | 2019-05-09 15:03:22 -0300 | [diff] [blame] | 245 | # `sign` expects the full image payload (sha256 done internally), |
| 246 | # while `sign_digest` expects only the digest of the payload |
| 247 | |
| 248 | if hasattr(key, 'sign'): |
| 249 | sig = key.sign(bytes(self.payload)) |
| 250 | else: |
| 251 | sig = key.sign_digest(digest) |
David Brown | 0f0c6a8 | 2017-06-08 09:26:24 -0600 | [diff] [blame] | 252 | tlv.add(key.sig_tlv(), sig) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 253 | |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 254 | if enckey is not None: |
| 255 | plainkey = os.urandom(16) |
| 256 | cipherkey = enckey._get_public().encrypt( |
| 257 | plainkey, padding.OAEP( |
| 258 | mgf=padding.MGF1(algorithm=hashes.SHA256()), |
| 259 | algorithm=hashes.SHA256(), |
| 260 | label=None)) |
| 261 | tlv.add('ENCRSA2048', cipherkey) |
| 262 | |
| 263 | nonce = bytes([0] * 16) |
| 264 | cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce), |
| 265 | backend=default_backend()) |
| 266 | encryptor = cipher.encryptor() |
| 267 | img = bytes(self.payload[self.header_size:]) |
| 268 | self.payload[self.header_size:] = encryptor.update(img) + \ |
| 269 | encryptor.finalize() |
| 270 | |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 271 | self.payload += tlv.get()[protected_tlv_size:] |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 272 | |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 273 | def add_header(self, enckey, protected_tlv_size): |
Fabio Utzig | cd28406 | 2018-11-30 11:05:45 -0200 | [diff] [blame] | 274 | """Install the image header.""" |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 275 | |
David Brown | 0f0c6a8 | 2017-06-08 09:26:24 -0600 | [diff] [blame] | 276 | flags = 0 |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 277 | if enckey is not None: |
| 278 | flags |= IMAGE_F['ENCRYPTED'] |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 279 | |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 280 | e = STRUCT_ENDIAN_DICT[self.endian] |
| 281 | fmt = (e + |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 282 | # type ImageHdr struct { |
| 283 | 'I' + # Magic uint32 |
| 284 | 'I' + # LoadAddr uint32 |
| 285 | 'H' + # HdrSz uint16 |
| 286 | 'H' + # PTLVSz uint16 |
| 287 | 'I' + # ImgSz uint32 |
| 288 | 'I' + # Flags uint32 |
| 289 | 'BBHI' + # Vers ImageVersion |
| 290 | 'I' # Pad1 uint32 |
| 291 | ) # } |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 292 | assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE |
| 293 | header = struct.pack(fmt, |
| 294 | IMAGE_MAGIC, |
Fabio Utzig | b5b59f1 | 2018-05-10 07:27:08 -0300 | [diff] [blame] | 295 | 0, # LoadAddr |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 296 | self.header_size, |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 297 | protected_tlv_size, # TLV Info header + Dependency TLVs |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 298 | len(self.payload) - self.header_size, # ImageSz |
| 299 | flags, # Flags |
| 300 | self.version.major, |
| 301 | self.version.minor or 0, |
| 302 | self.version.revision or 0, |
| 303 | self.version.build or 0, |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 304 | 0) # Pad1 |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 305 | self.payload = bytearray(self.payload) |
| 306 | self.payload[:len(header)] = header |
| 307 | |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 308 | def _trailer_size(self, write_size, max_sectors, overwrite_only): |
Fabio Utzig | 519285f | 2018-06-04 11:11:53 -0300 | [diff] [blame] | 309 | # NOTE: should already be checked by the argument parser |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 310 | if overwrite_only: |
| 311 | return 8 * 2 + 16 |
| 312 | else: |
| 313 | if write_size not in set([1, 2, 4, 8]): |
| 314 | raise Exception("Invalid alignment: {}".format(write_size)) |
| 315 | m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors |
| 316 | return m * 3 * write_size + 8 * 2 + 16 |
Fabio Utzig | 519285f | 2018-06-04 11:11:53 -0300 | [diff] [blame] | 317 | |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 318 | def pad_to(self, size): |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 319 | """Pad the image to the given size, with the given flash alignment.""" |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 320 | tsize = self._trailer_size(self.align, self.max_sectors, |
| 321 | self.overwrite_only) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 322 | padding = size - (len(self.payload) + tsize) |
Fabio Utzig | e08f087 | 2017-06-28 18:12:16 -0300 | [diff] [blame] | 323 | pbytes = b'\xff' * padding |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 324 | pbytes += b'\xff' * (tsize - len(boot_magic)) |
Fabio Utzig | e08f087 | 2017-06-28 18:12:16 -0300 | [diff] [blame] | 325 | pbytes += boot_magic |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 326 | self.payload += pbytes |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 327 | |
| 328 | @staticmethod |
| 329 | def verify(imgfile, key): |
| 330 | with open(imgfile, "rb") as f: |
| 331 | b = f.read() |
| 332 | |
| 333 | magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16]) |
| 334 | if magic != IMAGE_MAGIC: |
| 335 | return VerifyResult.INVALID_MAGIC |
| 336 | |
| 337 | tlv_info = b[header_size+img_size:header_size+img_size+TLV_INFO_SIZE] |
| 338 | magic, tlv_tot = struct.unpack('HH', tlv_info) |
| 339 | if magic != TLV_INFO_MAGIC: |
| 340 | return VerifyResult.INVALID_TLV_INFO_MAGIC |
| 341 | |
| 342 | sha = hashlib.sha256() |
| 343 | sha.update(b[:header_size+img_size]) |
| 344 | digest = sha.digest() |
| 345 | |
| 346 | tlv_off = header_size + img_size |
| 347 | tlv_end = tlv_off + tlv_tot |
| 348 | tlv_off += TLV_INFO_SIZE # skip tlv info |
| 349 | while tlv_off < tlv_end: |
| 350 | tlv = b[tlv_off:tlv_off+TLV_SIZE] |
| 351 | tlv_type, _, tlv_len = struct.unpack('BBH', tlv) |
| 352 | if tlv_type == TLV_VALUES["SHA256"]: |
| 353 | off = tlv_off + TLV_SIZE |
| 354 | if digest == b[off:off+tlv_len]: |
| 355 | if key is None: |
| 356 | return VerifyResult.OK |
| 357 | else: |
| 358 | return VerifyResult.INVALID_HASH |
| 359 | elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]: |
| 360 | off = tlv_off + TLV_SIZE |
| 361 | tlv_sig = b[off:off+tlv_len] |
| 362 | payload = b[:header_size+img_size] |
| 363 | try: |
Fabio Utzig | 8101d1f | 2019-05-09 15:03:22 -0300 | [diff] [blame] | 364 | if hasattr(key, 'verify'): |
| 365 | key.verify(tlv_sig, payload) |
| 366 | else: |
| 367 | key.verify_digest(tlv_sig, digest) |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 368 | return VerifyResult.OK |
| 369 | except InvalidSignature: |
| 370 | # continue to next TLV |
| 371 | pass |
| 372 | tlv_off += TLV_SIZE + tlv_len |
| 373 | return VerifyResult.INVALID_SIGNATURE |