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