blob: 36f94e9942ab74b1c1bd79324e62440b07544dd5 [file] [log] [blame]
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +00001// 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
Hasini Gunasinghe0e161452021-01-27 19:34:37 +000015//! This module implements IKeystoreAuthorization AIDL interface.
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +000016
Janis Danisevskisea03cff2021-12-16 08:10:17 -080017use crate::error::anyhow_error_to_cstring;
James Willcoxd215da82023-10-03 21:31:31 +000018use crate::error::Error as KeystoreError;
19use crate::globals::{DB, ENFORCEMENTS, LEGACY_IMPORTER, SUPER_KEY};
20use crate::ks_err;
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +000021use crate::permission::KeystorePerm;
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +000022use crate::utils::{check_keystore_permission, watchdog as wd};
James Willcoxd215da82023-10-03 21:31:31 +000023use aconfig_android_hardware_biometrics_rust;
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +000024use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
James Willcoxd215da82023-10-03 21:31:31 +000025 HardwareAuthToken::HardwareAuthToken, HardwareAuthenticatorType::HardwareAuthenticatorType,
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +000026};
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +000027use android_security_authorization::aidl::android::security::authorization::{
James Willcoxd215da82023-10-03 21:31:31 +000028 AuthorizationTokens::AuthorizationTokens, IKeystoreAuthorization::BnKeystoreAuthorization,
Eric Biggers10afa962023-12-01 23:05:24 +000029 IKeystoreAuthorization::IKeystoreAuthorization, ResponseCode::ResponseCode,
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +000030};
James Willcoxd215da82023-10-03 21:31:31 +000031use android_security_authorization::binder::{
32 BinderFeatures, ExceptionCode, Interface, Result as BinderResult, Status as BinderStatus,
33 Strong,
34};
35use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode as KsResponseCode;
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +000036use anyhow::{Context, Result};
Paul Crowleyf61fee72021-03-17 14:38:44 -070037use keystore2_crypto::Password;
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +000038use keystore2_selinux as selinux;
James Willcoxd215da82023-10-03 21:31:31 +000039use std::ffi::CString;
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +000040
41/// This is the Authorization error type, it wraps binder exceptions and the
42/// Authorization ResponseCode
Chris Wailes263de9f2022-08-11 15:00:51 -070043#[derive(Debug, thiserror::Error, PartialEq, Eq)]
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +000044pub enum Error {
45 /// Wraps an IKeystoreAuthorization response code as defined by
46 /// android.security.authorization AIDL interface specification.
47 #[error("Error::Rc({0:?})")]
48 Rc(ResponseCode),
49 /// Wraps a Binder exception code other than a service specific exception.
50 #[error("Binder exception code {0:?}, {1:?}")]
51 Binder(ExceptionCode, i32),
52}
53
54/// This function should be used by authorization service calls to translate error conditions
55/// into service specific exceptions.
56///
57/// All error conditions get logged by this function.
58///
59/// `Error::Rc(x)` variants get mapped onto a service specific error code of `x`.
60/// Certain response codes may be returned from keystore/ResponseCode.aidl by the keystore2 modules,
61/// which are then converted to the corresponding response codes of android.security.authorization
62/// AIDL interface specification.
63///
64/// `selinux::Error::perm()` is mapped on `ResponseCode::PERMISSION_DENIED`.
65///
66/// All non `Error` error conditions get mapped onto ResponseCode::SYSTEM_ERROR`.
67///
68/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
69/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
70/// typically returns Ok(value).
71pub fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
72where
73 F: FnOnce(U) -> BinderResult<T>,
74{
75 result.map_or_else(
76 |e| {
77 log::error!("{:#?}", e);
78 let root_cause = e.root_cause();
79 if let Some(KeystoreError::Rc(ks_rcode)) = root_cause.downcast_ref::<KeystoreError>() {
80 let rc = match *ks_rcode {
81 // Although currently keystore2/ResponseCode.aidl and
82 // authorization/ResponseCode.aidl share the same integer values for the
83 // common response codes, this may deviate in the future, hence the
84 // conversion here.
85 KsResponseCode::SYSTEM_ERROR => ResponseCode::SYSTEM_ERROR.0,
86 KsResponseCode::KEY_NOT_FOUND => ResponseCode::KEY_NOT_FOUND.0,
87 KsResponseCode::VALUE_CORRUPTED => ResponseCode::VALUE_CORRUPTED.0,
88 KsResponseCode::INVALID_ARGUMENT => ResponseCode::INVALID_ARGUMENT.0,
89 // If the code paths of IKeystoreAuthorization aidl's methods happen to return
90 // other error codes from KsResponseCode in the future, they should be converted
91 // as well.
92 _ => ResponseCode::SYSTEM_ERROR.0,
93 };
Janis Danisevskisea03cff2021-12-16 08:10:17 -080094 return Err(BinderStatus::new_service_specific_error(
95 rc,
96 anyhow_error_to_cstring(&e).as_deref(),
97 ));
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +000098 }
99 let rc = match root_cause.downcast_ref::<Error>() {
100 Some(Error::Rc(rcode)) => rcode.0,
101 Some(Error::Binder(_, _)) => ResponseCode::SYSTEM_ERROR.0,
102 None => match root_cause.downcast_ref::<selinux::Error>() {
103 Some(selinux::Error::PermissionDenied) => ResponseCode::PERMISSION_DENIED.0,
104 _ => ResponseCode::SYSTEM_ERROR.0,
105 },
106 };
Janis Danisevskisea03cff2021-12-16 08:10:17 -0800107 Err(BinderStatus::new_service_specific_error(
108 rc,
109 anyhow_error_to_cstring(&e).as_deref(),
110 ))
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000111 },
112 handle_ok,
113 )
114}
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000115
116/// This struct is defined to implement the aforementioned AIDL interface.
117/// As of now, it is an empty struct.
118pub struct AuthorizationManager;
119
120impl AuthorizationManager {
121 /// Create a new instance of Keystore Authorization service.
Stephen Crane221bbb52020-12-16 15:52:10 -0800122 pub fn new_native_binder() -> Result<Strong<dyn IKeystoreAuthorization>> {
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000123 Ok(BnKeystoreAuthorization::new_binder(
124 Self,
125 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
126 ))
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000127 }
128
129 fn add_auth_token(&self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700130 // Check keystore permission.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000131 check_keystore_permission(KeystorePerm::AddAuth).context(ks_err!())?;
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000132
David Drysdalebf2d72f2023-06-15 13:38:36 +0100133 log::info!(
134 "add_auth_token(challenge={}, userId={}, authId={}, authType={:#x}, timestamp={}ms)",
135 auth_token.challenge,
136 auth_token.userId,
137 auth_token.authenticatorId,
138 auth_token.authenticatorType.0,
139 auth_token.timestamp.milliSeconds,
140 );
141
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700142 ENFORCEMENTS.add_auth_token(auth_token.clone());
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000143 Ok(())
144 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000145
Eric Biggers10afa962023-12-01 23:05:24 +0000146 fn on_device_unlocked(&self, user_id: i32, password: Option<Password>) -> Result<()> {
Paul Crowley618869e2021-04-08 20:30:54 -0700147 log::info!(
Eric Biggers10afa962023-12-01 23:05:24 +0000148 "on_device_unlocked(user_id={}, password.is_some()={})",
Paul Crowley618869e2021-04-08 20:30:54 -0700149 user_id,
150 password.is_some(),
Paul Crowley618869e2021-04-08 20:30:54 -0700151 );
Eric Biggers10afa962023-12-01 23:05:24 +0000152 check_keystore_permission(KeystorePerm::Unlock).context(ks_err!("Unlock."))?;
153 ENFORCEMENTS.set_device_locked(user_id, false);
Paul Crowley7a658392021-03-18 17:08:20 -0700154
Eric Biggers10afa962023-12-01 23:05:24 +0000155 let mut skm = SUPER_KEY.write().unwrap();
156 if let Some(password) = password {
157 DB.with(|db| {
158 skm.unlock_user(&mut db.borrow_mut(), &LEGACY_IMPORTER, user_id as u32, &password)
159 })
160 .context(ks_err!("Unlock with password."))
161 } else {
162 DB.with(|db| skm.try_unlock_user_with_biometric(&mut db.borrow_mut(), user_id as u32))
163 .context(ks_err!("try_unlock_user_with_biometric failed"))
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000164 }
165 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000166
Eric Biggers10afa962023-12-01 23:05:24 +0000167 fn on_device_locked(&self, user_id: i32, unlocking_sids: &[i64]) -> Result<()> {
168 log::info!("on_device_locked(user_id={}, unlocking_sids={:?})", user_id, unlocking_sids);
169
170 check_keystore_permission(KeystorePerm::Lock).context(ks_err!("Lock"))?;
171 ENFORCEMENTS.set_device_locked(user_id, true);
172 let mut skm = SUPER_KEY.write().unwrap();
173 DB.with(|db| {
174 skm.lock_unlocked_device_required_keys(
175 &mut db.borrow_mut(),
176 user_id as u32,
177 unlocking_sids,
178 );
179 });
180 Ok(())
181 }
182
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000183 fn get_auth_tokens_for_credstore(
184 &self,
185 challenge: i64,
186 secure_user_id: i64,
187 auth_token_max_age_millis: i64,
188 ) -> Result<AuthorizationTokens> {
189 // Check permission. Function should return if this failed. Therefore having '?' at the end
190 // is very important.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000191 check_keystore_permission(KeystorePerm::GetAuthToken).context(ks_err!("GetAuthToken"))?;
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000192
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700193 // If the challenge is zero, return error
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000194 if challenge == 0 {
195 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000196 .context(ks_err!("Challenge can not be zero."));
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000197 }
198 // Obtain the auth token and the timestamp token from the enforcement module.
199 let (auth_token, ts_token) =
200 ENFORCEMENTS.get_auth_tokens(challenge, secure_user_id, auth_token_max_age_millis)?;
201 Ok(AuthorizationTokens { authToken: auth_token, timestampToken: ts_token })
202 }
James Willcoxd215da82023-10-03 21:31:31 +0000203
204 fn get_last_auth_time(
205 &self,
206 secure_user_id: i64,
207 auth_types: &[HardwareAuthenticatorType],
208 ) -> Result<i64> {
209 // Check keystore permission.
210 check_keystore_permission(KeystorePerm::GetLastAuthTime).context(ks_err!())?;
211
212 let mut max_time: i64 = -1;
213 for auth_type in auth_types.iter() {
214 if let Some(time) = ENFORCEMENTS.get_last_auth_time(secure_user_id, *auth_type) {
215 if time.milliseconds() > max_time {
216 max_time = time.milliseconds();
217 }
218 }
219 }
220
221 if max_time >= 0 {
222 Ok(max_time)
223 } else {
224 Err(Error::Rc(ResponseCode::NO_AUTH_TOKEN_FOUND))
225 .context(ks_err!("No auth token found"))
226 }
227 }
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000228}
229
230impl Interface for AuthorizationManager {}
231
232impl IKeystoreAuthorization for AuthorizationManager {
233 fn addAuthToken(&self, auth_token: &HardwareAuthToken) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000234 let _wp = wd::watch_millis("IKeystoreAuthorization::addAuthToken", 500);
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000235 map_or_log_err(self.add_auth_token(auth_token), Ok)
236 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000237
Eric Biggers10afa962023-12-01 23:05:24 +0000238 fn onDeviceUnlocked(&self, user_id: i32, password: Option<&[u8]>) -> BinderResult<()> {
239 let _wp = wd::watch_millis("IKeystoreAuthorization::onDeviceUnlocked", 500);
240 map_or_log_err(self.on_device_unlocked(user_id, password.map(|pw| pw.into())), Ok)
241 }
242
243 fn onDeviceLocked(&self, user_id: i32, unlocking_sids: &[i64]) -> BinderResult<()> {
244 let _wp = wd::watch_millis("IKeystoreAuthorization::onDeviceLocked", 500);
245 map_or_log_err(self.on_device_locked(user_id, unlocking_sids), Ok)
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000246 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000247
248 fn getAuthTokensForCredStore(
249 &self,
250 challenge: i64,
251 secure_user_id: i64,
252 auth_token_max_age_millis: i64,
Stephen Crane23cf7242022-01-19 17:49:46 +0000253 ) -> binder::Result<AuthorizationTokens> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000254 let _wp = wd::watch_millis("IKeystoreAuthorization::getAuthTokensForCredStore", 500);
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000255 map_or_log_err(
256 self.get_auth_tokens_for_credstore(
257 challenge,
258 secure_user_id,
259 auth_token_max_age_millis,
260 ),
261 Ok,
262 )
263 }
James Willcoxd215da82023-10-03 21:31:31 +0000264
265 fn getLastAuthTime(
266 &self,
267 secure_user_id: i64,
268 auth_types: &[HardwareAuthenticatorType],
269 ) -> binder::Result<i64> {
270 if aconfig_android_hardware_biometrics_rust::last_authentication_time() {
271 map_or_log_err(self.get_last_auth_time(secure_user_id, auth_types), Ok)
272 } else {
273 Err(BinderStatus::new_service_specific_error(
274 ResponseCode::PERMISSION_DENIED.0,
275 Some(CString::new("Feature is not enabled.").unwrap().as_c_str()),
276 ))
277 }
278 }
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000279}