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