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