1 // 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 15 //! This module implements IKeystoreMaintenance AIDL interface. 16 17 use crate::database::{KeyEntryLoadBits, KeyType, MonotonicRawTime}; 18 use crate::error::map_km_error; 19 use crate::error::map_or_log_err; 20 use crate::error::Error; 21 use crate::globals::get_keymint_device; 22 use crate::globals::{DB, LEGACY_IMPORTER, SUPER_KEY}; 23 use crate::ks_err; 24 use crate::permission::{KeyPerm, KeystorePerm}; 25 use crate::super_key::{SuperKeyManager, UserState}; 26 use crate::utils::{ 27 check_key_permission, check_keystore_permission, uid_to_android_user, watchdog as wd, 28 }; 29 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ 30 IKeyMintDevice::IKeyMintDevice, SecurityLevel::SecurityLevel, 31 }; 32 use android_security_maintenance::aidl::android::security::maintenance::{ 33 IKeystoreMaintenance::{BnKeystoreMaintenance, IKeystoreMaintenance}, 34 UserState::UserState as AidlUserState, 35 }; 36 use android_security_maintenance::binder::{ 37 BinderFeatures, Interface, Result as BinderResult, Strong, ThreadState, 38 }; 39 use android_system_keystore2::aidl::android::system::keystore2::KeyDescriptor::KeyDescriptor; 40 use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode; 41 use anyhow::{Context, Result}; 42 use keystore2_crypto::Password; 43 44 /// Reexport Domain for the benefit of DeleteListener 45 pub use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain; 46 47 /// The Maintenance module takes a delete listener argument which observes user and namespace 48 /// deletion events. 49 pub trait DeleteListener { 50 /// Called by the maintenance module when an app/namespace is deleted. delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()>51 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()>; 52 /// Called by the maintenance module when a user is deleted. delete_user(&self, user_id: u32) -> Result<()>53 fn delete_user(&self, user_id: u32) -> Result<()>; 54 } 55 56 /// This struct is defined to implement the aforementioned AIDL interface. 57 pub struct Maintenance { 58 delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>, 59 } 60 61 impl Maintenance { 62 /// Create a new instance of Keystore Maintenance service. new_native_binder( delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>, ) -> Result<Strong<dyn IKeystoreMaintenance>>63 pub fn new_native_binder( 64 delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>, 65 ) -> Result<Strong<dyn IKeystoreMaintenance>> { 66 Ok(BnKeystoreMaintenance::new_binder( 67 Self { delete_listener }, 68 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() }, 69 )) 70 } 71 on_user_password_changed(user_id: i32, password: Option<Password>) -> Result<()>72 fn on_user_password_changed(user_id: i32, password: Option<Password>) -> Result<()> { 73 // Check permission. Function should return if this failed. Therefore having '?' at the end 74 // is very important. 75 check_keystore_permission(KeystorePerm::ChangePassword).context(ks_err!())?; 76 77 let mut skm = SUPER_KEY.write().unwrap(); 78 79 if let Some(pw) = password.as_ref() { 80 DB.with(|db| { 81 skm.unlock_screen_lock_bound_key(&mut db.borrow_mut(), user_id as u32, pw) 82 }) 83 .context(ks_err!("unlock_screen_lock_bound_key failed"))?; 84 } 85 86 match DB 87 .with(|db| { 88 skm.reset_or_init_user_and_get_user_state( 89 &mut db.borrow_mut(), 90 &LEGACY_IMPORTER, 91 user_id as u32, 92 password.as_ref(), 93 ) 94 }) 95 .context(ks_err!())? 96 { 97 UserState::LskfLocked => { 98 // Error - password can not be changed when the device is locked 99 Err(Error::Rc(ResponseCode::LOCKED)).context(ks_err!("Device is locked.")) 100 } 101 _ => { 102 // LskfLocked is the only error case for password change 103 Ok(()) 104 } 105 } 106 } 107 add_or_remove_user(&self, user_id: i32) -> Result<()>108 fn add_or_remove_user(&self, user_id: i32) -> Result<()> { 109 // Check permission. Function should return if this failed. Therefore having '?' at the end 110 // is very important. 111 check_keystore_permission(KeystorePerm::ChangeUser).context(ks_err!())?; 112 113 DB.with(|db| { 114 SUPER_KEY.write().unwrap().reset_user( 115 &mut db.borrow_mut(), 116 &LEGACY_IMPORTER, 117 user_id as u32, 118 false, 119 ) 120 }) 121 .context(ks_err!("Trying to delete keys from db."))?; 122 self.delete_listener 123 .delete_user(user_id as u32) 124 .context(ks_err!("While invoking the delete listener.")) 125 } 126 clear_namespace(&self, domain: Domain, nspace: i64) -> Result<()>127 fn clear_namespace(&self, domain: Domain, nspace: i64) -> Result<()> { 128 // Permission check. Must return on error. Do not touch the '?'. 129 check_keystore_permission(KeystorePerm::ClearUID).context("In clear_namespace.")?; 130 131 LEGACY_IMPORTER 132 .bulk_delete_uid(domain, nspace) 133 .context(ks_err!("Trying to delete legacy keys."))?; 134 DB.with(|db| db.borrow_mut().unbind_keys_for_namespace(domain, nspace)) 135 .context(ks_err!("Trying to delete keys from db."))?; 136 self.delete_listener 137 .delete_namespace(domain, nspace) 138 .context(ks_err!("While invoking the delete listener.")) 139 } 140 get_state(user_id: i32) -> Result<AidlUserState>141 fn get_state(user_id: i32) -> Result<AidlUserState> { 142 // Check permission. Function should return if this failed. Therefore having '?' at the end 143 // is very important. 144 check_keystore_permission(KeystorePerm::GetState).context("In get_state.")?; 145 let state = DB 146 .with(|db| { 147 SUPER_KEY.read().unwrap().get_user_state( 148 &mut db.borrow_mut(), 149 &LEGACY_IMPORTER, 150 user_id as u32, 151 ) 152 }) 153 .context(ks_err!("Trying to get UserState."))?; 154 155 match state { 156 UserState::Uninitialized => Ok(AidlUserState::UNINITIALIZED), 157 UserState::LskfUnlocked(_) => Ok(AidlUserState::LSKF_UNLOCKED), 158 UserState::LskfLocked => Ok(AidlUserState::LSKF_LOCKED), 159 } 160 } 161 call_with_watchdog<F>(sec_level: SecurityLevel, name: &'static str, op: &F) -> Result<()> where F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>,162 fn call_with_watchdog<F>(sec_level: SecurityLevel, name: &'static str, op: &F) -> Result<()> 163 where 164 F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>, 165 { 166 let (km_dev, _, _) = 167 get_keymint_device(&sec_level).context(ks_err!("getting keymint device"))?; 168 169 let _wp = wd::watch_millis_with("In call_with_watchdog", 500, move || { 170 format!("Seclevel: {:?} Op: {}", sec_level, name) 171 }); 172 map_km_error(op(km_dev)).with_context(|| ks_err!("calling {}", name))?; 173 Ok(()) 174 } 175 call_on_all_security_levels<F>(name: &'static str, op: F) -> Result<()> where F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>,176 fn call_on_all_security_levels<F>(name: &'static str, op: F) -> Result<()> 177 where 178 F: Fn(Strong<dyn IKeyMintDevice>) -> binder::Result<()>, 179 { 180 let sec_levels = [ 181 (SecurityLevel::TRUSTED_ENVIRONMENT, "TRUSTED_ENVIRONMENT"), 182 (SecurityLevel::STRONGBOX, "STRONGBOX"), 183 ]; 184 sec_levels.iter().fold(Ok(()), move |result, (sec_level, sec_level_string)| { 185 let curr_result = Maintenance::call_with_watchdog(*sec_level, name, &op); 186 match curr_result { 187 Ok(()) => log::info!( 188 "Call to {} succeeded for security level {}.", 189 name, 190 &sec_level_string 191 ), 192 Err(ref e) => log::error!( 193 "Call to {} failed for security level {}: {}.", 194 name, 195 &sec_level_string, 196 e 197 ), 198 } 199 result.and(curr_result) 200 }) 201 } 202 early_boot_ended() -> Result<()>203 fn early_boot_ended() -> Result<()> { 204 check_keystore_permission(KeystorePerm::EarlyBootEnded) 205 .context(ks_err!("Checking permission"))?; 206 log::info!("In early_boot_ended."); 207 208 if let Err(e) = 209 DB.with(|db| SuperKeyManager::set_up_boot_level_cache(&SUPER_KEY, &mut db.borrow_mut())) 210 { 211 log::error!("SUPER_KEY.set_up_boot_level_cache failed:\n{:?}\n:(", e); 212 } 213 Maintenance::call_on_all_security_levels("earlyBootEnded", |dev| dev.earlyBootEnded()) 214 } 215 on_device_off_body() -> Result<()>216 fn on_device_off_body() -> Result<()> { 217 // Security critical permission check. This statement must return on fail. 218 check_keystore_permission(KeystorePerm::ReportOffBody).context(ks_err!())?; 219 220 DB.with(|db| db.borrow_mut().update_last_off_body(MonotonicRawTime::now())); 221 Ok(()) 222 } 223 migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()>224 fn migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()> { 225 let calling_uid = ThreadState::get_calling_uid(); 226 227 match source.domain { 228 Domain::SELINUX | Domain::KEY_ID | Domain::APP => (), 229 _ => { 230 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)) 231 .context(ks_err!("Source domain must be one of APP, SELINUX, or KEY_ID.")); 232 } 233 }; 234 235 match destination.domain { 236 Domain::SELINUX | Domain::APP => (), 237 _ => { 238 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)) 239 .context(ks_err!("Destination domain must be one of APP or SELINUX.")); 240 } 241 }; 242 243 let user_id = uid_to_android_user(calling_uid); 244 245 let super_key = SUPER_KEY.read().unwrap().get_per_boot_key_by_user_id(user_id); 246 247 DB.with(|db| { 248 let (key_id_guard, _) = LEGACY_IMPORTER 249 .with_try_import(source, calling_uid, super_key, || { 250 db.borrow_mut().load_key_entry( 251 source, 252 KeyType::Client, 253 KeyEntryLoadBits::NONE, 254 calling_uid, 255 |k, av| { 256 check_key_permission(KeyPerm::Use, k, &av)?; 257 check_key_permission(KeyPerm::Delete, k, &av)?; 258 check_key_permission(KeyPerm::Grant, k, &av) 259 }, 260 ) 261 }) 262 .context(ks_err!("Failed to load key blob."))?; 263 { 264 db.borrow_mut().migrate_key_namespace(key_id_guard, destination, calling_uid, |k| { 265 check_key_permission(KeyPerm::Rebind, k, &None) 266 }) 267 } 268 }) 269 } 270 delete_all_keys() -> Result<()>271 fn delete_all_keys() -> Result<()> { 272 // Security critical permission check. This statement must return on fail. 273 check_keystore_permission(KeystorePerm::DeleteAllKeys) 274 .context(ks_err!("Checking permission"))?; 275 log::info!("In delete_all_keys."); 276 277 Maintenance::call_on_all_security_levels("deleteAllKeys", |dev| dev.deleteAllKeys()) 278 } 279 } 280 281 impl Interface for Maintenance {} 282 283 impl IKeystoreMaintenance for Maintenance { onUserPasswordChanged(&self, user_id: i32, password: Option<&[u8]>) -> BinderResult<()>284 fn onUserPasswordChanged(&self, user_id: i32, password: Option<&[u8]>) -> BinderResult<()> { 285 let _wp = wd::watch_millis("IKeystoreMaintenance::onUserPasswordChanged", 500); 286 map_or_log_err(Self::on_user_password_changed(user_id, password.map(|pw| pw.into())), Ok) 287 } 288 onUserAdded(&self, user_id: i32) -> BinderResult<()>289 fn onUserAdded(&self, user_id: i32) -> BinderResult<()> { 290 let _wp = wd::watch_millis("IKeystoreMaintenance::onUserAdded", 500); 291 map_or_log_err(self.add_or_remove_user(user_id), Ok) 292 } 293 onUserRemoved(&self, user_id: i32) -> BinderResult<()>294 fn onUserRemoved(&self, user_id: i32) -> BinderResult<()> { 295 let _wp = wd::watch_millis("IKeystoreMaintenance::onUserRemoved", 500); 296 map_or_log_err(self.add_or_remove_user(user_id), Ok) 297 } 298 clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()>299 fn clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()> { 300 let _wp = wd::watch_millis("IKeystoreMaintenance::clearNamespace", 500); 301 map_or_log_err(self.clear_namespace(domain, nspace), Ok) 302 } 303 getState(&self, user_id: i32) -> BinderResult<AidlUserState>304 fn getState(&self, user_id: i32) -> BinderResult<AidlUserState> { 305 let _wp = wd::watch_millis("IKeystoreMaintenance::getState", 500); 306 map_or_log_err(Self::get_state(user_id), Ok) 307 } 308 earlyBootEnded(&self) -> BinderResult<()>309 fn earlyBootEnded(&self) -> BinderResult<()> { 310 let _wp = wd::watch_millis("IKeystoreMaintenance::earlyBootEnded", 500); 311 map_or_log_err(Self::early_boot_ended(), Ok) 312 } 313 onDeviceOffBody(&self) -> BinderResult<()>314 fn onDeviceOffBody(&self) -> BinderResult<()> { 315 let _wp = wd::watch_millis("IKeystoreMaintenance::onDeviceOffBody", 500); 316 map_or_log_err(Self::on_device_off_body(), Ok) 317 } 318 migrateKeyNamespace( &self, source: &KeyDescriptor, destination: &KeyDescriptor, ) -> BinderResult<()>319 fn migrateKeyNamespace( 320 &self, 321 source: &KeyDescriptor, 322 destination: &KeyDescriptor, 323 ) -> BinderResult<()> { 324 let _wp = wd::watch_millis("IKeystoreMaintenance::migrateKeyNamespace", 500); 325 map_or_log_err(Self::migrate_key_namespace(source, destination), Ok) 326 } 327 deleteAllKeys(&self) -> BinderResult<()>328 fn deleteAllKeys(&self) -> BinderResult<()> { 329 let _wp = wd::watch_millis("IKeystoreMaintenance::deleteAllKeys", 500); 330 map_or_log_err(Self::delete_all_keys(), Ok) 331 } 332 } 333