blob: 051e72acc1ae23533cef4c55e8b0b671d18e74e8 [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 Brown9c6322f2021-08-19 13:03:39 -060020use cipher::FromBlockCipher;
David Brown8a4e23b2021-06-11 10:29:01 -060021use crate::caps::Caps;
David Brown7a81c4b2019-07-29 15:20:21 -060022use crate::image::ImageVersion;
Fabio Utzige84f0ef2019-11-22 12:29:32 -030023use log::info;
Fabio Utzig90f449e2019-10-24 07:43:53 -030024use ring::{digest, rand, agreement, hkdf, hmac};
Fabio Utzige84f0ef2019-11-22 12:29:32 -030025use ring::rand::SecureRandom;
Fabio Utzig05ab0142018-07-10 09:15:28 -030026use ring::signature::{
27 RsaKeyPair,
28 RSA_PSS_SHA256,
29 EcdsaKeyPair,
30 ECDSA_P256_SHA256_ASN1_SIGNING,
Fabio Utzig97710282019-05-24 17:44:49 -030031 Ed25519KeyPair,
Fabio Utzig05ab0142018-07-10 09:15:28 -030032};
David Brown9c6322f2021-08-19 13:03:39 -060033use aes::{
34 Aes128,
Fabio Utzig90f449e2019-10-24 07:43:53 -030035 Aes128Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060036 Aes256,
Salome Thirot6fdbf552021-05-14 16:46:14 +010037 Aes256Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060038 NewBlockCipher
39};
40use cipher::{
41 generic_array::GenericArray,
42 StreamCipher,
Fabio Utzig90f449e2019-10-24 07:43:53 -030043};
Fabio Utzig80fde2f2017-12-05 09:25:31 -020044use mcuboot_sys::c;
Salome Thirot6fdbf552021-05-14 16:46:14 +010045use typenum::{U16, U32};
David Brown187dd882017-07-11 11:15:23 -060046
David Brown69721182019-12-04 14:50:52 -070047#[repr(u16)]
David Brownc3898d62019-08-05 14:20:02 -060048#[derive(Copy, Clone, Debug, PartialEq, Eq)]
David Brown187dd882017-07-11 11:15:23 -060049#[allow(dead_code)] // TODO: For now
50pub enum TlvKinds {
David Brown43cda332017-09-01 09:53:23 -060051 KEYHASH = 0x01,
David Brown27648b82017-08-31 10:40:29 -060052 SHA256 = 0x10,
53 RSA2048 = 0x20,
54 ECDSA224 = 0x21,
55 ECDSA256 = 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,
Fabio Utzig1e48b912018-09-18 09:04:18 -030063}
64
65#[allow(dead_code, non_camel_case_types)]
66pub enum TlvFlags {
67 PIC = 0x01,
68 NON_BOOTABLE = 0x02,
Salome Thirot6fdbf552021-05-14 16:46:14 +010069 ENCRYPTED_AES128 = 0x04,
Salome Thirot6fdbf552021-05-14 16:46:14 +010070 ENCRYPTED_AES256 = 0x08,
David Brownd8713a52021-10-22 16:27:23 -060071 RAM_LOAD = 0x20,
David Brown187dd882017-07-11 11:15:23 -060072}
73
David Brown43643dd2019-01-11 15:43:28 -070074/// A generator for manifests. The format of the manifest can be either a
75/// traditional "TLV" or a SUIT-style manifest.
76pub trait ManifestGen {
David Brownac46e262019-01-11 15:46:18 -070077 /// Retrieve the header magic value for this manifest type.
78 fn get_magic(&self) -> u32;
79
David Brown43643dd2019-01-11 15:43:28 -070080 /// Retrieve the flags value for this particular manifest type.
81 fn get_flags(&self) -> u32;
82
David Brown7a81c4b2019-07-29 15:20:21 -060083 /// Retrieve the number of bytes of this manifest that is "protected".
84 /// This field is stored in the outside image header instead of the
85 /// manifest header.
86 fn protect_size(&self) -> u16;
87
88 /// Add a dependency on another image.
89 fn add_dependency(&mut self, id: u8, version: &ImageVersion);
90
David Brown43643dd2019-01-11 15:43:28 -070091 /// Add a sequence of bytes to the payload that the manifest is
92 /// protecting.
93 fn add_bytes(&mut self, bytes: &[u8]);
94
David Browne90b13f2019-12-06 15:04:00 -070095 /// Set an internal flag indicating that the next `make_tlv` should
96 /// corrupt the signature.
97 fn corrupt_sig(&mut self);
98
David Brown43643dd2019-01-11 15:43:28 -070099 /// Construct the manifest for this payload.
100 fn make_tlv(self: Box<Self>) -> Vec<u8>;
Fabio Utzig90f449e2019-10-24 07:43:53 -0300101
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300102 /// Generate a new encryption random key
103 fn generate_enc_key(&mut self);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300104
105 /// Return the current encryption key
106 fn get_enc_key(&self) -> Vec<u8>;
David Brown43643dd2019-01-11 15:43:28 -0700107}
108
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300109#[derive(Debug, Default)]
David Brown187dd882017-07-11 11:15:23 -0600110pub struct TlvGen {
David Brown43cda332017-09-01 09:53:23 -0600111 flags: u32,
David Brown187dd882017-07-11 11:15:23 -0600112 kinds: Vec<TlvKinds>,
David Brown4243ab02017-07-11 12:24:23 -0600113 payload: Vec<u8>,
David Brown7a81c4b2019-07-29 15:20:21 -0600114 dependencies: Vec<Dependency>,
Fabio Utzig90f449e2019-10-24 07:43:53 -0300115 enc_key: Vec<u8>,
David Browne90b13f2019-12-06 15:04:00 -0700116 /// Should this signature be corrupted.
117 gen_corrupted: bool,
David Brown7a81c4b2019-07-29 15:20:21 -0600118}
119
David Brownc3898d62019-08-05 14:20:02 -0600120#[derive(Debug)]
David Brown7a81c4b2019-07-29 15:20:21 -0600121struct Dependency {
122 id: u8,
123 version: ImageVersion,
David Brown187dd882017-07-11 11:15:23 -0600124}
125
126impl TlvGen {
127 /// Construct a new tlv generator that will only contain a hash of the data.
David Brown7e701d82017-07-11 13:24:25 -0600128 #[allow(dead_code)]
David Brown187dd882017-07-11 11:15:23 -0600129 pub fn new_hash_only() -> TlvGen {
130 TlvGen {
David Brown187dd882017-07-11 11:15:23 -0600131 kinds: vec![TlvKinds::SHA256],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300132 ..Default::default()
David Brown187dd882017-07-11 11:15:23 -0600133 }
134 }
135
David Brown7e701d82017-07-11 13:24:25 -0600136 #[allow(dead_code)]
137 pub fn new_rsa_pss() -> TlvGen {
138 TlvGen {
Fabio Utzig754438d2018-12-14 06:39:58 -0200139 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300140 ..Default::default()
David Brown7e701d82017-07-11 13:24:25 -0600141 }
142 }
143
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200144 #[allow(dead_code)]
Fabio Utzig39297432019-05-08 18:51:10 -0300145 pub fn new_rsa3072_pss() -> TlvGen {
146 TlvGen {
Fabio Utzig39297432019-05-08 18:51:10 -0300147 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA3072],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300148 ..Default::default()
Fabio Utzig39297432019-05-08 18:51:10 -0300149 }
150 }
151
152 #[allow(dead_code)]
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200153 pub fn new_ecdsa() -> TlvGen {
154 TlvGen {
Fabio Utzig754438d2018-12-14 06:39:58 -0200155 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSA256],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300156 ..Default::default()
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200157 }
158 }
159
Fabio Utzig1e48b912018-09-18 09:04:18 -0300160 #[allow(dead_code)]
Fabio Utzig97710282019-05-24 17:44:49 -0300161 pub fn new_ed25519() -> TlvGen {
162 TlvGen {
Fabio Utzig97710282019-05-24 17:44:49 -0300163 kinds: vec![TlvKinds::SHA256, TlvKinds::ED25519],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300164 ..Default::default()
Fabio Utzig97710282019-05-24 17:44:49 -0300165 }
166 }
167
168 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100169 pub fn new_enc_rsa(aes_key_size: u32) -> TlvGen {
170 let flag = if aes_key_size == 256 {
171 TlvFlags::ENCRYPTED_AES256 as u32
172 } else {
173 TlvFlags::ENCRYPTED_AES128 as u32
174 };
Fabio Utzig1e48b912018-09-18 09:04:18 -0300175 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100176 flags: flag,
Fabio Utzig1e48b912018-09-18 09:04:18 -0300177 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCRSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300178 ..Default::default()
Fabio Utzig1e48b912018-09-18 09:04:18 -0300179 }
180 }
181
182 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100183 pub fn new_sig_enc_rsa(aes_key_size: u32) -> TlvGen {
184 let flag = if aes_key_size == 256 {
185 TlvFlags::ENCRYPTED_AES256 as u32
186 } else {
187 TlvFlags::ENCRYPTED_AES128 as u32
188 };
Fabio Utzig754438d2018-12-14 06:39:58 -0200189 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100190 flags: flag,
Fabio Utzig754438d2018-12-14 06:39:58 -0200191 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048, TlvKinds::ENCRSA2048],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300192 ..Default::default()
Fabio Utzig754438d2018-12-14 06:39:58 -0200193 }
194 }
195
196 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100197 pub fn new_enc_kw(aes_key_size: u32) -> TlvGen {
198 let flag = if aes_key_size == 256 {
199 TlvFlags::ENCRYPTED_AES256 as u32
200 } else {
201 TlvFlags::ENCRYPTED_AES128 as u32
202 };
Fabio Utzig1e48b912018-09-18 09:04:18 -0300203 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100204 flags: flag,
Salome Thirot0f641972021-05-14 11:19:55 +0100205 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300206 ..Default::default()
Fabio Utzig1e48b912018-09-18 09:04:18 -0300207 }
208 }
209
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200210 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100211 pub fn new_rsa_kw(aes_key_size: u32) -> TlvGen {
212 let flag = if aes_key_size == 256 {
213 TlvFlags::ENCRYPTED_AES256 as u32
214 } else {
215 TlvFlags::ENCRYPTED_AES128 as u32
216 };
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200217 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100218 flags: flag,
Salome Thirot0f641972021-05-14 11:19:55 +0100219 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300220 ..Default::default()
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200221 }
222 }
223
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200224 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100225 pub fn new_ecdsa_kw(aes_key_size: u32) -> TlvGen {
226 let flag = if aes_key_size == 256 {
227 TlvFlags::ENCRYPTED_AES256 as u32
228 } else {
229 TlvFlags::ENCRYPTED_AES128 as u32
230 };
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200231 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100232 flags: flag,
Salome Thirot0f641972021-05-14 11:19:55 +0100233 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSA256, TlvKinds::ENCKW],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300234 ..Default::default()
Fabio Utzig90f449e2019-10-24 07:43:53 -0300235 }
236 }
237
238 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100239 pub fn new_ecies_p256(aes_key_size: u32) -> TlvGen {
240 let flag = if aes_key_size == 256 {
241 TlvFlags::ENCRYPTED_AES256 as u32
242 } else {
243 TlvFlags::ENCRYPTED_AES128 as u32
244 };
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300245 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100246 flags: flag,
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300247 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCEC256],
Fabio Utzig66b4caa2020-01-04 20:19:28 -0300248 ..Default::default()
249 }
250 }
251
252 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100253 pub fn new_ecdsa_ecies_p256(aes_key_size: u32) -> TlvGen {
254 let flag = if aes_key_size == 256 {
255 TlvFlags::ENCRYPTED_AES256 as u32
256 } else {
257 TlvFlags::ENCRYPTED_AES128 as u32
258 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300259 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100260 flags: flag,
Fabio Utzig90f449e2019-10-24 07:43:53 -0300261 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSA256, TlvKinds::ENCEC256],
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300262 ..Default::default()
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200263 }
264 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300265
266 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100267 pub fn new_ecies_x25519(aes_key_size: u32) -> TlvGen {
268 let flag = if aes_key_size == 256 {
269 TlvFlags::ENCRYPTED_AES256 as u32
270 } else {
271 TlvFlags::ENCRYPTED_AES128 as u32
272 };
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300273 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100274 flags: flag,
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300275 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCX25519],
276 ..Default::default()
277 }
278 }
279
280 #[allow(dead_code)]
Salome Thirot6fdbf552021-05-14 16:46:14 +0100281 pub fn new_ed25519_ecies_x25519(aes_key_size: u32) -> TlvGen {
282 let flag = if aes_key_size == 256 {
283 TlvFlags::ENCRYPTED_AES256 as u32
284 } else {
285 TlvFlags::ENCRYPTED_AES128 as u32
286 };
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300287 TlvGen {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100288 flags: flag,
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300289 kinds: vec![TlvKinds::SHA256, TlvKinds::ED25519, TlvKinds::ENCX25519],
290 ..Default::default()
291 }
292 }
David Brown43643dd2019-01-11 15:43:28 -0700293}
294
295impl ManifestGen for TlvGen {
David Brownac46e262019-01-11 15:46:18 -0700296 fn get_magic(&self) -> u32 {
297 0x96f3b83d
298 }
299
David Brown43643dd2019-01-11 15:43:28 -0700300 /// Retrieve the header flags for this configuration. This can be called at any time.
301 fn get_flags(&self) -> u32 {
David Brown8a4e23b2021-06-11 10:29:01 -0600302 // For the RamLoad case, add in the flag for this feature.
303 if Caps::RamLoad.present() {
304 self.flags | (TlvFlags::RAM_LOAD as u32)
305 } else {
306 self.flags
307 }
David Brown43643dd2019-01-11 15:43:28 -0700308 }
David Brown187dd882017-07-11 11:15:23 -0600309
310 /// Add bytes to the covered hash.
David Brown43643dd2019-01-11 15:43:28 -0700311 fn add_bytes(&mut self, bytes: &[u8]) {
David Brown4243ab02017-07-11 12:24:23 -0600312 self.payload.extend_from_slice(bytes);
David Brown187dd882017-07-11 11:15:23 -0600313 }
314
David Brown7a81c4b2019-07-29 15:20:21 -0600315 fn protect_size(&self) -> u16 {
David Brown2b73ed92020-01-08 17:01:22 -0700316 if self.dependencies.is_empty() {
David Brown7a81c4b2019-07-29 15:20:21 -0600317 0
318 } else {
David Brown2b73ed92020-01-08 17:01:22 -0700319 // Include the header and space for each dependency.
320 4 + (self.dependencies.len() as u16) * (4 + 4 + 8)
David Brown7a81c4b2019-07-29 15:20:21 -0600321 }
322 }
323
324 fn add_dependency(&mut self, id: u8, version: &ImageVersion) {
David Brown7a81c4b2019-07-29 15:20:21 -0600325 self.dependencies.push(Dependency {
David Brown4dfb33c2021-03-10 05:15:45 -0700326 id,
David Brown7a81c4b2019-07-29 15:20:21 -0600327 version: version.clone(),
328 });
329 }
330
David Browne90b13f2019-12-06 15:04:00 -0700331 fn corrupt_sig(&mut self) {
332 self.gen_corrupted = true;
333 }
334
David Brown187dd882017-07-11 11:15:23 -0600335 /// Compute the TLV given the specified block of data.
David Brown43643dd2019-01-11 15:43:28 -0700336 fn make_tlv(self: Box<Self>) -> Vec<u8> {
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300337 let mut protected_tlv: Vec<u8> = vec![];
David Brown187dd882017-07-11 11:15:23 -0600338
David Brown2b73ed92020-01-08 17:01:22 -0700339 if self.protect_size() > 0 {
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300340 protected_tlv.push(0x08);
341 protected_tlv.push(0x69);
David Brown2b73ed92020-01-08 17:01:22 -0700342 let size = self.protect_size();
343 protected_tlv.write_u16::<LittleEndian>(size).unwrap();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300344 for dep in &self.dependencies {
David Brown69721182019-12-04 14:50:52 -0700345 protected_tlv.write_u16::<LittleEndian>(TlvKinds::DEPENDENCY as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700346 protected_tlv.write_u16::<LittleEndian>(12).unwrap();
David Brownf5b33d82017-09-01 10:58:27 -0600347
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300348 // The dependency.
349 protected_tlv.push(dep.id);
David Brownf66b2052021-03-10 05:26:36 -0700350 protected_tlv.push(0);
351 protected_tlv.write_u16::<LittleEndian>(0).unwrap();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300352 protected_tlv.push(dep.version.major);
353 protected_tlv.push(dep.version.minor);
354 protected_tlv.write_u16::<LittleEndian>(dep.version.revision).unwrap();
355 protected_tlv.write_u32::<LittleEndian>(dep.version.build_num).unwrap();
David Brown7a81c4b2019-07-29 15:20:21 -0600356 }
David Brown2b73ed92020-01-08 17:01:22 -0700357
358 assert_eq!(size, protected_tlv.len() as u16, "protected TLV length incorrect");
David Brown7a81c4b2019-07-29 15:20:21 -0600359 }
360
361 // Ring does the signature itself, which means that it must be
362 // given a full, contiguous payload. Although this does help from
363 // a correct usage perspective, it is fairly stupid from an
364 // efficiency view. If this is shown to be a performance issue
365 // with the tests, the protected data could be appended to the
366 // payload, and then removed after the signature is done. For now,
367 // just make a signed payload.
368 let mut sig_payload = self.payload.clone();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300369 sig_payload.extend_from_slice(&protected_tlv);
370
371 let mut result: Vec<u8> = vec![];
372
373 // add back signed payload
374 result.extend_from_slice(&protected_tlv);
375
376 // add non-protected payload
David Brown3dc86c92020-01-08 17:22:55 -0700377 let npro_pos = result.len();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300378 result.push(0x07);
379 result.push(0x69);
David Brown3dc86c92020-01-08 17:22:55 -0700380 // Placeholder for the size.
381 result.write_u16::<LittleEndian>(0).unwrap();
David Brown7a81c4b2019-07-29 15:20:21 -0600382
David Brown187dd882017-07-11 11:15:23 -0600383 if self.kinds.contains(&TlvKinds::SHA256) {
David Browne90b13f2019-12-06 15:04:00 -0700384 // If a signature is not requested, corrupt the hash we are
385 // generating. But, if there is a signature, output the
386 // correct hash. We want the hash test to pass so that the
387 // signature verification can be validated.
388 let mut corrupt_hash = self.gen_corrupted;
389 for k in &[TlvKinds::RSA2048, TlvKinds::RSA3072,
390 TlvKinds::ECDSA224, TlvKinds::ECDSA256,
391 TlvKinds::ED25519]
392 {
393 if self.kinds.contains(k) {
394 corrupt_hash = false;
395 break;
396 }
397 }
398
399 if corrupt_hash {
400 sig_payload[0] ^= 1;
401 }
402
David Brown7a81c4b2019-07-29 15:20:21 -0600403 let hash = digest::digest(&digest::SHA256, &sig_payload);
David Brown8054ce22017-07-11 12:12:09 -0600404 let hash = hash.as_ref();
David Brown187dd882017-07-11 11:15:23 -0600405
David Brown8054ce22017-07-11 12:12:09 -0600406 assert!(hash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700407 result.write_u16::<LittleEndian>(TlvKinds::SHA256 as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700408 result.write_u16::<LittleEndian>(32).unwrap();
David Brown8054ce22017-07-11 12:12:09 -0600409 result.extend_from_slice(hash);
David Browne90b13f2019-12-06 15:04:00 -0700410
411 // Undo the corruption.
412 if corrupt_hash {
413 sig_payload[0] ^= 1;
414 }
415
416 }
417
418 if self.gen_corrupted {
419 // Corrupt what is signed by modifying the input to the
420 // signature code.
421 sig_payload[0] ^= 1;
David Brown187dd882017-07-11 11:15:23 -0600422 }
423
Fabio Utzig39297432019-05-08 18:51:10 -0300424 if self.kinds.contains(&TlvKinds::RSA2048) ||
425 self.kinds.contains(&TlvKinds::RSA3072) {
426
427 let is_rsa2048 = self.kinds.contains(&TlvKinds::RSA2048);
428
David Brown43cda332017-09-01 09:53:23 -0600429 // Output the hash of the public key.
Fabio Utzig39297432019-05-08 18:51:10 -0300430 let hash = if is_rsa2048 {
431 digest::digest(&digest::SHA256, RSA_PUB_KEY)
432 } else {
433 digest::digest(&digest::SHA256, RSA3072_PUB_KEY)
434 };
David Brown43cda332017-09-01 09:53:23 -0600435 let hash = hash.as_ref();
436
437 assert!(hash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700438 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700439 result.write_u16::<LittleEndian>(32).unwrap();
David Brown43cda332017-09-01 09:53:23 -0600440 result.extend_from_slice(hash);
441
David Brown7e701d82017-07-11 13:24:25 -0600442 // For now assume PSS.
Fabio Utzig39297432019-05-08 18:51:10 -0300443 let key_bytes = if is_rsa2048 {
444 pem::parse(include_bytes!("../../root-rsa-2048.pem").as_ref()).unwrap()
445 } else {
446 pem::parse(include_bytes!("../../root-rsa-3072.pem").as_ref()).unwrap()
447 };
David Brown7e701d82017-07-11 13:24:25 -0600448 assert_eq!(key_bytes.tag, "RSA PRIVATE KEY");
Fabio Utzig90f449e2019-10-24 07:43:53 -0300449 let key_pair = RsaKeyPair::from_der(&key_bytes.contents).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600450 let rng = rand::SystemRandom::new();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300451 let mut signature = vec![0; key_pair.public_modulus_len()];
Fabio Utzig39297432019-05-08 18:51:10 -0300452 if is_rsa2048 {
453 assert_eq!(signature.len(), 256);
454 } else {
455 assert_eq!(signature.len(), 384);
456 }
David Brown7a81c4b2019-07-29 15:20:21 -0600457 key_pair.sign(&RSA_PSS_SHA256, &rng, &sig_payload, &mut signature).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600458
Fabio Utzig39297432019-05-08 18:51:10 -0300459 if is_rsa2048 {
David Brown69721182019-12-04 14:50:52 -0700460 result.write_u16::<LittleEndian>(TlvKinds::RSA2048 as u16).unwrap();
Fabio Utzig39297432019-05-08 18:51:10 -0300461 } else {
David Brown69721182019-12-04 14:50:52 -0700462 result.write_u16::<LittleEndian>(TlvKinds::RSA3072 as u16).unwrap();
Fabio Utzig39297432019-05-08 18:51:10 -0300463 }
David Brown91d68632019-07-29 14:32:13 -0600464 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600465 result.extend_from_slice(&signature);
466 }
467
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200468 if self.kinds.contains(&TlvKinds::ECDSA256) {
469 let keyhash = digest::digest(&digest::SHA256, ECDSA256_PUB_KEY);
470 let keyhash = keyhash.as_ref();
471
472 assert!(keyhash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700473 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700474 result.write_u16::<LittleEndian>(32).unwrap();
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200475 result.extend_from_slice(keyhash);
476
Fabio Utzig05ab0142018-07-10 09:15:28 -0300477 let key_bytes = pem::parse(include_bytes!("../../root-ec-p256-pkcs8.pem").as_ref()).unwrap();
478 assert_eq!(key_bytes.tag, "PRIVATE KEY");
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200479
Fabio Utzig05ab0142018-07-10 09:15:28 -0300480 let key_pair = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING,
Fabio Utzig90f449e2019-10-24 07:43:53 -0300481 &key_bytes.contents).unwrap();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300482 let rng = rand::SystemRandom::new();
Fabio Utzig90f449e2019-10-24 07:43:53 -0300483 let signature = key_pair.sign(&rng, &sig_payload).unwrap();
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200484
David Brown69721182019-12-04 14:50:52 -0700485 result.write_u16::<LittleEndian>(TlvKinds::ECDSA256 as u16).unwrap();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300486
David Browna4c58642019-12-12 17:28:33 -0700487 let signature = signature.as_ref().to_vec();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300488
David Brown91d68632019-07-29 14:32:13 -0600489 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300490 result.extend_from_slice(signature.as_ref());
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200491 }
492
Fabio Utzig97710282019-05-24 17:44:49 -0300493 if self.kinds.contains(&TlvKinds::ED25519) {
494 let keyhash = digest::digest(&digest::SHA256, ED25519_PUB_KEY);
495 let keyhash = keyhash.as_ref();
496
497 assert!(keyhash.len() == 32);
David Brown69721182019-12-04 14:50:52 -0700498 result.write_u16::<LittleEndian>(TlvKinds::KEYHASH as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700499 result.write_u16::<LittleEndian>(32).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300500 result.extend_from_slice(keyhash);
501
David Brown7a81c4b2019-07-29 15:20:21 -0600502 let hash = digest::digest(&digest::SHA256, &sig_payload);
Fabio Utzig97710282019-05-24 17:44:49 -0300503 let hash = hash.as_ref();
504 assert!(hash.len() == 32);
505
506 let key_bytes = pem::parse(include_bytes!("../../root-ed25519.pem").as_ref()).unwrap();
507 assert_eq!(key_bytes.tag, "PRIVATE KEY");
508
Fabio Utzig90f449e2019-10-24 07:43:53 -0300509 let key_pair = Ed25519KeyPair::from_seed_and_public_key(
510 &key_bytes.contents[16..48], &ED25519_PUB_KEY[12..44]).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300511 let signature = key_pair.sign(&hash);
512
David Brown69721182019-12-04 14:50:52 -0700513 result.write_u16::<LittleEndian>(TlvKinds::ED25519 as u16).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300514
515 let signature = signature.as_ref().to_vec();
David Brown91d68632019-07-29 14:32:13 -0600516 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300517 result.extend_from_slice(signature.as_ref());
518 }
519
Fabio Utzig1e48b912018-09-18 09:04:18 -0300520 if self.kinds.contains(&TlvKinds::ENCRSA2048) {
521 let key_bytes = pem::parse(include_bytes!("../../enc-rsa2048-pub.pem")
522 .as_ref()).unwrap();
523 assert_eq!(key_bytes.tag, "PUBLIC KEY");
524
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300525 let cipherkey = self.get_enc_key();
526 let cipherkey = cipherkey.as_slice();
527 let encbuf = match c::rsa_oaep_encrypt(&key_bytes.contents, cipherkey) {
Fabio Utzig1e48b912018-09-18 09:04:18 -0300528 Ok(v) => v,
529 Err(_) => panic!("Failed to encrypt secret key"),
530 };
531
532 assert!(encbuf.len() == 256);
David Brown69721182019-12-04 14:50:52 -0700533 result.write_u16::<LittleEndian>(TlvKinds::ENCRSA2048 as u16).unwrap();
David Brown4fae8b82019-12-05 11:26:59 -0700534 result.write_u16::<LittleEndian>(256).unwrap();
Fabio Utzig1e48b912018-09-18 09:04:18 -0300535 result.extend_from_slice(&encbuf);
536 }
537
Salome Thirot0f641972021-05-14 11:19:55 +0100538 if self.kinds.contains(&TlvKinds::ENCKW) {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100539 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
540 let aes256 = (self.get_flags() & flag) == flag;
541 let key_bytes = if aes256 {
542 base64::decode(
543 include_str!("../../enc-aes256kw.b64").trim()).unwrap()
544 } else {
545 base64::decode(
546 include_str!("../../enc-aes128kw.b64").trim()).unwrap()
547 };
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300548 let cipherkey = self.get_enc_key();
549 let cipherkey = cipherkey.as_slice();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100550 let keylen = if aes256 { 32 } else { 16 };
551 let encbuf = match c::kw_encrypt(&key_bytes, cipherkey, keylen) {
Fabio Utzig1e48b912018-09-18 09:04:18 -0300552 Ok(v) => v,
553 Err(_) => panic!("Failed to encrypt secret key"),
554 };
555
Salome Thirot6fdbf552021-05-14 16:46:14 +0100556 let size = if aes256 { 40 } else { 24 };
557 assert!(encbuf.len() == size);
Salome Thirot0f641972021-05-14 11:19:55 +0100558 result.write_u16::<LittleEndian>(TlvKinds::ENCKW as u16).unwrap();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100559 result.write_u16::<LittleEndian>(size as u16).unwrap();
Fabio Utzig1e48b912018-09-18 09:04:18 -0300560 result.extend_from_slice(&encbuf);
561 }
562
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300563 if self.kinds.contains(&TlvKinds::ENCEC256) || self.kinds.contains(&TlvKinds::ENCX25519) {
564 let key_bytes = if self.kinds.contains(&TlvKinds::ENCEC256) {
565 pem::parse(include_bytes!("../../enc-ec256-pub.pem").as_ref()).unwrap()
566 } else {
567 pem::parse(include_bytes!("../../enc-x25519-pub.pem").as_ref()).unwrap()
568 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300569 assert_eq!(key_bytes.tag, "PUBLIC KEY");
Fabio Utzig90f449e2019-10-24 07:43:53 -0300570 let rng = rand::SystemRandom::new();
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300571 let alg = if self.kinds.contains(&TlvKinds::ENCEC256) {
572 &agreement::ECDH_P256
573 } else {
574 &agreement::X25519
575 };
576 let pk = match agreement::EphemeralPrivateKey::generate(alg, &rng) {
Fabio Utzig90f449e2019-10-24 07:43:53 -0300577 Ok(v) => v,
578 Err(_) => panic!("Failed to generate ephemeral keypair"),
579 };
580
581 let pubk = match pk.compute_public_key() {
582 Ok(pubk) => pubk,
583 Err(_) => panic!("Failed computing ephemeral public key"),
584 };
585
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300586 let peer_pubk = if self.kinds.contains(&TlvKinds::ENCEC256) {
587 agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, &key_bytes.contents[26..])
588 } else {
589 agreement::UnparsedPublicKey::new(&agreement::X25519, &key_bytes.contents[12..])
590 };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300591
592 #[derive(Debug, PartialEq)]
593 struct OkmLen<T: core::fmt::Debug + PartialEq>(T);
594
595 impl hkdf::KeyType for OkmLen<usize> {
596 fn len(&self) -> usize {
597 self.0
598 }
599 }
600
Salome Thirot6fdbf552021-05-14 16:46:14 +0100601 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
602 let aes256 = (self.get_flags() & flag) == flag;
603
Fabio Utzig90f449e2019-10-24 07:43:53 -0300604 let derived_key = match agreement::agree_ephemeral(
605 pk, &peer_pubk, ring::error::Unspecified, |shared| {
606 let salt = hkdf::Salt::new(hkdf::HKDF_SHA256, &[]);
607 let prk = salt.extract(&shared);
Salome Thirot6fdbf552021-05-14 16:46:14 +0100608 let okm_len = if aes256 { 64 } else { 48 };
609 let okm = match prk.expand(&[b"MCUBoot_ECIES_v1"], OkmLen(okm_len)) {
Fabio Utzig90f449e2019-10-24 07:43:53 -0300610 Ok(okm) => okm,
611 Err(_) => panic!("Failed building HKDF OKM"),
612 };
Salome Thirot6fdbf552021-05-14 16:46:14 +0100613 let mut buf = if aes256 { vec![0u8; 64] } else { vec![0u8; 48] };
Fabio Utzig90f449e2019-10-24 07:43:53 -0300614 match okm.fill(&mut buf) {
615 Ok(_) => Ok(buf),
616 Err(_) => panic!("Failed generating HKDF output"),
617 }
618 },
619 ) {
620 Ok(v) => v,
621 Err(_) => panic!("Failed building HKDF"),
622 };
623
Fabio Utzig90f449e2019-10-24 07:43:53 -0300624 let nonce = GenericArray::from_slice(&[0; 16]);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300625 let mut cipherkey = self.get_enc_key();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100626 if aes256 {
627 let key: &GenericArray<u8, U32> = GenericArray::from_slice(&derived_key[..32]);
David Brown9c6322f2021-08-19 13:03:39 -0600628 let block = Aes256::new(&key);
629 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +0100630 cipher.apply_keystream(&mut cipherkey);
631 } else {
632 let key: &GenericArray<u8, U16> = GenericArray::from_slice(&derived_key[..16]);
David Brown9c6322f2021-08-19 13:03:39 -0600633 let block = Aes128::new(&key);
634 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +0100635 cipher.apply_keystream(&mut cipherkey);
636 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300637
Salome Thirot6fdbf552021-05-14 16:46:14 +0100638 let size = if aes256 { 32 } else { 16 };
639 let key = hmac::Key::new(hmac::HMAC_SHA256, &derived_key[size..]);
Fabio Utzig90f449e2019-10-24 07:43:53 -0300640 let tag = hmac::sign(&key, &cipherkey);
641
642 let mut buf = vec![];
643 buf.append(&mut pubk.as_ref().to_vec());
644 buf.append(&mut tag.as_ref().to_vec());
645 buf.append(&mut cipherkey);
646
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300647 if self.kinds.contains(&TlvKinds::ENCEC256) {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100648 let size = if aes256 { 129 } else { 113 };
649 assert!(buf.len() == size);
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300650 result.write_u16::<LittleEndian>(TlvKinds::ENCEC256 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 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100653 let size = if aes256 { 96 } else { 80 };
654 assert!(buf.len() == size);
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300655 result.write_u16::<LittleEndian>(TlvKinds::ENCX25519 as u16).unwrap();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100656 result.write_u16::<LittleEndian>(size as u16).unwrap();
Fabio Utzig3fa72ca2020-04-02 11:20:37 -0300657 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300658 result.extend_from_slice(&buf);
659 }
660
David Brown3dc86c92020-01-08 17:22:55 -0700661 // Patch the size back into the TLV header.
662 let size = (result.len() - npro_pos) as u16;
663 let mut size_buf = &mut result[npro_pos + 2 .. npro_pos + 4];
664 size_buf.write_u16::<LittleEndian>(size).unwrap();
665
David Brown187dd882017-07-11 11:15:23 -0600666 result
667 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300668
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300669 fn generate_enc_key(&mut self) {
670 let rng = rand::SystemRandom::new();
Salome Thirot6fdbf552021-05-14 16:46:14 +0100671 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
672 let aes256 = (self.get_flags() & flag) == flag;
673 let mut buf = if aes256 {
674 vec![0u8; 32]
675 } else {
676 vec![0u8; 16]
677 };
David Brown26edaf32021-03-10 05:27:38 -0700678 if rng.fill(&mut buf).is_err() {
679 panic!("Error generating encrypted key");
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300680 }
681 info!("New encryption key: {:02x?}", buf);
682 self.enc_key = buf;
Fabio Utzig90f449e2019-10-24 07:43:53 -0300683 }
684
685 fn get_enc_key(&self) -> Vec<u8> {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100686 if self.enc_key.len() != 32 && self.enc_key.len() != 16 {
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300687 panic!("No random key was generated");
688 }
689 self.enc_key.clone()
Fabio Utzig90f449e2019-10-24 07:43:53 -0300690 }
David Brown187dd882017-07-11 11:15:23 -0600691}
David Brown43cda332017-09-01 09:53:23 -0600692
693include!("rsa_pub_key-rs.txt");
Fabio Utzig39297432019-05-08 18:51:10 -0300694include!("rsa3072_pub_key-rs.txt");
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200695include!("ecdsa_pub_key-rs.txt");
Fabio Utzig97710282019-05-24 17:44:49 -0300696include!("ed25519_pub_key-rs.txt");