blob: a64244695cadbd1112acf424667b410b6e8a0327 [file] [log] [blame]
David Browne2acfae2020-01-21 16:45:01 -07001// Copyright (c) 2017-2020 Linaro LTD
2// Copyright (c) 2017-2020 JUUL Labs
Salome Thirot6fdbf552021-05-14 16:46:14 +01003// Copyright (c) 2021 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 Brown8a4e23b2021-06-11 10:29:01 -060020use crate::caps::Caps;
David Brown7a81c4b2019-07-29 15:20:21 -060021use crate::image::ImageVersion;
Fabio Utzige84f0ef2019-11-22 12:29:32 -030022use log::info;
Fabio Utzig90f449e2019-10-24 07:43:53 -030023use ring::{digest, rand, agreement, hkdf, hmac};
Fabio Utzige84f0ef2019-11-22 12:29:32 -030024use ring::rand::SecureRandom;
Fabio Utzig05ab0142018-07-10 09:15:28 -030025use ring::signature::{
26 RsaKeyPair,
27 RSA_PSS_SHA256,
28 EcdsaKeyPair,
29 ECDSA_P256_SHA256_ASN1_SIGNING,
Fabio Utzig97710282019-05-24 17:44:49 -030030 Ed25519KeyPair,
Fabio Utzig05ab0142018-07-10 09:15:28 -030031};
Fabio Utzig90f449e2019-10-24 07:43:53 -030032use aes_ctr::{
33 Aes128Ctr,
Salome Thirot6fdbf552021-05-14 16:46:14 +010034 Aes256Ctr,
Fabio Utzig90f449e2019-10-24 07:43:53 -030035 stream_cipher::{
36 generic_array::GenericArray,
David Brown8a99adf2020-07-09 16:52:38 -060037 NewStreamCipher,
38 SyncStreamCipher,
Fabio Utzig90f449e2019-10-24 07:43:53 -030039 },
40};
Fabio Utzig80fde2f2017-12-05 09:25:31 -020041use mcuboot_sys::c;
Salome Thirot6fdbf552021-05-14 16:46:14 +010042use typenum::{U16, U32};
David Brown187dd882017-07-11 11:15:23 -060043
David Brown69721182019-12-04 14:50:52 -070044#[repr(u16)]
David Brownc3898d62019-08-05 14:20:02 -060045#[derive(Copy, Clone, Debug, PartialEq, Eq)]
David Brown187dd882017-07-11 11:15:23 -060046#[allow(dead_code)] // TODO: For now
47pub enum TlvKinds {
David Brown43cda332017-09-01 09:53:23 -060048 KEYHASH = 0x01,
David Brown27648b82017-08-31 10:40:29 -060049 SHA256 = 0x10,
50 RSA2048 = 0x20,
51 ECDSA224 = 0x21,
52 ECDSA256 = 0x22,
Fabio Utzig39297432019-05-08 18:51:10 -030053 RSA3072 = 0x23,
Fabio Utzig97710282019-05-24 17:44:49 -030054 ED25519 = 0x24,
Fabio Utzig1e48b912018-09-18 09:04:18 -030055 ENCRSA2048 = 0x30,
Salome Thirot0f641972021-05-14 11:19:55 +010056 ENCKW = 0x31,
Fabio Utzig90f449e2019-10-24 07:43:53 -030057 ENCEC256 = 0x32,
Fabio Utzig3fa72ca2020-04-02 11:20:37 -030058 ENCX25519 = 0x33,
David Brown7a81c4b2019-07-29 15:20:21 -060059 DEPENDENCY = 0x40,
Fabio Utzig1e48b912018-09-18 09:04:18 -030060}
61
62#[allow(dead_code, non_camel_case_types)]
63pub enum TlvFlags {
64 PIC = 0x01,
65 NON_BOOTABLE = 0x02,
Salome Thirot6fdbf552021-05-14 16:46:14 +010066 ENCRYPTED_AES128 = 0x04,
Fabio Utzig1e48b912018-09-18 09:04:18 -030067 RAM_LOAD = 0x20,
Salome Thirot6fdbf552021-05-14 16:46:14 +010068 ENCRYPTED_AES256 = 0x08,
David Brown187dd882017-07-11 11:15:23 -060069}
70
David Brown43643dd2019-01-11 15:43:28 -070071/// A generator for manifests. The format of the manifest can be either a
72/// traditional "TLV" or a SUIT-style manifest.
73pub trait ManifestGen {
David Brownac46e262019-01-11 15:46:18 -070074 /// Retrieve the header magic value for this manifest type.
75 fn get_magic(&self) -> u32;
76
David Brown43643dd2019-01-11 15:43:28 -070077 /// Retrieve the flags value for this particular manifest type.
78 fn get_flags(&self) -> u32;
79
David Brown7a81c4b2019-07-29 15:20:21 -060080 /// Retrieve the number of bytes of this manifest that is "protected".
81 /// This field is stored in the outside image header instead of the
82 /// manifest header.
83 fn protect_size(&self) -> u16;
84
85 /// Add a dependency on another image.
86 fn add_dependency(&mut self, id: u8, version: &ImageVersion);
87
David Brown43643dd2019-01-11 15:43:28 -070088 /// Add a sequence of bytes to the payload that the manifest is
89 /// protecting.
90 fn add_bytes(&mut self, bytes: &[u8]);
91
David Browne90b13f2019-12-06 15:04:00 -070092 /// Set an internal flag indicating that the next `make_tlv` should
93 /// corrupt the signature.
94 fn corrupt_sig(&mut self);
95
David Brown43643dd2019-01-11 15:43:28 -070096 /// Construct the manifest for this payload.
97 fn make_tlv(self: Box<Self>) -> Vec<u8>;
Fabio Utzig90f449e2019-10-24 07:43:53 -030098
Fabio Utzige84f0ef2019-11-22 12:29:32 -030099 /// Generate a new encryption random key
100 fn generate_enc_key(&mut self);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300101
102 /// Return the current encryption key
103 fn get_enc_key(&self) -> Vec<u8>;
David Brown43643dd2019-01-11 15:43:28 -0700104}
105
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300106#[derive(Debug, Default)]
David Brown187dd882017-07-11 11:15:23 -0600107pub struct TlvGen {
David Brown43cda332017-09-01 09:53:23 -0600108 flags: u32,
David Brown187dd882017-07-11 11:15:23 -0600109 kinds: Vec<TlvKinds>,
David Brown4243ab02017-07-11 12:24:23 -0600110 payload: Vec<u8>,
David Brown7a81c4b2019-07-29 15:20:21 -0600111 dependencies: Vec<Dependency>,
Fabio Utzig90f449e2019-10-24 07:43:53 -0300112 enc_key: Vec<u8>,
David Browne90b13f2019-12-06 15:04:00 -0700113 /// Should this signature be corrupted.
114 gen_corrupted: bool,
David Brown7a81c4b2019-07-29 15:20:21 -0600115}
116
David Brownc3898d62019-08-05 14:20:02 -0600117#[derive(Debug)]
David Brown7a81c4b2019-07-29 15:20:21 -0600118struct Dependency {
119 id: u8,
120 version: ImageVersion,
David Brown187dd882017-07-11 11:15:23 -0600121}
122
123impl TlvGen {
124 /// Construct a new tlv generator that will only contain a hash of the data.
David Brown7e701d82017-07-11 13:24:25 -0600125 #[allow(dead_code)]
David Brown187dd882017-07-11 11:15:23 -0600126 pub fn new_hash_only() -> TlvGen {
127 TlvGen {
David Brown187dd882017-07-11 11:15:23 -0600128 kinds: vec![TlvKinds::SHA256],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300129 ..Default::default()
David Brown187dd882017-07-11 11:15:23 -0600130 }
131 }
132
David Brown7e701d82017-07-11 13:24:25 -0600133 #[allow(dead_code)]
134 pub fn new_rsa_pss() -> TlvGen {
135 TlvGen {
Fabio Utzig754438d2018-12-14 06:39:58 -0200136 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300137 ..Default::default()
David Brown7e701d82017-07-11 13:24:25 -0600138 }
139 }
140
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200141 #[allow(dead_code)]
Fabio Utzig39297432019-05-08 18:51:10 -0300142 pub fn new_rsa3072_pss() -> TlvGen {
143 TlvGen {
Fabio Utzig39297432019-05-08 18:51:10 -0300144 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA3072],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300145 ..Default::default()
Fabio Utzig39297432019-05-08 18:51:10 -0300146 }
147 }
148
149 #[allow(dead_code)]
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200150 pub fn new_ecdsa() -> TlvGen {
151 TlvGen {
Fabio Utzig754438d2018-12-14 06:39:58 -0200152 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSA256],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300153 ..Default::default()
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200154 }
155 }
156
Fabio Utzig1e48b912018-09-18 09:04:18 -0300157 #[allow(dead_code)]
Fabio Utzig97710282019-05-24 17:44:49 -0300158 pub fn new_ed25519() -> TlvGen {
159 TlvGen {
Fabio Utzig97710282019-05-24 17:44:49 -0300160 kinds: vec![TlvKinds::SHA256, TlvKinds::ED25519],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300161 ..Default::default()
Fabio Utzig97710282019-05-24 17:44:49 -0300162 }
163 }
164
165 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100166 pub fn new_enc_rsa(aes_key_size: u32) -> TlvGen {
167 let flag = if aes_key_size == 256 {
168 TlvFlags::ENCRYPTED_AES256 as u32
169 } else {
170 TlvFlags::ENCRYPTED_AES128 as u32
171 };
Fabio Utzig1e48b912018-09-18 09:04:18 -0300172 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100173 flags: flag,
Fabio Utzig1e48b912018-09-18 09:04:18 -0300174 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCRSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300175 ..Default::default()
Fabio Utzig1e48b912018-09-18 09:04:18 -0300176 }
177 }
178
179 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100180 pub fn new_sig_enc_rsa(aes_key_size: u32) -> TlvGen {
181 let flag = if aes_key_size == 256 {
182 TlvFlags::ENCRYPTED_AES256 as u32
183 } else {
184 TlvFlags::ENCRYPTED_AES128 as u32
185 };
Fabio Utzig754438d2018-12-14 06:39:58 -0200186 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100187 flags: flag,
Fabio Utzig754438d2018-12-14 06:39:58 -0200188 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048, TlvKinds::ENCRSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300189 ..Default::default()
Fabio Utzig754438d2018-12-14 06:39:58 -0200190 }
191 }
192
193 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100194 pub fn new_enc_kw(aes_key_size: u32) -> TlvGen {
195 let flag = if aes_key_size == 256 {
196 TlvFlags::ENCRYPTED_AES256 as u32
197 } else {
198 TlvFlags::ENCRYPTED_AES128 as u32
199 };
Fabio Utzig1e48b912018-09-18 09:04:18 -0300200 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100201 flags: flag,
Salome Thirot0f641972021-05-14 11:19:55 +0100202 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300203 ..Default::default()
Fabio Utzig1e48b912018-09-18 09:04:18 -0300204 }
205 }
206
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200207 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100208 pub fn new_rsa_kw(aes_key_size: u32) -> TlvGen {
209 let flag = if aes_key_size == 256 {
210 TlvFlags::ENCRYPTED_AES256 as u32
211 } else {
212 TlvFlags::ENCRYPTED_AES128 as u32
213 };
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200214 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100215 flags: flag,
Salome Thirot0f641972021-05-14 11:19:55 +0100216 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300217 ..Default::default()
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200218 }
219 }
220
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200221 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100222 pub fn new_ecdsa_kw(aes_key_size: u32) -> TlvGen {
223 let flag = if aes_key_size == 256 {
224 TlvFlags::ENCRYPTED_AES256 as u32
225 } else {
226 TlvFlags::ENCRYPTED_AES128 as u32
227 };
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200228 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100229 flags: flag,
Salome Thirot0f641972021-05-14 11:19:55 +0100230 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSA256, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300231 ..Default::default()
Fabio Utzig90f449e2019-10-24 07:43:53 -0300232 }
233 }
234
235 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100236 pub fn new_ecies_p256(aes_key_size: u32) -> TlvGen {
237 let flag = if aes_key_size == 256 {
238 TlvFlags::ENCRYPTED_AES256 as u32
239 } else {
240 TlvFlags::ENCRYPTED_AES128 as u32
241 };
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300242 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100243 flags: flag,
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300244 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCEC256],
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300245 ..Default::default()
246 }
247 }
248
249 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100250 pub fn new_ecdsa_ecies_p256(aes_key_size: u32) -> TlvGen {
251 let flag = if aes_key_size == 256 {
252 TlvFlags::ENCRYPTED_AES256 as u32
253 } else {
254 TlvFlags::ENCRYPTED_AES128 as u32
255 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300256 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100257 flags: flag,
Fabio Utzig90f449e2019-10-24 07:43:53 -0300258 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSA256, TlvKinds::ENCEC256],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300259 ..Default::default()
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200260 }
261 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300262
263 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100264 pub fn new_ecies_x25519(aes_key_size: u32) -> TlvGen {
265 let flag = if aes_key_size == 256 {
266 TlvFlags::ENCRYPTED_AES256 as u32
267 } else {
268 TlvFlags::ENCRYPTED_AES128 as u32
269 };
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300270 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100271 flags: flag,
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300272 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCX25519],
273 ..Default::default()
274 }
275 }
276
277 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100278 pub fn new_ed25519_ecies_x25519(aes_key_size: u32) -> TlvGen {
279 let flag = if aes_key_size == 256 {
280 TlvFlags::ENCRYPTED_AES256 as u32
281 } else {
282 TlvFlags::ENCRYPTED_AES128 as u32
283 };
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300284 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100285 flags: flag,
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300286 kinds: vec![TlvKinds::SHA256, TlvKinds::ED25519, TlvKinds::ENCX25519],
287 ..Default::default()
288 }
289 }
David Brown43643dd2019-01-11 15:43:28 -0700290}
291
292impl ManifestGen for TlvGen {
David Brownac46e262019-01-11 15:46:18 -0700293 fn get_magic(&self) -> u32 {
294 0x96f3b83d
295 }
296
David Brown43643dd2019-01-11 15:43:28 -0700297 /// Retrieve the header flags for this configuration. This can be called at any time.
298 fn get_flags(&self) -> u32 {
David Brown8a4e23b2021-06-11 10:29:01 -0600299 // For the RamLoad case, add in the flag for this feature.
300 if Caps::RamLoad.present() {
301 self.flags | (TlvFlags::RAM_LOAD as u32)
302 } else {
303 self.flags
304 }
David Brown43643dd2019-01-11 15:43:28 -0700305 }
David Brown187dd882017-07-11 11:15:23 -0600306
307 /// Add bytes to the covered hash.
David Brown43643dd2019-01-11 15:43:28 -0700308 fn add_bytes(&mut self, bytes: &[u8]) {
David Brown4243ab02017-07-11 12:24:23 -0600309 self.payload.extend_from_slice(bytes);
David Brown187dd882017-07-11 11:15:23 -0600310 }
311
David Brown7a81c4b2019-07-29 15:20:21 -0600312 fn protect_size(&self) -> u16 {
David Brown2b73ed92020-01-08 17:01:22 -0700313 if self.dependencies.is_empty() {
David Brown7a81c4b2019-07-29 15:20:21 -0600314 0
315 } else {
David Brown2b73ed92020-01-08 17:01:22 -0700316 // Include the header and space for each dependency.
317 4 + (self.dependencies.len() as u16) * (4 + 4 + 8)
David Brown7a81c4b2019-07-29 15:20:21 -0600318 }
319 }
320
321 fn add_dependency(&mut self, id: u8, version: &ImageVersion) {
David Brown7a81c4b2019-07-29 15:20:21 -0600322 self.dependencies.push(Dependency {
David Brown4dfb33c2021-03-10 05:15:45 -0700323 id,
David Brown7a81c4b2019-07-29 15:20:21 -0600324 version: version.clone(),
325 });
326 }
327
David Browne90b13f2019-12-06 15:04:00 -0700328 fn corrupt_sig(&mut self) {
329 self.gen_corrupted = true;
330 }
331
David Brown187dd882017-07-11 11:15:23 -0600332 /// Compute the TLV given the specified block of data.
David Brown43643dd2019-01-11 15:43:28 -0700333 fn make_tlv(self: Box<Self>) -> Vec<u8> {
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300334 let mut protected_tlv: Vec<u8> = vec![];
David Brown187dd882017-07-11 11:15:23 -0600335
David Brown2b73ed92020-01-08 17:01:22 -0700336 if self.protect_size() > 0 {
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300337 protected_tlv.push(0x08);
338 protected_tlv.push(0x69);
David Brown2b73ed92020-01-08 17:01:22 -0700339 let size = self.protect_size();
340 protected_tlv.write_u16::<LittleEndian>(size).unwrap();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300341 for dep in &self.dependencies {
David Brown69721182019-12-04 14:50:52 -0700342 protected_tlv.write_u16::<LittleEndian>(TlvKinds::DEPENDENCY as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700343 protected_tlv.write_u16::<LittleEndian>(12).unwrap();
David Brownf5b33d82017-09-01 10:58:27 -0600344
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300345 // The dependency.
346 protected_tlv.push(dep.id);
David Brownf66b2052021-03-10 05:26:36 -0700347 protected_tlv.push(0);
348 protected_tlv.write_u16::<LittleEndian>(0).unwrap();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300349 protected_tlv.push(dep.version.major);
350 protected_tlv.push(dep.version.minor);
351 protected_tlv.write_u16::<LittleEndian>(dep.version.revision).unwrap();
352 protected_tlv.write_u32::<LittleEndian>(dep.version.build_num).unwrap();
David Brown7a81c4b2019-07-29 15:20:21 -0600353 }
David Brown2b73ed92020-01-08 17:01:22 -0700354
355 assert_eq!(size, protected_tlv.len() as u16, "protected TLV length incorrect");
David Brown7a81c4b2019-07-29 15:20:21 -0600356 }
357
358 // Ring does the signature itself, which means that it must be
359 // given a full, contiguous payload. Although this does help from
360 // a correct usage perspective, it is fairly stupid from an
361 // efficiency view. If this is shown to be a performance issue
362 // with the tests, the protected data could be appended to the
363 // payload, and then removed after the signature is done. For now,
364 // just make a signed payload.
365 let mut sig_payload = self.payload.clone();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300366 sig_payload.extend_from_slice(&protected_tlv);
367
368 let mut result: Vec<u8> = vec![];
369
370 // add back signed payload
371 result.extend_from_slice(&protected_tlv);
372
373 // add non-protected payload
David Brown3dc86c92020-01-08 17:22:55 -0700374 let npro_pos = result.len();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300375 result.push(0x07);
376 result.push(0x69);
David Brown3dc86c92020-01-08 17:22:55 -0700377 // Placeholder for the size.
378 result.write_u16::<LittleEndian>(0).unwrap();
David Brown7a81c4b2019-07-29 15:20:21 -0600379
David Brown187dd882017-07-11 11:15:23 -0600380 if self.kinds.contains(&TlvKinds::SHA256) {
David Browne90b13f2019-12-06 15:04:00 -0700381 // If a signature is not requested, corrupt the hash we are
382 // generating. But, if there is a signature, output the
383 // correct hash. We want the hash test to pass so that the
384 // signature verification can be validated.
385 let mut corrupt_hash = self.gen_corrupted;
386 for k in &[TlvKinds::RSA2048, TlvKinds::RSA3072,
387 TlvKinds::ECDSA224, TlvKinds::ECDSA256,
388 TlvKinds::ED25519]
389 {
390 if self.kinds.contains(k) {
391 corrupt_hash = false;
392 break;
393 }
394 }
395
396 if corrupt_hash {
397 sig_payload[0] ^= 1;
398 }
399
David Brown7a81c4b2019-07-29 15:20:21 -0600400 let hash = digest::digest(&digest::SHA256, &sig_payload);
David Brown8054ce22017-07-11 12:12:09 -0600401 let hash = hash.as_ref();
David Brown187dd882017-07-11 11:15:23 -0600402
David Brown8054ce22017-07-11 12:12:09 -0600403 assert!(hash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700404 result.write_u16::<LittleEndian>(TlvKinds::SHA256 as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700405 result.write_u16::<LittleEndian>(32).unwrap();
David Brown8054ce22017-07-11 12:12:09 -0600406 result.extend_from_slice(hash);
David Browne90b13f2019-12-06 15:04:00 -0700407
408 // Undo the corruption.
409 if corrupt_hash {
410 sig_payload[0] ^= 1;
411 }
412
413 }
414
415 if self.gen_corrupted {
416 // Corrupt what is signed by modifying the input to the
417 // signature code.
418 sig_payload[0] ^= 1;
David Brown187dd882017-07-11 11:15:23 -0600419 }
420
Fabio Utzig39297432019-05-08 18:51:10 -0300421 if self.kinds.contains(&TlvKinds::RSA2048) ||
422 self.kinds.contains(&TlvKinds::RSA3072) {
423
424 let is_rsa2048 = self.kinds.contains(&TlvKinds::RSA2048);
425
David Brown43cda332017-09-01 09:53:23 -0600426 // Output the hash of the public key.
Fabio Utzig39297432019-05-08 18:51:10 -0300427 let hash = if is_rsa2048 {
428 digest::digest(&digest::SHA256, RSA_PUB_KEY)
429 } else {
430 digest::digest(&digest::SHA256, RSA3072_PUB_KEY)
431 };
David Brown43cda332017-09-01 09:53:23 -0600432 let hash = hash.as_ref();
433
434 assert!(hash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700435 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700436 result.write_u16::<LittleEndian>(32).unwrap();
David Brown43cda332017-09-01 09:53:23 -0600437 result.extend_from_slice(hash);
438
David Brown7e701d82017-07-11 13:24:25 -0600439 // For now assume PSS.
Fabio Utzig39297432019-05-08 18:51:10 -0300440 let key_bytes = if is_rsa2048 {
441 pem::parse(include_bytes!("../../root-rsa-2048.pem").as_ref()).unwrap()
442 } else {
443 pem::parse(include_bytes!("../../root-rsa-3072.pem").as_ref()).unwrap()
444 };
David Brown7e701d82017-07-11 13:24:25 -0600445 assert_eq!(key_bytes.tag, "RSA PRIVATE KEY");
Fabio Utzig90f449e2019-10-24 07:43:53 -0300446 let key_pair = RsaKeyPair::from_der(&key_bytes.contents).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600447 let rng = rand::SystemRandom::new();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300448 let mut signature = vec![0; key_pair.public_modulus_len()];
Fabio Utzig39297432019-05-08 18:51:10 -0300449 if is_rsa2048 {
450 assert_eq!(signature.len(), 256);
451 } else {
452 assert_eq!(signature.len(), 384);
453 }
David Brown7a81c4b2019-07-29 15:20:21 -0600454 key_pair.sign(&RSA_PSS_SHA256, &rng, &sig_payload, &mut signature).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600455
Fabio Utzig39297432019-05-08 18:51:10 -0300456 if is_rsa2048 {
David Brown69721182019-12-04 14:50:52 -0700457 result.write_u16::<LittleEndian>(TlvKinds::RSA2048 as u16).unwrap();
Fabio Utzig39297432019-05-08 18:51:10 -0300458 } else {
David Brown69721182019-12-04 14:50:52 -0700459 result.write_u16::<LittleEndian>(TlvKinds::RSA3072 as u16).unwrap();
Fabio Utzig39297432019-05-08 18:51:10 -0300460 }
David Brown91d68632019-07-29 14:32:13 -0600461 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600462 result.extend_from_slice(&signature);
463 }
464
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200465 if self.kinds.contains(&TlvKinds::ECDSA256) {
466 let keyhash = digest::digest(&digest::SHA256, ECDSA256_PUB_KEY);
467 let keyhash = keyhash.as_ref();
468
469 assert!(keyhash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700470 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700471 result.write_u16::<LittleEndian>(32).unwrap();
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200472 result.extend_from_slice(keyhash);
473
Fabio Utzig05ab0142018-07-10 09:15:28 -0300474 let key_bytes = pem::parse(include_bytes!("../../root-ec-p256-pkcs8.pem").as_ref()).unwrap();
475 assert_eq!(key_bytes.tag, "PRIVATE KEY");
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200476
Fabio Utzig05ab0142018-07-10 09:15:28 -0300477 let key_pair = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING,
Fabio Utzig90f449e2019-10-24 07:43:53 -0300478 &key_bytes.contents).unwrap();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300479 let rng = rand::SystemRandom::new();
Fabio Utzig90f449e2019-10-24 07:43:53 -0300480 let signature = key_pair.sign(&rng, &sig_payload).unwrap();
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200481
David Brown69721182019-12-04 14:50:52 -0700482 result.write_u16::<LittleEndian>(TlvKinds::ECDSA256 as u16).unwrap();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300483
David Browna4c58642019-12-12 17:28:33 -0700484 let signature = signature.as_ref().to_vec();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300485
David Brown91d68632019-07-29 14:32:13 -0600486 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300487 result.extend_from_slice(signature.as_ref());
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200488 }
489
Fabio Utzig97710282019-05-24 17:44:49 -0300490 if self.kinds.contains(&TlvKinds::ED25519) {
491 let keyhash = digest::digest(&digest::SHA256, ED25519_PUB_KEY);
492 let keyhash = keyhash.as_ref();
493
494 assert!(keyhash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700495 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700496 result.write_u16::<LittleEndian>(32).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300497 result.extend_from_slice(keyhash);
498
David Brown7a81c4b2019-07-29 15:20:21 -0600499 let hash = digest::digest(&digest::SHA256, &sig_payload);
Fabio Utzig97710282019-05-24 17:44:49 -0300500 let hash = hash.as_ref();
501 assert!(hash.len() == 32);
502
503 let key_bytes = pem::parse(include_bytes!("../../root-ed25519.pem").as_ref()).unwrap();
504 assert_eq!(key_bytes.tag, "PRIVATE KEY");
505
Fabio Utzig90f449e2019-10-24 07:43:53 -0300506 let key_pair = Ed25519KeyPair::from_seed_and_public_key(
507 &key_bytes.contents[16..48], &ED25519_PUB_KEY[12..44]).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300508 let signature = key_pair.sign(&hash);
509
David Brown69721182019-12-04 14:50:52 -0700510 result.write_u16::<LittleEndian>(TlvKinds::ED25519 as u16).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300511
512 let signature = signature.as_ref().to_vec();
David Brown91d68632019-07-29 14:32:13 -0600513 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300514 result.extend_from_slice(signature.as_ref());
515 }
516
Fabio Utzig1e48b912018-09-18 09:04:18 -0300517 if self.kinds.contains(&TlvKinds::ENCRSA2048) {
518 let key_bytes = pem::parse(include_bytes!("../../enc-rsa2048-pub.pem")
519 .as_ref()).unwrap();
520 assert_eq!(key_bytes.tag, "PUBLIC KEY");
521
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300522 let cipherkey = self.get_enc_key();
523 let cipherkey = cipherkey.as_slice();
524 let encbuf = match c::rsa_oaep_encrypt(&key_bytes.contents, cipherkey) {
Fabio Utzig1e48b912018-09-18 09:04:18 -0300525 Ok(v) => v,
526 Err(_) => panic!("Failed to encrypt secret key"),
527 };
528
529 assert!(encbuf.len() == 256);
David Brown69721182019-12-04 14:50:52 -0700530 result.write_u16::<LittleEndian>(TlvKinds::ENCRSA2048 as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700531 result.write_u16::<LittleEndian>(256).unwrap();
Fabio Utzig1e48b912018-09-18 09:04:18 -0300532 result.extend_from_slice(&encbuf);
533 }
534
Salome Thirot0f641972021-05-14 11:19:55 +0100535 if self.kinds.contains(&TlvKinds::ENCKW) {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100536 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
537 let aes256 = (self.get_flags() & flag) == flag;
538 let key_bytes = if aes256 {
539 base64::decode(
540 include_str!("../../enc-aes256kw.b64").trim()).unwrap()
541 } else {
542 base64::decode(
543 include_str!("../../enc-aes128kw.b64").trim()).unwrap()
544 };
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300545 let cipherkey = self.get_enc_key();
546 let cipherkey = cipherkey.as_slice();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100547 let keylen = if aes256 { 32 } else { 16 };
548 let encbuf = match c::kw_encrypt(&key_bytes, cipherkey, keylen) {
Fabio Utzig1e48b912018-09-18 09:04:18 -0300549 Ok(v) => v,
550 Err(_) => panic!("Failed to encrypt secret key"),
551 };
552
Salome Thirot6fdbf552021-05-14 16:46:14 +0100553 let size = if aes256 { 40 } else { 24 };
554 assert!(encbuf.len() == size);
Salome Thirot0f641972021-05-14 11:19:55 +0100555 result.write_u16::<LittleEndian>(TlvKinds::ENCKW as u16).unwrap();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100556 result.write_u16::<LittleEndian>(size as u16).unwrap();
Fabio Utzig1e48b912018-09-18 09:04:18 -0300557 result.extend_from_slice(&encbuf);
558 }
559
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300560 if self.kinds.contains(&TlvKinds::ENCEC256) || self.kinds.contains(&TlvKinds::ENCX25519) {
561 let key_bytes = if self.kinds.contains(&TlvKinds::ENCEC256) {
562 pem::parse(include_bytes!("../../enc-ec256-pub.pem").as_ref()).unwrap()
563 } else {
564 pem::parse(include_bytes!("../../enc-x25519-pub.pem").as_ref()).unwrap()
565 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300566 assert_eq!(key_bytes.tag, "PUBLIC KEY");
Fabio Utzig90f449e2019-10-24 07:43:53 -0300567 let rng = rand::SystemRandom::new();
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300568 let alg = if self.kinds.contains(&TlvKinds::ENCEC256) {
569 &agreement::ECDH_P256
570 } else {
571 &agreement::X25519
572 };
573 let pk = match agreement::EphemeralPrivateKey::generate(alg, &rng) {
Fabio Utzig90f449e2019-10-24 07:43:53 -0300574 Ok(v) => v,
575 Err(_) => panic!("Failed to generate ephemeral keypair"),
576 };
577
578 let pubk = match pk.compute_public_key() {
579 Ok(pubk) => pubk,
580 Err(_) => panic!("Failed computing ephemeral public key"),
581 };
582
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300583 let peer_pubk = if self.kinds.contains(&TlvKinds::ENCEC256) {
584 agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, &key_bytes.contents[26..])
585 } else {
586 agreement::UnparsedPublicKey::new(&agreement::X25519, &key_bytes.contents[12..])
587 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300588
589 #[derive(Debug, PartialEq)]
590 struct OkmLen<T: core::fmt::Debug + PartialEq>(T);
591
592 impl hkdf::KeyType for OkmLen<usize> {
593 fn len(&self) -> usize {
594 self.0
595 }
596 }
597
Salome Thirot6fdbf552021-05-14 16:46:14 +0100598 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
599 let aes256 = (self.get_flags() & flag) == flag;
600
Fabio Utzig90f449e2019-10-24 07:43:53 -0300601 let derived_key = match agreement::agree_ephemeral(
602 pk, &peer_pubk, ring::error::Unspecified, |shared| {
603 let salt = hkdf::Salt::new(hkdf::HKDF_SHA256, &[]);
604 let prk = salt.extract(&shared);
Salome Thirot6fdbf552021-05-14 16:46:14 +0100605 let okm_len = if aes256 { 64 } else { 48 };
606 let okm = match prk.expand(&[b"MCUBoot_ECIES_v1"], OkmLen(okm_len)) {
Fabio Utzig90f449e2019-10-24 07:43:53 -0300607 Ok(okm) => okm,
608 Err(_) => panic!("Failed building HKDF OKM"),
609 };
Salome Thirot6fdbf552021-05-14 16:46:14 +0100610 let mut buf = if aes256 { vec![0u8; 64] } else { vec![0u8; 48] };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300611 match okm.fill(&mut buf) {
612 Ok(_) => Ok(buf),
613 Err(_) => panic!("Failed generating HKDF output"),
614 }
615 },
616 ) {
617 Ok(v) => v,
618 Err(_) => panic!("Failed building HKDF"),
619 };
620
Fabio Utzig90f449e2019-10-24 07:43:53 -0300621 let nonce = GenericArray::from_slice(&[0; 16]);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300622 let mut cipherkey = self.get_enc_key();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100623 if aes256 {
624 let key: &GenericArray<u8, U32> = GenericArray::from_slice(&derived_key[..32]);
625 let mut cipher = Aes256Ctr::new(&key, &nonce);
626 cipher.apply_keystream(&mut cipherkey);
627 } else {
628 let key: &GenericArray<u8, U16> = GenericArray::from_slice(&derived_key[..16]);
629 let mut cipher = Aes128Ctr::new(&key, &nonce);
630 cipher.apply_keystream(&mut cipherkey);
631 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300632
Salome Thirot6fdbf552021-05-14 16:46:14 +0100633 let size = if aes256 { 32 } else { 16 };
634 let key = hmac::Key::new(hmac::HMAC_SHA256, &derived_key[size..]);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300635 let tag = hmac::sign(&key, &cipherkey);
636
637 let mut buf = vec![];
638 buf.append(&mut pubk.as_ref().to_vec());
639 buf.append(&mut tag.as_ref().to_vec());
640 buf.append(&mut cipherkey);
641
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300642 if self.kinds.contains(&TlvKinds::ENCEC256) {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100643 let size = if aes256 { 129 } else { 113 };
644 assert!(buf.len() == size);
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300645 result.write_u16::<LittleEndian>(TlvKinds::ENCEC256 as u16).unwrap();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100646 result.write_u16::<LittleEndian>(size as u16).unwrap();
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300647 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100648 let size = if aes256 { 96 } else { 80 };
649 assert!(buf.len() == size);
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300650 result.write_u16::<LittleEndian>(TlvKinds::ENCX25519 as u16).unwrap();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100651 result.write_u16::<LittleEndian>(size as u16).unwrap();
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300652 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300653 result.extend_from_slice(&buf);
654 }
655
David Brown3dc86c92020-01-08 17:22:55 -0700656 // Patch the size back into the TLV header.
657 let size = (result.len() - npro_pos) as u16;
658 let mut size_buf = &mut result[npro_pos + 2 .. npro_pos + 4];
659 size_buf.write_u16::<LittleEndian>(size).unwrap();
660
David Brown187dd882017-07-11 11:15:23 -0600661 result
662 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300663
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300664 fn generate_enc_key(&mut self) {
665 let rng = rand::SystemRandom::new();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100666 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
667 let aes256 = (self.get_flags() & flag) == flag;
668 let mut buf = if aes256 {
669 vec![0u8; 32]
670 } else {
671 vec![0u8; 16]
672 };
David Brown26edaf32021-03-10 05:27:38 -0700673 if rng.fill(&mut buf).is_err() {
674 panic!("Error generating encrypted key");
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300675 }
676 info!("New encryption key: {:02x?}", buf);
677 self.enc_key = buf;
Fabio Utzig90f449e2019-10-24 07:43:53 -0300678 }
679
680 fn get_enc_key(&self) -> Vec<u8> {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100681 if self.enc_key.len() != 32 && self.enc_key.len() != 16 {
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300682 panic!("No random key was generated");
683 }
684 self.enc_key.clone()
Fabio Utzig90f449e2019-10-24 07:43:53 -0300685 }
David Brown187dd882017-07-11 11:15:23 -0600686}
David Brown43cda332017-09-01 09:53:23 -0600687
688include!("rsa_pub_key-rs.txt");
Fabio Utzig39297432019-05-08 18:51:10 -0300689include!("rsa3072_pub_key-rs.txt");
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200690include!("ecdsa_pub_key-rs.txt");
Fabio Utzig97710282019-05-24 17:44:49 -0300691include!("ed25519_pub_key-rs.txt");