blob: 4c1ba5ca5c67d154cc55646f60503e3a40e868a7 [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 Wang000595b2023-10-02 13:46:45 +000024 BN_bn2bin_padded, BN_clear_free, BN_new, CBB_flush, CBB_len, EC_GROUP_new_by_curve_name,
25 EC_KEY_check_key, EC_KEY_free, EC_KEY_generate_key, EC_KEY_get0_group, EC_KEY_get0_public_key,
26 EC_KEY_marshal_private_key, EC_KEY_new_by_curve_name, EC_KEY_parse_private_key,
27 EC_POINT_get_affine_coordinates, NID_X9_62_prime256v1, BIGNUM, EC_GROUP, EC_KEY, EC_POINT,
Alan Stokesb1f64ee2023-09-25 10:38:13 +010028};
Alice Wanga78d3f02023-09-13 12:39:16 +000029use core::ptr::{self, NonNull};
Alice Wang7b2ab942023-09-12 13:04:42 +000030use core::result;
Alice Wanga78d3f02023-09-13 12:39:16 +000031use coset::{iana, CoseKey, CoseKeyBuilder};
Alice Wang7b2ab942023-09-12 13:04:42 +000032use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
33
Alice Wanga78d3f02023-09-13 12:39:16 +000034const P256_AFFINE_COORDINATE_SIZE: usize = 32;
35
Alice Wanga78d3f02023-09-13 12:39:16 +000036type Coordinate = [u8; P256_AFFINE_COORDINATE_SIZE];
Alice Wang7b2ab942023-09-12 13:04:42 +000037
38/// Wrapper of an `EC_KEY` object, representing a public or private EC key.
39pub struct EcKey(NonNull<EC_KEY>);
40
41impl Drop for EcKey {
42 fn drop(&mut self) {
43 // SAFETY: It is safe because the key has been allocated by BoringSSL and isn't
44 // used after this.
45 unsafe { EC_KEY_free(self.0.as_ptr()) }
46 }
47}
48
49impl EcKey {
50 /// Creates a new EC P-256 key pair.
51 pub fn new_p256() -> Result<Self> {
52 // SAFETY: The returned pointer is checked below.
Alan Stokesb1f64ee2023-09-25 10:38:13 +010053 let ec_key = unsafe {
54 EC_KEY_new_by_curve_name(NID_X9_62_prime256v1) // EC P-256 CURVE Nid
55 };
Alice Wangc8f88f52023-09-25 14:02:17 +000056 let mut ec_key = NonNull::new(ec_key)
57 .map(Self)
Alice Wang47287e72023-09-29 13:14:33 +000058 .ok_or(to_call_failed_error(ApiName::EC_KEY_new_by_curve_name))?;
Alice Wang7b2ab942023-09-12 13:04:42 +000059 ec_key.generate_key()?;
60 Ok(ec_key)
61 }
62
Alice Wang000595b2023-10-02 13:46:45 +000063 /// Performs several checks on the key. See BoringSSL doc for more details:
64 ///
65 /// https://commondatastorage.googleapis.com/chromium-boringssl-docs/ec_key.h.html#EC_KEY_check_key
66 pub fn check_key(&self) -> Result<()> {
67 // SAFETY: This function only reads the `EC_KEY` pointer, the non-null check is performed
68 // within the function.
69 let ret = unsafe { EC_KEY_check_key(self.0.as_ptr()) };
70 check_int_result(ret, ApiName::EC_KEY_check_key)
71 }
72
Alice Wang7b2ab942023-09-12 13:04:42 +000073 /// Generates a random, private key, calculates the corresponding public key and stores both
74 /// in the `EC_KEY`.
75 fn generate_key(&mut self) -> Result<()> {
76 // SAFETY: The non-null pointer is created with `EC_KEY_new_by_curve_name` and should
77 // point to a valid `EC_KEY`.
78 // The randomness is provided by `getentropy()` in `vmbase`.
79 let ret = unsafe { EC_KEY_generate_key(self.0.as_ptr()) };
Alice Wangc8f88f52023-09-25 14:02:17 +000080 check_int_result(ret, ApiName::EC_KEY_generate_key)
Alice Wang7b2ab942023-09-12 13:04:42 +000081 }
82
Alice Wanga78d3f02023-09-13 12:39:16 +000083 /// Returns the `CoseKey` for the public key.
84 pub fn cose_public_key(&self) -> Result<CoseKey> {
85 const ALGO: iana::Algorithm = iana::Algorithm::ES256;
86 const CURVE: iana::EllipticCurve = iana::EllipticCurve::P_256;
87
88 let (x, y) = self.public_key_coordinates()?;
89 let key =
90 CoseKeyBuilder::new_ec2_pub_key(CURVE, x.to_vec(), y.to_vec()).algorithm(ALGO).build();
91 Ok(key)
92 }
93
94 /// Returns the x and y coordinates of the public key.
95 fn public_key_coordinates(&self) -> Result<(Coordinate, Coordinate)> {
96 let ec_group = self.ec_group()?;
97 let ec_point = self.public_key_ec_point()?;
98 let mut x = BigNum::new()?;
99 let mut y = BigNum::new()?;
100 let ctx = ptr::null_mut();
101 // SAFETY: All the parameters are checked non-null and initialized when needed.
102 // The last parameter `ctx` is generated when needed inside the function.
103 let ret = unsafe {
104 EC_POINT_get_affine_coordinates(ec_group, ec_point, x.as_mut_ptr(), y.as_mut_ptr(), ctx)
105 };
Alice Wangc8f88f52023-09-25 14:02:17 +0000106 check_int_result(ret, ApiName::EC_POINT_get_affine_coordinates)?;
Alice Wanga78d3f02023-09-13 12:39:16 +0000107 Ok((x.try_into()?, y.try_into()?))
108 }
109
110 /// Returns a pointer to the public key point inside `EC_KEY`. The memory region pointed
111 /// by the pointer is owned by the `EC_KEY`.
112 fn public_key_ec_point(&self) -> Result<*const EC_POINT> {
113 let ec_point =
114 // SAFETY: It is safe since the key pair has been generated and stored in the
115 // `EC_KEY` pointer.
116 unsafe { EC_KEY_get0_public_key(self.0.as_ptr()) };
117 if ec_point.is_null() {
Alice Wang47287e72023-09-29 13:14:33 +0000118 Err(to_call_failed_error(ApiName::EC_KEY_get0_public_key))
Alice Wanga78d3f02023-09-13 12:39:16 +0000119 } else {
120 Ok(ec_point)
121 }
122 }
123
124 /// Returns a pointer to the `EC_GROUP` object inside `EC_KEY`. The memory region pointed
125 /// by the pointer is owned by the `EC_KEY`.
126 fn ec_group(&self) -> Result<*const EC_GROUP> {
127 let group =
128 // SAFETY: It is safe since the key pair has been generated and stored in the
129 // `EC_KEY` pointer.
130 unsafe { EC_KEY_get0_group(self.0.as_ptr()) };
131 if group.is_null() {
Alice Wang47287e72023-09-29 13:14:33 +0000132 Err(to_call_failed_error(ApiName::EC_KEY_get0_group))
Alice Wanga78d3f02023-09-13 12:39:16 +0000133 } else {
134 Ok(group)
135 }
136 }
Alice Wang7b2ab942023-09-12 13:04:42 +0000137
Alice Wang000595b2023-10-02 13:46:45 +0000138 /// Constructs an `EcKey` instance from the provided DER-encoded ECPrivateKey slice.
139 ///
140 /// Currently, only the EC P-256 curve is supported.
141 pub fn from_ec_private_key(der_encoded_ec_private_key: &[u8]) -> Result<Self> {
142 // SAFETY: This function only returns a pointer to a static object, and the
143 // return is checked below.
144 let ec_group = unsafe {
145 EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1) // EC P-256 CURVE Nid
146 };
147 if ec_group.is_null() {
148 return Err(to_call_failed_error(ApiName::EC_GROUP_new_by_curve_name));
149 }
150 let mut cbs = Cbs::new(der_encoded_ec_private_key);
151 // SAFETY: The function only reads bytes from the buffer managed by the valid `CBS`
152 // object, and the returned EC_KEY is checked.
153 let ec_key = unsafe { EC_KEY_parse_private_key(cbs.as_mut(), ec_group) };
154
155 let ec_key = NonNull::new(ec_key)
156 .map(Self)
157 .ok_or(to_call_failed_error(ApiName::EC_KEY_parse_private_key))?;
158 ec_key.check_key()?;
159 Ok(ec_key)
160 }
161
Alice Wang7b2ab942023-09-12 13:04:42 +0000162 /// Returns the DER-encoded ECPrivateKey structure described in RFC 5915 Section 3:
163 ///
164 /// https://datatracker.ietf.org/doc/html/rfc5915#section-3
Alice Wang000595b2023-10-02 13:46:45 +0000165 pub fn ec_private_key(&self) -> Result<ZVec> {
Alice Wang7b2ab942023-09-12 13:04:42 +0000166 const CAPACITY: usize = 256;
167 let mut buf = Zeroizing::new([0u8; CAPACITY]);
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100168 let mut cbb = CbbFixed::new(buf.as_mut());
Alice Wang7b2ab942023-09-12 13:04:42 +0000169 let enc_flags = 0;
170 let ret =
171 // SAFETY: The function only write bytes to the buffer managed by the valid `CBB`
172 // object, and the key has been allocated by BoringSSL.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100173 unsafe { EC_KEY_marshal_private_key(cbb.as_mut(), self.0.as_ptr(), enc_flags) };
Alice Wang7b2ab942023-09-12 13:04:42 +0000174
Alice Wangc8f88f52023-09-25 14:02:17 +0000175 check_int_result(ret, ApiName::EC_KEY_marshal_private_key)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000176 // SAFETY: This is safe because the CBB pointer is a valid pointer initialized with
177 // `CBB_init_fixed()`.
Alice Wangc8f88f52023-09-25 14:02:17 +0000178 check_int_result(unsafe { CBB_flush(cbb.as_mut()) }, ApiName::CBB_flush)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000179 // SAFETY: This is safe because the CBB pointer is initialized with `CBB_init_fixed()`,
180 // and it has been flushed, thus it has no active children.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100181 let len = unsafe { CBB_len(cbb.as_ref()) };
Alice Wang47287e72023-09-29 13:14:33 +0000182 Ok(buf.get(0..len).ok_or(to_call_failed_error(ApiName::CBB_len))?.to_vec().into())
Alice Wang7b2ab942023-09-12 13:04:42 +0000183 }
184}
185
186/// A u8 vector that is zeroed when dropped.
187#[derive(Zeroize, ZeroizeOnDrop)]
188pub struct ZVec(Vec<u8>);
189
190impl ZVec {
191 /// Extracts a slice containing the entire vector.
192 pub fn as_slice(&self) -> &[u8] {
193 &self.0[..]
194 }
195}
196
197impl From<Vec<u8>> for ZVec {
198 fn from(v: Vec<u8>) -> Self {
199 Self(v)
200 }
201}
202
Alice Wanga78d3f02023-09-13 12:39:16 +0000203struct BigNum(NonNull<BIGNUM>);
204
205impl Drop for BigNum {
206 fn drop(&mut self) {
207 // SAFETY: The pointer has been created with `BN_new`.
208 unsafe { BN_clear_free(self.as_mut_ptr()) }
209 }
210}
211
212impl BigNum {
213 fn new() -> Result<Self> {
214 // SAFETY: The returned pointer is checked below.
215 let bn = unsafe { BN_new() };
Alice Wang47287e72023-09-29 13:14:33 +0000216 NonNull::new(bn).map(Self).ok_or(to_call_failed_error(ApiName::BN_new))
Alice Wanga78d3f02023-09-13 12:39:16 +0000217 }
218
219 fn as_mut_ptr(&mut self) -> *mut BIGNUM {
220 self.0.as_ptr()
221 }
222}
223
224/// Converts the `BigNum` to a big-endian integer. The integer is padded with leading zeros up to
225/// size `N`. The conversion fails if `N` is smaller thanthe size of the integer.
226impl<const N: usize> TryFrom<BigNum> for [u8; N] {
Alice Wangc8f88f52023-09-25 14:02:17 +0000227 type Error = Error;
Alice Wanga78d3f02023-09-13 12:39:16 +0000228
229 fn try_from(bn: BigNum) -> result::Result<Self, Self::Error> {
230 let mut num = [0u8; N];
231 // SAFETY: The `BIGNUM` pointer has been created with `BN_new`.
232 let ret = unsafe { BN_bn2bin_padded(num.as_mut_ptr(), num.len(), bn.0.as_ptr()) };
Alice Wangc8f88f52023-09-25 14:02:17 +0000233 check_int_result(ret, ApiName::BN_bn2bin_padded)?;
Alice Wanga78d3f02023-09-13 12:39:16 +0000234 Ok(num)
235 }
236}
237
Alice Wang7b2ab942023-09-12 13:04:42 +0000238// TODO(b/301068421): Unit tests the EcKey.