Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 1 | // 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 | |
| 18 | use alloc::vec::Vec; |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame^] | 19 | use bssl_ffi::BN_bn2bin_padded; |
| 20 | use bssl_ffi::BN_clear_free; |
| 21 | use bssl_ffi::BN_new; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 22 | use bssl_ffi::CBB_flush; |
| 23 | use bssl_ffi::CBB_init_fixed; |
| 24 | use bssl_ffi::CBB_len; |
| 25 | use bssl_ffi::EC_KEY_free; |
| 26 | use bssl_ffi::EC_KEY_generate_key; |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame^] | 27 | use bssl_ffi::EC_KEY_get0_group; |
| 28 | use bssl_ffi::EC_KEY_get0_public_key; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 29 | use bssl_ffi::EC_KEY_marshal_private_key; |
| 30 | use bssl_ffi::EC_KEY_new_by_curve_name; |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame^] | 31 | use bssl_ffi::EC_POINT_get_affine_coordinates; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 32 | use bssl_ffi::NID_X9_62_prime256v1; // EC P-256 CURVE Nid |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame^] | 33 | use bssl_ffi::BIGNUM; |
| 34 | use bssl_ffi::EC_GROUP; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 35 | use bssl_ffi::EC_KEY; |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame^] | 36 | use bssl_ffi::EC_POINT; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 37 | use core::mem::MaybeUninit; |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame^] | 38 | use core::ptr::{self, NonNull}; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 39 | use core::result; |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame^] | 40 | use coset::{iana, CoseKey, CoseKeyBuilder}; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 41 | use service_vm_comm::{BoringSSLApiName, RequestProcessingError}; |
| 42 | use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; |
| 43 | |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame^] | 44 | const P256_AFFINE_COORDINATE_SIZE: usize = 32; |
| 45 | |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 46 | type Result<T> = result::Result<T, RequestProcessingError>; |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame^] | 47 | type Coordinate = [u8; P256_AFFINE_COORDINATE_SIZE]; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 48 | |
| 49 | /// Wrapper of an `EC_KEY` object, representing a public or private EC key. |
| 50 | pub struct EcKey(NonNull<EC_KEY>); |
| 51 | |
| 52 | impl Drop for EcKey { |
| 53 | fn drop(&mut self) { |
| 54 | // SAFETY: It is safe because the key has been allocated by BoringSSL and isn't |
| 55 | // used after this. |
| 56 | unsafe { EC_KEY_free(self.0.as_ptr()) } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | impl EcKey { |
| 61 | /// Creates a new EC P-256 key pair. |
| 62 | pub fn new_p256() -> Result<Self> { |
| 63 | // SAFETY: The returned pointer is checked below. |
| 64 | let ec_key = unsafe { EC_KEY_new_by_curve_name(NID_X9_62_prime256v1) }; |
| 65 | let mut ec_key = NonNull::new(ec_key).map(Self).ok_or( |
| 66 | RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::EC_KEY_new_by_curve_name), |
| 67 | )?; |
| 68 | ec_key.generate_key()?; |
| 69 | Ok(ec_key) |
| 70 | } |
| 71 | |
| 72 | /// Generates a random, private key, calculates the corresponding public key and stores both |
| 73 | /// in the `EC_KEY`. |
| 74 | fn generate_key(&mut self) -> Result<()> { |
| 75 | // SAFETY: The non-null pointer is created with `EC_KEY_new_by_curve_name` and should |
| 76 | // point to a valid `EC_KEY`. |
| 77 | // The randomness is provided by `getentropy()` in `vmbase`. |
| 78 | let ret = unsafe { EC_KEY_generate_key(self.0.as_ptr()) }; |
| 79 | check_int_result(ret, BoringSSLApiName::EC_KEY_generate_key) |
| 80 | } |
| 81 | |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame^] | 82 | /// Returns the `CoseKey` for the public key. |
| 83 | pub fn cose_public_key(&self) -> Result<CoseKey> { |
| 84 | const ALGO: iana::Algorithm = iana::Algorithm::ES256; |
| 85 | const CURVE: iana::EllipticCurve = iana::EllipticCurve::P_256; |
| 86 | |
| 87 | let (x, y) = self.public_key_coordinates()?; |
| 88 | let key = |
| 89 | CoseKeyBuilder::new_ec2_pub_key(CURVE, x.to_vec(), y.to_vec()).algorithm(ALGO).build(); |
| 90 | Ok(key) |
| 91 | } |
| 92 | |
| 93 | /// Returns the x and y coordinates of the public key. |
| 94 | fn public_key_coordinates(&self) -> Result<(Coordinate, Coordinate)> { |
| 95 | let ec_group = self.ec_group()?; |
| 96 | let ec_point = self.public_key_ec_point()?; |
| 97 | let mut x = BigNum::new()?; |
| 98 | let mut y = BigNum::new()?; |
| 99 | let ctx = ptr::null_mut(); |
| 100 | // SAFETY: All the parameters are checked non-null and initialized when needed. |
| 101 | // The last parameter `ctx` is generated when needed inside the function. |
| 102 | let ret = unsafe { |
| 103 | EC_POINT_get_affine_coordinates(ec_group, ec_point, x.as_mut_ptr(), y.as_mut_ptr(), ctx) |
| 104 | }; |
| 105 | check_int_result(ret, BoringSSLApiName::EC_POINT_get_affine_coordinates)?; |
| 106 | Ok((x.try_into()?, y.try_into()?)) |
| 107 | } |
| 108 | |
| 109 | /// Returns a pointer to the public key point inside `EC_KEY`. The memory region pointed |
| 110 | /// by the pointer is owned by the `EC_KEY`. |
| 111 | fn public_key_ec_point(&self) -> Result<*const EC_POINT> { |
| 112 | let ec_point = |
| 113 | // SAFETY: It is safe since the key pair has been generated and stored in the |
| 114 | // `EC_KEY` pointer. |
| 115 | unsafe { EC_KEY_get0_public_key(self.0.as_ptr()) }; |
| 116 | if ec_point.is_null() { |
| 117 | Err(RequestProcessingError::BoringSSLCallFailed( |
| 118 | BoringSSLApiName::EC_KEY_get0_public_key, |
| 119 | )) |
| 120 | } else { |
| 121 | Ok(ec_point) |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | /// Returns a pointer to the `EC_GROUP` object inside `EC_KEY`. The memory region pointed |
| 126 | /// by the pointer is owned by the `EC_KEY`. |
| 127 | fn ec_group(&self) -> Result<*const EC_GROUP> { |
| 128 | let group = |
| 129 | // SAFETY: It is safe since the key pair has been generated and stored in the |
| 130 | // `EC_KEY` pointer. |
| 131 | unsafe { EC_KEY_get0_group(self.0.as_ptr()) }; |
| 132 | if group.is_null() { |
| 133 | Err(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::EC_KEY_get0_group)) |
| 134 | } else { |
| 135 | Ok(group) |
| 136 | } |
| 137 | } |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 138 | |
| 139 | /// Returns the DER-encoded ECPrivateKey structure described in RFC 5915 Section 3: |
| 140 | /// |
| 141 | /// https://datatracker.ietf.org/doc/html/rfc5915#section-3 |
| 142 | pub fn private_key(&self) -> Result<ZVec> { |
| 143 | const CAPACITY: usize = 256; |
| 144 | let mut buf = Zeroizing::new([0u8; CAPACITY]); |
| 145 | // SAFETY: `CBB_init_fixed()` is infallible and always returns one. |
| 146 | // The `buf` is never moved and remains valid during the lifetime of `cbb`. |
| 147 | let mut cbb = unsafe { |
| 148 | let mut cbb = MaybeUninit::uninit(); |
| 149 | CBB_init_fixed(cbb.as_mut_ptr(), buf.as_mut_ptr(), buf.len()); |
| 150 | cbb.assume_init() |
| 151 | }; |
| 152 | let enc_flags = 0; |
| 153 | let ret = |
| 154 | // SAFETY: The function only write bytes to the buffer managed by the valid `CBB` |
| 155 | // object, and the key has been allocated by BoringSSL. |
| 156 | unsafe { EC_KEY_marshal_private_key(&mut cbb, self.0.as_ptr(), enc_flags) }; |
| 157 | |
| 158 | check_int_result(ret, BoringSSLApiName::EC_KEY_marshal_private_key)?; |
| 159 | // SAFETY: This is safe because the CBB pointer is a valid pointer initialized with |
| 160 | // `CBB_init_fixed()`. |
| 161 | check_int_result(unsafe { CBB_flush(&mut cbb) }, BoringSSLApiName::CBB_flush)?; |
| 162 | // SAFETY: This is safe because the CBB pointer is initialized with `CBB_init_fixed()`, |
| 163 | // and it has been flushed, thus it has no active children. |
| 164 | let len = unsafe { CBB_len(&cbb) }; |
| 165 | Ok(buf |
| 166 | .get(0..len) |
| 167 | .ok_or(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::CBB_len))? |
| 168 | .to_vec() |
| 169 | .into()) |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | /// A u8 vector that is zeroed when dropped. |
| 174 | #[derive(Zeroize, ZeroizeOnDrop)] |
| 175 | pub struct ZVec(Vec<u8>); |
| 176 | |
| 177 | impl ZVec { |
| 178 | /// Extracts a slice containing the entire vector. |
| 179 | pub fn as_slice(&self) -> &[u8] { |
| 180 | &self.0[..] |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | impl From<Vec<u8>> for ZVec { |
| 185 | fn from(v: Vec<u8>) -> Self { |
| 186 | Self(v) |
| 187 | } |
| 188 | } |
| 189 | |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame^] | 190 | struct BigNum(NonNull<BIGNUM>); |
| 191 | |
| 192 | impl Drop for BigNum { |
| 193 | fn drop(&mut self) { |
| 194 | // SAFETY: The pointer has been created with `BN_new`. |
| 195 | unsafe { BN_clear_free(self.as_mut_ptr()) } |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | impl BigNum { |
| 200 | fn new() -> Result<Self> { |
| 201 | // SAFETY: The returned pointer is checked below. |
| 202 | let bn = unsafe { BN_new() }; |
| 203 | NonNull::new(bn) |
| 204 | .map(Self) |
| 205 | .ok_or(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::BN_new)) |
| 206 | } |
| 207 | |
| 208 | fn as_mut_ptr(&mut self) -> *mut BIGNUM { |
| 209 | self.0.as_ptr() |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | /// Converts the `BigNum` to a big-endian integer. The integer is padded with leading zeros up to |
| 214 | /// size `N`. The conversion fails if `N` is smaller thanthe size of the integer. |
| 215 | impl<const N: usize> TryFrom<BigNum> for [u8; N] { |
| 216 | type Error = RequestProcessingError; |
| 217 | |
| 218 | fn try_from(bn: BigNum) -> result::Result<Self, Self::Error> { |
| 219 | let mut num = [0u8; N]; |
| 220 | // SAFETY: The `BIGNUM` pointer has been created with `BN_new`. |
| 221 | let ret = unsafe { BN_bn2bin_padded(num.as_mut_ptr(), num.len(), bn.0.as_ptr()) }; |
| 222 | check_int_result(ret, BoringSSLApiName::BN_bn2bin_padded)?; |
| 223 | Ok(num) |
| 224 | } |
| 225 | } |
| 226 | |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 227 | fn check_int_result(ret: i32, api_name: BoringSSLApiName) -> Result<()> { |
| 228 | if ret == 1 { |
| 229 | Ok(()) |
| 230 | } else { |
| 231 | assert_eq!(ret, 0, "Unexpected return value {ret} for {api_name:?}"); |
| 232 | Err(RequestProcessingError::BoringSSLCallFailed(api_name)) |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | // TODO(b/301068421): Unit tests the EcKey. |