blob: 45785263e3434722e103e25dd2f3dd6e3b147199 [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
Alan Stokesb1f64ee2023-09-25 10:38:13 +010018use super::cbb::CbbFixed;
Alice Wang7b2ab942023-09-12 13:04:42 +000019use alloc::vec::Vec;
Alan Stokesb1f64ee2023-09-25 10:38:13 +010020use bssl_ffi::{
21 BN_bn2bin_padded, BN_clear_free, BN_new, CBB_flush, CBB_len, EC_KEY_free, EC_KEY_generate_key,
22 EC_KEY_get0_group, EC_KEY_get0_public_key, EC_KEY_marshal_private_key,
23 EC_KEY_new_by_curve_name, EC_POINT_get_affine_coordinates, NID_X9_62_prime256v1, BIGNUM,
24 EC_GROUP, EC_KEY, EC_POINT,
25};
Alice Wanga78d3f02023-09-13 12:39:16 +000026use core::ptr::{self, NonNull};
Alice Wang7b2ab942023-09-12 13:04:42 +000027use core::result;
Alice Wanga78d3f02023-09-13 12:39:16 +000028use coset::{iana, CoseKey, CoseKeyBuilder};
Alice Wang7b2ab942023-09-12 13:04:42 +000029use service_vm_comm::{BoringSSLApiName, RequestProcessingError};
30use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
31
Alice Wanga78d3f02023-09-13 12:39:16 +000032const P256_AFFINE_COORDINATE_SIZE: usize = 32;
33
Alice Wang7b2ab942023-09-12 13:04:42 +000034type Result<T> = result::Result<T, RequestProcessingError>;
Alice Wanga78d3f02023-09-13 12:39:16 +000035type Coordinate = [u8; P256_AFFINE_COORDINATE_SIZE];
Alice Wang7b2ab942023-09-12 13:04:42 +000036
37/// Wrapper of an `EC_KEY` object, representing a public or private EC key.
38pub struct EcKey(NonNull<EC_KEY>);
39
40impl Drop for EcKey {
41 fn drop(&mut self) {
42 // SAFETY: It is safe because the key has been allocated by BoringSSL and isn't
43 // used after this.
44 unsafe { EC_KEY_free(self.0.as_ptr()) }
45 }
46}
47
48impl EcKey {
49 /// Creates a new EC P-256 key pair.
50 pub fn new_p256() -> Result<Self> {
51 // SAFETY: The returned pointer is checked below.
Alan Stokesb1f64ee2023-09-25 10:38:13 +010052 let ec_key = unsafe {
53 EC_KEY_new_by_curve_name(NID_X9_62_prime256v1) // EC P-256 CURVE Nid
54 };
Alice Wang7b2ab942023-09-12 13:04:42 +000055 let mut ec_key = NonNull::new(ec_key).map(Self).ok_or(
56 RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::EC_KEY_new_by_curve_name),
57 )?;
58 ec_key.generate_key()?;
59 Ok(ec_key)
60 }
61
62 /// Generates a random, private key, calculates the corresponding public key and stores both
63 /// in the `EC_KEY`.
64 fn generate_key(&mut self) -> Result<()> {
65 // SAFETY: The non-null pointer is created with `EC_KEY_new_by_curve_name` and should
66 // point to a valid `EC_KEY`.
67 // The randomness is provided by `getentropy()` in `vmbase`.
68 let ret = unsafe { EC_KEY_generate_key(self.0.as_ptr()) };
69 check_int_result(ret, BoringSSLApiName::EC_KEY_generate_key)
70 }
71
Alice Wanga78d3f02023-09-13 12:39:16 +000072 /// Returns the `CoseKey` for the public key.
73 pub fn cose_public_key(&self) -> Result<CoseKey> {
74 const ALGO: iana::Algorithm = iana::Algorithm::ES256;
75 const CURVE: iana::EllipticCurve = iana::EllipticCurve::P_256;
76
77 let (x, y) = self.public_key_coordinates()?;
78 let key =
79 CoseKeyBuilder::new_ec2_pub_key(CURVE, x.to_vec(), y.to_vec()).algorithm(ALGO).build();
80 Ok(key)
81 }
82
83 /// Returns the x and y coordinates of the public key.
84 fn public_key_coordinates(&self) -> Result<(Coordinate, Coordinate)> {
85 let ec_group = self.ec_group()?;
86 let ec_point = self.public_key_ec_point()?;
87 let mut x = BigNum::new()?;
88 let mut y = BigNum::new()?;
89 let ctx = ptr::null_mut();
90 // SAFETY: All the parameters are checked non-null and initialized when needed.
91 // The last parameter `ctx` is generated when needed inside the function.
92 let ret = unsafe {
93 EC_POINT_get_affine_coordinates(ec_group, ec_point, x.as_mut_ptr(), y.as_mut_ptr(), ctx)
94 };
95 check_int_result(ret, BoringSSLApiName::EC_POINT_get_affine_coordinates)?;
96 Ok((x.try_into()?, y.try_into()?))
97 }
98
99 /// Returns a pointer to the public key point inside `EC_KEY`. The memory region pointed
100 /// by the pointer is owned by the `EC_KEY`.
101 fn public_key_ec_point(&self) -> Result<*const EC_POINT> {
102 let ec_point =
103 // SAFETY: It is safe since the key pair has been generated and stored in the
104 // `EC_KEY` pointer.
105 unsafe { EC_KEY_get0_public_key(self.0.as_ptr()) };
106 if ec_point.is_null() {
107 Err(RequestProcessingError::BoringSSLCallFailed(
108 BoringSSLApiName::EC_KEY_get0_public_key,
109 ))
110 } else {
111 Ok(ec_point)
112 }
113 }
114
115 /// Returns a pointer to the `EC_GROUP` object inside `EC_KEY`. The memory region pointed
116 /// by the pointer is owned by the `EC_KEY`.
117 fn ec_group(&self) -> Result<*const EC_GROUP> {
118 let group =
119 // SAFETY: It is safe since the key pair has been generated and stored in the
120 // `EC_KEY` pointer.
121 unsafe { EC_KEY_get0_group(self.0.as_ptr()) };
122 if group.is_null() {
123 Err(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::EC_KEY_get0_group))
124 } else {
125 Ok(group)
126 }
127 }
Alice Wang7b2ab942023-09-12 13:04:42 +0000128
129 /// Returns the DER-encoded ECPrivateKey structure described in RFC 5915 Section 3:
130 ///
131 /// https://datatracker.ietf.org/doc/html/rfc5915#section-3
132 pub fn private_key(&self) -> Result<ZVec> {
133 const CAPACITY: usize = 256;
134 let mut buf = Zeroizing::new([0u8; CAPACITY]);
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100135 let mut cbb = CbbFixed::new(buf.as_mut());
Alice Wang7b2ab942023-09-12 13:04:42 +0000136 let enc_flags = 0;
137 let ret =
138 // SAFETY: The function only write bytes to the buffer managed by the valid `CBB`
139 // object, and the key has been allocated by BoringSSL.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100140 unsafe { EC_KEY_marshal_private_key(cbb.as_mut(), self.0.as_ptr(), enc_flags) };
Alice Wang7b2ab942023-09-12 13:04:42 +0000141
142 check_int_result(ret, BoringSSLApiName::EC_KEY_marshal_private_key)?;
143 // SAFETY: This is safe because the CBB pointer is a valid pointer initialized with
144 // `CBB_init_fixed()`.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100145 check_int_result(unsafe { CBB_flush(cbb.as_mut()) }, BoringSSLApiName::CBB_flush)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000146 // SAFETY: This is safe because the CBB pointer is initialized with `CBB_init_fixed()`,
147 // and it has been flushed, thus it has no active children.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100148 let len = unsafe { CBB_len(cbb.as_ref()) };
Alice Wang7b2ab942023-09-12 13:04:42 +0000149 Ok(buf
150 .get(0..len)
151 .ok_or(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::CBB_len))?
152 .to_vec()
153 .into())
154 }
155}
156
157/// A u8 vector that is zeroed when dropped.
158#[derive(Zeroize, ZeroizeOnDrop)]
159pub struct ZVec(Vec<u8>);
160
161impl ZVec {
162 /// Extracts a slice containing the entire vector.
163 pub fn as_slice(&self) -> &[u8] {
164 &self.0[..]
165 }
166}
167
168impl From<Vec<u8>> for ZVec {
169 fn from(v: Vec<u8>) -> Self {
170 Self(v)
171 }
172}
173
Alice Wanga78d3f02023-09-13 12:39:16 +0000174struct BigNum(NonNull<BIGNUM>);
175
176impl Drop for BigNum {
177 fn drop(&mut self) {
178 // SAFETY: The pointer has been created with `BN_new`.
179 unsafe { BN_clear_free(self.as_mut_ptr()) }
180 }
181}
182
183impl BigNum {
184 fn new() -> Result<Self> {
185 // SAFETY: The returned pointer is checked below.
186 let bn = unsafe { BN_new() };
187 NonNull::new(bn)
188 .map(Self)
189 .ok_or(RequestProcessingError::BoringSSLCallFailed(BoringSSLApiName::BN_new))
190 }
191
192 fn as_mut_ptr(&mut self) -> *mut BIGNUM {
193 self.0.as_ptr()
194 }
195}
196
197/// Converts the `BigNum` to a big-endian integer. The integer is padded with leading zeros up to
198/// size `N`. The conversion fails if `N` is smaller thanthe size of the integer.
199impl<const N: usize> TryFrom<BigNum> for [u8; N] {
200 type Error = RequestProcessingError;
201
202 fn try_from(bn: BigNum) -> result::Result<Self, Self::Error> {
203 let mut num = [0u8; N];
204 // SAFETY: The `BIGNUM` pointer has been created with `BN_new`.
205 let ret = unsafe { BN_bn2bin_padded(num.as_mut_ptr(), num.len(), bn.0.as_ptr()) };
206 check_int_result(ret, BoringSSLApiName::BN_bn2bin_padded)?;
207 Ok(num)
208 }
209}
210
Alice Wang7b2ab942023-09-12 13:04:42 +0000211fn check_int_result(ret: i32, api_name: BoringSSLApiName) -> Result<()> {
212 if ret == 1 {
213 Ok(())
214 } else {
215 assert_eq!(ret, 0, "Unexpected return value {ret} for {api_name:?}");
216 Err(RequestProcessingError::BoringSSLCallFailed(api_name))
217 }
218}
219
220// TODO(b/301068421): Unit tests the EcKey.