blob: 6931d0bc9dcb81cd97fe7ecb018427743dee41d2 [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 Brown7e701d82017-07-11 13:24:25 -060011use std::sync::Arc;
12use pem;
Fabio Utzig1e48b912018-09-18 09:04:18 -030013use base64;
David Brown7e701d82017-07-11 13:24:25 -060014use ring::{digest, rand, signature};
15use untrusted;
Fabio Utzig80fde2f2017-12-05 09:25:31 -020016use mcuboot_sys::c;
David Brown187dd882017-07-11 11:15:23 -060017
David Brown187dd882017-07-11 11:15:23 -060018#[repr(u8)]
19#[derive(Copy, Clone, PartialEq, Eq)]
20#[allow(dead_code)] // TODO: For now
21pub enum TlvKinds {
David Brown43cda332017-09-01 09:53:23 -060022 KEYHASH = 0x01,
David Brown27648b82017-08-31 10:40:29 -060023 SHA256 = 0x10,
24 RSA2048 = 0x20,
25 ECDSA224 = 0x21,
26 ECDSA256 = 0x22,
Fabio Utzig1e48b912018-09-18 09:04:18 -030027 ENCRSA2048 = 0x30,
28 ENCKW128 = 0x31,
29}
30
31#[allow(dead_code, non_camel_case_types)]
32pub enum TlvFlags {
33 PIC = 0x01,
34 NON_BOOTABLE = 0x02,
35 ENCRYPTED = 0x04,
36 RAM_LOAD = 0x20,
David Brown187dd882017-07-11 11:15:23 -060037}
38
39pub struct TlvGen {
David Brown43cda332017-09-01 09:53:23 -060040 flags: u32,
David Brown187dd882017-07-11 11:15:23 -060041 kinds: Vec<TlvKinds>,
42 size: u16,
David Brown4243ab02017-07-11 12:24:23 -060043 payload: Vec<u8>,
David Brown187dd882017-07-11 11:15:23 -060044}
45
Fabio Utzig1e48b912018-09-18 09:04:18 -030046pub const AES_SEC_KEY: &[u8; 16] = b"0123456789ABCDEF";
47
David Brown187dd882017-07-11 11:15:23 -060048impl TlvGen {
49 /// Construct a new tlv generator that will only contain a hash of the data.
David Brown7e701d82017-07-11 13:24:25 -060050 #[allow(dead_code)]
David Brown187dd882017-07-11 11:15:23 -060051 pub fn new_hash_only() -> TlvGen {
52 TlvGen {
David Brown43cda332017-09-01 09:53:23 -060053 flags: 0,
David Brown187dd882017-07-11 11:15:23 -060054 kinds: vec![TlvKinds::SHA256],
55 size: 4 + 32,
David Brown4243ab02017-07-11 12:24:23 -060056 payload: vec![],
David Brown187dd882017-07-11 11:15:23 -060057 }
58 }
59
David Brown7e701d82017-07-11 13:24:25 -060060 #[allow(dead_code)]
61 pub fn new_rsa_pss() -> TlvGen {
62 TlvGen {
David Brown43cda332017-09-01 09:53:23 -060063 flags: 0,
Fabio Utzig754438d2018-12-14 06:39:58 -020064 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048],
65 size: 4 + 32 + 4 + 32 + 4 + 256,
David Brown7e701d82017-07-11 13:24:25 -060066 payload: vec![],
67 }
68 }
69
Fabio Utzig80fde2f2017-12-05 09:25:31 -020070 #[allow(dead_code)]
71 pub fn new_ecdsa() -> TlvGen {
72 TlvGen {
73 flags: 0,
Fabio Utzig754438d2018-12-14 06:39:58 -020074 kinds: vec![TlvKinds::SHA256, TlvKinds::ECDSA256],
75 size: 4 + 32 + 4 + 32 + 4 + 72,
Fabio Utzig80fde2f2017-12-05 09:25:31 -020076 payload: vec![],
77 }
78 }
79
Fabio Utzig1e48b912018-09-18 09:04:18 -030080 #[allow(dead_code)]
81 pub fn new_enc_rsa() -> TlvGen {
82 TlvGen {
83 flags: TlvFlags::ENCRYPTED as u32,
84 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCRSA2048],
85 size: 4 + 32 + 4 + 256,
86 payload: vec![],
87 }
88 }
89
90 #[allow(dead_code)]
Fabio Utzig754438d2018-12-14 06:39:58 -020091 pub fn new_sig_enc_rsa() -> TlvGen {
92 TlvGen {
93 flags: TlvFlags::ENCRYPTED as u32,
94 kinds: vec![TlvKinds::SHA256, TlvKinds::RSA2048, TlvKinds::ENCRSA2048],
95 size: 4 + 32 + 4 + 32 + 4 + 256 + 4 + 256,
96 payload: vec![],
97 }
98 }
99
100 #[allow(dead_code)]
Fabio Utzig1e48b912018-09-18 09:04:18 -0300101 pub fn new_enc_kw() -> TlvGen {
102 TlvGen {
103 flags: TlvFlags::ENCRYPTED as u32,
104 kinds: vec![TlvKinds::SHA256, TlvKinds::ENCKW128],
105 size: 4 + 32 + 4 + 24,
106 payload: vec![],
107 }
108 }
109
David Brown187dd882017-07-11 11:15:23 -0600110 /// Retrieve the header flags for this configuration. This can be called at any time.
111 pub fn get_flags(&self) -> u32 {
David Brown43cda332017-09-01 09:53:23 -0600112 self.flags
David Brown187dd882017-07-11 11:15:23 -0600113 }
114
115 /// Retrieve the size that the TLV will occupy. This can be called at any time.
116 pub fn get_size(&self) -> u16 {
David Brownf5b33d82017-09-01 10:58:27 -0600117 4 + self.size
David Brown187dd882017-07-11 11:15:23 -0600118 }
119
120 /// Add bytes to the covered hash.
121 pub fn add_bytes(&mut self, bytes: &[u8]) {
David Brown4243ab02017-07-11 12:24:23 -0600122 self.payload.extend_from_slice(bytes);
David Brown187dd882017-07-11 11:15:23 -0600123 }
124
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200125 /// Create a DER representation of one ec curve point
126 fn _make_der_int(&self, x: &[u8]) -> Vec<u8> {
127 assert!(x.len() == 32);
128
129 let mut i: Vec<u8> = vec![0x02];
130 if x[0] >= 0x7f {
131 i.push(33);
132 i.push(0);
133 } else {
134 i.push(32);
135 }
136 i.extend(x);
137 i
138 }
139
140 /// Create an ecdsa256 TLV
141 fn _make_der_sequence(&self, r: Vec<u8>, s: Vec<u8>) -> Vec<u8> {
142 let mut der: Vec<u8> = vec![0x30];
143 der.push(r.len() as u8 + s.len() as u8);
144 der.extend(r);
145 der.extend(s);
146 let mut size = der.len();
147 // must pad up to 72 bytes...
148 while size <= 72 {
149 der.push(0);
150 der[1] += 1;
151 size += 1;
152 }
153 der
154 }
155
David Brown187dd882017-07-11 11:15:23 -0600156 /// Compute the TLV given the specified block of data.
David Brown8054ce22017-07-11 12:12:09 -0600157 pub fn make_tlv(self) -> Vec<u8> {
David Brown187dd882017-07-11 11:15:23 -0600158 let mut result: Vec<u8> = vec![];
159
David Brownf5b33d82017-09-01 10:58:27 -0600160 let size = self.get_size();
161 result.push(0x07);
162 result.push(0x69);
163 result.push((size & 0xFF) as u8);
164 result.push(((size >> 8) & 0xFF) as u8);
165
David Brown187dd882017-07-11 11:15:23 -0600166 if self.kinds.contains(&TlvKinds::SHA256) {
David Brown4243ab02017-07-11 12:24:23 -0600167 let hash = digest::digest(&digest::SHA256, &self.payload);
David Brown8054ce22017-07-11 12:12:09 -0600168 let hash = hash.as_ref();
David Brown187dd882017-07-11 11:15:23 -0600169
David Brown8054ce22017-07-11 12:12:09 -0600170 assert!(hash.len() == 32);
David Brown187dd882017-07-11 11:15:23 -0600171 result.push(TlvKinds::SHA256 as u8);
172 result.push(0);
173 result.push(32);
174 result.push(0);
David Brown8054ce22017-07-11 12:12:09 -0600175 result.extend_from_slice(hash);
David Brown187dd882017-07-11 11:15:23 -0600176 }
177
David Brown7e701d82017-07-11 13:24:25 -0600178 if self.kinds.contains(&TlvKinds::RSA2048) {
David Brown43cda332017-09-01 09:53:23 -0600179 // Output the hash of the public key.
180 let hash = digest::digest(&digest::SHA256, RSA_PUB_KEY);
181 let hash = hash.as_ref();
182
183 assert!(hash.len() == 32);
184 result.push(TlvKinds::KEYHASH as u8);
185 result.push(0);
186 result.push(32);
187 result.push(0);
188 result.extend_from_slice(hash);
189
David Brown7e701d82017-07-11 13:24:25 -0600190 // For now assume PSS.
191 let key_bytes = pem::parse(include_bytes!("../../root-rsa-2048.pem").as_ref()).unwrap();
192 assert_eq!(key_bytes.tag, "RSA PRIVATE KEY");
193 let key_bytes = untrusted::Input::from(&key_bytes.contents);
194 let key = signature::RSAKeyPair::from_der(key_bytes).unwrap();
195 let mut signer = signature::RSASigningState::new(Arc::new(key)).unwrap();
196 let rng = rand::SystemRandom::new();
197 let mut signature = vec![0; signer.key_pair().public_modulus_len()];
198 assert_eq!(signature.len(), 256);
199 signer.sign(&signature::RSA_PSS_SHA256, &rng, &self.payload, &mut signature).unwrap();
200
201 result.push(TlvKinds::RSA2048 as u8);
202 result.push(0);
203 result.push((signature.len() & 0xFF) as u8);
204 result.push(((signature.len() >> 8) & 0xFF) as u8);
205 result.extend_from_slice(&signature);
206 }
207
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200208 if self.kinds.contains(&TlvKinds::ECDSA256) {
209 let keyhash = digest::digest(&digest::SHA256, ECDSA256_PUB_KEY);
210 let keyhash = keyhash.as_ref();
211
212 assert!(keyhash.len() == 32);
213 result.push(TlvKinds::KEYHASH as u8);
214 result.push(0);
215 result.push(32);
216 result.push(0);
217 result.extend_from_slice(keyhash);
218
219 let key_bytes = pem::parse(include_bytes!("../../root-ec-p256.pem").as_ref()).unwrap();
220 assert_eq!(key_bytes.tag, "EC PRIVATE KEY");
221
222 let hash = digest::digest(&digest::SHA256, &self.payload);
223 let hash = hash.as_ref();
224 assert!(hash.len() == 32);
225
226 /* FIXME
227 *
228 * Although `ring` has an ASN1 parser, it hides access
229 * to its low-level data, which was designed to be used
230 * by its internal signing/verifying functions. Since it does
231 * not yet support ecdsa signing, for the time being I am
232 * manually loading the key from its index in the PEM and
233 * building the TLV DER manually.
234 *
235 * Once ring gets ecdsa signing (hopefully soon!) this code
236 * should be updated to leverage its functionality...
237 */
238
239 /* Load key directly from PEM */
240 let key = &key_bytes.contents[7..39];
241
242 let signature = match c::ecdsa256_sign(&key, &hash) {
243 Ok(sign) => sign,
244 Err(_) => panic!("Failed signature generation"),
245 };
246
247 let r = self._make_der_int(&signature.to_vec()[..32]);
248 let s = self._make_der_int(&signature.to_vec()[32..64]);
249 let der = self._make_der_sequence(r, s);
250
251 result.push(TlvKinds::ECDSA256 as u8);
252 result.push(0);
253 result.push(der.len() as u8);
254 result.push(0);
255 result.extend(der);
256 }
257
Fabio Utzig1e48b912018-09-18 09:04:18 -0300258 if self.kinds.contains(&TlvKinds::ENCRSA2048) {
259 let key_bytes = pem::parse(include_bytes!("../../enc-rsa2048-pub.pem")
260 .as_ref()).unwrap();
261 assert_eq!(key_bytes.tag, "PUBLIC KEY");
262
263 let encbuf = match c::rsa_oaep_encrypt(&key_bytes.contents, AES_SEC_KEY) {
264 Ok(v) => v,
265 Err(_) => panic!("Failed to encrypt secret key"),
266 };
267
268 assert!(encbuf.len() == 256);
269 result.push(TlvKinds::ENCRSA2048 as u8);
270 result.push(0);
271 result.push(0);
272 result.push(1);
273 result.extend_from_slice(&encbuf);
274 }
275
276 if self.kinds.contains(&TlvKinds::ENCKW128) {
277 let key_bytes = base64::decode(
278 include_str!("../../enc-aes128kw.b64").trim()).unwrap();
279
280 let encbuf = match c::kw_encrypt(&key_bytes, AES_SEC_KEY) {
281 Ok(v) => v,
282 Err(_) => panic!("Failed to encrypt secret key"),
283 };
284
285 assert!(encbuf.len() == 24);
286 result.push(TlvKinds::ENCKW128 as u8);
287 result.push(0);
288 result.push(24);
289 result.push(0);
290 result.extend_from_slice(&encbuf);
291 }
292
David Brown187dd882017-07-11 11:15:23 -0600293 result
294 }
295}
David Brown43cda332017-09-01 09:53:23 -0600296
297include!("rsa_pub_key-rs.txt");
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200298include!("ecdsa_pub_key-rs.txt");