diff --git a/crates/optee-teec-build/src/plugin.rs b/crates/optee-teec-build/src/plugin.rs index c2d1f418..f4d1c273 100644 --- a/crates/optee-teec-build/src/plugin.rs +++ b/crates/optee-teec-build/src/plugin.rs @@ -85,9 +85,7 @@ impl PluginConfig { ) .to_string(); let out_path = self.get_out_path(); - if let Ok(v) = std::fs::read(&out_path) - && v.eq(codes.as_bytes()) - { + if std::fs::read(&out_path).is_ok_and(|v| v == codes.as_bytes()) { return Ok(()); } @@ -104,15 +102,10 @@ impl PluginConfig { /// Uses the custom destination if set, otherwise defaults to /// `$OUT_DIR/plugin_static.rs`. fn get_out_path(&self) -> PathBuf { - match self.dest.as_ref() { - Some(v) => v.clone(), - None => { - let out_dir = PathBuf::from( - std::env::var("OUT_DIR").expect("Infallible when using in build.rs"), - ); - out_dir.join("plugin_static.rs") - } - } + self.dest.clone().unwrap_or_else(|| { + PathBuf::from(std::env::var("OUT_DIR").expect("Infallible when using in build.rs")) + .join("plugin_static.rs") + }) } } diff --git a/crates/optee-teec-systest/build.rs b/crates/optee-teec-systest/build.rs index 367014a5..17e27d00 100644 --- a/crates/optee-teec-systest/build.rs +++ b/crates/optee-teec-systest/build.rs @@ -19,11 +19,7 @@ use std::{env, path::PathBuf}; fn main() { let mut cfg = ctest::TestGenerator::new(); - let path = { - let mut tmp = PathBuf::from(env::var("OPTEE_CLIENT_EXPORT").unwrap()); - tmp.push("usr/include"); - tmp - }; + let path = PathBuf::from(env::var("OPTEE_CLIENT_EXPORT").unwrap()).join("usr/include"); cfg.language(ctest::Language::C) .edition(2024) .target("aarch64-unknown-linux-gnu") diff --git a/crates/optee-teec/src/context.rs b/crates/optee-teec/src/context.rs index e33ceda3..4b5bc32b 100644 --- a/crates/optee-teec/src/context.rs +++ b/crates/optee-teec/src/context.rs @@ -15,7 +15,9 @@ // specific language governing permissions and limitations // under the License. -use crate::{ConnectionMethods, Error, Operation, Param, ParamNone, Result, Session, Uuid, raw}; +use crate::{ + ConnectionMethods, Operation, Param, ParamNone, Result, Session, Uuid, raw, teec_check, +}; use std::{cell::RefCell, ptr, rc::Rc}; pub struct InnerContext(pub raw::TEEC_Context); @@ -59,12 +61,10 @@ impl Context { // SAFETY: // raw_ctx is a C struct(TEEC_Context), which zero value is valid. let mut raw_ctx = unsafe { std::mem::zeroed() }; - match unsafe { raw::TEEC_InitializeContext(ptr::null_mut(), &mut raw_ctx) } { - raw::TEEC_SUCCESS => Ok(Self { - raw: Rc::new(RefCell::new(InnerContext(raw_ctx))), - }), - code => Err(Error::from_raw_error(code)), - } + teec_check(unsafe { raw::TEEC_InitializeContext(ptr::null_mut(), &mut raw_ctx) })?; + Ok(Self { + raw: Rc::new(RefCell::new(InnerContext(raw_ctx))), + }) } /// Opens a new session with the specified trusted application. @@ -87,12 +87,7 @@ impl Context { /// } /// ``` pub fn open_session(&mut self, uuid: Uuid) -> Result { - Session::new( - self, - uuid, - ConnectionMethods::LoginPublic, - None::<&mut Operation>, - ) + self.open_session_with_login(uuid, ConnectionMethods::LoginPublic) } pub fn open_session_with_login( diff --git a/crates/optee-teec/src/error.rs b/crates/optee-teec/src/error.rs index 0b6675d5..1ba28b8a 100644 --- a/crates/optee-teec/src/error.rs +++ b/crates/optee-teec/src/error.rs @@ -34,6 +34,24 @@ use std::fmt; /// ```` pub type Result = std::result::Result; +/// Checks the result of a TEE client API call, converting a non-success code +/// into [`Error`]. +pub(crate) fn teec_check(code: raw::TEEC_Result) -> Result<()> { + match code { + raw::TEEC_SUCCESS => Ok(()), + code => Err(Error::from_raw_error(code)), + } +} + +/// Like [`teec_check`], but attaches the error origin returned by the TEE +/// client API on failure. +pub(crate) fn teec_check_with_origin(code: raw::TEEC_Result, origin: u32) -> Result<()> { + match code { + raw::TEEC_SUCCESS => Ok(()), + code => Err(Error::from_raw_error(code).with_origin(origin.into())), + } +} + /// The error type for TEE operations of [`Context`] and [`Session`]. /// /// [`Context`]: struct.Context.html @@ -127,7 +145,7 @@ impl ErrorKind { impl Error { pub fn new(kind: ErrorKind) -> Error { - Error { kind, origin: None } + kind.into() } /// Creates a new instance of an `Error` from a particular TEE error code. /// @@ -140,10 +158,7 @@ impl Error { /// assert_eq!(error.kind(), ErrorKind::Security); /// ``` pub fn from_raw_error(code: u32) -> Error { - Error { - kind: ErrorKind::from(code), - origin: None, - } + ErrorKind::from(code).into() } pub fn with_origin(mut self, origin: ErrorOrigin) -> Self { diff --git a/crates/optee-teec/src/extension.rs b/crates/optee-teec/src/extension.rs index 1b28131e..fc217bf3 100644 --- a/crates/optee-teec/src/extension.rs +++ b/crates/optee-teec/src/extension.rs @@ -159,12 +159,8 @@ impl<'a, 'b> PluginParameters<'a, 'b> { if out_len > self.buf.len() { return Err(ErrorKind::BadParameters.into()); } - match self.out_len.as_mut() { - None => Err(ErrorKind::BadState.into()), - Some(v) => { - **v = out_len; - Ok(()) - } - } + let v = self.out_len.as_mut().ok_or(ErrorKind::BadState)?; + **v = out_len; + Ok(()) } } diff --git a/crates/optee-teec/src/lib.rs b/crates/optee-teec/src/lib.rs index 1b7f230f..b0fb8532 100644 --- a/crates/optee-teec/src/lib.rs +++ b/crates/optee-teec/src/lib.rs @@ -24,6 +24,7 @@ pub use self::context::Context; pub use self::error::{Error, ErrorKind, ErrorOrigin, Result}; +pub(crate) use self::error::{teec_check, teec_check_with_origin}; pub use self::extension::*; pub use self::operation::Operation; pub use self::parameter::{Param, ParamNone, ParamTmpRef, ParamType, ParamTypes, ParamValue}; diff --git a/crates/optee-teec/src/parameter.rs b/crates/optee-teec/src/parameter.rs index 34f9d940..77f139dd 100644 --- a/crates/optee-teec/src/parameter.rs +++ b/crates/optee-teec/src/parameter.rs @@ -74,8 +74,7 @@ pub struct ParamNone; impl Param for ParamNone { fn to_raw(&mut self) -> raw::TEEC_Parameter { - let raw: raw::TEEC_Parameter = unsafe { mem::zeroed() }; - raw + unsafe { mem::zeroed() } } fn param_type(&self) -> ParamType { diff --git a/crates/optee-teec/src/session.rs b/crates/optee-teec/src/session.rs index 02b6bc1c..ebf61c66 100644 --- a/crates/optee-teec/src/session.rs +++ b/crates/optee-teec/src/session.rs @@ -16,7 +16,7 @@ // under the License. use super::context::InnerContext; -use crate::{Context, Error, Operation, Param, Result, Uuid, raw}; +use crate::{Context, Operation, Param, Result, Uuid, raw, teec_check_with_origin}; use std::{cell::RefCell, ptr, rc::Rc}; /// Session login methods. @@ -66,31 +66,29 @@ impl Session { // block to maximize Rust's safety checks and leverage the compiler's // validation. let mut err_origin: u32 = 0; - let raw_operation = match operation { - Some(o) => o.as_mut_raw_ptr(), - None => ptr::null_mut(), - }; + let raw_operation = operation.map_or(ptr::null_mut(), |o| o.as_mut_raw_ptr()); let inner_ctx = context.inner_context(); let raw_ctx = &mut inner_ctx.borrow_mut().0; let raw_uuid = uuid.as_raw_ptr(); - match unsafe { - raw::TEEC_OpenSession( - raw_ctx, - &mut raw_session, - raw_uuid, - login as u32, - ptr::null(), - raw_operation, - &mut err_origin, - ) - } { - raw::TEEC_SUCCESS => Ok(Self { - raw: raw_session, - _ctx: context.inner_context(), - }), - code => Err(Error::from_raw_error(code).with_origin(err_origin.into())), - } + teec_check_with_origin( + unsafe { + raw::TEEC_OpenSession( + raw_ctx, + &mut raw_session, + raw_uuid, + login as u32, + ptr::null(), + raw_operation, + &mut err_origin, + ) + }, + err_origin, + )?; + Ok(Self { + raw: raw_session, + _ctx: context.inner_context(), + }) } /// Invokes a command with an operation with this session. @@ -100,17 +98,17 @@ impl Session { operation: &mut Operation, ) -> Result<()> { let mut err_origin: u32 = 0; - match unsafe { - raw::TEEC_InvokeCommand( - &mut self.raw, - command_id, - operation.as_mut_raw_ptr(), - &mut err_origin, - ) - } { - raw::TEEC_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code).with_origin(err_origin.into())), - } + teec_check_with_origin( + unsafe { + raw::TEEC_InvokeCommand( + &mut self.raw, + command_id, + operation.as_mut_raw_ptr(), + &mut err_origin, + ) + }, + err_origin, + ) } } diff --git a/crates/optee-utee-build/src/builder.rs b/crates/optee-utee-build/src/builder.rs index 25bf9970..4c6fd5d3 100644 --- a/crates/optee-utee-build/src/builder.rs +++ b/crates/optee-utee-build/src/builder.rs @@ -107,10 +107,11 @@ impl Builder { impl Builder { fn write_header_file(&self, out: PathBuf) -> Result<(), Error> { - let out_header_file_name = out.join(match self.header_file_name.as_ref() { - Some(v) => v.as_str(), - None => DEFAULT_HEADER_FILE_NAME, - }); + let out_header_file_name = out.join( + self.header_file_name + .as_deref() + .unwrap_or(DEFAULT_HEADER_FILE_NAME), + ); let mut buffer = File::create(out_header_file_name.clone())?; let header_codes = HeaderFileGenerator::new().generate(&self.ta_config)?; buffer.write_all(header_codes.as_bytes())?; diff --git a/crates/optee-utee/src/arithmetical.rs b/crates/optee-utee/src/arithmetical.rs index a1e5366e..b94d86c2 100644 --- a/crates/optee-utee/src/arithmetical.rs +++ b/crates/optee-utee/src/arithmetical.rs @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -use crate::{Error, Result}; +use crate::{Result, tee_check}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; use core::{cmp::max, fmt}; @@ -45,35 +45,28 @@ impl BigInt { } pub fn convert_from_octet_string(&mut self, buffer: &[u8], sign: i32) -> Result<()> { - match unsafe { + tee_check(unsafe { raw::TEE_BigIntConvertFromOctetString( self.0.as_mut_ptr(), buffer.as_ptr(), buffer.len(), sign, ) - } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + }) } pub fn convert_to_octet_string(&self) -> Result> { let mut buffer_size: usize = (self.0.len() - 2) * 4; let mut tmp_vec = vec![0u8; buffer_size]; - match unsafe { + tee_check(unsafe { raw::TEE_BigIntConvertToOctetString( tmp_vec.as_mut_ptr(), &mut buffer_size, self.data_ptr(), ) - } { - raw::TEE_SUCCESS => { - tmp_vec.truncate(buffer_size); - Ok(tmp_vec) - } - code => Err(Error::from_raw_error(code)), - } + })?; + tmp_vec.truncate(buffer_size); + Ok(tmp_vec) } pub fn convert_from_s32(&mut self, short_val: i32) { @@ -82,10 +75,8 @@ impl BigInt { pub fn convert_to_s32(&self) -> Result { let mut short_val: i32 = 0; - match unsafe { raw::TEE_BigIntConvertToS32(&mut short_val as _, self.data_ptr()) } { - raw::TEE_SUCCESS => Ok(short_val), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { raw::TEE_BigIntConvertToS32(&mut short_val as _, self.data_ptr()) })?; + Ok(short_val) } /* return negative number if self < target, @@ -114,19 +105,14 @@ impl BigInt { } pub fn set_bit(&mut self, bit_index: u32, set: bool) -> Result<()> { - match unsafe { raw::TEE_BigIntSetBit(self.0.as_mut_ptr(), bit_index, set) } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { raw::TEE_BigIntSetBit(self.0.as_mut_ptr(), bit_index, set) }) } pub fn abs(&self) -> Result { let bits = Self::get_bit_count(self); let mut res = Self::new(bits); - match unsafe { raw::TEE_BigIntAbs(res.0.as_mut_ptr(), self.data_ptr()) } { - raw::TEE_SUCCESS => Ok(res), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { raw::TEE_BigIntAbs(res.0.as_mut_ptr(), self.data_ptr()) })?; + Ok(res) } pub fn add(op1: &Self, op2: &Self) -> Self { @@ -238,7 +224,7 @@ impl BigInt { pub fn exp_mod(op1: &Self, op2: &Self, n: &Self, context: &BigIntFMMContext) -> Result { let mut res = Self::new(Self::get_bit_count(n)); - match unsafe { + tee_check(unsafe { raw::TEE_BigIntExpMod( res.0.as_mut_ptr(), op1.data_ptr(), @@ -246,10 +232,8 @@ impl BigInt { n.data_ptr(), context.data_ptr(), ) - } { - raw::TEE_SUCCESS => Ok(res), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(res) } pub fn relative_prime(op1: &Self, op2: &Self) -> bool { @@ -257,10 +241,7 @@ impl BigInt { } pub fn assign(&mut self, op2: &Self) -> Result<()> { - match unsafe { raw::TEE_BigIntAssign(self.0.as_mut_ptr(), op2.data_ptr()) } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { raw::TEE_BigIntAssign(self.0.as_mut_ptr(), op2.data_ptr()) }) } pub fn compute_extended_gcd(op1: &Self, op2: &Self) -> (Self, Self, Self) { diff --git a/crates/optee-utee/src/crypto_op.rs b/crates/optee-utee/src/crypto_op.rs index 0499926a..bda53d7f 100644 --- a/crates/optee-utee/src/crypto_op.rs +++ b/crates/optee-utee/src/crypto_op.rs @@ -20,7 +20,7 @@ use core::{mem, ptr}; use optee_utee_sys as raw; -use crate::{Attribute, Error, GenericObject, Result, TransientObject}; +use crate::{Attribute, GenericObject, Result, TransientObject, tee_check}; /// Specify one of the available cryptographic operations. #[repr(u32)] @@ -178,17 +178,15 @@ impl OperationHandle { fn allocate(algo: AlgorithmId, mode: OperationMode, max_key_size: usize) -> Result { let raw_handle: *mut raw::TEE_OperationHandle = Box::into_raw(Box::new(ptr::null_mut())); - match unsafe { + tee_check(unsafe { raw::TEE_AllocateOperation( raw_handle as *mut _, algo as u32, mode as u32, max_key_size as u32, ) - } { - raw::TEE_SUCCESS => Ok(Self::from_raw(raw_handle)), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(Self::from_raw(raw_handle)) } fn info(&self) -> OperationInfo { @@ -199,15 +197,13 @@ impl OperationHandle { fn info_multiple(&self, info_buf: &mut [u8]) -> Result { let mut tmp_size: usize = 0; - match unsafe { + tee_check(unsafe { raw::TEE_GetOperationInfoMultiple(self.handle(), info_buf.as_ptr() as _, &mut tmp_size) - } { - raw::TEE_SUCCESS => Ok(OperationInfoMultiple::from_raw( - info_buf.as_ptr() as _, - tmp_size, - )), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(OperationInfoMultiple::from_raw( + info_buf.as_ptr() as _, + tmp_size, + )) } fn reset(&mut self) { @@ -217,10 +213,7 @@ impl OperationHandle { } fn set_key(&self, object: &T) -> Result<()> { - match unsafe { raw::TEE_SetOperationKey(self.handle(), *object.as_raw_ref()) } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { raw::TEE_SetOperationKey(self.handle(), *object.as_raw_ref()) }) } fn set_key_2( @@ -228,12 +221,9 @@ impl OperationHandle { object1: &T, object2: &D, ) -> Result<()> { - match unsafe { + tee_check(unsafe { raw::TEE_SetOperationKey2(self.handle(), *object1.as_raw_ref(), *object2.as_raw_ref()) - } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + }) } fn copy(&mut self, src: &T) { @@ -245,10 +235,7 @@ impl OperationHandle { /// determine whether a combination of algId and element is supported pub fn is_algorithm_supported(alg_id: u32, element: u32) -> Result<()> { - match unsafe { raw::TEE_IsAlgorithmSupported(alg_id, element) } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { raw::TEE_IsAlgorithmSupported(alg_id, element) }) } // free before check it's not null @@ -343,7 +330,7 @@ impl Digest { //hash size is dynamic changed so we returned it's updated size pub fn do_final(&self, chunk: &[u8], hash: &mut [u8]) -> Result { let mut hash_size: usize = hash.len(); - match unsafe { + tee_check(unsafe { raw::TEE_DigestDoFinal( self.handle(), chunk.as_ptr() as _, @@ -351,10 +338,8 @@ impl Digest { hash.as_mut_ptr() as _, &mut hash_size, ) - } { - raw::TEE_SUCCESS => Ok(hash_size), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(hash_size) } /// Create a Digest operation without any specific algorithm or other data. @@ -628,7 +613,7 @@ impl Cipher { /// 4) If the Implementation detects any other error. pub fn update(&self, src: &[u8], dest: &mut [u8]) -> Result { let mut dest_size: usize = dest.len(); - match unsafe { + tee_check(unsafe { raw::TEE_CipherUpdate( self.handle(), src.as_ptr() as _, @@ -636,10 +621,8 @@ impl Cipher { dest.as_mut_ptr() as _, &mut dest_size, ) - } { - raw::TEE_SUCCESS => Ok(dest_size), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(dest_size) } /// Finalize the cipher operation, processing data that has not been processed by previous calls @@ -662,7 +645,7 @@ impl Cipher { /// 4) If the Implementation detects any other error. pub fn do_final(&self, src: &[u8], dest: &mut [u8]) -> Result { let mut dest_size: usize = dest.len(); - match unsafe { + tee_check(unsafe { raw::TEE_CipherDoFinal( self.handle(), src.as_ptr() as _, @@ -670,10 +653,8 @@ impl Cipher { dest.as_mut_ptr() as _, &mut dest_size, ) - } { - raw::TEE_SUCCESS => Ok(dest_size), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(dest_size) } /// Create a Cipher operation without any specific algorithm or other data. @@ -882,7 +863,7 @@ impl Mac { /// 5) If the Implementation detects any other error. pub fn compute_final(&self, message: &[u8], mac: &mut [u8]) -> Result { let mut mac_size: usize = mac.len(); - match unsafe { + tee_check(unsafe { raw::TEE_MACComputeFinal( self.handle(), message.as_ptr() as _, @@ -890,10 +871,8 @@ impl Mac { mac.as_mut_ptr() as _, &mut mac_size, ) - } { - raw::TEE_SUCCESS => Ok(mac_size), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(mac_size) } /// Finalize the MAC operation and compares the MAC with the buffer passed to the function. @@ -917,7 +896,7 @@ impl Mac { /// 4) Hardware or cryptographic algorithm failure. /// 5) If the Implementation detects any other error. pub fn compare_final(&self, message: &[u8], mac: &[u8]) -> Result<()> { - match unsafe { + tee_check(unsafe { raw::TEE_MACCompareFinal( self.handle(), message.as_ptr() as _, @@ -925,10 +904,7 @@ impl Mac { mac.as_ptr() as _, mac.len(), ) - } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + }) } /// Create a Mac operation without any specific algorithm or other data. @@ -1011,7 +987,7 @@ impl AE { aad_len: usize, pay_load_len: usize, ) -> Result<()> { - match unsafe { + tee_check(unsafe { raw::TEE_AEInit( self.handle(), nonce.as_ptr() as _, @@ -1020,10 +996,7 @@ impl AE { aad_len, pay_load_len, ) - } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + }) } /// Feed a new chunk of Additional Authentication Data (AAD) to the AE operation. @@ -1071,7 +1044,7 @@ impl AE { /// 6) If the Implementation detects any other error. pub fn update(&self, src: &[u8], dest: &mut [u8]) -> Result { let mut dest_size: usize = dest.len(); - match unsafe { + tee_check(unsafe { raw::TEE_AEUpdate( self.handle(), src.as_ptr() as _, @@ -1079,10 +1052,8 @@ impl AE { dest.as_mut_ptr() as _, &mut dest_size, ) - } { - raw::TEE_SUCCESS => Ok(dest_size), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(dest_size) } /// Process data that has not been processed by previous calls to [update](AE::update) as well as data supplied in `src`. /// It completes the AE operation and computes the tag. @@ -1155,7 +1126,7 @@ impl AE { ) -> Result<(usize, usize)> { let mut dest_size: usize = dest.len(); let mut tag_size: usize = tag.len(); - match unsafe { + tee_check(unsafe { raw::TEE_AEEncryptFinal( self.handle(), src.as_ptr() as _, @@ -1165,10 +1136,8 @@ impl AE { tag.as_mut_ptr() as _, &mut tag_size, ) - } { - raw::TEE_SUCCESS => Ok((dest_size, tag_size)), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok((dest_size, tag_size)) } /// Process data that has not been processed by previous calls to [update](AE::update) as well as data supplied in `src`. @@ -1196,7 +1165,7 @@ impl AE { /// 5) If the Implementation detects any other error. pub fn decrypt_final(&self, src: &[u8], dest: &mut [u8], tag: &[u8]) -> Result { let mut dest_size: usize = dest.len(); - match unsafe { + tee_check(unsafe { raw::TEE_AEDecryptFinal( self.handle(), src.as_ptr() as _, @@ -1206,10 +1175,8 @@ impl AE { tag.as_ptr() as _, tag.len(), ) - } { - raw::TEE_SUCCESS => Ok(dest_size), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(dest_size) } /// Create an AE operation without any specific algorithm or other data. @@ -1322,7 +1289,7 @@ impl Asymmetric { let p: Vec = params.iter().map(|p| p.raw()).collect(); let mut res_size: usize = self.info().key_size() as usize; let mut res_vec: Vec = vec![0u8; res_size]; - match unsafe { + tee_check(unsafe { raw::TEE_AsymmetricEncrypt( self.handle(), p.as_ptr() as _, @@ -1332,13 +1299,9 @@ impl Asymmetric { res_vec.as_mut_ptr() as _, &mut res_size, ) - } { - raw::TEE_SUCCESS => { - res_vec.truncate(res_size); - Ok(res_vec) - } - code => Err(Error::from_raw_error(code)), - } + })?; + res_vec.truncate(res_size); + Ok(res_vec) } /// Decrypt a message. @@ -1365,7 +1328,7 @@ impl Asymmetric { let p: Vec = params.iter().map(|p| p.raw()).collect(); let mut res_size: usize = self.info().key_size() as usize; let mut res_vec: Vec = vec![0u8; res_size]; - match unsafe { + tee_check(unsafe { raw::TEE_AsymmetricDecrypt( self.handle(), p.as_ptr() as _, @@ -1375,13 +1338,9 @@ impl Asymmetric { res_vec.as_mut_ptr() as _, &mut res_size, ) - } { - raw::TEE_SUCCESS => { - res_vec.truncate(res_size); - Ok(res_vec) - } - code => Err(Error::from_raw_error(code)), - } + })?; + res_vec.truncate(res_size); + Ok(res_vec) } /// Sign a message digest. @@ -1413,7 +1372,7 @@ impl Asymmetric { ) -> Result { let p: Vec = params.iter().map(|p| p.raw()).collect(); let mut signature_size: usize = signature.len(); - match unsafe { + tee_check(unsafe { raw::TEE_AsymmetricSignDigest( self.handle(), p.as_ptr() as _, @@ -1423,10 +1382,8 @@ impl Asymmetric { signature.as_mut_ptr() as _, &mut signature_size, ) - } { - raw::TEE_SUCCESS => Ok(signature_size), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(signature_size) } /// Verify a message digest. @@ -1457,7 +1414,7 @@ impl Asymmetric { signature: &[u8], ) -> Result<()> { let p: Vec = params.iter().map(|p| p.raw()).collect(); - match unsafe { + tee_check(unsafe { raw::TEE_AsymmetricVerifyDigest( self.handle(), p.as_ptr() as _, @@ -1467,10 +1424,7 @@ impl Asymmetric { signature.as_ptr() as _, signature.len(), ) - } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + }) } /// Create an Asymmetric operation without any specific algorithm or other data. diff --git a/crates/optee-utee/src/error.rs b/crates/optee-utee/src/error.rs index 749f542d..a40ce235 100644 --- a/crates/optee-utee/src/error.rs +++ b/crates/optee-utee/src/error.rs @@ -37,6 +37,24 @@ use std::error; /// ```` pub type Result = result::Result; +/// Checks the result of a TEE API call, converting a non-success code into +/// [`Error`]. +pub(crate) fn tee_check(code: raw::TEE_Result) -> Result<()> { + match code { + raw::TEE_SUCCESS => Ok(()), + code => Err(Error::from_raw_error(code)), + } +} + +/// Like [`tee_check`], but attaches the error origin returned by the TEE API +/// on failure. +pub(crate) fn tee_check_with_origin(code: raw::TEE_Result, origin: u32) -> Result<()> { + match code { + raw::TEE_SUCCESS => Ok(()), + code => Err(Error::from_raw_error(code).with_origin(origin.into())), + } +} + #[derive(Clone)] pub struct Error { kind: ErrorKind, @@ -164,7 +182,7 @@ impl ErrorKind { impl Error { pub fn new(kind: ErrorKind) -> Error { - Error { kind, origin: None } + kind.into() } /// Creates a new instance of an `Error` from a particular TEE error code. @@ -178,10 +196,7 @@ impl Error { /// assert_eq!(error.kind(), optee_utee::ErrorKind::Security); /// ``` pub fn from_raw_error(code: u32) -> Error { - Error { - kind: ErrorKind::from(code), - origin: None, - } + ErrorKind::from(code).into() } pub fn with_origin(mut self, origin: ErrorOrigin) -> Self { diff --git a/crates/optee-utee/src/extension.rs b/crates/optee-utee/src/extension.rs index 300af63e..105f2989 100644 --- a/crates/optee-utee/src/extension.rs +++ b/crates/optee-utee/src/extension.rs @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -use crate::{Error, ErrorKind, Result, Uuid}; +use crate::{ErrorKind, Result, Uuid, tee_check}; #[cfg(not(feature = "std"))] use alloc::{borrow::ToOwned, vec::Vec}; use optee_utee_sys as raw; @@ -135,7 +135,7 @@ impl<'a> LoadablePluginCommand<'a> { let mut outlen: usize = 0; let mut buffer = self.buffer; buffer.resize(buffer.capacity(), 0); // resize to capacity first - match unsafe { + tee_check(unsafe { raw::tee_invoke_supp_plugin( self.plugin.uuid.as_raw_ptr(), self.cmd_id, @@ -145,16 +145,12 @@ impl<'a> LoadablePluginCommand<'a> { buffer.len(), &mut outlen as *mut usize, ) - } { - raw::TEE_SUCCESS => { - if outlen > buffer.len() { - return Err(ErrorKind::ShortBuffer.into()); - } - buffer.resize(outlen, 0); - Ok(buffer) - } - code => Err(Error::from_raw_error(code)), + })?; + if outlen > buffer.len() { + return Err(ErrorKind::ShortBuffer.into()); } + buffer.resize(outlen, 0); + Ok(buffer) } } diff --git a/crates/optee-utee/src/lib.rs b/crates/optee-utee/src/lib.rs index d78102c1..4312b751 100644 --- a/crates/optee-utee/src/lib.rs +++ b/crates/optee-utee/src/lib.rs @@ -60,6 +60,7 @@ mod unwind_stubs { pub use arithmetical::*; pub use crypto_op::*; pub use error::{Error, ErrorKind, Result}; +pub(crate) use error::{tee_check, tee_check_with_origin}; pub use extension::*; pub use identity::{Identity, LoginType}; pub use object::*; diff --git a/crates/optee-utee/src/object/enum_handle.rs b/crates/optee-utee/src/object/enum_handle.rs index 81a94df0..c78d18f4 100644 --- a/crates/optee-utee/src/object/enum_handle.rs +++ b/crates/optee-utee/src/object/enum_handle.rs @@ -20,7 +20,7 @@ use alloc::boxed::Box; use optee_utee_sys as raw; use super::ObjectInfo; -use crate::{Error, Result}; +use crate::{Error, Result, tee_check}; // TODO: The examples and detailed function explanation will be added after we // test this struct and its functions. @@ -61,10 +61,7 @@ impl ObjectEnumHandle { /// [ObjectEnumHandle::get_next](crate::ObjectEnumHandle::get_next) /// repeatedly. pub fn start(&mut self, storage_id: u32) -> Result<()> { - match unsafe { raw::TEE_StartPersistentObjectEnumerator(*self.raw, storage_id) } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { raw::TEE_StartPersistentObjectEnumerator(*self.raw, storage_id) }) } /// Get the next object in an enumeration and returns information about the @@ -79,17 +76,15 @@ impl ObjectEnumHandle { Some(a) => &mut a.raw, None => core::ptr::null_mut(), }; - match unsafe { + tee_check(unsafe { raw::TEE_GetNextPersistentObject( *self.raw, object_info, object_id.as_mut_ptr() as _, &mut object_id_len, ) - } { - raw::TEE_SUCCESS => Ok(object_id_len as u32), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(object_id_len as u32) } } diff --git a/crates/optee-utee/src/object/generic_object.rs b/crates/optee-utee/src/object/generic_object.rs index ea16a8c5..244df2e0 100644 --- a/crates/optee-utee/src/object/generic_object.rs +++ b/crates/optee-utee/src/object/generic_object.rs @@ -18,7 +18,7 @@ use core::mem; use super::{AttributeId, ObjectInfo, UsageFlag}; -use crate::{Error, Result}; +use crate::{Result, tee_check}; use optee_utee_sys as raw; @@ -55,10 +55,8 @@ pub trait GenericObject { /// for this function. fn info(&self) -> Result { let mut raw_info: raw::TEE_ObjectInfo = unsafe { mem::zeroed() }; - match unsafe { raw::TEE_GetObjectInfo1(*self.as_raw_ref(), &mut raw_info) } { - raw::TEE_SUCCESS => Ok(ObjectInfo::from_raw(raw_info)), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { raw::TEE_GetObjectInfo1(*self.as_raw_ref(), &mut raw_info) })?; + Ok(ObjectInfo::from_raw(raw_info)) } /// Restrict the object usage flags of an object handle to contain at most @@ -81,10 +79,7 @@ pub trait GenericObject { /// function that is not explicitly associated with a defined return code /// for this function. fn restrict_usage(&mut self, obj_usage: UsageFlag) -> Result<()> { - match unsafe { raw::TEE_RestrictObjectUsage1(*self.as_raw_ref(), obj_usage.bits()) } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { raw::TEE_RestrictObjectUsage1(*self.as_raw_ref(), obj_usage.bits()) }) } /// Extract one buffer attribute from an object. The attribute is @@ -120,17 +115,15 @@ pub trait GenericObject { /// for this function. fn ref_attribute(&self, id: AttributeId, buffer: &mut [u8]) -> Result { let mut size = buffer.len(); - match unsafe { + tee_check(unsafe { raw::TEE_GetObjectBufferAttribute( *self.as_raw_ref(), id as u32, buffer as *mut _ as _, &mut size, ) - } { - raw::TEE_SUCCESS => Ok(size), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(size) } /// Extract one value attribute from an object. The attribute is identified @@ -167,16 +160,14 @@ pub trait GenericObject { fn value_attribute(&self, id: u32) -> Result<(u32, u32)> { let mut value_a: u32 = 0; let mut value_b: u32 = 0; - match unsafe { + tee_check(unsafe { raw::TEE_GetObjectValueAttribute( *self.as_raw_ref(), id, &mut value_a as *mut _, &mut value_b as *mut _, ) - } { - raw::TEE_SUCCESS => Ok((value_a, value_b)), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok((value_a, value_b)) } } diff --git a/crates/optee-utee/src/object/persistent_object.rs b/crates/optee-utee/src/object/persistent_object.rs index 991cb756..15a91731 100644 --- a/crates/optee-utee/src/object/persistent_object.rs +++ b/crates/optee-utee/src/object/persistent_object.rs @@ -19,7 +19,7 @@ use alloc::vec::Vec; use optee_utee_sys as raw; use super::{DataFlag, GenericObject, ObjectHandle, ObjectStorageConstants, Whence}; -use crate::{Error, ErrorKind, Result}; +use crate::{ErrorKind, Result, tee_check}; /// An object identified by an Object Identifier and including a Data Stream. /// @@ -89,7 +89,7 @@ impl PersistentObject { // Move as much code as possible out of unsafe blocks to maximize Rust’s // safety checks. let handle_mut = &mut handle; - match unsafe { + tee_check(unsafe { raw::TEE_OpenPersistentObject( storage_id as u32, object_id.as_ptr() as _, @@ -97,10 +97,8 @@ impl PersistentObject { flags.bits(), handle_mut, ) - } { - raw::TEE_SUCCESS => Ok(Self(ObjectHandle::from_raw(handle)?)), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(Self(ObjectHandle::from_raw(handle)?)) } /// Create an object with initial attributes and an initial data stream @@ -181,7 +179,7 @@ impl PersistentObject { Some(a) => unsafe { *a.as_raw_ref() }, None => core::ptr::null_mut(), }; - match unsafe { + tee_check(unsafe { raw::TEE_CreatePersistentObject( storage_id as u32, object_id.as_ptr() as _, @@ -192,10 +190,8 @@ impl PersistentObject { initial_data.len(), handle_mut, ) - } { - raw::TEE_SUCCESS => Ok(Self(ObjectHandle::from_raw(handle)?)), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(Self(ObjectHandle::from_raw(handle)?)) } /// Marks an object for deletion and closes the object. @@ -251,10 +247,8 @@ impl PersistentObject { /// # Ok(()) /// # } pub fn close_and_delete(self) -> Result<()> { - let result = match unsafe { raw::TEE_CloseAndDeletePersistentObject1(*self.as_raw_ref()) } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - }; + let result = + tee_check(unsafe { raw::TEE_CloseAndDeletePersistentObject1(*self.as_raw_ref()) }); // According to `GPD_TEE_Internal_Core_API_Specification_v1.3.1`: // At 5.7.4 TEE_CloseAndDeletePersistentObject1: // Deleting an object is atomic; once this function returns, the object @@ -313,16 +307,13 @@ impl PersistentObject { /// function which is not explicitly associated with a defined return /// code for this function. pub fn rename(&mut self, new_object_id: &[u8]) -> Result<()> { - match unsafe { + tee_check(unsafe { raw::TEE_RenamePersistentObject( *self.0.as_raw_ref(), new_object_id.as_ptr() as _, new_object_id.len(), ) - } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + }) } /// Read requested size from the data stream associate with the object into @@ -372,17 +363,15 @@ impl PersistentObject { /// code for this function. pub fn read(&mut self, buf: &mut [u8]) -> Result { let mut count: usize = 0; - match unsafe { + tee_check(unsafe { raw::TEE_ReadObjectData( *self.as_raw_ref(), buf.as_mut_ptr() as _, buf.len(), &mut count, ) - } { - raw::TEE_SUCCESS => Ok(count as u32), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(count as u32) } /// Reads the remaining data from the current cursor into a new TA-private vector. @@ -459,11 +448,9 @@ impl PersistentObject { /// function which is not explicitly associated with a defined return /// code for this function. pub fn write(&mut self, buf: &[u8]) -> Result<()> { - match unsafe { raw::TEE_WriteObjectData(*self.as_raw_ref(), buf.as_ptr() as _, buf.len()) } - { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { + raw::TEE_WriteObjectData(*self.as_raw_ref(), buf.as_ptr() as _, buf.len()) + }) } /// Change the size of a data stream associate with the object. @@ -505,10 +492,7 @@ impl PersistentObject { /// function which is not explicitly associated with a defined return /// code for this function. pub fn truncate(&mut self, size: u32) -> Result<()> { - match unsafe { raw::TEE_TruncateObjectData(*self.as_raw_ref(), size as usize) } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { raw::TEE_TruncateObjectData(*self.as_raw_ref(), size as usize) }) } /// Set the data position indicator associate with the object. @@ -554,10 +538,9 @@ impl PersistentObject { /// function which is not explicitly associated with a defined return /// code for this function. pub fn seek(&mut self, offset: i32, whence: Whence) -> Result<()> { - match unsafe { raw::TEE_SeekObjectData(*self.as_raw_ref(), offset.into(), whence.into()) } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { + raw::TEE_SeekObjectData(*self.as_raw_ref(), offset.into(), whence.into()) + }) } } diff --git a/crates/optee-utee/src/object/transient_object.rs b/crates/optee-utee/src/object/transient_object.rs index fbfbdfa8..71d655e0 100644 --- a/crates/optee-utee/src/object/transient_object.rs +++ b/crates/optee-utee/src/object/transient_object.rs @@ -20,7 +20,7 @@ use alloc::vec::Vec; use optee_utee_sys as raw; use super::{Attribute, GenericObject, ObjectHandle}; -use crate::{Error, Result}; +use crate::{Result, tee_check}; /// Define types of [TransientObject](crate::TransientObject) with /// predefined maximum sizes. @@ -177,12 +177,10 @@ impl TransientObject { // Move as much code as possible out of unsafe blocks to maximize Rust’s // safety checks. let handle_mut = &mut handle; - match unsafe { + tee_check(unsafe { raw::TEE_AllocateTransientObject(object_type as u32, max_object_size as u32, handle_mut) - } { - raw::TEE_SUCCESS => Ok(Self(ObjectHandle::from_raw(handle)?)), - code => Err(Error::from_raw_error(code)), - } + })?; + Ok(Self(ObjectHandle::from_raw(handle)?)) } /// Reset the object to its initial state after allocation. @@ -249,16 +247,13 @@ impl TransientObject { /// code for this function. pub fn populate(&mut self, attrs: &[Attribute]) -> Result<()> { let p: Vec = attrs.iter().map(|p| p.raw()).collect(); - match unsafe { + tee_check(unsafe { raw::TEE_PopulateTransientObject( *self.0.as_raw_ref(), p.as_ptr() as _, attrs.len() as u32, ) - } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + }) } /// Populates an uninitialized object handle with the attributes of another @@ -315,12 +310,9 @@ impl TransientObject { /// function which is not explicitly associated with a defined return /// code for this function. pub fn copy_attribute_from(&mut self, src_object: &T) -> Result<()> { - match unsafe { + tee_check(unsafe { raw::TEE_CopyObjectAttributes1(*self.as_raw_ref(), *src_object.as_raw_ref()) - } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + }) } /// Generates a random key or a key-pair and populates a transient key @@ -366,17 +358,14 @@ impl TransientObject { /// code for this function. pub fn generate_key(&self, key_size: usize, params: &[Attribute]) -> Result<()> { let p: Vec = params.iter().map(|p| p.raw()).collect(); - unsafe { - match raw::TEE_GenerateKey( + tee_check(unsafe { + raw::TEE_GenerateKey( *self.as_raw_ref(), key_size as u32, p.as_slice().as_ptr() as _, p.len() as u32, - ) { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } - } + ) + }) } } diff --git a/crates/optee-utee/src/property.rs b/crates/optee-utee/src/property.rs index 49153bd0..25303ce9 100644 --- a/crates/optee-utee/src/property.rs +++ b/crates/optee-utee/src/property.rs @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -use crate::{Error, ErrorKind, Result}; +use crate::{Error, ErrorKind, Result, tee_check}; use crate::{Identity, Uuid}; use alloc::{ffi::CString, string::String, vec::Vec}; use optee_utee_sys as raw; @@ -89,9 +89,7 @@ impl PropertyValue for String { &mut out_size, ) }; - if res != raw::TEE_SUCCESS { - return Err(Error::from_raw_error(res)); - } + tee_check(res)?; // Convert the char buffer with null terminator to a C string let c_str = core::ffi::CStr::from_bytes_with_nul(&out_buffer) @@ -111,9 +109,7 @@ impl PropertyValue for bool { let mut b: bool = false; let res = unsafe { raw::TEE_GetPropertyAsBool(set, key.as_ptr() as *const _, &mut b) }; - if res != 0 { - return Err(Error::from_raw_error(res)); - } + tee_check(res)?; Ok(b) } @@ -124,9 +120,7 @@ impl PropertyValue for u32 { let mut value = 0; let res = unsafe { raw::TEE_GetPropertyAsU32(set, key.as_ptr() as *const _, &mut value) }; - if res != 0 { - return Err(Error::from_raw_error(res)); - } + tee_check(res)?; Ok(value) } @@ -137,9 +131,7 @@ impl PropertyValue for u64 { let mut value = 0; let res = unsafe { raw::TEE_GetPropertyAsU64(set, key.as_ptr() as *const _, &mut value) }; - if res != 0 { - return Err(Error::from_raw_error(res)); - } + tee_check(res)?; Ok(value) } @@ -180,11 +172,8 @@ impl PropertyValue for Vec { &mut out_size, ) }; - if res != raw::TEE_SUCCESS { - Err(Error::from_raw_error(res)) - } else { - Ok(buf) - } + tee_check(res)?; + Ok(buf) } _ => Err(Error::from_raw_error(res)), } @@ -202,9 +191,7 @@ impl PropertyValue for Uuid { let res = unsafe { raw::TEE_GetPropertyAsUUID(set, key.as_ptr() as *const _, &mut raw_uuid) }; - if res != 0 { - return Err(Error::from_raw_error(res)); - } + tee_check(res)?; Ok(Uuid::from(raw_uuid)) } @@ -225,9 +212,7 @@ impl PropertyValue for Identity { let res = unsafe { raw::TEE_GetPropertyAsIdentity(set, key.as_ptr() as *const _, &mut raw_id) }; - if res != 0 { - return Err(Error::from_raw_error(res)); - } + tee_check(res)?; Ok(Identity::from(raw_id)) } diff --git a/crates/optee-utee/src/ta_session.rs b/crates/optee-utee/src/ta_session.rs index 4fa9ddac..6ef6e624 100644 --- a/crates/optee-utee/src/ta_session.rs +++ b/crates/optee-utee/src/ta_session.rs @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -use crate::{Error, Result, TeeParams, Uuid}; +use crate::{Result, TeeParams, Uuid, tee_check_with_origin}; use optee_utee_sys as raw; pub struct TaSessionBuilder<'a> { @@ -64,27 +64,26 @@ impl<'a> TaSessionBuilder<'a> { // raw_params.as_mut_ptr() provides a valid pointer to the parameters. // The remaining arguments are either valid values or null/mut pointers as expected by the C API. // For parameters that are intended to be modified by the call, the buffer constraints are checked later in update_from_raw(). - match unsafe { - raw::TEE_OpenTASession( - self.target_uuid.as_raw_ptr(), - self.timeout, - raw_param_types, - raw_params_ptr, - &mut raw_session, - &mut err_origin, - ) - } { - raw::TEE_SUCCESS => { - // From this point on, ensure every error path closes the opened session. - let session = TaSession { raw: raw_session }; - if let (Some(params), Some(raw_params)) = (&mut self.params, raw_params_opt) { - params.update_from_raw(&raw_params)?; - } - - Ok(session) - } - code => Err(Error::from_raw_error(code).with_origin(err_origin.into())), + tee_check_with_origin( + unsafe { + raw::TEE_OpenTASession( + self.target_uuid.as_raw_ptr(), + self.timeout, + raw_param_types, + raw_params_ptr, + &mut raw_session, + &mut err_origin, + ) + }, + err_origin, + )?; + // From this point on, ensure every error path closes the opened session. + let session = TaSession { raw: raw_session }; + if let (Some(params), Some(raw_params)) = (&mut self.params, raw_params_opt) { + params.update_from_raw(&raw_params)?; } + + Ok(session) } } @@ -114,23 +113,22 @@ impl TaSession { // raw_params.as_mut_ptr() yields a valid mutable pointer to the parameters array. // The remaining arguments are either valid values or null/mutable pointers, as expected by the C API. // For parameters that are intended to be modified by the call, the buffer constraints are checked later in update_from_raw(). - match unsafe { - raw::TEE_InvokeTACommand( - self.raw, - timeout, - command_id, - param_types, - raw_params.as_mut_ptr(), - &mut err_origin, - ) - } { - raw::TEE_SUCCESS => { - // Update the parameters with the results - params.update_from_raw(&raw_params)?; - Ok(()) - } - code => Err(Error::from_raw_error(code).with_origin(err_origin.into())), - } + tee_check_with_origin( + unsafe { + raw::TEE_InvokeTACommand( + self.raw, + timeout, + command_id, + param_types, + raw_params.as_mut_ptr(), + &mut err_origin, + ) + }, + err_origin, + )?; + // Update the parameters with the results + params.update_from_raw(&raw_params)?; + Ok(()) } } diff --git a/crates/optee-utee/src/time.rs b/crates/optee-utee/src/time.rs index 5dcd393f..10f61c11 100644 --- a/crates/optee-utee/src/time.rs +++ b/crates/optee-utee/src/time.rs @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -use crate::{Error, Result}; +use crate::{Result, tee_check}; use core::fmt; use optee_utee_sys as raw; @@ -90,10 +90,7 @@ impl Time { /// /// 1) If the Implementation detects any error. pub fn wait(timeout: u32) -> Result<()> { - match unsafe { raw::TEE_Wait(timeout) } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { raw::TEE_Wait(timeout) }) } /// Retrieve the persisten time of the Trusted Application. Since the timer is not @@ -125,10 +122,7 @@ impl Time { /// /// 1) If the Implementation detects any error. pub fn ta_time(&mut self) -> Result<()> { - match unsafe { raw::TEE_GetTAPersistentTime(self as *mut _ as _) } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { raw::TEE_GetTAPersistentTime(self as *mut _ as _) }) } /// Set the persistent time of the current Trusted Application. @@ -142,10 +136,7 @@ impl Time { /// /// 1) If the Implementation detects any error. pub fn set_ta_time(&self) -> Result<()> { - match unsafe { raw::TEE_SetTAPersistentTime(self as *const _ as _) } { - raw::TEE_SUCCESS => Ok(()), - code => Err(Error::from_raw_error(code)), - } + tee_check(unsafe { raw::TEE_SetTAPersistentTime(self as *const _ as _) }) } /// Retrieve the current REE system time. diff --git a/crates/rustls_provider/src/lib.rs b/crates/rustls_provider/src/lib.rs index 6c8ce3d5..8eab38a3 100644 --- a/crates/rustls_provider/src/lib.rs +++ b/crates/rustls_provider/src/lib.rs @@ -59,17 +59,11 @@ impl TimeProvider for ReeTimeProvider { let seconds = time.seconds as u64; let millis = time.millis as u64; - // Create UnixTime from seconds and milliseconds, check overflow - let total_millis = match seconds + // Create UnixTime from seconds and milliseconds, checking overflow + seconds .checked_mul(1000) .and_then(|ms| ms.checked_add(millis)) - { - Some(total) => total, - None => return None, // Return None if overflow occurs - }; - Some(UnixTime::since_unix_epoch(Duration::from_millis( - total_millis, - ))) + .map(|total| UnixTime::since_unix_epoch(Duration::from_millis(total))) } } diff --git a/crates/secure_db/src/db.rs b/crates/secure_db/src/db.rs index a5b08c68..47072df3 100644 --- a/crates/secure_db/src/db.rs +++ b/crates/secure_db/src/db.rs @@ -16,7 +16,7 @@ // under the License. use crate::{delete_from_secure_storage, load_from_secure_storage, save_in_secure_storage}; -use anyhow::{bail, ensure, Result}; +use anyhow::{anyhow, ensure, Result}; use hashbrown::HashSet; use std::collections::HashMap; @@ -32,62 +32,42 @@ pub struct SecureStorageDb { impl SecureStorageDb { pub fn open(name: String) -> Result { - match load_from_secure_storage(name.as_bytes())? { - Some(data) => { - let key_list = bincode::deserialize(&data)?; - Ok(Self { name, key_list }) - } + let key_list = match load_from_secure_storage(name.as_bytes())? { + Some(data) => bincode::deserialize(&data)?, None => { // create new db - Ok(Self { - name, - // Note: `std::collections::HashSet` was replaced with - // `hashbrown::HashSet`, due to a write permission fault - // observed during testing. The exact cause of the issue is - // unclear, but using `hashbrown::HashSet` resolves it. - key_list: HashSet::new(), - }) + // + // Note: `std::collections::HashSet` was replaced with + // `hashbrown::HashSet`, due to a write permission fault + // observed during testing. The exact cause of the issue is + // unclear, but using `hashbrown::HashSet` resolves it. + HashSet::new() } - } + }; + Ok(Self { name, key_list }) } pub fn put(&mut self, key: String, value: Vec) -> Result<()> { - match save_in_secure_storage(key.as_bytes(), &value) { - Ok(_) => { - self.key_list.insert(key); - self.store_key_list()?; - } - Err(e) => { - bail!("[+] SecureStorage::insert(): save error: {}", e); - } - }; - Ok(()) + save_in_secure_storage(key.as_bytes(), &value) + .map_err(|e| anyhow!("[+] SecureStorage::insert(): save error: {}", e))?; + self.key_list.insert(key); + self.store_key_list() } pub fn get(&self, key: &str) -> Result> { ensure!(self.key_list.contains(key), "Key not found in key list"); - match load_from_secure_storage(key.as_bytes()) { - Ok(Some(data)) => Ok(data), - Ok(None) => bail!("[+] SecureStorage::get(): object not found in db"), - Err(e) => { - bail!("[+] SecureStorage::get(): load error: {}", e); - } - } + load_from_secure_storage(key.as_bytes()) + .map_err(|e| anyhow!("[+] SecureStorage::get(): load error: {}", e))? + .ok_or_else(|| anyhow!("[+] SecureStorage::get(): object not found in db")) } pub fn delete(&mut self, key: &str) -> Result<()> { // ensure key must exist ensure!(self.key_list.contains(key), "Key not found in key list"); - match delete_from_secure_storage(key.as_bytes()) { - Ok(_) => { - self.key_list.remove(key); - self.store_key_list()?; - } - Err(e) => { - bail!("[+] SecureStorage::delete(): delete error: {}", e); - } - }; - Ok(()) + delete_from_secure_storage(key.as_bytes()) + .map_err(|e| anyhow!("[+] SecureStorage::delete(): delete error: {}", e))?; + self.key_list.remove(key); + self.store_key_list() } pub fn clear(&mut self) -> Result<()> {