Skip to main content

optee_utee/
error.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18#[cfg(not(feature = "std"))]
19use core::error;
20use core::{fmt, result};
21use num_enum::{FromPrimitive, IntoPrimitive};
22use optee_utee_sys as raw;
23#[cfg(feature = "std")]
24use std::error;
25
26/// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html)
27/// type for TEE operations.
28///
29/// # Examples
30///
31/// ``` rust,no_run
32/// # use optee_utee::prelude::*;
33/// use optee_utee::Result;
34/// fn open_session(params: &mut ParametersAny) -> Result<()> {
35///     Ok(())
36/// }
37/// ````
38pub type Result<T> = result::Result<T, Error>;
39
40/// Checks the result of a TEE API call, converting a non-success code into
41/// [`Error`].
42pub(crate) fn tee_check(code: raw::TEE_Result) -> Result<()> {
43    match code {
44        raw::TEE_SUCCESS => Ok(()),
45        code => Err(Error::from_raw_error(code)),
46    }
47}
48
49/// Like [`tee_check`], but attaches the error origin returned by the TEE API
50/// on failure.
51pub(crate) fn tee_check_with_origin(code: raw::TEE_Result, origin: u32) -> Result<()> {
52    match code {
53        raw::TEE_SUCCESS => Ok(()),
54        code => Err(Error::from_raw_error(code).with_origin(origin.into())),
55    }
56}
57
58#[derive(Clone)]
59pub struct Error {
60    kind: ErrorKind,
61    origin: Option<ErrorOrigin>,
62}
63
64/// A list specifying general categories of TEE error and its corresponding code
65/// in OP-TEE OS.
66///
67/// Unrecognized codes are preserved in the `Unknown` catch-all variant, so
68/// `raw_code()` always round-trips the value passed to
69/// [`Error::from_raw_error`].
70#[derive(
71    Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, FromPrimitive, IntoPrimitive,
72)]
73#[repr(u32)]
74pub enum ErrorKind {
75    /// Object corruption.
76    CorruptObject = raw::TEE_ERROR_CORRUPT_OBJECT,
77    /// Persistent object corruption.
78    CorruptObject2 = raw::TEE_ERROR_CORRUPT_OBJECT_2,
79    /// Object storage is not available.
80    StorageNotAvailable = raw::TEE_ERROR_STORAGE_NOT_AVAILABLE,
81    /// Persistent object storage is not available.
82    StorageNotAvailable2 = raw::TEE_ERROR_STORAGE_NOT_AVAILABLE_2,
83    /// Non-specific cause.
84    Generic = raw::TEE_ERROR_GENERIC,
85    /// Access privileges are not sufficient.
86    AccessDenied = raw::TEE_ERROR_ACCESS_DENIED,
87    /// The operation was canceled.
88    Cancel = raw::TEE_ERROR_CANCEL,
89    /// Concurrent accesses caused conflict.
90    AccessConflict = raw::TEE_ERROR_ACCESS_CONFLICT,
91    /// Too much data for the requested operation was passed.
92    ExcessData = raw::TEE_ERROR_EXCESS_DATA,
93    /// Input data was of invalid format.
94    BadFormat = raw::TEE_ERROR_BAD_FORMAT,
95    /// Input parameters were invalid.
96    BadParameters = raw::TEE_ERROR_BAD_PARAMETERS,
97    /// Operation is not valid in the current state.
98    BadState = raw::TEE_ERROR_BAD_STATE,
99    /// The requested data item is not found.
100    ItemNotFound = raw::TEE_ERROR_ITEM_NOT_FOUND,
101    /// The requested operation should exist but is not yet implemented.
102    NotImplemented = raw::TEE_ERROR_NOT_IMPLEMENTED,
103    /// The requested operation is valid but is not supported in this implementation.
104    NotSupported = raw::TEE_ERROR_NOT_SUPPORTED,
105    /// Expected data was missing.
106    NoData = raw::TEE_ERROR_NO_DATA,
107    /// System ran out of resources.
108    OutOfMemory = raw::TEE_ERROR_OUT_OF_MEMORY,
109    /// The system is busy working on something else.
110    Busy = raw::TEE_ERROR_BUSY,
111    /// Communication with a remote party failed.
112    Communication = raw::TEE_ERROR_COMMUNICATION,
113    /// A security fault was detected.
114    Security = raw::TEE_ERROR_SECURITY,
115    /// The supplied buffer is too short for the generated output.
116    ShortBuffer = raw::TEE_ERROR_SHORT_BUFFER,
117    /// The operation has been cancelled by an external event which occurred in
118    /// the REE while the function was in progress.
119    ExternalCancel = raw::TEE_ERROR_EXTERNAL_CANCEL,
120    /// Data overflow.
121    Overflow = raw::TEE_ERROR_OVERFLOW,
122    /// Trusted Application has panicked during the operation.
123    TargetDead = raw::TEE_ERROR_TARGET_DEAD,
124    /// Insufficient space is available.
125    StorageNoSpace = raw::TEE_ERROR_STORAGE_NO_SPACE,
126    /// MAC is invalid.
127    MacInvalid = raw::TEE_ERROR_MAC_INVALID,
128    /// Signature is invalid.
129    SignatureInvalid = raw::TEE_ERROR_SIGNATURE_INVALID,
130    /// The persistent time has not been set.
131    TimeNotSet = raw::TEE_ERROR_TIME_NOT_SET,
132    /// The persistent time has been set but may have been corrupted and SHALL
133    /// no longer be trusted.
134    TimeNeedsReset = raw::TEE_ERROR_TIME_NEEDS_RESET,
135    /// Unknown error, holding the original raw code.
136    #[num_enum(catch_all)]
137    Unknown(u32),
138}
139
140impl ErrorKind {
141    pub(crate) fn as_str(&self) -> &'static str {
142        match *self {
143            ErrorKind::CorruptObject => "Object corruption.",
144            ErrorKind::CorruptObject2 => "Persistent object corruption.",
145            ErrorKind::StorageNotAvailable => "Object storage is not available.",
146            ErrorKind::StorageNotAvailable2 => "Persistent object storage is not available.",
147            ErrorKind::Generic => "Non-specific cause.",
148            ErrorKind::AccessDenied => "Access privileges are not sufficient.",
149            ErrorKind::Cancel => "The operation was canceled.",
150            ErrorKind::AccessConflict => "Concurrent accesses caused conflict.",
151            ErrorKind::ExcessData => "Too much data for the requested operation was passed.",
152            ErrorKind::BadFormat => "Input data was of invalid format.",
153            ErrorKind::BadParameters => "Input parameters were invalid.",
154            ErrorKind::BadState => "Operation is not valid in the current state.",
155            ErrorKind::ItemNotFound => "The requested data item is not found.",
156            ErrorKind::NotImplemented => {
157                "The requested operation should exist but is not yet implemented."
158            }
159            ErrorKind::NotSupported => {
160                "The requested operation is valid but is not supported in this implementation."
161            }
162            ErrorKind::NoData => "Expected data was missing.",
163            ErrorKind::OutOfMemory => "System ran out of resources.",
164            ErrorKind::Busy => "The system is busy working on something else.",
165            ErrorKind::Communication => "Communication with a remote party failed.",
166            ErrorKind::Security => "A security fault was detected.",
167            ErrorKind::ShortBuffer => "The supplied buffer is too short for the generated output.",
168            ErrorKind::ExternalCancel => "Undocumented.",
169            ErrorKind::Overflow => "Data overflow.",
170            ErrorKind::TargetDead => "Trusted Application has panicked during the operation.",
171            ErrorKind::StorageNoSpace => "Insufficient space is available.",
172            ErrorKind::MacInvalid => "MAC is invalid.",
173            ErrorKind::SignatureInvalid => "Signature is invalid.",
174            ErrorKind::TimeNotSet => "The persistent time has not been set.",
175            ErrorKind::TimeNeedsReset => {
176                "The persistent time has been set but may have been corrupted and SHALL no longer be trusted."
177            }
178            ErrorKind::Unknown(_) => "Unknown error.",
179        }
180    }
181}
182
183impl Error {
184    pub fn new(kind: ErrorKind) -> Error {
185        kind.into()
186    }
187
188    /// Creates a new instance of an `Error` from a particular TEE error code.
189    ///
190    /// # Examples
191    ///
192    /// ``` no_run
193    /// use optee_utee;
194    ///
195    /// let error = optee_utee::Error::from_raw_error(0xFFFF000F);
196    /// assert_eq!(error.kind(), optee_utee::ErrorKind::Security);
197    /// ```
198    pub fn from_raw_error(code: u32) -> Error {
199        ErrorKind::from(code).into()
200    }
201
202    pub fn with_origin(mut self, origin: ErrorOrigin) -> Self {
203        self.origin = Some(origin);
204        self
205    }
206
207    /// Returns the corresponding `ErrorKind` for this error.
208    ///
209    /// # Examples
210    ///
211    /// ``` no_run
212    /// use optee_utee;
213    ///
214    /// let error = optee_utee::Error::new(optee_utee::ErrorKind::Security);
215    /// ```
216    pub fn kind(&self) -> ErrorKind {
217        self.kind
218    }
219
220    /// Returns the origin of this error.
221    pub fn origin(&self) -> Option<ErrorOrigin> {
222        self.origin.clone()
223    }
224
225    /// Returns raw code of this error.
226    pub fn raw_code(&self) -> u32 {
227        self.kind.into()
228    }
229
230    /// Returns corresponding error message of this error.
231    pub fn message(&self) -> &str {
232        self.kind().as_str()
233    }
234}
235
236impl fmt::Debug for Error {
237    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
238        write!(
239            fmt,
240            "{} (error code 0x{:x}, origin 0x{:x})",
241            self.message(),
242            self.raw_code(),
243            self.origin().map(|v| v.into()).unwrap_or(0_u32),
244        )
245    }
246}
247
248impl fmt::Display for Error {
249    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
250        fmt::Debug::fmt(self, f)
251    }
252}
253
254impl error::Error for Error {
255    fn description(&self) -> &str {
256        self.message()
257    }
258}
259
260impl From<ErrorKind> for Error {
261    #[inline]
262    fn from(kind: ErrorKind) -> Error {
263        Error { kind, origin: None }
264    }
265}
266
267#[derive(Clone, Debug, Default, Eq, PartialEq)]
268#[repr(u32)]
269pub enum ErrorOrigin {
270    Api = raw::TEE_ORIGIN_API,
271    Comms = raw::TEE_ORIGIN_COMMS,
272    Tee = raw::TEE_ORIGIN_TEE,
273    Ta = raw::TEE_ORIGIN_TRUSTED_APP,
274    #[default]
275    Unknown,
276}
277
278impl From<ErrorOrigin> for u32 {
279    fn from(origin: ErrorOrigin) -> u32 {
280        origin as u32
281    }
282}
283
284impl From<u32> for ErrorOrigin {
285    fn from(code: u32) -> ErrorOrigin {
286        match code {
287            raw::TEE_ORIGIN_API => ErrorOrigin::Api,
288            raw::TEE_ORIGIN_COMMS => ErrorOrigin::Comms,
289            raw::TEE_ORIGIN_TEE => ErrorOrigin::Tee,
290            raw::TEE_ORIGIN_TRUSTED_APP => ErrorOrigin::Ta,
291            _ => ErrorOrigin::Unknown,
292        }
293    }
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299
300    /// Guarantees: unrecognized codes are preserved in the catch-all variant
301    /// and round-trip through `Error`.
302    #[test]
303    fn unknown_raw_code_round_trips() {
304        let code = 0x1234_5678;
305        assert_eq!(ErrorKind::from(code), ErrorKind::Unknown(code));
306        let back: u32 = ErrorKind::Unknown(code).into();
307        assert_eq!(back, code);
308
309        let err = Error::from_raw_error(code);
310        assert_eq!(err.kind(), ErrorKind::Unknown(code));
311        assert_eq!(err.raw_code(), code);
312    }
313
314    /// Guarantees: known codes still map to their named variants.
315    #[test]
316    fn known_codes_still_map() {
317        assert_eq!(
318            ErrorKind::from(raw::TEE_ERROR_SECURITY),
319            ErrorKind::Security
320        );
321        let code: u32 = ErrorKind::Security.into();
322        assert_eq!(code, raw::TEE_ERROR_SECURITY);
323    }
324}