blob: bd5906cf6e16e5508d6b5740c7d95a1db1eb0277 [file] [log] [blame]
Joel Galensonca0efb12020-10-01 14:32:30 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis9d90b812020-11-25 21:02:11 -080015//! This module implements safe wrappers for some crypto operations required by
16//! Keystore 2.0.
17
18mod error;
19mod zvec;
20pub use error::Error;
21use keystore2_crypto_bindgen::{
Shawn Willden8fde4c22021-02-14 13:58:22 -070022 extractSubjectFromCertificate, generateKeyFromPassword, randomBytes, AES_gcm_decrypt,
23 AES_gcm_encrypt, ECDHComputeKey, ECKEYDeriveFromSecret, ECKEYGenerateKey, ECPOINTOct2Point,
24 ECPOINTPoint2Oct, EC_KEY_free, EC_KEY_get0_public_key, EC_POINT_free, HKDFExpand, HKDFExtract,
25 EC_KEY, EC_MAX_BYTES, EC_POINT, EVP_MAX_MD_SIZE,
Janis Danisevskis9d90b812020-11-25 21:02:11 -080026};
Shawn Willden8fde4c22021-02-14 13:58:22 -070027use std::convert::TryFrom;
Joel Galenson05914582021-01-08 09:30:41 -080028use std::convert::TryInto;
29use std::marker::PhantomData;
Janis Danisevskis9d90b812020-11-25 21:02:11 -080030pub use zvec::ZVec;
31
32/// Length of the expected initialization vector.
33pub const IV_LENGTH: usize = 16;
34/// Length of the expected AEAD TAG.
35pub const TAG_LENGTH: usize = 16;
36/// Length of an AES 256 key in bytes.
37pub const AES_256_KEY_LENGTH: usize = 32;
38/// Length of an AES 128 key in bytes.
39pub const AES_128_KEY_LENGTH: usize = 16;
40/// Length of the expected salt for key from password generation.
41pub const SALT_LENGTH: usize = 16;
42
43// This is the number of bytes of the GCM IV that is expected to be initialized
44// with random bytes.
45const GCM_IV_LENGTH: usize = 12;
46
47/// Generate an AES256 key, essentially 32 random bytes from the underlying
48/// boringssl library discretely stuffed into a ZVec.
49pub fn generate_aes256_key() -> Result<ZVec, Error> {
50 // Safety: key has the same length as the requested number of random bytes.
51 let mut key = ZVec::new(AES_256_KEY_LENGTH)?;
Joel Galenson05914582021-01-08 09:30:41 -080052 if unsafe { randomBytes(key.as_mut_ptr(), AES_256_KEY_LENGTH) } {
Janis Danisevskis9d90b812020-11-25 21:02:11 -080053 Ok(key)
54 } else {
55 Err(Error::RandomNumberGenerationFailed)
56 }
57}
58
59/// Generate a salt.
60pub fn generate_salt() -> Result<Vec<u8>, Error> {
David Drysdale0e45a612021-02-25 17:24:36 +000061 generate_random_data(SALT_LENGTH)
62}
63
64/// Generate random data of the given size.
65pub fn generate_random_data(size: usize) -> Result<Vec<u8>, Error> {
66 // Safety: data has the same length as the requested number of random bytes.
67 let mut data = vec![0; size];
68 if unsafe { randomBytes(data.as_mut_ptr(), size) } {
69 Ok(data)
Janis Danisevskis9d90b812020-11-25 21:02:11 -080070 } else {
71 Err(Error::RandomNumberGenerationFailed)
72 }
73}
74
75/// Uses AES GCM to decipher a message given an initialization vector, aead tag, and key.
76/// This function accepts 128 and 256-bit keys and uses AES128 and AES256 respectively based
77/// on the key length.
78/// This function returns the plaintext message in a ZVec because it is assumed that
79/// it contains sensitive information that should be zeroed from memory before its buffer is
80/// freed. Input key is taken as a slice for flexibility, but it is recommended that it is held
81/// in a ZVec as well.
82pub fn aes_gcm_decrypt(data: &[u8], iv: &[u8], tag: &[u8], key: &[u8]) -> Result<ZVec, Error> {
83 if iv.len() != IV_LENGTH {
84 return Err(Error::InvalidIvLength);
85 }
86
87 if tag.len() != TAG_LENGTH {
88 return Err(Error::InvalidAeadTagLength);
89 }
90
91 match key.len() {
92 AES_128_KEY_LENGTH | AES_256_KEY_LENGTH => {}
93 _ => return Err(Error::InvalidKeyLength),
94 }
95
96 let mut result = ZVec::new(data.len())?;
97
98 // Safety: The first two arguments must point to buffers with a size given by the third
99 // argument. The key must have a size of 16 or 32 bytes which we check above.
100 // The iv and tag arguments must be 16 bytes, which we also check above.
101 match unsafe {
102 AES_gcm_decrypt(
103 data.as_ptr(),
104 result.as_mut_ptr(),
Joel Galenson05914582021-01-08 09:30:41 -0800105 data.len(),
Janis Danisevskis9d90b812020-11-25 21:02:11 -0800106 key.as_ptr(),
Joel Galenson05914582021-01-08 09:30:41 -0800107 key.len(),
Janis Danisevskis9d90b812020-11-25 21:02:11 -0800108 iv.as_ptr(),
109 tag.as_ptr(),
110 )
111 } {
112 true => Ok(result),
113 false => Err(Error::DecryptionFailed),
114 }
115}
116
117/// Uses AES GCM to encrypt a message given a key.
118/// This function accepts 128 and 256-bit keys and uses AES128 and AES256 respectively based on
119/// the key length. The function generates an initialization vector. The return value is a tuple
120/// of `(ciphertext, iv, tag)`.
121pub fn aes_gcm_encrypt(data: &[u8], key: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>), Error> {
122 let mut iv = vec![0; IV_LENGTH];
123 // Safety: iv is longer than GCM_IV_LENGTH, which is 12 while IV_LENGTH is 16.
124 // The iv needs to be 16 bytes long, but the last 4 bytes remain zeroed.
Joel Galenson05914582021-01-08 09:30:41 -0800125 if !unsafe { randomBytes(iv.as_mut_ptr(), GCM_IV_LENGTH) } {
Janis Danisevskis9d90b812020-11-25 21:02:11 -0800126 return Err(Error::RandomNumberGenerationFailed);
127 }
128
129 match key.len() {
130 AES_128_KEY_LENGTH | AES_256_KEY_LENGTH => {}
131 _ => return Err(Error::InvalidKeyLength),
132 }
133
134 let mut result: Vec<u8> = vec![0; data.len()];
135 let mut tag: Vec<u8> = vec![0; TAG_LENGTH];
136 match unsafe {
137 AES_gcm_encrypt(
138 data.as_ptr(),
139 result.as_mut_ptr(),
Joel Galenson05914582021-01-08 09:30:41 -0800140 data.len(),
Janis Danisevskis9d90b812020-11-25 21:02:11 -0800141 key.as_ptr(),
Joel Galenson05914582021-01-08 09:30:41 -0800142 key.len(),
Janis Danisevskis9d90b812020-11-25 21:02:11 -0800143 iv.as_ptr(),
144 tag.as_mut_ptr(),
145 )
146 } {
147 true => Ok((result, iv, tag)),
148 false => Err(Error::EncryptionFailed),
149 }
150}
151
152/// Generates a key from the given password and salt.
153/// The salt must be exactly 16 bytes long.
154/// Two key sizes are accepted: 16 and 32 bytes.
155pub fn derive_key_from_password(
156 pw: &[u8],
157 salt: Option<&[u8]>,
158 key_length: usize,
159) -> Result<ZVec, Error> {
160 let salt: *const u8 = match salt {
161 Some(s) => {
162 if s.len() != SALT_LENGTH {
163 return Err(Error::InvalidSaltLength);
164 }
165 s.as_ptr()
166 }
167 None => std::ptr::null(),
168 };
169
170 match key_length {
171 AES_128_KEY_LENGTH | AES_256_KEY_LENGTH => {}
172 _ => return Err(Error::InvalidKeyLength),
173 }
174
175 let mut result = ZVec::new(key_length)?;
176
177 unsafe {
178 generateKeyFromPassword(
179 result.as_mut_ptr(),
Joel Galenson05914582021-01-08 09:30:41 -0800180 result.len(),
Janis Danisevskis9d90b812020-11-25 21:02:11 -0800181 pw.as_ptr() as *const std::os::raw::c_char,
Joel Galenson05914582021-01-08 09:30:41 -0800182 pw.len(),
Janis Danisevskis9d90b812020-11-25 21:02:11 -0800183 salt,
184 )
185 };
186
187 Ok(result)
188}
Joel Galenson46d6fd02020-11-19 17:58:33 -0800189
Joel Galenson05914582021-01-08 09:30:41 -0800190/// Calls the boringssl HKDF_extract function.
191pub fn hkdf_extract(secret: &[u8], salt: &[u8]) -> Result<ZVec, Error> {
192 let max_size: usize = EVP_MAX_MD_SIZE.try_into().unwrap();
193 let mut buf = ZVec::new(max_size)?;
194 let mut out_len = 0;
195 // Safety: HKDF_extract writes at most EVP_MAX_MD_SIZE bytes.
196 // Secret and salt point to valid buffers.
197 let result = unsafe {
198 HKDFExtract(
199 buf.as_mut_ptr(),
200 &mut out_len,
201 secret.as_ptr(),
202 secret.len(),
203 salt.as_ptr(),
204 salt.len(),
205 )
206 };
207 if !result {
208 return Err(Error::HKDFExtractFailed);
209 }
210 // According to the boringssl API, this should never happen.
211 if out_len > max_size {
212 return Err(Error::HKDFExtractFailed);
213 }
214 // HKDF_extract may write fewer than the maximum number of bytes, so we
215 // truncate the buffer.
216 buf.reduce_len(out_len);
217 Ok(buf)
218}
219
220/// Calls the boringssl HKDF_expand function.
221pub fn hkdf_expand(out_len: usize, prk: &[u8], info: &[u8]) -> Result<ZVec, Error> {
222 let mut buf = ZVec::new(out_len)?;
223 // Safety: HKDF_expand writes out_len bytes to the buffer.
224 // prk and info are valid buffers.
225 let result = unsafe {
226 HKDFExpand(buf.as_mut_ptr(), out_len, prk.as_ptr(), prk.len(), info.as_ptr(), info.len())
227 };
228 if !result {
229 return Err(Error::HKDFExpandFailed);
230 }
231 Ok(buf)
232}
233
234/// A wrapper around the boringssl EC_KEY type that frees it on drop.
235pub struct ECKey(*mut EC_KEY);
236
237impl Drop for ECKey {
238 fn drop(&mut self) {
239 // Safety: We only create ECKey objects for valid EC_KEYs
240 // and they are the sole owners of those keys.
241 unsafe { EC_KEY_free(self.0) };
242 }
243}
244
245// Wrappers around the boringssl EC_POINT type.
246// The EC_POINT can either be owned (and therefore mutable) or a pointer to an
247// EC_POINT owned by someone else (and thus immutable). The former are freed
248// on drop.
249
250/// An owned EC_POINT object.
251pub struct OwnedECPoint(*mut EC_POINT);
252
253/// A pointer to an EC_POINT object.
254pub struct BorrowedECPoint<'a> {
255 data: *const EC_POINT,
256 phantom: PhantomData<&'a EC_POINT>,
257}
258
259impl OwnedECPoint {
260 /// Get the wrapped EC_POINT object.
261 pub fn get_point(&self) -> &EC_POINT {
262 // Safety: We only create OwnedECPoint objects for valid EC_POINTs.
263 unsafe { self.0.as_ref().unwrap() }
264 }
265}
266
267impl<'a> BorrowedECPoint<'a> {
268 /// Get the wrapped EC_POINT object.
269 pub fn get_point(&self) -> &EC_POINT {
270 // Safety: We only create BorrowedECPoint objects for valid EC_POINTs.
271 unsafe { self.data.as_ref().unwrap() }
272 }
273}
274
275impl Drop for OwnedECPoint {
276 fn drop(&mut self) {
277 // Safety: We only create OwnedECPoint objects for valid
278 // EC_POINTs and they are the sole owners of those points.
279 unsafe { EC_POINT_free(self.0) };
280 }
281}
282
283/// Calls the boringssl ECDH_compute_key function.
284pub fn ecdh_compute_key(pub_key: &EC_POINT, priv_key: &ECKey) -> Result<ZVec, Error> {
285 let mut buf = ZVec::new(EC_MAX_BYTES)?;
286 // Safety: Our ECDHComputeKey wrapper passes EC_MAX_BYES to ECDH_compute_key, which
287 // writes at most that many bytes to the output.
288 // The two keys are valid objects.
289 let result =
290 unsafe { ECDHComputeKey(buf.as_mut_ptr() as *mut std::ffi::c_void, pub_key, priv_key.0) };
291 if result == -1 {
292 return Err(Error::ECDHComputeKeyFailed);
293 }
294 let out_len = result.try_into().unwrap();
295 // According to the boringssl API, this should never happen.
296 if out_len > buf.len() {
297 return Err(Error::ECDHComputeKeyFailed);
298 }
299 // ECDH_compute_key may write fewer than the maximum number of bytes, so we
300 // truncate the buffer.
301 buf.reduce_len(out_len);
302 Ok(buf)
303}
304
305/// Calls the boringssl EC_KEY_generate_key function.
306pub fn ec_key_generate_key() -> Result<ECKey, Error> {
307 // Safety: Creates a new key on its own.
308 let key = unsafe { ECKEYGenerateKey() };
309 if key.is_null() {
310 return Err(Error::ECKEYGenerateKeyFailed);
311 }
312 Ok(ECKey(key))
313}
314
315/// Calls the boringssl EC_KEY_derive_from_secret function.
316pub fn ec_key_derive_from_secret(secret: &[u8]) -> Result<ECKey, Error> {
317 // Safety: secret is a valid buffer.
318 let result = unsafe { ECKEYDeriveFromSecret(secret.as_ptr(), secret.len()) };
319 if result.is_null() {
320 return Err(Error::ECKEYDeriveFailed);
321 }
322 Ok(ECKey(result))
323}
324
325/// Calls the boringssl EC_KEY_get0_public_key function.
326pub fn ec_key_get0_public_key(key: &ECKey) -> BorrowedECPoint {
327 // Safety: The key is valid.
328 // This returns a pointer to a key, so we create an immutable variant.
329 BorrowedECPoint { data: unsafe { EC_KEY_get0_public_key(key.0) }, phantom: PhantomData }
330}
331
332/// Calls the boringssl EC_POINT_point2oct.
333pub fn ec_point_point_to_oct(point: &EC_POINT) -> Result<Vec<u8>, Error> {
334 // We fix the length to 65 (1 + 2 * field_elem_size), as we get an error if it's too small.
335 let len = 65;
336 let mut buf = vec![0; len];
337 // Safety: EC_POINT_point2oct writes at most len bytes. The point is valid.
338 let result = unsafe { ECPOINTPoint2Oct(point, buf.as_mut_ptr(), len) };
339 if result == 0 {
340 return Err(Error::ECPoint2OctFailed);
341 }
342 // According to the boringssl API, this should never happen.
343 if result > len {
344 return Err(Error::ECPoint2OctFailed);
345 }
346 buf.resize(result, 0);
347 Ok(buf)
348}
349
350/// Calls the boringssl EC_POINT_oct2point function.
351pub fn ec_point_oct_to_point(buf: &[u8]) -> Result<OwnedECPoint, Error> {
352 // Safety: The buffer is valid.
353 let result = unsafe { ECPOINTOct2Point(buf.as_ptr(), buf.len()) };
354 if result.is_null() {
355 return Err(Error::ECPoint2OctFailed);
356 }
357 // Our C wrapper creates a new EC_POINT, so we mark this mutable and free
358 // it on drop.
359 Ok(OwnedECPoint(result))
360}
361
Shawn Willden34120872021-02-24 21:56:30 -0700362/// Uses BoringSSL to extract the DER-encoded subject from a DER-encoded X.509 certificate.
363pub fn parse_subject_from_certificate(cert_buf: &[u8]) -> Result<Vec<u8>, Error> {
Shawn Willden8fde4c22021-02-14 13:58:22 -0700364 // Try with a 200-byte output buffer, should be enough in all but bizarre cases.
365 let mut retval = vec![0; 200];
Shawn Willden34120872021-02-24 21:56:30 -0700366
367 // Safety: extractSubjectFromCertificate reads at most cert_buf.len() bytes from cert_buf and
368 // writes at most retval.len() bytes to retval.
Shawn Willden8fde4c22021-02-14 13:58:22 -0700369 let mut size = unsafe {
370 extractSubjectFromCertificate(
371 cert_buf.as_ptr(),
372 cert_buf.len(),
373 retval.as_mut_ptr(),
374 retval.len(),
375 )
376 };
377
378 if size == 0 {
379 return Err(Error::ExtractSubjectFailed);
380 }
381
382 if size < 0 {
383 // Our buffer wasn't big enough. Make one that is just the right size and try again.
Shawn Willden34120872021-02-24 21:56:30 -0700384 let negated_size = usize::try_from(-size).map_err(|_e| Error::ExtractSubjectFailed)?;
385 retval = vec![0; negated_size];
Shawn Willden8fde4c22021-02-14 13:58:22 -0700386
Shawn Willden34120872021-02-24 21:56:30 -0700387 // Safety: extractSubjectFromCertificate reads at most cert_buf.len() bytes from cert_buf
388 // and writes at most retval.len() bytes to retval.
Shawn Willden8fde4c22021-02-14 13:58:22 -0700389 size = unsafe {
390 extractSubjectFromCertificate(
391 cert_buf.as_ptr(),
392 cert_buf.len(),
393 retval.as_mut_ptr(),
394 retval.len(),
395 )
396 };
397
398 if size <= 0 {
399 return Err(Error::ExtractSubjectFailed);
400 }
401 }
402
403 // Reduce buffer size to the amount written.
Shawn Willden34120872021-02-24 21:56:30 -0700404 let safe_size = usize::try_from(size).map_err(|_e| Error::ExtractSubjectFailed)?;
405 retval.truncate(safe_size);
Shawn Willden8fde4c22021-02-14 13:58:22 -0700406
407 Ok(retval)
408}
409
Joel Galensonca0efb12020-10-01 14:32:30 -0700410#[cfg(test)]
411mod tests {
412
Janis Danisevskis9d90b812020-11-25 21:02:11 -0800413 use super::*;
Joel Galensonca0efb12020-10-01 14:32:30 -0700414 use keystore2_crypto_bindgen::{
415 generateKeyFromPassword, AES_gcm_decrypt, AES_gcm_encrypt, CreateKeyId,
416 };
417
418 #[test]
Janis Danisevskis9d90b812020-11-25 21:02:11 -0800419 fn test_wrapper_roundtrip() {
420 let key = generate_aes256_key().unwrap();
421 let message = b"totally awesome message";
422 let (cipher_text, iv, tag) = aes_gcm_encrypt(message, &key).unwrap();
423 let message2 = aes_gcm_decrypt(&cipher_text, &iv, &tag, &key).unwrap();
424 assert_eq!(message[..], message2[..])
425 }
426
427 #[test]
Joel Galensonca0efb12020-10-01 14:32:30 -0700428 fn test_encrypt_decrypt() {
429 let input = vec![0; 16];
430 let mut out = vec![0; 16];
431 let mut out2 = vec![0; 16];
432 let key = vec![0; 16];
433 let iv = vec![0; 12];
434 let mut tag = vec![0; 16];
435 unsafe {
436 let res = AES_gcm_encrypt(
437 input.as_ptr(),
438 out.as_mut_ptr(),
439 16,
440 key.as_ptr(),
441 16,
442 iv.as_ptr(),
443 tag.as_mut_ptr(),
444 );
445 assert!(res);
446 assert_ne!(out, input);
447 assert_ne!(tag, input);
448 let res = AES_gcm_decrypt(
449 out.as_ptr(),
450 out2.as_mut_ptr(),
451 16,
452 key.as_ptr(),
453 16,
454 iv.as_ptr(),
455 tag.as_ptr(),
456 );
457 assert!(res);
458 assert_eq!(out2, input);
459 }
460 }
461
462 #[test]
463 fn test_create_key_id() {
464 let blob = vec![0; 16];
465 let mut out: u64 = 0;
466 unsafe {
467 let res = CreateKeyId(blob.as_ptr(), 16, &mut out);
468 assert!(res);
469 assert_ne!(out, 0);
470 }
471 }
472
473 #[test]
474 fn test_generate_key_from_password() {
475 let mut key = vec![0; 16];
476 let pw = vec![0; 16];
477 let mut salt = vec![0; 16];
478 unsafe {
479 generateKeyFromPassword(key.as_mut_ptr(), 16, pw.as_ptr(), 16, salt.as_mut_ptr());
480 }
481 assert_ne!(key, vec![0; 16]);
482 }
Joel Galenson05914582021-01-08 09:30:41 -0800483
484 #[test]
485 fn test_hkdf() {
486 let result = hkdf_extract(&[0; 16], &[0; 16]);
487 assert!(result.is_ok());
488 for out_len in 4..=8 {
489 let result = hkdf_expand(out_len, &[0; 16], &[0; 16]);
490 assert!(result.is_ok());
491 assert_eq!(result.unwrap().len(), out_len);
492 }
493 }
494
495 #[test]
496 fn test_ec() {
497 let key = ec_key_generate_key();
498 assert!(key.is_ok());
499 assert!(!key.unwrap().0.is_null());
500
501 let key = ec_key_derive_from_secret(&[42; 16]);
502 assert!(key.is_ok());
503 let key = key.unwrap();
504 assert!(!key.0.is_null());
505
506 let point = ec_key_get0_public_key(&key);
507
508 let result = ecdh_compute_key(point.get_point(), &key);
509 assert!(result.is_ok());
510
511 let oct = ec_point_point_to_oct(point.get_point());
512 assert!(oct.is_ok());
513 let oct = oct.unwrap();
514
515 let point2 = ec_point_oct_to_point(oct.as_slice());
516 assert!(point2.is_ok());
517 }
Joel Galensonca0efb12020-10-01 14:32:30 -0700518}