blob: 95e17445721df4ce19a92a73554eee4acabeeca7 [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();
David Drysdale18c29f32024-07-19 12:54:19 +010065 let (dev, uuid) = match KeystoreSecurityLevel::new_native_binder(
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070066 SecurityLevel::TRUSTED_ENVIRONMENT,
67 id_rotation_state.clone(),
David Drysdale18c29f32024-07-19 12:54:19 +010068 ) {
69 Ok(v) => v,
70 Err(e) => {
71 log::error!("Failed to construct mandatory security level TEE: {e:?}");
72 log::error!("Does the device have a /default Keymaster or KeyMint instance?");
73 return Err(e.context(ks_err!("Trying to construct mandatory security level TEE")));
74 }
75 };
76
Max Bires8e93d2b2021-01-14 13:17:59 -080077 result.i_sec_level_by_uuid.insert(uuid, dev);
78 result.uuid_by_sec_level.insert(SecurityLevel::TRUSTED_ENVIRONMENT, uuid);
Janis Danisevskisba998992020-12-29 16:08:40 -080079
Max Bires8e93d2b2021-01-14 13:17:59 -080080 // Strongbox is optional, so we ignore errors and turn the result into an Option.
Janis Danisevskis5cb52dc2021-04-07 16:31:18 -070081 if let Ok((dev, uuid)) =
82 KeystoreSecurityLevel::new_native_binder(SecurityLevel::STRONGBOX, id_rotation_state)
Max Bires8e93d2b2021-01-14 13:17:59 -080083 {
84 result.i_sec_level_by_uuid.insert(uuid, dev);
85 result.uuid_by_sec_level.insert(SecurityLevel::STRONGBOX, uuid);
86 }
87
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000088 let uuid_by_sec_level = result.uuid_by_sec_level.clone();
Janis Danisevskis0ffb8a82022-02-06 22:37:21 -080089 LEGACY_IMPORTER
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000090 .set_init(move || {
91 (create_thread_local_db(), uuid_by_sec_level, LEGACY_BLOB_LOADER.clone())
92 })
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +000093 .context(ks_err!("Trying to initialize the legacy migrator."))?;
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +000094
Andrew Walbrande45c8b2021-04-13 14:42:38 +000095 Ok(BnKeystoreService::new_binder(
96 result,
97 BinderFeatures { set_requesting_sid: true, ..BinderFeatures::default() },
98 ))
Janis Danisevskis1af91262020-08-10 14:58:08 -070099 }
100
Max Bires8e93d2b2021-01-14 13:17:59 -0800101 fn uuid_to_sec_level(&self, uuid: &Uuid) -> SecurityLevel {
102 self.uuid_by_sec_level
103 .iter()
104 .find(|(_, v)| **v == *uuid)
105 .map(|(s, _)| *s)
106 .unwrap_or(SecurityLevel::SOFTWARE)
107 }
108
Stephen Crane221bbb52020-12-16 15:52:10 -0800109 fn get_i_sec_level_by_uuid(&self, uuid: &Uuid) -> Result<Strong<dyn IKeystoreSecurityLevel>> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800110 if let Some(dev) = self.i_sec_level_by_uuid.get(uuid) {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700111 Ok(dev.clone())
Max Bires8e93d2b2021-01-14 13:17:59 -0800112 } else {
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000113 Err(error::Error::sys()).context(ks_err!("KeyMint instance for key not found."))
Max Bires8e93d2b2021-01-14 13:17:59 -0800114 }
Janis Danisevskisba998992020-12-29 16:08:40 -0800115 }
116
Janis Danisevskis1af91262020-08-10 14:58:08 -0700117 fn get_security_level(
118 &self,
Max Bires8e93d2b2021-01-14 13:17:59 -0800119 sec_level: SecurityLevel,
Stephen Crane221bbb52020-12-16 15:52:10 -0800120 ) -> Result<Strong<dyn IKeystoreSecurityLevel>> {
Max Bires8e93d2b2021-01-14 13:17:59 -0800121 if let Some(dev) = self
122 .uuid_by_sec_level
123 .get(&sec_level)
124 .and_then(|uuid| self.i_sec_level_by_uuid.get(uuid))
125 {
Janis Danisevskis5f3a0572021-06-18 11:26:42 -0700126 Ok(dev.clone())
Max Bires8e93d2b2021-01-14 13:17:59 -0800127 } else {
128 Err(error::Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000129 .context(ks_err!("No such security level."))
Max Bires8e93d2b2021-01-14 13:17:59 -0800130 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700131 }
132
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700133 fn get_key_entry(&self, key: &KeyDescriptor) -> Result<KeyEntryResponse> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000134 let caller_uid = ThreadState::get_calling_uid();
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800135
Eric Biggers673d34a2023-10-18 01:54:18 +0000136 let super_key = SUPER_KEY
137 .read()
138 .unwrap()
139 .get_after_first_unlock_key_by_user_id(uid_to_android_user(caller_uid));
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800140
Janis Danisevskisaec14592020-11-12 09:41:49 -0800141 let (key_id_guard, mut key_entry) = DB
Janis Danisevskis1af91262020-08-10 14:58:08 -0700142 .with(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800143 LEGACY_IMPORTER.with_try_import(key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000144 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700145 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000146 KeyType::Client,
147 KeyEntryLoadBits::PUBLIC,
148 caller_uid,
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700149 |k, av| check_key_permission(KeyPerm::GetInfo, k, &av),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000150 )
151 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700152 })
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000153 .context(ks_err!("while trying to load key info."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700154
Janis Danisevskis377d1002021-01-27 19:07:48 -0800155 let i_sec_level = if !key_entry.pure_cert() {
156 Some(
Max Bires8e93d2b2021-01-14 13:17:59 -0800157 self.get_i_sec_level_by_uuid(key_entry.km_uuid())
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000158 .context(ks_err!("Trying to get security level proxy."))?,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800159 )
160 } else {
161 None
162 };
Janis Danisevskis1af91262020-08-10 14:58:08 -0700163
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700164 Ok(KeyEntryResponse {
Janis Danisevskis377d1002021-01-27 19:07:48 -0800165 iSecurityLevel: i_sec_level,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700166 metadata: KeyMetadata {
Janis Danisevskis1af91262020-08-10 14:58:08 -0700167 key: KeyDescriptor {
168 domain: Domain::KEY_ID,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800169 nspace: key_id_guard.id(),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700170 ..Default::default()
171 },
Max Bires8e93d2b2021-01-14 13:17:59 -0800172 keySecurityLevel: self.uuid_to_sec_level(key_entry.km_uuid()),
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700173 certificate: key_entry.take_cert(),
174 certificateChain: key_entry.take_cert_chain(),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800175 modificationTimeMs: key_entry
176 .metadata()
177 .creation_date()
178 .map(|d| d.to_millis_epoch())
179 .ok_or(Error::Rc(ResponseCode::VALUE_CORRUPTED))
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000180 .context(ks_err!("Trying to get creation date."))?,
Janis Danisevskis04b02832020-10-26 09:21:40 -0700181 authorizations: key_parameters_to_authorizations(key_entry.into_key_parameters()),
Janis Danisevskis1af91262020-08-10 14:58:08 -0700182 },
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700183 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700184 }
185
186 fn update_subcomponent(
187 &self,
188 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700189 public_cert: Option<&[u8]>,
190 certificate_chain: Option<&[u8]>,
Janis Danisevskis1af91262020-08-10 14:58:08 -0700191 ) -> Result<()> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000192 let caller_uid = ThreadState::get_calling_uid();
Eric Biggers673d34a2023-10-18 01:54:18 +0000193 let super_key = SUPER_KEY
194 .read()
195 .unwrap()
196 .get_after_first_unlock_key_by_user_id(uid_to_android_user(caller_uid));
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800197
Janis Danisevskis1af91262020-08-10 14:58:08 -0700198 DB.with::<_, Result<()>>(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800199 let entry = match LEGACY_IMPORTER.with_try_import(key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000200 db.borrow_mut().load_key_entry(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700201 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000202 KeyType::Client,
203 KeyEntryLoadBits::NONE,
204 caller_uid,
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000205 |k, av| check_key_permission(KeyPerm::Update, k, &av).context(ks_err!()),
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000206 )
207 }) {
Janis Danisevskis377d1002021-01-27 19:07:48 -0800208 Err(e) => match e.root_cause().downcast_ref::<Error>() {
209 Some(Error::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
210 _ => Err(e),
211 },
212 Ok(v) => Ok(Some(v)),
213 }
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000214 .context(ks_err!("Failed to load key entry."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700215
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000216 let mut db = db.borrow_mut();
Paul Crowleyd5653e52021-03-25 09:46:31 -0700217 if let Some((key_id_guard, _key_entry)) = entry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800218 db.set_blob(&key_id_guard, SubComponentType::CERT, public_cert, None)
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000219 .context(ks_err!("Failed to update cert subcomponent."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -0800220
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800221 db.set_blob(&key_id_guard, SubComponentType::CERT_CHAIN, certificate_chain, None)
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000222 .context(ks_err!("Failed to update cert chain subcomponent."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -0800223 return Ok(());
Janis Danisevskis1af91262020-08-10 14:58:08 -0700224 }
225
Janis Danisevskis377d1002021-01-27 19:07:48 -0800226 // If we reach this point we have to check the special condition where a certificate
227 // entry may be made.
228 if !(public_cert.is_none() && certificate_chain.is_some()) {
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000229 return Err(Error::Rc(ResponseCode::KEY_NOT_FOUND))
230 .context(ks_err!("No key to update."));
Janis Danisevskis1af91262020-08-10 14:58:08 -0700231 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800232
233 // So we know that we have a certificate chain and no public cert.
234 // Now check that we have everything we need to make a new certificate entry.
235 let key = match (key.domain, &key.alias) {
236 (Domain::APP, Some(ref alias)) => KeyDescriptor {
237 domain: Domain::APP,
238 nspace: ThreadState::get_calling_uid() as i64,
239 alias: Some(alias.clone()),
240 blob: None,
241 },
242 (Domain::SELINUX, Some(_)) => key.clone(),
243 _ => {
244 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000245 .context(ks_err!("Domain must be APP or SELINUX to insert a certificate."))
Janis Danisevskis377d1002021-01-27 19:07:48 -0800246 }
247 };
248
249 // Security critical: This must return on failure. Do not remove the `?`;
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700250 check_key_permission(KeyPerm::Rebind, &key, &None)
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000251 .context(ks_err!("Caller does not have permission to insert this certificate."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -0800252
Janis Danisevskis0cabd712021-05-25 11:07:10 -0700253 db.store_new_certificate(
254 &key,
255 KeyType::Client,
256 certificate_chain.unwrap(),
257 &KEYSTORE_UUID,
258 )
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000259 .context(ks_err!("Failed to insert new certificate."))?;
Janis Danisevskis1af91262020-08-10 14:58:08 -0700260 Ok(())
261 })
Shaquille Johnsonaec2eca2022-11-30 17:08:05 +0000262 .context(ks_err!())
Janis Danisevskis1af91262020-08-10 14:58:08 -0700263 }
264
Eran Messeri24f31972023-01-25 17:00:33 +0000265 fn get_key_descriptor_for_lookup(
266 &self,
267 domain: Domain,
268 namespace: i64,
269 ) -> Result<KeyDescriptor> {
Janis Danisevskise92a5e62020-12-02 12:57:41 -0800270 let mut k = match domain {
271 Domain::APP => KeyDescriptor {
272 domain,
273 nspace: ThreadState::get_calling_uid() as u64 as i64,
274 ..Default::default()
275 },
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000276 Domain::SELINUX => KeyDescriptor { domain, nspace: namespace, ..Default::default() },
277 _ => {
278 return Err(Error::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!(
279 "List entries is only supported for Domain::APP and Domain::SELINUX."
280 ))
281 }
Janis Danisevskise92a5e62020-12-02 12:57:41 -0800282 };
283
284 // First we check if the caller has the info permission for the selected domain/namespace.
285 // By default we use the calling uid as namespace if domain is Domain::APP.
286 // If the first check fails we check if the caller has the list permission allowing to list
287 // any namespace. In that case we also adjust the queried namespace if a specific uid was
288 // selected.
Chris Wailes20f50df2022-04-19 17:23:52 -0700289 if let Err(e) = check_key_permission(KeyPerm::GetInfo, &k, &None) {
290 if let Some(selinux::Error::PermissionDenied) =
Rajesh Nyamagoud16198a32022-07-26 18:45:55 +0000291 e.root_cause().downcast_ref::<selinux::Error>()
292 {
Chris Wailes20f50df2022-04-19 17:23:52 -0700293 check_keystore_permission(KeystorePerm::List)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000294 .context(ks_err!("While checking keystore permission."))?;
Chris Wailes20f50df2022-04-19 17:23:52 -0700295 if namespace != -1 {
296 k.nspace = namespace;
Janis Danisevskise92a5e62020-12-02 12:57:41 -0800297 }
Chris Wailes20f50df2022-04-19 17:23:52 -0700298 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000299 return Err(e).context(ks_err!("While checking key permission."))?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -0800300 }
Chris Wailes20f50df2022-04-19 17:23:52 -0700301 }
Eran Messeri24f31972023-01-25 17:00:33 +0000302 Ok(k)
303 }
Janis Danisevskise92a5e62020-12-02 12:57:41 -0800304
Eran Messeri24f31972023-01-25 17:00:33 +0000305 fn list_entries(&self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
306 let k = self.get_key_descriptor_for_lookup(domain, namespace)?;
307
308 DB.with(|db| list_key_entries(&mut db.borrow_mut(), k.domain, k.nspace, None))
309 }
310
311 fn count_num_entries(&self, domain: Domain, namespace: i64) -> Result<i32> {
312 let k = self.get_key_descriptor_for_lookup(domain, namespace)?;
313
314 DB.with(|db| count_key_entries(&mut db.borrow_mut(), k.domain, k.nspace))
315 }
316
317 fn list_entries_batched(
318 &self,
319 domain: Domain,
320 namespace: i64,
321 start_past_alias: Option<&str>,
322 ) -> Result<Vec<KeyDescriptor>> {
323 let k = self.get_key_descriptor_for_lookup(domain, namespace)?;
324 DB.with(|db| list_key_entries(&mut db.borrow_mut(), k.domain, k.nspace, start_past_alias))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700325 }
326
327 fn delete_key(&self, key: &KeyDescriptor) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800328 let caller_uid = ThreadState::get_calling_uid();
Eric Biggers673d34a2023-10-18 01:54:18 +0000329 let super_key = SUPER_KEY
330 .read()
331 .unwrap()
332 .get_after_first_unlock_key_by_user_id(uid_to_android_user(caller_uid));
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800333
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800334 DB.with(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800335 LEGACY_IMPORTER.with_try_import(key, caller_uid, super_key, || {
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700336 db.borrow_mut().unbind_key(key, KeyType::Client, caller_uid, |k, av| {
Shaquille Johnsone8b152a2023-02-09 15:15:50 +0000337 check_key_permission(KeyPerm::Delete, k, &av)
338 .context(ks_err!("During delete_key."))
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000339 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800340 })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800341 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000342 .context(ks_err!("Trying to unbind the key."))?;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -0800343 Ok(())
Janis Danisevskis1af91262020-08-10 14:58:08 -0700344 }
345
346 fn grant(
347 &self,
348 key: &KeyDescriptor,
349 grantee_uid: i32,
350 access_vector: permission::KeyPermSet,
351 ) -> Result<KeyDescriptor> {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000352 let caller_uid = ThreadState::get_calling_uid();
Eric Biggers673d34a2023-10-18 01:54:18 +0000353 let super_key = SUPER_KEY
354 .read()
355 .unwrap()
356 .get_after_first_unlock_key_by_user_id(uid_to_android_user(caller_uid));
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800357
Janis Danisevskis1af91262020-08-10 14:58:08 -0700358 DB.with(|db| {
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800359 LEGACY_IMPORTER.with_try_import(key, caller_uid, super_key, || {
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000360 db.borrow_mut().grant(
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700361 key,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +0000362 caller_uid,
363 grantee_uid as u32,
364 access_vector,
365 |k, av| check_grant_permission(*av, k).context("During grant."),
366 )
367 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700368 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000369 .context(ks_err!("KeystoreService::grant."))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700370 }
371
372 fn ungrant(&self, key: &KeyDescriptor, grantee_uid: i32) -> Result<()> {
373 DB.with(|db| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700374 db.borrow_mut().ungrant(key, ThreadState::get_calling_uid(), grantee_uid as u32, |k| {
Janis Danisevskis39d57e72021-10-19 16:56:20 -0700375 check_key_permission(KeyPerm::Grant, k, &None)
Janis Danisevskis66784c42021-01-27 08:40:25 -0800376 })
Janis Danisevskis1af91262020-08-10 14:58:08 -0700377 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000378 .context(ks_err!("KeystoreService::ungrant."))
Janis Danisevskis1af91262020-08-10 14:58:08 -0700379 }
380}
381
382impl binder::Interface for KeystoreService {}
383
384// Implementation of IKeystoreService. See AIDL spec at
385// system/security/keystore2/binder/android/security/keystore2/IKeystoreService.aidl
386impl IKeystoreService for KeystoreService {
387 fn getSecurityLevel(
388 &self,
Janis Danisevskisa53c9cf2020-10-26 11:52:33 -0700389 security_level: SecurityLevel,
Stephen Crane23cf7242022-01-19 17:49:46 +0000390 ) -> binder::Result<Strong<dyn IKeystoreSecurityLevel>> {
David Drysdale387c85b2024-06-10 14:40:45 +0100391 let _wp = wd::watch_millis_with("IKeystoreService::getSecurityLevel", 500, security_level);
David Drysdaledb7ddde2024-06-07 16:22:49 +0100392 self.get_security_level(security_level).map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700393 }
Stephen Crane23cf7242022-01-19 17:49:46 +0000394 fn getKeyEntry(&self, key: &KeyDescriptor) -> binder::Result<KeyEntryResponse> {
David Drysdale541846b2024-05-23 13:16:07 +0100395 let _wp = wd::watch("IKeystoreService::get_key_entry");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100396 self.get_key_entry(key).map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700397 }
398 fn updateSubcomponent(
399 &self,
400 key: &KeyDescriptor,
Janis Danisevskis2c7f9622020-09-30 16:30:31 -0700401 public_cert: Option<&[u8]>,
402 certificate_chain: Option<&[u8]>,
Stephen Crane23cf7242022-01-19 17:49:46 +0000403 ) -> binder::Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100404 let _wp = wd::watch("IKeystoreService::updateSubcomponent");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100405 self.update_subcomponent(key, public_cert, certificate_chain).map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700406 }
Stephen Crane23cf7242022-01-19 17:49:46 +0000407 fn listEntries(&self, domain: Domain, namespace: i64) -> binder::Result<Vec<KeyDescriptor>> {
David Drysdale541846b2024-05-23 13:16:07 +0100408 let _wp = wd::watch("IKeystoreService::listEntries");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100409 self.list_entries(domain, namespace).map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700410 }
Stephen Crane23cf7242022-01-19 17:49:46 +0000411 fn deleteKey(&self, key: &KeyDescriptor) -> binder::Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100412 let _wp = wd::watch("IKeystoreService::deleteKey");
Pavel Grafov94243c22021-04-21 18:03:11 +0100413 let result = self.delete_key(key);
414 log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
David Drysdaledb7ddde2024-06-07 16:22:49 +0100415 result.map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700416 }
417 fn grant(
418 &self,
419 key: &KeyDescriptor,
420 grantee_uid: i32,
421 access_vector: i32,
Stephen Crane23cf7242022-01-19 17:49:46 +0000422 ) -> binder::Result<KeyDescriptor> {
David Drysdale541846b2024-05-23 13:16:07 +0100423 let _wp = wd::watch("IKeystoreService::grant");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100424 self.grant(key, grantee_uid, access_vector.into()).map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700425 }
Stephen Crane23cf7242022-01-19 17:49:46 +0000426 fn ungrant(&self, key: &KeyDescriptor, grantee_uid: i32) -> binder::Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100427 let _wp = wd::watch("IKeystoreService::ungrant");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100428 self.ungrant(key, grantee_uid).map_err(into_logged_binder)
Janis Danisevskis1af91262020-08-10 14:58:08 -0700429 }
Eran Messeri24f31972023-01-25 17:00:33 +0000430 fn listEntriesBatched(
431 &self,
432 domain: Domain,
433 namespace: i64,
434 start_past_alias: Option<&str>,
435 ) -> binder::Result<Vec<KeyDescriptor>> {
David Drysdale541846b2024-05-23 13:16:07 +0100436 let _wp = wd::watch("IKeystoreService::listEntriesBatched");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100437 self.list_entries_batched(domain, namespace, start_past_alias).map_err(into_logged_binder)
Eran Messeri24f31972023-01-25 17:00:33 +0000438 }
439
440 fn getNumberOfEntries(&self, domain: Domain, namespace: i64) -> binder::Result<i32> {
David Drysdale541846b2024-05-23 13:16:07 +0100441 let _wp = wd::watch("IKeystoreService::getNumberOfEntries");
David Drysdaledb7ddde2024-06-07 16:22:49 +0100442 self.count_num_entries(domain, namespace).map_err(into_logged_binder)
Eran Messeri24f31972023-01-25 17:00:33 +0000443 }
Janis Danisevskis1af91262020-08-10 14:58:08 -0700444}