blob: 9a7e14f99d5308506a2e3819dc875bdc848af2eb [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,
Roland Mikhel5899fac2023-03-14 13:59:55 +010032 ECDSA_P384_SHA384_ASN1_SIGNING,
Fabio Utzig05ab0142018-07-10 09:15:28 -030033};
David Brown9c6322f2021-08-19 13:03:39 -060034use aes::{
35 Aes128,
Fabio Utzig90f449e2019-10-24 07:43:53 -030036 Aes128Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060037 Aes256,
Salome Thirot6fdbf552021-05-14 16:46:14 +010038 Aes256Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060039 NewBlockCipher
40};
41use cipher::{
42 generic_array::GenericArray,
43 StreamCipher,
Fabio Utzig90f449e2019-10-24 07:43:53 -030044};
Fabio Utzig80fde2f2017-12-05 09:25:31 -020045use mcuboot_sys::c;
Salome Thirot6fdbf552021-05-14 16:46:14 +010046use typenum::{U16, U32};
David Brown187dd882017-07-11 11:15:23 -060047
David Brown69721182019-12-04 14:50:52 -070048#[repr(u16)]
David Brownc3898d62019-08-05 14:20:02 -060049#[derive(Copy, Clone, Debug, PartialEq, Eq)]
David Brown187dd882017-07-11 11:15:23 -060050#[allow(dead_code)] // TODO: For now
51pub enum TlvKinds {
David Brown43cda332017-09-01 09:53:23 -060052 KEYHASH = 0x01,
David Brown27648b82017-08-31 10:40:29 -060053 SHA256 = 0x10,
54 RSA2048 = 0x20,
David Vincze4395b802023-04-27 16:11:49 +020055 ECDSASIG = 0x22,
Fabio Utzig39297432019-05-08 18:51:10 -030056 RSA3072 = 0x23,
Fabio Utzig97710282019-05-24 17:44:49 -030057 ED25519 = 0x24,
Fabio Utzig1e48b912018-09-18 09:04:18 -030058 ENCRSA2048 = 0x30,
Salome Thirot0f641972021-05-14 11:19:55 +010059 ENCKW = 0x31,
Fabio Utzig90f449e2019-10-24 07:43:53 -030060 ENCEC256 = 0x32,
Fabio Utzig3fa72ca2020-04-02 11:20:37 -030061 ENCX25519 = 0x33,
David Brown7a81c4b2019-07-29 15:20:21 -060062 DEPENDENCY = 0x40,
Roland Mikheld6703522023-04-27 14:24:30 +020063 SECCNT = 0x50,
Fabio Utzig1e48b912018-09-18 09:04:18 -030064}
65
66#[allow(dead_code, non_camel_case_types)]
67pub enum TlvFlags {
68 PIC = 0x01,
69 NON_BOOTABLE = 0x02,
Salome Thirot6fdbf552021-05-14 16:46:14 +010070 ENCRYPTED_AES128 = 0x04,
Salome Thirot6fdbf552021-05-14 16:46:14 +010071 ENCRYPTED_AES256 = 0x08,
David Brownd8713a52021-10-22 16:27:23 -060072 RAM_LOAD = 0x20,
David Brown187dd882017-07-11 11:15:23 -060073}
74
David Brown43643dd2019-01-11 15:43:28 -070075/// A generator for manifests. The format of the manifest can be either a
76/// traditional "TLV" or a SUIT-style manifest.
77pub trait ManifestGen {
David Brownac46e262019-01-11 15:46:18 -070078 /// Retrieve the header magic value for this manifest type.
79 fn get_magic(&self) -> u32;
80
David Brown43643dd2019-01-11 15:43:28 -070081 /// Retrieve the flags value for this particular manifest type.
82 fn get_flags(&self) -> u32;
83
David Brown7a81c4b2019-07-29 15:20:21 -060084 /// Retrieve the number of bytes of this manifest that is "protected".
85 /// This field is stored in the outside image header instead of the
86 /// manifest header.
87 fn protect_size(&self) -> u16;
88
89 /// Add a dependency on another image.
90 fn add_dependency(&mut self, id: u8, version: &ImageVersion);
91
David Brown43643dd2019-01-11 15:43:28 -070092 /// Add a sequence of bytes to the payload that the manifest is
93 /// protecting.
94 fn add_bytes(&mut self, bytes: &[u8]);
95
David Browne90b13f2019-12-06 15:04:00 -070096 /// Set an internal flag indicating that the next `make_tlv` should
97 /// corrupt the signature.
98 fn corrupt_sig(&mut self);
99
David Brownef4f0742021-10-22 17:09:50 -0600100 /// Estimate the size of the TLV. This can be called before the payload is added (but after
101 /// other information is added). Some of the signature algorithms can generate variable sized
102 /// data, and therefore, this can slightly overestimate the size.
103 fn estimate_size(&self) -> usize;
104
David Brown43643dd2019-01-11 15:43:28 -0700105 /// Construct the manifest for this payload.
106 fn make_tlv(self: Box<Self>) -> Vec<u8>;
Fabio Utzig90f449e2019-10-24 07:43:53 -0300107
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300108 /// Generate a new encryption random key
109 fn generate_enc_key(&mut self);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300110
111 /// Return the current encryption key
112 fn get_enc_key(&self) -> Vec<u8>;
Roland Mikheld6703522023-04-27 14:24:30 +0200113
114 /// Set the security counter to the specified value.
115 fn set_security_counter(&mut self, security_cnt: Option<u32>);
Roland Mikhel6945bb62023-04-11 15:57:49 +0200116
117 /// Sets the ignore_ram_load_flag so that can be validated when it is missing,
118 /// it will not load successfully.
119 fn set_ignore_ram_load_flag(&mut self);
David Brown43643dd2019-01-11 15:43:28 -0700120}
121
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300122#[derive(Debug, Default)]
David Brown187dd882017-07-11 11:15:23 -0600123pub struct TlvGen {
David Brown43cda332017-09-01 09:53:23 -0600124 flags: u32,
David Brown187dd882017-07-11 11:15:23 -0600125 kinds: Vec<TlvKinds>,
David Brown4243ab02017-07-11 12:24:23 -0600126 payload: Vec<u8>,
David Brown7a81c4b2019-07-29 15:20:21 -0600127 dependencies: Vec<Dependency>,
Fabio Utzig90f449e2019-10-24 07:43:53 -0300128 enc_key: Vec<u8>,
David Browne90b13f2019-12-06 15:04:00 -0700129 /// Should this signature be corrupted.
130 gen_corrupted: bool,
Roland Mikheld6703522023-04-27 14:24:30 +0200131 security_cnt: Option<u32>,
Roland Mikhel6945bb62023-04-11 15:57:49 +0200132 /// Ignore RAM_LOAD flag
133 ignore_ram_load_flag: bool,
David Brown7a81c4b2019-07-29 15:20:21 -0600134}
135
David Brownc3898d62019-08-05 14:20:02 -0600136#[derive(Debug)]
David Brown7a81c4b2019-07-29 15:20:21 -0600137struct Dependency {
138 id: u8,
139 version: ImageVersion,
David Brown187dd882017-07-11 11:15:23 -0600140}
141
142impl TlvGen {
143 /// Construct a new tlv generator that will only contain a hash of the data.
David Brown7e701d82017-07-11 13:24:25 -0600144 #[allow(dead_code)]
David Brown187dd882017-07-11 11:15:23 -0600145 pub fn new_hash_only() -> TlvGen {
146 TlvGen {
David Brown187dd882017-07-11 11:15:23 -0600147 kinds: vec![TlvKinds::SHA256],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300148 ..Default::default()
David Brown187dd882017-07-11 11:15:23 -0600149 }
150 }
151
David Brown7e701d82017-07-11 13:24:25 -0600152 #[allow(dead_code)]
153 pub fn new_rsa_pss() -> TlvGen {
154 TlvGen {
Fabio Utzig754438d2018-12-14 06:39:58 -0200155 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300156 ..Default::default()
David Brown7e701d82017-07-11 13:24:25 -0600157 }
158 }
159
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200160 #[allow(dead_code)]
Fabio Utzig39297432019-05-08 18:51:10 -0300161 pub fn new_rsa3072_pss() -> TlvGen {
162 TlvGen {
Fabio Utzig39297432019-05-08 18:51:10 -0300163 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA3072],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300164 ..Default::default()
Fabio Utzig39297432019-05-08 18:51:10 -0300165 }
166 }
167
168 #[allow(dead_code)]
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200169 pub fn new_ecdsa() -> TlvGen {
170 TlvGen {
Roland Mikhel30978512023-02-08 14:06:58 +0100171 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSASIG],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300172 ..Default::default()
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200173 }
174 }
175
Fabio Utzig1e48b912018-09-18 09:04:18 -0300176 #[allow(dead_code)]
Fabio Utzig97710282019-05-24 17:44:49 -0300177 pub fn new_ed25519() -> TlvGen {
178 TlvGen {
Fabio Utzig97710282019-05-24 17:44:49 -0300179 kinds: vec![TlvKinds::SHA256, TlvKinds::ED25519],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300180 ..Default::default()
Fabio Utzig97710282019-05-24 17:44:49 -0300181 }
182 }
183
184 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100185 pub fn new_enc_rsa(aes_key_size: u32) -> TlvGen {
186 let flag = if aes_key_size == 256 {
187 TlvFlags::ENCRYPTED_AES256 as u32
188 } else {
189 TlvFlags::ENCRYPTED_AES128 as u32
190 };
Fabio Utzig1e48b912018-09-18 09:04:18 -0300191 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100192 flags: flag,
Fabio Utzig1e48b912018-09-18 09:04:18 -0300193 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCRSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300194 ..Default::default()
Fabio Utzig1e48b912018-09-18 09:04:18 -0300195 }
196 }
197
198 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100199 pub fn new_sig_enc_rsa(aes_key_size: u32) -> TlvGen {
200 let flag = if aes_key_size == 256 {
201 TlvFlags::ENCRYPTED_AES256 as u32
202 } else {
203 TlvFlags::ENCRYPTED_AES128 as u32
204 };
Fabio Utzig754438d2018-12-14 06:39:58 -0200205 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100206 flags: flag,
Fabio Utzig754438d2018-12-14 06:39:58 -0200207 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048, TlvKinds::ENCRSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300208 ..Default::default()
Fabio Utzig754438d2018-12-14 06:39:58 -0200209 }
210 }
211
212 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100213 pub fn new_enc_kw(aes_key_size: u32) -> TlvGen {
214 let flag = if aes_key_size == 256 {
215 TlvFlags::ENCRYPTED_AES256 as u32
216 } else {
217 TlvFlags::ENCRYPTED_AES128 as u32
218 };
Fabio Utzig1e48b912018-09-18 09:04:18 -0300219 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100220 flags: flag,
Salome Thirot0f641972021-05-14 11:19:55 +0100221 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300222 ..Default::default()
Fabio Utzig1e48b912018-09-18 09:04:18 -0300223 }
224 }
225
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200226 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100227 pub fn new_rsa_kw(aes_key_size: u32) -> TlvGen {
228 let flag = if aes_key_size == 256 {
229 TlvFlags::ENCRYPTED_AES256 as u32
230 } else {
231 TlvFlags::ENCRYPTED_AES128 as u32
232 };
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200233 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100234 flags: flag,
Salome Thirot0f641972021-05-14 11:19:55 +0100235 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300236 ..Default::default()
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200237 }
238 }
239
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200240 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100241 pub fn new_ecdsa_kw(aes_key_size: u32) -> TlvGen {
242 let flag = if aes_key_size == 256 {
243 TlvFlags::ENCRYPTED_AES256 as u32
244 } else {
245 TlvFlags::ENCRYPTED_AES128 as u32
246 };
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200247 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100248 flags: flag,
Roland Mikhel30978512023-02-08 14:06:58 +0100249 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSASIG, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300250 ..Default::default()
Fabio Utzig90f449e2019-10-24 07:43:53 -0300251 }
252 }
253
254 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100255 pub fn new_ecies_p256(aes_key_size: u32) -> TlvGen {
256 let flag = if aes_key_size == 256 {
257 TlvFlags::ENCRYPTED_AES256 as u32
258 } else {
259 TlvFlags::ENCRYPTED_AES128 as u32
260 };
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300261 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100262 flags: flag,
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300263 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCEC256],
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300264 ..Default::default()
265 }
266 }
267
268 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100269 pub fn new_ecdsa_ecies_p256(aes_key_size: u32) -> TlvGen {
270 let flag = if aes_key_size == 256 {
271 TlvFlags::ENCRYPTED_AES256 as u32
272 } else {
273 TlvFlags::ENCRYPTED_AES128 as u32
274 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300275 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100276 flags: flag,
Roland Mikhel30978512023-02-08 14:06:58 +0100277 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSASIG, TlvKinds::ENCEC256],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300278 ..Default::default()
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200279 }
280 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300281
282 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100283 pub fn new_ecies_x25519(aes_key_size: u32) -> TlvGen {
284 let flag = if aes_key_size == 256 {
285 TlvFlags::ENCRYPTED_AES256 as u32
286 } else {
287 TlvFlags::ENCRYPTED_AES128 as u32
288 };
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300289 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100290 flags: flag,
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300291 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCX25519],
292 ..Default::default()
293 }
294 }
295
296 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100297 pub fn new_ed25519_ecies_x25519(aes_key_size: u32) -> TlvGen {
298 let flag = if aes_key_size == 256 {
299 TlvFlags::ENCRYPTED_AES256 as u32
300 } else {
301 TlvFlags::ENCRYPTED_AES128 as u32
302 };
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300303 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100304 flags: flag,
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300305 kinds: vec![TlvKinds::SHA256, TlvKinds::ED25519, TlvKinds::ENCX25519],
306 ..Default::default()
307 }
308 }
Roland Mikheld6703522023-04-27 14:24:30 +0200309
310 #[allow(dead_code)]
311 pub fn new_sec_cnt() -> TlvGen {
312 TlvGen {
313 kinds: vec![TlvKinds::SHA256, TlvKinds::SECCNT],
314 ..Default::default()
315 }
316 }
317
David Brown43643dd2019-01-11 15:43:28 -0700318}
319
320impl ManifestGen for TlvGen {
David Brownac46e262019-01-11 15:46:18 -0700321 fn get_magic(&self) -> u32 {
322 0x96f3b83d
323 }
324
David Brown43643dd2019-01-11 15:43:28 -0700325 /// Retrieve the header flags for this configuration. This can be called at any time.
326 fn get_flags(&self) -> u32 {
David Brown8a4e23b2021-06-11 10:29:01 -0600327 // For the RamLoad case, add in the flag for this feature.
Roland Mikhel6945bb62023-04-11 15:57:49 +0200328 if Caps::RamLoad.present() && !self.ignore_ram_load_flag {
David Brown8a4e23b2021-06-11 10:29:01 -0600329 self.flags | (TlvFlags::RAM_LOAD as u32)
330 } else {
331 self.flags
332 }
David Brown43643dd2019-01-11 15:43:28 -0700333 }
David Brown187dd882017-07-11 11:15:23 -0600334
335 /// Add bytes to the covered hash.
David Brown43643dd2019-01-11 15:43:28 -0700336 fn add_bytes(&mut self, bytes: &[u8]) {
David Brown4243ab02017-07-11 12:24:23 -0600337 self.payload.extend_from_slice(bytes);
David Brown187dd882017-07-11 11:15:23 -0600338 }
339
David Brown7a81c4b2019-07-29 15:20:21 -0600340 fn protect_size(&self) -> u16 {
Roland Mikheld6703522023-04-27 14:24:30 +0200341 let mut size = 0;
342 if !self.dependencies.is_empty() || (Caps::HwRollbackProtection.present() && self.security_cnt.is_some()) {
343 // include the TLV area header.
344 size += 4;
345 // add space for each dependency.
346 size += (self.dependencies.len() as u16) * (4 + std::mem::size_of::<Dependency>() as u16);
347 if Caps::HwRollbackProtection.present() && self.security_cnt.is_some() {
348 size += 4 + 4;
349 }
David Brown7a81c4b2019-07-29 15:20:21 -0600350 }
Roland Mikheld6703522023-04-27 14:24:30 +0200351 size
David Brown7a81c4b2019-07-29 15:20:21 -0600352 }
353
354 fn add_dependency(&mut self, id: u8, version: &ImageVersion) {
David Brown7a81c4b2019-07-29 15:20:21 -0600355 self.dependencies.push(Dependency {
David Brown4dfb33c2021-03-10 05:15:45 -0700356 id,
David Brown7a81c4b2019-07-29 15:20:21 -0600357 version: version.clone(),
358 });
359 }
360
David Browne90b13f2019-12-06 15:04:00 -0700361 fn corrupt_sig(&mut self) {
362 self.gen_corrupted = true;
363 }
364
David Brownef4f0742021-10-22 17:09:50 -0600365 fn estimate_size(&self) -> usize {
366 // Begin the estimate with the 4 byte header.
367 let mut estimate = 4;
368 // A very poor estimate.
369
370 // Estimate the size of the image hash.
371 if self.kinds.contains(&TlvKinds::SHA256) {
372 estimate += 4 + 32;
373 }
374
375 // Add an estimate in for each of the signature algorithms.
376 if self.kinds.contains(&TlvKinds::RSA2048) {
377 estimate += 4 + 32; // keyhash
378 estimate += 4 + 256; // RSA2048
379 }
380 if self.kinds.contains(&TlvKinds::RSA3072) {
381 estimate += 4 + 32; // keyhash
382 estimate += 4 + 384; // RSA3072
383 }
David Brownef4f0742021-10-22 17:09:50 -0600384 if self.kinds.contains(&TlvKinds::ED25519) {
385 estimate += 4 + 32; // keyhash
386 estimate += 4 + 64; // ED25519 signature.
387 }
Roland Mikhel6205c102023-02-06 13:32:02 +0100388 if self.kinds.contains(&TlvKinds::ECDSASIG) {
Roland Mikhel5899fac2023-03-14 13:59:55 +0100389 // ECDSA signatures are encoded as ASN.1 with the x and y values
390 // stored as signed integers. As such, the size can vary by 2 bytes,
391 // if for example the 256-bit value has the high bit, it takes an
392 // extra 0 byte to avoid it being seen as a negative number.
393 if cfg!(feature = "use-p384-curve") {
394 estimate += 4 + 48; // keyhash
395 estimate += 4 + 104; // ECDSA384 (varies)
396 } else {
397 estimate += 4 + 32; // keyhash
398 estimate += 4 + 72; // ECDSA256 (varies)
399 }
Roland Mikhel6205c102023-02-06 13:32:02 +0100400 }
David Brownef4f0742021-10-22 17:09:50 -0600401
402 // Estimate encryption.
403 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
404 let aes256 = (self.get_flags() & flag) == flag;
405
406 if self.kinds.contains(&TlvKinds::ENCRSA2048) {
407 estimate += 4 + 256;
408 }
409 if self.kinds.contains(&TlvKinds::ENCKW) {
410 estimate += 4 + if aes256 { 40 } else { 24 };
411 }
412 if self.kinds.contains(&TlvKinds::ENCEC256) {
413 estimate += 4 + if aes256 { 129 } else { 113 };
414 }
415 if self.kinds.contains(&TlvKinds::ENCX25519) {
416 estimate += 4 + if aes256 { 96 } else { 80 };
417 }
418
Roland Mikheld6703522023-04-27 14:24:30 +0200419 // Gather the size of the protected TLV area.
420 estimate += self.protect_size() as usize;
David Brownef4f0742021-10-22 17:09:50 -0600421
422 estimate
423 }
424
David Brown187dd882017-07-11 11:15:23 -0600425 /// Compute the TLV given the specified block of data.
David Brown43643dd2019-01-11 15:43:28 -0700426 fn make_tlv(self: Box<Self>) -> Vec<u8> {
David Brownef4f0742021-10-22 17:09:50 -0600427 let size_estimate = self.estimate_size();
428
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300429 let mut protected_tlv: Vec<u8> = vec![];
David Brown187dd882017-07-11 11:15:23 -0600430
David Brown2b73ed92020-01-08 17:01:22 -0700431 if self.protect_size() > 0 {
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300432 protected_tlv.push(0x08);
433 protected_tlv.push(0x69);
David Brown2b73ed92020-01-08 17:01:22 -0700434 let size = self.protect_size();
435 protected_tlv.write_u16::<LittleEndian>(size).unwrap();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300436 for dep in &self.dependencies {
David Brown69721182019-12-04 14:50:52 -0700437 protected_tlv.write_u16::<LittleEndian>(TlvKinds::DEPENDENCY as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700438 protected_tlv.write_u16::<LittleEndian>(12).unwrap();
David Brownf5b33d82017-09-01 10:58:27 -0600439
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300440 // The dependency.
441 protected_tlv.push(dep.id);
David Brownf66b2052021-03-10 05:26:36 -0700442 protected_tlv.push(0);
443 protected_tlv.write_u16::<LittleEndian>(0).unwrap();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300444 protected_tlv.push(dep.version.major);
445 protected_tlv.push(dep.version.minor);
446 protected_tlv.write_u16::<LittleEndian>(dep.version.revision).unwrap();
447 protected_tlv.write_u32::<LittleEndian>(dep.version.build_num).unwrap();
David Brown7a81c4b2019-07-29 15:20:21 -0600448 }
David Brown2b73ed92020-01-08 17:01:22 -0700449
Roland Mikheld6703522023-04-27 14:24:30 +0200450 // Security counter has to be at the protected TLV area also
451 if Caps::HwRollbackProtection.present() && self.security_cnt.is_some() {
452 protected_tlv.write_u16::<LittleEndian>(TlvKinds::SECCNT as u16).unwrap();
453 protected_tlv.write_u16::<LittleEndian>(std::mem::size_of::<u32>() as u16).unwrap();
454 protected_tlv.write_u32::<LittleEndian>(self.security_cnt.unwrap() as u32).unwrap();
455 }
456
David Brown2b73ed92020-01-08 17:01:22 -0700457 assert_eq!(size, protected_tlv.len() as u16, "protected TLV length incorrect");
David Brown7a81c4b2019-07-29 15:20:21 -0600458 }
459
460 // Ring does the signature itself, which means that it must be
461 // given a full, contiguous payload. Although this does help from
462 // a correct usage perspective, it is fairly stupid from an
463 // efficiency view. If this is shown to be a performance issue
464 // with the tests, the protected data could be appended to the
465 // payload, and then removed after the signature is done. For now,
466 // just make a signed payload.
467 let mut sig_payload = self.payload.clone();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300468 sig_payload.extend_from_slice(&protected_tlv);
469
470 let mut result: Vec<u8> = vec![];
471
472 // add back signed payload
473 result.extend_from_slice(&protected_tlv);
474
475 // add non-protected payload
David Brown3dc86c92020-01-08 17:22:55 -0700476 let npro_pos = result.len();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300477 result.push(0x07);
478 result.push(0x69);
David Brown3dc86c92020-01-08 17:22:55 -0700479 // Placeholder for the size.
480 result.write_u16::<LittleEndian>(0).unwrap();
David Brown7a81c4b2019-07-29 15:20:21 -0600481
David Brown187dd882017-07-11 11:15:23 -0600482 if self.kinds.contains(&TlvKinds::SHA256) {
David Browne90b13f2019-12-06 15:04:00 -0700483 // If a signature is not requested, corrupt the hash we are
484 // generating. But, if there is a signature, output the
485 // correct hash. We want the hash test to pass so that the
486 // signature verification can be validated.
487 let mut corrupt_hash = self.gen_corrupted;
488 for k in &[TlvKinds::RSA2048, TlvKinds::RSA3072,
Roland Mikhel30978512023-02-08 14:06:58 +0100489 TlvKinds::ED25519, TlvKinds::ECDSASIG]
David Browne90b13f2019-12-06 15:04:00 -0700490 {
491 if self.kinds.contains(k) {
492 corrupt_hash = false;
493 break;
494 }
495 }
496
497 if corrupt_hash {
498 sig_payload[0] ^= 1;
499 }
500
David Brown7a81c4b2019-07-29 15:20:21 -0600501 let hash = digest::digest(&digest::SHA256, &sig_payload);
David Brown8054ce22017-07-11 12:12:09 -0600502 let hash = hash.as_ref();
David Brown187dd882017-07-11 11:15:23 -0600503
David Brown8054ce22017-07-11 12:12:09 -0600504 assert!(hash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700505 result.write_u16::<LittleEndian>(TlvKinds::SHA256 as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700506 result.write_u16::<LittleEndian>(32).unwrap();
David Brown8054ce22017-07-11 12:12:09 -0600507 result.extend_from_slice(hash);
David Browne90b13f2019-12-06 15:04:00 -0700508
509 // Undo the corruption.
510 if corrupt_hash {
511 sig_payload[0] ^= 1;
512 }
513
514 }
515
516 if self.gen_corrupted {
517 // Corrupt what is signed by modifying the input to the
518 // signature code.
519 sig_payload[0] ^= 1;
David Brown187dd882017-07-11 11:15:23 -0600520 }
521
Fabio Utzig39297432019-05-08 18:51:10 -0300522 if self.kinds.contains(&TlvKinds::RSA2048) ||
523 self.kinds.contains(&TlvKinds::RSA3072) {
524
525 let is_rsa2048 = self.kinds.contains(&TlvKinds::RSA2048);
526
David Brown43cda332017-09-01 09:53:23 -0600527 // Output the hash of the public key.
Fabio Utzig39297432019-05-08 18:51:10 -0300528 let hash = if is_rsa2048 {
529 digest::digest(&digest::SHA256, RSA_PUB_KEY)
530 } else {
531 digest::digest(&digest::SHA256, RSA3072_PUB_KEY)
532 };
David Brown43cda332017-09-01 09:53:23 -0600533 let hash = hash.as_ref();
534
535 assert!(hash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700536 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700537 result.write_u16::<LittleEndian>(32).unwrap();
David Brown43cda332017-09-01 09:53:23 -0600538 result.extend_from_slice(hash);
539
David Brown7e701d82017-07-11 13:24:25 -0600540 // For now assume PSS.
Fabio Utzig39297432019-05-08 18:51:10 -0300541 let key_bytes = if is_rsa2048 {
542 pem::parse(include_bytes!("../../root-rsa-2048.pem").as_ref()).unwrap()
543 } else {
544 pem::parse(include_bytes!("../../root-rsa-3072.pem").as_ref()).unwrap()
545 };
David Brown7e701d82017-07-11 13:24:25 -0600546 assert_eq!(key_bytes.tag, "RSA PRIVATE KEY");
Fabio Utzig90f449e2019-10-24 07:43:53 -0300547 let key_pair = RsaKeyPair::from_der(&key_bytes.contents).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600548 let rng = rand::SystemRandom::new();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300549 let mut signature = vec![0; key_pair.public_modulus_len()];
Fabio Utzig39297432019-05-08 18:51:10 -0300550 if is_rsa2048 {
551 assert_eq!(signature.len(), 256);
552 } else {
553 assert_eq!(signature.len(), 384);
554 }
David Brown7a81c4b2019-07-29 15:20:21 -0600555 key_pair.sign(&RSA_PSS_SHA256, &rng, &sig_payload, &mut signature).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600556
Fabio Utzig39297432019-05-08 18:51:10 -0300557 if is_rsa2048 {
David Brown69721182019-12-04 14:50:52 -0700558 result.write_u16::<LittleEndian>(TlvKinds::RSA2048 as u16).unwrap();
Fabio Utzig39297432019-05-08 18:51:10 -0300559 } else {
David Brown69721182019-12-04 14:50:52 -0700560 result.write_u16::<LittleEndian>(TlvKinds::RSA3072 as u16).unwrap();
Fabio Utzig39297432019-05-08 18:51:10 -0300561 }
David Brown91d68632019-07-29 14:32:13 -0600562 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600563 result.extend_from_slice(&signature);
564 }
565
Roland Mikhel6205c102023-02-06 13:32:02 +0100566 if self.kinds.contains(&TlvKinds::ECDSASIG) {
567 let rng = rand::SystemRandom::new();
Roland Mikhel5899fac2023-03-14 13:59:55 +0100568 let (signature, keyhash) = if cfg!(feature = "use-p384-curve") {
569 let keyhash = digest::digest(&digest::SHA384, ECDSAP384_PUB_KEY);
570 let key_bytes = pem::parse(include_bytes!("../../root-ec-p384-pkcs8.pem").as_ref()).unwrap();
571 let sign_algo = &ECDSA_P384_SHA384_ASN1_SIGNING;
572 let key_pair = EcdsaKeyPair::from_pkcs8(sign_algo, &key_bytes.contents).unwrap();
573 (key_pair.sign(&rng, &sig_payload).unwrap(), keyhash)
574 } else {
575 let keyhash = digest::digest(&digest::SHA256, ECDSA256_PUB_KEY);
576 let key_bytes = pem::parse(include_bytes!("../../root-ec-p256-pkcs8.pem").as_ref()).unwrap();
577 let sign_algo = &ECDSA_P256_SHA256_ASN1_SIGNING;
578 let key_pair = EcdsaKeyPair::from_pkcs8(sign_algo, &key_bytes.contents).unwrap();
579 (key_pair.sign(&rng, &sig_payload).unwrap(), keyhash)
580 };
Roland Mikhel6205c102023-02-06 13:32:02 +0100581
582 // Write public key
583 let keyhash_slice = keyhash.as_ref();
584 assert!(keyhash_slice.len() == 32);
585 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
586 result.write_u16::<LittleEndian>(32).unwrap();
587 result.extend_from_slice(keyhash_slice);
588
589 // Write signature
590 result.write_u16::<LittleEndian>(TlvKinds::ECDSASIG as u16).unwrap();
591 let signature = signature.as_ref().to_vec();
592 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
593 result.extend_from_slice(&signature);
594 }
Roland Mikhel5899fac2023-03-14 13:59:55 +0100595
Fabio Utzig97710282019-05-24 17:44:49 -0300596 if self.kinds.contains(&TlvKinds::ED25519) {
597 let keyhash = digest::digest(&digest::SHA256, ED25519_PUB_KEY);
598 let keyhash = keyhash.as_ref();
599
600 assert!(keyhash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700601 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700602 result.write_u16::<LittleEndian>(32).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300603 result.extend_from_slice(keyhash);
604
David Brown7a81c4b2019-07-29 15:20:21 -0600605 let hash = digest::digest(&digest::SHA256, &sig_payload);
Fabio Utzig97710282019-05-24 17:44:49 -0300606 let hash = hash.as_ref();
607 assert!(hash.len() == 32);
608
609 let key_bytes = pem::parse(include_bytes!("../../root-ed25519.pem").as_ref()).unwrap();
610 assert_eq!(key_bytes.tag, "PRIVATE KEY");
611
Fabio Utzig90f449e2019-10-24 07:43:53 -0300612 let key_pair = Ed25519KeyPair::from_seed_and_public_key(
613 &key_bytes.contents[16..48], &ED25519_PUB_KEY[12..44]).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300614 let signature = key_pair.sign(&hash);
615
David Brown69721182019-12-04 14:50:52 -0700616 result.write_u16::<LittleEndian>(TlvKinds::ED25519 as u16).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300617
618 let signature = signature.as_ref().to_vec();
David Brown91d68632019-07-29 14:32:13 -0600619 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300620 result.extend_from_slice(signature.as_ref());
621 }
622
Fabio Utzig1e48b912018-09-18 09:04:18 -0300623 if self.kinds.contains(&TlvKinds::ENCRSA2048) {
624 let key_bytes = pem::parse(include_bytes!("../../enc-rsa2048-pub.pem")
625 .as_ref()).unwrap();
626 assert_eq!(key_bytes.tag, "PUBLIC KEY");
627
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300628 let cipherkey = self.get_enc_key();
629 let cipherkey = cipherkey.as_slice();
630 let encbuf = match c::rsa_oaep_encrypt(&key_bytes.contents, cipherkey) {
Fabio Utzig1e48b912018-09-18 09:04:18 -0300631 Ok(v) => v,
632 Err(_) => panic!("Failed to encrypt secret key"),
633 };
634
635 assert!(encbuf.len() == 256);
David Brown69721182019-12-04 14:50:52 -0700636 result.write_u16::<LittleEndian>(TlvKinds::ENCRSA2048 as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700637 result.write_u16::<LittleEndian>(256).unwrap();
Fabio Utzig1e48b912018-09-18 09:04:18 -0300638 result.extend_from_slice(&encbuf);
639 }
640
Salome Thirot0f641972021-05-14 11:19:55 +0100641 if self.kinds.contains(&TlvKinds::ENCKW) {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100642 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
643 let aes256 = (self.get_flags() & flag) == flag;
644 let key_bytes = if aes256 {
645 base64::decode(
646 include_str!("../../enc-aes256kw.b64").trim()).unwrap()
647 } else {
648 base64::decode(
649 include_str!("../../enc-aes128kw.b64").trim()).unwrap()
650 };
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300651 let cipherkey = self.get_enc_key();
652 let cipherkey = cipherkey.as_slice();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100653 let keylen = if aes256 { 32 } else { 16 };
654 let encbuf = match c::kw_encrypt(&key_bytes, cipherkey, keylen) {
Fabio Utzig1e48b912018-09-18 09:04:18 -0300655 Ok(v) => v,
656 Err(_) => panic!("Failed to encrypt secret key"),
657 };
658
Salome Thirot6fdbf552021-05-14 16:46:14 +0100659 let size = if aes256 { 40 } else { 24 };
660 assert!(encbuf.len() == size);
Salome Thirot0f641972021-05-14 11:19:55 +0100661 result.write_u16::<LittleEndian>(TlvKinds::ENCKW as u16).unwrap();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100662 result.write_u16::<LittleEndian>(size as u16).unwrap();
Fabio Utzig1e48b912018-09-18 09:04:18 -0300663 result.extend_from_slice(&encbuf);
664 }
665
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300666 if self.kinds.contains(&TlvKinds::ENCEC256) || self.kinds.contains(&TlvKinds::ENCX25519) {
667 let key_bytes = if self.kinds.contains(&TlvKinds::ENCEC256) {
668 pem::parse(include_bytes!("../../enc-ec256-pub.pem").as_ref()).unwrap()
669 } else {
670 pem::parse(include_bytes!("../../enc-x25519-pub.pem").as_ref()).unwrap()
671 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300672 assert_eq!(key_bytes.tag, "PUBLIC KEY");
Fabio Utzig90f449e2019-10-24 07:43:53 -0300673 let rng = rand::SystemRandom::new();
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300674 let alg = if self.kinds.contains(&TlvKinds::ENCEC256) {
675 &agreement::ECDH_P256
676 } else {
677 &agreement::X25519
678 };
679 let pk = match agreement::EphemeralPrivateKey::generate(alg, &rng) {
Fabio Utzig90f449e2019-10-24 07:43:53 -0300680 Ok(v) => v,
681 Err(_) => panic!("Failed to generate ephemeral keypair"),
682 };
683
684 let pubk = match pk.compute_public_key() {
685 Ok(pubk) => pubk,
686 Err(_) => panic!("Failed computing ephemeral public key"),
687 };
688
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300689 let peer_pubk = if self.kinds.contains(&TlvKinds::ENCEC256) {
690 agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, &key_bytes.contents[26..])
691 } else {
692 agreement::UnparsedPublicKey::new(&agreement::X25519, &key_bytes.contents[12..])
693 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300694
695 #[derive(Debug, PartialEq)]
696 struct OkmLen<T: core::fmt::Debug + PartialEq>(T);
697
698 impl hkdf::KeyType for OkmLen<usize> {
699 fn len(&self) -> usize {
700 self.0
701 }
702 }
703
Salome Thirot6fdbf552021-05-14 16:46:14 +0100704 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
705 let aes256 = (self.get_flags() & flag) == flag;
706
Fabio Utzig90f449e2019-10-24 07:43:53 -0300707 let derived_key = match agreement::agree_ephemeral(
708 pk, &peer_pubk, ring::error::Unspecified, |shared| {
709 let salt = hkdf::Salt::new(hkdf::HKDF_SHA256, &[]);
710 let prk = salt.extract(&shared);
Salome Thirot6fdbf552021-05-14 16:46:14 +0100711 let okm_len = if aes256 { 64 } else { 48 };
712 let okm = match prk.expand(&[b"MCUBoot_ECIES_v1"], OkmLen(okm_len)) {
Fabio Utzig90f449e2019-10-24 07:43:53 -0300713 Ok(okm) => okm,
714 Err(_) => panic!("Failed building HKDF OKM"),
715 };
Salome Thirot6fdbf552021-05-14 16:46:14 +0100716 let mut buf = if aes256 { vec![0u8; 64] } else { vec![0u8; 48] };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300717 match okm.fill(&mut buf) {
718 Ok(_) => Ok(buf),
719 Err(_) => panic!("Failed generating HKDF output"),
720 }
721 },
722 ) {
723 Ok(v) => v,
724 Err(_) => panic!("Failed building HKDF"),
725 };
726
Fabio Utzig90f449e2019-10-24 07:43:53 -0300727 let nonce = GenericArray::from_slice(&[0; 16]);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300728 let mut cipherkey = self.get_enc_key();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100729 if aes256 {
730 let key: &GenericArray<u8, U32> = GenericArray::from_slice(&derived_key[..32]);
David Brown9c6322f2021-08-19 13:03:39 -0600731 let block = Aes256::new(&key);
732 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +0100733 cipher.apply_keystream(&mut cipherkey);
734 } else {
735 let key: &GenericArray<u8, U16> = GenericArray::from_slice(&derived_key[..16]);
David Brown9c6322f2021-08-19 13:03:39 -0600736 let block = Aes128::new(&key);
737 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +0100738 cipher.apply_keystream(&mut cipherkey);
739 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300740
Salome Thirot6fdbf552021-05-14 16:46:14 +0100741 let size = if aes256 { 32 } else { 16 };
742 let key = hmac::Key::new(hmac::HMAC_SHA256, &derived_key[size..]);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300743 let tag = hmac::sign(&key, &cipherkey);
744
745 let mut buf = vec![];
746 buf.append(&mut pubk.as_ref().to_vec());
747 buf.append(&mut tag.as_ref().to_vec());
748 buf.append(&mut cipherkey);
749
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300750 if self.kinds.contains(&TlvKinds::ENCEC256) {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100751 let size = if aes256 { 129 } else { 113 };
752 assert!(buf.len() == size);
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300753 result.write_u16::<LittleEndian>(TlvKinds::ENCEC256 as u16).unwrap();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100754 result.write_u16::<LittleEndian>(size as u16).unwrap();
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300755 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100756 let size = if aes256 { 96 } else { 80 };
757 assert!(buf.len() == size);
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300758 result.write_u16::<LittleEndian>(TlvKinds::ENCX25519 as u16).unwrap();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100759 result.write_u16::<LittleEndian>(size as u16).unwrap();
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300760 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300761 result.extend_from_slice(&buf);
762 }
763
David Brown3dc86c92020-01-08 17:22:55 -0700764 // Patch the size back into the TLV header.
765 let size = (result.len() - npro_pos) as u16;
766 let mut size_buf = &mut result[npro_pos + 2 .. npro_pos + 4];
767 size_buf.write_u16::<LittleEndian>(size).unwrap();
768
David Brownb408b432021-10-27 15:55:39 -0600769 // ECDSA is stored as an ASN.1 integer. For a 128-bit value, this maximally results in 33
770 // bytes of storage for each of the two values. If the high bit is zero, it will take 32
771 // bytes, if the top 8 bits are zero, it will take 31 bits, and so on. The smaller size
772 // will occur with decreasing likelihood. We'll allow this to get a bit smaller, hopefully
773 // allowing the tests to pass with false failures rare. For this case, we'll handle up to
774 // the top 16 bits of both numbers being all zeros (1 in 2^32).
775 if !Caps::has_ecdsa() {
776 if size_estimate != result.len() {
777 panic!("Incorrect size estimate: {} (actual {})", size_estimate, result.len());
778 }
779 } else {
780 if size_estimate < result.len() || size_estimate > result.len() + 6 {
781 panic!("Incorrect size estimate: {} (actual {})", size_estimate, result.len());
782 }
David Brownef4f0742021-10-22 17:09:50 -0600783 }
784 if size_estimate != result.len() {
785 log::warn!("Size off: {} actual {}", size_estimate, result.len());
786 }
787
David Brown187dd882017-07-11 11:15:23 -0600788 result
789 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300790
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300791 fn generate_enc_key(&mut self) {
792 let rng = rand::SystemRandom::new();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100793 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
794 let aes256 = (self.get_flags() & flag) == flag;
795 let mut buf = if aes256 {
796 vec![0u8; 32]
797 } else {
798 vec![0u8; 16]
799 };
David Brown26edaf32021-03-10 05:27:38 -0700800 if rng.fill(&mut buf).is_err() {
801 panic!("Error generating encrypted key");
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300802 }
803 info!("New encryption key: {:02x?}", buf);
804 self.enc_key = buf;
Fabio Utzig90f449e2019-10-24 07:43:53 -0300805 }
806
807 fn get_enc_key(&self) -> Vec<u8> {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100808 if self.enc_key.len() != 32 && self.enc_key.len() != 16 {
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300809 panic!("No random key was generated");
810 }
811 self.enc_key.clone()
Fabio Utzig90f449e2019-10-24 07:43:53 -0300812 }
Roland Mikheld6703522023-04-27 14:24:30 +0200813
814 fn set_security_counter(&mut self, security_cnt: Option<u32>) {
815 self.security_cnt = security_cnt;
816 }
Roland Mikhel6945bb62023-04-11 15:57:49 +0200817
818 fn set_ignore_ram_load_flag(&mut self) {
819 self.ignore_ram_load_flag = true;
820 }
David Brown187dd882017-07-11 11:15:23 -0600821}
David Brown43cda332017-09-01 09:53:23 -0600822
823include!("rsa_pub_key-rs.txt");
Fabio Utzig39297432019-05-08 18:51:10 -0300824include!("rsa3072_pub_key-rs.txt");
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200825include!("ecdsa_pub_key-rs.txt");
Fabio Utzig97710282019-05-24 17:44:49 -0300826include!("ed25519_pub_key-rs.txt");