blob: 572ad4bbaeca49436a6a8df6317f5f83f4109ae3 [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 Wang7b2ab942023-09-12 13:04:42 +000021use alloc::vec::Vec;
Alice Wangb3fcf632023-09-26 08:32:55 +000022use bssl_avf_error::{ApiName, Error, Result};
Alan Stokesb1f64ee2023-09-25 10:38:13 +010023use bssl_ffi::{
Alice Wang9bd98092023-11-10 14:08:12 +000024 BN_bin2bn, BN_bn2bin_padded, BN_clear_free, BN_new, CBB_flush, CBB_len,
25 EC_GROUP_new_by_curve_name, EC_KEY_check_key, EC_KEY_free, EC_KEY_generate_key,
26 EC_KEY_get0_group, EC_KEY_get0_public_key, EC_KEY_marshal_private_key,
27 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 +000028 EC_POINT_get_affine_coordinates, NID_X9_62_prime256v1, BIGNUM, EC_GROUP, EC_KEY, EC_POINT,
Alan Stokesb1f64ee2023-09-25 10:38:13 +010029};
Alice Wang9bd98092023-11-10 14:08:12 +000030use ciborium::Value;
Alice Wanga78d3f02023-09-13 12:39:16 +000031use core::ptr::{self, NonNull};
Alice Wang7b2ab942023-09-12 13:04:42 +000032use core::result;
Alice Wang9bd98092023-11-10 14:08:12 +000033use coset::{
34 iana::{self, EnumI64},
35 CborSerializable, CoseKey, CoseKeyBuilder, Label,
36};
37use log::error;
Alice Wang7b2ab942023-09-12 13:04:42 +000038use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
39
Alice Wang9bd98092023-11-10 14:08:12 +000040const ES256_ALGO: iana::Algorithm = iana::Algorithm::ES256;
41const P256_CURVE: iana::EllipticCurve = iana::EllipticCurve::P_256;
Alice Wanga78d3f02023-09-13 12:39:16 +000042const P256_AFFINE_COORDINATE_SIZE: usize = 32;
43
Alice Wanga78d3f02023-09-13 12:39:16 +000044type Coordinate = [u8; P256_AFFINE_COORDINATE_SIZE];
Alice Wang7b2ab942023-09-12 13:04:42 +000045
46/// Wrapper of an `EC_KEY` object, representing a public or private EC key.
47pub struct EcKey(NonNull<EC_KEY>);
48
49impl Drop for EcKey {
50 fn drop(&mut self) {
51 // SAFETY: It is safe because the key has been allocated by BoringSSL and isn't
52 // used after this.
53 unsafe { EC_KEY_free(self.0.as_ptr()) }
54 }
55}
56
57impl EcKey {
58 /// Creates a new EC P-256 key pair.
59 pub fn new_p256() -> Result<Self> {
60 // SAFETY: The returned pointer is checked below.
Alan Stokesb1f64ee2023-09-25 10:38:13 +010061 let ec_key = unsafe {
62 EC_KEY_new_by_curve_name(NID_X9_62_prime256v1) // EC P-256 CURVE Nid
63 };
Alice Wang9bd98092023-11-10 14:08:12 +000064 NonNull::new(ec_key)
Alice Wangc8f88f52023-09-25 14:02:17 +000065 .map(Self)
Alice Wang9bd98092023-11-10 14:08:12 +000066 .ok_or(to_call_failed_error(ApiName::EC_KEY_new_by_curve_name))
67 }
68
69 /// Constructs an `EcKey` instance from the provided COSE_Key encoded public key slice.
70 pub fn from_cose_public_key(cose_key: &[u8]) -> Result<Self> {
71 let cose_key = CoseKey::from_slice(cose_key).map_err(|e| {
72 error!("Failed to deserialize COSE_Key: {e:?}");
73 Error::CoseKeyDecodingFailed
74 })?;
75 if cose_key.alg != Some(coset::Algorithm::Assigned(ES256_ALGO)) {
76 error!(
77 "Only ES256 algorithm is supported. Algo type in the COSE Key: {:?}",
78 cose_key.alg
79 );
80 return Err(Error::Unimplemented);
81 }
82 let crv = get_label_value(&cose_key, Label::Int(iana::Ec2KeyParameter::Crv.to_i64()))?;
83 if &Value::from(P256_CURVE.to_i64()) != crv {
84 error!("Only EC P-256 curve is supported. Curve type in the COSE Key: {crv:?}");
85 return Err(Error::Unimplemented);
86 }
87
88 let x = get_label_value_as_bytes(&cose_key, Label::Int(iana::Ec2KeyParameter::X.to_i64()))?;
89 let y = get_label_value_as_bytes(&cose_key, Label::Int(iana::Ec2KeyParameter::Y.to_i64()))?;
90
91 check_p256_affine_coordinate_size(x)?;
92 check_p256_affine_coordinate_size(y)?;
93
94 let x = BigNum::from_slice(x)?;
95 let y = BigNum::from_slice(y)?;
96
97 let ec_key = EcKey::new_p256()?;
98 // SAFETY: All the parameters are checked non-null and initialized.
99 // The function only reads the coordinates x and y within their bounds.
100 let ret = unsafe {
101 EC_KEY_set_public_key_affine_coordinates(ec_key.0.as_ptr(), x.as_ref(), y.as_ref())
102 };
103 check_int_result(ret, ApiName::EC_KEY_set_public_key_affine_coordinates)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000104 Ok(ec_key)
105 }
106
Alice Wang000595b2023-10-02 13:46:45 +0000107 /// Performs several checks on the key. See BoringSSL doc for more details:
108 ///
109 /// https://commondatastorage.googleapis.com/chromium-boringssl-docs/ec_key.h.html#EC_KEY_check_key
110 pub fn check_key(&self) -> Result<()> {
111 // SAFETY: This function only reads the `EC_KEY` pointer, the non-null check is performed
112 // within the function.
113 let ret = unsafe { EC_KEY_check_key(self.0.as_ptr()) };
114 check_int_result(ret, ApiName::EC_KEY_check_key)
115 }
116
Alice Wang9bd98092023-11-10 14:08:12 +0000117 /// Verifies the DER-encoded ECDSA `signature` of the `message` with the current `EcKey`.
118 pub fn ecdsa_verify(&self, _signature: &[u8], _message: &[u8]) -> Result<()> {
119 // TODO(b/310634099): Implement ECDSA sign with `bssl::ECDSA_do_sign`.
120 Ok(())
121 }
122
123 /// Signs the `message` with the current `EcKey` using ECDSA.
124 ///
125 /// Returns the DER-encoded ECDSA signature.
126 pub fn ecdsa_sign(&self, _message: &[u8]) -> Result<Vec<u8>> {
127 // TODO(b/310634099): Implement ECDSA verify with `bssl::ECDSA_do_verify`.
128 Ok(Vec::new())
129 }
130
Alice Wang7b2ab942023-09-12 13:04:42 +0000131 /// Generates a random, private key, calculates the corresponding public key and stores both
132 /// in the `EC_KEY`.
Alice Wang9bd98092023-11-10 14:08:12 +0000133 pub fn generate_key(&mut self) -> Result<()> {
Alice Wang7b2ab942023-09-12 13:04:42 +0000134 // SAFETY: The non-null pointer is created with `EC_KEY_new_by_curve_name` and should
135 // point to a valid `EC_KEY`.
136 // The randomness is provided by `getentropy()` in `vmbase`.
137 let ret = unsafe { EC_KEY_generate_key(self.0.as_ptr()) };
Alice Wangc8f88f52023-09-25 14:02:17 +0000138 check_int_result(ret, ApiName::EC_KEY_generate_key)
Alice Wang7b2ab942023-09-12 13:04:42 +0000139 }
140
Alice Wanga78d3f02023-09-13 12:39:16 +0000141 /// Returns the `CoseKey` for the public key.
142 pub fn cose_public_key(&self) -> Result<CoseKey> {
Alice Wanga78d3f02023-09-13 12:39:16 +0000143 let (x, y) = self.public_key_coordinates()?;
Alice Wang9bd98092023-11-10 14:08:12 +0000144 let key = CoseKeyBuilder::new_ec2_pub_key(P256_CURVE, x.to_vec(), y.to_vec())
145 .algorithm(ES256_ALGO)
146 .build();
Alice Wanga78d3f02023-09-13 12:39:16 +0000147 Ok(key)
148 }
149
150 /// Returns the x and y coordinates of the public key.
151 fn public_key_coordinates(&self) -> Result<(Coordinate, Coordinate)> {
152 let ec_group = self.ec_group()?;
153 let ec_point = self.public_key_ec_point()?;
154 let mut x = BigNum::new()?;
155 let mut y = BigNum::new()?;
156 let ctx = ptr::null_mut();
157 // SAFETY: All the parameters are checked non-null and initialized when needed.
158 // The last parameter `ctx` is generated when needed inside the function.
159 let ret = unsafe {
160 EC_POINT_get_affine_coordinates(ec_group, ec_point, x.as_mut_ptr(), y.as_mut_ptr(), ctx)
161 };
Alice Wangc8f88f52023-09-25 14:02:17 +0000162 check_int_result(ret, ApiName::EC_POINT_get_affine_coordinates)?;
Alice Wanga78d3f02023-09-13 12:39:16 +0000163 Ok((x.try_into()?, y.try_into()?))
164 }
165
166 /// Returns a pointer to the public key point inside `EC_KEY`. The memory region pointed
167 /// by the pointer is owned by the `EC_KEY`.
168 fn public_key_ec_point(&self) -> Result<*const EC_POINT> {
169 let ec_point =
170 // SAFETY: It is safe since the key pair has been generated and stored in the
171 // `EC_KEY` pointer.
172 unsafe { EC_KEY_get0_public_key(self.0.as_ptr()) };
173 if ec_point.is_null() {
Alice Wang47287e72023-09-29 13:14:33 +0000174 Err(to_call_failed_error(ApiName::EC_KEY_get0_public_key))
Alice Wanga78d3f02023-09-13 12:39:16 +0000175 } else {
176 Ok(ec_point)
177 }
178 }
179
180 /// Returns a pointer to the `EC_GROUP` object inside `EC_KEY`. The memory region pointed
181 /// by the pointer is owned by the `EC_KEY`.
182 fn ec_group(&self) -> Result<*const EC_GROUP> {
183 let group =
184 // SAFETY: It is safe since the key pair has been generated and stored in the
185 // `EC_KEY` pointer.
186 unsafe { EC_KEY_get0_group(self.0.as_ptr()) };
187 if group.is_null() {
Alice Wang47287e72023-09-29 13:14:33 +0000188 Err(to_call_failed_error(ApiName::EC_KEY_get0_group))
Alice Wanga78d3f02023-09-13 12:39:16 +0000189 } else {
190 Ok(group)
191 }
192 }
Alice Wang7b2ab942023-09-12 13:04:42 +0000193
Alice Wang000595b2023-10-02 13:46:45 +0000194 /// Constructs an `EcKey` instance from the provided DER-encoded ECPrivateKey slice.
195 ///
196 /// Currently, only the EC P-256 curve is supported.
197 pub fn from_ec_private_key(der_encoded_ec_private_key: &[u8]) -> Result<Self> {
198 // SAFETY: This function only returns a pointer to a static object, and the
199 // return is checked below.
200 let ec_group = unsafe {
201 EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1) // EC P-256 CURVE Nid
202 };
203 if ec_group.is_null() {
204 return Err(to_call_failed_error(ApiName::EC_GROUP_new_by_curve_name));
205 }
206 let mut cbs = Cbs::new(der_encoded_ec_private_key);
207 // SAFETY: The function only reads bytes from the buffer managed by the valid `CBS`
208 // object, and the returned EC_KEY is checked.
209 let ec_key = unsafe { EC_KEY_parse_private_key(cbs.as_mut(), ec_group) };
210
211 let ec_key = NonNull::new(ec_key)
212 .map(Self)
213 .ok_or(to_call_failed_error(ApiName::EC_KEY_parse_private_key))?;
214 ec_key.check_key()?;
215 Ok(ec_key)
216 }
217
Alice Wang7b2ab942023-09-12 13:04:42 +0000218 /// Returns the DER-encoded ECPrivateKey structure described in RFC 5915 Section 3:
219 ///
220 /// https://datatracker.ietf.org/doc/html/rfc5915#section-3
Alice Wang000595b2023-10-02 13:46:45 +0000221 pub fn ec_private_key(&self) -> Result<ZVec> {
Alice Wang7b2ab942023-09-12 13:04:42 +0000222 const CAPACITY: usize = 256;
223 let mut buf = Zeroizing::new([0u8; CAPACITY]);
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100224 let mut cbb = CbbFixed::new(buf.as_mut());
Alice Wang7b2ab942023-09-12 13:04:42 +0000225 let enc_flags = 0;
226 let ret =
227 // SAFETY: The function only write bytes to the buffer managed by the valid `CBB`
228 // object, and the key has been allocated by BoringSSL.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100229 unsafe { EC_KEY_marshal_private_key(cbb.as_mut(), self.0.as_ptr(), enc_flags) };
Alice Wang7b2ab942023-09-12 13:04:42 +0000230
Alice Wangc8f88f52023-09-25 14:02:17 +0000231 check_int_result(ret, ApiName::EC_KEY_marshal_private_key)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000232 // SAFETY: This is safe because the CBB pointer is a valid pointer initialized with
233 // `CBB_init_fixed()`.
Alice Wangc8f88f52023-09-25 14:02:17 +0000234 check_int_result(unsafe { CBB_flush(cbb.as_mut()) }, ApiName::CBB_flush)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000235 // SAFETY: This is safe because the CBB pointer is initialized with `CBB_init_fixed()`,
236 // and it has been flushed, thus it has no active children.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100237 let len = unsafe { CBB_len(cbb.as_ref()) };
Alice Wang47287e72023-09-29 13:14:33 +0000238 Ok(buf.get(0..len).ok_or(to_call_failed_error(ApiName::CBB_len))?.to_vec().into())
Alice Wang7b2ab942023-09-12 13:04:42 +0000239 }
240}
241
Alice Wang9bd98092023-11-10 14:08:12 +0000242fn get_label_value_as_bytes(key: &CoseKey, label: Label) -> Result<&[u8]> {
243 Ok(get_label_value(key, label)?.as_bytes().ok_or_else(|| {
244 error!("Value not a bstr.");
245 Error::CoseKeyDecodingFailed
246 })?)
247}
248
249fn get_label_value(key: &CoseKey, label: Label) -> Result<&Value> {
250 Ok(&key.params.iter().find(|(k, _)| k == &label).ok_or(Error::CoseKeyDecodingFailed)?.1)
251}
252
253fn check_p256_affine_coordinate_size(coordinate: &[u8]) -> Result<()> {
254 if P256_AFFINE_COORDINATE_SIZE == coordinate.len() {
255 Ok(())
256 } else {
257 error!(
258 "The size of the affine coordinate '{}' does not match the expected size '{}'",
259 coordinate.len(),
260 P256_AFFINE_COORDINATE_SIZE
261 );
262 Err(Error::CoseKeyDecodingFailed)
263 }
264}
265
Alice Wang7b2ab942023-09-12 13:04:42 +0000266/// A u8 vector that is zeroed when dropped.
267#[derive(Zeroize, ZeroizeOnDrop)]
268pub struct ZVec(Vec<u8>);
269
270impl ZVec {
271 /// Extracts a slice containing the entire vector.
272 pub fn as_slice(&self) -> &[u8] {
273 &self.0[..]
274 }
275}
276
277impl From<Vec<u8>> for ZVec {
278 fn from(v: Vec<u8>) -> Self {
279 Self(v)
280 }
281}
282
Alice Wanga78d3f02023-09-13 12:39:16 +0000283struct BigNum(NonNull<BIGNUM>);
284
285impl Drop for BigNum {
286 fn drop(&mut self) {
287 // SAFETY: The pointer has been created with `BN_new`.
288 unsafe { BN_clear_free(self.as_mut_ptr()) }
289 }
290}
291
292impl BigNum {
Alice Wang9bd98092023-11-10 14:08:12 +0000293 fn from_slice(x: &[u8]) -> Result<Self> {
294 // SAFETY: The function reads `x` within its bounds, and the returned
295 // pointer is checked below.
296 let bn = unsafe { BN_bin2bn(x.as_ptr(), x.len(), ptr::null_mut()) };
297 NonNull::new(bn).map(Self).ok_or(to_call_failed_error(ApiName::BN_bin2bn))
298 }
299
Alice Wanga78d3f02023-09-13 12:39:16 +0000300 fn new() -> Result<Self> {
301 // SAFETY: The returned pointer is checked below.
302 let bn = unsafe { BN_new() };
Alice Wang47287e72023-09-29 13:14:33 +0000303 NonNull::new(bn).map(Self).ok_or(to_call_failed_error(ApiName::BN_new))
Alice Wanga78d3f02023-09-13 12:39:16 +0000304 }
305
306 fn as_mut_ptr(&mut self) -> *mut BIGNUM {
307 self.0.as_ptr()
308 }
309}
310
Alice Wang9bd98092023-11-10 14:08:12 +0000311impl AsRef<BIGNUM> for BigNum {
312 fn as_ref(&self) -> &BIGNUM {
313 // SAFETY: The pointer is valid and points to an initialized instance of `BIGNUM`
314 // when the instance was created.
315 unsafe { self.0.as_ref() }
316 }
317}
318
Alice Wanga78d3f02023-09-13 12:39:16 +0000319/// Converts the `BigNum` to a big-endian integer. The integer is padded with leading zeros up to
320/// size `N`. The conversion fails if `N` is smaller thanthe size of the integer.
321impl<const N: usize> TryFrom<BigNum> for [u8; N] {
Alice Wangc8f88f52023-09-25 14:02:17 +0000322 type Error = Error;
Alice Wanga78d3f02023-09-13 12:39:16 +0000323
324 fn try_from(bn: BigNum) -> result::Result<Self, Self::Error> {
325 let mut num = [0u8; N];
326 // SAFETY: The `BIGNUM` pointer has been created with `BN_new`.
327 let ret = unsafe { BN_bn2bin_padded(num.as_mut_ptr(), num.len(), bn.0.as_ptr()) };
Alice Wangc8f88f52023-09-25 14:02:17 +0000328 check_int_result(ret, ApiName::BN_bn2bin_padded)?;
Alice Wanga78d3f02023-09-13 12:39:16 +0000329 Ok(num)
330 }
331}
332
Alice Wang7b2ab942023-09-12 13:04:42 +0000333// TODO(b/301068421): Unit tests the EcKey.