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