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 error handling functions in BoringSSL err.h.
16 
17 use alloc::string::{String, ToString};
18 use bssl_avf_error::{CipherError, EcError, EcdsaError, GlobalError, ReasonCode};
19 use bssl_sys::{
20     self, ERR_get_error_line, ERR_lib_error_string, ERR_reason_error_string, ERR_GET_LIB_RUST,
21     ERR_GET_REASON_RUST,
22 };
23 use core::ffi::{c_char, CStr};
24 use core::ptr;
25 use log::{error, info};
26 
27 const NO_ERROR_REASON_CODE: i32 = 0;
28 
29 /// Processes the error queue till it is empty, logs the information for all the errors in
30 /// the queue from the least recent to the most recent, and returns the reason code for the
31 /// most recent error.
process_error_queue() -> ReasonCode32 pub(crate) fn process_error_queue() -> ReasonCode {
33     let mut reason_code = ReasonCode::NoError;
34     loop {
35         let code = process_least_recent_error();
36         if code == ReasonCode::NoError {
37             break;
38         }
39         reason_code = code;
40     }
41     reason_code
42 }
43 
44 /// Removes the least recent error in the error queue and logs the error information.
45 ///
46 /// Returns the reason code for the least recent error.
process_least_recent_error() -> ReasonCode47 fn process_least_recent_error() -> ReasonCode {
48     let mut file = ptr::null();
49     let mut line = 0;
50     // SAFETY: This function only reads the error queue and writes to the given
51     // pointers. It doesn't retain any references to the pointers.
52     let packed_error = unsafe { ERR_get_error_line(&mut file, &mut line) };
53     let reason = get_reason(packed_error);
54     if reason == NO_ERROR_REASON_CODE {
55         info!("No error in the BoringSSL error queue");
56         return ReasonCode::NoError;
57     }
58 
59     // SAFETY: Any non-null result is expected to point to a global const C string.
60     let file = unsafe { cstr_to_string(file, "<unknown file>") };
61     error!(
62         "BoringSSL error: {}:{}: lib = {}, reason = {}",
63         file,
64         line,
65         lib_error_string(packed_error),
66         reason_error_string(packed_error),
67     );
68 
69     let lib = get_lib(packed_error);
70     map_to_reason_code(reason, lib)
71 }
72 
lib_error_string(packed_error: u32) -> String73 fn lib_error_string(packed_error: u32) -> String {
74     // SAFETY: This function only reads the given error code and returns a
75     // pointer to a static string.
76     let p = unsafe { ERR_lib_error_string(packed_error) };
77     // SAFETY: Any non-null result is expected to point to a global const C string.
78     unsafe { cstr_to_string(p, "<unknown library>") }
79 }
80 
reason_error_string(packed_error: u32) -> String81 fn reason_error_string(packed_error: u32) -> String {
82     // SAFETY: This function only reads the given error code and returns a
83     // pointer to a static string.
84     let p = unsafe { ERR_reason_error_string(packed_error) };
85     // SAFETY: Any non-null result is expected to point to a global const C string.
86     unsafe { cstr_to_string(p, "<unknown reason>") }
87 }
88 
89 /// Converts a C string pointer to a Rust string.
90 ///
91 /// # Safety
92 ///
93 /// The caller needs to ensure that the pointer is null or points to a valid C string.
cstr_to_string(p: *const c_char, default: &str) -> String94 unsafe fn cstr_to_string(p: *const c_char, default: &str) -> String {
95     if p.is_null() {
96         return default.to_string();
97     }
98     // Safety: Safe given the requirements of this function.
99     let s = unsafe { CStr::from_ptr(p) };
100     s.to_str().unwrap_or(default).to_string()
101 }
102 
get_reason(packed_error: u32) -> i32103 fn get_reason(packed_error: u32) -> i32 {
104     // SAFETY: This function only reads the given error code.
105     unsafe { ERR_GET_REASON_RUST(packed_error) }
106 }
107 
108 /// Returns the library code for the error.
get_lib(packed_error: u32) -> i32109 fn get_lib(packed_error: u32) -> i32 {
110     // SAFETY: This function only reads the given error code.
111     unsafe { ERR_GET_LIB_RUST(packed_error) }
112 }
113 
map_to_reason_code(reason: i32, lib: i32) -> ReasonCode114 fn map_to_reason_code(reason: i32, lib: i32) -> ReasonCode {
115     if reason == NO_ERROR_REASON_CODE {
116         return ReasonCode::NoError;
117     }
118     map_global_reason_code(reason)
119         .map(ReasonCode::Global)
120         .or_else(|| map_library_reason_code(reason, lib))
121         .unwrap_or(ReasonCode::Unknown(reason, lib))
122 }
123 
124 /// Global errors may occur in any library.
map_global_reason_code(reason: i32) -> Option<GlobalError>125 fn map_global_reason_code(reason: i32) -> Option<GlobalError> {
126     let reason = match reason {
127         bssl_sys::ERR_R_FATAL => GlobalError::Fatal,
128         bssl_sys::ERR_R_MALLOC_FAILURE => GlobalError::MallocFailure,
129         bssl_sys::ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED => GlobalError::ShouldNotHaveBeenCalled,
130         bssl_sys::ERR_R_PASSED_NULL_PARAMETER => GlobalError::PassedNullParameter,
131         bssl_sys::ERR_R_INTERNAL_ERROR => GlobalError::InternalError,
132         bssl_sys::ERR_R_OVERFLOW => GlobalError::Overflow,
133         _ => return None,
134     };
135     Some(reason)
136 }
137 
map_library_reason_code(reason: i32, lib: i32) -> Option<ReasonCode>138 fn map_library_reason_code(reason: i32, lib: i32) -> Option<ReasonCode> {
139     u32::try_from(lib).ok().and_then(|x| match x {
140         bssl_sys::ERR_LIB_CIPHER => map_cipher_reason_code(reason).map(ReasonCode::Cipher),
141         bssl_sys::ERR_LIB_EC => map_ec_reason_code(reason).map(ReasonCode::Ec),
142         bssl_sys::ERR_LIB_ECDSA => map_ecdsa_reason_code(reason).map(ReasonCode::Ecdsa),
143         _ => None,
144     })
145 }
146 
map_cipher_reason_code(reason: i32) -> Option<CipherError>147 fn map_cipher_reason_code(reason: i32) -> Option<CipherError> {
148     let error = match reason {
149         bssl_sys::CIPHER_R_AES_KEY_SETUP_FAILED => CipherError::AesKeySetupFailed,
150         bssl_sys::CIPHER_R_BAD_DECRYPT => CipherError::BadDecrypt,
151         bssl_sys::CIPHER_R_BAD_KEY_LENGTH => CipherError::BadKeyLength,
152         bssl_sys::CIPHER_R_BUFFER_TOO_SMALL => CipherError::BufferTooSmall,
153         bssl_sys::CIPHER_R_CTRL_NOT_IMPLEMENTED => CipherError::CtrlNotImplemented,
154         bssl_sys::CIPHER_R_CTRL_OPERATION_NOT_IMPLEMENTED => {
155             CipherError::CtrlOperationNotImplemented
156         }
157         bssl_sys::CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH => {
158             CipherError::DataNotMultipleOfBlockLength
159         }
160         bssl_sys::CIPHER_R_INITIALIZATION_ERROR => CipherError::InitializationError,
161         bssl_sys::CIPHER_R_INPUT_NOT_INITIALIZED => CipherError::InputNotInitialized,
162         bssl_sys::CIPHER_R_INVALID_AD_SIZE => CipherError::InvalidAdSize,
163         bssl_sys::CIPHER_R_INVALID_KEY_LENGTH => CipherError::InvalidKeyLength,
164         bssl_sys::CIPHER_R_INVALID_NONCE_SIZE => CipherError::InvalidNonceSize,
165         bssl_sys::CIPHER_R_INVALID_OPERATION => CipherError::InvalidOperation,
166         bssl_sys::CIPHER_R_IV_TOO_LARGE => CipherError::IvTooLarge,
167         bssl_sys::CIPHER_R_NO_CIPHER_SET => CipherError::NoCipherSet,
168         bssl_sys::CIPHER_R_OUTPUT_ALIASES_INPUT => CipherError::OutputAliasesInput,
169         bssl_sys::CIPHER_R_TAG_TOO_LARGE => CipherError::TagTooLarge,
170         bssl_sys::CIPHER_R_TOO_LARGE => CipherError::TooLarge,
171         bssl_sys::CIPHER_R_WRONG_FINAL_BLOCK_LENGTH => CipherError::WrongFinalBlockLength,
172         bssl_sys::CIPHER_R_NO_DIRECTION_SET => CipherError::NoDirectionSet,
173         bssl_sys::CIPHER_R_INVALID_NONCE => CipherError::InvalidNonce,
174         _ => return None,
175     };
176     Some(error)
177 }
178 
map_ec_reason_code(reason: i32) -> Option<EcError>179 fn map_ec_reason_code(reason: i32) -> Option<EcError> {
180     let error = match reason {
181         bssl_sys::EC_R_BUFFER_TOO_SMALL => EcError::BufferTooSmall,
182         bssl_sys::EC_R_COORDINATES_OUT_OF_RANGE => EcError::CoordinatesOutOfRange,
183         bssl_sys::EC_R_D2I_ECPKPARAMETERS_FAILURE => EcError::D2IEcpkparametersFailure,
184         bssl_sys::EC_R_EC_GROUP_NEW_BY_NAME_FAILURE => EcError::EcGroupNewByNameFailure,
185         bssl_sys::EC_R_GROUP2PKPARAMETERS_FAILURE => EcError::Group2PkparametersFailure,
186         bssl_sys::EC_R_I2D_ECPKPARAMETERS_FAILURE => EcError::I2DEcpkparametersFailure,
187         bssl_sys::EC_R_INCOMPATIBLE_OBJECTS => EcError::IncompatibleObjects,
188         bssl_sys::EC_R_INVALID_COMPRESSED_POINT => EcError::InvalidCompressedPoint,
189         bssl_sys::EC_R_INVALID_COMPRESSION_BIT => EcError::InvalidCompressionBit,
190         bssl_sys::EC_R_INVALID_ENCODING => EcError::InvalidEncoding,
191         bssl_sys::EC_R_INVALID_FIELD => EcError::InvalidField,
192         bssl_sys::EC_R_INVALID_FORM => EcError::InvalidForm,
193         bssl_sys::EC_R_INVALID_GROUP_ORDER => EcError::InvalidGroupOrder,
194         bssl_sys::EC_R_INVALID_PRIVATE_KEY => EcError::InvalidPrivateKey,
195         bssl_sys::EC_R_MISSING_PARAMETERS => EcError::MissingParameters,
196         bssl_sys::EC_R_MISSING_PRIVATE_KEY => EcError::MissingPrivateKey,
197         bssl_sys::EC_R_NON_NAMED_CURVE => EcError::NonNamedCurve,
198         bssl_sys::EC_R_NOT_INITIALIZED => EcError::NotInitialized,
199         bssl_sys::EC_R_PKPARAMETERS2GROUP_FAILURE => EcError::Pkparameters2GroupFailure,
200         bssl_sys::EC_R_POINT_AT_INFINITY => EcError::PointAtInfinity,
201         bssl_sys::EC_R_POINT_IS_NOT_ON_CURVE => EcError::PointIsNotOnCurve,
202         bssl_sys::EC_R_SLOT_FULL => EcError::SlotFull,
203         bssl_sys::EC_R_UNDEFINED_GENERATOR => EcError::UndefinedGenerator,
204         bssl_sys::EC_R_UNKNOWN_GROUP => EcError::UnknownGroup,
205         bssl_sys::EC_R_UNKNOWN_ORDER => EcError::UnknownOrder,
206         bssl_sys::EC_R_WRONG_ORDER => EcError::WrongOrder,
207         bssl_sys::EC_R_BIGNUM_OUT_OF_RANGE => EcError::BignumOutOfRange,
208         bssl_sys::EC_R_WRONG_CURVE_PARAMETERS => EcError::WrongCurveParameters,
209         bssl_sys::EC_R_DECODE_ERROR => EcError::DecodeError,
210         bssl_sys::EC_R_ENCODE_ERROR => EcError::EncodeError,
211         bssl_sys::EC_R_GROUP_MISMATCH => EcError::GroupMismatch,
212         bssl_sys::EC_R_INVALID_COFACTOR => EcError::InvalidCofactor,
213         bssl_sys::EC_R_PUBLIC_KEY_VALIDATION_FAILED => EcError::PublicKeyValidationFailed,
214         bssl_sys::EC_R_INVALID_SCALAR => EcError::InvalidScalar,
215         _ => return None,
216     };
217     Some(error)
218 }
219 
map_ecdsa_reason_code(reason: i32) -> Option<EcdsaError>220 fn map_ecdsa_reason_code(reason: i32) -> Option<EcdsaError> {
221     let error = match reason {
222         bssl_sys::ECDSA_R_BAD_SIGNATURE => EcdsaError::BadSignature,
223         bssl_sys::ECDSA_R_MISSING_PARAMETERS => EcdsaError::MissingParameters,
224         bssl_sys::ECDSA_R_NEED_NEW_SETUP_VALUES => EcdsaError::NeedNewSetupValues,
225         bssl_sys::ECDSA_R_NOT_IMPLEMENTED => EcdsaError::NotImplemented,
226         bssl_sys::ECDSA_R_RANDOM_NUMBER_GENERATION_FAILED => {
227             EcdsaError::RandomNumberGenerationFailed
228         }
229         bssl_sys::ECDSA_R_ENCODE_ERROR => EcdsaError::EncodeError,
230         bssl_sys::ECDSA_R_TOO_MANY_ITERATIONS => EcdsaError::TooManyIterations,
231         _ => return None,
232     };
233     Some(error)
234 }
235