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