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