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 | 0271ee0 | 2023-11-15 15:03:42 +0000 | [diff] [blame] | 21 | use alloc::vec; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 22 | use alloc::vec::Vec; |
Alice Wang | b3fcf63 | 2023-09-26 08:32:55 +0000 | [diff] [blame] | 23 | use bssl_avf_error::{ApiName, Error, Result}; |
Alan Stokes | b1f64ee | 2023-09-25 10:38:13 +0100 | [diff] [blame] | 24 | use bssl_ffi::{ |
Alice Wang | 0271ee0 | 2023-11-15 15:03:42 +0000 | [diff] [blame] | 25 | BN_bin2bn, BN_bn2bin_padded, BN_clear_free, BN_new, CBB_flush, CBB_len, ECDSA_sign, ECDSA_size, |
| 26 | ECDSA_verify, EC_GROUP_new_by_curve_name, EC_KEY_check_key, EC_KEY_free, EC_KEY_generate_key, |
Alice Wang | 9bd9809 | 2023-11-10 14:08:12 +0000 | [diff] [blame] | 27 | EC_KEY_get0_group, EC_KEY_get0_public_key, EC_KEY_marshal_private_key, |
| 28 | EC_KEY_new_by_curve_name, EC_KEY_parse_private_key, EC_KEY_set_public_key_affine_coordinates, |
Alice Wang | 000595b | 2023-10-02 13:46:45 +0000 | [diff] [blame] | 29 | 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] | 30 | }; |
Alice Wang | 9bd9809 | 2023-11-10 14:08:12 +0000 | [diff] [blame] | 31 | use ciborium::Value; |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame] | 32 | use core::ptr::{self, NonNull}; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 33 | use core::result; |
Alice Wang | 9bd9809 | 2023-11-10 14:08:12 +0000 | [diff] [blame] | 34 | use coset::{ |
| 35 | iana::{self, EnumI64}, |
| 36 | CborSerializable, CoseKey, CoseKeyBuilder, Label, |
| 37 | }; |
| 38 | use log::error; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 39 | use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; |
| 40 | |
Alice Wang | 9bd9809 | 2023-11-10 14:08:12 +0000 | [diff] [blame] | 41 | const ES256_ALGO: iana::Algorithm = iana::Algorithm::ES256; |
| 42 | const P256_CURVE: iana::EllipticCurve = iana::EllipticCurve::P_256; |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame] | 43 | const P256_AFFINE_COORDINATE_SIZE: usize = 32; |
| 44 | |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame] | 45 | type Coordinate = [u8; P256_AFFINE_COORDINATE_SIZE]; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 46 | |
| 47 | /// Wrapper of an `EC_KEY` object, representing a public or private EC key. |
Alice Wang | 600ea5b | 2023-11-17 15:12:16 +0000 | [diff] [blame^] | 48 | pub struct EcKey(pub(crate) NonNull<EC_KEY>); |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 49 | |
| 50 | impl Drop for EcKey { |
| 51 | fn drop(&mut self) { |
| 52 | // SAFETY: It is safe because the key has been allocated by BoringSSL and isn't |
| 53 | // used after this. |
| 54 | unsafe { EC_KEY_free(self.0.as_ptr()) } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | impl EcKey { |
| 59 | /// Creates a new EC P-256 key pair. |
| 60 | pub fn new_p256() -> Result<Self> { |
| 61 | // SAFETY: The returned pointer is checked below. |
Alan Stokes | b1f64ee | 2023-09-25 10:38:13 +0100 | [diff] [blame] | 62 | let ec_key = unsafe { |
| 63 | EC_KEY_new_by_curve_name(NID_X9_62_prime256v1) // EC P-256 CURVE Nid |
| 64 | }; |
Alice Wang | 9bd9809 | 2023-11-10 14:08:12 +0000 | [diff] [blame] | 65 | NonNull::new(ec_key) |
Alice Wang | c8f88f5 | 2023-09-25 14:02:17 +0000 | [diff] [blame] | 66 | .map(Self) |
Alice Wang | 9bd9809 | 2023-11-10 14:08:12 +0000 | [diff] [blame] | 67 | .ok_or(to_call_failed_error(ApiName::EC_KEY_new_by_curve_name)) |
| 68 | } |
| 69 | |
| 70 | /// Constructs an `EcKey` instance from the provided COSE_Key encoded public key slice. |
| 71 | pub fn from_cose_public_key(cose_key: &[u8]) -> Result<Self> { |
| 72 | let cose_key = CoseKey::from_slice(cose_key).map_err(|e| { |
| 73 | error!("Failed to deserialize COSE_Key: {e:?}"); |
| 74 | Error::CoseKeyDecodingFailed |
| 75 | })?; |
| 76 | if cose_key.alg != Some(coset::Algorithm::Assigned(ES256_ALGO)) { |
| 77 | error!( |
| 78 | "Only ES256 algorithm is supported. Algo type in the COSE Key: {:?}", |
| 79 | cose_key.alg |
| 80 | ); |
| 81 | return Err(Error::Unimplemented); |
| 82 | } |
| 83 | let crv = get_label_value(&cose_key, Label::Int(iana::Ec2KeyParameter::Crv.to_i64()))?; |
| 84 | if &Value::from(P256_CURVE.to_i64()) != crv { |
| 85 | error!("Only EC P-256 curve is supported. Curve type in the COSE Key: {crv:?}"); |
| 86 | return Err(Error::Unimplemented); |
| 87 | } |
| 88 | |
| 89 | let x = get_label_value_as_bytes(&cose_key, Label::Int(iana::Ec2KeyParameter::X.to_i64()))?; |
| 90 | let y = get_label_value_as_bytes(&cose_key, Label::Int(iana::Ec2KeyParameter::Y.to_i64()))?; |
| 91 | |
| 92 | check_p256_affine_coordinate_size(x)?; |
| 93 | check_p256_affine_coordinate_size(y)?; |
| 94 | |
| 95 | let x = BigNum::from_slice(x)?; |
| 96 | let y = BigNum::from_slice(y)?; |
| 97 | |
| 98 | let ec_key = EcKey::new_p256()?; |
| 99 | // SAFETY: All the parameters are checked non-null and initialized. |
| 100 | // The function only reads the coordinates x and y within their bounds. |
| 101 | let ret = unsafe { |
| 102 | EC_KEY_set_public_key_affine_coordinates(ec_key.0.as_ptr(), x.as_ref(), y.as_ref()) |
| 103 | }; |
| 104 | check_int_result(ret, ApiName::EC_KEY_set_public_key_affine_coordinates)?; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 105 | Ok(ec_key) |
| 106 | } |
| 107 | |
Alice Wang | 000595b | 2023-10-02 13:46:45 +0000 | [diff] [blame] | 108 | /// Performs several checks on the key. See BoringSSL doc for more details: |
| 109 | /// |
| 110 | /// https://commondatastorage.googleapis.com/chromium-boringssl-docs/ec_key.h.html#EC_KEY_check_key |
| 111 | pub fn check_key(&self) -> Result<()> { |
| 112 | // SAFETY: This function only reads the `EC_KEY` pointer, the non-null check is performed |
| 113 | // within the function. |
| 114 | let ret = unsafe { EC_KEY_check_key(self.0.as_ptr()) }; |
| 115 | check_int_result(ret, ApiName::EC_KEY_check_key) |
| 116 | } |
| 117 | |
Alice Wang | 0271ee0 | 2023-11-15 15:03:42 +0000 | [diff] [blame] | 118 | /// Verifies the DER-encoded ECDSA `signature` of the `digest` with the current `EcKey`. |
| 119 | /// |
| 120 | /// Returns Ok(()) if the verification succeeds, otherwise an error will be returned. |
| 121 | pub fn ecdsa_verify(&self, signature: &[u8], digest: &[u8]) -> Result<()> { |
| 122 | // The `type` argument should be 0 as required in the BoringSSL spec. |
| 123 | const TYPE: i32 = 0; |
| 124 | |
| 125 | // SAFETY: This function only reads the given data within its bounds. |
| 126 | // The `EC_KEY` passed to this function has been initialized and checked non-null. |
| 127 | let ret = unsafe { |
| 128 | ECDSA_verify( |
| 129 | TYPE, |
| 130 | digest.as_ptr(), |
| 131 | digest.len(), |
| 132 | signature.as_ptr(), |
| 133 | signature.len(), |
| 134 | self.0.as_ptr(), |
| 135 | ) |
| 136 | }; |
| 137 | check_int_result(ret, ApiName::ECDSA_verify) |
Alice Wang | 9bd9809 | 2023-11-10 14:08:12 +0000 | [diff] [blame] | 138 | } |
| 139 | |
Alice Wang | 0271ee0 | 2023-11-15 15:03:42 +0000 | [diff] [blame] | 140 | /// Signs the `digest` with the current `EcKey` using ECDSA. |
Alice Wang | 9bd9809 | 2023-11-10 14:08:12 +0000 | [diff] [blame] | 141 | /// |
| 142 | /// Returns the DER-encoded ECDSA signature. |
Alice Wang | 0271ee0 | 2023-11-15 15:03:42 +0000 | [diff] [blame] | 143 | pub fn ecdsa_sign(&self, digest: &[u8]) -> Result<Vec<u8>> { |
| 144 | // The `type` argument should be 0 as required in the BoringSSL spec. |
| 145 | const TYPE: i32 = 0; |
| 146 | |
| 147 | let mut signature = vec![0u8; self.ecdsa_size()?]; |
| 148 | let mut signature_len = 0; |
| 149 | // SAFETY: This function only reads the given data within its bounds. |
| 150 | // The `EC_KEY` passed to this function has been initialized and checked non-null. |
| 151 | let ret = unsafe { |
| 152 | ECDSA_sign( |
| 153 | TYPE, |
| 154 | digest.as_ptr(), |
| 155 | digest.len(), |
| 156 | signature.as_mut_ptr(), |
| 157 | &mut signature_len, |
| 158 | self.0.as_ptr(), |
| 159 | ) |
| 160 | }; |
| 161 | check_int_result(ret, ApiName::ECDSA_sign)?; |
| 162 | if signature.len() < (signature_len as usize) { |
| 163 | Err(to_call_failed_error(ApiName::ECDSA_sign)) |
| 164 | } else { |
| 165 | signature.truncate(signature_len as usize); |
| 166 | Ok(signature) |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | /// Returns the maximum size of an ECDSA signature using the current `EcKey`. |
| 171 | fn ecdsa_size(&self) -> Result<usize> { |
| 172 | // SAFETY: This function only reads the `EC_KEY` that has been initialized |
| 173 | // and checked non-null when this instance is created. |
| 174 | let size = unsafe { ECDSA_size(self.0.as_ptr()) }; |
| 175 | if size == 0 { |
| 176 | Err(to_call_failed_error(ApiName::ECDSA_size)) |
| 177 | } else { |
| 178 | Ok(size) |
| 179 | } |
Alice Wang | 9bd9809 | 2023-11-10 14:08:12 +0000 | [diff] [blame] | 180 | } |
| 181 | |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 182 | /// Generates a random, private key, calculates the corresponding public key and stores both |
| 183 | /// in the `EC_KEY`. |
Alice Wang | 9bd9809 | 2023-11-10 14:08:12 +0000 | [diff] [blame] | 184 | pub fn generate_key(&mut self) -> Result<()> { |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 185 | // SAFETY: The non-null pointer is created with `EC_KEY_new_by_curve_name` and should |
| 186 | // point to a valid `EC_KEY`. |
| 187 | // The randomness is provided by `getentropy()` in `vmbase`. |
| 188 | let ret = unsafe { EC_KEY_generate_key(self.0.as_ptr()) }; |
Alice Wang | c8f88f5 | 2023-09-25 14:02:17 +0000 | [diff] [blame] | 189 | check_int_result(ret, ApiName::EC_KEY_generate_key) |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 190 | } |
| 191 | |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame] | 192 | /// Returns the `CoseKey` for the public key. |
| 193 | pub fn cose_public_key(&self) -> Result<CoseKey> { |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame] | 194 | let (x, y) = self.public_key_coordinates()?; |
Alice Wang | 9bd9809 | 2023-11-10 14:08:12 +0000 | [diff] [blame] | 195 | let key = CoseKeyBuilder::new_ec2_pub_key(P256_CURVE, x.to_vec(), y.to_vec()) |
| 196 | .algorithm(ES256_ALGO) |
| 197 | .build(); |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame] | 198 | Ok(key) |
| 199 | } |
| 200 | |
| 201 | /// Returns the x and y coordinates of the public key. |
| 202 | fn public_key_coordinates(&self) -> Result<(Coordinate, Coordinate)> { |
| 203 | let ec_group = self.ec_group()?; |
| 204 | let ec_point = self.public_key_ec_point()?; |
| 205 | let mut x = BigNum::new()?; |
| 206 | let mut y = BigNum::new()?; |
| 207 | let ctx = ptr::null_mut(); |
| 208 | // SAFETY: All the parameters are checked non-null and initialized when needed. |
| 209 | // The last parameter `ctx` is generated when needed inside the function. |
| 210 | let ret = unsafe { |
| 211 | EC_POINT_get_affine_coordinates(ec_group, ec_point, x.as_mut_ptr(), y.as_mut_ptr(), ctx) |
| 212 | }; |
Alice Wang | c8f88f5 | 2023-09-25 14:02:17 +0000 | [diff] [blame] | 213 | check_int_result(ret, ApiName::EC_POINT_get_affine_coordinates)?; |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame] | 214 | Ok((x.try_into()?, y.try_into()?)) |
| 215 | } |
| 216 | |
| 217 | /// Returns a pointer to the public key point inside `EC_KEY`. The memory region pointed |
| 218 | /// by the pointer is owned by the `EC_KEY`. |
| 219 | fn public_key_ec_point(&self) -> Result<*const EC_POINT> { |
| 220 | let ec_point = |
| 221 | // SAFETY: It is safe since the key pair has been generated and stored in the |
| 222 | // `EC_KEY` pointer. |
| 223 | unsafe { EC_KEY_get0_public_key(self.0.as_ptr()) }; |
| 224 | if ec_point.is_null() { |
Alice Wang | 47287e7 | 2023-09-29 13:14:33 +0000 | [diff] [blame] | 225 | Err(to_call_failed_error(ApiName::EC_KEY_get0_public_key)) |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame] | 226 | } else { |
| 227 | Ok(ec_point) |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | /// Returns a pointer to the `EC_GROUP` object inside `EC_KEY`. The memory region pointed |
| 232 | /// by the pointer is owned by the `EC_KEY`. |
| 233 | fn ec_group(&self) -> Result<*const EC_GROUP> { |
| 234 | let group = |
| 235 | // SAFETY: It is safe since the key pair has been generated and stored in the |
| 236 | // `EC_KEY` pointer. |
| 237 | unsafe { EC_KEY_get0_group(self.0.as_ptr()) }; |
| 238 | if group.is_null() { |
Alice Wang | 47287e7 | 2023-09-29 13:14:33 +0000 | [diff] [blame] | 239 | Err(to_call_failed_error(ApiName::EC_KEY_get0_group)) |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame] | 240 | } else { |
| 241 | Ok(group) |
| 242 | } |
| 243 | } |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 244 | |
Alice Wang | 000595b | 2023-10-02 13:46:45 +0000 | [diff] [blame] | 245 | /// Constructs an `EcKey` instance from the provided DER-encoded ECPrivateKey slice. |
| 246 | /// |
| 247 | /// Currently, only the EC P-256 curve is supported. |
| 248 | pub fn from_ec_private_key(der_encoded_ec_private_key: &[u8]) -> Result<Self> { |
| 249 | // SAFETY: This function only returns a pointer to a static object, and the |
| 250 | // return is checked below. |
| 251 | let ec_group = unsafe { |
| 252 | EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1) // EC P-256 CURVE Nid |
| 253 | }; |
| 254 | if ec_group.is_null() { |
| 255 | return Err(to_call_failed_error(ApiName::EC_GROUP_new_by_curve_name)); |
| 256 | } |
| 257 | let mut cbs = Cbs::new(der_encoded_ec_private_key); |
| 258 | // SAFETY: The function only reads bytes from the buffer managed by the valid `CBS` |
| 259 | // object, and the returned EC_KEY is checked. |
| 260 | let ec_key = unsafe { EC_KEY_parse_private_key(cbs.as_mut(), ec_group) }; |
| 261 | |
| 262 | let ec_key = NonNull::new(ec_key) |
| 263 | .map(Self) |
| 264 | .ok_or(to_call_failed_error(ApiName::EC_KEY_parse_private_key))?; |
| 265 | ec_key.check_key()?; |
| 266 | Ok(ec_key) |
| 267 | } |
| 268 | |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 269 | /// Returns the DER-encoded ECPrivateKey structure described in RFC 5915 Section 3: |
| 270 | /// |
| 271 | /// https://datatracker.ietf.org/doc/html/rfc5915#section-3 |
Alice Wang | 000595b | 2023-10-02 13:46:45 +0000 | [diff] [blame] | 272 | pub fn ec_private_key(&self) -> Result<ZVec> { |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 273 | const CAPACITY: usize = 256; |
| 274 | let mut buf = Zeroizing::new([0u8; CAPACITY]); |
Alan Stokes | b1f64ee | 2023-09-25 10:38:13 +0100 | [diff] [blame] | 275 | let mut cbb = CbbFixed::new(buf.as_mut()); |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 276 | let enc_flags = 0; |
| 277 | let ret = |
| 278 | // SAFETY: The function only write bytes to the buffer managed by the valid `CBB` |
| 279 | // object, and the key has been allocated by BoringSSL. |
Alan Stokes | b1f64ee | 2023-09-25 10:38:13 +0100 | [diff] [blame] | 280 | 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] | 281 | |
Alice Wang | c8f88f5 | 2023-09-25 14:02:17 +0000 | [diff] [blame] | 282 | check_int_result(ret, ApiName::EC_KEY_marshal_private_key)?; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 283 | // SAFETY: This is safe because the CBB pointer is a valid pointer initialized with |
| 284 | // `CBB_init_fixed()`. |
Alice Wang | c8f88f5 | 2023-09-25 14:02:17 +0000 | [diff] [blame] | 285 | check_int_result(unsafe { CBB_flush(cbb.as_mut()) }, ApiName::CBB_flush)?; |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 286 | // SAFETY: This is safe because the CBB pointer is initialized with `CBB_init_fixed()`, |
| 287 | // and it has been flushed, thus it has no active children. |
Alan Stokes | b1f64ee | 2023-09-25 10:38:13 +0100 | [diff] [blame] | 288 | let len = unsafe { CBB_len(cbb.as_ref()) }; |
Alice Wang | 47287e7 | 2023-09-29 13:14:33 +0000 | [diff] [blame] | 289 | 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] | 290 | } |
| 291 | } |
| 292 | |
Alice Wang | 9bd9809 | 2023-11-10 14:08:12 +0000 | [diff] [blame] | 293 | fn get_label_value_as_bytes(key: &CoseKey, label: Label) -> Result<&[u8]> { |
| 294 | Ok(get_label_value(key, label)?.as_bytes().ok_or_else(|| { |
| 295 | error!("Value not a bstr."); |
| 296 | Error::CoseKeyDecodingFailed |
| 297 | })?) |
| 298 | } |
| 299 | |
| 300 | fn get_label_value(key: &CoseKey, label: Label) -> Result<&Value> { |
| 301 | Ok(&key.params.iter().find(|(k, _)| k == &label).ok_or(Error::CoseKeyDecodingFailed)?.1) |
| 302 | } |
| 303 | |
| 304 | fn check_p256_affine_coordinate_size(coordinate: &[u8]) -> Result<()> { |
| 305 | if P256_AFFINE_COORDINATE_SIZE == coordinate.len() { |
| 306 | Ok(()) |
| 307 | } else { |
| 308 | error!( |
| 309 | "The size of the affine coordinate '{}' does not match the expected size '{}'", |
| 310 | coordinate.len(), |
| 311 | P256_AFFINE_COORDINATE_SIZE |
| 312 | ); |
| 313 | Err(Error::CoseKeyDecodingFailed) |
| 314 | } |
| 315 | } |
| 316 | |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 317 | /// A u8 vector that is zeroed when dropped. |
| 318 | #[derive(Zeroize, ZeroizeOnDrop)] |
| 319 | pub struct ZVec(Vec<u8>); |
| 320 | |
| 321 | impl ZVec { |
| 322 | /// Extracts a slice containing the entire vector. |
| 323 | pub fn as_slice(&self) -> &[u8] { |
| 324 | &self.0[..] |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | impl From<Vec<u8>> for ZVec { |
| 329 | fn from(v: Vec<u8>) -> Self { |
| 330 | Self(v) |
| 331 | } |
| 332 | } |
| 333 | |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame] | 334 | struct BigNum(NonNull<BIGNUM>); |
| 335 | |
| 336 | impl Drop for BigNum { |
| 337 | fn drop(&mut self) { |
| 338 | // SAFETY: The pointer has been created with `BN_new`. |
| 339 | unsafe { BN_clear_free(self.as_mut_ptr()) } |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | impl BigNum { |
Alice Wang | 9bd9809 | 2023-11-10 14:08:12 +0000 | [diff] [blame] | 344 | fn from_slice(x: &[u8]) -> Result<Self> { |
| 345 | // SAFETY: The function reads `x` within its bounds, and the returned |
| 346 | // pointer is checked below. |
| 347 | let bn = unsafe { BN_bin2bn(x.as_ptr(), x.len(), ptr::null_mut()) }; |
| 348 | NonNull::new(bn).map(Self).ok_or(to_call_failed_error(ApiName::BN_bin2bn)) |
| 349 | } |
| 350 | |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame] | 351 | fn new() -> Result<Self> { |
| 352 | // SAFETY: The returned pointer is checked below. |
| 353 | let bn = unsafe { BN_new() }; |
Alice Wang | 47287e7 | 2023-09-29 13:14:33 +0000 | [diff] [blame] | 354 | 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] | 355 | } |
| 356 | |
| 357 | fn as_mut_ptr(&mut self) -> *mut BIGNUM { |
| 358 | self.0.as_ptr() |
| 359 | } |
| 360 | } |
| 361 | |
Alice Wang | 9bd9809 | 2023-11-10 14:08:12 +0000 | [diff] [blame] | 362 | impl AsRef<BIGNUM> for BigNum { |
| 363 | fn as_ref(&self) -> &BIGNUM { |
| 364 | // SAFETY: The pointer is valid and points to an initialized instance of `BIGNUM` |
| 365 | // when the instance was created. |
| 366 | unsafe { self.0.as_ref() } |
| 367 | } |
| 368 | } |
| 369 | |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame] | 370 | /// Converts the `BigNum` to a big-endian integer. The integer is padded with leading zeros up to |
| 371 | /// size `N`. The conversion fails if `N` is smaller thanthe size of the integer. |
| 372 | impl<const N: usize> TryFrom<BigNum> for [u8; N] { |
Alice Wang | c8f88f5 | 2023-09-25 14:02:17 +0000 | [diff] [blame] | 373 | type Error = Error; |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame] | 374 | |
| 375 | fn try_from(bn: BigNum) -> result::Result<Self, Self::Error> { |
| 376 | let mut num = [0u8; N]; |
| 377 | // SAFETY: The `BIGNUM` pointer has been created with `BN_new`. |
| 378 | 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] | 379 | check_int_result(ret, ApiName::BN_bn2bin_padded)?; |
Alice Wang | a78d3f0 | 2023-09-13 12:39:16 +0000 | [diff] [blame] | 380 | Ok(num) |
| 381 | } |
| 382 | } |
| 383 | |
Alice Wang | 7b2ab94 | 2023-09-12 13:04:42 +0000 | [diff] [blame] | 384 | // TODO(b/301068421): Unit tests the EcKey. |