blob: 13a5b437d3631158798fc03c9ea145df1ec74c8c [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::IKeyMintDevice::IKeyMintDevice;
27use android_hardware_security_keymint::aidl::android::hardware::security::keymint::SecurityLevel::SecurityLevel;
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +000028use android_security_maintenance::aidl::android::security::maintenance::{
29 IKeystoreMaintenance::{BnKeystoreMaintenance, IKeystoreMaintenance},
30 UserState::UserState as AidlUserState,
Hasini Gunasingheda895552021-01-27 19:34:37 +000031};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000032use android_security_maintenance::binder::{
33 BinderFeatures, Interface, Result as BinderResult, Strong, ThreadState,
34};
Hasini Gunasingheda895552021-01-27 19:34:37 +000035use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -070036use android_system_keystore2::aidl::android::system::keystore2::{
37 Domain::Domain, KeyDescriptor::KeyDescriptor,
38};
Hasini Gunasingheda895552021-01-27 19:34:37 +000039use anyhow::{Context, Result};
Paul Crowleyf61fee72021-03-17 14:38:44 -070040use keystore2_crypto::Password;
Hasini Gunasingheda895552021-01-27 19:34:37 +000041
42/// This struct is defined to implement the aforementioned AIDL interface.
43/// As of now, it is an empty struct.
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080044pub struct Maintenance;
Hasini Gunasingheda895552021-01-27 19:34:37 +000045
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080046impl Maintenance {
Hasini Gunasingheda895552021-01-27 19:34:37 +000047 /// Create a new instance of Keystore User Manager service.
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080048 pub fn new_native_binder() -> Result<Strong<dyn IKeystoreMaintenance>> {
Andrew Walbrande45c8b2021-04-13 14:42:38 +000049 Ok(BnKeystoreMaintenance::new_binder(
50 Self,
51 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
52 ))
Hasini Gunasingheda895552021-01-27 19:34:37 +000053 }
54
Paul Crowleyf61fee72021-03-17 14:38:44 -070055 fn on_user_password_changed(user_id: i32, password: Option<Password>) -> Result<()> {
Hasini Gunasingheda895552021-01-27 19:34:37 +000056 //Check permission. Function should return if this failed. Therefore having '?' at the end
57 //is very important.
58 check_keystore_permission(KeystorePerm::change_password())
59 .context("In on_user_password_changed.")?;
60
Paul Crowley7a658392021-03-18 17:08:20 -070061 if let Some(pw) = password.as_ref() {
62 DB.with(|db| {
Paul Crowley8d5b2532021-03-19 10:53:07 -070063 SUPER_KEY.unlock_screen_lock_bound_key(&mut db.borrow_mut(), user_id as u32, pw)
Paul Crowley7a658392021-03-18 17:08:20 -070064 })
Paul Crowley8d5b2532021-03-19 10:53:07 -070065 .context("In on_user_password_changed: unlock_screen_lock_bound_key failed")?;
Paul Crowley7a658392021-03-18 17:08:20 -070066 }
67
Hasini Gunasingheda895552021-01-27 19:34:37 +000068 match DB
69 .with(|db| {
70 UserState::get_with_password_changed(
71 &mut db.borrow_mut(),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000072 &LEGACY_MIGRATOR,
Hasini Gunasingheda895552021-01-27 19:34:37 +000073 &SUPER_KEY,
74 user_id as u32,
Paul Crowleyf61fee72021-03-17 14:38:44 -070075 password.as_ref(),
Hasini Gunasingheda895552021-01-27 19:34:37 +000076 )
77 })
78 .context("In on_user_password_changed.")?
79 {
80 UserState::LskfLocked => {
Janis Danisevskiseed69842021-02-18 20:04:10 -080081 // Error - password can not be changed when the device is locked
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -070082 Err(Error::Rc(ResponseCode::LOCKED))
Hasini Gunasingheda895552021-01-27 19:34:37 +000083 .context("In on_user_password_changed. Device is locked.")
84 }
85 _ => {
Janis Danisevskiseed69842021-02-18 20:04:10 -080086 // LskfLocked is the only error case for password change
Hasini Gunasingheda895552021-01-27 19:34:37 +000087 Ok(())
88 }
89 }
90 }
91
92 fn add_or_remove_user(user_id: i32) -> Result<()> {
93 // Check permission. Function should return if this failed. Therefore having '?' at the end
94 // is very important.
95 check_keystore_permission(KeystorePerm::change_user()).context("In add_or_remove_user.")?;
Janis Danisevskiseed69842021-02-18 20:04:10 -080096 DB.with(|db| {
97 UserState::reset_user(
98 &mut db.borrow_mut(),
99 &SUPER_KEY,
100 &LEGACY_MIGRATOR,
101 user_id as u32,
102 false,
103 )
104 })
105 .context("In add_or_remove_user: Trying to delete keys from db.")
Hasini Gunasingheda895552021-01-27 19:34:37 +0000106 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800107
108 fn clear_namespace(domain: Domain, nspace: i64) -> Result<()> {
109 // Permission check. Must return on error. Do not touch the '?'.
110 check_keystore_permission(KeystorePerm::clear_uid()).context("In clear_namespace.")?;
111
112 LEGACY_MIGRATOR
113 .bulk_delete_uid(domain, nspace)
114 .context("In clear_namespace: Trying to delete legacy keys.")?;
115 DB.with(|db| db.borrow_mut().unbind_keys_for_namespace(domain, nspace))
116 .context("In clear_namespace: Trying to delete keys from db.")
117 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000118
119 fn get_state(user_id: i32) -> Result<AidlUserState> {
120 // Check permission. Function should return if this failed. Therefore having '?' at the end
121 // is very important.
122 check_keystore_permission(KeystorePerm::get_state()).context("In get_state.")?;
123 let state = DB
124 .with(|db| {
125 UserState::get(&mut db.borrow_mut(), &LEGACY_MIGRATOR, &SUPER_KEY, user_id as u32)
126 })
127 .context("In get_state. Trying to get UserState.")?;
128
129 match state {
130 UserState::Uninitialized => Ok(AidlUserState::UNINITIALIZED),
131 UserState::LskfUnlocked(_) => Ok(AidlUserState::LSKF_UNLOCKED),
132 UserState::LskfLocked => Ok(AidlUserState::LSKF_LOCKED),
133 }
134 }
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700135
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700136 fn early_boot_ended_help(sec_level: SecurityLevel) -> Result<()> {
137 let (dev, _, _) = get_keymint_device(&sec_level)
138 .context("In early_boot_ended: getting keymint device")?;
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800139 let km_dev: Strong<dyn IKeyMintDevice> =
140 dev.get_interface().context("In early_boot_ended: getting keymint device interface")?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700141
142 let _wp = wd::watch_millis_with(
143 "In early_boot_ended_help: calling earlyBootEnded()",
144 500,
145 move || format!("Seclevel: {:?}", sec_level),
146 );
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800147 map_km_error(km_dev.earlyBootEnded())
148 .context("In keymint device: calling earlyBootEnded")?;
149 Ok(())
150 }
151
152 fn early_boot_ended() -> Result<()> {
153 check_keystore_permission(KeystorePerm::early_boot_ended())
154 .context("In early_boot_ended. Checking permission")?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000155 log::info!("In early_boot_ended.");
156
157 if let Err(e) = DB.with(|db| SUPER_KEY.set_up_boot_level_cache(&mut db.borrow_mut())) {
158 log::error!("SUPER_KEY.set_up_boot_level_cache failed:\n{:?}\n:(", e);
159 }
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800160
161 let sec_levels = [
162 (SecurityLevel::TRUSTED_ENVIRONMENT, "TRUSTED_ENVIRONMENT"),
163 (SecurityLevel::STRONGBOX, "STRONGBOX"),
164 ];
165 sec_levels.iter().fold(Ok(()), |result, (sec_level, sec_level_string)| {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700166 let curr_result = Maintenance::early_boot_ended_help(*sec_level);
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800167 if curr_result.is_err() {
168 log::error!(
169 "Call to earlyBootEnded failed for security level {}.",
170 &sec_level_string
171 );
172 }
173 result.and(curr_result)
174 })
175 }
176
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700177 fn on_device_off_body() -> Result<()> {
178 // Security critical permission check. This statement must return on fail.
179 check_keystore_permission(KeystorePerm::report_off_body())
180 .context("In on_device_off_body.")?;
181
182 DB.with(|db| db.borrow_mut().update_last_off_body(MonotonicRawTime::now()))
183 .context("In on_device_off_body: Trying to update last off body time.")
184 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700185
186 fn migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()> {
187 let caller_uid = ThreadState::get_calling_uid();
188
189 DB.with(|db| {
190 let key_id_guard = match source.domain {
191 Domain::APP | Domain::SELINUX | Domain::KEY_ID => {
192 let (key_id_guard, _) = LEGACY_MIGRATOR
193 .with_try_migrate(&source, caller_uid, || {
194 db.borrow_mut().load_key_entry(
195 &source,
196 KeyType::Client,
197 KeyEntryLoadBits::NONE,
198 caller_uid,
199 |k, av| {
200 check_key_permission(KeyPerm::use_(), k, &av)?;
201 check_key_permission(KeyPerm::delete(), k, &av)?;
202 check_key_permission(KeyPerm::grant(), k, &av)
203 },
204 )
205 })
206 .context("In migrate_key_namespace: Failed to load key blob.")?;
207 key_id_guard
208 }
209 _ => {
210 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(concat!(
211 "In migrate_key_namespace: ",
212 "Source domain must be one of APP, SELINUX, or KEY_ID."
213 ))
214 }
215 };
216
217 db.borrow_mut().migrate_key_namespace(key_id_guard, destination, caller_uid, |k| {
218 check_key_permission(KeyPerm::rebind(), k, &None)
219 })
220 })
221 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000222}
223
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800224impl Interface for Maintenance {}
Hasini Gunasingheda895552021-01-27 19:34:37 +0000225
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800226impl IKeystoreMaintenance for Maintenance {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000227 fn onUserPasswordChanged(&self, user_id: i32, password: Option<&[u8]>) -> BinderResult<()> {
Paul Crowleyf61fee72021-03-17 14:38:44 -0700228 map_or_log_err(Self::on_user_password_changed(user_id, password.map(|pw| pw.into())), Ok)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000229 }
230
231 fn onUserAdded(&self, user_id: i32) -> BinderResult<()> {
232 map_or_log_err(Self::add_or_remove_user(user_id), Ok)
233 }
234
235 fn onUserRemoved(&self, user_id: i32) -> BinderResult<()> {
236 map_or_log_err(Self::add_or_remove_user(user_id), Ok)
237 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800238
239 fn clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()> {
240 map_or_log_err(Self::clear_namespace(domain, nspace), Ok)
241 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000242
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700243 fn getState(&self, user_id: i32) -> BinderResult<AidlUserState> {
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000244 map_or_log_err(Self::get_state(user_id), Ok)
245 }
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700246
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800247 fn earlyBootEnded(&self) -> BinderResult<()> {
248 map_or_log_err(Self::early_boot_ended(), Ok)
249 }
250
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700251 fn onDeviceOffBody(&self) -> BinderResult<()> {
252 map_or_log_err(Self::on_device_off_body(), Ok)
253 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700254
255 fn migrateKeyNamespace(
256 &self,
257 source: &KeyDescriptor,
258 destination: &KeyDescriptor,
259 ) -> BinderResult<()> {
260 map_or_log_err(Self::migrate_key_namespace(source, destination), Ok)
261 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000262}