blob: f956787588ab61021612ef854283183efc4de58c [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 Biggers6946daa2024-01-17 22:51:37 +0000167 fn on_device_locked(
168 &self,
169 user_id: i32,
170 unlocking_sids: &[i64],
171 mut weak_unlock_enabled: bool,
172 ) -> Result<()> {
173 log::info!(
174 "on_device_locked(user_id={}, unlocking_sids={:?}, weak_unlock_enabled={})",
175 user_id,
176 unlocking_sids,
177 weak_unlock_enabled
178 );
179 if !android_security_flags::fix_unlocked_device_required_keys_v2() {
180 weak_unlock_enabled = false;
181 }
Eric Biggers10afa962023-12-01 23:05:24 +0000182 check_keystore_permission(KeystorePerm::Lock).context(ks_err!("Lock"))?;
183 ENFORCEMENTS.set_device_locked(user_id, true);
184 let mut skm = SUPER_KEY.write().unwrap();
185 DB.with(|db| {
186 skm.lock_unlocked_device_required_keys(
187 &mut db.borrow_mut(),
188 user_id as u32,
189 unlocking_sids,
Eric Biggers6946daa2024-01-17 22:51:37 +0000190 weak_unlock_enabled,
Eric Biggers10afa962023-12-01 23:05:24 +0000191 );
192 });
193 Ok(())
194 }
195
Eric Biggers6946daa2024-01-17 22:51:37 +0000196 fn on_weak_unlock_methods_expired(&self, user_id: i32) -> Result<()> {
197 log::info!("on_weak_unlock_methods_expired(user_id={})", user_id);
198 if !android_security_flags::fix_unlocked_device_required_keys_v2() {
199 return Ok(());
200 }
201 check_keystore_permission(KeystorePerm::Lock).context(ks_err!("Lock"))?;
202 SUPER_KEY.write().unwrap().wipe_plaintext_unlocked_device_required_keys(user_id as u32);
203 Ok(())
204 }
205
206 fn on_non_lskf_unlock_methods_expired(&self, user_id: i32) -> Result<()> {
207 log::info!("on_non_lskf_unlock_methods_expired(user_id={})", user_id);
208 if !android_security_flags::fix_unlocked_device_required_keys_v2() {
209 return Ok(());
210 }
211 check_keystore_permission(KeystorePerm::Lock).context(ks_err!("Lock"))?;
212 SUPER_KEY.write().unwrap().wipe_all_unlocked_device_required_keys(user_id as u32);
213 Ok(())
214 }
215
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000216 fn get_auth_tokens_for_credstore(
217 &self,
218 challenge: i64,
219 secure_user_id: i64,
220 auth_token_max_age_millis: i64,
221 ) -> Result<AuthorizationTokens> {
222 // Check permission. Function should return if this failed. Therefore having '?' at the end
223 // is very important.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000224 check_keystore_permission(KeystorePerm::GetAuthToken).context(ks_err!("GetAuthToken"))?;
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000225
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700226 // If the challenge is zero, return error
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000227 if challenge == 0 {
228 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000229 .context(ks_err!("Challenge can not be zero."));
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000230 }
231 // Obtain the auth token and the timestamp token from the enforcement module.
232 let (auth_token, ts_token) =
233 ENFORCEMENTS.get_auth_tokens(challenge, secure_user_id, auth_token_max_age_millis)?;
234 Ok(AuthorizationTokens { authToken: auth_token, timestampToken: ts_token })
235 }
James Willcoxd215da82023-10-03 21:31:31 +0000236
237 fn get_last_auth_time(
238 &self,
239 secure_user_id: i64,
240 auth_types: &[HardwareAuthenticatorType],
241 ) -> Result<i64> {
242 // Check keystore permission.
243 check_keystore_permission(KeystorePerm::GetLastAuthTime).context(ks_err!())?;
244
245 let mut max_time: i64 = -1;
246 for auth_type in auth_types.iter() {
247 if let Some(time) = ENFORCEMENTS.get_last_auth_time(secure_user_id, *auth_type) {
248 if time.milliseconds() > max_time {
249 max_time = time.milliseconds();
250 }
251 }
252 }
253
254 if max_time >= 0 {
255 Ok(max_time)
256 } else {
257 Err(Error::Rc(ResponseCode::NO_AUTH_TOKEN_FOUND))
258 .context(ks_err!("No auth token found"))
259 }
260 }
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000261}
262
263impl Interface for AuthorizationManager {}
264
265impl IKeystoreAuthorization for AuthorizationManager {
266 fn addAuthToken(&self, auth_token: &HardwareAuthToken) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000267 let _wp = wd::watch_millis("IKeystoreAuthorization::addAuthToken", 500);
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000268 map_or_log_err(self.add_auth_token(auth_token), Ok)
269 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000270
Eric Biggers10afa962023-12-01 23:05:24 +0000271 fn onDeviceUnlocked(&self, user_id: i32, password: Option<&[u8]>) -> BinderResult<()> {
272 let _wp = wd::watch_millis("IKeystoreAuthorization::onDeviceUnlocked", 500);
273 map_or_log_err(self.on_device_unlocked(user_id, password.map(|pw| pw.into())), Ok)
274 }
275
Eric Biggers6946daa2024-01-17 22:51:37 +0000276 fn onDeviceLocked(
277 &self,
278 user_id: i32,
279 unlocking_sids: &[i64],
280 weak_unlock_enabled: bool,
281 ) -> BinderResult<()> {
Eric Biggers10afa962023-12-01 23:05:24 +0000282 let _wp = wd::watch_millis("IKeystoreAuthorization::onDeviceLocked", 500);
Eric Biggers6946daa2024-01-17 22:51:37 +0000283 map_or_log_err(self.on_device_locked(user_id, unlocking_sids, weak_unlock_enabled), Ok)
284 }
285
286 fn onWeakUnlockMethodsExpired(&self, user_id: i32) -> BinderResult<()> {
287 let _wp = wd::watch_millis("IKeystoreAuthorization::onWeakUnlockMethodsExpired", 500);
288 map_or_log_err(self.on_weak_unlock_methods_expired(user_id), Ok)
289 }
290
291 fn onNonLskfUnlockMethodsExpired(&self, user_id: i32) -> BinderResult<()> {
292 let _wp = wd::watch_millis("IKeystoreAuthorization::onNonLskfUnlockMethodsExpired", 500);
293 map_or_log_err(self.on_non_lskf_unlock_methods_expired(user_id), Ok)
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000294 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000295
296 fn getAuthTokensForCredStore(
297 &self,
298 challenge: i64,
299 secure_user_id: i64,
300 auth_token_max_age_millis: i64,
Stephen Crane23cf7242022-01-19 17:49:46 +0000301 ) -> binder::Result<AuthorizationTokens> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000302 let _wp = wd::watch_millis("IKeystoreAuthorization::getAuthTokensForCredStore", 500);
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000303 map_or_log_err(
304 self.get_auth_tokens_for_credstore(
305 challenge,
306 secure_user_id,
307 auth_token_max_age_millis,
308 ),
309 Ok,
310 )
311 }
James Willcoxd215da82023-10-03 21:31:31 +0000312
313 fn getLastAuthTime(
314 &self,
315 secure_user_id: i64,
316 auth_types: &[HardwareAuthenticatorType],
317 ) -> binder::Result<i64> {
318 if aconfig_android_hardware_biometrics_rust::last_authentication_time() {
319 map_or_log_err(self.get_last_auth_time(secure_user_id, auth_types), Ok)
320 } else {
321 Err(BinderStatus::new_service_specific_error(
322 ResponseCode::PERMISSION_DENIED.0,
323 Some(CString::new("Feature is not enabled.").unwrap().as_c_str()),
324 ))
325 }
326 }
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000327}