blob: 1691f9d38ea6870554e7cb72b27606aa102d31ab [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 Danisevskiscdcf4e52021-04-14 15:44:36 -070025use crate::utils::{check_key_permission, check_keystore_permission};
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};
Janis Danisevskis34a0cf22021-03-08 09:19:03 -080032use android_security_maintenance::binder::{Interface, Result as BinderResult};
Hasini Gunasingheda895552021-01-27 19:34:37 +000033use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -070034use android_system_keystore2::aidl::android::system::keystore2::{
35 Domain::Domain, KeyDescriptor::KeyDescriptor,
36};
Hasini Gunasingheda895552021-01-27 19:34:37 +000037use anyhow::{Context, Result};
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -070038use binder::{IBinderInternal, Strong, ThreadState};
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>> {
48 let result = BnKeystoreMaintenance::new_binder(Self);
Hasini Gunasingheda895552021-01-27 19:34:37 +000049 result.as_binder().set_requesting_sid(true);
50 Ok(result)
51 }
52
Paul Crowleyf61fee72021-03-17 14:38:44 -070053 fn on_user_password_changed(user_id: i32, password: Option<Password>) -> Result<()> {
Hasini Gunasingheda895552021-01-27 19:34:37 +000054 //Check permission. Function should return if this failed. Therefore having '?' at the end
55 //is very important.
56 check_keystore_permission(KeystorePerm::change_password())
57 .context("In on_user_password_changed.")?;
58
Paul Crowley7a658392021-03-18 17:08:20 -070059 if let Some(pw) = password.as_ref() {
60 DB.with(|db| {
Paul Crowley8d5b2532021-03-19 10:53:07 -070061 SUPER_KEY.unlock_screen_lock_bound_key(&mut db.borrow_mut(), user_id as u32, pw)
Paul Crowley7a658392021-03-18 17:08:20 -070062 })
Paul Crowley8d5b2532021-03-19 10:53:07 -070063 .context("In on_user_password_changed: unlock_screen_lock_bound_key failed")?;
Paul Crowley7a658392021-03-18 17:08:20 -070064 }
65
Hasini Gunasingheda895552021-01-27 19:34:37 +000066 match DB
67 .with(|db| {
68 UserState::get_with_password_changed(
69 &mut db.borrow_mut(),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000070 &LEGACY_MIGRATOR,
Hasini Gunasingheda895552021-01-27 19:34:37 +000071 &SUPER_KEY,
72 user_id as u32,
Paul Crowleyf61fee72021-03-17 14:38:44 -070073 password.as_ref(),
Hasini Gunasingheda895552021-01-27 19:34:37 +000074 )
75 })
76 .context("In on_user_password_changed.")?
77 {
78 UserState::LskfLocked => {
Janis Danisevskiseed69842021-02-18 20:04:10 -080079 // Error - password can not be changed when the device is locked
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -070080 Err(Error::Rc(ResponseCode::LOCKED))
Hasini Gunasingheda895552021-01-27 19:34:37 +000081 .context("In on_user_password_changed. Device is locked.")
82 }
83 _ => {
Janis Danisevskiseed69842021-02-18 20:04:10 -080084 // LskfLocked is the only error case for password change
Hasini Gunasingheda895552021-01-27 19:34:37 +000085 Ok(())
86 }
87 }
88 }
89
90 fn add_or_remove_user(user_id: i32) -> Result<()> {
91 // Check permission. Function should return if this failed. Therefore having '?' at the end
92 // is very important.
93 check_keystore_permission(KeystorePerm::change_user()).context("In add_or_remove_user.")?;
Janis Danisevskiseed69842021-02-18 20:04:10 -080094 DB.with(|db| {
95 UserState::reset_user(
96 &mut db.borrow_mut(),
97 &SUPER_KEY,
98 &LEGACY_MIGRATOR,
99 user_id as u32,
100 false,
101 )
102 })
103 .context("In add_or_remove_user: Trying to delete keys from db.")
Hasini Gunasingheda895552021-01-27 19:34:37 +0000104 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800105
106 fn clear_namespace(domain: Domain, nspace: i64) -> Result<()> {
107 // Permission check. Must return on error. Do not touch the '?'.
108 check_keystore_permission(KeystorePerm::clear_uid()).context("In clear_namespace.")?;
109
110 LEGACY_MIGRATOR
111 .bulk_delete_uid(domain, nspace)
112 .context("In clear_namespace: Trying to delete legacy keys.")?;
113 DB.with(|db| db.borrow_mut().unbind_keys_for_namespace(domain, nspace))
114 .context("In clear_namespace: Trying to delete keys from db.")
115 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000116
117 fn get_state(user_id: i32) -> Result<AidlUserState> {
118 // Check permission. Function should return if this failed. Therefore having '?' at the end
119 // is very important.
120 check_keystore_permission(KeystorePerm::get_state()).context("In get_state.")?;
121 let state = DB
122 .with(|db| {
123 UserState::get(&mut db.borrow_mut(), &LEGACY_MIGRATOR, &SUPER_KEY, user_id as u32)
124 })
125 .context("In get_state. Trying to get UserState.")?;
126
127 match state {
128 UserState::Uninitialized => Ok(AidlUserState::UNINITIALIZED),
129 UserState::LskfUnlocked(_) => Ok(AidlUserState::LSKF_UNLOCKED),
130 UserState::LskfLocked => Ok(AidlUserState::LSKF_LOCKED),
131 }
132 }
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700133
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800134 fn early_boot_ended_help(sec_level: &SecurityLevel) -> Result<()> {
135 let (dev, _, _) =
136 get_keymint_device(sec_level).context("In early_boot_ended: getting keymint device")?;
137 let km_dev: Strong<dyn IKeyMintDevice> =
138 dev.get_interface().context("In early_boot_ended: getting keymint device interface")?;
139 map_km_error(km_dev.earlyBootEnded())
140 .context("In keymint device: calling earlyBootEnded")?;
141 Ok(())
142 }
143
144 fn early_boot_ended() -> Result<()> {
145 check_keystore_permission(KeystorePerm::early_boot_ended())
146 .context("In early_boot_ended. Checking permission")?;
Paul Crowley44c02da2021-04-08 17:04:43 +0000147 log::info!("In early_boot_ended.");
148
149 if let Err(e) = DB.with(|db| SUPER_KEY.set_up_boot_level_cache(&mut db.borrow_mut())) {
150 log::error!("SUPER_KEY.set_up_boot_level_cache failed:\n{:?}\n:(", e);
151 }
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800152
153 let sec_levels = [
154 (SecurityLevel::TRUSTED_ENVIRONMENT, "TRUSTED_ENVIRONMENT"),
155 (SecurityLevel::STRONGBOX, "STRONGBOX"),
156 ];
157 sec_levels.iter().fold(Ok(()), |result, (sec_level, sec_level_string)| {
158 let curr_result = Maintenance::early_boot_ended_help(sec_level);
159 if curr_result.is_err() {
160 log::error!(
161 "Call to earlyBootEnded failed for security level {}.",
162 &sec_level_string
163 );
164 }
165 result.and(curr_result)
166 })
167 }
168
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700169 fn on_device_off_body() -> Result<()> {
170 // Security critical permission check. This statement must return on fail.
171 check_keystore_permission(KeystorePerm::report_off_body())
172 .context("In on_device_off_body.")?;
173
174 DB.with(|db| db.borrow_mut().update_last_off_body(MonotonicRawTime::now()))
175 .context("In on_device_off_body: Trying to update last off body time.")
176 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700177
178 fn migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()> {
179 let caller_uid = ThreadState::get_calling_uid();
180
181 DB.with(|db| {
182 let key_id_guard = match source.domain {
183 Domain::APP | Domain::SELINUX | Domain::KEY_ID => {
184 let (key_id_guard, _) = LEGACY_MIGRATOR
185 .with_try_migrate(&source, caller_uid, || {
186 db.borrow_mut().load_key_entry(
187 &source,
188 KeyType::Client,
189 KeyEntryLoadBits::NONE,
190 caller_uid,
191 |k, av| {
192 check_key_permission(KeyPerm::use_(), k, &av)?;
193 check_key_permission(KeyPerm::delete(), k, &av)?;
194 check_key_permission(KeyPerm::grant(), k, &av)
195 },
196 )
197 })
198 .context("In migrate_key_namespace: Failed to load key blob.")?;
199 key_id_guard
200 }
201 _ => {
202 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(concat!(
203 "In migrate_key_namespace: ",
204 "Source domain must be one of APP, SELINUX, or KEY_ID."
205 ))
206 }
207 };
208
209 db.borrow_mut().migrate_key_namespace(key_id_guard, destination, caller_uid, |k| {
210 check_key_permission(KeyPerm::rebind(), k, &None)
211 })
212 })
213 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000214}
215
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800216impl Interface for Maintenance {}
Hasini Gunasingheda895552021-01-27 19:34:37 +0000217
Janis Danisevskis34a0cf22021-03-08 09:19:03 -0800218impl IKeystoreMaintenance for Maintenance {
Hasini Gunasingheda895552021-01-27 19:34:37 +0000219 fn onUserPasswordChanged(&self, user_id: i32, password: Option<&[u8]>) -> BinderResult<()> {
Paul Crowleyf61fee72021-03-17 14:38:44 -0700220 map_or_log_err(Self::on_user_password_changed(user_id, password.map(|pw| pw.into())), Ok)
Hasini Gunasingheda895552021-01-27 19:34:37 +0000221 }
222
223 fn onUserAdded(&self, user_id: i32) -> BinderResult<()> {
224 map_or_log_err(Self::add_or_remove_user(user_id), Ok)
225 }
226
227 fn onUserRemoved(&self, user_id: i32) -> BinderResult<()> {
228 map_or_log_err(Self::add_or_remove_user(user_id), Ok)
229 }
Janis Danisevskisddd6e752021-02-22 18:46:55 -0800230
231 fn clearNamespace(&self, domain: Domain, nspace: i64) -> BinderResult<()> {
232 map_or_log_err(Self::clear_namespace(domain, nspace), Ok)
233 }
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000234
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700235 fn getState(&self, user_id: i32) -> BinderResult<AidlUserState> {
Hasini Gunasinghe9ee18412021-03-11 20:12:44 +0000236 map_or_log_err(Self::get_state(user_id), Ok)
237 }
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700238
Satya Tangirala5b9e5b12021-03-09 12:54:21 -0800239 fn earlyBootEnded(&self) -> BinderResult<()> {
240 map_or_log_err(Self::early_boot_ended(), Ok)
241 }
242
Janis Danisevskis333b7c02021-03-23 18:57:41 -0700243 fn onDeviceOffBody(&self) -> BinderResult<()> {
244 map_or_log_err(Self::on_device_off_body(), Ok)
245 }
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -0700246
247 fn migrateKeyNamespace(
248 &self,
249 source: &KeyDescriptor,
250 destination: &KeyDescriptor,
251 ) -> BinderResult<()> {
252 map_or_log_err(Self::migrate_key_namespace(source, destination), Ok)
253 }
Hasini Gunasingheda895552021-01-27 19:34:37 +0000254}