Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 1 | // 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 | //! Wrapper around BoringSSL/OpenSSL symbols. |
| 16 | |
| 17 | use core::convert::AsRef; |
| 18 | use core::ffi::{c_char, c_int, CStr}; |
| 19 | use core::fmt; |
| 20 | use core::mem::MaybeUninit; |
| 21 | use core::num::NonZeroU32; |
| 22 | use core::ptr; |
| 23 | |
Pierre-Clément Tosi | 41748ed | 2023-03-31 18:20:40 +0100 | [diff] [blame] | 24 | use bssl_ffi::CRYPTO_library_init; |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 25 | use bssl_ffi::ERR_get_error_line; |
| 26 | use bssl_ffi::ERR_lib_error_string; |
| 27 | use bssl_ffi::ERR_reason_error_string; |
| 28 | use bssl_ffi::EVP_AEAD_CTX_aead; |
| 29 | use bssl_ffi::EVP_AEAD_CTX_init; |
| 30 | use bssl_ffi::EVP_AEAD_CTX_open; |
| 31 | use bssl_ffi::EVP_AEAD_CTX_seal; |
| 32 | use bssl_ffi::EVP_AEAD_max_overhead; |
| 33 | use bssl_ffi::EVP_aead_aes_256_gcm_randnonce; |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 34 | use bssl_ffi::EVP_AEAD; |
| 35 | use bssl_ffi::EVP_AEAD_CTX; |
Pierre-Clément Tosi | 1bf532b | 2023-11-13 11:06:20 +0000 | [diff] [blame^] | 36 | use cstr::cstr; |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 37 | |
| 38 | #[derive(Debug)] |
| 39 | pub struct Error { |
| 40 | packed: NonZeroU32, |
| 41 | file: Option<&'static CStr>, |
| 42 | line: c_int, |
| 43 | } |
| 44 | |
| 45 | impl Error { |
| 46 | fn get() -> Option<Self> { |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 47 | let mut file = ptr::null(); |
| 48 | let mut line = 0; |
| 49 | // SAFETY: The function writes to the provided pointers, which are valid because they come |
| 50 | // from references. It doesn't retain them after it returns. |
| 51 | let packed = unsafe { ERR_get_error_line(&mut file, &mut line) }; |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 52 | |
| 53 | let packed = packed.try_into().ok()?; |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 54 | // SAFETY: Any non-NULL result is expected to point to a global const C string. |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 55 | let file = unsafe { as_static_cstr(file) }; |
| 56 | |
| 57 | Some(Self { packed, file, line }) |
| 58 | } |
| 59 | |
| 60 | fn packed_value(&self) -> u32 { |
| 61 | self.packed.get() |
| 62 | } |
| 63 | |
| 64 | fn library_name(&self) -> Option<&'static CStr> { |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 65 | // SAFETY: Call to a pure function. |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 66 | let name = unsafe { ERR_lib_error_string(self.packed_value()) }; |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 67 | // SAFETY: Any non-NULL result is expected to point to a global const C string. |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 68 | unsafe { as_static_cstr(name) } |
| 69 | } |
| 70 | |
| 71 | fn reason(&self) -> Option<&'static CStr> { |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 72 | // SAFETY: Call to a pure function. |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 73 | let reason = unsafe { ERR_reason_error_string(self.packed_value()) }; |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 74 | // SAFETY: Any non-NULL result is expected to point to a global const C string. |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 75 | unsafe { as_static_cstr(reason) } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | impl fmt::Display for Error { |
| 80 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 81 | let packed = self.packed_value(); |
Jiyong Park | b87f330 | 2023-03-21 10:03:11 +0900 | [diff] [blame] | 82 | let library = self.library_name().unwrap_or(cstr!("{unknown library}")).to_str().unwrap(); |
| 83 | let reason = self.reason().unwrap_or(cstr!("{unknown reason}")).to_str().unwrap(); |
| 84 | let file = self.file.unwrap_or(cstr!("??")).to_str().unwrap(); |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 85 | let line = self.line; |
| 86 | |
| 87 | write!(f, "{file}:{line}: {library}: {reason} ({packed:#x})") |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | #[derive(Copy, Clone)] |
| 92 | pub struct ErrorIterator {} |
| 93 | |
| 94 | impl Iterator for ErrorIterator { |
| 95 | type Item = Error; |
| 96 | |
| 97 | fn next(&mut self) -> Option<Self::Item> { |
| 98 | Self::Item::get() |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | pub type Result<T> = core::result::Result<T, ErrorIterator>; |
| 103 | |
| 104 | #[repr(transparent)] |
| 105 | pub struct Aead(EVP_AEAD); |
| 106 | |
| 107 | impl Aead { |
| 108 | pub fn aes_256_gcm_randnonce() -> Option<&'static Self> { |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 109 | // SAFETY: Returned pointer is checked below. |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 110 | let aead = unsafe { EVP_aead_aes_256_gcm_randnonce() }; |
| 111 | if aead.is_null() { |
| 112 | None |
| 113 | } else { |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 114 | // SAFETY: We assume that the non-NULL value points to a valid and static EVP_AEAD. |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 115 | Some(unsafe { &*(aead as *const _) }) |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | pub fn max_overhead(&self) -> usize { |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 120 | // SAFETY: Function should only read from self. |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 121 | unsafe { EVP_AEAD_max_overhead(self.as_ref() as *const _) } |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | #[repr(transparent)] |
| 126 | pub struct AeadCtx(EVP_AEAD_CTX); |
| 127 | |
| 128 | impl AeadCtx { |
| 129 | pub fn new_aes_256_gcm_randnonce(key: &[u8]) -> Result<Self> { |
| 130 | let aead = Aead::aes_256_gcm_randnonce().unwrap(); |
| 131 | |
| 132 | Self::new(aead, key) |
| 133 | } |
| 134 | |
| 135 | fn new(aead: &'static Aead, key: &[u8]) -> Result<Self> { |
| 136 | const DEFAULT_TAG_LENGTH: usize = 0; |
| 137 | let engine = ptr::null_mut(); // Use default implementation. |
| 138 | let mut ctx = MaybeUninit::zeroed(); |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 139 | // SAFETY: Initialize the EVP_AEAD_CTX with const pointers to the AEAD and key. |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 140 | let result = unsafe { |
| 141 | EVP_AEAD_CTX_init( |
| 142 | ctx.as_mut_ptr(), |
| 143 | aead.as_ref() as *const _, |
| 144 | key.as_ptr(), |
| 145 | key.len(), |
| 146 | DEFAULT_TAG_LENGTH, |
| 147 | engine, |
| 148 | ) |
| 149 | }; |
| 150 | |
| 151 | if result == 1 { |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 152 | // SAFETY: We assume that the non-NULL value points to a valid and static EVP_AEAD. |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 153 | Ok(Self(unsafe { ctx.assume_init() })) |
| 154 | } else { |
| 155 | Err(ErrorIterator {}) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | pub fn aead(&self) -> Option<&'static Aead> { |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 160 | // SAFETY: The function should only read from self. |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 161 | let aead = unsafe { EVP_AEAD_CTX_aead(self.as_ref() as *const _) }; |
| 162 | if aead.is_null() { |
| 163 | None |
| 164 | } else { |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 165 | // SAFETY: We assume that the non-NULL value points to a valid and static EVP_AEAD. |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 166 | Some(unsafe { &*(aead as *const _) }) |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | pub fn open<'b>(&self, out: &'b mut [u8], data: &[u8]) -> Result<&'b mut [u8]> { |
| 171 | let nonce = ptr::null_mut(); |
| 172 | let nonce_len = 0; |
| 173 | let ad = ptr::null_mut(); |
| 174 | let ad_len = 0; |
| 175 | let mut out_len = MaybeUninit::uninit(); |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 176 | // SAFETY: The function should only read from self and write to out (at most the provided |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 177 | // number of bytes) and out_len while reading from data (at most the provided number of |
| 178 | // bytes), ignoring any NULL input. |
| 179 | let result = unsafe { |
| 180 | EVP_AEAD_CTX_open( |
| 181 | self.as_ref() as *const _, |
| 182 | out.as_mut_ptr(), |
| 183 | out_len.as_mut_ptr(), |
| 184 | out.len(), |
| 185 | nonce, |
| 186 | nonce_len, |
| 187 | data.as_ptr(), |
| 188 | data.len(), |
| 189 | ad, |
| 190 | ad_len, |
| 191 | ) |
| 192 | }; |
| 193 | |
| 194 | if result == 1 { |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 195 | // SAFETY: Any value written to out_len could be a valid usize. The value itself is |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 196 | // validated as being a proper slice length by panicking in the following indexing |
| 197 | // otherwise. |
| 198 | let out_len = unsafe { out_len.assume_init() }; |
| 199 | Ok(&mut out[..out_len]) |
| 200 | } else { |
| 201 | Err(ErrorIterator {}) |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | pub fn seal<'b>(&self, out: &'b mut [u8], data: &[u8]) -> Result<&'b mut [u8]> { |
| 206 | let nonce = ptr::null_mut(); |
| 207 | let nonce_len = 0; |
| 208 | let ad = ptr::null_mut(); |
| 209 | let ad_len = 0; |
| 210 | let mut out_len = MaybeUninit::uninit(); |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 211 | // SAFETY: The function should only read from self and write to out (at most the provided |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 212 | // number of bytes) while reading from data (at most the provided number of bytes), |
| 213 | // ignoring any NULL input. |
| 214 | let result = unsafe { |
| 215 | EVP_AEAD_CTX_seal( |
| 216 | self.as_ref() as *const _, |
| 217 | out.as_mut_ptr(), |
| 218 | out_len.as_mut_ptr(), |
| 219 | out.len(), |
| 220 | nonce, |
| 221 | nonce_len, |
| 222 | data.as_ptr(), |
| 223 | data.len(), |
| 224 | ad, |
| 225 | ad_len, |
| 226 | ) |
| 227 | }; |
| 228 | |
| 229 | if result == 1 { |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 230 | // SAFETY: Any value written to out_len could be a valid usize. The value itself is |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 231 | // validated as being a proper slice length by panicking in the following indexing |
| 232 | // otherwise. |
| 233 | let out_len = unsafe { out_len.assume_init() }; |
| 234 | Ok(&mut out[..out_len]) |
| 235 | } else { |
| 236 | Err(ErrorIterator {}) |
| 237 | } |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | /// Cast a C string pointer to a static non-mutable reference. |
| 242 | /// |
| 243 | /// # Safety |
| 244 | /// |
Alan Stokes | a0e4296 | 2023-04-14 17:59:50 +0100 | [diff] [blame] | 245 | /// The caller needs to ensure that the pointer is null or points to a valid C string and that the |
| 246 | /// C lifetime of the string is compatible with a static Rust lifetime. |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 247 | unsafe fn as_static_cstr(p: *const c_char) -> Option<&'static CStr> { |
| 248 | if p.is_null() { |
| 249 | None |
| 250 | } else { |
Alan Stokes | a0e4296 | 2023-04-14 17:59:50 +0100 | [diff] [blame] | 251 | // Safety: Safe given the requirements of this function. |
| 252 | Some(unsafe { CStr::from_ptr(p) }) |
Pierre-Clément Tosi | 90cd4f1 | 2023-02-17 11:19:56 +0000 | [diff] [blame] | 253 | } |
| 254 | } |
| 255 | |
| 256 | impl AsRef<EVP_AEAD> for Aead { |
| 257 | fn as_ref(&self) -> &EVP_AEAD { |
| 258 | &self.0 |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | impl AsRef<EVP_AEAD_CTX> for AeadCtx { |
| 263 | fn as_ref(&self) -> &EVP_AEAD_CTX { |
| 264 | &self.0 |
| 265 | } |
| 266 | } |
| 267 | |
Pierre-Clément Tosi | 41748ed | 2023-03-31 18:20:40 +0100 | [diff] [blame] | 268 | pub fn init() { |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 269 | // SAFETY: Configures the internal state of the library - may be called multiple times. |
Pierre-Clément Tosi | 41748ed | 2023-03-31 18:20:40 +0100 | [diff] [blame] | 270 | unsafe { CRYPTO_library_init() } |
| 271 | } |