blob: afb88eca8e79936dbe7196e2cb562a09b1a19845 [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};
Hasini Gunasingheda895552021-01-27 19:34:37 +000034use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -070035use android_system_keystore2::aidl::android::system::keystore2::{
36 Domain::Domain, KeyDescriptor::KeyDescriptor,
37};
Hasini Gunasingheda895552021-01-27 19:34:37 +000038use anyhow::{Context, Result};
Paul Crowleyf61fee72021-03-17 14:38:44 -070039use keystore2_crypto::Password;
Hasini Gunasingheda895552021-01-27 19:34:37 +000040
41/// This struct is defined to implement the aforementioned AIDL interface.
42/// As of now, it is an empty struct.
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080043pub struct Maintenance;
Hasini Gunasingheda895552021-01-27 19:34:37 +000044
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080045impl Maintenance {
Hasini Gunasingheda895552021-01-27 19:34:37 +000046 /// Create a new instance of Keystore User Manager service.
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080047 pub fn new_native_binder() -> Result<Strong<dyn IKeystoreMaintenance>> {
Andrew Walbrande45c8b2021-04-13 14:42:38 +000048 Ok(BnKeystoreMaintenance::new_binder(
49 Self,
50 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
51 ))
Hasini Gunasingheda895552021-01-27 19:34:37 +000052 }
53
Paul Crowleyf61fee72021-03-17 14:38:44 -070054 fn on_user_password_changed(user_id: i32, password: Option<Password>) -> Result<()> {
Hasini Gunasingheda895552021-01-27 19:34:37 +000055 //Check permission. Function should return if this failed. Therefore having '?' at the end
56 //is very important.
57 check_keystore_permission(KeystorePerm::change_password())
58 .context("In on_user_password_changed.")?;
59
Paul Crowley7a658392021-03-18 17:08:20 -070060 if let Some(pw) = password.as_ref() {
61 DB.with(|db| {
Paul Crowley8d5b2532021-03-19 10:53:07 -070062 SUPER_KEY.unlock_screen_lock_bound_key(&mut db.borrow_mut(), user_id as u32, pw)
Paul Crowley7a658392021-03-18 17:08:20 -070063 })
Paul Crowley8d5b2532021-03-19 10:53:07 -070064 .context("In on_user_password_changed: unlock_screen_lock_bound_key failed")?;
Paul Crowley7a658392021-03-18 17:08:20 -070065 }
66
Hasini Gunasingheda895552021-01-27 19:34:37 +000067 match DB
68 .with(|db| {
69 UserState::get_with_password_changed(
70 &mut db.borrow_mut(),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000071 &LEGACY_MIGRATOR,
Hasini Gunasingheda895552021-01-27 19:34:37 +000072 &SUPER_KEY,
73 user_id as u32,
Paul Crowleyf61fee72021-03-17 14:38:44 -070074 password.as_ref(),
Hasini Gunasingheda895552021-01-27 19:34:37 +000075 )
76 })
77 .context("In on_user_password_changed.")?
78 {
79 UserState::LskfLocked => {
Janis Danisevskiseed69842021-02-18 20:04:10 -080080 // Error - password can not be changed when the device is locked
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -070081 Err(Error::Rc(ResponseCode::LOCKED))
Hasini Gunasingheda895552021-01-27 19:34:37 +000082 .context("In on_user_password_changed. Device is locked.")
83 }
84 _ => {
Janis Danisevskiseed69842021-02-18 20:04:10 -080085 // LskfLocked is the only error case for password change
Hasini Gunasingheda895552021-01-27 19:34:37 +000086 Ok(())
87 }
88 }
89 }
90
91 fn add_or_remove_user(user_id: i32) -> Result<()> {
92 // Check permission. Function should return if this failed. Therefore having '?' at the end
93 // is very important.
94 check_keystore_permission(KeystorePerm::change_user()).context("In add_or_remove_user.")?;
Janis Danisevskiseed69842021-02-18 20:04:10 -080095 DB.with(|db| {
96 UserState::reset_user(
97 &mut db.borrow_mut(),
98 &SUPER_KEY,
99 &LEGACY_MIGRATOR,
100 user_id as u32,
101 false,
102 )
103 })
104 .context("In add_or_remove_user: Trying to delete keys from db.")
Hasini Gunasingheda895552021-01-27 19:34:37 +0000105 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800106
107 fn clear_namespace(domain: Domain, nspace: i64) -> Result<()> {
108 // Permission check. Must return on error. Do not touch the '?'.
109 check_keystore_permission(KeystorePerm::clear_uid()).context("In clear_namespace.")?;
110
111 LEGACY_MIGRATOR
112 .bulk_delete_uid(domain, nspace)
113 .context("In clear_namespace: Trying to delete legacy keys.")?;
114 DB.with(|db| db.borrow_mut().unbind_keys_for_namespace(domain, nspace))
115 .context("In clear_namespace: Trying to delete keys from db.")
116 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000117
118 fn get_state(user_id: i32) -> Result<AidlUserState> {
119 // Check permission. Function should return if this failed. Therefore having '?' at the end
120 // is very important.
121 check_keystore_permission(KeystorePerm::get_state()).context("In get_state.")?;
122 let state = DB
123 .with(|db| {
124 UserState::get(&mut db.borrow_mut(), &LEGACY_MIGRATOR, &SUPER_KEY, user_id as u32)
125 })
126 .context("In get_state. Trying to get UserState.")?;
127
128 match state {
129 UserState::Uninitialized => Ok(AidlUserState::UNINITIALIZED),
130 UserState::LskfUnlocked(_) => Ok(AidlUserState::LSKF_UNLOCKED),
131 UserState::LskfLocked => Ok(AidlUserState::LSKF_LOCKED),
132 }
133 }
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700134
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700135 fn early_boot_ended_help(sec_level: SecurityLevel) -> Result<()> {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700136 let (km_dev, _, _) = get_keymint_device(&sec_level)
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700137 .context("In early_boot_ended: getting keymint device")?;
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700138
139 let _wp = wd::watch_millis_with(
140 "In early_boot_ended_help: calling earlyBootEnded()",
141 500,
142 move || format!("Seclevel: {:?}", sec_level),
143 );
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800144 map_km_error(km_dev.earlyBootEnded())
145 .context("In keymint device: calling earlyBootEnded")?;
146 Ok(())
147 }
148
149 fn early_boot_ended() -> Result<()> {
150 check_keystore_permission(KeystorePerm::early_boot_ended())
151 .context("In early_boot_ended. Checking permission")?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000152 log::info!("In early_boot_ended.");
153
154 if let Err(e) = DB.with(|db| SUPER_KEY.set_up_boot_level_cache(&mut db.borrow_mut())) {
155 log::error!("SUPER_KEY.set_up_boot_level_cache failed:\n{:?}\n:(", e);
156 }
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800157
158 let sec_levels = [
159 (SecurityLevel::TRUSTED_ENVIRONMENT, "TRUSTED_ENVIRONMENT"),
160 (SecurityLevel::STRONGBOX, "STRONGBOX"),
161 ];
162 sec_levels.iter().fold(Ok(()), |result, (sec_level, sec_level_string)| {
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700163 let curr_result = Maintenance::early_boot_ended_help(*sec_level);
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800164 if curr_result.is_err() {
165 log::error!(
166 "Call to earlyBootEnded failed for security level {}.",
167 &sec_level_string
168 );
169 }
170 result.and(curr_result)
171 })
172 }
173
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700174 fn on_device_off_body() -> Result<()> {
175 // Security critical permission check. This statement must return on fail.
176 check_keystore_permission(KeystorePerm::report_off_body())
177 .context("In on_device_off_body.")?;
178
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700179 DB.with(|db| db.borrow_mut().update_last_off_body(MonotonicRawTime::now()));
180 Ok(())
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700181 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700182
183 fn migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()> {
184 let caller_uid = ThreadState::get_calling_uid();
185
186 DB.with(|db| {
187 let key_id_guard = match source.domain {
188 Domain::APP | Domain::SELINUX | Domain::KEY_ID => {
189 let (key_id_guard, _) = LEGACY_MIGRATOR
190 .with_try_migrate(&source, caller_uid, || {
191 db.borrow_mut().load_key_entry(
192 &source,
193 KeyType::Client,
194 KeyEntryLoadBits::NONE,
195 caller_uid,
196 |k, av| {
197 check_key_permission(KeyPerm::use_(), k, &av)?;
198 check_key_permission(KeyPerm::delete(), k, &av)?;
199 check_key_permission(KeyPerm::grant(), k, &av)
200 },
201 )
202 })
203 .context("In migrate_key_namespace: Failed to load key blob.")?;
204 key_id_guard
205 }
206 _ => {
207 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(concat!(
208 "In migrate_key_namespace: ",
209 "Source domain must be one of APP, SELINUX, or KEY_ID."
210 ))
211 }
212 };
213
214 db.borrow_mut().migrate_key_namespace(key_id_guard, destination, caller_uid, |k| {
215 check_key_permission(KeyPerm::rebind(), k, &None)
216 })
217 })
218 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000219}
220
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800221impl Interface for Maintenance {}
Hasini Gunasingheda895552021-01-27 19:34:37 +0000222
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800223impl IKeystoreMaintenance for Maintenance {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000224 fn onUserPasswordChanged(&self, user_id: i32, password: Option<&[u8]>) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000225 let _wp = wd::watch_millis("IKeystoreMaintenance::onUserPasswordChanged", 500);
Paul Crowleyf61fee72021-03-17 14:38:44 -0700226 map_or_log_err(Self::on_user_password_changed(user_id, password.map(|pw| pw.into())), Ok)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000227 }
228
229 fn onUserAdded(&self, user_id: i32) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000230 let _wp = wd::watch_millis("IKeystoreMaintenance::onUserAdded", 500);
Hasini Gunasingheda895552021-01-27 19:34:37 +0000231 map_or_log_err(Self::add_or_remove_user(user_id), Ok)
232 }
233
234 fn onUserRemoved(&self, user_id: i32) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000235 let _wp = wd::watch_millis("IKeystoreMaintenance::onUserRemoved", 500);
Hasini Gunasingheda895552021-01-27 19:34:37 +0000236 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<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000240 let _wp = wd::watch_millis("IKeystoreMaintenance::clearNamespace", 500);
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800241 map_or_log_err(Self::clear_namespace(domain, nspace), Ok)
242 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000243
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700244 fn getState(&self, user_id: i32) -> BinderResult<AidlUserState> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000245 let _wp = wd::watch_millis("IKeystoreMaintenance::getState", 500);
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000246 map_or_log_err(Self::get_state(user_id), Ok)
247 }
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700248
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800249 fn earlyBootEnded(&self) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000250 let _wp = wd::watch_millis("IKeystoreMaintenance::earlyBootEnded", 500);
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800251 map_or_log_err(Self::early_boot_ended(), Ok)
252 }
253
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700254 fn onDeviceOffBody(&self) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000255 let _wp = wd::watch_millis("IKeystoreMaintenance::onDeviceOffBody", 500);
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700256 map_or_log_err(Self::on_device_off_body(), Ok)
257 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700258
259 fn migrateKeyNamespace(
260 &self,
261 source: &KeyDescriptor,
262 destination: &KeyDescriptor,
263 ) -> BinderResult<()> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000264 let _wp = wd::watch_millis("IKeystoreMaintenance::migrateKeyNamespace", 500);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700265 map_or_log_err(Self::migrate_key_namespace(source, destination), Ok)
266 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000267}