blob: d67f5f46327f8105192b9b9a88457f296e632376 [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),
Max Biresb2e1d032021-02-08 21:35:05 -080060 /// Wraps a Remote Provisioning ErrorCode as defined by the IRemotelyProvisionedComponent
61 /// AIDL interface spec.
62 #[error("Error::Rp({0:?})")]
63 Rp(ErrorCode),
Janis Danisevskis7d77a762020-07-20 13:03:31 -070064}
65
66impl Error {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070067 /// Short hand for `Error::Rc(ResponseCode::SYSTEM_ERROR)`
Janis Danisevskis7d77a762020-07-20 13:03:31 -070068 pub fn sys() -> Self {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070069 Error::Rc(ResponseCode::SYSTEM_ERROR)
Janis Danisevskis7d77a762020-07-20 13:03:31 -070070 }
71
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070072 /// Short hand for `Error::Rc(ResponseCode::PERMISSION_DENIED`
Janis Danisevskis7d77a762020-07-20 13:03:31 -070073 pub fn perm() -> Self {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070074 Error::Rc(ResponseCode::PERMISSION_DENIED)
Janis Danisevskis7d77a762020-07-20 13:03:31 -070075 }
76}
77
Janis Danisevskis017d2092020-09-02 10:15:52 -070078/// Helper function to map the binder status we get from calls into KeyMint
79/// to a Keystore Error. We don't create an anyhow error here to make
80/// it easier to evaluate KeyMint errors, which we must do in some cases, e.g.,
81/// when diagnosing authentication requirements, update requirements, and running
82/// out of operation slots.
83pub fn map_km_error<T>(r: BinderResult<T>) -> Result<T, Error> {
84 r.map_err(|s| {
85 match s.exception_code() {
86 ExceptionCode::SERVICE_SPECIFIC => {
87 let se = s.service_specific_error();
88 if se < 0 {
89 // Negative service specific errors are KM error codes.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070090 Error::Km(ErrorCode(s.service_specific_error()))
Janis Danisevskis017d2092020-09-02 10:15:52 -070091 } else {
92 // Non negative error codes cannot be KM error codes.
93 // So we create an `Error::Binder` variant to preserve
94 // the service specific error code for logging.
95 // `map_or_log_err` will map this on a system error,
96 // but not before logging the details to logcat.
97 Error::Binder(ExceptionCode::SERVICE_SPECIFIC, se)
98 }
99 }
100 // We create `Error::Binder` to preserve the exception code
101 // for logging.
102 // `map_or_log_err` will map this on a system error.
103 e_code => Error::Binder(e_code, 0),
104 }
105 })
106}
107
Max Biresb2e1d032021-02-08 21:35:05 -0800108/// Helper function to map the binder status we get from calls into a RemotelyProvisionedComponent
109/// to a Keystore Error. We don't create an anyhow error here to make
110/// it easier to evaluate service specific errors.
111pub fn map_rem_prov_error<T>(r: BinderResult<T>) -> Result<T, Error> {
112 r.map_err(|s| match s.exception_code() {
113 ExceptionCode::SERVICE_SPECIFIC => Error::Rp(ErrorCode(s.service_specific_error())),
114 e_code => Error::Binder(e_code, 0),
115 })
116}
117
Janis Danisevskisba998992020-12-29 16:08:40 -0800118/// This function is similar to map_km_error only that we don't expect
119/// any KeyMint error codes, we simply preserve the exception code and optional
120/// service specific exception.
121pub fn map_binder_status<T>(r: BinderResult<T>) -> Result<T, Error> {
122 r.map_err(|s| match s.exception_code() {
123 ExceptionCode::SERVICE_SPECIFIC => {
124 let se = s.service_specific_error();
125 Error::Binder(ExceptionCode::SERVICE_SPECIFIC, se)
126 }
127 ExceptionCode::TRANSACTION_FAILED => {
128 let e = s.transaction_error();
129 Error::BinderTransaction(e)
130 }
131 e_code => Error::Binder(e_code, 0),
132 })
133}
134
135/// This function maps a status code onto a Keystore Error.
136pub fn map_binder_status_code<T>(r: Result<T, StatusCode>) -> Result<T, Error> {
137 r.map_err(Error::BinderTransaction)
138}
139
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700140/// This function should be used by Keystore service calls to translate error conditions
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800141/// into service specific exceptions.
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700142///
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800143/// All error conditions get logged by this function.
144///
145/// All `Error::Rc(x)` and `Error::Km(x)` variants get mapped onto a service specific error
146/// code of x. This is possible because KeyMint `ErrorCode` errors are always negative and
147/// `ResponseCode` codes are always positive.
148/// `selinux::Error::PermissionDenied` is mapped on `ResponseCode::PERMISSION_DENIED`.
149///
150/// All non `Error` error conditions and the Error::Binder variant get mapped onto
151/// ResponseCode::SYSTEM_ERROR`.
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700152///
153/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800154/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
155/// typically returns Ok(value).
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700156///
157/// # Examples
158///
159/// ```
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800160/// fn loadKey() -> anyhow::Result<Vec<u8>> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700161/// if (good_but_auth_required) {
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800162/// Ok(vec!['k', 'e', 'y'])
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700163/// } else {
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800164/// Err(anyhow!(Error::Rc(ResponseCode::KEY_NOT_FOUND)))
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700165/// }
166/// }
167///
Janis Danisevskis8ea5f552020-11-20 11:22:59 -0800168/// map_or_log_err(loadKey(), Ok)
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700169/// ```
Janis Danisevskise24f3472020-08-12 17:58:49 -0700170pub fn map_or_log_err<T, U, F>(result: anyhow::Result<U>, handle_ok: F) -> BinderResult<T>
171where
172 F: FnOnce(U) -> BinderResult<T>,
173{
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700174 result.map_or_else(
175 |e| {
176 log::error!("{:?}", e);
Janis Danisevskise24f3472020-08-12 17:58:49 -0700177 let root_cause = e.root_cause();
178 let rc = match root_cause.downcast_ref::<Error>() {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700179 Some(Error::Rc(rcode)) => rcode.0,
180 Some(Error::Km(ec)) => ec.0,
Max Biresb2e1d032021-02-08 21:35:05 -0800181 Some(Error::Rp(_)) => ResponseCode::SYSTEM_ERROR.0,
Janis Danisevskis017d2092020-09-02 10:15:52 -0700182 // If an Error::Binder reaches this stage we report a system error.
183 // The exception code and possible service specific error will be
184 // printed in the error log above.
Janis Danisevskisba998992020-12-29 16:08:40 -0800185 Some(Error::Binder(_, _)) | Some(Error::BinderTransaction(_)) => {
186 ResponseCode::SYSTEM_ERROR.0
187 }
Janis Danisevskise24f3472020-08-12 17:58:49 -0700188 None => match root_cause.downcast_ref::<selinux::Error>() {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700189 Some(selinux::Error::PermissionDenied) => ResponseCode::PERMISSION_DENIED.0,
190 _ => ResponseCode::SYSTEM_ERROR.0,
Janis Danisevskise24f3472020-08-12 17:58:49 -0700191 },
192 };
193 Err(BinderStatus::new_service_specific_error(rc, None))
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700194 },
195 handle_ok,
196 )
197}
198
199#[cfg(test)]
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000200pub mod tests {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700201
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700202 use super::*;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700203 use android_system_keystore2::binder::{
Janis Danisevskis017d2092020-09-02 10:15:52 -0700204 ExceptionCode, Result as BinderResult, Status as BinderStatus,
205 };
Janis Danisevskise24f3472020-08-12 17:58:49 -0700206 use anyhow::{anyhow, Context};
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700207
Janis Danisevskise24f3472020-08-12 17:58:49 -0700208 fn nested_nested_rc(rc: ResponseCode) -> anyhow::Result<()> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700209 Err(anyhow!(Error::Rc(rc))).context("nested nested rc")
210 }
211
Janis Danisevskise24f3472020-08-12 17:58:49 -0700212 fn nested_rc(rc: ResponseCode) -> anyhow::Result<()> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700213 nested_nested_rc(rc).context("nested rc")
214 }
215
216 fn nested_nested_ec(ec: ErrorCode) -> anyhow::Result<()> {
217 Err(anyhow!(Error::Km(ec))).context("nested nested ec")
218 }
219
220 fn nested_ec(ec: ErrorCode) -> anyhow::Result<()> {
221 nested_nested_ec(ec).context("nested ec")
222 }
223
Janis Danisevskise24f3472020-08-12 17:58:49 -0700224 fn nested_nested_ok(rc: ResponseCode) -> anyhow::Result<ResponseCode> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700225 Ok(rc)
226 }
227
Janis Danisevskise24f3472020-08-12 17:58:49 -0700228 fn nested_ok(rc: ResponseCode) -> anyhow::Result<ResponseCode> {
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700229 nested_nested_ok(rc).context("nested ok")
230 }
231
Janis Danisevskisce995432020-07-21 12:22:34 -0700232 fn nested_nested_selinux_perm() -> anyhow::Result<()> {
233 Err(anyhow!(selinux::Error::perm())).context("nested nexted selinux permission denied")
234 }
235
236 fn nested_selinux_perm() -> anyhow::Result<()> {
237 nested_nested_selinux_perm().context("nested selinux permission denied")
238 }
239
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700240 #[derive(Debug, thiserror::Error)]
241 enum TestError {
242 #[error("TestError::Fail")]
243 Fail = 0,
244 }
245
246 fn nested_nested_other_error() -> anyhow::Result<()> {
247 Err(anyhow!(TestError::Fail)).context("nested nested other error")
248 }
249
250 fn nested_other_error() -> anyhow::Result<()> {
251 nested_nested_other_error().context("nested other error")
252 }
253
Janis Danisevskis017d2092020-09-02 10:15:52 -0700254 fn binder_sse_error(sse: i32) -> BinderResult<()> {
255 Err(BinderStatus::new_service_specific_error(sse, None))
256 }
257
258 fn binder_exception(ex: ExceptionCode) -> BinderResult<()> {
259 Err(BinderStatus::new_exception(ex, None))
260 }
261
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700262 #[test]
263 fn keystore_error_test() -> anyhow::Result<(), String> {
264 android_logger::init_once(
265 android_logger::Config::default()
266 .with_tag("keystore_error_tests")
267 .with_min_level(log::Level::Debug),
268 );
Janis Danisevskise24f3472020-08-12 17:58:49 -0700269 // All Error::Rc(x) get mapped on a service specific error
270 // code of x.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700271 for rc in ResponseCode::LOCKED.0..ResponseCode::BACKEND_BUSY.0 {
Janis Danisevskise24f3472020-08-12 17:58:49 -0700272 assert_eq!(
273 Result::<(), i32>::Err(rc),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700274 map_or_log_err(nested_rc(ResponseCode(rc)), |_| Err(BinderStatus::ok()))
Janis Danisevskise24f3472020-08-12 17:58:49 -0700275 .map_err(|s| s.service_specific_error())
276 );
277 }
278
Janis Danisevskis017d2092020-09-02 10:15:52 -0700279 // All Keystore Error::Km(x) get mapped on a service
Janis Danisevskise24f3472020-08-12 17:58:49 -0700280 // specific error of x.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700281 for ec in ErrorCode::UNKNOWN_ERROR.0..ErrorCode::ROOT_OF_TRUST_ALREADY_SET.0 {
Janis Danisevskise24f3472020-08-12 17:58:49 -0700282 assert_eq!(
283 Result::<(), i32>::Err(ec),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700284 map_or_log_err(nested_ec(ErrorCode(ec)), |_| Err(BinderStatus::ok()))
Janis Danisevskise24f3472020-08-12 17:58:49 -0700285 .map_err(|s| s.service_specific_error())
286 );
287 }
288
Janis Danisevskis017d2092020-09-02 10:15:52 -0700289 // All Keymint errors x received through a Binder Result get mapped on
290 // a service specific error of x.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700291 for ec in ErrorCode::UNKNOWN_ERROR.0..ErrorCode::ROOT_OF_TRUST_ALREADY_SET.0 {
Janis Danisevskis017d2092020-09-02 10:15:52 -0700292 assert_eq!(
293 Result::<(), i32>::Err(ec),
294 map_or_log_err(
295 map_km_error(binder_sse_error(ec))
296 .with_context(|| format!("Km error code: {}.", ec)),
297 |_| Err(BinderStatus::ok())
298 )
299 .map_err(|s| s.service_specific_error())
300 );
301 }
302
303 // map_km_error creates an Error::Binder variant storing
304 // ExceptionCode::SERVICE_SPECIFIC and the given
305 // service specific error.
306 let sse = map_km_error(binder_sse_error(1));
307 assert_eq!(Err(Error::Binder(ExceptionCode::SERVICE_SPECIFIC, 1)), sse);
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700308 // map_or_log_err then maps it on a service specific error of ResponseCode::SYSTEM_ERROR.
Janis Danisevskis017d2092020-09-02 10:15:52 -0700309 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700310 Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
Janis Danisevskis017d2092020-09-02 10:15:52 -0700311 map_or_log_err(sse.context("Non negative service specific error."), |_| Err(
312 BinderStatus::ok()
313 ))
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700314 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis017d2092020-09-02 10:15:52 -0700315 );
316
317 // map_km_error creates a Error::Binder variant storing the given exception code.
318 let binder_exception = map_km_error(binder_exception(ExceptionCode::TRANSACTION_FAILED));
319 assert_eq!(Err(Error::Binder(ExceptionCode::TRANSACTION_FAILED, 0)), binder_exception);
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700320 // map_or_log_err then maps it on a service specific error of ResponseCode::SYSTEM_ERROR.
Janis Danisevskis017d2092020-09-02 10:15:52 -0700321 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700322 Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
Janis Danisevskis017d2092020-09-02 10:15:52 -0700323 map_or_log_err(binder_exception.context("Binder Exception."), |_| Err(
324 BinderStatus::ok()
325 ))
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700326 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis017d2092020-09-02 10:15:52 -0700327 );
328
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700329 // selinux::Error::Perm() needs to be mapped to ResponseCode::PERMISSION_DENIED
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700330 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700331 Result::<(), ResponseCode>::Err(ResponseCode::PERMISSION_DENIED),
Janis Danisevskise24f3472020-08-12 17:58:49 -0700332 map_or_log_err(nested_selinux_perm(), |_| Err(BinderStatus::ok()))
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700333 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700334 );
335
Janis Danisevskise24f3472020-08-12 17:58:49 -0700336 // All other errors get mapped on System Error.
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700337 assert_eq!(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700338 Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
Janis Danisevskise24f3472020-08-12 17:58:49 -0700339 map_or_log_err(nested_other_error(), |_| Err(BinderStatus::ok()))
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700340 .map_err(|s| ResponseCode(s.service_specific_error()))
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700341 );
342
343 // Result::Ok variants get passed to the ok handler.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700344 assert_eq!(Ok(ResponseCode::LOCKED), map_or_log_err(nested_ok(ResponseCode::LOCKED), Ok));
345 assert_eq!(
346 Ok(ResponseCode::SYSTEM_ERROR),
347 map_or_log_err(nested_ok(ResponseCode::SYSTEM_ERROR), Ok)
348 );
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700349
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700350 Ok(())
351 }
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000352
353 //Helper function to test whether error cases are handled as expected.
Janis Danisevskise24f3472020-08-12 17:58:49 -0700354 pub fn check_result_contains_error_string<T>(
355 result: anyhow::Result<T>,
356 expected_error_string: &str,
357 ) {
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000358 let error_str = format!(
359 "{:#?}",
360 result.err().unwrap_or_else(|| panic!("Expected the error: {}", expected_error_string))
361 );
362 assert!(
363 error_str.contains(expected_error_string),
364 "The string \"{}\" should contain \"{}\"",
365 error_str,
366 expected_error_string
367 );
368 }
Janis Danisevskis7d77a762020-07-20 13:03:31 -0700369} // mod tests