blob: 7227f6258ae8519654f027701a0a45f553d52370 [file] [log] [blame]
Janis Danisevskis7d77a762020-07-20 13:03:31 -07001// 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
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070028//! `ResponseCode::SYSTEM_ERROR` and logs any error condition.
Janis Danisevskis7d77a762020-07-20 13:03:31 -070029//!
30//! Keystore functions should use `anyhow::Result` to return error conditions, and
31//! context should be added every time an error is forwarded.
32
33use std::cmp::PartialEq;
Janis Danisevskis7d77a762020-07-20 13:03:31 -070034
Shawn Willden708744a2020-12-11 13:05:27 +000035pub use android_hardware_security_keymint::aidl::android::hardware::security::keymint::ErrorCode::ErrorCode;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070036pub use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode;
Janis Danisevskis7d77a762020-07-20 13:03:31 -070037
Janis Danisevskisce995432020-07-21 12:22:34 -070038use keystore2_selinux as selinux;
39
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070040use android_system_keystore2::binder::{
Janis Danisevskisba998992020-12-29 16:08:40 -080041 ExceptionCode, Result as BinderResult, Status as BinderStatus, StatusCode,
Janis Danisevskis017d2092020-09-02 10:15:52 -070042};
Janis Danisevskis7d77a762020-07-20 13:03:31 -070043
44/// This is the main Keystore error type. It wraps the Keystore `ResponseCode` generated
45/// from AIDL in the `Rc` variant and Keymint `ErrorCode` in the Km variant.
46#[derive(Debug, thiserror::Error, PartialEq)]
47pub enum Error {
48 /// Wraps a Keystore `ResponseCode` as defined by the Keystore AIDL interface specification.
49 #[error("Error::Rc({0:?})")]
Janis Danisevskise24f3472020-08-12 17:58:49 -070050 Rc(ResponseCode),
Janis Danisevskis7d77a762020-07-20 13:03:31 -070051 /// Wraps a Keymint `ErrorCode` as defined by the Keymint AIDL interface specification.
52 #[error("Error::Km({0:?})")]
Janis Danisevskise24f3472020-08-12 17:58:49 -070053 Km(ErrorCode),
Janis Danisevskis017d2092020-09-02 10:15:52 -070054 /// Wraps a Binder exception code other than a service specific exception.
55 #[error("Binder exception code {0:?}, {1:?}")]
56 Binder(ExceptionCode, i32),
Janis Danisevskisba998992020-12-29 16:08:40 -080057 /// Wraps a Binder status code.
58 #[error("Binder transaction error {0:?}")]
59 BinderTransaction(StatusCode),
Janis Danisevskis7d77a762020-07-20 13:03:31 -070060}
61
62impl Error {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070063 /// Short hand for `Error::Rc(ResponseCode::SYSTEM_ERROR)`
Janis Danisevskis7d77a762020-07-20 13:03:31 -070064 pub fn sys() -> Self {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070065 Error::Rc(ResponseCode::SYSTEM_ERROR)
Janis Danisevskis7d77a762020-07-20 13:03:31 -070066 }
67
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070068 /// Short hand for `Error::Rc(ResponseCode::PERMISSION_DENIED`
Janis Danisevskis7d77a762020-07-20 13:03:31 -070069 pub fn perm() -> Self {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070070 Error::Rc(ResponseCode::PERMISSION_DENIED)
Janis Danisevskis7d77a762020-07-20 13:03:31 -070071 }
72}
73
Janis Danisevskis017d2092020-09-02 10:15:52 -070074/// Helper function to map the binder status we get from calls into KeyMint
75/// to a Keystore Error. We don't create an anyhow error here to make
76/// it easier to evaluate KeyMint errors, which we must do in some cases, e.g.,
77/// when diagnosing authentication requirements, update requirements, and running
78/// out of operation slots.
79pub fn map_km_error<T>(r: BinderResult<T>) -> Result<T, Error> {
80 r.map_err(|s| {
81 match s.exception_code() {
82 ExceptionCode::SERVICE_SPECIFIC => {
83 let se = s.service_specific_error();
84 if se < 0 {
85 // Negative service specific errors are KM error codes.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070086 Error::Km(ErrorCode(s.service_specific_error()))
Janis Danisevskis017d2092020-09-02 10:15:52 -070087 } else {
88 // Non negative error codes cannot be KM error codes.
89 // So we create an `Error::Binder` variant to preserve
90 // the service specific error code for logging.
91 // `map_or_log_err` will map this on a system error,
92 // but not before logging the details to logcat.
93 Error::Binder(ExceptionCode::SERVICE_SPECIFIC, se)
94 }
95 }
96 // We create `Error::Binder` to preserve the exception code
97 // for logging.
98 // `map_or_log_err` will map this on a system error.
99 e_code => Error::Binder(e_code, 0),
100 }
101 })
102}
103
Janis Danisevskisba998992020-12-29 16:08:40 -0800104/// This function is similar to map_km_error only that we don't expect
105/// any KeyMint error codes, we simply preserve the exception code and optional
106/// service specific exception.
107pub fn map_binder_status<T>(r: BinderResult<T>) -> Result<T, Error> {
108 r.map_err(|s| match s.exception_code() {
109 ExceptionCode::SERVICE_SPECIFIC => {
110 let se = s.service_specific_error();
111 Error::Binder(ExceptionCode::SERVICE_SPECIFIC, se)
112 }
113 ExceptionCode::TRANSACTION_FAILED => {
114 let e = s.transaction_error();
115 Error::BinderTransaction(e)
116 }
117 e_code => Error::Binder(e_code, 0),
118 })
119}
120
121/// This function maps a status code onto a Keystore Error.
122pub fn map_binder_status_code<T>(r: Result<T, StatusCode>) -> Result<T, Error> {
123 r.map_err(Error::BinderTransaction)
124}
125
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700126/// This function should be used by Keystore service calls to translate error conditions
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800127/// into service specific exceptions.
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700128///
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800129/// All error conditions get logged by this function.
130///
131/// All `Error::Rc(x)` and `Error::Km(x)` variants get mapped onto a service specific error
132/// code of x. This is possible because KeyMint `ErrorCode` errors are always negative and
133/// `ResponseCode` codes are always positive.
134/// `selinux::Error::PermissionDenied` is mapped on `ResponseCode::PERMISSION_DENIED`.
135///
136/// All non `Error` error conditions and the Error::Binder variant get mapped onto
137/// ResponseCode::SYSTEM_ERROR`.
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700138///
139/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800140/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
141/// typically returns Ok(value).
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700142///
143/// # Examples
144///
145/// ```
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800146/// fn loadKey() -> anyhow::Result<Vec<u8>> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700147/// if (good_but_auth_required) {
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800148/// Ok(vec!['k', 'e', 'y'])
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700149/// } else {
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800150/// Err(anyhow!(Error::Rc(ResponseCode::KEY_NOT_FOUND)))
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700151/// }
152/// }
153///
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800154/// map_or_log_err(loadKey(), Ok)
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700155/// ```
Janis Danisevskise24f3472020-08-12 17:58:49 -0700156pub fn map_or_log_err<T, U, F>(result: anyhow::Result<U>, handle_ok: F) -> BinderResult<T>
157where
158 F: FnOnce(U) -> BinderResult<T>,
159{
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700160 result.map_or_else(
161 |e| {
162 log::error!("{:?}", e);
Janis Danisevskise24f3472020-08-12 17:58:49 -0700163 let root_cause = e.root_cause();
164 let rc = match root_cause.downcast_ref::<Error>() {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700165 Some(Error::Rc(rcode)) => rcode.0,
166 Some(Error::Km(ec)) => ec.0,
Janis Danisevskis017d2092020-09-02 10:15:52 -0700167 // If an Error::Binder reaches this stage we report a system error.
168 // The exception code and possible service specific error will be
169 // printed in the error log above.
Janis Danisevskisba998992020-12-29 16:08:40 -0800170 Some(Error::Binder(_, _)) | Some(Error::BinderTransaction(_)) => {
171 ResponseCode::SYSTEM_ERROR.0
172 }
Janis Danisevskise24f3472020-08-12 17:58:49 -0700173 None => match root_cause.downcast_ref::<selinux::Error>() {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700174 Some(selinux::Error::PermissionDenied) => ResponseCode::PERMISSION_DENIED.0,
175 _ => ResponseCode::SYSTEM_ERROR.0,
Janis Danisevskise24f3472020-08-12 17:58:49 -0700176 },
177 };
178 Err(BinderStatus::new_service_specific_error(rc, None))
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700179 },
180 handle_ok,
181 )
182}
183
184#[cfg(test)]
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000185pub mod tests {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700186
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700187 use super::*;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700188 use android_system_keystore2::binder::{
Janis Danisevskis017d2092020-09-02 10:15:52 -0700189 ExceptionCode, Result as BinderResult, Status as BinderStatus,
190 };
Janis Danisevskise24f3472020-08-12 17:58:49 -0700191 use anyhow::{anyhow, Context};
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700192
Janis Danisevskise24f3472020-08-12 17:58:49 -0700193 fn nested_nested_rc(rc: ResponseCode) -> anyhow::Result<()> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700194 Err(anyhow!(Error::Rc(rc))).context("nested nested rc")
195 }
196
Janis Danisevskise24f3472020-08-12 17:58:49 -0700197 fn nested_rc(rc: ResponseCode) -> anyhow::Result<()> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700198 nested_nested_rc(rc).context("nested rc")
199 }
200
201 fn nested_nested_ec(ec: ErrorCode) -> anyhow::Result<()> {
202 Err(anyhow!(Error::Km(ec))).context("nested nested ec")
203 }
204
205 fn nested_ec(ec: ErrorCode) -> anyhow::Result<()> {
206 nested_nested_ec(ec).context("nested ec")
207 }
208
Janis Danisevskise24f3472020-08-12 17:58:49 -0700209 fn nested_nested_ok(rc: ResponseCode) -> anyhow::Result<ResponseCode> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700210 Ok(rc)
211 }
212
Janis Danisevskise24f3472020-08-12 17:58:49 -0700213 fn nested_ok(rc: ResponseCode) -> anyhow::Result<ResponseCode> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700214 nested_nested_ok(rc).context("nested ok")
215 }
216
Janis Danisevskisce995432020-07-21 12:22:34 -0700217 fn nested_nested_selinux_perm() -> anyhow::Result<()> {
218 Err(anyhow!(selinux::Error::perm())).context("nested nexted selinux permission denied")
219 }
220
221 fn nested_selinux_perm() -> anyhow::Result<()> {
222 nested_nested_selinux_perm().context("nested selinux permission denied")
223 }
224
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700225 #[derive(Debug, thiserror::Error)]
226 enum TestError {
227 #[error("TestError::Fail")]
228 Fail = 0,
229 }
230
231 fn nested_nested_other_error() -> anyhow::Result<()> {
232 Err(anyhow!(TestError::Fail)).context("nested nested other error")
233 }
234
235 fn nested_other_error() -> anyhow::Result<()> {
236 nested_nested_other_error().context("nested other error")
237 }
238
Janis Danisevskis017d2092020-09-02 10:15:52 -0700239 fn binder_sse_error(sse: i32) -> BinderResult<()> {
240 Err(BinderStatus::new_service_specific_error(sse, None))
241 }
242
243 fn binder_exception(ex: ExceptionCode) -> BinderResult<()> {
244 Err(BinderStatus::new_exception(ex, None))
245 }
246
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700247 #[test]
248 fn keystore_error_test() -> anyhow::Result<(), String> {
249 android_logger::init_once(
250 android_logger::Config::default()
251 .with_tag("keystore_error_tests")
252 .with_min_level(log::Level::Debug),
253 );
Janis Danisevskise24f3472020-08-12 17:58:49 -0700254 // All Error::Rc(x) get mapped on a service specific error
255 // code of x.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700256 for rc in ResponseCode::LOCKED.0..ResponseCode::BACKEND_BUSY.0 {
Janis Danisevskise24f3472020-08-12 17:58:49 -0700257 assert_eq!(
258 Result::<(), i32>::Err(rc),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700259 map_or_log_err(nested_rc(ResponseCode(rc)), |_| Err(BinderStatus::ok()))
Janis Danisevskise24f3472020-08-12 17:58:49 -0700260 .map_err(|s| s.service_specific_error())
261 );
262 }
263
Janis Danisevskis017d2092020-09-02 10:15:52 -0700264 // All Keystore Error::Km(x) get mapped on a service
Janis Danisevskise24f3472020-08-12 17:58:49 -0700265 // specific error of x.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700266 for ec in ErrorCode::UNKNOWN_ERROR.0..ErrorCode::ROOT_OF_TRUST_ALREADY_SET.0 {
Janis Danisevskise24f3472020-08-12 17:58:49 -0700267 assert_eq!(
268 Result::<(), i32>::Err(ec),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700269 map_or_log_err(nested_ec(ErrorCode(ec)), |_| Err(BinderStatus::ok()))
Janis Danisevskise24f3472020-08-12 17:58:49 -0700270 .map_err(|s| s.service_specific_error())
271 );
272 }
273
Janis Danisevskis017d2092020-09-02 10:15:52 -0700274 // All Keymint errors x received through a Binder Result get mapped on
275 // a service specific error of x.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700276 for ec in ErrorCode::UNKNOWN_ERROR.0..ErrorCode::ROOT_OF_TRUST_ALREADY_SET.0 {
Janis Danisevskis017d2092020-09-02 10:15:52 -0700277 assert_eq!(
278 Result::<(), i32>::Err(ec),
279 map_or_log_err(
280 map_km_error(binder_sse_error(ec))
281 .with_context(|| format!("Km error code: {}.", ec)),
282 |_| Err(BinderStatus::ok())
283 )
284 .map_err(|s| s.service_specific_error())
285 );
286 }
287
288 // map_km_error creates an Error::Binder variant storing
289 // ExceptionCode::SERVICE_SPECIFIC and the given
290 // service specific error.
291 let sse = map_km_error(binder_sse_error(1));
292 assert_eq!(Err(Error::Binder(ExceptionCode::SERVICE_SPECIFIC, 1)), sse);
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700293 // map_or_log_err then maps it on a service specific error of ResponseCode::SYSTEM_ERROR.
Janis Danisevskis017d2092020-09-02 10:15:52 -0700294 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700295 Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
Janis Danisevskis017d2092020-09-02 10:15:52 -0700296 map_or_log_err(sse.context("Non negative service specific error."), |_| Err(
297 BinderStatus::ok()
298 ))
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700299 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis017d2092020-09-02 10:15:52 -0700300 );
301
302 // map_km_error creates a Error::Binder variant storing the given exception code.
303 let binder_exception = map_km_error(binder_exception(ExceptionCode::TRANSACTION_FAILED));
304 assert_eq!(Err(Error::Binder(ExceptionCode::TRANSACTION_FAILED, 0)), binder_exception);
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700305 // map_or_log_err then maps it on a service specific error of ResponseCode::SYSTEM_ERROR.
Janis Danisevskis017d2092020-09-02 10:15:52 -0700306 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700307 Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
Janis Danisevskis017d2092020-09-02 10:15:52 -0700308 map_or_log_err(binder_exception.context("Binder Exception."), |_| Err(
309 BinderStatus::ok()
310 ))
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700311 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis017d2092020-09-02 10:15:52 -0700312 );
313
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700314 // selinux::Error::Perm() needs to be mapped to ResponseCode::PERMISSION_DENIED
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700315 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700316 Result::<(), ResponseCode>::Err(ResponseCode::PERMISSION_DENIED),
Janis Danisevskise24f3472020-08-12 17:58:49 -0700317 map_or_log_err(nested_selinux_perm(), |_| Err(BinderStatus::ok()))
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700318 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700319 );
320
Janis Danisevskise24f3472020-08-12 17:58:49 -0700321 // All other errors get mapped on System Error.
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700322 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700323 Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
Janis Danisevskise24f3472020-08-12 17:58:49 -0700324 map_or_log_err(nested_other_error(), |_| Err(BinderStatus::ok()))
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700325 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700326 );
327
328 // Result::Ok variants get passed to the ok handler.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700329 assert_eq!(Ok(ResponseCode::LOCKED), map_or_log_err(nested_ok(ResponseCode::LOCKED), Ok));
330 assert_eq!(
331 Ok(ResponseCode::SYSTEM_ERROR),
332 map_or_log_err(nested_ok(ResponseCode::SYSTEM_ERROR), Ok)
333 );
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700334
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700335 Ok(())
336 }
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000337
338 //Helper function to test whether error cases are handled as expected.
Janis Danisevskise24f3472020-08-12 17:58:49 -0700339 pub fn check_result_contains_error_string<T>(
340 result: anyhow::Result<T>,
341 expected_error_string: &str,
342 ) {
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000343 let error_str = format!(
344 "{:#?}",
345 result.err().unwrap_or_else(|| panic!("Expected the error: {}", expected_error_string))
346 );
347 assert!(
348 error_str.contains(expected_error_string),
349 "The string \"{}\" should contain \"{}\"",
350 error_str,
351 expected_error_string
352 );
353 }
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700354} // mod tests