blob: 7038e21519e5cdd4addd264a3fbd9b17ef1673d8 [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 Wang47287e72023-09-29 13:14:33 +000019use crate::util::{check_int_result, to_call_failed_error};
Alice Wang7b2ab942023-09-12 13:04:42 +000020use alloc::vec::Vec;
Alice Wangb3fcf632023-09-26 08:32:55 +000021use bssl_avf_error::{ApiName, Error, Result};
Alan Stokesb1f64ee2023-09-25 10:38:13 +010022use bssl_ffi::{
23 BN_bn2bin_padded, BN_clear_free, BN_new, CBB_flush, CBB_len, EC_KEY_free, EC_KEY_generate_key,
24 EC_KEY_get0_group, EC_KEY_get0_public_key, EC_KEY_marshal_private_key,
25 EC_KEY_new_by_curve_name, EC_POINT_get_affine_coordinates, NID_X9_62_prime256v1, BIGNUM,
26 EC_GROUP, EC_KEY, EC_POINT,
27};
Alice Wanga78d3f02023-09-13 12:39:16 +000028use core::ptr::{self, NonNull};
Alice Wang7b2ab942023-09-12 13:04:42 +000029use core::result;
Alice Wanga78d3f02023-09-13 12:39:16 +000030use coset::{iana, CoseKey, CoseKeyBuilder};
Alice Wang7b2ab942023-09-12 13:04:42 +000031use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
32
Alice Wanga78d3f02023-09-13 12:39:16 +000033const P256_AFFINE_COORDINATE_SIZE: usize = 32;
34
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 Wangc8f88f52023-09-25 14:02:17 +000055 let mut ec_key = NonNull::new(ec_key)
56 .map(Self)
Alice Wang47287e72023-09-29 13:14:33 +000057 .ok_or(to_call_failed_error(ApiName::EC_KEY_new_by_curve_name))?;
Alice Wang7b2ab942023-09-12 13:04:42 +000058 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()) };
Alice Wangc8f88f52023-09-25 14:02:17 +000069 check_int_result(ret, ApiName::EC_KEY_generate_key)
Alice Wang7b2ab942023-09-12 13:04:42 +000070 }
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 };
Alice Wangc8f88f52023-09-25 14:02:17 +000095 check_int_result(ret, ApiName::EC_POINT_get_affine_coordinates)?;
Alice Wanga78d3f02023-09-13 12:39:16 +000096 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() {
Alice Wang47287e72023-09-29 13:14:33 +0000107 Err(to_call_failed_error(ApiName::EC_KEY_get0_public_key))
Alice Wanga78d3f02023-09-13 12:39:16 +0000108 } else {
109 Ok(ec_point)
110 }
111 }
112
113 /// Returns a pointer to the `EC_GROUP` object inside `EC_KEY`. The memory region pointed
114 /// by the pointer is owned by the `EC_KEY`.
115 fn ec_group(&self) -> Result<*const EC_GROUP> {
116 let group =
117 // SAFETY: It is safe since the key pair has been generated and stored in the
118 // `EC_KEY` pointer.
119 unsafe { EC_KEY_get0_group(self.0.as_ptr()) };
120 if group.is_null() {
Alice Wang47287e72023-09-29 13:14:33 +0000121 Err(to_call_failed_error(ApiName::EC_KEY_get0_group))
Alice Wanga78d3f02023-09-13 12:39:16 +0000122 } else {
123 Ok(group)
124 }
125 }
Alice Wang7b2ab942023-09-12 13:04:42 +0000126
127 /// Returns the DER-encoded ECPrivateKey structure described in RFC 5915 Section 3:
128 ///
129 /// https://datatracker.ietf.org/doc/html/rfc5915#section-3
130 pub fn private_key(&self) -> Result<ZVec> {
131 const CAPACITY: usize = 256;
132 let mut buf = Zeroizing::new([0u8; CAPACITY]);
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100133 let mut cbb = CbbFixed::new(buf.as_mut());
Alice Wang7b2ab942023-09-12 13:04:42 +0000134 let enc_flags = 0;
135 let ret =
136 // SAFETY: The function only write bytes to the buffer managed by the valid `CBB`
137 // object, and the key has been allocated by BoringSSL.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100138 unsafe { EC_KEY_marshal_private_key(cbb.as_mut(), self.0.as_ptr(), enc_flags) };
Alice Wang7b2ab942023-09-12 13:04:42 +0000139
Alice Wangc8f88f52023-09-25 14:02:17 +0000140 check_int_result(ret, ApiName::EC_KEY_marshal_private_key)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000141 // SAFETY: This is safe because the CBB pointer is a valid pointer initialized with
142 // `CBB_init_fixed()`.
Alice Wangc8f88f52023-09-25 14:02:17 +0000143 check_int_result(unsafe { CBB_flush(cbb.as_mut()) }, ApiName::CBB_flush)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000144 // SAFETY: This is safe because the CBB pointer is initialized with `CBB_init_fixed()`,
145 // and it has been flushed, thus it has no active children.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100146 let len = unsafe { CBB_len(cbb.as_ref()) };
Alice Wang47287e72023-09-29 13:14:33 +0000147 Ok(buf.get(0..len).ok_or(to_call_failed_error(ApiName::CBB_len))?.to_vec().into())
Alice Wang7b2ab942023-09-12 13:04:42 +0000148 }
149}
150
151/// A u8 vector that is zeroed when dropped.
152#[derive(Zeroize, ZeroizeOnDrop)]
153pub struct ZVec(Vec<u8>);
154
155impl ZVec {
156 /// Extracts a slice containing the entire vector.
157 pub fn as_slice(&self) -> &[u8] {
158 &self.0[..]
159 }
160}
161
162impl From<Vec<u8>> for ZVec {
163 fn from(v: Vec<u8>) -> Self {
164 Self(v)
165 }
166}
167
Alice Wanga78d3f02023-09-13 12:39:16 +0000168struct BigNum(NonNull<BIGNUM>);
169
170impl Drop for BigNum {
171 fn drop(&mut self) {
172 // SAFETY: The pointer has been created with `BN_new`.
173 unsafe { BN_clear_free(self.as_mut_ptr()) }
174 }
175}
176
177impl BigNum {
178 fn new() -> Result<Self> {
179 // SAFETY: The returned pointer is checked below.
180 let bn = unsafe { BN_new() };
Alice Wang47287e72023-09-29 13:14:33 +0000181 NonNull::new(bn).map(Self).ok_or(to_call_failed_error(ApiName::BN_new))
Alice Wanga78d3f02023-09-13 12:39:16 +0000182 }
183
184 fn as_mut_ptr(&mut self) -> *mut BIGNUM {
185 self.0.as_ptr()
186 }
187}
188
189/// Converts the `BigNum` to a big-endian integer. The integer is padded with leading zeros up to
190/// size `N`. The conversion fails if `N` is smaller thanthe size of the integer.
191impl<const N: usize> TryFrom<BigNum> for [u8; N] {
Alice Wangc8f88f52023-09-25 14:02:17 +0000192 type Error = Error;
Alice Wanga78d3f02023-09-13 12:39:16 +0000193
194 fn try_from(bn: BigNum) -> result::Result<Self, Self::Error> {
195 let mut num = [0u8; N];
196 // SAFETY: The `BIGNUM` pointer has been created with `BN_new`.
197 let ret = unsafe { BN_bn2bin_padded(num.as_mut_ptr(), num.len(), bn.0.as_ptr()) };
Alice Wangc8f88f52023-09-25 14:02:17 +0000198 check_int_result(ret, ApiName::BN_bn2bin_padded)?;
Alice Wanga78d3f02023-09-13 12:39:16 +0000199 Ok(num)
200 }
201}
202
Alice Wang7b2ab942023-09-12 13:04:42 +0000203// TODO(b/301068421): Unit tests the EcKey.