blob: 08fa8d2c6ea50f530bffb9701d97e09b08e62ad8 [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};
Satya Tangirala5b9e5b12021-03-09 12:54:21 -080026use android_hardware_security_keymint::aidl::android::hardware::security::keymint::SecurityLevel::SecurityLevel;
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +000027use android_security_maintenance::aidl::android::security::maintenance::{
28 IKeystoreMaintenance::{BnKeystoreMaintenance, IKeystoreMaintenance},
29 UserState::UserState as AidlUserState,
Hasini Gunasingheda895552021-01-27 19:34:37 +000030};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000031use android_security_maintenance::binder::{
32 BinderFeatures, Interface, Result as BinderResult, Strong, ThreadState,
33};
Janis Danisevskis5898d152021-06-15 08:23:46 -070034use android_system_keystore2::aidl::android::system::keystore2::KeyDescriptor::KeyDescriptor;
Hasini Gunasingheda895552021-01-27 19:34:37 +000035use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode;
36use anyhow::{Context, Result};
Paul Crowleyf61fee72021-03-17 14:38:44 -070037use keystore2_crypto::Password;
Hasini Gunasingheda895552021-01-27 19:34:37 +000038
Janis Danisevskis5898d152021-06-15 08:23:46 -070039/// Reexport Domain for the benefit of DeleteListener
40pub use android_system_keystore2::aidl::android::system::keystore2::Domain::Domain;
41
42/// The Maintenance module takes a delete listener argument which observes user and namespace
43/// deletion events.
44pub trait DeleteListener {
45 /// Called by the maintenance module when an app/namespace is deleted.
46 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()>;
47 /// Called by the maintenance module when a user is deleted.
48 fn delete_user(&self, user_id: u32) -> Result<()>;
49}
50
Hasini Gunasingheda895552021-01-27 19:34:37 +000051/// This struct is defined to implement the aforementioned AIDL interface.
Janis Danisevskis5898d152021-06-15 08:23:46 -070052pub struct Maintenance {
53 delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>,
54}
Hasini Gunasingheda895552021-01-27 19:34:37 +000055
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080056impl Maintenance {
Janis Danisevskis5898d152021-06-15 08:23:46 -070057 /// Create a new instance of Keystore Maintenance service.
58 pub fn new_native_binder(
59 delete_listener: Box<dyn DeleteListener + Send + Sync + 'static>,
60 ) -> Result<Strong<dyn IKeystoreMaintenance>> {
Andrew Walbrande45c8b2021-04-13 14:42:38 +000061 Ok(BnKeystoreMaintenance::new_binder(
Janis Danisevskis5898d152021-06-15 08:23:46 -070062 Self { delete_listener },
Andrew Walbrande45c8b2021-04-13 14:42:38 +000063 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
64 ))
Hasini Gunasingheda895552021-01-27 19:34:37 +000065 }
66
Paul Crowleyf61fee72021-03-17 14:38:44 -070067 fn on_user_password_changed(user_id: i32, password: Option<Password>) -> Result<()> {
Hasini Gunasingheda895552021-01-27 19:34:37 +000068 //Check permission. Function should return if this failed. Therefore having '?' at the end
69 //is very important.
70 check_keystore_permission(KeystorePerm::change_password())
71 .context("In on_user_password_changed.")?;
72
Paul Crowley7a658392021-03-18 17:08:20 -070073 if let Some(pw) = password.as_ref() {
74 DB.with(|db| {
Paul Crowley8d5b2532021-03-19 10:53:07 -070075 SUPER_KEY.unlock_screen_lock_bound_key(&mut db.borrow_mut(), user_id as u32, pw)
Paul Crowley7a658392021-03-18 17:08:20 -070076 })
Paul Crowley8d5b2532021-03-19 10:53:07 -070077 .context("In on_user_password_changed: unlock_screen_lock_bound_key failed")?;
Paul Crowley7a658392021-03-18 17:08:20 -070078 }
79
Hasini Gunasingheda895552021-01-27 19:34:37 +000080 match DB
81 .with(|db| {
82 UserState::get_with_password_changed(
83 &mut db.borrow_mut(),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000084 &LEGACY_MIGRATOR,
Hasini Gunasingheda895552021-01-27 19:34:37 +000085 &SUPER_KEY,
86 user_id as u32,
Paul Crowleyf61fee72021-03-17 14:38:44 -070087 password.as_ref(),
Hasini Gunasingheda895552021-01-27 19:34:37 +000088 )
89 })
90 .context("In on_user_password_changed.")?
91 {
92 UserState::LskfLocked => {
Janis Danisevskiseed69842021-02-18 20:04:10 -080093 // Error - password can not be changed when the device is locked
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -070094 Err(Error::Rc(ResponseCode::LOCKED))
Hasini Gunasingheda895552021-01-27 19:34:37 +000095 .context("In on_user_password_changed. Device is locked.")
96 }
97 _ => {
Janis Danisevskiseed69842021-02-18 20:04:10 -080098 // LskfLocked is the only error case for password change
Hasini Gunasingheda895552021-01-27 19:34:37 +000099 Ok(())
100 }
101 }
102 }
103
Janis Danisevskis5898d152021-06-15 08:23:46 -0700104 fn add_or_remove_user(&self, user_id: i32) -> Result<()> {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000105 // Check permission. Function should return if this failed. Therefore having '?' at the end
106 // is very important.
107 check_keystore_permission(KeystorePerm::change_user()).context("In add_or_remove_user.")?;
Janis Danisevskiseed69842021-02-18 20:04:10 -0800108 DB.with(|db| {
109 UserState::reset_user(
110 &mut db.borrow_mut(),
111 &SUPER_KEY,
112 &LEGACY_MIGRATOR,
113 user_id as u32,
114 false,
115 )
116 })
Janis Danisevskis5898d152021-06-15 08:23:46 -0700117 .context("In add_or_remove_user: Trying to delete keys from db.")?;
118 self.delete_listener
119 .delete_user(user_id as u32)
120 .context("In add_or_remove_user: While invoking the delete listener.")
Hasini Gunasingheda895552021-01-27 19:34:37 +0000121 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800122
Janis Danisevskis5898d152021-06-15 08:23:46 -0700123 fn clear_namespace(&self, domain: Domain, nspace: i64) -> Result<()> {
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800124 // Permission check. Must return on error. Do not touch the '?'.
125 check_keystore_permission(KeystorePerm::clear_uid()).context("In clear_namespace.")?;
126
127 LEGACY_MIGRATOR
128 .bulk_delete_uid(domain, nspace)
129 .context("In clear_namespace: Trying to delete legacy keys.")?;
130 DB.with(|db| db.borrow_mut().unbind_keys_for_namespace(domain, nspace))
Janis Danisevskis5898d152021-06-15 08:23:46 -0700131 .context("In clear_namespace: Trying to delete keys from db.")?;
132 self.delete_listener
133 .delete_namespace(domain, nspace)
134 .context("In clear_namespace: While invoking the delete listener.")
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800135 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000136
137 fn get_state(user_id: i32) -> Result<AidlUserState> {
138 // Check permission. Function should return if this failed. Therefore having '?' at the end
139 // is very important.
140 check_keystore_permission(KeystorePerm::get_state()).context("In get_state.")?;
141 let state = DB
142 .with(|db| {
143 UserState::get(&mut db.borrow_mut(), &LEGACY_MIGRATOR, &SUPER_KEY, user_id as u32)
144 })
145 .context("In get_state. Trying to get UserState.")?;
146
147 match state {
148 UserState::Uninitialized => Ok(AidlUserState::UNINITIALIZED),
149 UserState::LskfUnlocked(_) => Ok(AidlUserState::LSKF_UNLOCKED),
150 UserState::LskfLocked => Ok(AidlUserState::LSKF_LOCKED),
151 }
152 }
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700153
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700154 fn early_boot_ended_help(sec_level: SecurityLevel) -> Result<()> {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700155 let (km_dev, _, _) = get_keymint_device(&sec_level)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700156 .context("In early_boot_ended: getting keymint device")?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700157
158 let _wp = wd::watch_millis_with(
159 "In early_boot_ended_help: calling earlyBootEnded()",
160 500,
161 move || format!("Seclevel: {:?}", sec_level),
162 );
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800163 map_km_error(km_dev.earlyBootEnded())
164 .context("In keymint device: calling earlyBootEnded")?;
165 Ok(())
166 }
167
168 fn early_boot_ended() -> Result<()> {
169 check_keystore_permission(KeystorePerm::early_boot_ended())
170 .context("In early_boot_ended. Checking permission")?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000171 log::info!("In early_boot_ended.");
172
173 if let Err(e) = DB.with(|db| SUPER_KEY.set_up_boot_level_cache(&mut db.borrow_mut())) {
174 log::error!("SUPER_KEY.set_up_boot_level_cache failed:\n{:?}\n:(", e);
175 }
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800176
177 let sec_levels = [
178 (SecurityLevel::TRUSTED_ENVIRONMENT, "TRUSTED_ENVIRONMENT"),
179 (SecurityLevel::STRONGBOX, "STRONGBOX"),
180 ];
181 sec_levels.iter().fold(Ok(()), |result, (sec_level, sec_level_string)| {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700182 let curr_result = Maintenance::early_boot_ended_help(*sec_level);
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800183 if curr_result.is_err() {
184 log::error!(
185 "Call to earlyBootEnded failed for security level {}.",
186 &sec_level_string
187 );
188 }
189 result.and(curr_result)
190 })
191 }
192
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700193 fn on_device_off_body() -> Result<()> {
194 // Security critical permission check. This statement must return on fail.
195 check_keystore_permission(KeystorePerm::report_off_body())
196 .context("In on_device_off_body.")?;
197
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700198 DB.with(|db| db.borrow_mut().update_last_off_body(MonotonicRawTime::now()));
199 Ok(())
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700200 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700201
202 fn migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()> {
203 let caller_uid = ThreadState::get_calling_uid();
204
205 DB.with(|db| {
206 let key_id_guard = match source.domain {
207 Domain::APP | Domain::SELINUX | Domain::KEY_ID => {
208 let (key_id_guard, _) = LEGACY_MIGRATOR
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700209 .with_try_migrate(source, caller_uid, || {
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700210 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700211 source,
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700212 KeyType::Client,
213 KeyEntryLoadBits::NONE,
214 caller_uid,
215 |k, av| {
216 check_key_permission(KeyPerm::use_(), k, &av)?;
217 check_key_permission(KeyPerm::delete(), k, &av)?;
218 check_key_permission(KeyPerm::grant(), k, &av)
219 },
220 )
221 })
222 .context("In migrate_key_namespace: Failed to load key blob.")?;
223 key_id_guard
224 }
225 _ => {
226 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(concat!(
227 "In migrate_key_namespace: ",
228 "Source domain must be one of APP, SELINUX, or KEY_ID."
229 ))
230 }
231 };
232
233 db.borrow_mut().migrate_key_namespace(key_id_guard, destination, caller_uid, |k| {
234 check_key_permission(KeyPerm::rebind(), k, &None)
235 })
236 })
237 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000238}
239
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800240impl Interface for Maintenance {}
Hasini Gunasingheda895552021-01-27 19:34:37 +0000241
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800242impl IKeystoreMaintenance for Maintenance {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000243 fn onUserPasswordChanged(&self, user_id: i32, password: Option<&[u8]>) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000244 let _wp = wd::watch_millis("IKeystoreMaintenance::onUserPasswordChanged", 500);
Paul Crowleyf61fee72021-03-17 14:38:44 -0700245 map_or_log_err(Self::on_user_password_changed(user_id, password.map(|pw| pw.into())), Ok)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000246 }
247
248 fn onUserAdded(&self, user_id: i32) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000249 let _wp = wd::watch_millis("IKeystoreMaintenance::onUserAdded", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700250 map_or_log_err(self.add_or_remove_user(user_id), Ok)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000251 }
252
253 fn onUserRemoved(&self, user_id: i32) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000254 let _wp = wd::watch_millis("IKeystoreMaintenance::onUserRemoved", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700255 map_or_log_err(self.add_or_remove_user(user_id), Ok)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000256 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800257
258 fn clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000259 let _wp = wd::watch_millis("IKeystoreMaintenance::clearNamespace", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700260 map_or_log_err(self.clear_namespace(domain, nspace), Ok)
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800261 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000262
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700263 fn getState(&self, user_id: i32) -> BinderResult<AidlUserState> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000264 let _wp = wd::watch_millis("IKeystoreMaintenance::getState", 500);
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000265 map_or_log_err(Self::get_state(user_id), Ok)
266 }
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700267
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800268 fn earlyBootEnded(&self) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000269 let _wp = wd::watch_millis("IKeystoreMaintenance::earlyBootEnded", 500);
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800270 map_or_log_err(Self::early_boot_ended(), Ok)
271 }
272
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700273 fn onDeviceOffBody(&self) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000274 let _wp = wd::watch_millis("IKeystoreMaintenance::onDeviceOffBody", 500);
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700275 map_or_log_err(Self::on_device_off_body(), Ok)
276 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700277
278 fn migrateKeyNamespace(
279 &self,
280 source: &KeyDescriptor,
281 destination: &KeyDescriptor,
282 ) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000283 let _wp = wd::watch_millis("IKeystoreMaintenance::migrateKeyNamespace", 500);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700284 map_or_log_err(Self::migrate_key_namespace(source, destination), Ok)
285 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000286}