blob: c76f86b01cff4072b8c18db47d08ee721f2e470e [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
David Drysdaledb7ddde2024-06-07 16:22:49 +010054/// Translate an error into a service specific exception, logging along the way.
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +000055///
56/// `Error::Rc(x)` variants get mapped onto a service specific error code of `x`.
57/// Certain response codes may be returned from keystore/ResponseCode.aidl by the keystore2 modules,
58/// which are then converted to the corresponding response codes of android.security.authorization
59/// AIDL interface specification.
60///
61/// `selinux::Error::perm()` is mapped on `ResponseCode::PERMISSION_DENIED`.
62///
63/// All non `Error` error conditions get mapped onto ResponseCode::SYSTEM_ERROR`.
David Drysdaledb7ddde2024-06-07 16:22:49 +010064pub fn into_logged_binder(e: anyhow::Error) -> BinderStatus {
65 log::error!("{:#?}", e);
66 let root_cause = e.root_cause();
67 if let Some(KeystoreError::Rc(ks_rcode)) = root_cause.downcast_ref::<KeystoreError>() {
68 let rc = match *ks_rcode {
69 // Although currently keystore2/ResponseCode.aidl and
70 // authorization/ResponseCode.aidl share the same integer values for the
71 // common response codes, this may deviate in the future, hence the
72 // conversion here.
73 KsResponseCode::SYSTEM_ERROR => ResponseCode::SYSTEM_ERROR.0,
74 KsResponseCode::KEY_NOT_FOUND => ResponseCode::KEY_NOT_FOUND.0,
75 KsResponseCode::VALUE_CORRUPTED => ResponseCode::VALUE_CORRUPTED.0,
76 KsResponseCode::INVALID_ARGUMENT => ResponseCode::INVALID_ARGUMENT.0,
77 // If the code paths of IKeystoreAuthorization aidl's methods happen to return
78 // other error codes from KsResponseCode in the future, they should be converted
79 // as well.
80 _ => ResponseCode::SYSTEM_ERROR.0,
81 };
82 BinderStatus::new_service_specific_error(rc, anyhow_error_to_cstring(&e).as_deref())
83 } else {
84 let rc = match root_cause.downcast_ref::<Error>() {
85 Some(Error::Rc(rcode)) => rcode.0,
86 Some(Error::Binder(_, _)) => ResponseCode::SYSTEM_ERROR.0,
87 None => match root_cause.downcast_ref::<selinux::Error>() {
88 Some(selinux::Error::PermissionDenied) => ResponseCode::PERMISSION_DENIED.0,
David Drysdale5238d772024-06-07 15:12:10 +010089 _ => ResponseCode::SYSTEM_ERROR.0,
David Drysdaledb7ddde2024-06-07 16:22:49 +010090 },
91 };
92 BinderStatus::new_service_specific_error(rc, anyhow_error_to_cstring(&e).as_deref())
93 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +000094}
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +000095
96/// This struct is defined to implement the aforementioned AIDL interface.
97/// As of now, it is an empty struct.
98pub struct AuthorizationManager;
99
100impl AuthorizationManager {
101 /// Create a new instance of Keystore Authorization service.
Stephen Crane221bbb52020-12-16 15:52:10 -0800102 pub fn new_native_binder() -> Result<Strong<dyn IKeystoreAuthorization>> {
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000103 Ok(BnKeystoreAuthorization::new_binder(
104 Self,
105 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
106 ))
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000107 }
108
109 fn add_auth_token(&self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700110 // Check keystore permission.
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000111 check_keystore_permission(KeystorePerm::AddAuth)
112 .context(ks_err!("caller missing AddAuth permissions"))?;
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000113
David Drysdalebf2d72f2023-06-15 13:38:36 +0100114 log::info!(
115 "add_auth_token(challenge={}, userId={}, authId={}, authType={:#x}, timestamp={}ms)",
116 auth_token.challenge,
117 auth_token.userId,
118 auth_token.authenticatorId,
119 auth_token.authenticatorType.0,
120 auth_token.timestamp.milliSeconds,
121 );
122
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700123 ENFORCEMENTS.add_auth_token(auth_token.clone());
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000124 Ok(())
125 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000126
Eric Biggers10afa962023-12-01 23:05:24 +0000127 fn on_device_unlocked(&self, user_id: i32, password: Option<Password>) -> Result<()> {
Paul Crowley618869e2021-04-08 20:30:54 -0700128 log::info!(
Eric Biggers10afa962023-12-01 23:05:24 +0000129 "on_device_unlocked(user_id={}, password.is_some()={})",
Paul Crowley618869e2021-04-08 20:30:54 -0700130 user_id,
131 password.is_some(),
Paul Crowley618869e2021-04-08 20:30:54 -0700132 );
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000133 check_keystore_permission(KeystorePerm::Unlock)
134 .context(ks_err!("caller missing Unlock permissions"))?;
Eric Biggers10afa962023-12-01 23:05:24 +0000135 ENFORCEMENTS.set_device_locked(user_id, false);
Paul Crowley7a658392021-03-18 17:08:20 -0700136
Eric Biggers10afa962023-12-01 23:05:24 +0000137 let mut skm = SUPER_KEY.write().unwrap();
138 if let Some(password) = password {
139 DB.with(|db| {
140 skm.unlock_user(&mut db.borrow_mut(), &LEGACY_IMPORTER, user_id as u32, &password)
141 })
142 .context(ks_err!("Unlock with password."))
143 } else {
144 DB.with(|db| skm.try_unlock_user_with_biometric(&mut db.borrow_mut(), user_id as u32))
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000145 .context(ks_err!("try_unlock_user_with_biometric failed user_id={user_id}"))
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000146 }
147 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000148
Eric Biggers6946daa2024-01-17 22:51:37 +0000149 fn on_device_locked(
150 &self,
151 user_id: i32,
152 unlocking_sids: &[i64],
Eric Biggers9f7ebeb2024-06-20 14:59:32 +0000153 weak_unlock_enabled: bool,
Eric Biggers6946daa2024-01-17 22:51:37 +0000154 ) -> Result<()> {
155 log::info!(
156 "on_device_locked(user_id={}, unlocking_sids={:?}, weak_unlock_enabled={})",
157 user_id,
158 unlocking_sids,
159 weak_unlock_enabled
160 );
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000161 check_keystore_permission(KeystorePerm::Lock)
162 .context(ks_err!("caller missing Lock permission"))?;
Eric Biggers10afa962023-12-01 23:05:24 +0000163 ENFORCEMENTS.set_device_locked(user_id, true);
164 let mut skm = SUPER_KEY.write().unwrap();
165 DB.with(|db| {
166 skm.lock_unlocked_device_required_keys(
167 &mut db.borrow_mut(),
168 user_id as u32,
169 unlocking_sids,
Eric Biggers6946daa2024-01-17 22:51:37 +0000170 weak_unlock_enabled,
Eric Biggers10afa962023-12-01 23:05:24 +0000171 );
172 });
173 Ok(())
174 }
175
Eric Biggers6946daa2024-01-17 22:51:37 +0000176 fn on_weak_unlock_methods_expired(&self, user_id: i32) -> Result<()> {
177 log::info!("on_weak_unlock_methods_expired(user_id={})", user_id);
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000178 check_keystore_permission(KeystorePerm::Lock)
179 .context(ks_err!("caller missing Lock permission"))?;
Eric Biggers6946daa2024-01-17 22:51:37 +0000180 SUPER_KEY.write().unwrap().wipe_plaintext_unlocked_device_required_keys(user_id as u32);
181 Ok(())
182 }
183
184 fn on_non_lskf_unlock_methods_expired(&self, user_id: i32) -> Result<()> {
185 log::info!("on_non_lskf_unlock_methods_expired(user_id={})", user_id);
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000186 check_keystore_permission(KeystorePerm::Lock)
187 .context(ks_err!("caller missing Lock permission"))?;
Eric Biggers6946daa2024-01-17 22:51:37 +0000188 SUPER_KEY.write().unwrap().wipe_all_unlocked_device_required_keys(user_id as u32);
189 Ok(())
190 }
191
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000192 fn get_auth_tokens_for_credstore(
193 &self,
194 challenge: i64,
195 secure_user_id: i64,
196 auth_token_max_age_millis: i64,
197 ) -> Result<AuthorizationTokens> {
198 // Check permission. Function should return if this failed. Therefore having '?' at the end
199 // is very important.
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000200 check_keystore_permission(KeystorePerm::GetAuthToken)
201 .context(ks_err!("caller missing GetAuthToken permission"))?;
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000202
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700203 // If the challenge is zero, return error
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000204 if challenge == 0 {
205 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000206 .context(ks_err!("Challenge can not be zero."));
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000207 }
208 // Obtain the auth token and the timestamp token from the enforcement module.
209 let (auth_token, ts_token) =
210 ENFORCEMENTS.get_auth_tokens(challenge, secure_user_id, auth_token_max_age_millis)?;
211 Ok(AuthorizationTokens { authToken: auth_token, timestampToken: ts_token })
212 }
James Willcoxd215da82023-10-03 21:31:31 +0000213
214 fn get_last_auth_time(
215 &self,
216 secure_user_id: i64,
217 auth_types: &[HardwareAuthenticatorType],
218 ) -> Result<i64> {
219 // Check keystore permission.
Shaquille Johnsona4d10db2024-02-28 20:39:14 +0000220 check_keystore_permission(KeystorePerm::GetLastAuthTime)
221 .context(ks_err!("caller missing GetLastAuthTime permission"))?;
James Willcoxd215da82023-10-03 21:31:31 +0000222
223 let mut max_time: i64 = -1;
224 for auth_type in auth_types.iter() {
225 if let Some(time) = ENFORCEMENTS.get_last_auth_time(secure_user_id, *auth_type) {
226 if time.milliseconds() > max_time {
227 max_time = time.milliseconds();
228 }
229 }
230 }
231
232 if max_time >= 0 {
233 Ok(max_time)
234 } else {
235 Err(Error::Rc(ResponseCode::NO_AUTH_TOKEN_FOUND))
236 .context(ks_err!("No auth token found"))
237 }
238 }
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000239}
240
241impl Interface for AuthorizationManager {}
242
243impl IKeystoreAuthorization for AuthorizationManager {
244 fn addAuthToken(&self, auth_token: &HardwareAuthToken) -> BinderResult<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100245 let _wp = wd::watch("IKeystoreAuthorization::addAuthToken");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100246 self.add_auth_token(auth_token).map_err(into_logged_binder)
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000247 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000248
Eric Biggers10afa962023-12-01 23:05:24 +0000249 fn onDeviceUnlocked(&self, user_id: i32, password: Option<&[u8]>) -> BinderResult<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100250 let _wp = wd::watch("IKeystoreAuthorization::onDeviceUnlocked");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100251 self.on_device_unlocked(user_id, password.map(|pw| pw.into())).map_err(into_logged_binder)
Eric Biggers10afa962023-12-01 23:05:24 +0000252 }
253
Eric Biggers6946daa2024-01-17 22:51:37 +0000254 fn onDeviceLocked(
255 &self,
256 user_id: i32,
257 unlocking_sids: &[i64],
258 weak_unlock_enabled: bool,
259 ) -> BinderResult<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100260 let _wp = wd::watch("IKeystoreAuthorization::onDeviceLocked");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100261 self.on_device_locked(user_id, unlocking_sids, weak_unlock_enabled)
262 .map_err(into_logged_binder)
Eric Biggers6946daa2024-01-17 22:51:37 +0000263 }
264
265 fn onWeakUnlockMethodsExpired(&self, user_id: i32) -> BinderResult<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100266 let _wp = wd::watch("IKeystoreAuthorization::onWeakUnlockMethodsExpired");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100267 self.on_weak_unlock_methods_expired(user_id).map_err(into_logged_binder)
Eric Biggers6946daa2024-01-17 22:51:37 +0000268 }
269
270 fn onNonLskfUnlockMethodsExpired(&self, user_id: i32) -> BinderResult<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100271 let _wp = wd::watch("IKeystoreAuthorization::onNonLskfUnlockMethodsExpired");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100272 self.on_non_lskf_unlock_methods_expired(user_id).map_err(into_logged_binder)
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000273 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000274
275 fn getAuthTokensForCredStore(
276 &self,
277 challenge: i64,
278 secure_user_id: i64,
279 auth_token_max_age_millis: i64,
Stephen Crane23cf7242022-01-19 17:49:46 +0000280 ) -> binder::Result<AuthorizationTokens> {
David Drysdale541846b2024-05-23 13:16:07 +0100281 let _wp = wd::watch("IKeystoreAuthorization::getAuthTokensForCredStore");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100282 self.get_auth_tokens_for_credstore(challenge, secure_user_id, auth_token_max_age_millis)
283 .map_err(into_logged_binder)
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000284 }
James Willcoxd215da82023-10-03 21:31:31 +0000285
286 fn getLastAuthTime(
287 &self,
288 secure_user_id: i64,
289 auth_types: &[HardwareAuthenticatorType],
290 ) -> binder::Result<i64> {
291 if aconfig_android_hardware_biometrics_rust::last_authentication_time() {
David Drysdaledb7ddde2024-06-07 16:22:49 +0100292 self.get_last_auth_time(secure_user_id, auth_types).map_err(into_logged_binder)
James Willcoxd215da82023-10-03 21:31:31 +0000293 } else {
294 Err(BinderStatus::new_service_specific_error(
295 ResponseCode::PERMISSION_DENIED.0,
296 Some(CString::new("Feature is not enabled.").unwrap().as_c_str()),
297 ))
298 }
299 }
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000300}