blob: 57abc26e3f9748dae083514b19b73a7a1238bab0 [file] [log] [blame]
Hasini Gunasingheda895552021-01-27 19:34:37 +00001// Copyright 2021, 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
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080015//! This module implements IKeystoreMaintenance AIDL interface.
Hasini Gunasingheda895552021-01-27 19:34:37 +000016
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -070017use crate::database::{KeyEntryLoadBits, KeyType, MonotonicRawTime};
Satya Tangirala5b9e5b12021-03-09 12:54:21 -080018use crate::error::map_km_error;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -070019use crate::error::map_or_log_err;
20use crate::error::Error;
Satya Tangirala5b9e5b12021-03-09 12:54:21 -080021use crate::globals::get_keymint_device;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000022use crate::globals::{DB, LEGACY_MIGRATOR, SUPER_KEY};
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -070023use crate::permission::{KeyPerm, KeystorePerm};
Hasini Gunasingheda895552021-01-27 19:34:37 +000024use crate::super_key::UserState;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -070025use crate::utils::{check_key_permission, check_keystore_permission, watchdog as wd};
Paul Crowley46c703e2021-08-06 15:13:53 -070026use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
27 IKeyMintDevice::IKeyMintDevice, SecurityLevel::SecurityLevel,
28};
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +000029use android_security_maintenance::aidl::android::security::maintenance::{
30 IKeystoreMaintenance::{BnKeystoreMaintenance, IKeystoreMaintenance},
31 UserState::UserState as AidlUserState,
Hasini Gunasingheda895552021-01-27 19:34:37 +000032};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000033use android_security_maintenance::binder::{
34 BinderFeatures, Interface, Result as BinderResult, Strong, ThreadState,
35};
Janis Danisevskis5898d152021-06-15 08:23:46 -070036use android_system_keystore2::aidl::android::system::keystore2::KeyDescriptor::KeyDescriptor;
Hasini Gunasingheda895552021-01-27 19:34:37 +000037use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode;
38use anyhow::{Context, Result};
Paul Crowleyf61fee72021-03-17 14:38:44 -070039use keystore2_crypto::Password;
Hasini Gunasingheda895552021-01-27 19:34:37 +000040
Janis Danisevskis5898d152021-06-15 08:23:46 -070041/// Reexport Domain for the benefit of DeleteListener
42pub use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain;
43
44/// The Maintenance module takes a delete listener argument which observes user and namespace
45/// deletion events.
46pub trait DeleteListener {
47 /// Called by the maintenance module when an app/namespace is deleted.
48 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()>;
49 /// Called by the maintenance module when a user is deleted.
50 fn delete_user(&self, user_id: u32) -> Result<()>;
51}
52
Hasini Gunasingheda895552021-01-27 19:34:37 +000053/// This struct is defined to implement the aforementioned AIDL interface.
Janis Danisevskis5898d152021-06-15 08:23:46 -070054pub struct Maintenance {
55 delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>,
56}
Hasini Gunasingheda895552021-01-27 19:34:37 +000057
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080058impl Maintenance {
Janis Danisevskis5898d152021-06-15 08:23:46 -070059 /// Create a new instance of Keystore Maintenance service.
60 pub fn new_native_binder(
61 delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>,
62 ) -> Result<Strong<dyn IKeystoreMaintenance>> {
Andrew Walbrande45c8b2021-04-13 14:42:38 +000063 Ok(BnKeystoreMaintenance::new_binder(
Janis Danisevskis5898d152021-06-15 08:23:46 -070064 Self { delete_listener },
Andrew Walbrande45c8b2021-04-13 14:42:38 +000065 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
66 ))
Hasini Gunasingheda895552021-01-27 19:34:37 +000067 }
68
Paul Crowleyf61fee72021-03-17 14:38:44 -070069 fn on_user_password_changed(user_id: i32, password: Option<Password>) -> Result<()> {
Hasini Gunasingheda895552021-01-27 19:34:37 +000070 //Check permission. Function should return if this failed. Therefore having '?' at the end
71 //is very important.
Janis Danisevskisa916d992021-10-19 15:46:09 -070072 check_keystore_permission(KeystorePerm::ChangePassword)
Hasini Gunasingheda895552021-01-27 19:34:37 +000073 .context("In on_user_password_changed.")?;
74
Paul Crowley7a658392021-03-18 17:08:20 -070075 if let Some(pw) = password.as_ref() {
76 DB.with(|db| {
Paul Crowley8d5b2532021-03-19 10:53:07 -070077 SUPER_KEY.unlock_screen_lock_bound_key(&mut db.borrow_mut(), user_id as u32, pw)
Paul Crowley7a658392021-03-18 17:08:20 -070078 })
Paul Crowley8d5b2532021-03-19 10:53:07 -070079 .context("In on_user_password_changed: unlock_screen_lock_bound_key failed")?;
Paul Crowley7a658392021-03-18 17:08:20 -070080 }
81
Hasini Gunasingheda895552021-01-27 19:34:37 +000082 match DB
83 .with(|db| {
84 UserState::get_with_password_changed(
85 &mut db.borrow_mut(),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000086 &LEGACY_MIGRATOR,
Hasini Gunasingheda895552021-01-27 19:34:37 +000087 &SUPER_KEY,
88 user_id as u32,
Paul Crowleyf61fee72021-03-17 14:38:44 -070089 password.as_ref(),
Hasini Gunasingheda895552021-01-27 19:34:37 +000090 )
91 })
92 .context("In on_user_password_changed.")?
93 {
94 UserState::LskfLocked => {
Janis Danisevskiseed69842021-02-18 20:04:10 -080095 // Error - password can not be changed when the device is locked
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -070096 Err(Error::Rc(ResponseCode::LOCKED))
Hasini Gunasingheda895552021-01-27 19:34:37 +000097 .context("In on_user_password_changed. Device is locked.")
98 }
99 _ => {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800100 // LskfLocked is the only error case for password change
Hasini Gunasingheda895552021-01-27 19:34:37 +0000101 Ok(())
102 }
103 }
104 }
105
Janis Danisevskis5898d152021-06-15 08:23:46 -0700106 fn add_or_remove_user(&self, user_id: i32) -> Result<()> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000107 // Check permission. Function should return if this failed. Therefore having '?' at the end
108 // is very important.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700109 check_keystore_permission(KeystorePerm::ChangeUser).context("In add_or_remove_user.")?;
Janis Danisevskiseed69842021-02-18 20:04:10 -0800110 DB.with(|db| {
111 UserState::reset_user(
112 &mut db.borrow_mut(),
113 &SUPER_KEY,
114 &LEGACY_MIGRATOR,
115 user_id as u32,
116 false,
117 )
118 })
Janis Danisevskis5898d152021-06-15 08:23:46 -0700119 .context("In add_or_remove_user: Trying to delete keys from db.")?;
120 self.delete_listener
121 .delete_user(user_id as u32)
122 .context("In add_or_remove_user: While invoking the delete listener.")
Hasini Gunasingheda895552021-01-27 19:34:37 +0000123 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800124
Janis Danisevskis5898d152021-06-15 08:23:46 -0700125 fn clear_namespace(&self, domain: Domain, nspace: i64) -> Result<()> {
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800126 // Permission check. Must return on error. Do not touch the '?'.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700127 check_keystore_permission(KeystorePerm::ClearUID).context("In clear_namespace.")?;
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800128
129 LEGACY_MIGRATOR
130 .bulk_delete_uid(domain, nspace)
131 .context("In clear_namespace: Trying to delete legacy keys.")?;
132 DB.with(|db| db.borrow_mut().unbind_keys_for_namespace(domain, nspace))
Janis Danisevskis5898d152021-06-15 08:23:46 -0700133 .context("In clear_namespace: Trying to delete keys from db.")?;
134 self.delete_listener
135 .delete_namespace(domain, nspace)
136 .context("In clear_namespace: While invoking the delete listener.")
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800137 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000138
139 fn get_state(user_id: i32) -> Result<AidlUserState> {
140 // Check permission. Function should return if this failed. Therefore having '?' at the end
141 // is very important.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700142 check_keystore_permission(KeystorePerm::GetState).context("In get_state.")?;
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000143 let state = DB
144 .with(|db| {
145 UserState::get(&mut db.borrow_mut(), &LEGACY_MIGRATOR, &SUPER_KEY, user_id as u32)
146 })
147 .context("In get_state. Trying to get UserState.")?;
148
149 match state {
150 UserState::Uninitialized => Ok(AidlUserState::UNINITIALIZED),
151 UserState::LskfUnlocked(_) => Ok(AidlUserState::LSKF_UNLOCKED),
152 UserState::LskfLocked => Ok(AidlUserState::LSKF_LOCKED),
153 }
154 }
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700155
Paul Crowley46c703e2021-08-06 15:13:53 -0700156 fn call_with_watchdog<F>(sec_level: SecurityLevel, name: &'static str, op: &F) -> Result<()>
157 where
158 F: Fn(Strong<dyn IKeyMintDevice>) -> binder::public_api::Result<()>,
159 {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700160 let (km_dev, _, _) = get_keymint_device(&sec_level)
Paul Crowley46c703e2021-08-06 15:13:53 -0700161 .context("In call_with_watchdog: getting keymint device")?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700162
Paul Crowley46c703e2021-08-06 15:13:53 -0700163 let _wp = wd::watch_millis_with("In call_with_watchdog", 500, move || {
164 format!("Seclevel: {:?} Op: {}", sec_level, name)
165 });
166 map_km_error(op(km_dev)).with_context(|| format!("In keymint device: calling {}", name))?;
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800167 Ok(())
168 }
169
Paul Crowley46c703e2021-08-06 15:13:53 -0700170 fn call_on_all_security_levels<F>(name: &'static str, op: F) -> Result<()>
171 where
172 F: Fn(Strong<dyn IKeyMintDevice>) -> binder::public_api::Result<()>,
173 {
174 let sec_levels = [
175 (SecurityLevel::TRUSTED_ENVIRONMENT, "TRUSTED_ENVIRONMENT"),
176 (SecurityLevel::STRONGBOX, "STRONGBOX"),
177 ];
178 sec_levels.iter().fold(Ok(()), move |result, (sec_level, sec_level_string)| {
179 let curr_result = Maintenance::call_with_watchdog(*sec_level, name, &op);
180 match curr_result {
181 Ok(()) => log::info!(
182 "Call to {} succeeded for security level {}.",
183 name,
184 &sec_level_string
185 ),
186 Err(ref e) => log::error!(
187 "Call to {} failed for security level {}: {}.",
188 name,
189 &sec_level_string,
190 e
191 ),
192 }
193 result.and(curr_result)
194 })
195 }
196
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800197 fn early_boot_ended() -> Result<()> {
Janis Danisevskisa916d992021-10-19 15:46:09 -0700198 check_keystore_permission(KeystorePerm::EarlyBootEnded)
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800199 .context("In early_boot_ended. Checking permission")?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000200 log::info!("In early_boot_ended.");
201
202 if let Err(e) = DB.with(|db| SUPER_KEY.set_up_boot_level_cache(&mut db.borrow_mut())) {
203 log::error!("SUPER_KEY.set_up_boot_level_cache failed:\n{:?}\n:(", e);
204 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700205 Maintenance::call_on_all_security_levels("earlyBootEnded", |dev| dev.earlyBootEnded())
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800206 }
207
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700208 fn on_device_off_body() -> Result<()> {
209 // Security critical permission check. This statement must return on fail.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700210 check_keystore_permission(KeystorePerm::ReportOffBody).context("In on_device_off_body.")?;
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700211
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700212 DB.with(|db| db.borrow_mut().update_last_off_body(MonotonicRawTime::now()));
213 Ok(())
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700214 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700215
216 fn migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()> {
217 let caller_uid = ThreadState::get_calling_uid();
Ashwini Orugantidaf73bc2021-11-15 10:46:31 -0800218 let migrate_any_key_permission =
219 check_keystore_permission(KeystorePerm::MigrateAnyKey).is_ok();
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700220
221 DB.with(|db| {
222 let key_id_guard = match source.domain {
223 Domain::APP | Domain::SELINUX | Domain::KEY_ID => {
224 let (key_id_guard, _) = LEGACY_MIGRATOR
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700225 .with_try_migrate(source, caller_uid, || {
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700226 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700227 source,
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700228 KeyType::Client,
229 KeyEntryLoadBits::NONE,
230 caller_uid,
231 |k, av| {
Ashwini Orugantidaf73bc2021-11-15 10:46:31 -0800232 if !migrate_any_key_permission {
233 check_key_permission(KeyPerm::Use, k, &av)?;
234 check_key_permission(KeyPerm::Delete, k, &av)?;
235 check_key_permission(KeyPerm::Grant, k, &av)?;
236 }
237 Ok(())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700238 },
239 )
240 })
241 .context("In migrate_key_namespace: Failed to load key blob.")?;
242 key_id_guard
243 }
244 _ => {
245 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(concat!(
246 "In migrate_key_namespace: ",
247 "Source domain must be one of APP, SELINUX, or KEY_ID."
248 ))
249 }
250 };
251
252 db.borrow_mut().migrate_key_namespace(key_id_guard, destination, caller_uid, |k| {
Ashwini Orugantidaf73bc2021-11-15 10:46:31 -0800253 if !migrate_any_key_permission {
254 check_key_permission(KeyPerm::Rebind, k, &None)?;
255 }
256 Ok(())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700257 })
258 })
259 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700260
261 fn delete_all_keys() -> Result<()> {
262 // Security critical permission check. This statement must return on fail.
Janis Danisevskisa916d992021-10-19 15:46:09 -0700263 check_keystore_permission(KeystorePerm::DeleteAllKeys)
Paul Crowley46c703e2021-08-06 15:13:53 -0700264 .context("In delete_all_keys. Checking permission")?;
265 log::info!("In delete_all_keys.");
266
267 Maintenance::call_on_all_security_levels("deleteAllKeys", |dev| dev.deleteAllKeys())
268 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000269}
270
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800271impl Interface for Maintenance {}
Hasini Gunasingheda895552021-01-27 19:34:37 +0000272
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800273impl IKeystoreMaintenance for Maintenance {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000274 fn onUserPasswordChanged(&self, user_id: i32, password: Option<&[u8]>) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000275 let _wp = wd::watch_millis("IKeystoreMaintenance::onUserPasswordChanged", 500);
Paul Crowleyf61fee72021-03-17 14:38:44 -0700276 map_or_log_err(Self::on_user_password_changed(user_id, password.map(|pw| pw.into())), Ok)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000277 }
278
279 fn onUserAdded(&self, user_id: i32) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000280 let _wp = wd::watch_millis("IKeystoreMaintenance::onUserAdded", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700281 map_or_log_err(self.add_or_remove_user(user_id), Ok)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000282 }
283
284 fn onUserRemoved(&self, user_id: i32) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000285 let _wp = wd::watch_millis("IKeystoreMaintenance::onUserRemoved", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700286 map_or_log_err(self.add_or_remove_user(user_id), Ok)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000287 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800288
289 fn clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000290 let _wp = wd::watch_millis("IKeystoreMaintenance::clearNamespace", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700291 map_or_log_err(self.clear_namespace(domain, nspace), Ok)
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800292 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000293
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700294 fn getState(&self, user_id: i32) -> BinderResult<AidlUserState> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000295 let _wp = wd::watch_millis("IKeystoreMaintenance::getState", 500);
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000296 map_or_log_err(Self::get_state(user_id), Ok)
297 }
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700298
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800299 fn earlyBootEnded(&self) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000300 let _wp = wd::watch_millis("IKeystoreMaintenance::earlyBootEnded", 500);
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800301 map_or_log_err(Self::early_boot_ended(), Ok)
302 }
303
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700304 fn onDeviceOffBody(&self) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000305 let _wp = wd::watch_millis("IKeystoreMaintenance::onDeviceOffBody", 500);
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700306 map_or_log_err(Self::on_device_off_body(), Ok)
307 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700308
309 fn migrateKeyNamespace(
310 &self,
311 source: &KeyDescriptor,
312 destination: &KeyDescriptor,
313 ) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000314 let _wp = wd::watch_millis("IKeystoreMaintenance::migrateKeyNamespace", 500);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700315 map_or_log_err(Self::migrate_key_namespace(source, destination), Ok)
316 }
Paul Crowley46c703e2021-08-06 15:13:53 -0700317
318 fn deleteAllKeys(&self) -> BinderResult<()> {
319 let _wp = wd::watch_millis("IKeystoreMaintenance::deleteAllKeys", 500);
320 map_or_log_err(Self::delete_all_keys(), Ok)
321 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000322}