blob: 37263580d3aaf42525c68ee3390b1fcae1ef785b [file] [log] [blame]
Janis Danisevskis1af91262020-08-10 14:58:08 -07001// Copyright 2020, 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 Danisevskis1af91262020-08-10 14:58:08 -070015//! This crate implement the core Keystore 2.0 service API as defined by the Keystore 2.0
16//! AIDL spec.
17
Max Bires8e93d2b2021-01-14 13:17:59 -080018use std::collections::HashMap;
19
Pavel Grafov94243c22021-04-21 18:03:11 +010020use crate::audit_log::log_key_deleted;
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000021use crate::ks_err;
Janis Danisevskise92a5e62020-12-02 12:57:41 -080022use crate::permission::{KeyPerm, KeystorePerm};
Janis Danisevskis1af91262020-08-10 14:58:08 -070023use crate::security_level::KeystoreSecurityLevel;
Janis Danisevskis04b02832020-10-26 09:21:40 -070024use crate::utils::{
Eran Messeri24f31972023-01-25 17:00:33 +000025 check_grant_permission, check_key_permission, check_keystore_permission, count_key_entries,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080026 key_parameters_to_authorizations, list_key_entries, uid_to_android_user, watchdog as wd,
Janis Danisevskis04b02832020-10-26 09:21:40 -070027};
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000028use crate::{
29 database::Uuid,
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080030 globals::{create_thread_local_db, DB, LEGACY_BLOB_LOADER, LEGACY_IMPORTER, SUPER_KEY},
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000031};
Max Bires8e93d2b2021-01-14 13:17:59 -080032use crate::{database::KEYSTORE_UUID, permission};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080033use crate::{
34 database::{KeyEntryLoadBits, KeyType, SubComponentType},
35 error::ResponseCode,
36};
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070037use crate::{
David Drysdaledb7ddde2024-06-07 16:22:49 +010038 error::{self, into_logged_binder, ErrorCode},
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070039 id_rotation::IdRotationState,
40};
Shawn Willden708744a2020-12-11 13:05:27 +000041use android_hardware_security_keymint::aidl::android::hardware::security::keymint::SecurityLevel::SecurityLevel;
Andrew Walbrande45c8b2021-04-13 14:42:38 +000042use android_hardware_security_keymint::binder::{BinderFeatures, Strong, ThreadState};
Janis Danisevskis1af91262020-08-10 14:58:08 -070043use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis2c7f9622020-09-30 16:30:31 -070044 Domain::Domain, IKeystoreSecurityLevel::IKeystoreSecurityLevel,
45 IKeystoreService::BnKeystoreService, IKeystoreService::IKeystoreService,
46 KeyDescriptor::KeyDescriptor, KeyEntryResponse::KeyEntryResponse, KeyMetadata::KeyMetadata,
Janis Danisevskis1af91262020-08-10 14:58:08 -070047};
Max Bires8e93d2b2021-01-14 13:17:59 -080048use anyhow::{Context, Result};
Janis Danisevskise92a5e62020-12-02 12:57:41 -080049use error::Error;
50use keystore2_selinux as selinux;
Janis Danisevskis1af91262020-08-10 14:58:08 -070051
52/// Implementation of the IKeystoreService.
Max Bires8e93d2b2021-01-14 13:17:59 -080053#[derive(Default)]
Janis Danisevskis1af91262020-08-10 14:58:08 -070054pub struct KeystoreService {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -070055 i_sec_level_by_uuid: HashMap<Uuid, Strong<dyn IKeystoreSecurityLevel>>,
Max Bires8e93d2b2021-01-14 13:17:59 -080056 uuid_by_sec_level: HashMap<SecurityLevel, Uuid>,
Janis Danisevskis1af91262020-08-10 14:58:08 -070057}
58
59impl KeystoreService {
60 /// Create a new instance of the Keystore 2.0 service.
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070061 pub fn new_native_binder(
62 id_rotation_state: IdRotationState,
63 ) -> Result<Strong<dyn IKeystoreService>> {
Max Bires8e93d2b2021-01-14 13:17:59 -080064 let mut result: Self = Default::default();
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070065 let (dev, uuid) = KeystoreSecurityLevel::new_native_binder(
66 SecurityLevel::TRUSTED_ENVIRONMENT,
67 id_rotation_state.clone(),
68 )
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000069 .context(ks_err!("Trying to construct mandatory security level TEE."))?;
Max Bires8e93d2b2021-01-14 13:17:59 -080070 result.i_sec_level_by_uuid.insert(uuid, dev);
71 result.uuid_by_sec_level.insert(SecurityLevel::TRUSTED_ENVIRONMENT, uuid);
Janis Danisevskisba998992020-12-29 16:08:40 -080072
Max Bires8e93d2b2021-01-14 13:17:59 -080073 // Strongbox is optional, so we ignore errors and turn the result into an Option.
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070074 if let Ok((dev, uuid)) =
75 KeystoreSecurityLevel::new_native_binder(SecurityLevel::STRONGBOX, id_rotation_state)
Max Bires8e93d2b2021-01-14 13:17:59 -080076 {
77 result.i_sec_level_by_uuid.insert(uuid, dev);
78 result.uuid_by_sec_level.insert(SecurityLevel::STRONGBOX, uuid);
79 }
80
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000081 let uuid_by_sec_level = result.uuid_by_sec_level.clone();
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080082 LEGACY_IMPORTER
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000083 .set_init(move || {
84 (create_thread_local_db(), uuid_by_sec_level, LEGACY_BLOB_LOADER.clone())
85 })
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000086 .context(ks_err!("Trying to initialize the legacy migrator."))?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000087
Andrew Walbrande45c8b2021-04-13 14:42:38 +000088 Ok(BnKeystoreService::new_binder(
89 result,
90 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
91 ))
Janis Danisevskis1af91262020-08-10 14:58:08 -070092 }
93
Max Bires8e93d2b2021-01-14 13:17:59 -080094 fn uuid_to_sec_level(&self, uuid: &Uuid) -> SecurityLevel {
95 self.uuid_by_sec_level
96 .iter()
97 .find(|(_, v)| **v == *uuid)
98 .map(|(s, _)| *s)
99 .unwrap_or(SecurityLevel::SOFTWARE)
100 }
101
Stephen Crane221bbb52020-12-16 15:52:10 -0800102 fn get_i_sec_level_by_uuid(&self, uuid: &Uuid) -> Result<Strong<dyn IKeystoreSecurityLevel>> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800103 if let Some(dev) = self.i_sec_level_by_uuid.get(uuid) {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700104 Ok(dev.clone())
Max Bires8e93d2b2021-01-14 13:17:59 -0800105 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000106 Err(error::Error::sys()).context(ks_err!("KeyMint instance for key not found."))
Max Bires8e93d2b2021-01-14 13:17:59 -0800107 }
Janis Danisevskisba998992020-12-29 16:08:40 -0800108 }
109
Janis Danisevskis1af91262020-08-10 14:58:08 -0700110 fn get_security_level(
111 &self,
Max Bires8e93d2b2021-01-14 13:17:59 -0800112 sec_level: SecurityLevel,
Stephen Crane221bbb52020-12-16 15:52:10 -0800113 ) -> Result<Strong<dyn IKeystoreSecurityLevel>> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800114 if let Some(dev) = self
115 .uuid_by_sec_level
116 .get(&sec_level)
117 .and_then(|uuid| self.i_sec_level_by_uuid.get(uuid))
118 {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700119 Ok(dev.clone())
Max Bires8e93d2b2021-01-14 13:17:59 -0800120 } else {
121 Err(error::Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000122 .context(ks_err!("No such security level."))
Max Bires8e93d2b2021-01-14 13:17:59 -0800123 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700124 }
125
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700126 fn get_key_entry(&self, key: &KeyDescriptor) -> Result<KeyEntryResponse> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000127 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800128
Eric Biggers673d34a2023-10-18 01:54:18 +0000129 let super_key = SUPER_KEY
130 .read()
131 .unwrap()
132 .get_after_first_unlock_key_by_user_id(uid_to_android_user(caller_uid));
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800133
Janis Danisevskisaec14592020-11-12 09:41:49 -0800134 let (key_id_guard, mut key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700135 .with(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800136 LEGACY_IMPORTER.with_try_import(key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000137 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700138 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000139 KeyType::Client,
140 KeyEntryLoadBits::PUBLIC,
141 caller_uid,
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700142 |k, av| check_key_permission(KeyPerm::GetInfo, k, &av),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000143 )
144 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700145 })
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000146 .context(ks_err!("while trying to load key info."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700147
Janis Danisevskis377d1002021-01-27 19:07:48 -0800148 let i_sec_level = if !key_entry.pure_cert() {
149 Some(
Max Bires8e93d2b2021-01-14 13:17:59 -0800150 self.get_i_sec_level_by_uuid(key_entry.km_uuid())
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000151 .context(ks_err!("Trying to get security level proxy."))?,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800152 )
153 } else {
154 None
155 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700156
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700157 Ok(KeyEntryResponse {
Janis Danisevskis377d1002021-01-27 19:07:48 -0800158 iSecurityLevel: i_sec_level,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700159 metadata: KeyMetadata {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700160 key: KeyDescriptor {
161 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800162 nspace: key_id_guard.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700163 ..Default::default()
164 },
Max Bires8e93d2b2021-01-14 13:17:59 -0800165 keySecurityLevel: self.uuid_to_sec_level(key_entry.km_uuid()),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700166 certificate: key_entry.take_cert(),
167 certificateChain: key_entry.take_cert_chain(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800168 modificationTimeMs: key_entry
169 .metadata()
170 .creation_date()
171 .map(|d| d.to_millis_epoch())
172 .ok_or(Error::Rc(ResponseCode::VALUE_CORRUPTED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000173 .context(ks_err!("Trying to get creation date."))?,
Janis Danisevskis04b02832020-10-26 09:21:40 -0700174 authorizations: key_parameters_to_authorizations(key_entry.into_key_parameters()),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700175 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700176 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700177 }
178
179 fn update_subcomponent(
180 &self,
181 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700182 public_cert: Option<&[u8]>,
183 certificate_chain: Option<&[u8]>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700184 ) -> Result<()> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000185 let caller_uid = ThreadState::get_calling_uid();
Eric Biggers673d34a2023-10-18 01:54:18 +0000186 let super_key = SUPER_KEY
187 .read()
188 .unwrap()
189 .get_after_first_unlock_key_by_user_id(uid_to_android_user(caller_uid));
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800190
Janis Danisevskis1af91262020-08-10 14:58:08 -0700191 DB.with::<_, Result<()>>(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800192 let entry = match LEGACY_IMPORTER.with_try_import(key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000193 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700194 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000195 KeyType::Client,
196 KeyEntryLoadBits::NONE,
197 caller_uid,
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000198 |k, av| check_key_permission(KeyPerm::Update, k, &av).context(ks_err!()),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000199 )
200 }) {
Janis Danisevskis377d1002021-01-27 19:07:48 -0800201 Err(e) => match e.root_cause().downcast_ref::<Error>() {
202 Some(Error::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
203 _ => Err(e),
204 },
205 Ok(v) => Ok(Some(v)),
206 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000207 .context(ks_err!("Failed to load key entry."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700208
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000209 let mut db = db.borrow_mut();
Paul Crowleyd5653e52021-03-25 09:46:31 -0700210 if let Some((key_id_guard, _key_entry)) = entry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800211 db.set_blob(&key_id_guard, SubComponentType::CERT, public_cert, None)
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000212 .context(ks_err!("Failed to update cert subcomponent."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -0800213
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800214 db.set_blob(&key_id_guard, SubComponentType::CERT_CHAIN, certificate_chain, None)
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000215 .context(ks_err!("Failed to update cert chain subcomponent."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -0800216 return Ok(());
Janis Danisevskis1af91262020-08-10 14:58:08 -0700217 }
218
Janis Danisevskis377d1002021-01-27 19:07:48 -0800219 // If we reach this point we have to check the special condition where a certificate
220 // entry may be made.
221 if !(public_cert.is_none() && certificate_chain.is_some()) {
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000222 return Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
223 .context(ks_err!("No key to update."));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700224 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800225
226 // So we know that we have a certificate chain and no public cert.
227 // Now check that we have everything we need to make a new certificate entry.
228 let key = match (key.domain, &key.alias) {
229 (Domain::APP, Some(ref alias)) => KeyDescriptor {
230 domain: Domain::APP,
231 nspace: ThreadState::get_calling_uid() as i64,
232 alias: Some(alias.clone()),
233 blob: None,
234 },
235 (Domain::SELINUX, Some(_)) => key.clone(),
236 _ => {
237 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000238 .context(ks_err!("Domain must be APP or SELINUX to insert a certificate."))
Janis Danisevskis377d1002021-01-27 19:07:48 -0800239 }
240 };
241
242 // Security critical: This must return on failure. Do not remove the `?`;
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700243 check_key_permission(KeyPerm::Rebind, &key, &None)
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000244 .context(ks_err!("Caller does not have permission to insert this certificate."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -0800245
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700246 db.store_new_certificate(
247 &key,
248 KeyType::Client,
249 certificate_chain.unwrap(),
250 &KEYSTORE_UUID,
251 )
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000252 .context(ks_err!("Failed to insert new certificate."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700253 Ok(())
254 })
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000255 .context(ks_err!())
Janis Danisevskis1af91262020-08-10 14:58:08 -0700256 }
257
Eran Messeri24f31972023-01-25 17:00:33 +0000258 fn get_key_descriptor_for_lookup(
259 &self,
260 domain: Domain,
261 namespace: i64,
262 ) -> Result<KeyDescriptor> {
Janis Danisevskise92a5e62020-12-02 12:57:41 -0800263 let mut k = match domain {
264 Domain::APP => KeyDescriptor {
265 domain,
266 nspace: ThreadState::get_calling_uid() as u64 as i64,
267 ..Default::default()
268 },
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000269 Domain::SELINUX => KeyDescriptor { domain, nspace: namespace, ..Default::default() },
270 _ => {
271 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!(
272 "List entries is only supported for Domain::APP and Domain::SELINUX."
273 ))
274 }
Janis Danisevskise92a5e62020-12-02 12:57:41 -0800275 };
276
277 // First we check if the caller has the info permission for the selected domain/namespace.
278 // By default we use the calling uid as namespace if domain is Domain::APP.
279 // If the first check fails we check if the caller has the list permission allowing to list
280 // any namespace. In that case we also adjust the queried namespace if a specific uid was
281 // selected.
Chris Wailes20f50df2022-04-19 17:23:52 -0700282 if let Err(e) = check_key_permission(KeyPerm::GetInfo, &k, &None) {
283 if let Some(selinux::Error::PermissionDenied) =
Rajesh Nyamagoud16198a32022-07-26 18:45:55 +0000284 e.root_cause().downcast_ref::<selinux::Error>()
285 {
Chris Wailes20f50df2022-04-19 17:23:52 -0700286 check_keystore_permission(KeystorePerm::List)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000287 .context(ks_err!("While checking keystore permission."))?;
Chris Wailes20f50df2022-04-19 17:23:52 -0700288 if namespace != -1 {
289 k.nspace = namespace;
Janis Danisevskise92a5e62020-12-02 12:57:41 -0800290 }
Chris Wailes20f50df2022-04-19 17:23:52 -0700291 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000292 return Err(e).context(ks_err!("While checking key permission."))?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -0800293 }
Chris Wailes20f50df2022-04-19 17:23:52 -0700294 }
Eran Messeri24f31972023-01-25 17:00:33 +0000295 Ok(k)
296 }
Janis Danisevskise92a5e62020-12-02 12:57:41 -0800297
Eran Messeri24f31972023-01-25 17:00:33 +0000298 fn list_entries(&self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
299 let k = self.get_key_descriptor_for_lookup(domain, namespace)?;
300
301 DB.with(|db| list_key_entries(&mut db.borrow_mut(), k.domain, k.nspace, None))
302 }
303
304 fn count_num_entries(&self, domain: Domain, namespace: i64) -> Result<i32> {
305 let k = self.get_key_descriptor_for_lookup(domain, namespace)?;
306
307 DB.with(|db| count_key_entries(&mut db.borrow_mut(), k.domain, k.nspace))
308 }
309
310 fn list_entries_batched(
311 &self,
312 domain: Domain,
313 namespace: i64,
314 start_past_alias: Option<&str>,
315 ) -> Result<Vec<KeyDescriptor>> {
316 let k = self.get_key_descriptor_for_lookup(domain, namespace)?;
317 DB.with(|db| list_key_entries(&mut db.borrow_mut(), k.domain, k.nspace, start_past_alias))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700318 }
319
320 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800321 let caller_uid = ThreadState::get_calling_uid();
Eric Biggers673d34a2023-10-18 01:54:18 +0000322 let super_key = SUPER_KEY
323 .read()
324 .unwrap()
325 .get_after_first_unlock_key_by_user_id(uid_to_android_user(caller_uid));
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800326
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800327 DB.with(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800328 LEGACY_IMPORTER.with_try_import(key, caller_uid, super_key, || {
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700329 db.borrow_mut().unbind_key(key, KeyType::Client, caller_uid, |k, av| {
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000330 check_key_permission(KeyPerm::Delete, k, &av)
331 .context(ks_err!("During delete_key."))
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000332 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800333 })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800334 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000335 .context(ks_err!("Trying to unbind the key."))?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800336 Ok(())
Janis Danisevskis1af91262020-08-10 14:58:08 -0700337 }
338
339 fn grant(
340 &self,
341 key: &KeyDescriptor,
342 grantee_uid: i32,
343 access_vector: permission::KeyPermSet,
344 ) -> Result<KeyDescriptor> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000345 let caller_uid = ThreadState::get_calling_uid();
Eric Biggers673d34a2023-10-18 01:54:18 +0000346 let super_key = SUPER_KEY
347 .read()
348 .unwrap()
349 .get_after_first_unlock_key_by_user_id(uid_to_android_user(caller_uid));
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800350
Janis Danisevskis1af91262020-08-10 14:58:08 -0700351 DB.with(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800352 LEGACY_IMPORTER.with_try_import(key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000353 db.borrow_mut().grant(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700354 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000355 caller_uid,
356 grantee_uid as u32,
357 access_vector,
358 |k, av| check_grant_permission(*av, k).context("During grant."),
359 )
360 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700361 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000362 .context(ks_err!("KeystoreService::grant."))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700363 }
364
365 fn ungrant(&self, key: &KeyDescriptor, grantee_uid: i32) -> Result<()> {
366 DB.with(|db| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700367 db.borrow_mut().ungrant(key, ThreadState::get_calling_uid(), grantee_uid as u32, |k| {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700368 check_key_permission(KeyPerm::Grant, k, &None)
Janis Danisevskis66784c42021-01-27 08:40:25 -0800369 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700370 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000371 .context(ks_err!("KeystoreService::ungrant."))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700372 }
373}
374
375impl binder::Interface for KeystoreService {}
376
377// Implementation of IKeystoreService. See AIDL spec at
378// system/security/keystore2/binder/android/security/keystore2/IKeystoreService.aidl
379impl IKeystoreService for KeystoreService {
380 fn getSecurityLevel(
381 &self,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700382 security_level: SecurityLevel,
Stephen Crane23cf7242022-01-19 17:49:46 +0000383 ) -> binder::Result<Strong<dyn IKeystoreSecurityLevel>> {
Hasini Gunasinghe5a893e82021-05-05 14:32:32 +0000384 let _wp = wd::watch_millis_with("IKeystoreService::getSecurityLevel", 500, move || {
385 format!("security_level: {}", security_level.0)
386 });
David Drysdaledb7ddde2024-06-07 16:22:49 +0100387 self.get_security_level(security_level).map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700388 }
Stephen Crane23cf7242022-01-19 17:49:46 +0000389 fn getKeyEntry(&self, key: &KeyDescriptor) -> binder::Result<KeyEntryResponse> {
David Drysdale541846b2024-05-23 13:16:07 +0100390 let _wp = wd::watch("IKeystoreService::get_key_entry");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100391 self.get_key_entry(key).map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700392 }
393 fn updateSubcomponent(
394 &self,
395 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700396 public_cert: Option<&[u8]>,
397 certificate_chain: Option<&[u8]>,
Stephen Crane23cf7242022-01-19 17:49:46 +0000398 ) -> binder::Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100399 let _wp = wd::watch("IKeystoreService::updateSubcomponent");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100400 self.update_subcomponent(key, public_cert, certificate_chain).map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700401 }
Stephen Crane23cf7242022-01-19 17:49:46 +0000402 fn listEntries(&self, domain: Domain, namespace: i64) -> binder::Result<Vec<KeyDescriptor>> {
David Drysdale541846b2024-05-23 13:16:07 +0100403 let _wp = wd::watch("IKeystoreService::listEntries");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100404 self.list_entries(domain, namespace).map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700405 }
Stephen Crane23cf7242022-01-19 17:49:46 +0000406 fn deleteKey(&self, key: &KeyDescriptor) -> binder::Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100407 let _wp = wd::watch("IKeystoreService::deleteKey");
Pavel Grafov94243c22021-04-21 18:03:11 +0100408 let result = self.delete_key(key);
409 log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
David Drysdaledb7ddde2024-06-07 16:22:49 +0100410 result.map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700411 }
412 fn grant(
413 &self,
414 key: &KeyDescriptor,
415 grantee_uid: i32,
416 access_vector: i32,
Stephen Crane23cf7242022-01-19 17:49:46 +0000417 ) -> binder::Result<KeyDescriptor> {
David Drysdale541846b2024-05-23 13:16:07 +0100418 let _wp = wd::watch("IKeystoreService::grant");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100419 self.grant(key, grantee_uid, access_vector.into()).map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700420 }
Stephen Crane23cf7242022-01-19 17:49:46 +0000421 fn ungrant(&self, key: &KeyDescriptor, grantee_uid: i32) -> binder::Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100422 let _wp = wd::watch("IKeystoreService::ungrant");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100423 self.ungrant(key, grantee_uid).map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700424 }
Eran Messeri24f31972023-01-25 17:00:33 +0000425 fn listEntriesBatched(
426 &self,
427 domain: Domain,
428 namespace: i64,
429 start_past_alias: Option<&str>,
430 ) -> binder::Result<Vec<KeyDescriptor>> {
David Drysdale541846b2024-05-23 13:16:07 +0100431 let _wp = wd::watch("IKeystoreService::listEntriesBatched");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100432 self.list_entries_batched(domain, namespace, start_past_alias).map_err(into_logged_binder)
Eran Messeri24f31972023-01-25 17:00:33 +0000433 }
434
435 fn getNumberOfEntries(&self, domain: Domain, namespace: i64) -> binder::Result<i32> {
David Drysdale541846b2024-05-23 13:16:07 +0100436 let _wp = wd::watch("IKeystoreService::getNumberOfEntries");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100437 self.count_num_entries(domain, namespace).map_err(into_logged_binder)
Eran Messeri24f31972023-01-25 17:00:33 +0000438 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700439}