blob: 6436be3a2c9b443dee0ab2f7f4fb9bd7e8b6853c [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
Alice Wangb3fcf632023-09-26 08:32:55 +000018use crate::cbb::CbbFixed;
Alice Wang000595b2023-10-02 13:46:45 +000019use crate::cbs::Cbs;
Alice Wang47287e72023-09-29 13:14:33 +000020use crate::util::{check_int_result, to_call_failed_error};
Alice Wang0271ee02023-11-15 15:03:42 +000021use alloc::vec;
Alice Wang7b2ab942023-09-12 13:04:42 +000022use alloc::vec::Vec;
Alice Wangb3fcf632023-09-26 08:32:55 +000023use bssl_avf_error::{ApiName, Error, Result};
Alan Stokesb1f64ee2023-09-25 10:38:13 +010024use bssl_ffi::{
Alice Wang0271ee02023-11-15 15:03:42 +000025 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 Wang9bd98092023-11-10 14:08:12 +000027 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 Wang000595b2023-10-02 13:46:45 +000029 EC_POINT_get_affine_coordinates, NID_X9_62_prime256v1, BIGNUM, EC_GROUP, EC_KEY, EC_POINT,
Alan Stokesb1f64ee2023-09-25 10:38:13 +010030};
Alice Wang9bd98092023-11-10 14:08:12 +000031use ciborium::Value;
Alice Wanga78d3f02023-09-13 12:39:16 +000032use core::ptr::{self, NonNull};
Alice Wang7b2ab942023-09-12 13:04:42 +000033use core::result;
Alice Wang9bd98092023-11-10 14:08:12 +000034use coset::{
35 iana::{self, EnumI64},
36 CborSerializable, CoseKey, CoseKeyBuilder, Label,
37};
38use log::error;
Alice Wang7b2ab942023-09-12 13:04:42 +000039use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
40
Alice Wang9bd98092023-11-10 14:08:12 +000041const ES256_ALGO: iana::Algorithm = iana::Algorithm::ES256;
42const P256_CURVE: iana::EllipticCurve = iana::EllipticCurve::P_256;
Alice Wanga78d3f02023-09-13 12:39:16 +000043const P256_AFFINE_COORDINATE_SIZE: usize = 32;
44
Alice Wanga78d3f02023-09-13 12:39:16 +000045type Coordinate = [u8; P256_AFFINE_COORDINATE_SIZE];
Alice Wang7b2ab942023-09-12 13:04:42 +000046
47/// Wrapper of an `EC_KEY` object, representing a public or private EC key.
Alice Wang600ea5b2023-11-17 15:12:16 +000048pub struct EcKey(pub(crate) NonNull<EC_KEY>);
Alice Wang7b2ab942023-09-12 13:04:42 +000049
50impl 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
58impl 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 Stokesb1f64ee2023-09-25 10:38:13 +010062 let ec_key = unsafe {
63 EC_KEY_new_by_curve_name(NID_X9_62_prime256v1) // EC P-256 CURVE Nid
64 };
Alice Wang9bd98092023-11-10 14:08:12 +000065 NonNull::new(ec_key)
Alice Wangc8f88f52023-09-25 14:02:17 +000066 .map(Self)
Alice Wang9bd98092023-11-10 14:08:12 +000067 .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 Wang7b2ab942023-09-12 13:04:42 +0000105 Ok(ec_key)
106 }
107
Alice Wang000595b2023-10-02 13:46:45 +0000108 /// 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 Wang0271ee02023-11-15 15:03:42 +0000118 /// 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 Wang9bd98092023-11-10 14:08:12 +0000138 }
139
Alice Wang0271ee02023-11-15 15:03:42 +0000140 /// Signs the `digest` with the current `EcKey` using ECDSA.
Alice Wang9bd98092023-11-10 14:08:12 +0000141 ///
142 /// Returns the DER-encoded ECDSA signature.
Alice Wang0271ee02023-11-15 15:03:42 +0000143 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 Wang9bd98092023-11-10 14:08:12 +0000180 }
181
Alice Wang7b2ab942023-09-12 13:04:42 +0000182 /// Generates a random, private key, calculates the corresponding public key and stores both
183 /// in the `EC_KEY`.
Alice Wang9bd98092023-11-10 14:08:12 +0000184 pub fn generate_key(&mut self) -> Result<()> {
Alice Wang7b2ab942023-09-12 13:04:42 +0000185 // 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 Wangc8f88f52023-09-25 14:02:17 +0000189 check_int_result(ret, ApiName::EC_KEY_generate_key)
Alice Wang7b2ab942023-09-12 13:04:42 +0000190 }
191
Alice Wanga78d3f02023-09-13 12:39:16 +0000192 /// Returns the `CoseKey` for the public key.
193 pub fn cose_public_key(&self) -> Result<CoseKey> {
Alice Wanga78d3f02023-09-13 12:39:16 +0000194 let (x, y) = self.public_key_coordinates()?;
Alice Wang9bd98092023-11-10 14:08:12 +0000195 let key = CoseKeyBuilder::new_ec2_pub_key(P256_CURVE, x.to_vec(), y.to_vec())
196 .algorithm(ES256_ALGO)
197 .build();
Alice Wanga78d3f02023-09-13 12:39:16 +0000198 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 Wangc8f88f52023-09-25 14:02:17 +0000213 check_int_result(ret, ApiName::EC_POINT_get_affine_coordinates)?;
Alice Wanga78d3f02023-09-13 12:39:16 +0000214 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 Wang47287e72023-09-29 13:14:33 +0000225 Err(to_call_failed_error(ApiName::EC_KEY_get0_public_key))
Alice Wanga78d3f02023-09-13 12:39:16 +0000226 } 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 Wang47287e72023-09-29 13:14:33 +0000239 Err(to_call_failed_error(ApiName::EC_KEY_get0_group))
Alice Wanga78d3f02023-09-13 12:39:16 +0000240 } else {
241 Ok(group)
242 }
243 }
Alice Wang7b2ab942023-09-12 13:04:42 +0000244
Alice Wang000595b2023-10-02 13:46:45 +0000245 /// 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 Wang7b2ab942023-09-12 13:04:42 +0000269 /// Returns the DER-encoded ECPrivateKey structure described in RFC 5915 Section 3:
270 ///
271 /// https://datatracker.ietf.org/doc/html/rfc5915#section-3
Alice Wang000595b2023-10-02 13:46:45 +0000272 pub fn ec_private_key(&self) -> Result<ZVec> {
Alice Wang7b2ab942023-09-12 13:04:42 +0000273 const CAPACITY: usize = 256;
274 let mut buf = Zeroizing::new([0u8; CAPACITY]);
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100275 let mut cbb = CbbFixed::new(buf.as_mut());
Alice Wang7b2ab942023-09-12 13:04:42 +0000276 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 Stokesb1f64ee2023-09-25 10:38:13 +0100280 unsafe { EC_KEY_marshal_private_key(cbb.as_mut(), self.0.as_ptr(), enc_flags) };
Alice Wang7b2ab942023-09-12 13:04:42 +0000281
Alice Wangc8f88f52023-09-25 14:02:17 +0000282 check_int_result(ret, ApiName::EC_KEY_marshal_private_key)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000283 // SAFETY: This is safe because the CBB pointer is a valid pointer initialized with
284 // `CBB_init_fixed()`.
Alice Wangc8f88f52023-09-25 14:02:17 +0000285 check_int_result(unsafe { CBB_flush(cbb.as_mut()) }, ApiName::CBB_flush)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000286 // 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 Stokesb1f64ee2023-09-25 10:38:13 +0100288 let len = unsafe { CBB_len(cbb.as_ref()) };
Alice Wang47287e72023-09-29 13:14:33 +0000289 Ok(buf.get(0..len).ok_or(to_call_failed_error(ApiName::CBB_len))?.to_vec().into())
Alice Wang7b2ab942023-09-12 13:04:42 +0000290 }
291}
292
Alice Wang9bd98092023-11-10 14:08:12 +0000293fn 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
300fn 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
304fn 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 Wang7b2ab942023-09-12 13:04:42 +0000317/// A u8 vector that is zeroed when dropped.
318#[derive(Zeroize, ZeroizeOnDrop)]
319pub struct ZVec(Vec<u8>);
320
321impl ZVec {
322 /// Extracts a slice containing the entire vector.
323 pub fn as_slice(&self) -> &[u8] {
324 &self.0[..]
325 }
326}
327
328impl From<Vec<u8>> for ZVec {
329 fn from(v: Vec<u8>) -> Self {
330 Self(v)
331 }
332}
333
Alice Wanga78d3f02023-09-13 12:39:16 +0000334struct BigNum(NonNull<BIGNUM>);
335
336impl 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
343impl BigNum {
Alice Wang9bd98092023-11-10 14:08:12 +0000344 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 Wanga78d3f02023-09-13 12:39:16 +0000351 fn new() -> Result<Self> {
352 // SAFETY: The returned pointer is checked below.
353 let bn = unsafe { BN_new() };
Alice Wang47287e72023-09-29 13:14:33 +0000354 NonNull::new(bn).map(Self).ok_or(to_call_failed_error(ApiName::BN_new))
Alice Wanga78d3f02023-09-13 12:39:16 +0000355 }
356
357 fn as_mut_ptr(&mut self) -> *mut BIGNUM {
358 self.0.as_ptr()
359 }
360}
361
Alice Wang9bd98092023-11-10 14:08:12 +0000362impl 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 Wanga78d3f02023-09-13 12:39:16 +0000370/// 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.
372impl<const N: usize> TryFrom<BigNum> for [u8; N] {
Alice Wangc8f88f52023-09-25 14:02:17 +0000373 type Error = Error;
Alice Wanga78d3f02023-09-13 12:39:16 +0000374
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 Wangc8f88f52023-09-25 14:02:17 +0000379 check_int_result(ret, ApiName::BN_bn2bin_padded)?;
Alice Wanga78d3f02023-09-13 12:39:16 +0000380 Ok(num)
381 }
382}
383
Alice Wang7b2ab942023-09-12 13:04:42 +0000384// TODO(b/301068421): Unit tests the EcKey.