blob: 073620dd92938f4b84916337daf3f047f354a5ec [file] [log] [blame]
David Brown187dd882017-07-11 11:15:23 -06001//! TLV Support
2//!
3//! mcuboot images are followed immediately by a list of TLV items that contain integrity
4//! information about the image. Their generation is made a little complicated because the size of
5//! the TLV block is in the image header, which is included in the hash. Since some signatures can
6//! vary in size, we just make them the largest size possible.
7//!
8//! Because of this header, we have to make two passes. The first pass will compute the size of
9//! the TLV, and the second pass will build the data for the TLV.
10
David Brown91d68632019-07-29 14:32:13 -060011use byteorder::{
12 LittleEndian, WriteBytesExt,
13};
David Brown7a81c4b2019-07-29 15:20:21 -060014use crate::image::ImageVersion;
David Brown7e701d82017-07-11 13:24:25 -060015use pem;
Fabio Utzig1e48b912018-09-18 09:04:18 -030016use base64;
Fabio Utzige84f0ef2019-11-22 12:29:32 -030017use log::info;
Fabio Utzig90f449e2019-10-24 07:43:53 -030018use ring::{digest, rand, agreement, hkdf, hmac};
Fabio Utzige84f0ef2019-11-22 12:29:32 -030019use ring::rand::SecureRandom;
Fabio Utzig05ab0142018-07-10 09:15:28 -030020use ring::signature::{
21 RsaKeyPair,
22 RSA_PSS_SHA256,
23 EcdsaKeyPair,
24 ECDSA_P256_SHA256_ASN1_SIGNING,
Fabio Utzig97710282019-05-24 17:44:49 -030025 Ed25519KeyPair,
Fabio Utzig05ab0142018-07-10 09:15:28 -030026};
Fabio Utzig90f449e2019-10-24 07:43:53 -030027use aes_ctr::{
28 Aes128Ctr,
29 stream_cipher::{
30 generic_array::GenericArray,
31 NewFixStreamCipher,
32 StreamCipherCore,
33 },
34};
Fabio Utzig80fde2f2017-12-05 09:25:31 -020035use mcuboot_sys::c;
David Brown187dd882017-07-11 11:15:23 -060036
David Brown187dd882017-07-11 11:15:23 -060037#[repr(u8)]
David Brownc3898d62019-08-05 14:20:02 -060038#[derive(Copy, Clone, Debug, PartialEq, Eq)]
David Brown187dd882017-07-11 11:15:23 -060039#[allow(dead_code)] // TODO: For now
40pub enum TlvKinds {
David Brown43cda332017-09-01 09:53:23 -060041 KEYHASH = 0x01,
David Brown27648b82017-08-31 10:40:29 -060042 SHA256 = 0x10,
43 RSA2048 = 0x20,
44 ECDSA224 = 0x21,
45 ECDSA256 = 0x22,
Fabio Utzig39297432019-05-08 18:51:10 -030046 RSA3072 = 0x23,
Fabio Utzig97710282019-05-24 17:44:49 -030047 ED25519 = 0x24,
Fabio Utzig1e48b912018-09-18 09:04:18 -030048 ENCRSA2048 = 0x30,
49 ENCKW128 = 0x31,
Fabio Utzig90f449e2019-10-24 07:43:53 -030050 ENCEC256 = 0x32,
David Brown7a81c4b2019-07-29 15:20:21 -060051 DEPENDENCY = 0x40,
Fabio Utzig1e48b912018-09-18 09:04:18 -030052}
53
54#[allow(dead_code, non_camel_case_types)]
55pub enum TlvFlags {
56 PIC = 0x01,
57 NON_BOOTABLE = 0x02,
58 ENCRYPTED = 0x04,
59 RAM_LOAD = 0x20,
David Brown187dd882017-07-11 11:15:23 -060060}
61
David Brown43643dd2019-01-11 15:43:28 -070062/// A generator for manifests. The format of the manifest can be either a
63/// traditional "TLV" or a SUIT-style manifest.
64pub trait ManifestGen {
David Brownac46e262019-01-11 15:46:18 -070065 /// Retrieve the header magic value for this manifest type.
66 fn get_magic(&self) -> u32;
67
David Brown43643dd2019-01-11 15:43:28 -070068 /// Retrieve the flags value for this particular manifest type.
69 fn get_flags(&self) -> u32;
70
David Brown7a81c4b2019-07-29 15:20:21 -060071 /// Retrieve the number of bytes of this manifest that is "protected".
72 /// This field is stored in the outside image header instead of the
73 /// manifest header.
74 fn protect_size(&self) -> u16;
75
76 /// Add a dependency on another image.
77 fn add_dependency(&mut self, id: u8, version: &ImageVersion);
78
David Brown43643dd2019-01-11 15:43:28 -070079 /// Add a sequence of bytes to the payload that the manifest is
80 /// protecting.
81 fn add_bytes(&mut self, bytes: &[u8]);
82
83 /// Construct the manifest for this payload.
84 fn make_tlv(self: Box<Self>) -> Vec<u8>;
Fabio Utzig90f449e2019-10-24 07:43:53 -030085
Fabio Utzige84f0ef2019-11-22 12:29:32 -030086 /// Generate a new encryption random key
87 fn generate_enc_key(&mut self);
Fabio Utzig90f449e2019-10-24 07:43:53 -030088
89 /// Return the current encryption key
90 fn get_enc_key(&self) -> Vec<u8>;
David Brown43643dd2019-01-11 15:43:28 -070091}
92
Fabio Utzig9a2b5de2019-11-22 12:50:02 -030093#[derive(Debug, Default)]
David Brown187dd882017-07-11 11:15:23 -060094pub struct TlvGen {
David Brown43cda332017-09-01 09:53:23 -060095 flags: u32,
David Brown187dd882017-07-11 11:15:23 -060096 kinds: Vec<TlvKinds>,
David Brown7a81c4b2019-07-29 15:20:21 -060097 /// The total size of the payload.
David Brown187dd882017-07-11 11:15:23 -060098 size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -060099 /// Extra bytes of the TLV that are protected.
100 protect_size: u16,
David Brown4243ab02017-07-11 12:24:23 -0600101 payload: Vec<u8>,
David Brown7a81c4b2019-07-29 15:20:21 -0600102 dependencies: Vec<Dependency>,
Fabio Utzig90f449e2019-10-24 07:43:53 -0300103 enc_key: Vec<u8>,
David Brown7a81c4b2019-07-29 15:20:21 -0600104}
105
David Brownc3898d62019-08-05 14:20:02 -0600106#[derive(Debug)]
David Brown7a81c4b2019-07-29 15:20:21 -0600107struct Dependency {
108 id: u8,
109 version: ImageVersion,
David Brown187dd882017-07-11 11:15:23 -0600110}
111
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300112const AES_KEY_LEN: usize = 16;
Fabio Utzig1e48b912018-09-18 09:04:18 -0300113
David Brown187dd882017-07-11 11:15:23 -0600114impl TlvGen {
115 /// Construct a new tlv generator that will only contain a hash of the data.
David Brown7e701d82017-07-11 13:24:25 -0600116 #[allow(dead_code)]
David Brown187dd882017-07-11 11:15:23 -0600117 pub fn new_hash_only() -> TlvGen {
118 TlvGen {
David Brown187dd882017-07-11 11:15:23 -0600119 kinds: vec![TlvKinds::SHA256],
120 size: 4 + 32,
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300121 ..Default::default()
David Brown187dd882017-07-11 11:15:23 -0600122 }
123 }
124
David Brown7e701d82017-07-11 13:24:25 -0600125 #[allow(dead_code)]
126 pub fn new_rsa_pss() -> TlvGen {
127 TlvGen {
Fabio Utzig754438d2018-12-14 06:39:58 -0200128 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048],
129 size: 4 + 32 + 4 + 32 + 4 + 256,
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300130 ..Default::default()
David Brown7e701d82017-07-11 13:24:25 -0600131 }
132 }
133
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200134 #[allow(dead_code)]
Fabio Utzig39297432019-05-08 18:51:10 -0300135 pub fn new_rsa3072_pss() -> TlvGen {
136 TlvGen {
Fabio Utzig39297432019-05-08 18:51:10 -0300137 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA3072],
138 size: 4 + 32 + 4 + 32 + 4 + 384,
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300139 ..Default::default()
Fabio Utzig39297432019-05-08 18:51:10 -0300140 }
141 }
142
143 #[allow(dead_code)]
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200144 pub fn new_ecdsa() -> TlvGen {
145 TlvGen {
Fabio Utzig754438d2018-12-14 06:39:58 -0200146 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSA256],
147 size: 4 + 32 + 4 + 32 + 4 + 72,
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300148 ..Default::default()
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200149 }
150 }
151
Fabio Utzig1e48b912018-09-18 09:04:18 -0300152 #[allow(dead_code)]
Fabio Utzig97710282019-05-24 17:44:49 -0300153 pub fn new_ed25519() -> TlvGen {
154 TlvGen {
Fabio Utzig97710282019-05-24 17:44:49 -0300155 kinds: vec![TlvKinds::SHA256, TlvKinds::ED25519],
156 size: 4 + 32 + 4 + 32 + 4 + 64,
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300157 ..Default::default()
Fabio Utzig97710282019-05-24 17:44:49 -0300158 }
159 }
160
161 #[allow(dead_code)]
Fabio Utzig1e48b912018-09-18 09:04:18 -0300162 pub fn new_enc_rsa() -> TlvGen {
163 TlvGen {
164 flags: TlvFlags::ENCRYPTED as u32,
165 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCRSA2048],
166 size: 4 + 32 + 4 + 256,
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300167 ..Default::default()
Fabio Utzig1e48b912018-09-18 09:04:18 -0300168 }
169 }
170
171 #[allow(dead_code)]
Fabio Utzig754438d2018-12-14 06:39:58 -0200172 pub fn new_sig_enc_rsa() -> TlvGen {
173 TlvGen {
174 flags: TlvFlags::ENCRYPTED as u32,
175 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048, TlvKinds::ENCRSA2048],
176 size: 4 + 32 + 4 + 32 + 4 + 256 + 4 + 256,
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300177 ..Default::default()
Fabio Utzig754438d2018-12-14 06:39:58 -0200178 }
179 }
180
181 #[allow(dead_code)]
Fabio Utzig1e48b912018-09-18 09:04:18 -0300182 pub fn new_enc_kw() -> TlvGen {
183 TlvGen {
184 flags: TlvFlags::ENCRYPTED as u32,
185 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCKW128],
186 size: 4 + 32 + 4 + 24,
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300187 ..Default::default()
Fabio Utzig1e48b912018-09-18 09:04:18 -0300188 }
189 }
190
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200191 #[allow(dead_code)]
192 pub fn new_rsa_kw() -> TlvGen {
193 TlvGen {
194 flags: TlvFlags::ENCRYPTED as u32,
195 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048, TlvKinds::ENCKW128],
196 size: 4 + 32 + 4 + 32 + 4 + 256 + 4 + 24,
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300197 ..Default::default()
Fabio Utzig251ef1d2018-12-18 17:20:19 -0200198 }
199 }
200
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200201 #[allow(dead_code)]
202 pub fn new_ecdsa_kw() -> TlvGen {
203 TlvGen {
204 flags: TlvFlags::ENCRYPTED as u32,
205 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSA256, TlvKinds::ENCKW128],
206 size: 4 + 32 + 4 + 32 + 4 + 72 + 4 + 24,
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300207 ..Default::default()
Fabio Utzig90f449e2019-10-24 07:43:53 -0300208 }
209 }
210
211 #[allow(dead_code)]
212 pub fn new_ecdsa_ecies_p256() -> TlvGen {
213 TlvGen {
214 flags: TlvFlags::ENCRYPTED as u32,
215 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSA256, TlvKinds::ENCEC256],
216 size: 4 + 32 + 4 + 32 + 4 + 72 + 4 + 113,
Fabio Utzig9a2b5de2019-11-22 12:50:02 -0300217 ..Default::default()
Fabio Utzigb4d20c82018-12-27 16:08:39 -0200218 }
219 }
220
David Brown187dd882017-07-11 11:15:23 -0600221 /// Retrieve the size that the TLV will occupy. This can be called at any time.
222 pub fn get_size(&self) -> u16 {
David Brownf5b33d82017-09-01 10:58:27 -0600223 4 + self.size
David Brown187dd882017-07-11 11:15:23 -0600224 }
David Brown43643dd2019-01-11 15:43:28 -0700225}
226
227impl ManifestGen for TlvGen {
David Brownac46e262019-01-11 15:46:18 -0700228 fn get_magic(&self) -> u32 {
229 0x96f3b83d
230 }
231
David Brown43643dd2019-01-11 15:43:28 -0700232 /// Retrieve the header flags for this configuration. This can be called at any time.
233 fn get_flags(&self) -> u32 {
234 self.flags
235 }
David Brown187dd882017-07-11 11:15:23 -0600236
237 /// Add bytes to the covered hash.
David Brown43643dd2019-01-11 15:43:28 -0700238 fn add_bytes(&mut self, bytes: &[u8]) {
David Brown4243ab02017-07-11 12:24:23 -0600239 self.payload.extend_from_slice(bytes);
David Brown187dd882017-07-11 11:15:23 -0600240 }
241
David Brown7a81c4b2019-07-29 15:20:21 -0600242 fn protect_size(&self) -> u16 {
243 if self.protect_size == 0 {
244 0
245 } else {
246 // Include the protected size, as well as the TLV header.
247 4 + self.protect_size
248 }
249 }
250
251 fn add_dependency(&mut self, id: u8, version: &ImageVersion) {
252 let my_size = 4 + 4 + 8;
253 self.protect_size += my_size;
254 self.size += my_size;
255 self.dependencies.push(Dependency {
256 id: id,
257 version: version.clone(),
258 });
259 }
260
David Brown187dd882017-07-11 11:15:23 -0600261 /// Compute the TLV given the specified block of data.
David Brown43643dd2019-01-11 15:43:28 -0700262 fn make_tlv(self: Box<Self>) -> Vec<u8> {
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300263 let mut protected_tlv: Vec<u8> = vec![];
David Brown187dd882017-07-11 11:15:23 -0600264
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300265 if self.protect_size > 0 {
266 protected_tlv.push(0x08);
267 protected_tlv.push(0x69);
268 protected_tlv.write_u16::<LittleEndian>(self.protect_size()).unwrap();
269 for dep in &self.dependencies {
270 protected_tlv.push(TlvKinds::DEPENDENCY as u8);
271 protected_tlv.push(0);
272 protected_tlv.push(12);
273 protected_tlv.push(0);
David Brownf5b33d82017-09-01 10:58:27 -0600274
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300275 // The dependency.
276 protected_tlv.push(dep.id);
277 for _ in 0 .. 3 {
278 protected_tlv.push(0);
279 }
280 protected_tlv.push(dep.version.major);
281 protected_tlv.push(dep.version.minor);
282 protected_tlv.write_u16::<LittleEndian>(dep.version.revision).unwrap();
283 protected_tlv.write_u32::<LittleEndian>(dep.version.build_num).unwrap();
David Brown7a81c4b2019-07-29 15:20:21 -0600284 }
David Brown7a81c4b2019-07-29 15:20:21 -0600285 }
286
287 // Ring does the signature itself, which means that it must be
288 // given a full, contiguous payload. Although this does help from
289 // a correct usage perspective, it is fairly stupid from an
290 // efficiency view. If this is shown to be a performance issue
291 // with the tests, the protected data could be appended to the
292 // payload, and then removed after the signature is done. For now,
293 // just make a signed payload.
294 let mut sig_payload = self.payload.clone();
Fabio Utzigea3d3ab2019-09-11 19:35:33 -0300295 sig_payload.extend_from_slice(&protected_tlv);
296
297 let mut result: Vec<u8> = vec![];
298
299 // add back signed payload
300 result.extend_from_slice(&protected_tlv);
301
302 // add non-protected payload
303 result.push(0x07);
304 result.push(0x69);
305 result.write_u16::<LittleEndian>(self.get_size()).unwrap();
David Brown7a81c4b2019-07-29 15:20:21 -0600306
David Brown187dd882017-07-11 11:15:23 -0600307 if self.kinds.contains(&TlvKinds::SHA256) {
David Brown7a81c4b2019-07-29 15:20:21 -0600308 let hash = digest::digest(&digest::SHA256, &sig_payload);
David Brown8054ce22017-07-11 12:12:09 -0600309 let hash = hash.as_ref();
David Brown187dd882017-07-11 11:15:23 -0600310
David Brown8054ce22017-07-11 12:12:09 -0600311 assert!(hash.len() == 32);
David Brown187dd882017-07-11 11:15:23 -0600312 result.push(TlvKinds::SHA256 as u8);
313 result.push(0);
314 result.push(32);
315 result.push(0);
David Brown8054ce22017-07-11 12:12:09 -0600316 result.extend_from_slice(hash);
David Brown187dd882017-07-11 11:15:23 -0600317 }
318
Fabio Utzig39297432019-05-08 18:51:10 -0300319 if self.kinds.contains(&TlvKinds::RSA2048) ||
320 self.kinds.contains(&TlvKinds::RSA3072) {
321
322 let is_rsa2048 = self.kinds.contains(&TlvKinds::RSA2048);
323
David Brown43cda332017-09-01 09:53:23 -0600324 // Output the hash of the public key.
Fabio Utzig39297432019-05-08 18:51:10 -0300325 let hash = if is_rsa2048 {
326 digest::digest(&digest::SHA256, RSA_PUB_KEY)
327 } else {
328 digest::digest(&digest::SHA256, RSA3072_PUB_KEY)
329 };
David Brown43cda332017-09-01 09:53:23 -0600330 let hash = hash.as_ref();
331
332 assert!(hash.len() == 32);
333 result.push(TlvKinds::KEYHASH as u8);
334 result.push(0);
335 result.push(32);
336 result.push(0);
337 result.extend_from_slice(hash);
338
David Brown7e701d82017-07-11 13:24:25 -0600339 // For now assume PSS.
Fabio Utzig39297432019-05-08 18:51:10 -0300340 let key_bytes = if is_rsa2048 {
341 pem::parse(include_bytes!("../../root-rsa-2048.pem").as_ref()).unwrap()
342 } else {
343 pem::parse(include_bytes!("../../root-rsa-3072.pem").as_ref()).unwrap()
344 };
David Brown7e701d82017-07-11 13:24:25 -0600345 assert_eq!(key_bytes.tag, "RSA PRIVATE KEY");
Fabio Utzig90f449e2019-10-24 07:43:53 -0300346 let key_pair = RsaKeyPair::from_der(&key_bytes.contents).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600347 let rng = rand::SystemRandom::new();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300348 let mut signature = vec![0; key_pair.public_modulus_len()];
Fabio Utzig39297432019-05-08 18:51:10 -0300349 if is_rsa2048 {
350 assert_eq!(signature.len(), 256);
351 } else {
352 assert_eq!(signature.len(), 384);
353 }
David Brown7a81c4b2019-07-29 15:20:21 -0600354 key_pair.sign(&RSA_PSS_SHA256, &rng, &sig_payload, &mut signature).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600355
Fabio Utzig39297432019-05-08 18:51:10 -0300356 if is_rsa2048 {
357 result.push(TlvKinds::RSA2048 as u8);
358 } else {
359 result.push(TlvKinds::RSA3072 as u8);
360 }
David Brown7e701d82017-07-11 13:24:25 -0600361 result.push(0);
David Brown91d68632019-07-29 14:32:13 -0600362 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
David Brown7e701d82017-07-11 13:24:25 -0600363 result.extend_from_slice(&signature);
364 }
365
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200366 if self.kinds.contains(&TlvKinds::ECDSA256) {
367 let keyhash = digest::digest(&digest::SHA256, ECDSA256_PUB_KEY);
368 let keyhash = keyhash.as_ref();
369
370 assert!(keyhash.len() == 32);
371 result.push(TlvKinds::KEYHASH as u8);
372 result.push(0);
373 result.push(32);
374 result.push(0);
375 result.extend_from_slice(keyhash);
376
Fabio Utzig05ab0142018-07-10 09:15:28 -0300377 let key_bytes = pem::parse(include_bytes!("../../root-ec-p256-pkcs8.pem").as_ref()).unwrap();
378 assert_eq!(key_bytes.tag, "PRIVATE KEY");
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200379
Fabio Utzig05ab0142018-07-10 09:15:28 -0300380 let key_pair = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING,
Fabio Utzig90f449e2019-10-24 07:43:53 -0300381 &key_bytes.contents).unwrap();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300382 let rng = rand::SystemRandom::new();
Fabio Utzig90f449e2019-10-24 07:43:53 -0300383 let signature = key_pair.sign(&rng, &sig_payload).unwrap();
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200384
385 result.push(TlvKinds::ECDSA256 as u8);
386 result.push(0);
Fabio Utzig05ab0142018-07-10 09:15:28 -0300387
388 // signature must be padded...
389 let mut signature = signature.as_ref().to_vec();
390 while signature.len() < 72 {
391 signature.push(0);
392 signature[1] += 1;
393 }
394
David Brown91d68632019-07-29 14:32:13 -0600395 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
Fabio Utzig05ab0142018-07-10 09:15:28 -0300396 result.extend_from_slice(signature.as_ref());
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200397 }
398
Fabio Utzig97710282019-05-24 17:44:49 -0300399 if self.kinds.contains(&TlvKinds::ED25519) {
400 let keyhash = digest::digest(&digest::SHA256, ED25519_PUB_KEY);
401 let keyhash = keyhash.as_ref();
402
403 assert!(keyhash.len() == 32);
404 result.push(TlvKinds::KEYHASH as u8);
405 result.push(0);
406 result.push(32);
407 result.push(0);
408 result.extend_from_slice(keyhash);
409
David Brown7a81c4b2019-07-29 15:20:21 -0600410 let hash = digest::digest(&digest::SHA256, &sig_payload);
Fabio Utzig97710282019-05-24 17:44:49 -0300411 let hash = hash.as_ref();
412 assert!(hash.len() == 32);
413
414 let key_bytes = pem::parse(include_bytes!("../../root-ed25519.pem").as_ref()).unwrap();
415 assert_eq!(key_bytes.tag, "PRIVATE KEY");
416
Fabio Utzig90f449e2019-10-24 07:43:53 -0300417 let key_pair = Ed25519KeyPair::from_seed_and_public_key(
418 &key_bytes.contents[16..48], &ED25519_PUB_KEY[12..44]).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300419 let signature = key_pair.sign(&hash);
420
421 result.push(TlvKinds::ED25519 as u8);
422 result.push(0);
423
424 let signature = signature.as_ref().to_vec();
David Brown91d68632019-07-29 14:32:13 -0600425 result.write_u16::<LittleEndian>(signature.len() as u16).unwrap();
Fabio Utzig97710282019-05-24 17:44:49 -0300426 result.extend_from_slice(signature.as_ref());
427 }
428
Fabio Utzig1e48b912018-09-18 09:04:18 -0300429 if self.kinds.contains(&TlvKinds::ENCRSA2048) {
430 let key_bytes = pem::parse(include_bytes!("../../enc-rsa2048-pub.pem")
431 .as_ref()).unwrap();
432 assert_eq!(key_bytes.tag, "PUBLIC KEY");
433
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300434 let cipherkey = self.get_enc_key();
435 let cipherkey = cipherkey.as_slice();
436 let encbuf = match c::rsa_oaep_encrypt(&key_bytes.contents, cipherkey) {
Fabio Utzig1e48b912018-09-18 09:04:18 -0300437 Ok(v) => v,
438 Err(_) => panic!("Failed to encrypt secret key"),
439 };
440
441 assert!(encbuf.len() == 256);
442 result.push(TlvKinds::ENCRSA2048 as u8);
443 result.push(0);
444 result.push(0);
445 result.push(1);
446 result.extend_from_slice(&encbuf);
447 }
448
449 if self.kinds.contains(&TlvKinds::ENCKW128) {
450 let key_bytes = base64::decode(
451 include_str!("../../enc-aes128kw.b64").trim()).unwrap();
452
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300453 let cipherkey = self.get_enc_key();
454 let cipherkey = cipherkey.as_slice();
455 let encbuf = match c::kw_encrypt(&key_bytes, cipherkey) {
Fabio Utzig1e48b912018-09-18 09:04:18 -0300456 Ok(v) => v,
457 Err(_) => panic!("Failed to encrypt secret key"),
458 };
459
460 assert!(encbuf.len() == 24);
461 result.push(TlvKinds::ENCKW128 as u8);
462 result.push(0);
463 result.push(24);
464 result.push(0);
465 result.extend_from_slice(&encbuf);
466 }
467
Fabio Utzig90f449e2019-10-24 07:43:53 -0300468 if self.kinds.contains(&TlvKinds::ENCEC256) {
469 let key_bytes = pem::parse(include_bytes!("../../enc-ec256-pub.pem").as_ref()).unwrap();
470 assert_eq!(key_bytes.tag, "PUBLIC KEY");
471
472 let rng = rand::SystemRandom::new();
473 let pk = match agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &rng) {
474 Ok(v) => v,
475 Err(_) => panic!("Failed to generate ephemeral keypair"),
476 };
477
478 let pubk = match pk.compute_public_key() {
479 Ok(pubk) => pubk,
480 Err(_) => panic!("Failed computing ephemeral public key"),
481 };
482
483 let peer_pubk = agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, &key_bytes.contents[26..]);
484
485 #[derive(Debug, PartialEq)]
486 struct OkmLen<T: core::fmt::Debug + PartialEq>(T);
487
488 impl hkdf::KeyType for OkmLen<usize> {
489 fn len(&self) -> usize {
490 self.0
491 }
492 }
493
494 let derived_key = match agreement::agree_ephemeral(
495 pk, &peer_pubk, ring::error::Unspecified, |shared| {
496 let salt = hkdf::Salt::new(hkdf::HKDF_SHA256, &[]);
497 let prk = salt.extract(&shared);
498 let okm = match prk.expand(&[b"MCUBoot_ECIES_v1"], OkmLen(48)) {
499 Ok(okm) => okm,
500 Err(_) => panic!("Failed building HKDF OKM"),
501 };
502 let mut buf = [0u8; 48];
503 match okm.fill(&mut buf) {
504 Ok(_) => Ok(buf),
505 Err(_) => panic!("Failed generating HKDF output"),
506 }
507 },
508 ) {
509 Ok(v) => v,
510 Err(_) => panic!("Failed building HKDF"),
511 };
512
513 let key = GenericArray::from_slice(&derived_key[..16]);
514 let nonce = GenericArray::from_slice(&[0; 16]);
515 let mut cipher = Aes128Ctr::new(&key, &nonce);
516 let mut cipherkey = self.get_enc_key();
517 cipher.apply_keystream(&mut cipherkey);
518
519 let key = hmac::Key::new(hmac::HMAC_SHA256, &derived_key[16..]);
520 let tag = hmac::sign(&key, &cipherkey);
521
522 let mut buf = vec![];
523 buf.append(&mut pubk.as_ref().to_vec());
524 buf.append(&mut tag.as_ref().to_vec());
525 buf.append(&mut cipherkey);
526
527 assert!(buf.len() == 113);
528 result.push(TlvKinds::ENCEC256 as u8);
529 result.push(0);
530 result.push(113);
531 result.push(0);
532 result.extend_from_slice(&buf);
533 }
534
David Brown187dd882017-07-11 11:15:23 -0600535 result
536 }
Fabio Utzig90f449e2019-10-24 07:43:53 -0300537
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300538 fn generate_enc_key(&mut self) {
539 let rng = rand::SystemRandom::new();
540 let mut buf = vec![0u8; AES_KEY_LEN];
541 match rng.fill(&mut buf) {
542 Err(_) => panic!("Error generating encrypted key"),
543 Ok(_) => (),
544 }
545 info!("New encryption key: {:02x?}", buf);
546 self.enc_key = buf;
Fabio Utzig90f449e2019-10-24 07:43:53 -0300547 }
548
549 fn get_enc_key(&self) -> Vec<u8> {
Fabio Utzige84f0ef2019-11-22 12:29:32 -0300550 if self.enc_key.len() != AES_KEY_LEN {
551 panic!("No random key was generated");
552 }
553 self.enc_key.clone()
Fabio Utzig90f449e2019-10-24 07:43:53 -0300554 }
David Brown187dd882017-07-11 11:15:23 -0600555}
David Brown43cda332017-09-01 09:53:23 -0600556
557include!("rsa_pub_key-rs.txt");
Fabio Utzig39297432019-05-08 18:51:10 -0300558include!("rsa3072_pub_key-rs.txt");
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200559include!("ecdsa_pub_key-rs.txt");
Fabio Utzig97710282019-05-24 17:44:49 -0300560include!("ed25519_pub_key-rs.txt");