blob: 5541f112b209838aacc4aee661d9a6ea3a742fcd [file] [log] [blame]
David Brownc8d62012021-10-27 15:03:48 -06001// Copyright (c) 2017-2021 Linaro LTD
David Browne2acfae2020-01-21 16:45:01 -07002// Copyright (c) 2017-2020 JUUL Labs
Roland Mikhel75c7c312023-02-23 15:39:14 +01003// Copyright (c) 2021-2023 Arm Limited
David Browne2acfae2020-01-21 16:45:01 -07004//
5// SPDX-License-Identifier: Apache-2.0
6
David Brown187dd882017-07-11 11:15:23 -06007//! TLV Support
8//!
9//! mcuboot images are followed immediately by a list of TLV items that contain integrity
10//! information about the image. Their generation is made a little complicated because the size of
11//! the TLV block is in the image header, which is included in the hash. Since some signatures can
12//! vary in size, we just make them the largest size possible.
13//!
14//! Because of this header, we have to make two passes. The first pass will compute the size of
15//! the TLV, and the second pass will build the data for the TLV.
16
David Brown91d68632019-07-29 14:32:13 -060017use byteorder::{
18 LittleEndian, WriteBytesExt,
19};
David Brown9c6322f2021-08-19 13:03:39 -060020use cipher::FromBlockCipher;
David Brown8a4e23b2021-06-11 10:29:01 -060021use crate::caps::Caps;
David Brown7a81c4b2019-07-29 15:20:21 -060022use crate::image::ImageVersion;
Fabio Utzige84f0ef2019-11-22 12:29:32 -030023use log::info;
Fabio Utzig90f449e2019-10-24 07:43:53 -030024use ring::{digest, rand, agreement, hkdf, hmac};
Fabio Utzige84f0ef2019-11-22 12:29:32 -030025use ring::rand::SecureRandom;
Fabio Utzig05ab0142018-07-10 09:15:28 -030026use ring::signature::{
27 RsaKeyPair,
28 RSA_PSS_SHA256,
29 EcdsaKeyPair,
30 ECDSA_P256_SHA256_ASN1_SIGNING,
Fabio Utzig97710282019-05-24 17:44:49 -030031 Ed25519KeyPair,
Fabio Utzig05ab0142018-07-10 09:15:28 -030032};
David Brown9c6322f2021-08-19 13:03:39 -060033use aes::{
34 Aes128,
Fabio Utzig90f449e2019-10-24 07:43:53 -030035 Aes128Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060036 Aes256,
Salome Thirot6fdbf552021-05-14 16:46:14 +010037 Aes256Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060038 NewBlockCipher
39};
40use cipher::{
41 generic_array::GenericArray,
42 StreamCipher,
Fabio Utzig90f449e2019-10-24 07:43:53 -030043};
Fabio Utzig80fde2f2017-12-05 09:25:31 -020044use mcuboot_sys::c;
Salome Thirot6fdbf552021-05-14 16:46:14 +010045use typenum::{U16, U32};
David Brown187dd882017-07-11 11:15:23 -060046
David Brown69721182019-12-04 14:50:52 -070047#[repr(u16)]
David Brownc3898d62019-08-05 14:20:02 -060048#[derive(Copy, Clone, Debug, PartialEq, Eq)]
David Brown187dd882017-07-11 11:15:23 -060049#[allow(dead_code)] // TODO: For now
50pub enum TlvKinds {
David Brown43cda332017-09-01 09:53:23 -060051 KEYHASH = 0x01,
David Brown27648b82017-08-31 10:40:29 -060052 SHA256 = 0x10,
53 RSA2048 = 0x20,
David Vincze4395b802023-04-27 16:11:49 +020054 ECDSASIG = 0x22,
Fabio Utzig39297432019-05-08 18:51:10 -030055 RSA3072 = 0x23,
Fabio Utzig97710282019-05-24 17:44:49 -030056 ED25519 = 0x24,
Fabio Utzig1e48b912018-09-18 09:04:18 -030057 ENCRSA2048 = 0x30,
Salome Thirot0f641972021-05-14 11:19:55 +010058 ENCKW = 0x31,
Fabio Utzig90f449e2019-10-24 07:43:53 -030059 ENCEC256 = 0x32,
Fabio Utzig3fa72ca2020-04-02 11:20:37 -030060 ENCX25519 = 0x33,
David Brown7a81c4b2019-07-29 15:20:21 -060061 DEPENDENCY = 0x40,
Roland Mikheld6703522023-04-27 14:24:30 +020062 SECCNT = 0x50,
Fabio Utzig1e48b912018-09-18 09:04:18 -030063}
64
65#[allow(dead_code, non_camel_case_types)]
66pub enum TlvFlags {
67 PIC = 0x01,
68 NON_BOOTABLE = 0x02,
Salome Thirot6fdbf552021-05-14 16:46:14 +010069 ENCRYPTED_AES128 = 0x04,
Salome Thirot6fdbf552021-05-14 16:46:14 +010070 ENCRYPTED_AES256 = 0x08,
David Brownd8713a52021-10-22 16:27:23 -060071 RAM_LOAD = 0x20,
David Brown187dd882017-07-11 11:15:23 -060072}
73
David Brown43643dd2019-01-11 15:43:28 -070074/// A generator for manifests. The format of the manifest can be either a
75/// traditional "TLV" or a SUIT-style manifest.
76pub trait ManifestGen {
David Brownac46e262019-01-11 15:46:18 -070077 /// Retrieve the header magic value for this manifest type.
78 fn get_magic(&self) -> u32;
79
David Brown43643dd2019-01-11 15:43:28 -070080 /// Retrieve the flags value for this particular manifest type.
81 fn get_flags(&self) -> u32;
82
David Brown7a81c4b2019-07-29 15:20:21 -060083 /// Retrieve the number of bytes of this manifest that is "protected".
84 /// This field is stored in the outside image header instead of the
85 /// manifest header.
86 fn protect_size(&self) -> u16;
87
88 /// Add a dependency on another image.
89 fn add_dependency(&mut self, id: u8, version: &ImageVersion);
90
David Brown43643dd2019-01-11 15:43:28 -070091 /// Add a sequence of bytes to the payload that the manifest is
92 /// protecting.
93 fn add_bytes(&mut self, bytes: &[u8]);
94
David Browne90b13f2019-12-06 15:04:00 -070095 /// Set an internal flag indicating that the next `make_tlv` should
96 /// corrupt the signature.
97 fn corrupt_sig(&mut self);
98
David Brownef4f0742021-10-22 17:09:50 -060099 /// Estimate the size of the TLV. This can be called before the payload is added (but after
100 /// other information is added). Some of the signature algorithms can generate variable sized
101 /// data, and therefore, this can slightly overestimate the size.
102 fn estimate_size(&self) -> usize;
103
David Brown43643dd2019-01-11 15:43:28 -0700104 /// Construct the manifest for this payload.
105 fn make_tlv(self: Box<Self>) -> Vec<u8>;
Fabio Utzig90f449e2019-10-24 07:43:53 -0300106
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300107 /// Generate a new encryption random key
108 fn generate_enc_key(&mut self);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300109
110 /// Return the current encryption key
111 fn get_enc_key(&self) -> Vec<u8>;
Roland Mikheld6703522023-04-27 14:24:30 +0200112
113 /// Set the security counter to the specified value.
114 fn set_security_counter(&mut self, security_cnt: Option<u32>);
Roland Mikhel6945bb62023-04-11 15:57:49 +0200115
116 /// Sets the ignore_ram_load_flag so that can be validated when it is missing,
117 /// it will not load successfully.
118 fn set_ignore_ram_load_flag(&mut self);
David Brown43643dd2019-01-11 15:43:28 -0700119}
120
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300121#[derive(Debug, Default)]
David Brown187dd882017-07-11 11:15:23 -0600122pub struct TlvGen {
David Brown43cda332017-09-01 09:53:23 -0600123 flags: u32,
David Brown187dd882017-07-11 11:15:23 -0600124 kinds: Vec<TlvKinds>,
David Brown4243ab02017-07-11 12:24:23 -0600125 payload: Vec<u8>,
David Brown7a81c4b2019-07-29 15:20:21 -0600126 dependencies: Vec<Dependency>,
Fabio Utzig90f449e2019-10-24 07:43:53 -0300127 enc_key: Vec<u8>,
David Browne90b13f2019-12-06 15:04:00 -0700128 /// Should this signature be corrupted.
129 gen_corrupted: bool,
Roland Mikheld6703522023-04-27 14:24:30 +0200130 security_cnt: Option<u32>,
Roland Mikhel6945bb62023-04-11 15:57:49 +0200131 /// Ignore RAM_LOAD flag
132 ignore_ram_load_flag: bool,
David Brown7a81c4b2019-07-29 15:20:21 -0600133}
134
David Brownc3898d62019-08-05 14:20:02 -0600135#[derive(Debug)]
David Brown7a81c4b2019-07-29 15:20:21 -0600136struct Dependency {
137 id: u8,
138 version: ImageVersion,
David Brown187dd882017-07-11 11:15:23 -0600139}
140
141impl TlvGen {
142 /// Construct a new tlv generator that will only contain a hash of the data.
David Brown7e701d82017-07-11 13:24:25 -0600143 #[allow(dead_code)]
David Brown187dd882017-07-11 11:15:23 -0600144 pub fn new_hash_only() -> TlvGen {
145 TlvGen {
David Brown187dd882017-07-11 11:15:23 -0600146 kinds: vec![TlvKinds::SHA256],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300147 ..Default::default()
David Brown187dd882017-07-11 11:15:23 -0600148 }
149 }
150
David Brown7e701d82017-07-11 13:24:25 -0600151 #[allow(dead_code)]
152 pub fn new_rsa_pss() -> TlvGen {
153 TlvGen {
Fabio Utzig754438d2018-12-14 06:39:58 -0200154 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300155 ..Default::default()
David Brown7e701d82017-07-11 13:24:25 -0600156 }
157 }
158
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200159 #[allow(dead_code)]
Fabio Utzig39297432019-05-08 18:51:10 -0300160 pub fn new_rsa3072_pss() -> TlvGen {
161 TlvGen {
Fabio Utzig39297432019-05-08 18:51:10 -0300162 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA3072],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300163 ..Default::default()
Fabio Utzig39297432019-05-08 18:51:10 -0300164 }
165 }
166
167 #[allow(dead_code)]
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200168 pub fn new_ecdsa() -> TlvGen {
169 TlvGen {
Roland Mikhel30978512023-02-08 14:06:58 +0100170 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSASIG],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300171 ..Default::default()
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200172 }
173 }
174
Fabio Utzig1e48b912018-09-18 09:04:18 -0300175 #[allow(dead_code)]
Fabio Utzig97710282019-05-24 17:44:49 -0300176 pub fn new_ed25519() -> TlvGen {
177 TlvGen {
Fabio Utzig97710282019-05-24 17:44:49 -0300178 kinds: vec![TlvKinds::SHA256, TlvKinds::ED25519],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300179 ..Default::default()
Fabio Utzig97710282019-05-24 17:44:49 -0300180 }
181 }
182
183 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100184 pub fn new_enc_rsa(aes_key_size: u32) -> TlvGen {
185 let flag = if aes_key_size == 256 {
186 TlvFlags::ENCRYPTED_AES256 as u32
187 } else {
188 TlvFlags::ENCRYPTED_AES128 as u32
189 };
Fabio Utzig1e48b912018-09-18 09:04:18 -0300190 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100191 flags: flag,
Fabio Utzig1e48b912018-09-18 09:04:18 -0300192 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCRSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300193 ..Default::default()
Fabio Utzig1e48b912018-09-18 09:04:18 -0300194 }
195 }
196
197 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100198 pub fn new_sig_enc_rsa(aes_key_size: u32) -> TlvGen {
199 let flag = if aes_key_size == 256 {
200 TlvFlags::ENCRYPTED_AES256 as u32
201 } else {
202 TlvFlags::ENCRYPTED_AES128 as u32
203 };
Fabio Utzig754438d2018-12-14 06:39:58 -0200204 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100205 flags: flag,
Fabio Utzig754438d2018-12-14 06:39:58 -0200206 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048, TlvKinds::ENCRSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300207 ..Default::default()
Fabio Utzig754438d2018-12-14 06:39:58 -0200208 }
209 }
210
211 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100212 pub fn new_enc_kw(aes_key_size: u32) -> TlvGen {
213 let flag = if aes_key_size == 256 {
214 TlvFlags::ENCRYPTED_AES256 as u32
215 } else {
216 TlvFlags::ENCRYPTED_AES128 as u32
217 };
Fabio Utzig1e48b912018-09-18 09:04:18 -0300218 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100219 flags: flag,
Salome Thirot0f641972021-05-14 11:19:55 +0100220 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300221 ..Default::default()
Fabio Utzig1e48b912018-09-18 09:04:18 -0300222 }
223 }
224
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200225 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100226 pub fn new_rsa_kw(aes_key_size: u32) -> TlvGen {
227 let flag = if aes_key_size == 256 {
228 TlvFlags::ENCRYPTED_AES256 as u32
229 } else {
230 TlvFlags::ENCRYPTED_AES128 as u32
231 };
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200232 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100233 flags: flag,
Salome Thirot0f641972021-05-14 11:19:55 +0100234 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300235 ..Default::default()
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200236 }
237 }
238
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200239 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100240 pub fn new_ecdsa_kw(aes_key_size: u32) -> TlvGen {
241 let flag = if aes_key_size == 256 {
242 TlvFlags::ENCRYPTED_AES256 as u32
243 } else {
244 TlvFlags::ENCRYPTED_AES128 as u32
245 };
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200246 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100247 flags: flag,
Roland Mikhel30978512023-02-08 14:06:58 +0100248 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSASIG, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300249 ..Default::default()
Fabio Utzig90f449e2019-10-24 07:43:53 -0300250 }
251 }
252
253 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100254 pub fn new_ecies_p256(aes_key_size: u32) -> TlvGen {
255 let flag = if aes_key_size == 256 {
256 TlvFlags::ENCRYPTED_AES256 as u32
257 } else {
258 TlvFlags::ENCRYPTED_AES128 as u32
259 };
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300260 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100261 flags: flag,
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300262 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCEC256],
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300263 ..Default::default()
264 }
265 }
266
267 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100268 pub fn new_ecdsa_ecies_p256(aes_key_size: u32) -> TlvGen {
269 let flag = if aes_key_size == 256 {
270 TlvFlags::ENCRYPTED_AES256 as u32
271 } else {
272 TlvFlags::ENCRYPTED_AES128 as u32
273 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300274 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100275 flags: flag,
Roland Mikhel30978512023-02-08 14:06:58 +0100276 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSASIG, TlvKinds::ENCEC256],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300277 ..Default::default()
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200278 }
279 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300280
281 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100282 pub fn new_ecies_x25519(aes_key_size: u32) -> TlvGen {
283 let flag = if aes_key_size == 256 {
284 TlvFlags::ENCRYPTED_AES256 as u32
285 } else {
286 TlvFlags::ENCRYPTED_AES128 as u32
287 };
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300288 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100289 flags: flag,
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300290 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCX25519],
291 ..Default::default()
292 }
293 }
294
295 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100296 pub fn new_ed25519_ecies_x25519(aes_key_size: u32) -> TlvGen {
297 let flag = if aes_key_size == 256 {
298 TlvFlags::ENCRYPTED_AES256 as u32
299 } else {
300 TlvFlags::ENCRYPTED_AES128 as u32
301 };
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300302 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100303 flags: flag,
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300304 kinds: vec![TlvKinds::SHA256, TlvKinds::ED25519, TlvKinds::ENCX25519],
305 ..Default::default()
306 }
307 }
Roland Mikheld6703522023-04-27 14:24:30 +0200308
309 #[allow(dead_code)]
310 pub fn new_sec_cnt() -> TlvGen {
311 TlvGen {
312 kinds: vec![TlvKinds::SHA256, TlvKinds::SECCNT],
313 ..Default::default()
314 }
315 }
316
David Brown43643dd2019-01-11 15:43:28 -0700317}
318
319impl ManifestGen for TlvGen {
David Brownac46e262019-01-11 15:46:18 -0700320 fn get_magic(&self) -> u32 {
321 0x96f3b83d
322 }
323
David Brown43643dd2019-01-11 15:43:28 -0700324 /// Retrieve the header flags for this configuration. This can be called at any time.
325 fn get_flags(&self) -> u32 {
David Brown8a4e23b2021-06-11 10:29:01 -0600326 // For the RamLoad case, add in the flag for this feature.
Roland Mikhel6945bb62023-04-11 15:57:49 +0200327 if Caps::RamLoad.present() && !self.ignore_ram_load_flag {
David Brown8a4e23b2021-06-11 10:29:01 -0600328 self.flags | (TlvFlags::RAM_LOAD as u32)
329 } else {
330 self.flags
331 }
David Brown43643dd2019-01-11 15:43:28 -0700332 }
David Brown187dd882017-07-11 11:15:23 -0600333
334 /// Add bytes to the covered hash.
David Brown43643dd2019-01-11 15:43:28 -0700335 fn add_bytes(&mut self, bytes: &[u8]) {
David Brown4243ab02017-07-11 12:24:23 -0600336 self.payload.extend_from_slice(bytes);
David Brown187dd882017-07-11 11:15:23 -0600337 }
338
David Brown7a81c4b2019-07-29 15:20:21 -0600339 fn protect_size(&self) -> u16 {
Roland Mikheld6703522023-04-27 14:24:30 +0200340 let mut size = 0;
341 if !self.dependencies.is_empty() || (Caps::HwRollbackProtection.present() && self.security_cnt.is_some()) {
342 // include the TLV area header.
343 size += 4;
344 // add space for each dependency.
345 size += (self.dependencies.len() as u16) * (4 + std::mem::size_of::<Dependency>() as u16);
346 if Caps::HwRollbackProtection.present() && self.security_cnt.is_some() {
347 size += 4 + 4;
348 }
David Brown7a81c4b2019-07-29 15:20:21 -0600349 }
Roland Mikheld6703522023-04-27 14:24:30 +0200350 size
David Brown7a81c4b2019-07-29 15:20:21 -0600351 }
352
353 fn add_dependency(&mut self, id: u8, version: &ImageVersion) {
David Brown7a81c4b2019-07-29 15:20:21 -0600354 self.dependencies.push(Dependency {
David Brown4dfb33c2021-03-10 05:15:45 -0700355 id,
David Brown7a81c4b2019-07-29 15:20:21 -0600356 version: version.clone(),
357 });
358 }
359
David Browne90b13f2019-12-06 15:04:00 -0700360 fn corrupt_sig(&mut self) {
361 self.gen_corrupted = true;
362 }
363
David Brownef4f0742021-10-22 17:09:50 -0600364 fn estimate_size(&self) -> usize {
365 // Begin the estimate with the 4 byte header.
366 let mut estimate = 4;
367 // A very poor estimate.
368
369 // Estimate the size of the image hash.
370 if self.kinds.contains(&TlvKinds::SHA256) {
371 estimate += 4 + 32;
372 }
373
374 // Add an estimate in for each of the signature algorithms.
375 if self.kinds.contains(&TlvKinds::RSA2048) {
376 estimate += 4 + 32; // keyhash
377 estimate += 4 + 256; // RSA2048
378 }
379 if self.kinds.contains(&TlvKinds::RSA3072) {
380 estimate += 4 + 32; // keyhash
381 estimate += 4 + 384; // RSA3072
382 }
David Brownef4f0742021-10-22 17:09:50 -0600383 if self.kinds.contains(&TlvKinds::ED25519) {
384 estimate += 4 + 32; // keyhash
385 estimate += 4 + 64; // ED25519 signature.
386 }
Roland Mikhel6205c102023-02-06 13:32:02 +0100387 if self.kinds.contains(&TlvKinds::ECDSASIG) {
388 estimate += 4 + 32; // keyhash
Roland Mikhel30978512023-02-08 14:06:58 +0100389
390 // ECDSA signatures are encoded as ASN.1 with the x and y values stored as signed
391 // integers. As such, the size can vary by 2 bytes, if the 256-bit value has the high
392 // bit, it takes an extra 0 byte to avoid it being seen as a negative number.
Roland Mikhel6205c102023-02-06 13:32:02 +0100393 estimate += 4 + 72; // ECDSA256 (varies)
394 }
David Brownef4f0742021-10-22 17:09:50 -0600395
396 // Estimate encryption.
397 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
398 let aes256 = (self.get_flags() & flag) == flag;
399
400 if self.kinds.contains(&TlvKinds::ENCRSA2048) {
401 estimate += 4 + 256;
402 }
403 if self.kinds.contains(&TlvKinds::ENCKW) {
404 estimate += 4 + if aes256 { 40 } else { 24 };
405 }
406 if self.kinds.contains(&TlvKinds::ENCEC256) {
407 estimate += 4 + if aes256 { 129 } else { 113 };
408 }
409 if self.kinds.contains(&TlvKinds::ENCX25519) {
410 estimate += 4 + if aes256 { 96 } else { 80 };
411 }
412
Roland Mikheld6703522023-04-27 14:24:30 +0200413 // Gather the size of the protected TLV area.
414 estimate += self.protect_size() as usize;
David Brownef4f0742021-10-22 17:09:50 -0600415
416 estimate
417 }
418
David Brown187dd882017-07-11 11:15:23 -0600419 /// Compute the TLV given the specified block of data.
David Brown43643dd2019-01-11 15:43:28 -0700420 fn make_tlv(self: Box<Self>) -> Vec<u8> {
David Brownef4f0742021-10-22 17:09:50 -0600421 let size_estimate = self.estimate_size();
422
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300423 let mut protected_tlv: Vec<u8> = vec![];
David Brown187dd882017-07-11 11:15:23 -0600424
David Brown2b73ed92020-01-08 17:01:22 -0700425 if self.protect_size() > 0 {
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300426 protected_tlv.push(0x08);
427 protected_tlv.push(0x69);
David Brown2b73ed92020-01-08 17:01:22 -0700428 let size = self.protect_size();
429 protected_tlv.write_u16::<LittleEndian>(size).unwrap();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300430 for dep in &self.dependencies {
David Brown69721182019-12-04 14:50:52 -0700431 protected_tlv.write_u16::<LittleEndian>(TlvKinds::DEPENDENCY as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700432 protected_tlv.write_u16::<LittleEndian>(12).unwrap();
David Brownf5b33d82017-09-01 10:58:27 -0600433
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300434 // The dependency.
435 protected_tlv.push(dep.id);
David Brownf66b2052021-03-10 05:26:36 -0700436 protected_tlv.push(0);
437 protected_tlv.write_u16::<LittleEndian>(0).unwrap();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300438 protected_tlv.push(dep.version.major);
439 protected_tlv.push(dep.version.minor);
440 protected_tlv.write_u16::<LittleEndian>(dep.version.revision).unwrap();
441 protected_tlv.write_u32::<LittleEndian>(dep.version.build_num).unwrap();
David Brown7a81c4b2019-07-29 15:20:21 -0600442 }
David Brown2b73ed92020-01-08 17:01:22 -0700443
Roland Mikheld6703522023-04-27 14:24:30 +0200444 // Security counter has to be at the protected TLV area also
445 if Caps::HwRollbackProtection.present() && self.security_cnt.is_some() {
446 protected_tlv.write_u16::<LittleEndian>(TlvKinds::SECCNT as u16).unwrap();
447 protected_tlv.write_u16::<LittleEndian>(std::mem::size_of::<u32>() as u16).unwrap();
448 protected_tlv.write_u32::<LittleEndian>(self.security_cnt.unwrap() as u32).unwrap();
449 }
450
David Brown2b73ed92020-01-08 17:01:22 -0700451 assert_eq!(size, protected_tlv.len() as u16, "protected TLV length incorrect");
David Brown7a81c4b2019-07-29 15:20:21 -0600452 }
453
454 // Ring does the signature itself, which means that it must be
455 // given a full, contiguous payload. Although this does help from
456 // a correct usage perspective, it is fairly stupid from an
457 // efficiency view. If this is shown to be a performance issue
458 // with the tests, the protected data could be appended to the
459 // payload, and then removed after the signature is done. For now,
460 // just make a signed payload.
461 let mut sig_payload = self.payload.clone();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300462 sig_payload.extend_from_slice(&protected_tlv);
463
464 let mut result: Vec<u8> = vec![];
465
466 // add back signed payload
467 result.extend_from_slice(&protected_tlv);
468
469 // add non-protected payload
David Brown3dc86c92020-01-08 17:22:55 -0700470 let npro_pos = result.len();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300471 result.push(0x07);
472 result.push(0x69);
David Brown3dc86c92020-01-08 17:22:55 -0700473 // Placeholder for the size.
474 result.write_u16::<LittleEndian>(0).unwrap();
David Brown7a81c4b2019-07-29 15:20:21 -0600475
David Brown187dd882017-07-11 11:15:23 -0600476 if self.kinds.contains(&TlvKinds::SHA256) {
David Browne90b13f2019-12-06 15:04:00 -0700477 // If a signature is not requested, corrupt the hash we are
478 // generating. But, if there is a signature, output the
479 // correct hash. We want the hash test to pass so that the
480 // signature verification can be validated.
481 let mut corrupt_hash = self.gen_corrupted;
482 for k in &[TlvKinds::RSA2048, TlvKinds::RSA3072,
Roland Mikhel30978512023-02-08 14:06:58 +0100483 TlvKinds::ED25519, TlvKinds::ECDSASIG]
David Browne90b13f2019-12-06 15:04:00 -0700484 {
485 if self.kinds.contains(k) {
486 corrupt_hash = false;
487 break;
488 }
489 }
490
491 if corrupt_hash {
492 sig_payload[0] ^= 1;
493 }
494
David Brown7a81c4b2019-07-29 15:20:21 -0600495 let hash = digest::digest(&digest::SHA256, &sig_payload);
David Brown8054ce22017-07-11 12:12:09 -0600496 let hash = hash.as_ref();
David Brown187dd882017-07-11 11:15:23 -0600497
David Brown8054ce22017-07-11 12:12:09 -0600498 assert!(hash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700499 result.write_u16::<LittleEndian>(TlvKinds::SHA256 as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700500 result.write_u16::<LittleEndian>(32).unwrap();
David Brown8054ce22017-07-11 12:12:09 -0600501 result.extend_from_slice(hash);
David Browne90b13f2019-12-06 15:04:00 -0700502
503 // Undo the corruption.
504 if corrupt_hash {
505 sig_payload[0] ^= 1;
506 }
507
508 }
509
510 if self.gen_corrupted {
511 // Corrupt what is signed by modifying the input to the
512 // signature code.
513 sig_payload[0] ^= 1;
David Brown187dd882017-07-11 11:15:23 -0600514 }
515
Fabio Utzig39297432019-05-08 18:51:10 -0300516 if self.kinds.contains(&TlvKinds::RSA2048) ||
517 self.kinds.contains(&TlvKinds::RSA3072) {
518
519 let is_rsa2048 = self.kinds.contains(&TlvKinds::RSA2048);
520
David Brown43cda332017-09-01 09:53:23 -0600521 // Output the hash of the public key.
Fabio Utzig39297432019-05-08 18:51:10 -0300522 let hash = if is_rsa2048 {
523 digest::digest(&digest::SHA256, RSA_PUB_KEY)
524 } else {
525 digest::digest(&digest::SHA256, RSA3072_PUB_KEY)
526 };
David Brown43cda332017-09-01 09:53:23 -0600527 let hash = hash.as_ref();
528
529 assert!(hash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700530 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700531 result.write_u16::<LittleEndian>(32).unwrap();
David Brown43cda332017-09-01 09:53:23 -0600532 result.extend_from_slice(hash);
533
David Brown7e701d82017-07-11 13:24:25 -0600534 // For now assume PSS.
Fabio Utzig39297432019-05-08 18:51:10 -0300535 let key_bytes = if is_rsa2048 {
536 pem::parse(include_bytes!("../../root-rsa-2048.pem").as_ref()).unwrap()
537 } else {
538 pem::parse(include_bytes!("../../root-rsa-3072.pem").as_ref()).unwrap()
539 };
David Brown7e701d82017-07-11 13:24:25 -0600540 assert_eq!(key_bytes.tag, "RSA PRIVATE KEY");
Fabio Utzig90f449e2019-10-24 07:43:53 -0300541 let key_pair = RsaKeyPair::from_der(&key_bytes.contents).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600542 let rng = rand::SystemRandom::new();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300543 let mut signature = vec![0; key_pair.public_modulus_len()];
Fabio Utzig39297432019-05-08 18:51:10 -0300544 if is_rsa2048 {
545 assert_eq!(signature.len(), 256);
546 } else {
547 assert_eq!(signature.len(), 384);
548 }
David Brown7a81c4b2019-07-29 15:20:21 -0600549 key_pair.sign(&RSA_PSS_SHA256, &rng, &sig_payload, &mut signature).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600550
Fabio Utzig39297432019-05-08 18:51:10 -0300551 if is_rsa2048 {
David Brown69721182019-12-04 14:50:52 -0700552 result.write_u16::<LittleEndian>(TlvKinds::RSA2048 as u16).unwrap();
Fabio Utzig39297432019-05-08 18:51:10 -0300553 } else {
David Brown69721182019-12-04 14:50:52 -0700554 result.write_u16::<LittleEndian>(TlvKinds::RSA3072 as u16).unwrap();
Fabio Utzig39297432019-05-08 18:51:10 -0300555 }
David Brown91d68632019-07-29 14:32:13 -0600556 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600557 result.extend_from_slice(&signature);
558 }
559
Roland Mikhel6205c102023-02-06 13:32:02 +0100560 if self.kinds.contains(&TlvKinds::ECDSASIG) {
561 let rng = rand::SystemRandom::new();
562 let keyhash = digest::digest(&digest::SHA256, ECDSA256_PUB_KEY);
563 let key_bytes = pem::parse(include_bytes!("../../root-ec-p256-pkcs8.pem").as_ref()).unwrap();
564 let sign_algo = &ECDSA_P256_SHA256_ASN1_SIGNING;
565 let key_pair = EcdsaKeyPair::from_pkcs8(sign_algo, &key_bytes.contents).unwrap();
566 let signature = key_pair.sign(&rng,&sig_payload).unwrap();
567
568 // Write public key
569 let keyhash_slice = keyhash.as_ref();
570 assert!(keyhash_slice.len() == 32);
571 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
572 result.write_u16::<LittleEndian>(32).unwrap();
573 result.extend_from_slice(keyhash_slice);
574
575 // Write signature
576 result.write_u16::<LittleEndian>(TlvKinds::ECDSASIG as u16).unwrap();
577 let signature = signature.as_ref().to_vec();
578 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
579 result.extend_from_slice(&signature);
580 }
Fabio Utzig97710282019-05-24 17:44:49 -0300581 if self.kinds.contains(&TlvKinds::ED25519) {
582 let keyhash = digest::digest(&digest::SHA256, ED25519_PUB_KEY);
583 let keyhash = keyhash.as_ref();
584
585 assert!(keyhash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700586 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700587 result.write_u16::<LittleEndian>(32).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300588 result.extend_from_slice(keyhash);
589
David Brown7a81c4b2019-07-29 15:20:21 -0600590 let hash = digest::digest(&digest::SHA256, &sig_payload);
Fabio Utzig97710282019-05-24 17:44:49 -0300591 let hash = hash.as_ref();
592 assert!(hash.len() == 32);
593
594 let key_bytes = pem::parse(include_bytes!("../../root-ed25519.pem").as_ref()).unwrap();
595 assert_eq!(key_bytes.tag, "PRIVATE KEY");
596
Fabio Utzig90f449e2019-10-24 07:43:53 -0300597 let key_pair = Ed25519KeyPair::from_seed_and_public_key(
598 &key_bytes.contents[16..48], &ED25519_PUB_KEY[12..44]).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300599 let signature = key_pair.sign(&hash);
600
David Brown69721182019-12-04 14:50:52 -0700601 result.write_u16::<LittleEndian>(TlvKinds::ED25519 as u16).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300602
603 let signature = signature.as_ref().to_vec();
David Brown91d68632019-07-29 14:32:13 -0600604 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300605 result.extend_from_slice(signature.as_ref());
606 }
607
Fabio Utzig1e48b912018-09-18 09:04:18 -0300608 if self.kinds.contains(&TlvKinds::ENCRSA2048) {
609 let key_bytes = pem::parse(include_bytes!("../../enc-rsa2048-pub.pem")
610 .as_ref()).unwrap();
611 assert_eq!(key_bytes.tag, "PUBLIC KEY");
612
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300613 let cipherkey = self.get_enc_key();
614 let cipherkey = cipherkey.as_slice();
615 let encbuf = match c::rsa_oaep_encrypt(&key_bytes.contents, cipherkey) {
Fabio Utzig1e48b912018-09-18 09:04:18 -0300616 Ok(v) => v,
617 Err(_) => panic!("Failed to encrypt secret key"),
618 };
619
620 assert!(encbuf.len() == 256);
David Brown69721182019-12-04 14:50:52 -0700621 result.write_u16::<LittleEndian>(TlvKinds::ENCRSA2048 as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700622 result.write_u16::<LittleEndian>(256).unwrap();
Fabio Utzig1e48b912018-09-18 09:04:18 -0300623 result.extend_from_slice(&encbuf);
624 }
625
Salome Thirot0f641972021-05-14 11:19:55 +0100626 if self.kinds.contains(&TlvKinds::ENCKW) {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100627 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
628 let aes256 = (self.get_flags() & flag) == flag;
629 let key_bytes = if aes256 {
630 base64::decode(
631 include_str!("../../enc-aes256kw.b64").trim()).unwrap()
632 } else {
633 base64::decode(
634 include_str!("../../enc-aes128kw.b64").trim()).unwrap()
635 };
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300636 let cipherkey = self.get_enc_key();
637 let cipherkey = cipherkey.as_slice();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100638 let keylen = if aes256 { 32 } else { 16 };
639 let encbuf = match c::kw_encrypt(&key_bytes, cipherkey, keylen) {
Fabio Utzig1e48b912018-09-18 09:04:18 -0300640 Ok(v) => v,
641 Err(_) => panic!("Failed to encrypt secret key"),
642 };
643
Salome Thirot6fdbf552021-05-14 16:46:14 +0100644 let size = if aes256 { 40 } else { 24 };
645 assert!(encbuf.len() == size);
Salome Thirot0f641972021-05-14 11:19:55 +0100646 result.write_u16::<LittleEndian>(TlvKinds::ENCKW as u16).unwrap();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100647 result.write_u16::<LittleEndian>(size as u16).unwrap();
Fabio Utzig1e48b912018-09-18 09:04:18 -0300648 result.extend_from_slice(&encbuf);
649 }
650
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300651 if self.kinds.contains(&TlvKinds::ENCEC256) || self.kinds.contains(&TlvKinds::ENCX25519) {
652 let key_bytes = if self.kinds.contains(&TlvKinds::ENCEC256) {
653 pem::parse(include_bytes!("../../enc-ec256-pub.pem").as_ref()).unwrap()
654 } else {
655 pem::parse(include_bytes!("../../enc-x25519-pub.pem").as_ref()).unwrap()
656 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300657 assert_eq!(key_bytes.tag, "PUBLIC KEY");
Fabio Utzig90f449e2019-10-24 07:43:53 -0300658 let rng = rand::SystemRandom::new();
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300659 let alg = if self.kinds.contains(&TlvKinds::ENCEC256) {
660 &agreement::ECDH_P256
661 } else {
662 &agreement::X25519
663 };
664 let pk = match agreement::EphemeralPrivateKey::generate(alg, &rng) {
Fabio Utzig90f449e2019-10-24 07:43:53 -0300665 Ok(v) => v,
666 Err(_) => panic!("Failed to generate ephemeral keypair"),
667 };
668
669 let pubk = match pk.compute_public_key() {
670 Ok(pubk) => pubk,
671 Err(_) => panic!("Failed computing ephemeral public key"),
672 };
673
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300674 let peer_pubk = if self.kinds.contains(&TlvKinds::ENCEC256) {
675 agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, &key_bytes.contents[26..])
676 } else {
677 agreement::UnparsedPublicKey::new(&agreement::X25519, &key_bytes.contents[12..])
678 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300679
680 #[derive(Debug, PartialEq)]
681 struct OkmLen<T: core::fmt::Debug + PartialEq>(T);
682
683 impl hkdf::KeyType for OkmLen<usize> {
684 fn len(&self) -> usize {
685 self.0
686 }
687 }
688
Salome Thirot6fdbf552021-05-14 16:46:14 +0100689 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
690 let aes256 = (self.get_flags() & flag) == flag;
691
Fabio Utzig90f449e2019-10-24 07:43:53 -0300692 let derived_key = match agreement::agree_ephemeral(
693 pk, &peer_pubk, ring::error::Unspecified, |shared| {
694 let salt = hkdf::Salt::new(hkdf::HKDF_SHA256, &[]);
695 let prk = salt.extract(&shared);
Salome Thirot6fdbf552021-05-14 16:46:14 +0100696 let okm_len = if aes256 { 64 } else { 48 };
697 let okm = match prk.expand(&[b"MCUBoot_ECIES_v1"], OkmLen(okm_len)) {
Fabio Utzig90f449e2019-10-24 07:43:53 -0300698 Ok(okm) => okm,
699 Err(_) => panic!("Failed building HKDF OKM"),
700 };
Salome Thirot6fdbf552021-05-14 16:46:14 +0100701 let mut buf = if aes256 { vec![0u8; 64] } else { vec![0u8; 48] };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300702 match okm.fill(&mut buf) {
703 Ok(_) => Ok(buf),
704 Err(_) => panic!("Failed generating HKDF output"),
705 }
706 },
707 ) {
708 Ok(v) => v,
709 Err(_) => panic!("Failed building HKDF"),
710 };
711
Fabio Utzig90f449e2019-10-24 07:43:53 -0300712 let nonce = GenericArray::from_slice(&[0; 16]);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300713 let mut cipherkey = self.get_enc_key();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100714 if aes256 {
715 let key: &GenericArray<u8, U32> = GenericArray::from_slice(&derived_key[..32]);
David Brown9c6322f2021-08-19 13:03:39 -0600716 let block = Aes256::new(&key);
717 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +0100718 cipher.apply_keystream(&mut cipherkey);
719 } else {
720 let key: &GenericArray<u8, U16> = GenericArray::from_slice(&derived_key[..16]);
David Brown9c6322f2021-08-19 13:03:39 -0600721 let block = Aes128::new(&key);
722 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +0100723 cipher.apply_keystream(&mut cipherkey);
724 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300725
Salome Thirot6fdbf552021-05-14 16:46:14 +0100726 let size = if aes256 { 32 } else { 16 };
727 let key = hmac::Key::new(hmac::HMAC_SHA256, &derived_key[size..]);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300728 let tag = hmac::sign(&key, &cipherkey);
729
730 let mut buf = vec![];
731 buf.append(&mut pubk.as_ref().to_vec());
732 buf.append(&mut tag.as_ref().to_vec());
733 buf.append(&mut cipherkey);
734
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300735 if self.kinds.contains(&TlvKinds::ENCEC256) {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100736 let size = if aes256 { 129 } else { 113 };
737 assert!(buf.len() == size);
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300738 result.write_u16::<LittleEndian>(TlvKinds::ENCEC256 as u16).unwrap();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100739 result.write_u16::<LittleEndian>(size as u16).unwrap();
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300740 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100741 let size = if aes256 { 96 } else { 80 };
742 assert!(buf.len() == size);
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300743 result.write_u16::<LittleEndian>(TlvKinds::ENCX25519 as u16).unwrap();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100744 result.write_u16::<LittleEndian>(size as u16).unwrap();
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300745 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300746 result.extend_from_slice(&buf);
747 }
748
David Brown3dc86c92020-01-08 17:22:55 -0700749 // Patch the size back into the TLV header.
750 let size = (result.len() - npro_pos) as u16;
751 let mut size_buf = &mut result[npro_pos + 2 .. npro_pos + 4];
752 size_buf.write_u16::<LittleEndian>(size).unwrap();
753
David Brownb408b432021-10-27 15:55:39 -0600754 // ECDSA is stored as an ASN.1 integer. For a 128-bit value, this maximally results in 33
755 // bytes of storage for each of the two values. If the high bit is zero, it will take 32
756 // bytes, if the top 8 bits are zero, it will take 31 bits, and so on. The smaller size
757 // will occur with decreasing likelihood. We'll allow this to get a bit smaller, hopefully
758 // allowing the tests to pass with false failures rare. For this case, we'll handle up to
759 // the top 16 bits of both numbers being all zeros (1 in 2^32).
760 if !Caps::has_ecdsa() {
761 if size_estimate != result.len() {
762 panic!("Incorrect size estimate: {} (actual {})", size_estimate, result.len());
763 }
764 } else {
765 if size_estimate < result.len() || size_estimate > result.len() + 6 {
766 panic!("Incorrect size estimate: {} (actual {})", size_estimate, result.len());
767 }
David Brownef4f0742021-10-22 17:09:50 -0600768 }
769 if size_estimate != result.len() {
770 log::warn!("Size off: {} actual {}", size_estimate, result.len());
771 }
772
David Brown187dd882017-07-11 11:15:23 -0600773 result
774 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300775
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300776 fn generate_enc_key(&mut self) {
777 let rng = rand::SystemRandom::new();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100778 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
779 let aes256 = (self.get_flags() & flag) == flag;
780 let mut buf = if aes256 {
781 vec![0u8; 32]
782 } else {
783 vec![0u8; 16]
784 };
David Brown26edaf32021-03-10 05:27:38 -0700785 if rng.fill(&mut buf).is_err() {
786 panic!("Error generating encrypted key");
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300787 }
788 info!("New encryption key: {:02x?}", buf);
789 self.enc_key = buf;
Fabio Utzig90f449e2019-10-24 07:43:53 -0300790 }
791
792 fn get_enc_key(&self) -> Vec<u8> {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100793 if self.enc_key.len() != 32 && self.enc_key.len() != 16 {
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300794 panic!("No random key was generated");
795 }
796 self.enc_key.clone()
Fabio Utzig90f449e2019-10-24 07:43:53 -0300797 }
Roland Mikheld6703522023-04-27 14:24:30 +0200798
799 fn set_security_counter(&mut self, security_cnt: Option<u32>) {
800 self.security_cnt = security_cnt;
801 }
Roland Mikhel6945bb62023-04-11 15:57:49 +0200802
803 fn set_ignore_ram_load_flag(&mut self) {
804 self.ignore_ram_load_flag = true;
805 }
David Brown187dd882017-07-11 11:15:23 -0600806}
David Brown43cda332017-09-01 09:53:23 -0600807
808include!("rsa_pub_key-rs.txt");
Fabio Utzig39297432019-05-08 18:51:10 -0300809include!("rsa3072_pub_key-rs.txt");
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200810include!("ecdsa_pub_key-rs.txt");
Fabio Utzig97710282019-05-24 17:44:49 -0300811include!("ed25519_pub_key-rs.txt");