1 // Copyright 2020, 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 //! Keystore error provides convenience methods and types for Keystore error handling.
16 //! Clients of Keystore expect one of two error codes, i.e., a Keystore ResponseCode as
17 //! defined by the Keystore AIDL interface, or a Keymint ErrorCode as defined by
18 //! the Keymint HAL specification.
19 //! This crate provides `Error` which can wrap both. It is to be used
20 //! internally by Keystore to diagnose error conditions that need to be reported to
21 //! the client. To report the error condition to the client the Keystore AIDL
22 //! interface defines a wire type `Result` which is distinctly different from Rust's
23 //! `enum Result<T,E>`.
24 //!
25 //! This crate provides the convenience method `map_or_log_err` to convert `anyhow::Error`
26 //! into this wire type. In addition to handling the conversion of `Error`
27 //! to the `Result` wire type it handles any other error by mapping it to
28 //! `ResponseCode::SYSTEM_ERROR` and logs any error condition.
29 //!
30 //! Keystore functions should use `anyhow::Result` to return error conditions, and
31 //! context should be added every time an error is forwarded.
32 
33 pub use android_hardware_security_keymint::aidl::android::hardware::security::keymint::ErrorCode::ErrorCode;
34 pub use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode;
35 use android_system_keystore2::binder::{
36     ExceptionCode, Result as BinderResult, Status as BinderStatus, StatusCode,
37 };
38 use keystore2_selinux as selinux;
39 use std::cmp::PartialEq;
40 
41 /// This is the main Keystore error type. It wraps the Keystore `ResponseCode` generated
42 /// from AIDL in the `Rc` variant and Keymint `ErrorCode` in the Km variant.
43 #[derive(Debug, thiserror::Error, PartialEq)]
44 pub enum Error {
45     /// Wraps a Keystore `ResponseCode` as defined by the Keystore AIDL interface specification.
46     #[error("Error::Rc({0:?})")]
47     Rc(ResponseCode),
48     /// Wraps a Keymint `ErrorCode` as defined by the Keymint AIDL interface specification.
49     #[error("Error::Km({0:?})")]
50     Km(ErrorCode),
51     /// Wraps a Binder exception code other than a service specific exception.
52     #[error("Binder exception code {0:?}, {1:?}")]
53     Binder(ExceptionCode, i32),
54     /// Wraps a Binder status code.
55     #[error("Binder transaction error {0:?}")]
56     BinderTransaction(StatusCode),
57     /// Wraps a Remote Provisioning ErrorCode as defined by the IRemotelyProvisionedComponent
58     /// AIDL interface spec.
59     #[error("Error::Rp({0:?})")]
60     Rp(ErrorCode),
61 }
62 
63 impl Error {
64     /// Short hand for `Error::Rc(ResponseCode::SYSTEM_ERROR)`
sys() -> Self65     pub fn sys() -> Self {
66         Error::Rc(ResponseCode::SYSTEM_ERROR)
67     }
68 
69     /// Short hand for `Error::Rc(ResponseCode::PERMISSION_DENIED`
perm() -> Self70     pub fn perm() -> Self {
71         Error::Rc(ResponseCode::PERMISSION_DENIED)
72     }
73 }
74 
75 /// Helper function to map the binder status we get from calls into KeyMint
76 /// to a Keystore Error. We don't create an anyhow error here to make
77 /// it easier to evaluate KeyMint errors, which we must do in some cases, e.g.,
78 /// when diagnosing authentication requirements, update requirements, and running
79 /// out of operation slots.
map_km_error<T>(r: BinderResult<T>) -> Result<T, Error>80 pub fn map_km_error<T>(r: BinderResult<T>) -> Result<T, Error> {
81     r.map_err(|s| {
82         match s.exception_code() {
83             ExceptionCode::SERVICE_SPECIFIC => {
84                 let se = s.service_specific_error();
85                 if se < 0 {
86                     // Negative service specific errors are KM error codes.
87                     Error::Km(ErrorCode(s.service_specific_error()))
88                 } else {
89                     // Non negative error codes cannot be KM error codes.
90                     // So we create an `Error::Binder` variant to preserve
91                     // the service specific error code for logging.
92                     // `map_or_log_err` will map this on a system error,
93                     // but not before logging the details to logcat.
94                     Error::Binder(ExceptionCode::SERVICE_SPECIFIC, se)
95                 }
96             }
97             // We create `Error::Binder` to preserve the exception code
98             // for logging.
99             // `map_or_log_err` will map this on a system error.
100             e_code => Error::Binder(e_code, 0),
101         }
102     })
103 }
104 
105 /// Helper function to map the binder status we get from calls into a RemotelyProvisionedComponent
106 /// to a Keystore Error. We don't create an anyhow error here to make
107 /// it easier to evaluate service specific errors.
map_rem_prov_error<T>(r: BinderResult<T>) -> Result<T, Error>108 pub fn map_rem_prov_error<T>(r: BinderResult<T>) -> Result<T, Error> {
109     r.map_err(|s| match s.exception_code() {
110         ExceptionCode::SERVICE_SPECIFIC => Error::Rp(ErrorCode(s.service_specific_error())),
111         e_code => Error::Binder(e_code, 0),
112     })
113 }
114 
115 /// This function is similar to map_km_error only that we don't expect
116 /// any KeyMint error codes, we simply preserve the exception code and optional
117 /// service specific exception.
map_binder_status<T>(r: BinderResult<T>) -> Result<T, Error>118 pub fn map_binder_status<T>(r: BinderResult<T>) -> Result<T, Error> {
119     r.map_err(|s| match s.exception_code() {
120         ExceptionCode::SERVICE_SPECIFIC => {
121             let se = s.service_specific_error();
122             Error::Binder(ExceptionCode::SERVICE_SPECIFIC, se)
123         }
124         ExceptionCode::TRANSACTION_FAILED => {
125             let e = s.transaction_error();
126             Error::BinderTransaction(e)
127         }
128         e_code => Error::Binder(e_code, 0),
129     })
130 }
131 
132 /// This function maps a status code onto a Keystore Error.
map_binder_status_code<T>(r: Result<T, StatusCode>) -> Result<T, Error>133 pub fn map_binder_status_code<T>(r: Result<T, StatusCode>) -> Result<T, Error> {
134     r.map_err(Error::BinderTransaction)
135 }
136 
137 /// This function should be used by Keystore service calls to translate error conditions
138 /// into service specific exceptions.
139 ///
140 /// All error conditions get logged by this function, except for KEY_NOT_FOUND error.
141 ///
142 /// All `Error::Rc(x)` and `Error::Km(x)` variants get mapped onto a service specific error
143 /// code of x. This is possible because KeyMint `ErrorCode` errors are always negative and
144 /// `ResponseCode` codes are always positive.
145 /// `selinux::Error::PermissionDenied` is mapped on `ResponseCode::PERMISSION_DENIED`.
146 ///
147 /// All non `Error` error conditions and the Error::Binder variant get mapped onto
148 /// ResponseCode::SYSTEM_ERROR`.
149 ///
150 /// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
151 /// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
152 /// typically returns Ok(value).
153 ///
154 /// # Examples
155 ///
156 /// ```
157 /// fn loadKey() -> anyhow::Result<Vec<u8>> {
158 ///     if (good_but_auth_required) {
159 ///         Ok(vec!['k', 'e', 'y'])
160 ///     } else {
161 ///         Err(anyhow!(Error::Rc(ResponseCode::KEY_NOT_FOUND)))
162 ///     }
163 /// }
164 ///
165 /// map_or_log_err(loadKey(), Ok)
166 /// ```
map_or_log_err<T, U, F>(result: anyhow::Result<U>, handle_ok: F) -> BinderResult<T> where F: FnOnce(U) -> BinderResult<T>,167 pub fn map_or_log_err<T, U, F>(result: anyhow::Result<U>, handle_ok: F) -> BinderResult<T>
168 where
169     F: FnOnce(U) -> BinderResult<T>,
170 {
171     map_err_with(
172         result,
173         |e| {
174             // Make the key not found errors silent.
175             if !matches!(
176                 e.root_cause().downcast_ref::<Error>(),
177                 Some(Error::Rc(ResponseCode::KEY_NOT_FOUND))
178             ) {
179                 log::error!("{:?}", e);
180             }
181             e
182         },
183         handle_ok,
184     )
185 }
186 
187 /// This function behaves similar to map_or_log_error, but it does not log the errors, instead
188 /// it calls map_err on the error before mapping it to a binder result allowing callers to
189 /// log or transform the error before mapping it.
map_err_with<T, U, F1, F2>( result: anyhow::Result<U>, map_err: F1, handle_ok: F2, ) -> BinderResult<T> where F1: FnOnce(anyhow::Error) -> anyhow::Error, F2: FnOnce(U) -> BinderResult<T>,190 pub fn map_err_with<T, U, F1, F2>(
191     result: anyhow::Result<U>,
192     map_err: F1,
193     handle_ok: F2,
194 ) -> BinderResult<T>
195 where
196     F1: FnOnce(anyhow::Error) -> anyhow::Error,
197     F2: FnOnce(U) -> BinderResult<T>,
198 {
199     result.map_or_else(
200         |e| {
201             let e = map_err(e);
202             let rc = get_error_code(&e);
203             Err(BinderStatus::new_service_specific_error(rc, None))
204         },
205         handle_ok,
206     )
207 }
208 
209 /// Returns the error code given a reference to the error
get_error_code(e: &anyhow::Error) -> i32210 pub fn get_error_code(e: &anyhow::Error) -> i32 {
211     let root_cause = e.root_cause();
212     match root_cause.downcast_ref::<Error>() {
213         Some(Error::Rc(rcode)) => rcode.0,
214         Some(Error::Km(ec)) => ec.0,
215         Some(Error::Rp(_)) => ResponseCode::SYSTEM_ERROR.0,
216         // If an Error::Binder reaches this stage we report a system error.
217         // The exception code and possible service specific error will be
218         // printed in the error log above.
219         Some(Error::Binder(_, _)) | Some(Error::BinderTransaction(_)) => {
220             ResponseCode::SYSTEM_ERROR.0
221         }
222         None => match root_cause.downcast_ref::<selinux::Error>() {
223             Some(selinux::Error::PermissionDenied) => ResponseCode::PERMISSION_DENIED.0,
224             _ => ResponseCode::SYSTEM_ERROR.0,
225         },
226     }
227 }
228 
229 #[cfg(test)]
230 pub mod tests {
231 
232     use super::*;
233     use android_system_keystore2::binder::{
234         ExceptionCode, Result as BinderResult, Status as BinderStatus,
235     };
236     use anyhow::{anyhow, Context};
237 
nested_nested_rc(rc: ResponseCode) -> anyhow::Result<()>238     fn nested_nested_rc(rc: ResponseCode) -> anyhow::Result<()> {
239         Err(anyhow!(Error::Rc(rc))).context("nested nested rc")
240     }
241 
nested_rc(rc: ResponseCode) -> anyhow::Result<()>242     fn nested_rc(rc: ResponseCode) -> anyhow::Result<()> {
243         nested_nested_rc(rc).context("nested rc")
244     }
245 
nested_nested_ec(ec: ErrorCode) -> anyhow::Result<()>246     fn nested_nested_ec(ec: ErrorCode) -> anyhow::Result<()> {
247         Err(anyhow!(Error::Km(ec))).context("nested nested ec")
248     }
249 
nested_ec(ec: ErrorCode) -> anyhow::Result<()>250     fn nested_ec(ec: ErrorCode) -> anyhow::Result<()> {
251         nested_nested_ec(ec).context("nested ec")
252     }
253 
nested_nested_ok(rc: ResponseCode) -> anyhow::Result<ResponseCode>254     fn nested_nested_ok(rc: ResponseCode) -> anyhow::Result<ResponseCode> {
255         Ok(rc)
256     }
257 
nested_ok(rc: ResponseCode) -> anyhow::Result<ResponseCode>258     fn nested_ok(rc: ResponseCode) -> anyhow::Result<ResponseCode> {
259         nested_nested_ok(rc).context("nested ok")
260     }
261 
nested_nested_selinux_perm() -> anyhow::Result<()>262     fn nested_nested_selinux_perm() -> anyhow::Result<()> {
263         Err(anyhow!(selinux::Error::perm())).context("nested nexted selinux permission denied")
264     }
265 
nested_selinux_perm() -> anyhow::Result<()>266     fn nested_selinux_perm() -> anyhow::Result<()> {
267         nested_nested_selinux_perm().context("nested selinux permission denied")
268     }
269 
270     #[derive(Debug, thiserror::Error)]
271     enum TestError {
272         #[error("TestError::Fail")]
273         Fail = 0,
274     }
275 
nested_nested_other_error() -> anyhow::Result<()>276     fn nested_nested_other_error() -> anyhow::Result<()> {
277         Err(anyhow!(TestError::Fail)).context("nested nested other error")
278     }
279 
nested_other_error() -> anyhow::Result<()>280     fn nested_other_error() -> anyhow::Result<()> {
281         nested_nested_other_error().context("nested other error")
282     }
283 
binder_sse_error(sse: i32) -> BinderResult<()>284     fn binder_sse_error(sse: i32) -> BinderResult<()> {
285         Err(BinderStatus::new_service_specific_error(sse, None))
286     }
287 
binder_exception(ex: ExceptionCode) -> BinderResult<()>288     fn binder_exception(ex: ExceptionCode) -> BinderResult<()> {
289         Err(BinderStatus::new_exception(ex, None))
290     }
291 
292     #[test]
keystore_error_test() -> anyhow::Result<(), String>293     fn keystore_error_test() -> anyhow::Result<(), String> {
294         android_logger::init_once(
295             android_logger::Config::default()
296                 .with_tag("keystore_error_tests")
297                 .with_min_level(log::Level::Debug),
298         );
299         // All Error::Rc(x) get mapped on a service specific error
300         // code of x.
301         for rc in ResponseCode::LOCKED.0..ResponseCode::BACKEND_BUSY.0 {
302             assert_eq!(
303                 Result::<(), i32>::Err(rc),
304                 map_or_log_err(nested_rc(ResponseCode(rc)), |_| Err(BinderStatus::ok()))
305                     .map_err(|s| s.service_specific_error())
306             );
307         }
308 
309         // All Keystore Error::Km(x) get mapped on a service
310         // specific error of x.
311         for ec in ErrorCode::UNKNOWN_ERROR.0..ErrorCode::ROOT_OF_TRUST_ALREADY_SET.0 {
312             assert_eq!(
313                 Result::<(), i32>::Err(ec),
314                 map_or_log_err(nested_ec(ErrorCode(ec)), |_| Err(BinderStatus::ok()))
315                     .map_err(|s| s.service_specific_error())
316             );
317         }
318 
319         // All Keymint errors x received through a Binder Result get mapped on
320         // a service specific error of x.
321         for ec in ErrorCode::UNKNOWN_ERROR.0..ErrorCode::ROOT_OF_TRUST_ALREADY_SET.0 {
322             assert_eq!(
323                 Result::<(), i32>::Err(ec),
324                 map_or_log_err(
325                     map_km_error(binder_sse_error(ec))
326                         .with_context(|| format!("Km error code: {}.", ec)),
327                     |_| Err(BinderStatus::ok())
328                 )
329                 .map_err(|s| s.service_specific_error())
330             );
331         }
332 
333         // map_km_error creates an Error::Binder variant storing
334         // ExceptionCode::SERVICE_SPECIFIC and the given
335         // service specific error.
336         let sse = map_km_error(binder_sse_error(1));
337         assert_eq!(Err(Error::Binder(ExceptionCode::SERVICE_SPECIFIC, 1)), sse);
338         // map_or_log_err then maps it on a service specific error of ResponseCode::SYSTEM_ERROR.
339         assert_eq!(
340             Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
341             map_or_log_err(sse.context("Non negative service specific error."), |_| Err(
342                 BinderStatus::ok()
343             ))
344             .map_err(|s| ResponseCode(s.service_specific_error()))
345         );
346 
347         // map_km_error creates a Error::Binder variant storing the given exception code.
348         let binder_exception = map_km_error(binder_exception(ExceptionCode::TRANSACTION_FAILED));
349         assert_eq!(Err(Error::Binder(ExceptionCode::TRANSACTION_FAILED, 0)), binder_exception);
350         // map_or_log_err then maps it on a service specific error of ResponseCode::SYSTEM_ERROR.
351         assert_eq!(
352             Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
353             map_or_log_err(binder_exception.context("Binder Exception."), |_| Err(
354                 BinderStatus::ok()
355             ))
356             .map_err(|s| ResponseCode(s.service_specific_error()))
357         );
358 
359         // selinux::Error::Perm() needs to be mapped to ResponseCode::PERMISSION_DENIED
360         assert_eq!(
361             Result::<(), ResponseCode>::Err(ResponseCode::PERMISSION_DENIED),
362             map_or_log_err(nested_selinux_perm(), |_| Err(BinderStatus::ok()))
363                 .map_err(|s| ResponseCode(s.service_specific_error()))
364         );
365 
366         // All other errors get mapped on System Error.
367         assert_eq!(
368             Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
369             map_or_log_err(nested_other_error(), |_| Err(BinderStatus::ok()))
370                 .map_err(|s| ResponseCode(s.service_specific_error()))
371         );
372 
373         // Result::Ok variants get passed to the ok handler.
374         assert_eq!(Ok(ResponseCode::LOCKED), map_or_log_err(nested_ok(ResponseCode::LOCKED), Ok));
375         assert_eq!(
376             Ok(ResponseCode::SYSTEM_ERROR),
377             map_or_log_err(nested_ok(ResponseCode::SYSTEM_ERROR), Ok)
378         );
379 
380         Ok(())
381     }
382 
383     //Helper function to test whether error cases are handled as expected.
check_result_contains_error_string<T>( result: anyhow::Result<T>, expected_error_string: &str, )384     pub fn check_result_contains_error_string<T>(
385         result: anyhow::Result<T>,
386         expected_error_string: &str,
387     ) {
388         let error_str = format!(
389             "{:#?}",
390             result.err().unwrap_or_else(|| panic!("Expected the error: {}", expected_error_string))
391         );
392         assert!(
393             error_str.contains(expected_error_string),
394             "The string \"{}\" should contain \"{}\"",
395             error_str,
396             expected_error_string
397         );
398     }
399 } // mod tests
400