blob: fa9602306667cbbdea789791140fc43c2a23a748 [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 Wangc8f88f52023-09-25 14:02:17 +000019use bssl_avf::{ApiName, CbbFixed, Error, Result};
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 zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
30
Alice Wanga78d3f02023-09-13 12:39:16 +000031const P256_AFFINE_COORDINATE_SIZE: usize = 32;
32
Alice Wanga78d3f02023-09-13 12:39:16 +000033type Coordinate = [u8; P256_AFFINE_COORDINATE_SIZE];
Alice Wang7b2ab942023-09-12 13:04:42 +000034
35/// Wrapper of an `EC_KEY` object, representing a public or private EC key.
36pub struct EcKey(NonNull<EC_KEY>);
37
38impl Drop for EcKey {
39 fn drop(&mut self) {
40 // SAFETY: It is safe because the key has been allocated by BoringSSL and isn't
41 // used after this.
42 unsafe { EC_KEY_free(self.0.as_ptr()) }
43 }
44}
45
46impl EcKey {
47 /// Creates a new EC P-256 key pair.
48 pub fn new_p256() -> Result<Self> {
49 // SAFETY: The returned pointer is checked below.
Alan Stokesb1f64ee2023-09-25 10:38:13 +010050 let ec_key = unsafe {
51 EC_KEY_new_by_curve_name(NID_X9_62_prime256v1) // EC P-256 CURVE Nid
52 };
Alice Wangc8f88f52023-09-25 14:02:17 +000053 let mut ec_key = NonNull::new(ec_key)
54 .map(Self)
55 .ok_or(Error::CallFailed(ApiName::EC_KEY_new_by_curve_name))?;
Alice Wang7b2ab942023-09-12 13:04:42 +000056 ec_key.generate_key()?;
57 Ok(ec_key)
58 }
59
60 /// Generates a random, private key, calculates the corresponding public key and stores both
61 /// in the `EC_KEY`.
62 fn generate_key(&mut self) -> Result<()> {
63 // SAFETY: The non-null pointer is created with `EC_KEY_new_by_curve_name` and should
64 // point to a valid `EC_KEY`.
65 // The randomness is provided by `getentropy()` in `vmbase`.
66 let ret = unsafe { EC_KEY_generate_key(self.0.as_ptr()) };
Alice Wangc8f88f52023-09-25 14:02:17 +000067 check_int_result(ret, ApiName::EC_KEY_generate_key)
Alice Wang7b2ab942023-09-12 13:04:42 +000068 }
69
Alice Wanga78d3f02023-09-13 12:39:16 +000070 /// Returns the `CoseKey` for the public key.
71 pub fn cose_public_key(&self) -> Result<CoseKey> {
72 const ALGO: iana::Algorithm = iana::Algorithm::ES256;
73 const CURVE: iana::EllipticCurve = iana::EllipticCurve::P_256;
74
75 let (x, y) = self.public_key_coordinates()?;
76 let key =
77 CoseKeyBuilder::new_ec2_pub_key(CURVE, x.to_vec(), y.to_vec()).algorithm(ALGO).build();
78 Ok(key)
79 }
80
81 /// Returns the x and y coordinates of the public key.
82 fn public_key_coordinates(&self) -> Result<(Coordinate, Coordinate)> {
83 let ec_group = self.ec_group()?;
84 let ec_point = self.public_key_ec_point()?;
85 let mut x = BigNum::new()?;
86 let mut y = BigNum::new()?;
87 let ctx = ptr::null_mut();
88 // SAFETY: All the parameters are checked non-null and initialized when needed.
89 // The last parameter `ctx` is generated when needed inside the function.
90 let ret = unsafe {
91 EC_POINT_get_affine_coordinates(ec_group, ec_point, x.as_mut_ptr(), y.as_mut_ptr(), ctx)
92 };
Alice Wangc8f88f52023-09-25 14:02:17 +000093 check_int_result(ret, ApiName::EC_POINT_get_affine_coordinates)?;
Alice Wanga78d3f02023-09-13 12:39:16 +000094 Ok((x.try_into()?, y.try_into()?))
95 }
96
97 /// Returns a pointer to the public key point inside `EC_KEY`. The memory region pointed
98 /// by the pointer is owned by the `EC_KEY`.
99 fn public_key_ec_point(&self) -> Result<*const EC_POINT> {
100 let ec_point =
101 // SAFETY: It is safe since the key pair has been generated and stored in the
102 // `EC_KEY` pointer.
103 unsafe { EC_KEY_get0_public_key(self.0.as_ptr()) };
104 if ec_point.is_null() {
Alice Wangc8f88f52023-09-25 14:02:17 +0000105 Err(Error::CallFailed(ApiName::EC_KEY_get0_public_key))
Alice Wanga78d3f02023-09-13 12:39:16 +0000106 } else {
107 Ok(ec_point)
108 }
109 }
110
111 /// Returns a pointer to the `EC_GROUP` object inside `EC_KEY`. The memory region pointed
112 /// by the pointer is owned by the `EC_KEY`.
113 fn ec_group(&self) -> Result<*const EC_GROUP> {
114 let group =
115 // SAFETY: It is safe since the key pair has been generated and stored in the
116 // `EC_KEY` pointer.
117 unsafe { EC_KEY_get0_group(self.0.as_ptr()) };
118 if group.is_null() {
Alice Wangc8f88f52023-09-25 14:02:17 +0000119 Err(Error::CallFailed(ApiName::EC_KEY_get0_group))
Alice Wanga78d3f02023-09-13 12:39:16 +0000120 } else {
121 Ok(group)
122 }
123 }
Alice Wang7b2ab942023-09-12 13:04:42 +0000124
125 /// Returns the DER-encoded ECPrivateKey structure described in RFC 5915 Section 3:
126 ///
127 /// https://datatracker.ietf.org/doc/html/rfc5915#section-3
128 pub fn private_key(&self) -> Result<ZVec> {
129 const CAPACITY: usize = 256;
130 let mut buf = Zeroizing::new([0u8; CAPACITY]);
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100131 let mut cbb = CbbFixed::new(buf.as_mut());
Alice Wang7b2ab942023-09-12 13:04:42 +0000132 let enc_flags = 0;
133 let ret =
134 // SAFETY: The function only write bytes to the buffer managed by the valid `CBB`
135 // object, and the key has been allocated by BoringSSL.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100136 unsafe { EC_KEY_marshal_private_key(cbb.as_mut(), self.0.as_ptr(), enc_flags) };
Alice Wang7b2ab942023-09-12 13:04:42 +0000137
Alice Wangc8f88f52023-09-25 14:02:17 +0000138 check_int_result(ret, ApiName::EC_KEY_marshal_private_key)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000139 // SAFETY: This is safe because the CBB pointer is a valid pointer initialized with
140 // `CBB_init_fixed()`.
Alice Wangc8f88f52023-09-25 14:02:17 +0000141 check_int_result(unsafe { CBB_flush(cbb.as_mut()) }, ApiName::CBB_flush)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000142 // SAFETY: This is safe because the CBB pointer is initialized with `CBB_init_fixed()`,
143 // and it has been flushed, thus it has no active children.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100144 let len = unsafe { CBB_len(cbb.as_ref()) };
Alice Wangc8f88f52023-09-25 14:02:17 +0000145 Ok(buf.get(0..len).ok_or(Error::CallFailed(ApiName::CBB_len))?.to_vec().into())
Alice Wang7b2ab942023-09-12 13:04:42 +0000146 }
147}
148
149/// A u8 vector that is zeroed when dropped.
150#[derive(Zeroize, ZeroizeOnDrop)]
151pub struct ZVec(Vec<u8>);
152
153impl ZVec {
154 /// Extracts a slice containing the entire vector.
155 pub fn as_slice(&self) -> &[u8] {
156 &self.0[..]
157 }
158}
159
160impl From<Vec<u8>> for ZVec {
161 fn from(v: Vec<u8>) -> Self {
162 Self(v)
163 }
164}
165
Alice Wanga78d3f02023-09-13 12:39:16 +0000166struct BigNum(NonNull<BIGNUM>);
167
168impl Drop for BigNum {
169 fn drop(&mut self) {
170 // SAFETY: The pointer has been created with `BN_new`.
171 unsafe { BN_clear_free(self.as_mut_ptr()) }
172 }
173}
174
175impl BigNum {
176 fn new() -> Result<Self> {
177 // SAFETY: The returned pointer is checked below.
178 let bn = unsafe { BN_new() };
Alice Wangc8f88f52023-09-25 14:02:17 +0000179 NonNull::new(bn).map(Self).ok_or(Error::CallFailed(ApiName::BN_new))
Alice Wanga78d3f02023-09-13 12:39:16 +0000180 }
181
182 fn as_mut_ptr(&mut self) -> *mut BIGNUM {
183 self.0.as_ptr()
184 }
185}
186
187/// Converts the `BigNum` to a big-endian integer. The integer is padded with leading zeros up to
188/// size `N`. The conversion fails if `N` is smaller thanthe size of the integer.
189impl<const N: usize> TryFrom<BigNum> for [u8; N] {
Alice Wangc8f88f52023-09-25 14:02:17 +0000190 type Error = Error;
Alice Wanga78d3f02023-09-13 12:39:16 +0000191
192 fn try_from(bn: BigNum) -> result::Result<Self, Self::Error> {
193 let mut num = [0u8; N];
194 // SAFETY: The `BIGNUM` pointer has been created with `BN_new`.
195 let ret = unsafe { BN_bn2bin_padded(num.as_mut_ptr(), num.len(), bn.0.as_ptr()) };
Alice Wangc8f88f52023-09-25 14:02:17 +0000196 check_int_result(ret, ApiName::BN_bn2bin_padded)?;
Alice Wanga78d3f02023-09-13 12:39:16 +0000197 Ok(num)
198 }
199}
200
Alice Wangc8f88f52023-09-25 14:02:17 +0000201fn check_int_result(ret: i32, api_name: ApiName) -> Result<()> {
Alice Wang7b2ab942023-09-12 13:04:42 +0000202 if ret == 1 {
203 Ok(())
204 } else {
205 assert_eq!(ret, 0, "Unexpected return value {ret} for {api_name:?}");
Alice Wangc8f88f52023-09-25 14:02:17 +0000206 Err(Error::CallFailed(api_name))
Alice Wang7b2ab942023-09-12 13:04:42 +0000207 }
208}
209
210// TODO(b/301068421): Unit tests the EcKey.