Carles Cufi | 37d052f | 2018-01-30 16:40:10 +0100 | [diff] [blame] | 1 | # Copyright 2018 Nordic Semiconductor ASA |
David Vincze | b2a1a48 | 2020-09-18 11:54:30 +0200 | [diff] [blame] | 2 | # Copyright 2017-2020 Linaro Limited |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 3 | # Copyright 2019-2020 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 |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 22 | from .boot_record import create_sw_component_data |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 23 | import click |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 24 | from enum import Enum |
Carles Cufi | 37d052f | 2018-01-30 16:40:10 +0100 | [diff] [blame] | 25 | from intelhex import IntelHex |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 26 | import hashlib |
| 27 | import struct |
Carles Cufi | 37d052f | 2018-01-30 16:40:10 +0100 | [diff] [blame] | 28 | import os.path |
Fabio Utzig | 960b4c5 | 2020-04-02 13:07:12 -0300 | [diff] [blame] | 29 | from .keys import rsa, ecdsa, x25519 |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 30 | from cryptography.hazmat.primitives.asymmetric import ec, padding |
Fabio Utzig | 960b4c5 | 2020-04-02 13:07:12 -0300 | [diff] [blame] | 31 | from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 32 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 33 | from cryptography.hazmat.primitives.kdf.hkdf import HKDF |
| 34 | from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 35 | from cryptography.hazmat.backends import default_backend |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 36 | from cryptography.hazmat.primitives import hashes, hmac |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 37 | from cryptography.exceptions import InvalidSignature |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 38 | |
David Brown | 72e7a51 | 2017-09-01 11:08:23 -0600 | [diff] [blame] | 39 | IMAGE_MAGIC = 0x96f3b83d |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 40 | IMAGE_HEADER_SIZE = 32 |
Carles Cufi | 37d052f | 2018-01-30 16:40:10 +0100 | [diff] [blame] | 41 | BIN_EXT = "bin" |
| 42 | INTEL_HEX_EXT = "hex" |
Fabio Utzig | 519285f | 2018-06-04 11:11:53 -0300 | [diff] [blame] | 43 | DEFAULT_MAX_SECTORS = 128 |
Fabio Utzig | 649d80f | 2019-09-12 10:26:23 -0300 | [diff] [blame] | 44 | MAX_ALIGN = 8 |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 45 | DEP_IMAGES_KEY = "images" |
| 46 | DEP_VERSIONS_KEY = "versions" |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 47 | MAX_SW_TYPE_LENGTH = 12 # Bytes |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 48 | |
| 49 | # Image header flags. |
| 50 | IMAGE_F = { |
| 51 | 'PIC': 0x0000001, |
Dominik Ermel | 50820b1 | 2020-12-14 13:16:46 +0000 | [diff] [blame] | 52 | 'ENCRYPTED': 0x0000004, |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 53 | 'NON_BOOTABLE': 0x0000010, |
David Vincze | 1e0c544 | 2020-04-07 14:12:33 +0200 | [diff] [blame] | 54 | 'RAM_LOAD': 0x0000020, |
Dominik Ermel | 50820b1 | 2020-12-14 13:16:46 +0000 | [diff] [blame] | 55 | 'ROM_FIXED': 0x0000100, |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 56 | } |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 57 | |
| 58 | TLV_VALUES = { |
David Brown | 43cda33 | 2017-09-01 09:53:23 -0600 | [diff] [blame] | 59 | 'KEYHASH': 0x01, |
David Vincze | dde178d | 2020-03-26 20:06:01 +0100 | [diff] [blame] | 60 | 'PUBKEY': 0x02, |
David Brown | 27648b8 | 2017-08-31 10:40:29 -0600 | [diff] [blame] | 61 | 'SHA256': 0x10, |
| 62 | 'RSA2048': 0x20, |
| 63 | 'ECDSA224': 0x21, |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 64 | 'ECDSA256': 0x22, |
Fabio Utzig | 19fd79a | 2019-05-08 18:20:39 -0300 | [diff] [blame] | 65 | 'RSA3072': 0x23, |
Fabio Utzig | 8101d1f | 2019-05-09 15:03:22 -0300 | [diff] [blame] | 66 | 'ED25519': 0x24, |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 67 | 'ENCRSA2048': 0x30, |
| 68 | 'ENCKW128': 0x31, |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 69 | 'ENCEC256': 0x32, |
Fabio Utzig | 960b4c5 | 2020-04-02 13:07:12 -0300 | [diff] [blame] | 70 | 'ENCX25519': 0x33, |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 71 | 'DEPENDENCY': 0x40, |
| 72 | 'SEC_CNT': 0x50, |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 73 | 'BOOT_RECORD': 0x60, |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 74 | } |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 75 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 76 | TLV_SIZE = 4 |
David Brown | f5b33d8 | 2017-09-01 10:58:27 -0600 | [diff] [blame] | 77 | TLV_INFO_SIZE = 4 |
| 78 | TLV_INFO_MAGIC = 0x6907 |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 79 | TLV_PROT_INFO_MAGIC = 0x6908 |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 80 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 81 | boot_magic = bytes([ |
| 82 | 0x77, 0xc2, 0x95, 0xf3, |
| 83 | 0x60, 0xd2, 0xef, 0x7f, |
| 84 | 0x35, 0x52, 0x50, 0x0f, |
| 85 | 0x2c, 0xb6, 0x79, 0x80, ]) |
| 86 | |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 87 | STRUCT_ENDIAN_DICT = { |
| 88 | 'little': '<', |
| 89 | 'big': '>' |
| 90 | } |
| 91 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 92 | VerifyResult = Enum('VerifyResult', |
| 93 | """ |
| 94 | OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH |
| 95 | INVALID_SIGNATURE |
| 96 | """) |
| 97 | |
| 98 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 99 | class TLV(): |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 100 | def __init__(self, endian, magic=TLV_INFO_MAGIC): |
| 101 | self.magic = magic |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 102 | self.buf = bytearray() |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 103 | self.endian = endian |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 104 | |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 105 | def __len__(self): |
| 106 | return TLV_INFO_SIZE + len(self.buf) |
| 107 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 108 | def add(self, kind, payload): |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 109 | """ |
| 110 | Add a TLV record. Kind should be a string found in TLV_VALUES above. |
| 111 | """ |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 112 | e = STRUCT_ENDIAN_DICT[self.endian] |
Ihor Slabkyy | 24d9373 | 2020-03-10 15:33:57 +0200 | [diff] [blame] | 113 | if isinstance(kind, int): |
| 114 | buf = struct.pack(e + 'BBH', kind, 0, len(payload)) |
| 115 | else: |
| 116 | buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload)) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 117 | self.buf += buf |
| 118 | self.buf += payload |
| 119 | |
| 120 | def get(self): |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 121 | if len(self.buf) == 0: |
| 122 | return bytes() |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 123 | e = STRUCT_ENDIAN_DICT[self.endian] |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 124 | header = struct.pack(e + 'HH', self.magic, len(self)) |
David Brown | f5b33d8 | 2017-09-01 10:58:27 -0600 | [diff] [blame] | 125 | return header + bytes(self.buf) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 126 | |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 127 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 128 | class Image(): |
Carles Cufi | 37d052f | 2018-01-30 16:40:10 +0100 | [diff] [blame] | 129 | |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 130 | def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE, |
Henrik Brix Andersen | 0ce958e | 2020-03-11 14:04:11 +0100 | [diff] [blame] | 131 | pad_header=False, pad=False, confirm=False, align=1, |
| 132 | slot_size=0, max_sectors=DEFAULT_MAX_SECTORS, |
| 133 | overwrite_only=False, endian="little", load_addr=0, |
Dominik Ermel | 50820b1 | 2020-12-14 13:16:46 +0000 | [diff] [blame] | 134 | rom_fixed=None, erased_val=None, save_enctlv=False, |
| 135 | security_counter=None): |
| 136 | |
| 137 | if load_addr and rom_fixed: |
| 138 | raise click.UsageError("Can not set rom_fixed and load_addr at the same time") |
| 139 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 140 | self.version = version or versmod.decode_version("0") |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 141 | self.header_size = header_size |
| 142 | self.pad_header = pad_header |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 143 | self.pad = pad |
Henrik Brix Andersen | 0ce958e | 2020-03-11 14:04:11 +0100 | [diff] [blame] | 144 | self.confirm = confirm |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 145 | self.align = align |
| 146 | self.slot_size = slot_size |
| 147 | self.max_sectors = max_sectors |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 148 | self.overwrite_only = overwrite_only |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 149 | self.endian = endian |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 150 | self.base_addr = None |
Håkon Øye Amundsen | df8c891 | 2019-08-26 12:15:28 +0000 | [diff] [blame] | 151 | self.load_addr = 0 if load_addr is None else load_addr |
Dominik Ermel | 50820b1 | 2020-12-14 13:16:46 +0000 | [diff] [blame] | 152 | self.rom_fixed = rom_fixed |
Fabio Utzig | cb08073 | 2020-02-07 12:01:39 -0300 | [diff] [blame] | 153 | self.erased_val = 0xff if erased_val is None else int(erased_val, 0) |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 154 | self.payload = [] |
Fabio Utzig | 649d80f | 2019-09-12 10:26:23 -0300 | [diff] [blame] | 155 | self.enckey = None |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 156 | self.save_enctlv = save_enctlv |
| 157 | self.enctlv_len = 0 |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 158 | |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 159 | if security_counter == 'auto': |
| 160 | # Security counter has not been explicitly provided, |
| 161 | # generate it from the version number |
| 162 | self.security_counter = ((self.version.major << 24) |
| 163 | + (self.version.minor << 16) |
| 164 | + self.version.revision) |
| 165 | else: |
| 166 | self.security_counter = security_counter |
| 167 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 168 | def __repr__(self): |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 169 | return "<Image version={}, header_size={}, security_counter={}, \ |
| 170 | base_addr={}, load_addr={}, align={}, slot_size={}, \ |
| 171 | max_sectors={}, overwrite_only={}, endian={} format={}, \ |
| 172 | payloadlen=0x{:x}>".format( |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 173 | self.version, |
| 174 | self.header_size, |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 175 | self.security_counter, |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 176 | self.base_addr if self.base_addr is not None else "N/A", |
Håkon Øye Amundsen | df8c891 | 2019-08-26 12:15:28 +0000 | [diff] [blame] | 177 | self.load_addr, |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 178 | self.align, |
| 179 | self.slot_size, |
| 180 | self.max_sectors, |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 181 | self.overwrite_only, |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 182 | self.endian, |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 183 | self.__class__.__name__, |
| 184 | len(self.payload)) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 185 | |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 186 | def load(self, path): |
| 187 | """Load an image from a given file""" |
| 188 | ext = os.path.splitext(path)[1][1:].lower() |
Fabio Utzig | 1f50892 | 2020-01-15 11:37:51 -0300 | [diff] [blame] | 189 | try: |
| 190 | if ext == INTEL_HEX_EXT: |
| 191 | ih = IntelHex(path) |
| 192 | self.payload = ih.tobinarray() |
| 193 | self.base_addr = ih.minaddr() |
| 194 | else: |
| 195 | with open(path, 'rb') as f: |
| 196 | self.payload = f.read() |
| 197 | except FileNotFoundError: |
| 198 | raise click.UsageError("Input file not found") |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 199 | |
| 200 | # Add the image header if needed. |
| 201 | if self.pad_header and self.header_size > 0: |
| 202 | if self.base_addr: |
| 203 | # Adjust base_addr for new header |
| 204 | self.base_addr -= self.header_size |
Fabio Utzig | 9117fde | 2019-10-17 11:11:46 -0300 | [diff] [blame] | 205 | self.payload = bytes([self.erased_val] * self.header_size) + \ |
| 206 | self.payload |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 207 | |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 208 | self.check_header() |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 209 | |
Fabio Utzig | edbabcf | 2019-10-11 13:03:37 -0300 | [diff] [blame] | 210 | def save(self, path, hex_addr=None): |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 211 | """Save an image from a given file""" |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 212 | ext = os.path.splitext(path)[1][1:].lower() |
| 213 | if ext == INTEL_HEX_EXT: |
| 214 | # input was in binary format, but HEX needs to know the base addr |
Fabio Utzig | edbabcf | 2019-10-11 13:03:37 -0300 | [diff] [blame] | 215 | if self.base_addr is None and hex_addr is None: |
Fabio Utzig | 1f50892 | 2020-01-15 11:37:51 -0300 | [diff] [blame] | 216 | raise click.UsageError("No address exists in input file " |
| 217 | "neither was it provided by user") |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 218 | h = IntelHex() |
Fabio Utzig | edbabcf | 2019-10-11 13:03:37 -0300 | [diff] [blame] | 219 | if hex_addr is not None: |
| 220 | self.base_addr = hex_addr |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 221 | h.frombytes(bytes=self.payload, offset=self.base_addr) |
Fabio Utzig | edbabcf | 2019-10-11 13:03:37 -0300 | [diff] [blame] | 222 | if self.pad: |
Fabio Utzig | 2269f47 | 2019-10-17 11:14:33 -0300 | [diff] [blame] | 223 | trailer_size = self._trailer_size(self.align, self.max_sectors, |
| 224 | self.overwrite_only, |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 225 | self.enckey, |
| 226 | self.save_enctlv, |
| 227 | self.enctlv_len) |
Fabio Utzig | 2269f47 | 2019-10-17 11:14:33 -0300 | [diff] [blame] | 228 | trailer_addr = (self.base_addr + self.slot_size) - trailer_size |
Roman Okhrimenko | 42b3239 | 2020-09-18 15:20:45 +0300 | [diff] [blame] | 229 | padding = bytearray([self.erased_val] * |
| 230 | (trailer_size - len(boot_magic))) |
| 231 | if self.confirm and not self.overwrite_only: |
| 232 | padding[-MAX_ALIGN] = 0x01 # image_ok = 0x01 |
| 233 | padding += boot_magic |
| 234 | h.puts(trailer_addr, bytes(padding)) |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 235 | h.tofile(path, 'hex') |
| 236 | else: |
Fabio Utzig | edbabcf | 2019-10-11 13:03:37 -0300 | [diff] [blame] | 237 | if self.pad: |
| 238 | self.pad_to(self.slot_size) |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 239 | with open(path, 'wb') as f: |
| 240 | f.write(self.payload) |
| 241 | |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 242 | def check_header(self): |
Fabio Utzig | f5556c3 | 2019-10-23 11:00:27 -0300 | [diff] [blame] | 243 | if self.header_size > 0 and not self.pad_header: |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 244 | if any(v != 0 for v in self.payload[0:self.header_size]): |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 245 | raise click.UsageError("Header padding was not requested and " |
| 246 | "image does not start with zeros") |
| 247 | |
| 248 | def check_trailer(self): |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 249 | if self.slot_size > 0: |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 250 | tsize = self._trailer_size(self.align, self.max_sectors, |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 251 | self.overwrite_only, self.enckey, |
| 252 | self.save_enctlv, self.enctlv_len) |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 253 | padding = self.slot_size - (len(self.payload) + tsize) |
| 254 | if padding < 0: |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 255 | msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds " \ |
| 256 | "requested size 0x{:x}".format( |
| 257 | len(self.payload), tsize, self.slot_size) |
| 258 | raise click.UsageError(msg) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 259 | |
Fabio Utzig | 960b4c5 | 2020-04-02 13:07:12 -0300 | [diff] [blame] | 260 | def ecies_hkdf(self, enckey, plainkey): |
| 261 | if isinstance(enckey, ecdsa.ECDSA256P1Public): |
| 262 | newpk = ec.generate_private_key(ec.SECP256R1(), default_backend()) |
| 263 | shared = newpk.exchange(ec.ECDH(), enckey._get_public()) |
| 264 | else: |
| 265 | newpk = X25519PrivateKey.generate() |
| 266 | shared = newpk.exchange(enckey._get_public()) |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 267 | derived_key = HKDF( |
| 268 | algorithm=hashes.SHA256(), length=48, salt=None, |
| 269 | info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared) |
| 270 | encryptor = Cipher(algorithms.AES(derived_key[:16]), |
| 271 | modes.CTR(bytes([0] * 16)), |
| 272 | backend=default_backend()).encryptor() |
| 273 | cipherkey = encryptor.update(plainkey) + encryptor.finalize() |
| 274 | mac = hmac.HMAC(derived_key[16:], hashes.SHA256(), |
| 275 | backend=default_backend()) |
| 276 | mac.update(cipherkey) |
| 277 | ciphermac = mac.finalize() |
Fabio Utzig | 960b4c5 | 2020-04-02 13:07:12 -0300 | [diff] [blame] | 278 | if isinstance(enckey, ecdsa.ECDSA256P1Public): |
| 279 | pubk = newpk.public_key().public_bytes( |
| 280 | encoding=Encoding.X962, |
| 281 | format=PublicFormat.UncompressedPoint) |
| 282 | else: |
| 283 | pubk = newpk.public_key().public_bytes( |
| 284 | encoding=Encoding.Raw, |
| 285 | format=PublicFormat.Raw) |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 286 | return cipherkey, ciphermac, pubk |
| 287 | |
David Vincze | dde178d | 2020-03-26 20:06:01 +0100 | [diff] [blame] | 288 | def create(self, key, public_key_format, enckey, dependencies=None, |
Ihor Slabkyy | 24d9373 | 2020-03-10 15:33:57 +0200 | [diff] [blame] | 289 | sw_type=None, custom_tlvs=None): |
Fabio Utzig | 649d80f | 2019-09-12 10:26:23 -0300 | [diff] [blame] | 290 | self.enckey = enckey |
| 291 | |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 292 | # Calculate the hash of the public key |
| 293 | if key is not None: |
| 294 | pub = key.get_public_bytes() |
| 295 | sha = hashlib.sha256() |
| 296 | sha.update(pub) |
| 297 | pubbytes = sha.digest() |
| 298 | else: |
| 299 | pubbytes = bytes(hashlib.sha256().digest_size) |
| 300 | |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 301 | protected_tlv_size = 0 |
| 302 | |
| 303 | if self.security_counter is not None: |
| 304 | # Size of the security counter TLV: header ('HH') + payload ('I') |
| 305 | # = 4 + 4 = 8 Bytes |
| 306 | protected_tlv_size += TLV_SIZE + 4 |
| 307 | |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 308 | if sw_type is not None: |
| 309 | if len(sw_type) > MAX_SW_TYPE_LENGTH: |
| 310 | msg = "'{}' is too long ({} characters) for sw_type. Its " \ |
| 311 | "maximum allowed length is 12 characters.".format( |
| 312 | sw_type, len(sw_type)) |
| 313 | raise click.UsageError(msg) |
| 314 | |
| 315 | image_version = (str(self.version.major) + '.' |
| 316 | + str(self.version.minor) + '.' |
| 317 | + str(self.version.revision)) |
| 318 | |
| 319 | # The image hash is computed over the image header, the image |
| 320 | # itself and the protected TLV area. However, the boot record TLV |
| 321 | # (which is part of the protected area) should contain this hash |
| 322 | # before it is even calculated. For this reason the script fills |
| 323 | # this field with zeros and the bootloader will insert the right |
| 324 | # value later. |
| 325 | digest = bytes(hashlib.sha256().digest_size) |
| 326 | |
| 327 | # Create CBOR encoded boot record |
| 328 | boot_record = create_sw_component_data(sw_type, image_version, |
| 329 | "SHA256", digest, |
| 330 | pubbytes) |
| 331 | |
| 332 | protected_tlv_size += TLV_SIZE + len(boot_record) |
| 333 | |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 334 | if dependencies is not None: |
| 335 | # Size of a Dependency TLV = Header ('HH') + Payload('IBBHI') |
| 336 | # = 4 + 12 = 16 Bytes |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 337 | dependencies_num = len(dependencies[DEP_IMAGES_KEY]) |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 338 | protected_tlv_size += (dependencies_num * 16) |
| 339 | |
David Vincze | b2a1a48 | 2020-09-18 11:54:30 +0200 | [diff] [blame] | 340 | if custom_tlvs is not None: |
Ihor Slabkyy | 24d9373 | 2020-03-10 15:33:57 +0200 | [diff] [blame] | 341 | for value in custom_tlvs.values(): |
| 342 | protected_tlv_size += TLV_SIZE + len(value) |
| 343 | |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 344 | if protected_tlv_size != 0: |
| 345 | # Add the size of the TLV info header |
| 346 | protected_tlv_size += TLV_INFO_SIZE |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 347 | |
Ihor Slabkyy | 24d9373 | 2020-03-10 15:33:57 +0200 | [diff] [blame] | 348 | # At this point the image is already on the payload |
| 349 | # |
| 350 | # This adds the padding if image is not aligned to the 16 Bytes |
| 351 | # in encrypted mode |
| 352 | if self.enckey is not None: |
| 353 | pad_len = len(self.payload) % 16 |
| 354 | if pad_len > 0: |
| 355 | self.payload += bytes(16 - pad_len) |
| 356 | |
| 357 | # This adds the header to the payload as well |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 358 | self.add_header(enckey, protected_tlv_size) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 359 | |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 360 | prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 361 | |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 362 | # Protected TLVs must be added first, because they are also included |
| 363 | # in the hash calculation |
| 364 | protected_tlv_off = None |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 365 | if protected_tlv_size != 0: |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 366 | |
| 367 | e = STRUCT_ENDIAN_DICT[self.endian] |
| 368 | |
| 369 | if self.security_counter is not None: |
| 370 | payload = struct.pack(e + 'I', self.security_counter) |
| 371 | prot_tlv.add('SEC_CNT', payload) |
| 372 | |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 373 | if sw_type is not None: |
| 374 | prot_tlv.add('BOOT_RECORD', boot_record) |
| 375 | |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 376 | if dependencies is not None: |
| 377 | for i in range(dependencies_num): |
| 378 | payload = struct.pack( |
| 379 | e + 'B3x'+'BBHI', |
| 380 | int(dependencies[DEP_IMAGES_KEY][i]), |
| 381 | dependencies[DEP_VERSIONS_KEY][i].major, |
| 382 | dependencies[DEP_VERSIONS_KEY][i].minor, |
| 383 | dependencies[DEP_VERSIONS_KEY][i].revision, |
| 384 | dependencies[DEP_VERSIONS_KEY][i].build |
| 385 | ) |
| 386 | prot_tlv.add('DEPENDENCY', payload) |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 387 | |
David Vincze | b2a1a48 | 2020-09-18 11:54:30 +0200 | [diff] [blame] | 388 | if custom_tlvs is not None: |
| 389 | for tag, value in custom_tlvs.items(): |
| 390 | prot_tlv.add(tag, value) |
Ihor Slabkyy | 24d9373 | 2020-03-10 15:33:57 +0200 | [diff] [blame] | 391 | |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 392 | protected_tlv_off = len(self.payload) |
| 393 | self.payload += prot_tlv.get() |
| 394 | |
| 395 | tlv = TLV(self.endian) |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 396 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 397 | # Note that ecdsa wants to do the hashing itself, which means |
| 398 | # we get to hash it twice. |
| 399 | sha = hashlib.sha256() |
| 400 | sha.update(self.payload) |
| 401 | digest = sha.digest() |
| 402 | |
| 403 | tlv.add('SHA256', digest) |
| 404 | |
David Brown | 0f0c6a8 | 2017-06-08 09:26:24 -0600 | [diff] [blame] | 405 | if key is not None: |
David Vincze | dde178d | 2020-03-26 20:06:01 +0100 | [diff] [blame] | 406 | if public_key_format == 'hash': |
| 407 | tlv.add('KEYHASH', pubbytes) |
| 408 | else: |
| 409 | tlv.add('PUBKEY', pub) |
David Brown | 43cda33 | 2017-09-01 09:53:23 -0600 | [diff] [blame] | 410 | |
Fabio Utzig | 8101d1f | 2019-05-09 15:03:22 -0300 | [diff] [blame] | 411 | # `sign` expects the full image payload (sha256 done internally), |
| 412 | # while `sign_digest` expects only the digest of the payload |
| 413 | |
| 414 | if hasattr(key, 'sign'): |
| 415 | sig = key.sign(bytes(self.payload)) |
| 416 | else: |
| 417 | sig = key.sign_digest(digest) |
David Brown | 0f0c6a8 | 2017-06-08 09:26:24 -0600 | [diff] [blame] | 418 | tlv.add(key.sig_tlv(), sig) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 419 | |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 420 | # At this point the image was hashed + signed, we can remove the |
| 421 | # protected TLVs from the payload (will be re-added later) |
| 422 | if protected_tlv_off is not None: |
| 423 | self.payload = self.payload[:protected_tlv_off] |
| 424 | |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 425 | if enckey is not None: |
| 426 | plainkey = os.urandom(16) |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 427 | |
| 428 | if isinstance(enckey, rsa.RSAPublic): |
| 429 | cipherkey = enckey._get_public().encrypt( |
| 430 | plainkey, padding.OAEP( |
| 431 | mgf=padding.MGF1(algorithm=hashes.SHA256()), |
| 432 | algorithm=hashes.SHA256(), |
| 433 | label=None)) |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 434 | self.enctlv_len = len(cipherkey) |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 435 | tlv.add('ENCRSA2048', cipherkey) |
Fabio Utzig | 960b4c5 | 2020-04-02 13:07:12 -0300 | [diff] [blame] | 436 | elif isinstance(enckey, (ecdsa.ECDSA256P1Public, |
| 437 | x25519.X25519Public)): |
| 438 | cipherkey, mac, pubk = self.ecies_hkdf(enckey, plainkey) |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 439 | enctlv = pubk + mac + cipherkey |
| 440 | self.enctlv_len = len(enctlv) |
Fabio Utzig | 960b4c5 | 2020-04-02 13:07:12 -0300 | [diff] [blame] | 441 | if isinstance(enckey, ecdsa.ECDSA256P1Public): |
| 442 | tlv.add('ENCEC256', enctlv) |
| 443 | else: |
| 444 | tlv.add('ENCX25519', enctlv) |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 445 | |
| 446 | nonce = bytes([0] * 16) |
| 447 | cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce), |
| 448 | backend=default_backend()) |
| 449 | encryptor = cipher.encryptor() |
| 450 | img = bytes(self.payload[self.header_size:]) |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 451 | self.payload[self.header_size:] = \ |
| 452 | encryptor.update(img) + encryptor.finalize() |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 453 | |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 454 | self.payload += prot_tlv.get() |
| 455 | self.payload += tlv.get() |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 456 | |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 457 | self.check_trailer() |
| 458 | |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 459 | def add_header(self, enckey, protected_tlv_size): |
Fabio Utzig | cd28406 | 2018-11-30 11:05:45 -0200 | [diff] [blame] | 460 | """Install the image header.""" |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 461 | |
David Brown | 0f0c6a8 | 2017-06-08 09:26:24 -0600 | [diff] [blame] | 462 | flags = 0 |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 463 | if enckey is not None: |
| 464 | flags |= IMAGE_F['ENCRYPTED'] |
David Vincze | 1e0c544 | 2020-04-07 14:12:33 +0200 | [diff] [blame] | 465 | if self.load_addr != 0: |
| 466 | # Indicates that this image should be loaded into RAM |
| 467 | # instead of run directly from flash. |
| 468 | flags |= IMAGE_F['RAM_LOAD'] |
Dominik Ermel | 50820b1 | 2020-12-14 13:16:46 +0000 | [diff] [blame] | 469 | if self.rom_fixed: |
| 470 | flags |= IMAGE_F['ROM_FIXED'] |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 471 | |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 472 | e = STRUCT_ENDIAN_DICT[self.endian] |
| 473 | fmt = (e + |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 474 | # type ImageHdr struct { |
| 475 | 'I' + # Magic uint32 |
| 476 | 'I' + # LoadAddr uint32 |
| 477 | 'H' + # HdrSz uint16 |
| 478 | 'H' + # PTLVSz uint16 |
| 479 | 'I' + # ImgSz uint32 |
| 480 | 'I' + # Flags uint32 |
| 481 | 'BBHI' + # Vers ImageVersion |
| 482 | 'I' # Pad1 uint32 |
| 483 | ) # } |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 484 | assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE |
| 485 | header = struct.pack(fmt, |
| 486 | IMAGE_MAGIC, |
Dominik Ermel | 50820b1 | 2020-12-14 13:16:46 +0000 | [diff] [blame] | 487 | self.rom_fixed or self.load_addr, |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 488 | self.header_size, |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 489 | protected_tlv_size, # TLV Info header + Protected TLVs |
| 490 | len(self.payload) - self.header_size, # ImageSz |
| 491 | flags, |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 492 | self.version.major, |
| 493 | self.version.minor or 0, |
| 494 | self.version.revision or 0, |
| 495 | self.version.build or 0, |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 496 | 0) # Pad1 |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 497 | self.payload = bytearray(self.payload) |
| 498 | self.payload[:len(header)] = header |
| 499 | |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 500 | def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey, |
| 501 | save_enctlv, enctlv_len): |
Fabio Utzig | 519285f | 2018-06-04 11:11:53 -0300 | [diff] [blame] | 502 | # NOTE: should already be checked by the argument parser |
Fabio Utzig | 649d80f | 2019-09-12 10:26:23 -0300 | [diff] [blame] | 503 | magic_size = 16 |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 504 | if overwrite_only: |
Fabio Utzig | 649d80f | 2019-09-12 10:26:23 -0300 | [diff] [blame] | 505 | return MAX_ALIGN * 2 + magic_size |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 506 | else: |
| 507 | if write_size not in set([1, 2, 4, 8]): |
Fabio Utzig | 1f50892 | 2020-01-15 11:37:51 -0300 | [diff] [blame] | 508 | raise click.BadParameter("Invalid alignment: {}".format( |
| 509 | write_size)) |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 510 | m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors |
Fabio Utzig | 649d80f | 2019-09-12 10:26:23 -0300 | [diff] [blame] | 511 | trailer = m * 3 * write_size # status area |
| 512 | if enckey is not None: |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 513 | if save_enctlv: |
| 514 | # TLV saved by the bootloader is aligned |
| 515 | keylen = (int((enctlv_len - 1) / MAX_ALIGN) + 1) * MAX_ALIGN |
| 516 | else: |
| 517 | keylen = 16 |
| 518 | trailer += keylen * 2 # encryption keys |
Fabio Utzig | 8828280 | 2019-10-17 11:17:18 -0300 | [diff] [blame] | 519 | trailer += MAX_ALIGN * 4 # image_ok/copy_done/swap_info/swap_size |
Fabio Utzig | 649d80f | 2019-09-12 10:26:23 -0300 | [diff] [blame] | 520 | trailer += magic_size |
| 521 | return trailer |
Fabio Utzig | 519285f | 2018-06-04 11:11:53 -0300 | [diff] [blame] | 522 | |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 523 | def pad_to(self, size): |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 524 | """Pad the image to the given size, with the given flash alignment.""" |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 525 | tsize = self._trailer_size(self.align, self.max_sectors, |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 526 | self.overwrite_only, self.enckey, |
| 527 | self.save_enctlv, self.enctlv_len) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 528 | padding = size - (len(self.payload) + tsize) |
Henrik Brix Andersen | 0ce958e | 2020-03-11 14:04:11 +0100 | [diff] [blame] | 529 | pbytes = bytearray([self.erased_val] * padding) |
| 530 | pbytes += bytearray([self.erased_val] * (tsize - len(boot_magic))) |
| 531 | if self.confirm and not self.overwrite_only: |
| 532 | pbytes[-MAX_ALIGN] = 0x01 # image_ok = 0x01 |
Fabio Utzig | e08f087 | 2017-06-28 18:12:16 -0300 | [diff] [blame] | 533 | pbytes += boot_magic |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 534 | self.payload += pbytes |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 535 | |
| 536 | @staticmethod |
| 537 | def verify(imgfile, key): |
| 538 | with open(imgfile, "rb") as f: |
| 539 | b = f.read() |
| 540 | |
| 541 | magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16]) |
Marek Pieta | e955510 | 2019-08-08 16:08:16 +0200 | [diff] [blame] | 542 | version = struct.unpack('BBHI', b[20:28]) |
| 543 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 544 | if magic != IMAGE_MAGIC: |
Casper Meijn | 2a01f3f | 2020-08-22 13:51:40 +0200 | [diff] [blame] | 545 | return VerifyResult.INVALID_MAGIC, None, None |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 546 | |
| 547 | tlv_info = b[header_size+img_size:header_size+img_size+TLV_INFO_SIZE] |
| 548 | magic, tlv_tot = struct.unpack('HH', tlv_info) |
| 549 | if magic != TLV_INFO_MAGIC: |
Casper Meijn | 2a01f3f | 2020-08-22 13:51:40 +0200 | [diff] [blame] | 550 | return VerifyResult.INVALID_TLV_INFO_MAGIC, None, None |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 551 | |
| 552 | sha = hashlib.sha256() |
| 553 | sha.update(b[:header_size+img_size]) |
| 554 | digest = sha.digest() |
| 555 | |
| 556 | tlv_off = header_size + img_size |
| 557 | tlv_end = tlv_off + tlv_tot |
| 558 | tlv_off += TLV_INFO_SIZE # skip tlv info |
| 559 | while tlv_off < tlv_end: |
| 560 | tlv = b[tlv_off:tlv_off+TLV_SIZE] |
| 561 | tlv_type, _, tlv_len = struct.unpack('BBH', tlv) |
| 562 | if tlv_type == TLV_VALUES["SHA256"]: |
| 563 | off = tlv_off + TLV_SIZE |
| 564 | if digest == b[off:off+tlv_len]: |
| 565 | if key is None: |
Casper Meijn | 2a01f3f | 2020-08-22 13:51:40 +0200 | [diff] [blame] | 566 | return VerifyResult.OK, version, digest |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 567 | else: |
Casper Meijn | 2a01f3f | 2020-08-22 13:51:40 +0200 | [diff] [blame] | 568 | return VerifyResult.INVALID_HASH, None, None |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 569 | elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]: |
| 570 | off = tlv_off + TLV_SIZE |
| 571 | tlv_sig = b[off:off+tlv_len] |
| 572 | payload = b[:header_size+img_size] |
| 573 | try: |
Fabio Utzig | 8101d1f | 2019-05-09 15:03:22 -0300 | [diff] [blame] | 574 | if hasattr(key, 'verify'): |
| 575 | key.verify(tlv_sig, payload) |
| 576 | else: |
| 577 | key.verify_digest(tlv_sig, digest) |
Casper Meijn | 2a01f3f | 2020-08-22 13:51:40 +0200 | [diff] [blame] | 578 | return VerifyResult.OK, version, digest |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 579 | except InvalidSignature: |
| 580 | # continue to next TLV |
| 581 | pass |
| 582 | tlv_off += TLV_SIZE + tlv_len |
Casper Meijn | 2a01f3f | 2020-08-22 13:51:40 +0200 | [diff] [blame] | 583 | return VerifyResult.INVALID_SIGNATURE, None, None |