blob: ce6876e9d9d8d32a54637e28f526e36200d0464d [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,
Roland Mikhelfb5507b2023-03-14 14:08:43 +010054 SHA384 = 0x11,
David Brown27648b82017-08-31 10:40:29 -060055 RSA2048 = 0x20,
David Vincze4395b802023-04-27 16:11:49 +020056 ECDSASIG = 0x22,
Fabio Utzig39297432019-05-08 18:51:10 -030057 RSA3072 = 0x23,
Fabio Utzig97710282019-05-24 17:44:49 -030058 ED25519 = 0x24,
Fabio Utzig1e48b912018-09-18 09:04:18 -030059 ENCRSA2048 = 0x30,
Salome Thirot0f641972021-05-14 11:19:55 +010060 ENCKW = 0x31,
Fabio Utzig90f449e2019-10-24 07:43:53 -030061 ENCEC256 = 0x32,
Fabio Utzig3fa72ca2020-04-02 11:20:37 -030062 ENCX25519 = 0x33,
David Brown7a81c4b2019-07-29 15:20:21 -060063 DEPENDENCY = 0x40,
Roland Mikheld6703522023-04-27 14:24:30 +020064 SECCNT = 0x50,
Fabio Utzig1e48b912018-09-18 09:04:18 -030065}
66
67#[allow(dead_code, non_camel_case_types)]
68pub enum TlvFlags {
69 PIC = 0x01,
70 NON_BOOTABLE = 0x02,
Salome Thirot6fdbf552021-05-14 16:46:14 +010071 ENCRYPTED_AES128 = 0x04,
Salome Thirot6fdbf552021-05-14 16:46:14 +010072 ENCRYPTED_AES256 = 0x08,
David Brownd8713a52021-10-22 16:27:23 -060073 RAM_LOAD = 0x20,
David Brown187dd882017-07-11 11:15:23 -060074}
75
David Brown43643dd2019-01-11 15:43:28 -070076/// A generator for manifests. The format of the manifest can be either a
77/// traditional "TLV" or a SUIT-style manifest.
78pub trait ManifestGen {
David Brownac46e262019-01-11 15:46:18 -070079 /// Retrieve the header magic value for this manifest type.
80 fn get_magic(&self) -> u32;
81
David Brown43643dd2019-01-11 15:43:28 -070082 /// Retrieve the flags value for this particular manifest type.
83 fn get_flags(&self) -> u32;
84
David Brown7a81c4b2019-07-29 15:20:21 -060085 /// Retrieve the number of bytes of this manifest that is "protected".
86 /// This field is stored in the outside image header instead of the
87 /// manifest header.
88 fn protect_size(&self) -> u16;
89
90 /// Add a dependency on another image.
91 fn add_dependency(&mut self, id: u8, version: &ImageVersion);
92
David Brown43643dd2019-01-11 15:43:28 -070093 /// Add a sequence of bytes to the payload that the manifest is
94 /// protecting.
95 fn add_bytes(&mut self, bytes: &[u8]);
96
David Browne90b13f2019-12-06 15:04:00 -070097 /// Set an internal flag indicating that the next `make_tlv` should
98 /// corrupt the signature.
99 fn corrupt_sig(&mut self);
100
David Brownef4f0742021-10-22 17:09:50 -0600101 /// Estimate the size of the TLV. This can be called before the payload is added (but after
102 /// other information is added). Some of the signature algorithms can generate variable sized
103 /// data, and therefore, this can slightly overestimate the size.
104 fn estimate_size(&self) -> usize;
105
David Brown43643dd2019-01-11 15:43:28 -0700106 /// Construct the manifest for this payload.
107 fn make_tlv(self: Box<Self>) -> Vec<u8>;
Fabio Utzig90f449e2019-10-24 07:43:53 -0300108
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300109 /// Generate a new encryption random key
110 fn generate_enc_key(&mut self);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300111
112 /// Return the current encryption key
113 fn get_enc_key(&self) -> Vec<u8>;
Roland Mikheld6703522023-04-27 14:24:30 +0200114
115 /// Set the security counter to the specified value.
116 fn set_security_counter(&mut self, security_cnt: Option<u32>);
Roland Mikhel6945bb62023-04-11 15:57:49 +0200117
118 /// Sets the ignore_ram_load_flag so that can be validated when it is missing,
119 /// it will not load successfully.
120 fn set_ignore_ram_load_flag(&mut self);
David Brown43643dd2019-01-11 15:43:28 -0700121}
122
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300123#[derive(Debug, Default)]
David Brown187dd882017-07-11 11:15:23 -0600124pub struct TlvGen {
David Brown43cda332017-09-01 09:53:23 -0600125 flags: u32,
David Brown187dd882017-07-11 11:15:23 -0600126 kinds: Vec<TlvKinds>,
David Brown4243ab02017-07-11 12:24:23 -0600127 payload: Vec<u8>,
David Brown7a81c4b2019-07-29 15:20:21 -0600128 dependencies: Vec<Dependency>,
Fabio Utzig90f449e2019-10-24 07:43:53 -0300129 enc_key: Vec<u8>,
David Browne90b13f2019-12-06 15:04:00 -0700130 /// Should this signature be corrupted.
131 gen_corrupted: bool,
Roland Mikheld6703522023-04-27 14:24:30 +0200132 security_cnt: Option<u32>,
Roland Mikhel6945bb62023-04-11 15:57:49 +0200133 /// Ignore RAM_LOAD flag
134 ignore_ram_load_flag: bool,
David Brown7a81c4b2019-07-29 15:20:21 -0600135}
136
David Brownc3898d62019-08-05 14:20:02 -0600137#[derive(Debug)]
David Brown7a81c4b2019-07-29 15:20:21 -0600138struct Dependency {
139 id: u8,
140 version: ImageVersion,
David Brown187dd882017-07-11 11:15:23 -0600141}
142
143impl TlvGen {
144 /// Construct a new tlv generator that will only contain a hash of the data.
David Brown7e701d82017-07-11 13:24:25 -0600145 #[allow(dead_code)]
David Brown187dd882017-07-11 11:15:23 -0600146 pub fn new_hash_only() -> TlvGen {
147 TlvGen {
David Brown187dd882017-07-11 11:15:23 -0600148 kinds: vec![TlvKinds::SHA256],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300149 ..Default::default()
David Brown187dd882017-07-11 11:15:23 -0600150 }
151 }
152
David Brown7e701d82017-07-11 13:24:25 -0600153 #[allow(dead_code)]
154 pub fn new_rsa_pss() -> TlvGen {
155 TlvGen {
Fabio Utzig754438d2018-12-14 06:39:58 -0200156 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300157 ..Default::default()
David Brown7e701d82017-07-11 13:24:25 -0600158 }
159 }
160
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200161 #[allow(dead_code)]
Fabio Utzig39297432019-05-08 18:51:10 -0300162 pub fn new_rsa3072_pss() -> TlvGen {
163 TlvGen {
Fabio Utzig39297432019-05-08 18:51:10 -0300164 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA3072],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300165 ..Default::default()
Fabio Utzig39297432019-05-08 18:51:10 -0300166 }
167 }
168
169 #[allow(dead_code)]
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200170 pub fn new_ecdsa() -> TlvGen {
Roland Mikhelfb5507b2023-03-14 14:08:43 +0100171 let hash_kind = if cfg!(feature = "sig-p384") {
172 TlvKinds::SHA384
173 } else {
174 TlvKinds::SHA256
175 };
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200176 TlvGen {
Roland Mikhelfb5507b2023-03-14 14:08:43 +0100177 kinds: vec![hash_kind, TlvKinds::ECDSASIG],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300178 ..Default::default()
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200179 }
180 }
181
Fabio Utzig1e48b912018-09-18 09:04:18 -0300182 #[allow(dead_code)]
Fabio Utzig97710282019-05-24 17:44:49 -0300183 pub fn new_ed25519() -> TlvGen {
184 TlvGen {
Fabio Utzig97710282019-05-24 17:44:49 -0300185 kinds: vec![TlvKinds::SHA256, TlvKinds::ED25519],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300186 ..Default::default()
Fabio Utzig97710282019-05-24 17:44:49 -0300187 }
188 }
189
190 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100191 pub fn new_enc_rsa(aes_key_size: u32) -> TlvGen {
192 let flag = if aes_key_size == 256 {
193 TlvFlags::ENCRYPTED_AES256 as u32
194 } else {
195 TlvFlags::ENCRYPTED_AES128 as u32
196 };
Fabio Utzig1e48b912018-09-18 09:04:18 -0300197 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100198 flags: flag,
Fabio Utzig1e48b912018-09-18 09:04:18 -0300199 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCRSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300200 ..Default::default()
Fabio Utzig1e48b912018-09-18 09:04:18 -0300201 }
202 }
203
204 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100205 pub fn new_sig_enc_rsa(aes_key_size: u32) -> TlvGen {
206 let flag = if aes_key_size == 256 {
207 TlvFlags::ENCRYPTED_AES256 as u32
208 } else {
209 TlvFlags::ENCRYPTED_AES128 as u32
210 };
Fabio Utzig754438d2018-12-14 06:39:58 -0200211 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100212 flags: flag,
Fabio Utzig754438d2018-12-14 06:39:58 -0200213 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048, TlvKinds::ENCRSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300214 ..Default::default()
Fabio Utzig754438d2018-12-14 06:39:58 -0200215 }
216 }
217
218 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100219 pub fn new_enc_kw(aes_key_size: u32) -> TlvGen {
220 let flag = if aes_key_size == 256 {
221 TlvFlags::ENCRYPTED_AES256 as u32
222 } else {
223 TlvFlags::ENCRYPTED_AES128 as u32
224 };
Fabio Utzig1e48b912018-09-18 09:04:18 -0300225 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100226 flags: flag,
Salome Thirot0f641972021-05-14 11:19:55 +0100227 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300228 ..Default::default()
Fabio Utzig1e48b912018-09-18 09:04:18 -0300229 }
230 }
231
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200232 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100233 pub fn new_rsa_kw(aes_key_size: u32) -> TlvGen {
234 let flag = if aes_key_size == 256 {
235 TlvFlags::ENCRYPTED_AES256 as u32
236 } else {
237 TlvFlags::ENCRYPTED_AES128 as u32
238 };
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200239 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100240 flags: flag,
Salome Thirot0f641972021-05-14 11:19:55 +0100241 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300242 ..Default::default()
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200243 }
244 }
245
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200246 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100247 pub fn new_ecdsa_kw(aes_key_size: u32) -> TlvGen {
248 let flag = if aes_key_size == 256 {
249 TlvFlags::ENCRYPTED_AES256 as u32
250 } else {
251 TlvFlags::ENCRYPTED_AES128 as u32
252 };
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200253 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100254 flags: flag,
Roland Mikhel30978512023-02-08 14:06:58 +0100255 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSASIG, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300256 ..Default::default()
Fabio Utzig90f449e2019-10-24 07:43:53 -0300257 }
258 }
259
260 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100261 pub fn new_ecies_p256(aes_key_size: u32) -> TlvGen {
262 let flag = if aes_key_size == 256 {
263 TlvFlags::ENCRYPTED_AES256 as u32
264 } else {
265 TlvFlags::ENCRYPTED_AES128 as u32
266 };
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300267 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100268 flags: flag,
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300269 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCEC256],
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300270 ..Default::default()
271 }
272 }
273
274 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100275 pub fn new_ecdsa_ecies_p256(aes_key_size: u32) -> TlvGen {
276 let flag = if aes_key_size == 256 {
277 TlvFlags::ENCRYPTED_AES256 as u32
278 } else {
279 TlvFlags::ENCRYPTED_AES128 as u32
280 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300281 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100282 flags: flag,
Roland Mikhel30978512023-02-08 14:06:58 +0100283 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSASIG, TlvKinds::ENCEC256],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300284 ..Default::default()
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200285 }
286 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300287
288 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100289 pub fn new_ecies_x25519(aes_key_size: u32) -> TlvGen {
290 let flag = if aes_key_size == 256 {
291 TlvFlags::ENCRYPTED_AES256 as u32
292 } else {
293 TlvFlags::ENCRYPTED_AES128 as u32
294 };
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300295 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100296 flags: flag,
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300297 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCX25519],
298 ..Default::default()
299 }
300 }
301
302 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100303 pub fn new_ed25519_ecies_x25519(aes_key_size: u32) -> TlvGen {
304 let flag = if aes_key_size == 256 {
305 TlvFlags::ENCRYPTED_AES256 as u32
306 } else {
307 TlvFlags::ENCRYPTED_AES128 as u32
308 };
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300309 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100310 flags: flag,
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300311 kinds: vec![TlvKinds::SHA256, TlvKinds::ED25519, TlvKinds::ENCX25519],
312 ..Default::default()
313 }
314 }
Roland Mikheld6703522023-04-27 14:24:30 +0200315
316 #[allow(dead_code)]
317 pub fn new_sec_cnt() -> TlvGen {
318 TlvGen {
319 kinds: vec![TlvKinds::SHA256, TlvKinds::SECCNT],
320 ..Default::default()
321 }
322 }
323
David Brown43643dd2019-01-11 15:43:28 -0700324}
325
326impl ManifestGen for TlvGen {
David Brownac46e262019-01-11 15:46:18 -0700327 fn get_magic(&self) -> u32 {
328 0x96f3b83d
329 }
330
David Brown43643dd2019-01-11 15:43:28 -0700331 /// Retrieve the header flags for this configuration. This can be called at any time.
332 fn get_flags(&self) -> u32 {
David Brown8a4e23b2021-06-11 10:29:01 -0600333 // For the RamLoad case, add in the flag for this feature.
Roland Mikhel6945bb62023-04-11 15:57:49 +0200334 if Caps::RamLoad.present() && !self.ignore_ram_load_flag {
David Brown8a4e23b2021-06-11 10:29:01 -0600335 self.flags | (TlvFlags::RAM_LOAD as u32)
336 } else {
337 self.flags
338 }
David Brown43643dd2019-01-11 15:43:28 -0700339 }
David Brown187dd882017-07-11 11:15:23 -0600340
341 /// Add bytes to the covered hash.
David Brown43643dd2019-01-11 15:43:28 -0700342 fn add_bytes(&mut self, bytes: &[u8]) {
David Brown4243ab02017-07-11 12:24:23 -0600343 self.payload.extend_from_slice(bytes);
David Brown187dd882017-07-11 11:15:23 -0600344 }
345
David Brown7a81c4b2019-07-29 15:20:21 -0600346 fn protect_size(&self) -> u16 {
Roland Mikheld6703522023-04-27 14:24:30 +0200347 let mut size = 0;
348 if !self.dependencies.is_empty() || (Caps::HwRollbackProtection.present() && self.security_cnt.is_some()) {
349 // include the TLV area header.
350 size += 4;
351 // add space for each dependency.
352 size += (self.dependencies.len() as u16) * (4 + std::mem::size_of::<Dependency>() as u16);
353 if Caps::HwRollbackProtection.present() && self.security_cnt.is_some() {
354 size += 4 + 4;
355 }
David Brown7a81c4b2019-07-29 15:20:21 -0600356 }
Roland Mikheld6703522023-04-27 14:24:30 +0200357 size
David Brown7a81c4b2019-07-29 15:20:21 -0600358 }
359
360 fn add_dependency(&mut self, id: u8, version: &ImageVersion) {
David Brown7a81c4b2019-07-29 15:20:21 -0600361 self.dependencies.push(Dependency {
David Brown4dfb33c2021-03-10 05:15:45 -0700362 id,
David Brown7a81c4b2019-07-29 15:20:21 -0600363 version: version.clone(),
364 });
365 }
366
David Browne90b13f2019-12-06 15:04:00 -0700367 fn corrupt_sig(&mut self) {
368 self.gen_corrupted = true;
369 }
370
David Brownef4f0742021-10-22 17:09:50 -0600371 fn estimate_size(&self) -> usize {
372 // Begin the estimate with the 4 byte header.
373 let mut estimate = 4;
374 // A very poor estimate.
375
376 // Estimate the size of the image hash.
377 if self.kinds.contains(&TlvKinds::SHA256) {
378 estimate += 4 + 32;
Roland Mikhelfb5507b2023-03-14 14:08:43 +0100379 } else if self.kinds.contains(&TlvKinds::SHA384) {
380 estimate += 4 + 48;
David Brownef4f0742021-10-22 17:09:50 -0600381 }
382
383 // Add an estimate in for each of the signature algorithms.
384 if self.kinds.contains(&TlvKinds::RSA2048) {
385 estimate += 4 + 32; // keyhash
386 estimate += 4 + 256; // RSA2048
387 }
388 if self.kinds.contains(&TlvKinds::RSA3072) {
389 estimate += 4 + 32; // keyhash
390 estimate += 4 + 384; // RSA3072
391 }
David Brownef4f0742021-10-22 17:09:50 -0600392 if self.kinds.contains(&TlvKinds::ED25519) {
393 estimate += 4 + 32; // keyhash
394 estimate += 4 + 64; // ED25519 signature.
395 }
Roland Mikhel6205c102023-02-06 13:32:02 +0100396 if self.kinds.contains(&TlvKinds::ECDSASIG) {
Roland Mikhel5899fac2023-03-14 13:59:55 +0100397 // ECDSA signatures are encoded as ASN.1 with the x and y values
398 // stored as signed integers. As such, the size can vary by 2 bytes,
399 // if for example the 256-bit value has the high bit, it takes an
400 // extra 0 byte to avoid it being seen as a negative number.
Roland Mikhelfb5507b2023-03-14 14:08:43 +0100401 if self.kinds.contains(&TlvKinds::SHA384) {
402 estimate += 4 + 48; // SHA384
Roland Mikhel5899fac2023-03-14 13:59:55 +0100403 estimate += 4 + 104; // ECDSA384 (varies)
404 } else {
Roland Mikhelfb5507b2023-03-14 14:08:43 +0100405 estimate += 4 + 32; // SHA256
Roland Mikhel5899fac2023-03-14 13:59:55 +0100406 estimate += 4 + 72; // ECDSA256 (varies)
407 }
Roland Mikhel6205c102023-02-06 13:32:02 +0100408 }
David Brownef4f0742021-10-22 17:09:50 -0600409
410 // Estimate encryption.
411 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
412 let aes256 = (self.get_flags() & flag) == flag;
413
414 if self.kinds.contains(&TlvKinds::ENCRSA2048) {
415 estimate += 4 + 256;
416 }
417 if self.kinds.contains(&TlvKinds::ENCKW) {
418 estimate += 4 + if aes256 { 40 } else { 24 };
419 }
420 if self.kinds.contains(&TlvKinds::ENCEC256) {
421 estimate += 4 + if aes256 { 129 } else { 113 };
422 }
423 if self.kinds.contains(&TlvKinds::ENCX25519) {
424 estimate += 4 + if aes256 { 96 } else { 80 };
425 }
426
Roland Mikheld6703522023-04-27 14:24:30 +0200427 // Gather the size of the protected TLV area.
428 estimate += self.protect_size() as usize;
David Brownef4f0742021-10-22 17:09:50 -0600429
430 estimate
431 }
432
David Brown187dd882017-07-11 11:15:23 -0600433 /// Compute the TLV given the specified block of data.
David Brown43643dd2019-01-11 15:43:28 -0700434 fn make_tlv(self: Box<Self>) -> Vec<u8> {
David Brownef4f0742021-10-22 17:09:50 -0600435 let size_estimate = self.estimate_size();
436
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300437 let mut protected_tlv: Vec<u8> = vec![];
David Brown187dd882017-07-11 11:15:23 -0600438
David Brown2b73ed92020-01-08 17:01:22 -0700439 if self.protect_size() > 0 {
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300440 protected_tlv.push(0x08);
441 protected_tlv.push(0x69);
David Brown2b73ed92020-01-08 17:01:22 -0700442 let size = self.protect_size();
443 protected_tlv.write_u16::<LittleEndian>(size).unwrap();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300444 for dep in &self.dependencies {
David Brown69721182019-12-04 14:50:52 -0700445 protected_tlv.write_u16::<LittleEndian>(TlvKinds::DEPENDENCY as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700446 protected_tlv.write_u16::<LittleEndian>(12).unwrap();
David Brownf5b33d82017-09-01 10:58:27 -0600447
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300448 // The dependency.
449 protected_tlv.push(dep.id);
David Brownf66b2052021-03-10 05:26:36 -0700450 protected_tlv.push(0);
451 protected_tlv.write_u16::<LittleEndian>(0).unwrap();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300452 protected_tlv.push(dep.version.major);
453 protected_tlv.push(dep.version.minor);
454 protected_tlv.write_u16::<LittleEndian>(dep.version.revision).unwrap();
455 protected_tlv.write_u32::<LittleEndian>(dep.version.build_num).unwrap();
David Brown7a81c4b2019-07-29 15:20:21 -0600456 }
David Brown2b73ed92020-01-08 17:01:22 -0700457
Roland Mikheld6703522023-04-27 14:24:30 +0200458 // Security counter has to be at the protected TLV area also
459 if Caps::HwRollbackProtection.present() && self.security_cnt.is_some() {
460 protected_tlv.write_u16::<LittleEndian>(TlvKinds::SECCNT as u16).unwrap();
461 protected_tlv.write_u16::<LittleEndian>(std::mem::size_of::<u32>() as u16).unwrap();
462 protected_tlv.write_u32::<LittleEndian>(self.security_cnt.unwrap() as u32).unwrap();
463 }
464
David Brown2b73ed92020-01-08 17:01:22 -0700465 assert_eq!(size, protected_tlv.len() as u16, "protected TLV length incorrect");
David Brown7a81c4b2019-07-29 15:20:21 -0600466 }
467
468 // Ring does the signature itself, which means that it must be
469 // given a full, contiguous payload. Although this does help from
470 // a correct usage perspective, it is fairly stupid from an
471 // efficiency view. If this is shown to be a performance issue
472 // with the tests, the protected data could be appended to the
473 // payload, and then removed after the signature is done. For now,
474 // just make a signed payload.
475 let mut sig_payload = self.payload.clone();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300476 sig_payload.extend_from_slice(&protected_tlv);
477
478 let mut result: Vec<u8> = vec![];
479
480 // add back signed payload
481 result.extend_from_slice(&protected_tlv);
482
483 // add non-protected payload
David Brown3dc86c92020-01-08 17:22:55 -0700484 let npro_pos = result.len();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300485 result.push(0x07);
486 result.push(0x69);
David Brown3dc86c92020-01-08 17:22:55 -0700487 // Placeholder for the size.
488 result.write_u16::<LittleEndian>(0).unwrap();
David Brown7a81c4b2019-07-29 15:20:21 -0600489
Roland Mikhelfb5507b2023-03-14 14:08:43 +0100490 if self.kinds.iter().any(|v| v == &TlvKinds::SHA256 || v == &TlvKinds::SHA384) {
David Browne90b13f2019-12-06 15:04:00 -0700491 // If a signature is not requested, corrupt the hash we are
492 // generating. But, if there is a signature, output the
493 // correct hash. We want the hash test to pass so that the
494 // signature verification can be validated.
495 let mut corrupt_hash = self.gen_corrupted;
496 for k in &[TlvKinds::RSA2048, TlvKinds::RSA3072,
Roland Mikhel30978512023-02-08 14:06:58 +0100497 TlvKinds::ED25519, TlvKinds::ECDSASIG]
David Browne90b13f2019-12-06 15:04:00 -0700498 {
499 if self.kinds.contains(k) {
500 corrupt_hash = false;
501 break;
502 }
503 }
504
505 if corrupt_hash {
506 sig_payload[0] ^= 1;
507 }
Roland Mikhelfb5507b2023-03-14 14:08:43 +0100508 let (hash,hash_size,tlv_kind) = if self.kinds.contains(&TlvKinds::SHA256)
509 {
510 let hash = digest::digest(&digest::SHA256, &sig_payload);
511 (hash,32,TlvKinds::SHA256)
512 }
513 else {
514 let hash = digest::digest(&digest::SHA384, &sig_payload);
515 (hash,48,TlvKinds::SHA384)
516 };
David Brown8054ce22017-07-11 12:12:09 -0600517 let hash = hash.as_ref();
David Brown187dd882017-07-11 11:15:23 -0600518
Roland Mikhelfb5507b2023-03-14 14:08:43 +0100519 assert!(hash.len() == hash_size);
520 result.write_u16::<LittleEndian>(tlv_kind as u16).unwrap();
521 result.write_u16::<LittleEndian>(hash_size as u16).unwrap();
David Brown8054ce22017-07-11 12:12:09 -0600522 result.extend_from_slice(hash);
David Browne90b13f2019-12-06 15:04:00 -0700523
524 // Undo the corruption.
525 if corrupt_hash {
526 sig_payload[0] ^= 1;
527 }
528
529 }
530
531 if self.gen_corrupted {
532 // Corrupt what is signed by modifying the input to the
533 // signature code.
534 sig_payload[0] ^= 1;
David Brown187dd882017-07-11 11:15:23 -0600535 }
536
Fabio Utzig39297432019-05-08 18:51:10 -0300537 if self.kinds.contains(&TlvKinds::RSA2048) ||
538 self.kinds.contains(&TlvKinds::RSA3072) {
539
540 let is_rsa2048 = self.kinds.contains(&TlvKinds::RSA2048);
541
David Brown43cda332017-09-01 09:53:23 -0600542 // Output the hash of the public key.
Fabio Utzig39297432019-05-08 18:51:10 -0300543 let hash = if is_rsa2048 {
544 digest::digest(&digest::SHA256, RSA_PUB_KEY)
545 } else {
546 digest::digest(&digest::SHA256, RSA3072_PUB_KEY)
547 };
David Brown43cda332017-09-01 09:53:23 -0600548 let hash = hash.as_ref();
549
550 assert!(hash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700551 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700552 result.write_u16::<LittleEndian>(32).unwrap();
David Brown43cda332017-09-01 09:53:23 -0600553 result.extend_from_slice(hash);
554
David Brown7e701d82017-07-11 13:24:25 -0600555 // For now assume PSS.
Fabio Utzig39297432019-05-08 18:51:10 -0300556 let key_bytes = if is_rsa2048 {
557 pem::parse(include_bytes!("../../root-rsa-2048.pem").as_ref()).unwrap()
558 } else {
559 pem::parse(include_bytes!("../../root-rsa-3072.pem").as_ref()).unwrap()
560 };
David Brown7e701d82017-07-11 13:24:25 -0600561 assert_eq!(key_bytes.tag, "RSA PRIVATE KEY");
Fabio Utzig90f449e2019-10-24 07:43:53 -0300562 let key_pair = RsaKeyPair::from_der(&key_bytes.contents).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600563 let rng = rand::SystemRandom::new();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300564 let mut signature = vec![0; key_pair.public_modulus_len()];
Fabio Utzig39297432019-05-08 18:51:10 -0300565 if is_rsa2048 {
566 assert_eq!(signature.len(), 256);
567 } else {
568 assert_eq!(signature.len(), 384);
569 }
David Brown7a81c4b2019-07-29 15:20:21 -0600570 key_pair.sign(&RSA_PSS_SHA256, &rng, &sig_payload, &mut signature).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600571
Fabio Utzig39297432019-05-08 18:51:10 -0300572 if is_rsa2048 {
David Brown69721182019-12-04 14:50:52 -0700573 result.write_u16::<LittleEndian>(TlvKinds::RSA2048 as u16).unwrap();
Fabio Utzig39297432019-05-08 18:51:10 -0300574 } else {
David Brown69721182019-12-04 14:50:52 -0700575 result.write_u16::<LittleEndian>(TlvKinds::RSA3072 as u16).unwrap();
Fabio Utzig39297432019-05-08 18:51:10 -0300576 }
David Brown91d68632019-07-29 14:32:13 -0600577 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600578 result.extend_from_slice(&signature);
579 }
580
Roland Mikhel6205c102023-02-06 13:32:02 +0100581 if self.kinds.contains(&TlvKinds::ECDSASIG) {
582 let rng = rand::SystemRandom::new();
Roland Mikhelfb5507b2023-03-14 14:08:43 +0100583 let (signature, keyhash, keyhash_size) = if self.kinds.contains(&TlvKinds::SHA384) {
Roland Mikhel5899fac2023-03-14 13:59:55 +0100584 let keyhash = digest::digest(&digest::SHA384, ECDSAP384_PUB_KEY);
585 let key_bytes = pem::parse(include_bytes!("../../root-ec-p384-pkcs8.pem").as_ref()).unwrap();
586 let sign_algo = &ECDSA_P384_SHA384_ASN1_SIGNING;
587 let key_pair = EcdsaKeyPair::from_pkcs8(sign_algo, &key_bytes.contents).unwrap();
Roland Mikhelfb5507b2023-03-14 14:08:43 +0100588 (key_pair.sign(&rng, &sig_payload).unwrap(), keyhash, 48)
Roland Mikhel5899fac2023-03-14 13:59:55 +0100589 } else {
590 let keyhash = digest::digest(&digest::SHA256, ECDSA256_PUB_KEY);
591 let key_bytes = pem::parse(include_bytes!("../../root-ec-p256-pkcs8.pem").as_ref()).unwrap();
592 let sign_algo = &ECDSA_P256_SHA256_ASN1_SIGNING;
593 let key_pair = EcdsaKeyPair::from_pkcs8(sign_algo, &key_bytes.contents).unwrap();
Roland Mikhelfb5507b2023-03-14 14:08:43 +0100594 (key_pair.sign(&rng, &sig_payload).unwrap(), keyhash, 32)
Roland Mikhel5899fac2023-03-14 13:59:55 +0100595 };
Roland Mikhel6205c102023-02-06 13:32:02 +0100596
597 // Write public key
598 let keyhash_slice = keyhash.as_ref();
Roland Mikhelfb5507b2023-03-14 14:08:43 +0100599 assert!(keyhash_slice.len() == keyhash_size);
Roland Mikhel6205c102023-02-06 13:32:02 +0100600 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
Roland Mikhelfb5507b2023-03-14 14:08:43 +0100601 result.write_u16::<LittleEndian>(keyhash_size as u16).unwrap();
Roland Mikhel6205c102023-02-06 13:32:02 +0100602 result.extend_from_slice(keyhash_slice);
603
604 // Write signature
605 result.write_u16::<LittleEndian>(TlvKinds::ECDSASIG as u16).unwrap();
606 let signature = signature.as_ref().to_vec();
607 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
608 result.extend_from_slice(&signature);
609 }
Roland Mikhel5899fac2023-03-14 13:59:55 +0100610
Fabio Utzig97710282019-05-24 17:44:49 -0300611 if self.kinds.contains(&TlvKinds::ED25519) {
612 let keyhash = digest::digest(&digest::SHA256, ED25519_PUB_KEY);
613 let keyhash = keyhash.as_ref();
614
615 assert!(keyhash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700616 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700617 result.write_u16::<LittleEndian>(32).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300618 result.extend_from_slice(keyhash);
619
David Brown7a81c4b2019-07-29 15:20:21 -0600620 let hash = digest::digest(&digest::SHA256, &sig_payload);
Fabio Utzig97710282019-05-24 17:44:49 -0300621 let hash = hash.as_ref();
622 assert!(hash.len() == 32);
623
624 let key_bytes = pem::parse(include_bytes!("../../root-ed25519.pem").as_ref()).unwrap();
625 assert_eq!(key_bytes.tag, "PRIVATE KEY");
626
Fabio Utzig90f449e2019-10-24 07:43:53 -0300627 let key_pair = Ed25519KeyPair::from_seed_and_public_key(
628 &key_bytes.contents[16..48], &ED25519_PUB_KEY[12..44]).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300629 let signature = key_pair.sign(&hash);
630
David Brown69721182019-12-04 14:50:52 -0700631 result.write_u16::<LittleEndian>(TlvKinds::ED25519 as u16).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300632
633 let signature = signature.as_ref().to_vec();
David Brown91d68632019-07-29 14:32:13 -0600634 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300635 result.extend_from_slice(signature.as_ref());
636 }
637
Fabio Utzig1e48b912018-09-18 09:04:18 -0300638 if self.kinds.contains(&TlvKinds::ENCRSA2048) {
639 let key_bytes = pem::parse(include_bytes!("../../enc-rsa2048-pub.pem")
640 .as_ref()).unwrap();
641 assert_eq!(key_bytes.tag, "PUBLIC KEY");
642
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300643 let cipherkey = self.get_enc_key();
644 let cipherkey = cipherkey.as_slice();
645 let encbuf = match c::rsa_oaep_encrypt(&key_bytes.contents, cipherkey) {
Fabio Utzig1e48b912018-09-18 09:04:18 -0300646 Ok(v) => v,
647 Err(_) => panic!("Failed to encrypt secret key"),
648 };
649
650 assert!(encbuf.len() == 256);
David Brown69721182019-12-04 14:50:52 -0700651 result.write_u16::<LittleEndian>(TlvKinds::ENCRSA2048 as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700652 result.write_u16::<LittleEndian>(256).unwrap();
Fabio Utzig1e48b912018-09-18 09:04:18 -0300653 result.extend_from_slice(&encbuf);
654 }
655
Salome Thirot0f641972021-05-14 11:19:55 +0100656 if self.kinds.contains(&TlvKinds::ENCKW) {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100657 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
658 let aes256 = (self.get_flags() & flag) == flag;
659 let key_bytes = if aes256 {
660 base64::decode(
661 include_str!("../../enc-aes256kw.b64").trim()).unwrap()
662 } else {
663 base64::decode(
664 include_str!("../../enc-aes128kw.b64").trim()).unwrap()
665 };
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300666 let cipherkey = self.get_enc_key();
667 let cipherkey = cipherkey.as_slice();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100668 let keylen = if aes256 { 32 } else { 16 };
669 let encbuf = match c::kw_encrypt(&key_bytes, cipherkey, keylen) {
Fabio Utzig1e48b912018-09-18 09:04:18 -0300670 Ok(v) => v,
671 Err(_) => panic!("Failed to encrypt secret key"),
672 };
673
Salome Thirot6fdbf552021-05-14 16:46:14 +0100674 let size = if aes256 { 40 } else { 24 };
675 assert!(encbuf.len() == size);
Salome Thirot0f641972021-05-14 11:19:55 +0100676 result.write_u16::<LittleEndian>(TlvKinds::ENCKW as u16).unwrap();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100677 result.write_u16::<LittleEndian>(size as u16).unwrap();
Fabio Utzig1e48b912018-09-18 09:04:18 -0300678 result.extend_from_slice(&encbuf);
679 }
680
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300681 if self.kinds.contains(&TlvKinds::ENCEC256) || self.kinds.contains(&TlvKinds::ENCX25519) {
682 let key_bytes = if self.kinds.contains(&TlvKinds::ENCEC256) {
683 pem::parse(include_bytes!("../../enc-ec256-pub.pem").as_ref()).unwrap()
684 } else {
685 pem::parse(include_bytes!("../../enc-x25519-pub.pem").as_ref()).unwrap()
686 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300687 assert_eq!(key_bytes.tag, "PUBLIC KEY");
Fabio Utzig90f449e2019-10-24 07:43:53 -0300688 let rng = rand::SystemRandom::new();
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300689 let alg = if self.kinds.contains(&TlvKinds::ENCEC256) {
690 &agreement::ECDH_P256
691 } else {
692 &agreement::X25519
693 };
694 let pk = match agreement::EphemeralPrivateKey::generate(alg, &rng) {
Fabio Utzig90f449e2019-10-24 07:43:53 -0300695 Ok(v) => v,
696 Err(_) => panic!("Failed to generate ephemeral keypair"),
697 };
698
699 let pubk = match pk.compute_public_key() {
700 Ok(pubk) => pubk,
701 Err(_) => panic!("Failed computing ephemeral public key"),
702 };
703
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300704 let peer_pubk = if self.kinds.contains(&TlvKinds::ENCEC256) {
705 agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, &key_bytes.contents[26..])
706 } else {
707 agreement::UnparsedPublicKey::new(&agreement::X25519, &key_bytes.contents[12..])
708 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300709
710 #[derive(Debug, PartialEq)]
711 struct OkmLen<T: core::fmt::Debug + PartialEq>(T);
712
713 impl hkdf::KeyType for OkmLen<usize> {
714 fn len(&self) -> usize {
715 self.0
716 }
717 }
718
Salome Thirot6fdbf552021-05-14 16:46:14 +0100719 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
720 let aes256 = (self.get_flags() & flag) == flag;
721
Fabio Utzig90f449e2019-10-24 07:43:53 -0300722 let derived_key = match agreement::agree_ephemeral(
723 pk, &peer_pubk, ring::error::Unspecified, |shared| {
724 let salt = hkdf::Salt::new(hkdf::HKDF_SHA256, &[]);
725 let prk = salt.extract(&shared);
Salome Thirot6fdbf552021-05-14 16:46:14 +0100726 let okm_len = if aes256 { 64 } else { 48 };
727 let okm = match prk.expand(&[b"MCUBoot_ECIES_v1"], OkmLen(okm_len)) {
Fabio Utzig90f449e2019-10-24 07:43:53 -0300728 Ok(okm) => okm,
729 Err(_) => panic!("Failed building HKDF OKM"),
730 };
Salome Thirot6fdbf552021-05-14 16:46:14 +0100731 let mut buf = if aes256 { vec![0u8; 64] } else { vec![0u8; 48] };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300732 match okm.fill(&mut buf) {
733 Ok(_) => Ok(buf),
734 Err(_) => panic!("Failed generating HKDF output"),
735 }
736 },
737 ) {
738 Ok(v) => v,
739 Err(_) => panic!("Failed building HKDF"),
740 };
741
Fabio Utzig90f449e2019-10-24 07:43:53 -0300742 let nonce = GenericArray::from_slice(&[0; 16]);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300743 let mut cipherkey = self.get_enc_key();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100744 if aes256 {
745 let key: &GenericArray<u8, U32> = GenericArray::from_slice(&derived_key[..32]);
David Brown9c6322f2021-08-19 13:03:39 -0600746 let block = Aes256::new(&key);
747 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +0100748 cipher.apply_keystream(&mut cipherkey);
749 } else {
750 let key: &GenericArray<u8, U16> = GenericArray::from_slice(&derived_key[..16]);
David Brown9c6322f2021-08-19 13:03:39 -0600751 let block = Aes128::new(&key);
752 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +0100753 cipher.apply_keystream(&mut cipherkey);
754 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300755
Salome Thirot6fdbf552021-05-14 16:46:14 +0100756 let size = if aes256 { 32 } else { 16 };
757 let key = hmac::Key::new(hmac::HMAC_SHA256, &derived_key[size..]);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300758 let tag = hmac::sign(&key, &cipherkey);
759
760 let mut buf = vec![];
761 buf.append(&mut pubk.as_ref().to_vec());
762 buf.append(&mut tag.as_ref().to_vec());
763 buf.append(&mut cipherkey);
764
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300765 if self.kinds.contains(&TlvKinds::ENCEC256) {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100766 let size = if aes256 { 129 } else { 113 };
767 assert!(buf.len() == size);
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300768 result.write_u16::<LittleEndian>(TlvKinds::ENCEC256 as u16).unwrap();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100769 result.write_u16::<LittleEndian>(size as u16).unwrap();
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300770 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100771 let size = if aes256 { 96 } else { 80 };
772 assert!(buf.len() == size);
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300773 result.write_u16::<LittleEndian>(TlvKinds::ENCX25519 as u16).unwrap();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100774 result.write_u16::<LittleEndian>(size as u16).unwrap();
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300775 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300776 result.extend_from_slice(&buf);
777 }
778
David Brown3dc86c92020-01-08 17:22:55 -0700779 // Patch the size back into the TLV header.
780 let size = (result.len() - npro_pos) as u16;
781 let mut size_buf = &mut result[npro_pos + 2 .. npro_pos + 4];
782 size_buf.write_u16::<LittleEndian>(size).unwrap();
783
David Brownb408b432021-10-27 15:55:39 -0600784 // ECDSA is stored as an ASN.1 integer. For a 128-bit value, this maximally results in 33
785 // bytes of storage for each of the two values. If the high bit is zero, it will take 32
786 // bytes, if the top 8 bits are zero, it will take 31 bits, and so on. The smaller size
787 // will occur with decreasing likelihood. We'll allow this to get a bit smaller, hopefully
788 // allowing the tests to pass with false failures rare. For this case, we'll handle up to
789 // the top 16 bits of both numbers being all zeros (1 in 2^32).
790 if !Caps::has_ecdsa() {
791 if size_estimate != result.len() {
792 panic!("Incorrect size estimate: {} (actual {})", size_estimate, result.len());
793 }
794 } else {
795 if size_estimate < result.len() || size_estimate > result.len() + 6 {
796 panic!("Incorrect size estimate: {} (actual {})", size_estimate, result.len());
797 }
David Brownef4f0742021-10-22 17:09:50 -0600798 }
799 if size_estimate != result.len() {
800 log::warn!("Size off: {} actual {}", size_estimate, result.len());
801 }
802
David Brown187dd882017-07-11 11:15:23 -0600803 result
804 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300805
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300806 fn generate_enc_key(&mut self) {
807 let rng = rand::SystemRandom::new();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100808 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
809 let aes256 = (self.get_flags() & flag) == flag;
810 let mut buf = if aes256 {
811 vec![0u8; 32]
812 } else {
813 vec![0u8; 16]
814 };
David Brown26edaf32021-03-10 05:27:38 -0700815 if rng.fill(&mut buf).is_err() {
816 panic!("Error generating encrypted key");
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300817 }
818 info!("New encryption key: {:02x?}", buf);
819 self.enc_key = buf;
Fabio Utzig90f449e2019-10-24 07:43:53 -0300820 }
821
822 fn get_enc_key(&self) -> Vec<u8> {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100823 if self.enc_key.len() != 32 && self.enc_key.len() != 16 {
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300824 panic!("No random key was generated");
825 }
826 self.enc_key.clone()
Fabio Utzig90f449e2019-10-24 07:43:53 -0300827 }
Roland Mikheld6703522023-04-27 14:24:30 +0200828
829 fn set_security_counter(&mut self, security_cnt: Option<u32>) {
830 self.security_cnt = security_cnt;
831 }
Roland Mikhel6945bb62023-04-11 15:57:49 +0200832
833 fn set_ignore_ram_load_flag(&mut self) {
834 self.ignore_ram_load_flag = true;
835 }
David Brown187dd882017-07-11 11:15:23 -0600836}
David Brown43cda332017-09-01 09:53:23 -0600837
838include!("rsa_pub_key-rs.txt");
Fabio Utzig39297432019-05-08 18:51:10 -0300839include!("rsa3072_pub_key-rs.txt");
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200840include!("ecdsa_pub_key-rs.txt");
Fabio Utzig97710282019-05-24 17:44:49 -0300841include!("ed25519_pub_key-rs.txt");