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 |
Salome Thirot | 0f64197 | 2021-05-14 11:19:55 +0100 | [diff] [blame] | 3 | # Copyright 2019-2021 Arm Limited |
David Brown | 1314bf3 | 2017-12-20 11:10:55 -0700 | [diff] [blame] | 4 | # |
David Brown | 79c4fcf | 2021-01-26 15:04:05 -0700 | [diff] [blame] | 5 | # SPDX-License-Identifier: Apache-2.0 |
| 6 | # |
David Brown | 1314bf3 | 2017-12-20 11:10:55 -0700 | [diff] [blame] | 7 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 8 | # you may not use this file except in compliance with the License. |
| 9 | # You may obtain a copy of the License at |
| 10 | # |
| 11 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | # |
| 13 | # Unless required by applicable law or agreed to in writing, software |
| 14 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 | # See the License for the specific language governing permissions and |
| 17 | # limitations under the License. |
| 18 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 19 | """ |
| 20 | Image signing and management. |
| 21 | """ |
| 22 | |
| 23 | from . import version as versmod |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 24 | from .boot_record import create_sw_component_data |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 25 | import click |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 26 | from enum import Enum |
Carles Cufi | 37d052f | 2018-01-30 16:40:10 +0100 | [diff] [blame] | 27 | from intelhex import IntelHex |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 28 | import hashlib |
| 29 | import struct |
Carles Cufi | 37d052f | 2018-01-30 16:40:10 +0100 | [diff] [blame] | 30 | import os.path |
Fabio Utzig | 960b4c5 | 2020-04-02 13:07:12 -0300 | [diff] [blame] | 31 | from .keys import rsa, ecdsa, x25519 |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 32 | from cryptography.hazmat.primitives.asymmetric import ec, padding |
Fabio Utzig | 960b4c5 | 2020-04-02 13:07:12 -0300 | [diff] [blame] | 33 | from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 34 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 35 | from cryptography.hazmat.primitives.kdf.hkdf import HKDF |
| 36 | from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 37 | from cryptography.hazmat.backends import default_backend |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 38 | from cryptography.hazmat.primitives import hashes, hmac |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 39 | from cryptography.exceptions import InvalidSignature |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 40 | |
David Brown | 72e7a51 | 2017-09-01 11:08:23 -0600 | [diff] [blame] | 41 | IMAGE_MAGIC = 0x96f3b83d |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 42 | IMAGE_HEADER_SIZE = 32 |
Carles Cufi | 37d052f | 2018-01-30 16:40:10 +0100 | [diff] [blame] | 43 | BIN_EXT = "bin" |
| 44 | INTEL_HEX_EXT = "hex" |
Fabio Utzig | 519285f | 2018-06-04 11:11:53 -0300 | [diff] [blame] | 45 | DEFAULT_MAX_SECTORS = 128 |
Kristine Jassmann | 73c38c6 | 2021-02-03 16:56:14 +0000 | [diff] [blame] | 46 | DEFAULT_MAX_ALIGN = 8 |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 47 | DEP_IMAGES_KEY = "images" |
| 48 | DEP_VERSIONS_KEY = "versions" |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 49 | MAX_SW_TYPE_LENGTH = 12 # Bytes |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 50 | |
| 51 | # Image header flags. |
| 52 | IMAGE_F = { |
| 53 | 'PIC': 0x0000001, |
Salome Thirot | 0f64197 | 2021-05-14 11:19:55 +0100 | [diff] [blame] | 54 | 'ENCRYPTED_AES128': 0x0000004, |
| 55 | 'ENCRYPTED_AES256': 0x0000008, |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 56 | 'NON_BOOTABLE': 0x0000010, |
David Vincze | 1e0c544 | 2020-04-07 14:12:33 +0200 | [diff] [blame] | 57 | 'RAM_LOAD': 0x0000020, |
Dominik Ermel | 50820b1 | 2020-12-14 13:16:46 +0000 | [diff] [blame] | 58 | 'ROM_FIXED': 0x0000100, |
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 | |
| 61 | TLV_VALUES = { |
David Brown | 43cda33 | 2017-09-01 09:53:23 -0600 | [diff] [blame] | 62 | 'KEYHASH': 0x01, |
David Vincze | dde178d | 2020-03-26 20:06:01 +0100 | [diff] [blame] | 63 | 'PUBKEY': 0x02, |
David Brown | 27648b8 | 2017-08-31 10:40:29 -0600 | [diff] [blame] | 64 | 'SHA256': 0x10, |
| 65 | 'RSA2048': 0x20, |
| 66 | 'ECDSA224': 0x21, |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 67 | 'ECDSA256': 0x22, |
Fabio Utzig | 19fd79a | 2019-05-08 18:20:39 -0300 | [diff] [blame] | 68 | 'RSA3072': 0x23, |
Fabio Utzig | 8101d1f | 2019-05-09 15:03:22 -0300 | [diff] [blame] | 69 | 'ED25519': 0x24, |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 70 | 'ENCRSA2048': 0x30, |
Salome Thirot | 0f64197 | 2021-05-14 11:19:55 +0100 | [diff] [blame] | 71 | 'ENCKW': 0x31, |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 72 | 'ENCEC256': 0x32, |
Fabio Utzig | 960b4c5 | 2020-04-02 13:07:12 -0300 | [diff] [blame] | 73 | 'ENCX25519': 0x33, |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 74 | 'DEPENDENCY': 0x40, |
| 75 | 'SEC_CNT': 0x50, |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 76 | 'BOOT_RECORD': 0x60, |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 77 | } |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 78 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 79 | TLV_SIZE = 4 |
David Brown | f5b33d8 | 2017-09-01 10:58:27 -0600 | [diff] [blame] | 80 | TLV_INFO_SIZE = 4 |
| 81 | TLV_INFO_MAGIC = 0x6907 |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 82 | TLV_PROT_INFO_MAGIC = 0x6908 |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 83 | |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 84 | STRUCT_ENDIAN_DICT = { |
| 85 | 'little': '<', |
| 86 | 'big': '>' |
| 87 | } |
| 88 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 89 | VerifyResult = Enum('VerifyResult', |
| 90 | """ |
| 91 | OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH |
| 92 | INVALID_SIGNATURE |
| 93 | """) |
| 94 | |
Gustavo Henrique Nihei | cf120ba | 2021-11-22 18:44:11 -0300 | [diff] [blame] | 95 | def align_up(num, align): |
| 96 | assert (align & (align - 1) == 0) and align != 0 |
| 97 | return (num + (align - 1)) & ~(align - 1) |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 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, |
Piotr Mienkowski | b6d5cf3 | 2022-01-31 01:01:11 +0100 | [diff] [blame] | 135 | security_counter=None, max_align=None): |
Dominik Ermel | 50820b1 | 2020-12-14 13:16:46 +0000 | [diff] [blame] | 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 |
Piotr Mienkowski | b6d5cf3 | 2022-01-31 01:01:11 +0100 | [diff] [blame] | 158 | self.max_align = max(DEFAULT_MAX_ALIGN, align) if max_align is None else int(max_align) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 159 | |
Gustavo Henrique Nihei | cf120ba | 2021-11-22 18:44:11 -0300 | [diff] [blame] | 160 | if self.max_align == DEFAULT_MAX_ALIGN: |
| 161 | self.boot_magic = bytes([ |
| 162 | 0x77, 0xc2, 0x95, 0xf3, |
| 163 | 0x60, 0xd2, 0xef, 0x7f, |
| 164 | 0x35, 0x52, 0x50, 0x0f, |
| 165 | 0x2c, 0xb6, 0x79, 0x80, ]) |
| 166 | else: |
| 167 | align_lsb = self.max_align & 0x00ff |
| 168 | align_msb = (self.max_align & 0xff00) >> 8 |
| 169 | self.boot_magic = bytes([ |
| 170 | align_lsb, align_msb, 0x2d, 0xe1, |
| 171 | 0x5d, 0x29, 0x41, 0x0b, |
| 172 | 0x8d, 0x77, 0x67, 0x9c, |
| 173 | 0x11, 0x0f, 0x1f, 0x8a, ]) |
| 174 | |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 175 | if security_counter == 'auto': |
| 176 | # Security counter has not been explicitly provided, |
| 177 | # generate it from the version number |
| 178 | self.security_counter = ((self.version.major << 24) |
| 179 | + (self.version.minor << 16) |
| 180 | + self.version.revision) |
| 181 | else: |
| 182 | self.security_counter = security_counter |
| 183 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 184 | def __repr__(self): |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 185 | return "<Image version={}, header_size={}, security_counter={}, \ |
| 186 | base_addr={}, load_addr={}, align={}, slot_size={}, \ |
| 187 | max_sectors={}, overwrite_only={}, endian={} format={}, \ |
| 188 | payloadlen=0x{:x}>".format( |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 189 | self.version, |
| 190 | self.header_size, |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 191 | self.security_counter, |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 192 | 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] | 193 | self.load_addr, |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 194 | self.align, |
| 195 | self.slot_size, |
| 196 | self.max_sectors, |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 197 | self.overwrite_only, |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 198 | self.endian, |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 199 | self.__class__.__name__, |
| 200 | len(self.payload)) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 201 | |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 202 | def load(self, path): |
| 203 | """Load an image from a given file""" |
| 204 | ext = os.path.splitext(path)[1][1:].lower() |
Fabio Utzig | 1f50892 | 2020-01-15 11:37:51 -0300 | [diff] [blame] | 205 | try: |
| 206 | if ext == INTEL_HEX_EXT: |
| 207 | ih = IntelHex(path) |
| 208 | self.payload = ih.tobinarray() |
| 209 | self.base_addr = ih.minaddr() |
| 210 | else: |
| 211 | with open(path, 'rb') as f: |
| 212 | self.payload = f.read() |
| 213 | except FileNotFoundError: |
| 214 | raise click.UsageError("Input file not found") |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 215 | |
| 216 | # Add the image header if needed. |
| 217 | if self.pad_header and self.header_size > 0: |
| 218 | if self.base_addr: |
| 219 | # Adjust base_addr for new header |
| 220 | self.base_addr -= self.header_size |
Fabio Utzig | 9117fde | 2019-10-17 11:11:46 -0300 | [diff] [blame] | 221 | self.payload = bytes([self.erased_val] * self.header_size) + \ |
| 222 | self.payload |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 223 | |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 224 | self.check_header() |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 225 | |
Fabio Utzig | edbabcf | 2019-10-11 13:03:37 -0300 | [diff] [blame] | 226 | def save(self, path, hex_addr=None): |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 227 | """Save an image from a given file""" |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 228 | ext = os.path.splitext(path)[1][1:].lower() |
| 229 | if ext == INTEL_HEX_EXT: |
| 230 | # 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] | 231 | if self.base_addr is None and hex_addr is None: |
Fabio Utzig | 1f50892 | 2020-01-15 11:37:51 -0300 | [diff] [blame] | 232 | raise click.UsageError("No address exists in input file " |
| 233 | "neither was it provided by user") |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 234 | h = IntelHex() |
Fabio Utzig | edbabcf | 2019-10-11 13:03:37 -0300 | [diff] [blame] | 235 | if hex_addr is not None: |
| 236 | self.base_addr = hex_addr |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 237 | h.frombytes(bytes=self.payload, offset=self.base_addr) |
Fabio Utzig | edbabcf | 2019-10-11 13:03:37 -0300 | [diff] [blame] | 238 | if self.pad: |
Fabio Utzig | 2269f47 | 2019-10-17 11:14:33 -0300 | [diff] [blame] | 239 | trailer_size = self._trailer_size(self.align, self.max_sectors, |
| 240 | self.overwrite_only, |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 241 | self.enckey, |
| 242 | self.save_enctlv, |
| 243 | self.enctlv_len) |
Fabio Utzig | 2269f47 | 2019-10-17 11:14:33 -0300 | [diff] [blame] | 244 | trailer_addr = (self.base_addr + self.slot_size) - trailer_size |
Kristine Jassmann | 73c38c6 | 2021-02-03 16:56:14 +0000 | [diff] [blame] | 245 | if self.confirm and not self.overwrite_only: |
Alexander Mihajlovic | f4df58f | 2022-08-17 15:44:53 +0200 | [diff] [blame^] | 246 | magic_align_size = align_up(len(self.boot_magic), self.max_align) |
Kristine Jassmann | 73c38c6 | 2021-02-03 16:56:14 +0000 | [diff] [blame] | 247 | image_ok_idx = -(magic_align_size + self.max_align) |
Alexander Mihajlovic | f4df58f | 2022-08-17 15:44:53 +0200 | [diff] [blame^] | 248 | flag = bytearray([self.erased_val] * self.max_align) |
Wouter Cappelle | c028d45 | 2022-01-25 10:25:24 +0100 | [diff] [blame] | 249 | flag[0] = 0x01 # image_ok = 0x01 |
Alexander Mihajlovic | f4df58f | 2022-08-17 15:44:53 +0200 | [diff] [blame^] | 250 | h.puts(trailer_addr + trailer_size + image_ok_idx, bytes(flag)) |
Wouter Cappelle | c028d45 | 2022-01-25 10:25:24 +0100 | [diff] [blame] | 251 | h.puts(trailer_addr + (trailer_size - len(self.boot_magic)), |
| 252 | bytes(self.boot_magic)) |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 253 | h.tofile(path, 'hex') |
| 254 | else: |
Fabio Utzig | edbabcf | 2019-10-11 13:03:37 -0300 | [diff] [blame] | 255 | if self.pad: |
| 256 | self.pad_to(self.slot_size) |
Fabio Utzig | 7c00acd | 2019-01-07 09:54:20 -0200 | [diff] [blame] | 257 | with open(path, 'wb') as f: |
| 258 | f.write(self.payload) |
| 259 | |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 260 | def check_header(self): |
Fabio Utzig | f5556c3 | 2019-10-23 11:00:27 -0300 | [diff] [blame] | 261 | if self.header_size > 0 and not self.pad_header: |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 262 | 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] | 263 | raise click.UsageError("Header padding was not requested and " |
| 264 | "image does not start with zeros") |
| 265 | |
| 266 | def check_trailer(self): |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 267 | if self.slot_size > 0: |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 268 | tsize = self._trailer_size(self.align, self.max_sectors, |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 269 | self.overwrite_only, self.enckey, |
| 270 | self.save_enctlv, self.enctlv_len) |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 271 | padding = self.slot_size - (len(self.payload) + tsize) |
| 272 | if padding < 0: |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 273 | msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds " \ |
| 274 | "requested size 0x{:x}".format( |
| 275 | len(self.payload), tsize, self.slot_size) |
| 276 | raise click.UsageError(msg) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 277 | |
Fabio Utzig | 960b4c5 | 2020-04-02 13:07:12 -0300 | [diff] [blame] | 278 | def ecies_hkdf(self, enckey, plainkey): |
| 279 | if isinstance(enckey, ecdsa.ECDSA256P1Public): |
| 280 | newpk = ec.generate_private_key(ec.SECP256R1(), default_backend()) |
| 281 | shared = newpk.exchange(ec.ECDH(), enckey._get_public()) |
| 282 | else: |
| 283 | newpk = X25519PrivateKey.generate() |
| 284 | shared = newpk.exchange(enckey._get_public()) |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 285 | derived_key = HKDF( |
| 286 | algorithm=hashes.SHA256(), length=48, salt=None, |
| 287 | info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared) |
| 288 | encryptor = Cipher(algorithms.AES(derived_key[:16]), |
| 289 | modes.CTR(bytes([0] * 16)), |
| 290 | backend=default_backend()).encryptor() |
| 291 | cipherkey = encryptor.update(plainkey) + encryptor.finalize() |
| 292 | mac = hmac.HMAC(derived_key[16:], hashes.SHA256(), |
| 293 | backend=default_backend()) |
| 294 | mac.update(cipherkey) |
| 295 | ciphermac = mac.finalize() |
Fabio Utzig | 960b4c5 | 2020-04-02 13:07:12 -0300 | [diff] [blame] | 296 | if isinstance(enckey, ecdsa.ECDSA256P1Public): |
| 297 | pubk = newpk.public_key().public_bytes( |
| 298 | encoding=Encoding.X962, |
| 299 | format=PublicFormat.UncompressedPoint) |
| 300 | else: |
| 301 | pubk = newpk.public_key().public_bytes( |
| 302 | encoding=Encoding.Raw, |
| 303 | format=PublicFormat.Raw) |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 304 | return cipherkey, ciphermac, pubk |
| 305 | |
David Vincze | dde178d | 2020-03-26 20:06:01 +0100 | [diff] [blame] | 306 | def create(self, key, public_key_format, enckey, dependencies=None, |
Andrzej Puzdrowski | dfce0be | 2022-03-28 09:34:15 +0200 | [diff] [blame] | 307 | sw_type=None, custom_tlvs=None, encrypt_keylen=128, clear=False, fixed_sig=None, pub_key=None, vector_to_sign=None): |
Fabio Utzig | 649d80f | 2019-09-12 10:26:23 -0300 | [diff] [blame] | 308 | self.enckey = enckey |
| 309 | |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 310 | # Calculate the hash of the public key |
| 311 | if key is not None: |
| 312 | pub = key.get_public_bytes() |
| 313 | sha = hashlib.sha256() |
| 314 | sha.update(pub) |
| 315 | pubbytes = sha.digest() |
Andrzej Puzdrowski | 160303c | 2022-03-15 15:41:14 +0100 | [diff] [blame] | 316 | elif pub_key is not None: |
Andrzej Puzdrowski | dfce0be | 2022-03-28 09:34:15 +0200 | [diff] [blame] | 317 | if hasattr(pub_key, 'sign'): |
| 318 | print("sign the payload") |
Andrzej Puzdrowski | 160303c | 2022-03-15 15:41:14 +0100 | [diff] [blame] | 319 | pub = pub_key.get_public_bytes() |
| 320 | sha = hashlib.sha256() |
| 321 | sha.update(pub) |
| 322 | pubbytes = sha.digest() |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 323 | else: |
| 324 | pubbytes = bytes(hashlib.sha256().digest_size) |
| 325 | |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 326 | protected_tlv_size = 0 |
| 327 | |
| 328 | if self.security_counter is not None: |
| 329 | # Size of the security counter TLV: header ('HH') + payload ('I') |
| 330 | # = 4 + 4 = 8 Bytes |
| 331 | protected_tlv_size += TLV_SIZE + 4 |
| 332 | |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 333 | if sw_type is not None: |
| 334 | if len(sw_type) > MAX_SW_TYPE_LENGTH: |
| 335 | msg = "'{}' is too long ({} characters) for sw_type. Its " \ |
| 336 | "maximum allowed length is 12 characters.".format( |
| 337 | sw_type, len(sw_type)) |
| 338 | raise click.UsageError(msg) |
| 339 | |
| 340 | image_version = (str(self.version.major) + '.' |
| 341 | + str(self.version.minor) + '.' |
| 342 | + str(self.version.revision)) |
| 343 | |
| 344 | # The image hash is computed over the image header, the image |
| 345 | # itself and the protected TLV area. However, the boot record TLV |
| 346 | # (which is part of the protected area) should contain this hash |
| 347 | # before it is even calculated. For this reason the script fills |
| 348 | # this field with zeros and the bootloader will insert the right |
| 349 | # value later. |
| 350 | digest = bytes(hashlib.sha256().digest_size) |
| 351 | |
| 352 | # Create CBOR encoded boot record |
| 353 | boot_record = create_sw_component_data(sw_type, image_version, |
| 354 | "SHA256", digest, |
| 355 | pubbytes) |
| 356 | |
| 357 | protected_tlv_size += TLV_SIZE + len(boot_record) |
| 358 | |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 359 | if dependencies is not None: |
| 360 | # Size of a Dependency TLV = Header ('HH') + Payload('IBBHI') |
| 361 | # = 4 + 12 = 16 Bytes |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 362 | dependencies_num = len(dependencies[DEP_IMAGES_KEY]) |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 363 | protected_tlv_size += (dependencies_num * 16) |
| 364 | |
David Vincze | b2a1a48 | 2020-09-18 11:54:30 +0200 | [diff] [blame] | 365 | if custom_tlvs is not None: |
Ihor Slabkyy | 24d9373 | 2020-03-10 15:33:57 +0200 | [diff] [blame] | 366 | for value in custom_tlvs.values(): |
| 367 | protected_tlv_size += TLV_SIZE + len(value) |
| 368 | |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 369 | if protected_tlv_size != 0: |
| 370 | # Add the size of the TLV info header |
| 371 | protected_tlv_size += TLV_INFO_SIZE |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 372 | |
Ihor Slabkyy | 24d9373 | 2020-03-10 15:33:57 +0200 | [diff] [blame] | 373 | # At this point the image is already on the payload |
| 374 | # |
| 375 | # This adds the padding if image is not aligned to the 16 Bytes |
| 376 | # in encrypted mode |
| 377 | if self.enckey is not None: |
| 378 | pad_len = len(self.payload) % 16 |
| 379 | if pad_len > 0: |
Fabio Utzig | d62631a | 2021-02-04 19:45:27 -0300 | [diff] [blame] | 380 | pad = bytes(16 - pad_len) |
| 381 | if isinstance(self.payload, bytes): |
| 382 | self.payload += pad |
| 383 | else: |
| 384 | self.payload.extend(pad) |
Ihor Slabkyy | 24d9373 | 2020-03-10 15:33:57 +0200 | [diff] [blame] | 385 | |
| 386 | # This adds the header to the payload as well |
Salome Thirot | 0f64197 | 2021-05-14 11:19:55 +0100 | [diff] [blame] | 387 | if encrypt_keylen == 256: |
| 388 | self.add_header(enckey, protected_tlv_size, 256) |
| 389 | else: |
| 390 | self.add_header(enckey, protected_tlv_size) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 391 | |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 392 | prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 393 | |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 394 | # Protected TLVs must be added first, because they are also included |
| 395 | # in the hash calculation |
| 396 | protected_tlv_off = None |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 397 | if protected_tlv_size != 0: |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 398 | |
| 399 | e = STRUCT_ENDIAN_DICT[self.endian] |
| 400 | |
| 401 | if self.security_counter is not None: |
| 402 | payload = struct.pack(e + 'I', self.security_counter) |
| 403 | prot_tlv.add('SEC_CNT', payload) |
| 404 | |
David Vincze | 71b8f98 | 2020-03-17 19:08:12 +0100 | [diff] [blame] | 405 | if sw_type is not None: |
| 406 | prot_tlv.add('BOOT_RECORD', boot_record) |
| 407 | |
David Vincze | 1a7a690 | 2020-02-18 15:05:16 +0100 | [diff] [blame] | 408 | if dependencies is not None: |
| 409 | for i in range(dependencies_num): |
| 410 | payload = struct.pack( |
| 411 | e + 'B3x'+'BBHI', |
| 412 | int(dependencies[DEP_IMAGES_KEY][i]), |
| 413 | dependencies[DEP_VERSIONS_KEY][i].major, |
| 414 | dependencies[DEP_VERSIONS_KEY][i].minor, |
| 415 | dependencies[DEP_VERSIONS_KEY][i].revision, |
| 416 | dependencies[DEP_VERSIONS_KEY][i].build |
| 417 | ) |
| 418 | prot_tlv.add('DEPENDENCY', payload) |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 419 | |
David Vincze | b2a1a48 | 2020-09-18 11:54:30 +0200 | [diff] [blame] | 420 | if custom_tlvs is not None: |
| 421 | for tag, value in custom_tlvs.items(): |
| 422 | prot_tlv.add(tag, value) |
Ihor Slabkyy | 24d9373 | 2020-03-10 15:33:57 +0200 | [diff] [blame] | 423 | |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 424 | protected_tlv_off = len(self.payload) |
| 425 | self.payload += prot_tlv.get() |
| 426 | |
| 427 | tlv = TLV(self.endian) |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 428 | |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 429 | # Note that ecdsa wants to do the hashing itself, which means |
| 430 | # we get to hash it twice. |
| 431 | sha = hashlib.sha256() |
| 432 | sha.update(self.payload) |
| 433 | digest = sha.digest() |
| 434 | |
| 435 | tlv.add('SHA256', digest) |
| 436 | |
Almir Okato | 3eb5026 | 2022-05-09 16:23:50 -0300 | [diff] [blame] | 437 | if key is not None or fixed_sig is not None: |
| 438 | if public_key_format == 'hash': |
| 439 | tlv.add('KEYHASH', pubbytes) |
Fabio Utzig | 8101d1f | 2019-05-09 15:03:22 -0300 | [diff] [blame] | 440 | else: |
Almir Okato | 3eb5026 | 2022-05-09 16:23:50 -0300 | [diff] [blame] | 441 | tlv.add('PUBKEY', pub) |
| 442 | |
| 443 | if vector_to_sign == 'payload': |
| 444 | # Stop amending data to the image |
| 445 | # Just keep data vector which is expected to be sigend |
| 446 | print('export payload') |
| 447 | return |
| 448 | elif vector_to_sign == 'digest': |
| 449 | self.payload = digest |
| 450 | print('export digest') |
| 451 | return |
| 452 | |
| 453 | if key is not None and fixed_sig is None: |
| 454 | # `sign` expects the full image payload (sha256 done internally), |
| 455 | # while `sign_digest` expects only the digest of the payload |
| 456 | |
| 457 | if hasattr(key, 'sign'): |
| 458 | print("sign the payload") |
| 459 | sig = key.sign(bytes(self.payload)) |
| 460 | else: |
| 461 | print("sign the digest") |
| 462 | sig = key.sign_digest(digest) |
| 463 | tlv.add(key.sig_tlv(), sig) |
| 464 | self.signature = sig |
| 465 | elif fixed_sig is not None and key is None: |
| 466 | tlv.add(pub_key.sig_tlv(), fixed_sig['value']) |
| 467 | self.signature = fixed_sig['value'] |
| 468 | else: |
| 469 | raise click.UsageError("Can not sign using key and provide fixed-signature at the same time") |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 470 | |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 471 | # At this point the image was hashed + signed, we can remove the |
| 472 | # protected TLVs from the payload (will be re-added later) |
| 473 | if protected_tlv_off is not None: |
| 474 | self.payload = self.payload[:protected_tlv_off] |
| 475 | |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 476 | if enckey is not None: |
Salome Thirot | 0f64197 | 2021-05-14 11:19:55 +0100 | [diff] [blame] | 477 | if encrypt_keylen == 256: |
| 478 | plainkey = os.urandom(32) |
| 479 | else: |
| 480 | plainkey = os.urandom(16) |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 481 | |
| 482 | if isinstance(enckey, rsa.RSAPublic): |
| 483 | cipherkey = enckey._get_public().encrypt( |
| 484 | plainkey, padding.OAEP( |
| 485 | mgf=padding.MGF1(algorithm=hashes.SHA256()), |
| 486 | algorithm=hashes.SHA256(), |
| 487 | label=None)) |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 488 | self.enctlv_len = len(cipherkey) |
Fabio Utzig | 7a3b260 | 2019-10-22 09:56:44 -0300 | [diff] [blame] | 489 | tlv.add('ENCRSA2048', cipherkey) |
Fabio Utzig | 960b4c5 | 2020-04-02 13:07:12 -0300 | [diff] [blame] | 490 | elif isinstance(enckey, (ecdsa.ECDSA256P1Public, |
| 491 | x25519.X25519Public)): |
| 492 | cipherkey, mac, pubk = self.ecies_hkdf(enckey, plainkey) |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 493 | enctlv = pubk + mac + cipherkey |
| 494 | self.enctlv_len = len(enctlv) |
Fabio Utzig | 960b4c5 | 2020-04-02 13:07:12 -0300 | [diff] [blame] | 495 | if isinstance(enckey, ecdsa.ECDSA256P1Public): |
| 496 | tlv.add('ENCEC256', enctlv) |
| 497 | else: |
| 498 | tlv.add('ENCX25519', enctlv) |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 499 | |
Michel Jaouen | d09aa6b | 2022-01-07 16:48:58 +0100 | [diff] [blame] | 500 | if not clear: |
| 501 | nonce = bytes([0] * 16) |
| 502 | cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce), |
| 503 | backend=default_backend()) |
| 504 | encryptor = cipher.encryptor() |
| 505 | img = bytes(self.payload[self.header_size:]) |
| 506 | self.payload[self.header_size:] = \ |
| 507 | encryptor.update(img) + encryptor.finalize() |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 508 | |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 509 | self.payload += prot_tlv.get() |
| 510 | self.payload += tlv.get() |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 511 | |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 512 | self.check_trailer() |
| 513 | |
Andrzej Puzdrowski | 160303c | 2022-03-15 15:41:14 +0100 | [diff] [blame] | 514 | def get_signature(self): |
| 515 | return self.signature |
| 516 | |
Salome Thirot | 0f64197 | 2021-05-14 11:19:55 +0100 | [diff] [blame] | 517 | def add_header(self, enckey, protected_tlv_size, aes_length=128): |
Fabio Utzig | cd28406 | 2018-11-30 11:05:45 -0200 | [diff] [blame] | 518 | """Install the image header.""" |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 519 | |
David Brown | 0f0c6a8 | 2017-06-08 09:26:24 -0600 | [diff] [blame] | 520 | flags = 0 |
Fabio Utzig | 06b77b8 | 2018-08-23 16:01:16 -0300 | [diff] [blame] | 521 | if enckey is not None: |
Salome Thirot | 0f64197 | 2021-05-14 11:19:55 +0100 | [diff] [blame] | 522 | if aes_length == 128: |
| 523 | flags |= IMAGE_F['ENCRYPTED_AES128'] |
| 524 | else: |
| 525 | flags |= IMAGE_F['ENCRYPTED_AES256'] |
David Vincze | 1e0c544 | 2020-04-07 14:12:33 +0200 | [diff] [blame] | 526 | if self.load_addr != 0: |
| 527 | # Indicates that this image should be loaded into RAM |
| 528 | # instead of run directly from flash. |
| 529 | flags |= IMAGE_F['RAM_LOAD'] |
Dominik Ermel | 50820b1 | 2020-12-14 13:16:46 +0000 | [diff] [blame] | 530 | if self.rom_fixed: |
| 531 | flags |= IMAGE_F['ROM_FIXED'] |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 532 | |
Mark Schulte | a66c687 | 2018-09-26 17:24:40 -0700 | [diff] [blame] | 533 | e = STRUCT_ENDIAN_DICT[self.endian] |
| 534 | fmt = (e + |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 535 | # type ImageHdr struct { |
| 536 | 'I' + # Magic uint32 |
| 537 | 'I' + # LoadAddr uint32 |
| 538 | 'H' + # HdrSz uint16 |
| 539 | 'H' + # PTLVSz uint16 |
| 540 | 'I' + # ImgSz uint32 |
| 541 | 'I' + # Flags uint32 |
| 542 | 'BBHI' + # Vers ImageVersion |
| 543 | 'I' # Pad1 uint32 |
| 544 | ) # } |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 545 | assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE |
| 546 | header = struct.pack(fmt, |
| 547 | IMAGE_MAGIC, |
Dominik Ermel | 50820b1 | 2020-12-14 13:16:46 +0000 | [diff] [blame] | 548 | self.rom_fixed or self.load_addr, |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 549 | self.header_size, |
Fabio Utzig | 510fddb | 2019-09-12 12:15:36 -0300 | [diff] [blame] | 550 | protected_tlv_size, # TLV Info header + Protected TLVs |
| 551 | len(self.payload) - self.header_size, # ImageSz |
| 552 | flags, |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 553 | self.version.major, |
| 554 | self.version.minor or 0, |
| 555 | self.version.revision or 0, |
| 556 | self.version.build or 0, |
David Vincze | da8c919 | 2019-03-26 17:17:41 +0100 | [diff] [blame] | 557 | 0) # Pad1 |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 558 | self.payload = bytearray(self.payload) |
| 559 | self.payload[:len(header)] = header |
| 560 | |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 561 | def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey, |
| 562 | save_enctlv, enctlv_len): |
Fabio Utzig | 519285f | 2018-06-04 11:11:53 -0300 | [diff] [blame] | 563 | # NOTE: should already be checked by the argument parser |
Fabio Utzig | 649d80f | 2019-09-12 10:26:23 -0300 | [diff] [blame] | 564 | magic_size = 16 |
Gustavo Henrique Nihei | cf120ba | 2021-11-22 18:44:11 -0300 | [diff] [blame] | 565 | magic_align_size = align_up(magic_size, self.max_align) |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 566 | if overwrite_only: |
Kristine Jassmann | 73c38c6 | 2021-02-03 16:56:14 +0000 | [diff] [blame] | 567 | return self.max_align * 2 + magic_align_size |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 568 | else: |
Kristine Jassmann | 73c38c6 | 2021-02-03 16:56:14 +0000 | [diff] [blame] | 569 | if write_size not in set([1, 2, 4, 8, 16, 32]): |
Fabio Utzig | 1f50892 | 2020-01-15 11:37:51 -0300 | [diff] [blame] | 570 | raise click.BadParameter("Invalid alignment: {}".format( |
| 571 | write_size)) |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 572 | m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors |
Fabio Utzig | 649d80f | 2019-09-12 10:26:23 -0300 | [diff] [blame] | 573 | trailer = m * 3 * write_size # status area |
| 574 | if enckey is not None: |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 575 | if save_enctlv: |
| 576 | # TLV saved by the bootloader is aligned |
Gustavo Henrique Nihei | cf120ba | 2021-11-22 18:44:11 -0300 | [diff] [blame] | 577 | keylen = align_up(enctlv_len, self.max_align) |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 578 | else: |
Gustavo Henrique Nihei | cf120ba | 2021-11-22 18:44:11 -0300 | [diff] [blame] | 579 | keylen = align_up(16, self.max_align) |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 580 | trailer += keylen * 2 # encryption keys |
Kristine Jassmann | 73c38c6 | 2021-02-03 16:56:14 +0000 | [diff] [blame] | 581 | trailer += self.max_align * 4 # image_ok/copy_done/swap_info/swap_size |
| 582 | trailer += magic_align_size |
Fabio Utzig | 649d80f | 2019-09-12 10:26:23 -0300 | [diff] [blame] | 583 | return trailer |
Fabio Utzig | 519285f | 2018-06-04 11:11:53 -0300 | [diff] [blame] | 584 | |
Fabio Utzig | 263d439 | 2018-06-05 10:37:35 -0300 | [diff] [blame] | 585 | def pad_to(self, size): |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 586 | """Pad the image to the given size, with the given flash alignment.""" |
Fabio Utzig | dcf0c9b | 2018-06-11 12:27:49 -0700 | [diff] [blame] | 587 | tsize = self._trailer_size(self.align, self.max_sectors, |
Fabio Utzig | 9a492d5 | 2020-01-15 11:31:52 -0300 | [diff] [blame] | 588 | self.overwrite_only, self.enckey, |
| 589 | self.save_enctlv, self.enctlv_len) |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 590 | padding = size - (len(self.payload) + tsize) |
Henrik Brix Andersen | 0ce958e | 2020-03-11 14:04:11 +0100 | [diff] [blame] | 591 | pbytes = bytearray([self.erased_val] * padding) |
Gustavo Henrique Nihei | cf120ba | 2021-11-22 18:44:11 -0300 | [diff] [blame] | 592 | pbytes += bytearray([self.erased_val] * (tsize - len(self.boot_magic))) |
| 593 | pbytes += self.boot_magic |
Kristine Jassmann | 73c38c6 | 2021-02-03 16:56:14 +0000 | [diff] [blame] | 594 | if self.confirm and not self.overwrite_only: |
| 595 | magic_size = 16 |
Gustavo Henrique Nihei | cf120ba | 2021-11-22 18:44:11 -0300 | [diff] [blame] | 596 | magic_align_size = align_up(magic_size, self.max_align) |
Kristine Jassmann | 73c38c6 | 2021-02-03 16:56:14 +0000 | [diff] [blame] | 597 | image_ok_idx = -(magic_align_size + self.max_align) |
| 598 | pbytes[image_ok_idx] = 0x01 # image_ok = 0x01 |
David Brown | 23f91ad | 2017-05-16 11:38:17 -0600 | [diff] [blame] | 599 | self.payload += pbytes |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 600 | |
| 601 | @staticmethod |
| 602 | def verify(imgfile, key): |
| 603 | with open(imgfile, "rb") as f: |
| 604 | b = f.read() |
| 605 | |
| 606 | magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16]) |
Marek Pieta | e955510 | 2019-08-08 16:08:16 +0200 | [diff] [blame] | 607 | version = struct.unpack('BBHI', b[20:28]) |
| 608 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 609 | if magic != IMAGE_MAGIC: |
Casper Meijn | 2a01f3f | 2020-08-22 13:51:40 +0200 | [diff] [blame] | 610 | return VerifyResult.INVALID_MAGIC, None, None |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 611 | |
Fabio Utzig | d12a8da | 2021-01-21 08:44:59 -0300 | [diff] [blame] | 612 | tlv_off = header_size + img_size |
| 613 | tlv_info = b[tlv_off:tlv_off+TLV_INFO_SIZE] |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 614 | magic, tlv_tot = struct.unpack('HH', tlv_info) |
Fabio Utzig | d12a8da | 2021-01-21 08:44:59 -0300 | [diff] [blame] | 615 | if magic == TLV_PROT_INFO_MAGIC: |
| 616 | tlv_off += tlv_tot |
| 617 | tlv_info = b[tlv_off:tlv_off+TLV_INFO_SIZE] |
| 618 | magic, tlv_tot = struct.unpack('HH', tlv_info) |
| 619 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 620 | if magic != TLV_INFO_MAGIC: |
Casper Meijn | 2a01f3f | 2020-08-22 13:51:40 +0200 | [diff] [blame] | 621 | return VerifyResult.INVALID_TLV_INFO_MAGIC, None, None |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 622 | |
| 623 | sha = hashlib.sha256() |
Fabio Utzig | d12a8da | 2021-01-21 08:44:59 -0300 | [diff] [blame] | 624 | prot_tlv_size = tlv_off |
| 625 | sha.update(b[:prot_tlv_size]) |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 626 | digest = sha.digest() |
| 627 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 628 | tlv_end = tlv_off + tlv_tot |
| 629 | tlv_off += TLV_INFO_SIZE # skip tlv info |
| 630 | while tlv_off < tlv_end: |
| 631 | tlv = b[tlv_off:tlv_off+TLV_SIZE] |
| 632 | tlv_type, _, tlv_len = struct.unpack('BBH', tlv) |
| 633 | if tlv_type == TLV_VALUES["SHA256"]: |
| 634 | off = tlv_off + TLV_SIZE |
| 635 | if digest == b[off:off+tlv_len]: |
| 636 | if key is None: |
Casper Meijn | 2a01f3f | 2020-08-22 13:51:40 +0200 | [diff] [blame] | 637 | return VerifyResult.OK, version, digest |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 638 | else: |
Casper Meijn | 2a01f3f | 2020-08-22 13:51:40 +0200 | [diff] [blame] | 639 | return VerifyResult.INVALID_HASH, None, None |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 640 | elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]: |
| 641 | off = tlv_off + TLV_SIZE |
| 642 | tlv_sig = b[off:off+tlv_len] |
Fabio Utzig | d12a8da | 2021-01-21 08:44:59 -0300 | [diff] [blame] | 643 | payload = b[:prot_tlv_size] |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 644 | try: |
Fabio Utzig | 8101d1f | 2019-05-09 15:03:22 -0300 | [diff] [blame] | 645 | if hasattr(key, 'verify'): |
| 646 | key.verify(tlv_sig, payload) |
| 647 | else: |
| 648 | key.verify_digest(tlv_sig, digest) |
Casper Meijn | 2a01f3f | 2020-08-22 13:51:40 +0200 | [diff] [blame] | 649 | return VerifyResult.OK, version, digest |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 650 | except InvalidSignature: |
| 651 | # continue to next TLV |
| 652 | pass |
| 653 | tlv_off += TLV_SIZE + tlv_len |
Casper Meijn | 2a01f3f | 2020-08-22 13:51:40 +0200 | [diff] [blame] | 654 | return VerifyResult.INVALID_SIGNATURE, None, None |