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