blob: fdd6f613b3bcb57f0cc81b22fff26f58269990be [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 Wang7b2ab942023-09-12 13:04:42 +000019use alloc::vec::Vec;
Alice Wangb3fcf632023-09-26 08:32:55 +000020use bssl_avf_error::{ApiName, Error, Result};
Alan Stokesb1f64ee2023-09-25 10:38:13 +010021use bssl_ffi::{
22 BN_bn2bin_padded, BN_clear_free, BN_new, CBB_flush, CBB_len, EC_KEY_free, EC_KEY_generate_key,
23 EC_KEY_get0_group, EC_KEY_get0_public_key, EC_KEY_marshal_private_key,
24 EC_KEY_new_by_curve_name, EC_POINT_get_affine_coordinates, NID_X9_62_prime256v1, BIGNUM,
25 EC_GROUP, EC_KEY, EC_POINT,
26};
Alice Wanga78d3f02023-09-13 12:39:16 +000027use core::ptr::{self, NonNull};
Alice Wang7b2ab942023-09-12 13:04:42 +000028use core::result;
Alice Wanga78d3f02023-09-13 12:39:16 +000029use coset::{iana, CoseKey, CoseKeyBuilder};
Alice Wang7b2ab942023-09-12 13:04:42 +000030use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
31
Alice Wanga78d3f02023-09-13 12:39:16 +000032const P256_AFFINE_COORDINATE_SIZE: usize = 32;
33
Alice Wanga78d3f02023-09-13 12:39:16 +000034type Coordinate = [u8; P256_AFFINE_COORDINATE_SIZE];
Alice Wang7b2ab942023-09-12 13:04:42 +000035
36/// Wrapper of an `EC_KEY` object, representing a public or private EC key.
37pub struct EcKey(NonNull<EC_KEY>);
38
39impl Drop for EcKey {
40 fn drop(&mut self) {
41 // SAFETY: It is safe because the key has been allocated by BoringSSL and isn't
42 // used after this.
43 unsafe { EC_KEY_free(self.0.as_ptr()) }
44 }
45}
46
47impl EcKey {
48 /// Creates a new EC P-256 key pair.
49 pub fn new_p256() -> Result<Self> {
50 // SAFETY: The returned pointer is checked below.
Alan Stokesb1f64ee2023-09-25 10:38:13 +010051 let ec_key = unsafe {
52 EC_KEY_new_by_curve_name(NID_X9_62_prime256v1) // EC P-256 CURVE Nid
53 };
Alice Wangc8f88f52023-09-25 14:02:17 +000054 let mut ec_key = NonNull::new(ec_key)
55 .map(Self)
56 .ok_or(Error::CallFailed(ApiName::EC_KEY_new_by_curve_name))?;
Alice Wang7b2ab942023-09-12 13:04:42 +000057 ec_key.generate_key()?;
58 Ok(ec_key)
59 }
60
61 /// Generates a random, private key, calculates the corresponding public key and stores both
62 /// in the `EC_KEY`.
63 fn generate_key(&mut self) -> Result<()> {
64 // SAFETY: The non-null pointer is created with `EC_KEY_new_by_curve_name` and should
65 // point to a valid `EC_KEY`.
66 // The randomness is provided by `getentropy()` in `vmbase`.
67 let ret = unsafe { EC_KEY_generate_key(self.0.as_ptr()) };
Alice Wangc8f88f52023-09-25 14:02:17 +000068 check_int_result(ret, ApiName::EC_KEY_generate_key)
Alice Wang7b2ab942023-09-12 13:04:42 +000069 }
70
Alice Wanga78d3f02023-09-13 12:39:16 +000071 /// Returns the `CoseKey` for the public key.
72 pub fn cose_public_key(&self) -> Result<CoseKey> {
73 const ALGO: iana::Algorithm = iana::Algorithm::ES256;
74 const CURVE: iana::EllipticCurve = iana::EllipticCurve::P_256;
75
76 let (x, y) = self.public_key_coordinates()?;
77 let key =
78 CoseKeyBuilder::new_ec2_pub_key(CURVE, x.to_vec(), y.to_vec()).algorithm(ALGO).build();
79 Ok(key)
80 }
81
82 /// Returns the x and y coordinates of the public key.
83 fn public_key_coordinates(&self) -> Result<(Coordinate, Coordinate)> {
84 let ec_group = self.ec_group()?;
85 let ec_point = self.public_key_ec_point()?;
86 let mut x = BigNum::new()?;
87 let mut y = BigNum::new()?;
88 let ctx = ptr::null_mut();
89 // SAFETY: All the parameters are checked non-null and initialized when needed.
90 // The last parameter `ctx` is generated when needed inside the function.
91 let ret = unsafe {
92 EC_POINT_get_affine_coordinates(ec_group, ec_point, x.as_mut_ptr(), y.as_mut_ptr(), ctx)
93 };
Alice Wangc8f88f52023-09-25 14:02:17 +000094 check_int_result(ret, ApiName::EC_POINT_get_affine_coordinates)?;
Alice Wanga78d3f02023-09-13 12:39:16 +000095 Ok((x.try_into()?, y.try_into()?))
96 }
97
98 /// Returns a pointer to the public key point inside `EC_KEY`. The memory region pointed
99 /// by the pointer is owned by the `EC_KEY`.
100 fn public_key_ec_point(&self) -> Result<*const EC_POINT> {
101 let ec_point =
102 // SAFETY: It is safe since the key pair has been generated and stored in the
103 // `EC_KEY` pointer.
104 unsafe { EC_KEY_get0_public_key(self.0.as_ptr()) };
105 if ec_point.is_null() {
Alice Wangc8f88f52023-09-25 14:02:17 +0000106 Err(Error::CallFailed(ApiName::EC_KEY_get0_public_key))
Alice Wanga78d3f02023-09-13 12:39:16 +0000107 } else {
108 Ok(ec_point)
109 }
110 }
111
112 /// Returns a pointer to the `EC_GROUP` object inside `EC_KEY`. The memory region pointed
113 /// by the pointer is owned by the `EC_KEY`.
114 fn ec_group(&self) -> Result<*const EC_GROUP> {
115 let group =
116 // SAFETY: It is safe since the key pair has been generated and stored in the
117 // `EC_KEY` pointer.
118 unsafe { EC_KEY_get0_group(self.0.as_ptr()) };
119 if group.is_null() {
Alice Wangc8f88f52023-09-25 14:02:17 +0000120 Err(Error::CallFailed(ApiName::EC_KEY_get0_group))
Alice Wanga78d3f02023-09-13 12:39:16 +0000121 } else {
122 Ok(group)
123 }
124 }
Alice Wang7b2ab942023-09-12 13:04:42 +0000125
126 /// Returns the DER-encoded ECPrivateKey structure described in RFC 5915 Section 3:
127 ///
128 /// https://datatracker.ietf.org/doc/html/rfc5915#section-3
129 pub fn private_key(&self) -> Result<ZVec> {
130 const CAPACITY: usize = 256;
131 let mut buf = Zeroizing::new([0u8; CAPACITY]);
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100132 let mut cbb = CbbFixed::new(buf.as_mut());
Alice Wang7b2ab942023-09-12 13:04:42 +0000133 let enc_flags = 0;
134 let ret =
135 // SAFETY: The function only write bytes to the buffer managed by the valid `CBB`
136 // object, and the key has been allocated by BoringSSL.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100137 unsafe { EC_KEY_marshal_private_key(cbb.as_mut(), self.0.as_ptr(), enc_flags) };
Alice Wang7b2ab942023-09-12 13:04:42 +0000138
Alice Wangc8f88f52023-09-25 14:02:17 +0000139 check_int_result(ret, ApiName::EC_KEY_marshal_private_key)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000140 // SAFETY: This is safe because the CBB pointer is a valid pointer initialized with
141 // `CBB_init_fixed()`.
Alice Wangc8f88f52023-09-25 14:02:17 +0000142 check_int_result(unsafe { CBB_flush(cbb.as_mut()) }, ApiName::CBB_flush)?;
Alice Wang7b2ab942023-09-12 13:04:42 +0000143 // SAFETY: This is safe because the CBB pointer is initialized with `CBB_init_fixed()`,
144 // and it has been flushed, thus it has no active children.
Alan Stokesb1f64ee2023-09-25 10:38:13 +0100145 let len = unsafe { CBB_len(cbb.as_ref()) };
Alice Wangc8f88f52023-09-25 14:02:17 +0000146 Ok(buf.get(0..len).ok_or(Error::CallFailed(ApiName::CBB_len))?.to_vec().into())
Alice Wang7b2ab942023-09-12 13:04:42 +0000147 }
148}
149
150/// A u8 vector that is zeroed when dropped.
151#[derive(Zeroize, ZeroizeOnDrop)]
152pub struct ZVec(Vec<u8>);
153
154impl ZVec {
155 /// Extracts a slice containing the entire vector.
156 pub fn as_slice(&self) -> &[u8] {
157 &self.0[..]
158 }
159}
160
161impl From<Vec<u8>> for ZVec {
162 fn from(v: Vec<u8>) -> Self {
163 Self(v)
164 }
165}
166
Alice Wanga78d3f02023-09-13 12:39:16 +0000167struct BigNum(NonNull<BIGNUM>);
168
169impl Drop for BigNum {
170 fn drop(&mut self) {
171 // SAFETY: The pointer has been created with `BN_new`.
172 unsafe { BN_clear_free(self.as_mut_ptr()) }
173 }
174}
175
176impl BigNum {
177 fn new() -> Result<Self> {
178 // SAFETY: The returned pointer is checked below.
179 let bn = unsafe { BN_new() };
Alice Wangc8f88f52023-09-25 14:02:17 +0000180 NonNull::new(bn).map(Self).ok_or(Error::CallFailed(ApiName::BN_new))
Alice Wanga78d3f02023-09-13 12:39:16 +0000181 }
182
183 fn as_mut_ptr(&mut self) -> *mut BIGNUM {
184 self.0.as_ptr()
185 }
186}
187
188/// Converts the `BigNum` to a big-endian integer. The integer is padded with leading zeros up to
189/// size `N`. The conversion fails if `N` is smaller thanthe size of the integer.
190impl<const N: usize> TryFrom<BigNum> for [u8; N] {
Alice Wangc8f88f52023-09-25 14:02:17 +0000191 type Error = Error;
Alice Wanga78d3f02023-09-13 12:39:16 +0000192
193 fn try_from(bn: BigNum) -> result::Result<Self, Self::Error> {
194 let mut num = [0u8; N];
195 // SAFETY: The `BIGNUM` pointer has been created with `BN_new`.
196 let ret = unsafe { BN_bn2bin_padded(num.as_mut_ptr(), num.len(), bn.0.as_ptr()) };
Alice Wangc8f88f52023-09-25 14:02:17 +0000197 check_int_result(ret, ApiName::BN_bn2bin_padded)?;
Alice Wanga78d3f02023-09-13 12:39:16 +0000198 Ok(num)
199 }
200}
201
Alice Wangc8f88f52023-09-25 14:02:17 +0000202fn check_int_result(ret: i32, api_name: ApiName) -> Result<()> {
Alice Wang7b2ab942023-09-12 13:04:42 +0000203 if ret == 1 {
204 Ok(())
205 } else {
206 assert_eq!(ret, 0, "Unexpected return value {ret} for {api_name:?}");
Alice Wangc8f88f52023-09-25 14:02:17 +0000207 Err(Error::CallFailed(api_name))
Alice Wang7b2ab942023-09-12 13:04:42 +0000208 }
209}
210
211// TODO(b/301068421): Unit tests the EcKey.