blob: a187259fc9ff9b078fb0fe0f6c1e41f24e6c3574 [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 Wangf061e472023-11-21 08:17:16 +0000105 ec_key.check_key()?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000106 Ok(ec_key)
107 }
108
Alice Wang000595b2023-10-02 13:46:45 +0000109 /// Performs several checks on the key. See BoringSSL doc for more details:
110 ///
111 /// https://commondatastorage.googleapis.com/chromium-boringssl-docs/ec_key.h.html#EC_KEY_check_key
112 pub fn check_key(&self) -> Result<()> {
113 // SAFETY: This function only reads the `EC_KEY` pointer, the non-null check is performed
114 // within the function.
115 let ret = unsafe { EC_KEY_check_key(self.0.as_ptr()) };
116 check_int_result(ret, ApiName::EC_KEY_check_key)
117 }
118
Alice Wang0271ee02023-11-15 15:03:42 +0000119 /// Verifies the DER-encoded ECDSA `signature` of the `digest` with the current `EcKey`.
120 ///
121 /// Returns Ok(()) if the verification succeeds, otherwise an error will be returned.
122 pub fn ecdsa_verify(&self, signature: &[u8], digest: &[u8]) -> Result<()> {
123 // The `type` argument should be 0 as required in the BoringSSL spec.
124 const TYPE: i32 = 0;
125
126 // SAFETY: This function only reads the given data within its bounds.
127 // The `EC_KEY` passed to this function has been initialized and checked non-null.
128 let ret = unsafe {
129 ECDSA_verify(
130 TYPE,
131 digest.as_ptr(),
132 digest.len(),
133 signature.as_ptr(),
134 signature.len(),
135 self.0.as_ptr(),
136 )
137 };
138 check_int_result(ret, ApiName::ECDSA_verify)
Alice Wang9bd98092023-11-10 14:08:12 +0000139 }
140
Alice Wang0271ee02023-11-15 15:03:42 +0000141 /// Signs the `digest` with the current `EcKey` using ECDSA.
Alice Wang9bd98092023-11-10 14:08:12 +0000142 ///
143 /// Returns the DER-encoded ECDSA signature.
Alice Wang0271ee02023-11-15 15:03:42 +0000144 pub fn ecdsa_sign(&self, digest: &[u8]) -> Result<Vec<u8>> {
145 // The `type` argument should be 0 as required in the BoringSSL spec.
146 const TYPE: i32 = 0;
147
148 let mut signature = vec![0u8; self.ecdsa_size()?];
149 let mut signature_len = 0;
150 // SAFETY: This function only reads the given data within its bounds.
151 // The `EC_KEY` passed to this function has been initialized and checked non-null.
152 let ret = unsafe {
153 ECDSA_sign(
154 TYPE,
155 digest.as_ptr(),
156 digest.len(),
157 signature.as_mut_ptr(),
158 &mut signature_len,
159 self.0.as_ptr(),
160 )
161 };
162 check_int_result(ret, ApiName::ECDSA_sign)?;
163 if signature.len() < (signature_len as usize) {
164 Err(to_call_failed_error(ApiName::ECDSA_sign))
165 } else {
166 signature.truncate(signature_len as usize);
167 Ok(signature)
168 }
169 }
170
171 /// Returns the maximum size of an ECDSA signature using the current `EcKey`.
172 fn ecdsa_size(&self) -> Result<usize> {
173 // SAFETY: This function only reads the `EC_KEY` that has been initialized
174 // and checked non-null when this instance is created.
175 let size = unsafe { ECDSA_size(self.0.as_ptr()) };
176 if size == 0 {
177 Err(to_call_failed_error(ApiName::ECDSA_size))
178 } else {
179 Ok(size)
180 }
Alice Wang9bd98092023-11-10 14:08:12 +0000181 }
182
Alice Wang7b2ab942023-09-12 13:04:42 +0000183 /// Generates a random, private key, calculates the corresponding public key and stores both
184 /// in the `EC_KEY`.
Alice Wang9bd98092023-11-10 14:08:12 +0000185 pub fn generate_key(&mut self) -> Result<()> {
Alice Wang7b2ab942023-09-12 13:04:42 +0000186 // SAFETY: The non-null pointer is created with `EC_KEY_new_by_curve_name` and should
187 // point to a valid `EC_KEY`.
188 // The randomness is provided by `getentropy()` in `vmbase`.
189 let ret = unsafe { EC_KEY_generate_key(self.0.as_ptr()) };
Alice Wangc8f88f52023-09-25 14:02:17 +0000190 check_int_result(ret, ApiName::EC_KEY_generate_key)
Alice Wang7b2ab942023-09-12 13:04:42 +0000191 }
192
Alice Wanga78d3f02023-09-13 12:39:16 +0000193 /// Returns the `CoseKey` for the public key.
194 pub fn cose_public_key(&self) -> Result<CoseKey> {
Alice Wanga78d3f02023-09-13 12:39:16 +0000195 let (x, y) = self.public_key_coordinates()?;
Alice Wang9bd98092023-11-10 14:08:12 +0000196 let key = CoseKeyBuilder::new_ec2_pub_key(P256_CURVE, x.to_vec(), y.to_vec())
197 .algorithm(ES256_ALGO)
198 .build();
Alice Wanga78d3f02023-09-13 12:39:16 +0000199 Ok(key)
200 }
201
202 /// Returns the x and y coordinates of the public key.
203 fn public_key_coordinates(&self) -> Result<(Coordinate, Coordinate)> {
204 let ec_group = self.ec_group()?;
205 let ec_point = self.public_key_ec_point()?;
206 let mut x = BigNum::new()?;
207 let mut y = BigNum::new()?;
208 let ctx = ptr::null_mut();
209 // SAFETY: All the parameters are checked non-null and initialized when needed.
210 // The last parameter `ctx` is generated when needed inside the function.
211 let ret = unsafe {
212 EC_POINT_get_affine_coordinates(ec_group, ec_point, x.as_mut_ptr(), y.as_mut_ptr(), ctx)
213 };
Alice Wangc8f88f52023-09-25 14:02:17 +0000214 check_int_result(ret, ApiName::EC_POINT_get_affine_coordinates)?;
Alice Wanga78d3f02023-09-13 12:39:16 +0000215 Ok((x.try_into()?, y.try_into()?))
216 }
217
218 /// Returns a pointer to the public key point inside `EC_KEY`. The memory region pointed
219 /// by the pointer is owned by the `EC_KEY`.
220 fn public_key_ec_point(&self) -> Result<*const EC_POINT> {
221 let ec_point =
222 // SAFETY: It is safe since the key pair has been generated and stored in the
223 // `EC_KEY` pointer.
224 unsafe { EC_KEY_get0_public_key(self.0.as_ptr()) };
225 if ec_point.is_null() {
Alice Wang47287e72023-09-29 13:14:33 +0000226 Err(to_call_failed_error(ApiName::EC_KEY_get0_public_key))
Alice Wanga78d3f02023-09-13 12:39:16 +0000227 } else {
228 Ok(ec_point)
229 }
230 }
231
232 /// Returns a pointer to the `EC_GROUP` object inside `EC_KEY`. The memory region pointed
233 /// by the pointer is owned by the `EC_KEY`.
234 fn ec_group(&self) -> Result<*const EC_GROUP> {
235 let group =
236 // SAFETY: It is safe since the key pair has been generated and stored in the
237 // `EC_KEY` pointer.
238 unsafe { EC_KEY_get0_group(self.0.as_ptr()) };
239 if group.is_null() {
Alice Wang47287e72023-09-29 13:14:33 +0000240 Err(to_call_failed_error(ApiName::EC_KEY_get0_group))
Alice Wanga78d3f02023-09-13 12:39:16 +0000241 } else {
242 Ok(group)
243 }
244 }
Alice Wang7b2ab942023-09-12 13:04:42 +0000245
Alice Wang000595b2023-10-02 13:46:45 +0000246 /// Constructs an `EcKey` instance from the provided DER-encoded ECPrivateKey slice.
247 ///
248 /// Currently, only the EC P-256 curve is supported.
249 pub fn from_ec_private_key(der_encoded_ec_private_key: &[u8]) -> Result<Self> {
250 // SAFETY: This function only returns a pointer to a static object, and the
251 // return is checked below.
252 let ec_group = unsafe {
253 EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1) // EC P-256 CURVE Nid
254 };
255 if ec_group.is_null() {
256 return Err(to_call_failed_error(ApiName::EC_GROUP_new_by_curve_name));
257 }
258 let mut cbs = Cbs::new(der_encoded_ec_private_key);
259 // SAFETY: The function only reads bytes from the buffer managed by the valid `CBS`
260 // object, and the returned EC_KEY is checked.
261 let ec_key = unsafe { EC_KEY_parse_private_key(cbs.as_mut(), ec_group) };
262
263 let ec_key = NonNull::new(ec_key)
264 .map(Self)
265 .ok_or(to_call_failed_error(ApiName::EC_KEY_parse_private_key))?;
266 ec_key.check_key()?;
267 Ok(ec_key)
268 }
269
Alice Wang7b2ab942023-09-12 13:04:42 +0000270 /// Returns the DER-encoded ECPrivateKey structure described in RFC 5915 Section 3:
271 ///
272 /// https://datatracker.ietf.org/doc/html/rfc5915#section-3
Alice Wang000595b2023-10-02 13:46:45 +0000273 pub fn ec_private_key(&self) -> Result<ZVec> {
Alice Wang7b2ab942023-09-12 13:04:42 +0000274 const CAPACITY: usize = 256;
275 let mut buf = Zeroizing::new([0u8; CAPACITY]);
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100276 let mut cbb = CbbFixed::new(buf.as_mut());
Alice Wang7b2ab942023-09-12 13:04:42 +0000277 let enc_flags = 0;
278 let ret =
279 // SAFETY: The function only write bytes to the buffer managed by the valid `CBB`
280 // object, and the key has been allocated by BoringSSL.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100281 unsafe { EC_KEY_marshal_private_key(cbb.as_mut(), self.0.as_ptr(), enc_flags) };
Alice Wang7b2ab942023-09-12 13:04:42 +0000282
Alice Wangc8f88f52023-09-25 14:02:17 +0000283 check_int_result(ret, ApiName::EC_KEY_marshal_private_key)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000284 // SAFETY: This is safe because the CBB pointer is a valid pointer initialized with
285 // `CBB_init_fixed()`.
Alice Wangc8f88f52023-09-25 14:02:17 +0000286 check_int_result(unsafe { CBB_flush(cbb.as_mut()) }, ApiName::CBB_flush)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000287 // SAFETY: This is safe because the CBB pointer is initialized with `CBB_init_fixed()`,
288 // and it has been flushed, thus it has no active children.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100289 let len = unsafe { CBB_len(cbb.as_ref()) };
Alice Wang47287e72023-09-29 13:14:33 +0000290 Ok(buf.get(0..len).ok_or(to_call_failed_error(ApiName::CBB_len))?.to_vec().into())
Alice Wang7b2ab942023-09-12 13:04:42 +0000291 }
292}
293
Alice Wang9bd98092023-11-10 14:08:12 +0000294fn get_label_value_as_bytes(key: &CoseKey, label: Label) -> Result<&[u8]> {
295 Ok(get_label_value(key, label)?.as_bytes().ok_or_else(|| {
296 error!("Value not a bstr.");
297 Error::CoseKeyDecodingFailed
298 })?)
299}
300
301fn get_label_value(key: &CoseKey, label: Label) -> Result<&Value> {
302 Ok(&key.params.iter().find(|(k, _)| k == &label).ok_or(Error::CoseKeyDecodingFailed)?.1)
303}
304
305fn check_p256_affine_coordinate_size(coordinate: &[u8]) -> Result<()> {
306 if P256_AFFINE_COORDINATE_SIZE == coordinate.len() {
307 Ok(())
308 } else {
309 error!(
310 "The size of the affine coordinate '{}' does not match the expected size '{}'",
311 coordinate.len(),
312 P256_AFFINE_COORDINATE_SIZE
313 );
314 Err(Error::CoseKeyDecodingFailed)
315 }
316}
317
Alice Wang7b2ab942023-09-12 13:04:42 +0000318/// A u8 vector that is zeroed when dropped.
319#[derive(Zeroize, ZeroizeOnDrop)]
320pub struct ZVec(Vec<u8>);
321
322impl ZVec {
323 /// Extracts a slice containing the entire vector.
324 pub fn as_slice(&self) -> &[u8] {
325 &self.0[..]
326 }
327}
328
329impl From<Vec<u8>> for ZVec {
330 fn from(v: Vec<u8>) -> Self {
331 Self(v)
332 }
333}
334
Alice Wanga78d3f02023-09-13 12:39:16 +0000335struct BigNum(NonNull<BIGNUM>);
336
337impl Drop for BigNum {
338 fn drop(&mut self) {
339 // SAFETY: The pointer has been created with `BN_new`.
340 unsafe { BN_clear_free(self.as_mut_ptr()) }
341 }
342}
343
344impl BigNum {
Alice Wang9bd98092023-11-10 14:08:12 +0000345 fn from_slice(x: &[u8]) -> Result<Self> {
346 // SAFETY: The function reads `x` within its bounds, and the returned
347 // pointer is checked below.
348 let bn = unsafe { BN_bin2bn(x.as_ptr(), x.len(), ptr::null_mut()) };
349 NonNull::new(bn).map(Self).ok_or(to_call_failed_error(ApiName::BN_bin2bn))
350 }
351
Alice Wanga78d3f02023-09-13 12:39:16 +0000352 fn new() -> Result<Self> {
353 // SAFETY: The returned pointer is checked below.
354 let bn = unsafe { BN_new() };
Alice Wang47287e72023-09-29 13:14:33 +0000355 NonNull::new(bn).map(Self).ok_or(to_call_failed_error(ApiName::BN_new))
Alice Wanga78d3f02023-09-13 12:39:16 +0000356 }
357
358 fn as_mut_ptr(&mut self) -> *mut BIGNUM {
359 self.0.as_ptr()
360 }
361}
362
Alice Wang9bd98092023-11-10 14:08:12 +0000363impl AsRef<BIGNUM> for BigNum {
364 fn as_ref(&self) -> &BIGNUM {
365 // SAFETY: The pointer is valid and points to an initialized instance of `BIGNUM`
366 // when the instance was created.
367 unsafe { self.0.as_ref() }
368 }
369}
370
Alice Wanga78d3f02023-09-13 12:39:16 +0000371/// Converts the `BigNum` to a big-endian integer. The integer is padded with leading zeros up to
372/// size `N`. The conversion fails if `N` is smaller thanthe size of the integer.
373impl<const N: usize> TryFrom<BigNum> for [u8; N] {
Alice Wangc8f88f52023-09-25 14:02:17 +0000374 type Error = Error;
Alice Wanga78d3f02023-09-13 12:39:16 +0000375
376 fn try_from(bn: BigNum) -> result::Result<Self, Self::Error> {
377 let mut num = [0u8; N];
378 // SAFETY: The `BIGNUM` pointer has been created with `BN_new`.
379 let ret = unsafe { BN_bn2bin_padded(num.as_mut_ptr(), num.len(), bn.0.as_ptr()) };
Alice Wangc8f88f52023-09-25 14:02:17 +0000380 check_int_result(ret, ApiName::BN_bn2bin_padded)?;
Alice Wanga78d3f02023-09-13 12:39:16 +0000381 Ok(num)
382 }
383}
384
Alice Wang7b2ab942023-09-12 13:04:42 +0000385// TODO(b/301068421): Unit tests the EcKey.