blob: 8265dd025bba88f6baf536ba16ff76b21155d659 [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
Hasini Gunasinghea020b532021-01-07 21:42:35 +000017use crate::error::Error as KeystoreError;
Janis Danisevskisea03cff2021-12-16 08:10:17 -080018use crate::error::anyhow_error_to_cstring;
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080019use crate::globals::{ENFORCEMENTS, SUPER_KEY, DB, LEGACY_IMPORTER};
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +000020use crate::permission::KeystorePerm;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +000021use crate::super_key::UserState;
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +000022use crate::utils::{check_keystore_permission, watchdog as wd};
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +000023use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Hasini Gunasingheda895552021-01-27 19:34:37 +000024 HardwareAuthToken::HardwareAuthToken,
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +000025};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000026use android_security_authorization::binder::{BinderFeatures,ExceptionCode, Interface, Result as BinderResult,
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +000027 Strong, Status as BinderStatus};
28use android_security_authorization::aidl::android::security::authorization::{
29 IKeystoreAuthorization::BnKeystoreAuthorization, IKeystoreAuthorization::IKeystoreAuthorization,
30 LockScreenEvent::LockScreenEvent, AuthorizationTokens::AuthorizationTokens,
31 ResponseCode::ResponseCode,
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +000032};
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +000033use android_system_keystore2::aidl::android::system::keystore2::{
34 ResponseCode::ResponseCode as KsResponseCode };
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +000035use anyhow::{Context, Result};
Paul Crowleyf61fee72021-03-17 14:38:44 -070036use keystore2_crypto::Password;
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +000037use keystore2_selinux as selinux;
38
39/// This is the Authorization error type, it wraps binder exceptions and the
40/// Authorization ResponseCode
41#[derive(Debug, thiserror::Error, PartialEq)]
42pub enum Error {
43 /// Wraps an IKeystoreAuthorization response code as defined by
44 /// android.security.authorization AIDL interface specification.
45 #[error("Error::Rc({0:?})")]
46 Rc(ResponseCode),
47 /// Wraps a Binder exception code other than a service specific exception.
48 #[error("Binder exception code {0:?}, {1:?}")]
49 Binder(ExceptionCode, i32),
50}
51
52/// This function should be used by authorization service calls to translate error conditions
53/// into service specific exceptions.
54///
55/// All error conditions get logged by this function.
56///
57/// `Error::Rc(x)` variants get mapped onto a service specific error code of `x`.
58/// Certain response codes may be returned from keystore/ResponseCode.aidl by the keystore2 modules,
59/// which are then converted to the corresponding response codes of android.security.authorization
60/// AIDL interface specification.
61///
62/// `selinux::Error::perm()` is mapped on `ResponseCode::PERMISSION_DENIED`.
63///
64/// All non `Error` error conditions get mapped onto ResponseCode::SYSTEM_ERROR`.
65///
66/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
67/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
68/// typically returns Ok(value).
69pub fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
70where
71 F: FnOnce(U) -> BinderResult<T>,
72{
73 result.map_or_else(
74 |e| {
75 log::error!("{:#?}", e);
76 let root_cause = e.root_cause();
77 if let Some(KeystoreError::Rc(ks_rcode)) = root_cause.downcast_ref::<KeystoreError>() {
78 let rc = match *ks_rcode {
79 // Although currently keystore2/ResponseCode.aidl and
80 // authorization/ResponseCode.aidl share the same integer values for the
81 // common response codes, this may deviate in the future, hence the
82 // conversion here.
83 KsResponseCode::SYSTEM_ERROR => ResponseCode::SYSTEM_ERROR.0,
84 KsResponseCode::KEY_NOT_FOUND => ResponseCode::KEY_NOT_FOUND.0,
85 KsResponseCode::VALUE_CORRUPTED => ResponseCode::VALUE_CORRUPTED.0,
86 KsResponseCode::INVALID_ARGUMENT => ResponseCode::INVALID_ARGUMENT.0,
87 // If the code paths of IKeystoreAuthorization aidl's methods happen to return
88 // other error codes from KsResponseCode in the future, they should be converted
89 // as well.
90 _ => ResponseCode::SYSTEM_ERROR.0,
91 };
Janis Danisevskisea03cff2021-12-16 08:10:17 -080092 return Err(BinderStatus::new_service_specific_error(
93 rc,
94 anyhow_error_to_cstring(&e).as_deref(),
95 ));
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +000096 }
97 let rc = match root_cause.downcast_ref::<Error>() {
98 Some(Error::Rc(rcode)) => rcode.0,
99 Some(Error::Binder(_, _)) => ResponseCode::SYSTEM_ERROR.0,
100 None => match root_cause.downcast_ref::<selinux::Error>() {
101 Some(selinux::Error::PermissionDenied) => ResponseCode::PERMISSION_DENIED.0,
102 _ => ResponseCode::SYSTEM_ERROR.0,
103 },
104 };
Janis Danisevskisea03cff2021-12-16 08:10:17 -0800105 Err(BinderStatus::new_service_specific_error(
106 rc,
107 anyhow_error_to_cstring(&e).as_deref(),
108 ))
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000109 },
110 handle_ok,
111 )
112}
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000113
114/// This struct is defined to implement the aforementioned AIDL interface.
115/// As of now, it is an empty struct.
116pub struct AuthorizationManager;
117
118impl AuthorizationManager {
119 /// Create a new instance of Keystore Authorization service.
Stephen Crane221bbb52020-12-16 15:52:10 -0800120 pub fn new_native_binder() -> Result<Strong<dyn IKeystoreAuthorization>> {
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000121 Ok(BnKeystoreAuthorization::new_binder(
122 Self,
123 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
124 ))
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000125 }
126
127 fn add_auth_token(&self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700128 // Check keystore permission.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700129 check_keystore_permission(KeystorePerm::AddAuth).context("In add_auth_token.")?;
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000130
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700131 ENFORCEMENTS.add_auth_token(auth_token.clone());
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000132 Ok(())
133 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000134
135 fn on_lock_screen_event(
136 &self,
137 lock_screen_event: LockScreenEvent,
138 user_id: i32,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700139 password: Option<Password>,
Paul Crowley618869e2021-04-08 20:30:54 -0700140 unlocking_sids: Option<&[i64]>,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000141 ) -> Result<()> {
Paul Crowley618869e2021-04-08 20:30:54 -0700142 log::info!(
143 "on_lock_screen_event({:?}, user_id={:?}, password.is_some()={}, unlocking_sids={:?})",
144 lock_screen_event,
145 user_id,
146 password.is_some(),
147 unlocking_sids
148 );
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000149 match (lock_screen_event, password) {
Paul Crowleyf61fee72021-03-17 14:38:44 -0700150 (LockScreenEvent::UNLOCK, Some(password)) => {
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700151 // This corresponds to the unlock() method in legacy keystore API.
152 // check permission
Janis Danisevskisa916d992021-10-19 15:46:09 -0700153 check_keystore_permission(KeystorePerm::Unlock)
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000154 .context("In on_lock_screen_event: Unlock with password.")?;
155 ENFORCEMENTS.set_device_locked(user_id, false);
Paul Crowley7a658392021-03-18 17:08:20 -0700156
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800157 let mut skm = SUPER_KEY.write().unwrap();
158
Paul Crowley7a658392021-03-18 17:08:20 -0700159 DB.with(|db| {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800160 skm.unlock_screen_lock_bound_key(
Paul Crowley7a658392021-03-18 17:08:20 -0700161 &mut db.borrow_mut(),
162 user_id as u32,
163 &password,
164 )
165 })
166 .context("In on_lock_screen_event: unlock_screen_lock_bound_key failed")?;
167
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000168 // Unlock super key.
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000169 if let UserState::Uninitialized = DB
170 .with(|db| {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800171 skm.unlock_and_get_user_state(
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000172 &mut db.borrow_mut(),
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -0800173 &LEGACY_IMPORTER,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000174 user_id as u32,
Paul Crowleyf61fee72021-03-17 14:38:44 -0700175 &password,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +0000176 )
177 })
178 .context("In on_lock_screen_event: Unlock with password.")?
179 {
180 log::info!(
181 "In on_lock_screen_event. Trying to unlock when LSKF is uninitialized."
182 );
183 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000184
185 Ok(())
186 }
187 (LockScreenEvent::UNLOCK, None) => {
Janis Danisevskisa916d992021-10-19 15:46:09 -0700188 check_keystore_permission(KeystorePerm::Unlock)
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000189 .context("In on_lock_screen_event: Unlock.")?;
190 ENFORCEMENTS.set_device_locked(user_id, false);
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800191 let mut skm = SUPER_KEY.write().unwrap();
Paul Crowley618869e2021-04-08 20:30:54 -0700192 DB.with(|db| {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800193 skm.try_unlock_user_with_biometric(&mut db.borrow_mut(), user_id as u32)
Paul Crowley618869e2021-04-08 20:30:54 -0700194 })
195 .context("In on_lock_screen_event: try_unlock_user_with_biometric failed")?;
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000196 Ok(())
197 }
198 (LockScreenEvent::LOCK, None) => {
Janis Danisevskisa916d992021-10-19 15:46:09 -0700199 check_keystore_permission(KeystorePerm::Lock)
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000200 .context("In on_lock_screen_event: Lock")?;
201 ENFORCEMENTS.set_device_locked(user_id, true);
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800202 let mut skm = SUPER_KEY.write().unwrap();
Paul Crowley618869e2021-04-08 20:30:54 -0700203 DB.with(|db| {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -0800204 skm.lock_screen_lock_bound_key(
Paul Crowley618869e2021-04-08 20:30:54 -0700205 &mut db.borrow_mut(),
206 user_id as u32,
207 unlocking_sids.unwrap_or(&[]),
208 );
209 });
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000210 Ok(())
211 }
212 _ => {
213 // Any other combination is not supported.
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000214 Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000215 .context("In on_lock_screen_event: Unknown event.")
216 }
217 }
218 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000219
220 fn get_auth_tokens_for_credstore(
221 &self,
222 challenge: i64,
223 secure_user_id: i64,
224 auth_token_max_age_millis: i64,
225 ) -> Result<AuthorizationTokens> {
226 // Check permission. Function should return if this failed. Therefore having '?' at the end
227 // is very important.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700228 check_keystore_permission(KeystorePerm::GetAuthToken)
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000229 .context("In get_auth_tokens_for_credstore.")?;
230
Janis Danisevskisbe1969e2021-04-20 15:16:24 -0700231 // If the challenge is zero, return error
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000232 if challenge == 0 {
233 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
234 .context("In get_auth_tokens_for_credstore. Challenge can not be zero.");
235 }
236 // Obtain the auth token and the timestamp token from the enforcement module.
237 let (auth_token, ts_token) =
238 ENFORCEMENTS.get_auth_tokens(challenge, secure_user_id, auth_token_max_age_millis)?;
239 Ok(AuthorizationTokens { authToken: auth_token, timestampToken: ts_token })
240 }
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000241}
242
243impl Interface for AuthorizationManager {}
244
245impl IKeystoreAuthorization for AuthorizationManager {
246 fn addAuthToken(&self, auth_token: &HardwareAuthToken) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000247 let _wp = wd::watch_millis("IKeystoreAuthorization::addAuthToken", 500);
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000248 map_or_log_err(self.add_auth_token(auth_token), Ok)
249 }
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000250
251 fn onLockScreenEvent(
252 &self,
253 lock_screen_event: LockScreenEvent,
254 user_id: i32,
255 password: Option<&[u8]>,
Paul Crowley618869e2021-04-08 20:30:54 -0700256 unlocking_sids: Option<&[i64]>,
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000257 ) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000258 let _wp =
259 wd::watch_millis_with("IKeystoreAuthorization::onLockScreenEvent", 500, move || {
260 format!("lock event: {}", lock_screen_event.0)
261 });
Paul Crowleyf61fee72021-03-17 14:38:44 -0700262 map_or_log_err(
Paul Crowley618869e2021-04-08 20:30:54 -0700263 self.on_lock_screen_event(
264 lock_screen_event,
265 user_id,
266 password.map(|pw| pw.into()),
267 unlocking_sids,
268 ),
Paul Crowleyf61fee72021-03-17 14:38:44 -0700269 Ok,
270 )
Hasini Gunasinghea020b532021-01-07 21:42:35 +0000271 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000272
273 fn getAuthTokensForCredStore(
274 &self,
275 challenge: i64,
276 secure_user_id: i64,
277 auth_token_max_age_millis: i64,
Stephen Crane23cf7242022-01-19 17:49:46 +0000278 ) -> binder::Result<AuthorizationTokens> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000279 let _wp = wd::watch_millis("IKeystoreAuthorization::getAuthTokensForCredStore", 500);
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000280 map_or_log_err(
281 self.get_auth_tokens_for_credstore(
282 challenge,
283 secure_user_id,
284 auth_token_max_age_millis,
285 ),
286 Ok,
287 )
288 }
Janis Danisevskis9f10a6a2021-01-18 16:45:21 +0000289}