blob: 243abf13e1fd4aa54ada4756cfbce202d3512b2e [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 Johnsona4d10db2024-02-28 20:39:14 +0000131 check_keystore_permission(KeystorePerm::AddAuth)
132 .context(ks_err!("caller missing AddAuth permissions"))?;
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000133
David Drysdalebf2d72f2023-06-15 13:38:36 +0100134 log::info!(
135 "add_auth_token(challenge={}, userId={}, authId={}, authType={:#x}, timestamp={}ms)",
136 auth_token.challenge,
137 auth_token.userId,
138 auth_token.authenticatorId,
139 auth_token.authenticatorType.0,
140 auth_token.timestamp.milliSeconds,
141 );
142
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700143 ENFORCEMENTS.add_auth_token(auth_token.clone());
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000144 Ok(())
145 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000146
Eric Biggers10afa962023-12-01 23:05:24 +0000147 fn on_device_unlocked(&self, user_id: i32, password: Option<Password>) -> Result<()> {
Paul Crowley618869e2021-04-08 20:30:54 -0700148 log::info!(
Eric Biggers10afa962023-12-01 23:05:24 +0000149 "on_device_unlocked(user_id={}, password.is_some()={})",
Paul Crowley618869e2021-04-08 20:30:54 -0700150 user_id,
151 password.is_some(),
Paul Crowley618869e2021-04-08 20:30:54 -0700152 );
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000153 check_keystore_permission(KeystorePerm::Unlock)
154 .context(ks_err!("caller missing Unlock permissions"))?;
Eric Biggers10afa962023-12-01 23:05:24 +0000155 ENFORCEMENTS.set_device_locked(user_id, false);
Paul Crowley7a658392021-03-18 17:08:20 -0700156
Eric Biggers10afa962023-12-01 23:05:24 +0000157 let mut skm = SUPER_KEY.write().unwrap();
158 if let Some(password) = password {
159 DB.with(|db| {
160 skm.unlock_user(&mut db.borrow_mut(), &LEGACY_IMPORTER, user_id as u32, &password)
161 })
162 .context(ks_err!("Unlock with password."))
163 } else {
164 DB.with(|db| skm.try_unlock_user_with_biometric(&mut db.borrow_mut(), user_id as u32))
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000165 .context(ks_err!("try_unlock_user_with_biometric failed user_id={user_id}"))
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000166 }
167 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000168
Eric Biggers6946daa2024-01-17 22:51:37 +0000169 fn on_device_locked(
170 &self,
171 user_id: i32,
172 unlocking_sids: &[i64],
173 mut weak_unlock_enabled: bool,
174 ) -> Result<()> {
175 log::info!(
176 "on_device_locked(user_id={}, unlocking_sids={:?}, weak_unlock_enabled={})",
177 user_id,
178 unlocking_sids,
179 weak_unlock_enabled
180 );
181 if !android_security_flags::fix_unlocked_device_required_keys_v2() {
182 weak_unlock_enabled = false;
183 }
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000184 check_keystore_permission(KeystorePerm::Lock)
185 .context(ks_err!("caller missing Lock permission"))?;
Eric Biggers10afa962023-12-01 23:05:24 +0000186 ENFORCEMENTS.set_device_locked(user_id, true);
187 let mut skm = SUPER_KEY.write().unwrap();
188 DB.with(|db| {
189 skm.lock_unlocked_device_required_keys(
190 &mut db.borrow_mut(),
191 user_id as u32,
192 unlocking_sids,
Eric Biggers6946daa2024-01-17 22:51:37 +0000193 weak_unlock_enabled,
Eric Biggers10afa962023-12-01 23:05:24 +0000194 );
195 });
196 Ok(())
197 }
198
Eric Biggers6946daa2024-01-17 22:51:37 +0000199 fn on_weak_unlock_methods_expired(&self, user_id: i32) -> Result<()> {
200 log::info!("on_weak_unlock_methods_expired(user_id={})", user_id);
201 if !android_security_flags::fix_unlocked_device_required_keys_v2() {
202 return Ok(());
203 }
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000204 check_keystore_permission(KeystorePerm::Lock)
205 .context(ks_err!("caller missing Lock permission"))?;
Eric Biggers6946daa2024-01-17 22:51:37 +0000206 SUPER_KEY.write().unwrap().wipe_plaintext_unlocked_device_required_keys(user_id as u32);
207 Ok(())
208 }
209
210 fn on_non_lskf_unlock_methods_expired(&self, user_id: i32) -> Result<()> {
211 log::info!("on_non_lskf_unlock_methods_expired(user_id={})", user_id);
212 if !android_security_flags::fix_unlocked_device_required_keys_v2() {
213 return Ok(());
214 }
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000215 check_keystore_permission(KeystorePerm::Lock)
216 .context(ks_err!("caller missing Lock permission"))?;
Eric Biggers6946daa2024-01-17 22:51:37 +0000217 SUPER_KEY.write().unwrap().wipe_all_unlocked_device_required_keys(user_id as u32);
218 Ok(())
219 }
220
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000221 fn get_auth_tokens_for_credstore(
222 &self,
223 challenge: i64,
224 secure_user_id: i64,
225 auth_token_max_age_millis: i64,
226 ) -> Result<AuthorizationTokens> {
227 // Check permission. Function should return if this failed. Therefore having '?' at the end
228 // is very important.
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000229 check_keystore_permission(KeystorePerm::GetAuthToken)
230 .context(ks_err!("caller missing GetAuthToken permission"))?;
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000231
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700232 // If the challenge is zero, return error
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000233 if challenge == 0 {
234 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000235 .context(ks_err!("Challenge can not be zero."));
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000236 }
237 // Obtain the auth token and the timestamp token from the enforcement module.
238 let (auth_token, ts_token) =
239 ENFORCEMENTS.get_auth_tokens(challenge, secure_user_id, auth_token_max_age_millis)?;
240 Ok(AuthorizationTokens { authToken: auth_token, timestampToken: ts_token })
241 }
James Willcoxd215da82023-10-03 21:31:31 +0000242
243 fn get_last_auth_time(
244 &self,
245 secure_user_id: i64,
246 auth_types: &[HardwareAuthenticatorType],
247 ) -> Result<i64> {
248 // Check keystore permission.
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000249 check_keystore_permission(KeystorePerm::GetLastAuthTime)
250 .context(ks_err!("caller missing GetLastAuthTime permission"))?;
James Willcoxd215da82023-10-03 21:31:31 +0000251
252 let mut max_time: i64 = -1;
253 for auth_type in auth_types.iter() {
254 if let Some(time) = ENFORCEMENTS.get_last_auth_time(secure_user_id, *auth_type) {
255 if time.milliseconds() > max_time {
256 max_time = time.milliseconds();
257 }
258 }
259 }
260
261 if max_time >= 0 {
262 Ok(max_time)
263 } else {
264 Err(Error::Rc(ResponseCode::NO_AUTH_TOKEN_FOUND))
265 .context(ks_err!("No auth token found"))
266 }
267 }
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000268}
269
270impl Interface for AuthorizationManager {}
271
272impl IKeystoreAuthorization for AuthorizationManager {
273 fn addAuthToken(&self, auth_token: &HardwareAuthToken) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000274 let _wp = wd::watch_millis("IKeystoreAuthorization::addAuthToken", 500);
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000275 map_or_log_err(self.add_auth_token(auth_token), Ok)
276 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000277
Eric Biggers10afa962023-12-01 23:05:24 +0000278 fn onDeviceUnlocked(&self, user_id: i32, password: Option<&[u8]>) -> BinderResult<()> {
279 let _wp = wd::watch_millis("IKeystoreAuthorization::onDeviceUnlocked", 500);
280 map_or_log_err(self.on_device_unlocked(user_id, password.map(|pw| pw.into())), Ok)
281 }
282
Eric Biggers6946daa2024-01-17 22:51:37 +0000283 fn onDeviceLocked(
284 &self,
285 user_id: i32,
286 unlocking_sids: &[i64],
287 weak_unlock_enabled: bool,
288 ) -> BinderResult<()> {
Eric Biggers10afa962023-12-01 23:05:24 +0000289 let _wp = wd::watch_millis("IKeystoreAuthorization::onDeviceLocked", 500);
Eric Biggers6946daa2024-01-17 22:51:37 +0000290 map_or_log_err(self.on_device_locked(user_id, unlocking_sids, weak_unlock_enabled), Ok)
291 }
292
293 fn onWeakUnlockMethodsExpired(&self, user_id: i32) -> BinderResult<()> {
294 let _wp = wd::watch_millis("IKeystoreAuthorization::onWeakUnlockMethodsExpired", 500);
295 map_or_log_err(self.on_weak_unlock_methods_expired(user_id), Ok)
296 }
297
298 fn onNonLskfUnlockMethodsExpired(&self, user_id: i32) -> BinderResult<()> {
299 let _wp = wd::watch_millis("IKeystoreAuthorization::onNonLskfUnlockMethodsExpired", 500);
300 map_or_log_err(self.on_non_lskf_unlock_methods_expired(user_id), Ok)
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000301 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000302
303 fn getAuthTokensForCredStore(
304 &self,
305 challenge: i64,
306 secure_user_id: i64,
307 auth_token_max_age_millis: i64,
Stephen Crane23cf7242022-01-19 17:49:46 +0000308 ) -> binder::Result<AuthorizationTokens> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000309 let _wp = wd::watch_millis("IKeystoreAuthorization::getAuthTokensForCredStore", 500);
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000310 map_or_log_err(
311 self.get_auth_tokens_for_credstore(
312 challenge,
313 secure_user_id,
314 auth_token_max_age_millis,
315 ),
316 Ok,
317 )
318 }
James Willcoxd215da82023-10-03 21:31:31 +0000319
320 fn getLastAuthTime(
321 &self,
322 secure_user_id: i64,
323 auth_types: &[HardwareAuthenticatorType],
324 ) -> binder::Result<i64> {
325 if aconfig_android_hardware_biometrics_rust::last_authentication_time() {
326 map_or_log_err(self.get_last_auth_time(secure_user_id, auth_types), Ok)
327 } else {
328 Err(BinderStatus::new_service_specific_error(
329 ResponseCode::PERMISSION_DENIED.0,
330 Some(CString::new("Feature is not enabled.").unwrap().as_c_str()),
331 ))
332 }
333 }
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000334}