blob: 2f3fe904d728b590ec4c16af61a33cd6be24b367 [file] [log] [blame]
Alice Wang7b2ab942023-09-12 13:04:42 +00001// Copyright 2023, 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
15//! Contains struct and functions that wraps the API related to EC_KEY in
16//! BoringSSL.
17
18use alloc::vec::Vec;
19use bssl_ffi::CBB_flush;
20use bssl_ffi::CBB_init_fixed;
21use bssl_ffi::CBB_len;
22use bssl_ffi::EC_KEY_free;
23use bssl_ffi::EC_KEY_generate_key;
24use bssl_ffi::EC_KEY_marshal_private_key;
25use bssl_ffi::EC_KEY_new_by_curve_name;
26use bssl_ffi::NID_X9_62_prime256v1; // EC P-256 CURVE Nid
27use bssl_ffi::EC_KEY;
28use core::mem::MaybeUninit;
29use core::ptr::NonNull;
30use core::result;
31use service_vm_comm::{BoringSSLApiName, RequestProcessingError};
32use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
33
34type Result<T> = result::Result<T, RequestProcessingError>;
35
36/// Wrapper of an `EC_KEY` object, representing a public or private EC key.
37pub struct EcKey(NonNull<EC_KEY>);
38
39impl Drop for EcKey {
40 fn drop(&mut self) {
41 // SAFETY: It is safe because the key has been allocated by BoringSSL and isn't
42 // used after this.
43 unsafe { EC_KEY_free(self.0.as_ptr()) }
44 }
45}
46
47impl EcKey {
48 /// Creates a new EC P-256 key pair.
49 pub fn new_p256() -> Result<Self> {
50 // SAFETY: The returned pointer is checked below.
51 let ec_key = unsafe { EC_KEY_new_by_curve_name(NID_X9_62_prime256v1) };
52 let mut ec_key = NonNull::new(ec_key).map(Self).ok_or(
53 RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::EC_KEY_new_by_curve_name),
54 )?;
55 ec_key.generate_key()?;
56 Ok(ec_key)
57 }
58
59 /// Generates a random, private key, calculates the corresponding public key and stores both
60 /// in the `EC_KEY`.
61 fn generate_key(&mut self) -> Result<()> {
62 // SAFETY: The non-null pointer is created with `EC_KEY_new_by_curve_name` and should
63 // point to a valid `EC_KEY`.
64 // The randomness is provided by `getentropy()` in `vmbase`.
65 let ret = unsafe { EC_KEY_generate_key(self.0.as_ptr()) };
66 check_int_result(ret, BoringSSLApiName::EC_KEY_generate_key)
67 }
68
69 // TODO(b/300068317): Returns the CoseKey for the public key.
70
71 /// Returns the DER-encoded ECPrivateKey structure described in RFC 5915 Section 3:
72 ///
73 /// https://datatracker.ietf.org/doc/html/rfc5915#section-3
74 pub fn private_key(&self) -> Result<ZVec> {
75 const CAPACITY: usize = 256;
76 let mut buf = Zeroizing::new([0u8; CAPACITY]);
77 // SAFETY: `CBB_init_fixed()` is infallible and always returns one.
78 // The `buf` is never moved and remains valid during the lifetime of `cbb`.
79 let mut cbb = unsafe {
80 let mut cbb = MaybeUninit::uninit();
81 CBB_init_fixed(cbb.as_mut_ptr(), buf.as_mut_ptr(), buf.len());
82 cbb.assume_init()
83 };
84 let enc_flags = 0;
85 let ret =
86 // SAFETY: The function only write bytes to the buffer managed by the valid `CBB`
87 // object, and the key has been allocated by BoringSSL.
88 unsafe { EC_KEY_marshal_private_key(&mut cbb, self.0.as_ptr(), enc_flags) };
89
90 check_int_result(ret, BoringSSLApiName::EC_KEY_marshal_private_key)?;
91 // SAFETY: This is safe because the CBB pointer is a valid pointer initialized with
92 // `CBB_init_fixed()`.
93 check_int_result(unsafe { CBB_flush(&mut cbb) }, BoringSSLApiName::CBB_flush)?;
94 // SAFETY: This is safe because the CBB pointer is initialized with `CBB_init_fixed()`,
95 // and it has been flushed, thus it has no active children.
96 let len = unsafe { CBB_len(&cbb) };
97 Ok(buf
98 .get(0..len)
99 .ok_or(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::CBB_len))?
100 .to_vec()
101 .into())
102 }
103}
104
105/// A u8 vector that is zeroed when dropped.
106#[derive(Zeroize, ZeroizeOnDrop)]
107pub struct ZVec(Vec<u8>);
108
109impl ZVec {
110 /// Extracts a slice containing the entire vector.
111 pub fn as_slice(&self) -> &[u8] {
112 &self.0[..]
113 }
114}
115
116impl From<Vec<u8>> for ZVec {
117 fn from(v: Vec<u8>) -> Self {
118 Self(v)
119 }
120}
121
122fn check_int_result(ret: i32, api_name: BoringSSLApiName) -> Result<()> {
123 if ret == 1 {
124 Ok(())
125 } else {
126 assert_eq!(ret, 0, "Unexpected return value {ret} for {api_name:?}");
127 Err(RequestProcessingError::BoringSSLCallFailed(api_name))
128 }
129}
130
131// TODO(b/301068421): Unit tests the EcKey.