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 //! Wrappers of the digest functions in BoringSSL digest.h.
16 
17 use crate::util::{check_int_result, to_call_failed_error};
18 use alloc::vec;
19 use alloc::vec::Vec;
20 use bssl_avf_error::{ApiName, Error, Result};
21 use bssl_sys::{
22     EVP_Digest, EVP_MD_CTX_free, EVP_MD_CTX_new, EVP_MD_size, EVP_sha256, EVP_sha384, EVP_sha512,
23     EVP_MAX_MD_SIZE, EVP_MD, EVP_MD_CTX,
24 };
25 use core::ptr::{self, NonNull};
26 use log::error;
27 
28 const MAX_DIGEST_SIZE: usize = EVP_MAX_MD_SIZE as usize;
29 
30 /// Message digester wrapping `EVP_MD`.
31 #[derive(Clone, Debug)]
32 pub struct Digester(pub(crate) &'static EVP_MD);
33 
34 impl Digester {
35     /// Returns a `Digester` implementing `SHA-256` algorithm.
sha256() -> Self36     pub fn sha256() -> Self {
37         // SAFETY: This function does not access any Rust variables and simply returns
38         // a pointer to the static variable in BoringSSL.
39         let p = unsafe { EVP_sha256() };
40         // SAFETY: The returned pointer should always be valid and points to a static
41         // `EVP_MD`.
42         Self(unsafe { p.as_ref().unwrap() })
43     }
44 
45     /// Returns a `Digester` implementing `SHA-384` algorithm.
sha384() -> Self46     pub fn sha384() -> Self {
47         // SAFETY: This function does not access any Rust variables and simply returns
48         // a pointer to the static variable in BoringSSL.
49         let p = unsafe { EVP_sha384() };
50         // SAFETY: The returned pointer should always be valid and points to a static
51         // `EVP_MD`.
52         Self(unsafe { p.as_ref().unwrap() })
53     }
54 
55     /// Returns a `Digester` implementing `SHA-512` algorithm.
sha512() -> Self56     pub fn sha512() -> Self {
57         // SAFETY: This function does not access any Rust variables and simply returns
58         // a pointer to the static variable in BoringSSL.
59         let p = unsafe { EVP_sha512() };
60         // SAFETY: The returned pointer should always be valid and points to a static
61         // `EVP_MD`.
62         Self(unsafe { p.as_ref().unwrap() })
63     }
64 
65     /// Returns the digest size in bytes.
size(&self) -> usize66     pub fn size(&self) -> usize {
67         // SAFETY: The inner pointer is fetched from EVP_* hash functions in BoringSSL digest.h
68         unsafe { EVP_MD_size(self.0) }
69     }
70 
71     /// Computes the digest of the provided `data`.
digest(&self, data: &[u8]) -> Result<Vec<u8>>72     pub fn digest(&self, data: &[u8]) -> Result<Vec<u8>> {
73         let mut out = vec![0u8; MAX_DIGEST_SIZE];
74         let mut out_size = 0;
75         let engine = ptr::null_mut(); // Use the default engine.
76         let ret =
77             // SAFETY: This function reads `data` and writes to `out` within its bounds.
78             // `out` has `MAX_DIGEST_SIZE` bytes of space for write as required in the
79             // BoringSSL spec.
80             // The digester is a valid pointer to a static `EVP_MD` as it is returned by
81             // BoringSSL API during the construction of this struct.
82             unsafe {
83                 EVP_Digest(
84                     data.as_ptr() as *const _,
85                     data.len(),
86                     out.as_mut_ptr(),
87                     &mut out_size,
88                     self.0,
89                     engine,
90                 )
91             };
92         check_int_result(ret, ApiName::EVP_Digest)?;
93         let out_size = usize::try_from(out_size).map_err(|e| {
94             error!("Failed to convert digest size to usize: {:?}", e);
95             Error::InternalError
96         })?;
97         if self.size() != out_size {
98             return Err(to_call_failed_error(ApiName::EVP_Digest));
99         }
100         out.truncate(out_size);
101         Ok(out)
102     }
103 }
104 
105 /// Message digester context wrapping `EVP_MD_CTX`.
106 #[derive(Clone, Debug)]
107 pub struct DigesterContext(NonNull<EVP_MD_CTX>);
108 
109 impl Drop for DigesterContext {
drop(&mut self)110     fn drop(&mut self) {
111         // SAFETY: This function frees any resources owned by `EVP_MD_CTX` and resets it to a
112         // freshly initialised state and then frees the context.
113         // It is safe because `EVP_MD_CTX` has been allocated by BoringSSL and isn't used after
114         // this.
115         unsafe { EVP_MD_CTX_free(self.0.as_ptr()) }
116     }
117 }
118 
119 impl DigesterContext {
120     /// Creates a new `DigesterContext` wrapping a freshly allocated and initialised `EVP_MD_CTX`.
new() -> Result<Self>121     pub fn new() -> Result<Self> {
122         // SAFETY: The returned pointer is checked below.
123         let ctx = unsafe { EVP_MD_CTX_new() };
124         NonNull::new(ctx).map(Self).ok_or_else(|| to_call_failed_error(ApiName::EVP_MD_CTX_new))
125     }
126 
as_mut_ptr(&mut self) -> *mut EVP_MD_CTX127     pub(crate) fn as_mut_ptr(&mut self) -> *mut EVP_MD_CTX {
128         self.0.as_ptr()
129     }
130 }
131