blob: d4074165ad24ffe5dd40a94f263cc025b712ffd9 [file] [log] [blame]
Janis Danisevskis77d72042021-01-20 15:36:30 -08001// 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 Danisevskis3eb829d2021-06-14 14:18:20 -070015//! Implements the android.security.legacykeystore interface.
Janis Danisevskis77d72042021-01-20 15:36:30 -080016
Janis Danisevskis3eb829d2021-06-14 14:18:20 -070017use android_security_legacykeystore::aidl::android::security::legacykeystore::{
18 ILegacyKeystore::BnLegacyKeystore, ILegacyKeystore::ILegacyKeystore,
19 ILegacyKeystore::ERROR_ENTRY_NOT_FOUND, ILegacyKeystore::ERROR_PERMISSION_DENIED,
20 ILegacyKeystore::ERROR_SYSTEM_ERROR, ILegacyKeystore::UID_SELF,
Janis Danisevskis77d72042021-01-20 15:36:30 -080021};
Janis Danisevskis3eb829d2021-06-14 14:18:20 -070022use android_security_legacykeystore::binder::{
Andrew Walbrande45c8b2021-04-13 14:42:38 +000023 BinderFeatures, ExceptionCode, Result as BinderResult, Status as BinderStatus, Strong,
24 ThreadState,
25};
Seth Moorefbe5cf52021-06-09 15:59:00 -070026use anyhow::{Context, Result};
Janis Danisevskis5898d152021-06-15 08:23:46 -070027use keystore2::{
Janis Danisevskisf84d0b02022-01-26 14:11:14 -080028 async_task::AsyncTask, error::anyhow_error_to_cstring, globals::SUPER_KEY,
29 legacy_blob::LegacyBlobLoader, maintenance::DeleteListener, maintenance::Domain,
30 utils::uid_to_android_user, utils::watchdog as wd,
Janis Danisevskis5898d152021-06-15 08:23:46 -070031};
Andrew Walbran78abb1e2023-05-30 16:20:56 +000032use rusqlite::{params, Connection, OptionalExtension, Transaction, TransactionBehavior};
Janis Danisevskis5898d152021-06-15 08:23:46 -070033use std::sync::Arc;
Janis Danisevskis06891072021-02-11 10:28:17 -080034use std::{
35 collections::HashSet,
36 path::{Path, PathBuf},
37};
Janis Danisevskis77d72042021-01-20 15:36:30 -080038
39struct DB {
40 conn: Connection,
41}
42
43impl DB {
44 fn new(db_file: &Path) -> Result<Self> {
45 let mut db = Self {
46 conn: Connection::open(db_file).context("Failed to initialize SQLite connection.")?,
47 };
Janis Danisevskis1be7e182021-04-12 14:31:12 -070048
Janis Danisevskis3eb829d2021-06-14 14:18:20 -070049 db.init_tables().context("Trying to initialize legacy keystore db.")?;
Janis Danisevskis77d72042021-01-20 15:36:30 -080050 Ok(db)
51 }
52
53 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
54 where
55 F: Fn(&Transaction) -> Result<T>,
56 {
57 loop {
James Farrellefe1a2f2024-02-28 21:36:47 +000058 let result = self
Janis Danisevskis77d72042021-01-20 15:36:30 -080059 .conn
60 .transaction_with_behavior(behavior)
61 .context("In with_transaction.")
62 .and_then(|tx| f(&tx).map(|result| (result, tx)))
63 .and_then(|(result, tx)| {
64 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
65 Ok(result)
James Farrellefe1a2f2024-02-28 21:36:47 +000066 });
67 match result {
Janis Danisevskis77d72042021-01-20 15:36:30 -080068 Ok(result) => break Ok(result),
69 Err(e) => {
70 if Self::is_locked_error(&e) {
71 std::thread::sleep(std::time::Duration::from_micros(500));
72 continue;
73 } else {
74 return Err(e).context("In with_transaction.");
75 }
76 }
77 }
78 }
79 }
80
81 fn is_locked_error(e: &anyhow::Error) -> bool {
Janis Danisevskis13f09152021-04-19 09:55:15 -070082 matches!(
83 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
84 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
85 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
86 )
Janis Danisevskis77d72042021-01-20 15:36:30 -080087 }
88
89 fn init_tables(&mut self) -> Result<()> {
90 self.with_transaction(TransactionBehavior::Immediate, |tx| {
91 tx.execute(
92 "CREATE TABLE IF NOT EXISTS profiles (
93 owner INTEGER,
94 alias BLOB,
95 profile BLOB,
96 UNIQUE(owner, alias));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +000097 [],
Janis Danisevskis77d72042021-01-20 15:36:30 -080098 )
99 .context("Failed to initialize \"profiles\" table.")?;
100 Ok(())
101 })
102 }
103
104 fn list(&mut self, caller_uid: u32) -> Result<Vec<String>> {
105 self.with_transaction(TransactionBehavior::Deferred, |tx| {
106 let mut stmt = tx
107 .prepare("SELECT alias FROM profiles WHERE owner = ? ORDER BY alias ASC;")
108 .context("In list: Failed to prepare statement.")?;
109
Chris Wailes263de9f2022-08-11 15:00:51 -0700110 // This allow is necessary to avoid the following error:
111 //
112 // error[E0597]: `stmt` does not live long enough
113 //
114 // See: https://github.com/rust-lang/rust-clippy/issues/8114
115 #[allow(clippy::let_and_return)]
Janis Danisevskis77d72042021-01-20 15:36:30 -0800116 let aliases = stmt
117 .query_map(params![caller_uid], |row| row.get(0))?
118 .collect::<rusqlite::Result<Vec<String>>>()
119 .context("In list: query_map failed.");
120 aliases
121 })
122 }
123
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700124 fn put(&mut self, caller_uid: u32, alias: &str, entry: &[u8]) -> Result<()> {
Shaquille Johnsonf015af12023-11-30 15:22:19 +0000125 ensure_keystore_put_is_enabled()?;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800126 self.with_transaction(TransactionBehavior::Immediate, |tx| {
127 tx.execute(
128 "INSERT OR REPLACE INTO profiles (owner, alias, profile) values (?, ?, ?)",
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700129 params![caller_uid, alias, entry,],
Janis Danisevskis77d72042021-01-20 15:36:30 -0800130 )
131 .context("In put: Failed to insert or replace.")?;
132 Ok(())
133 })
134 }
135
136 fn get(&mut self, caller_uid: u32, alias: &str) -> Result<Option<Vec<u8>>> {
137 self.with_transaction(TransactionBehavior::Deferred, |tx| {
138 tx.query_row(
139 "SELECT profile FROM profiles WHERE owner = ? AND alias = ?;",
140 params![caller_uid, alias],
141 |row| row.get(0),
142 )
143 .optional()
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700144 .context("In get: failed loading entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800145 })
146 }
147
148 fn remove(&mut self, caller_uid: u32, alias: &str) -> Result<bool> {
149 let removed = self.with_transaction(TransactionBehavior::Immediate, |tx| {
150 tx.execute(
151 "DELETE FROM profiles WHERE owner = ? AND alias = ?;",
152 params![caller_uid, alias],
153 )
154 .context("In remove: Failed to delete row.")
155 })?;
156 Ok(removed == 1)
157 }
Janis Danisevskis5898d152021-06-15 08:23:46 -0700158
159 fn remove_uid(&mut self, uid: u32) -> Result<()> {
160 self.with_transaction(TransactionBehavior::Immediate, |tx| {
161 tx.execute("DELETE FROM profiles WHERE owner = ?;", params![uid])
162 .context("In remove_uid: Failed to delete.")
163 })?;
164 Ok(())
165 }
166
167 fn remove_user(&mut self, user_id: u32) -> Result<()> {
168 self.with_transaction(TransactionBehavior::Immediate, |tx| {
169 tx.execute(
170 "DELETE FROM profiles WHERE cast ( ( owner/? ) as int) = ?;",
Joel Galenson81a50f22021-07-29 15:39:10 -0700171 params![rustutils::users::AID_USER_OFFSET, user_id],
Janis Danisevskis5898d152021-06-15 08:23:46 -0700172 )
173 .context("In remove_uid: Failed to delete.")
174 })?;
175 Ok(())
176 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800177}
178
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700179/// This is the main LegacyKeystore error type, it wraps binder exceptions and the
180/// LegacyKeystore errors.
Chris Wailes263de9f2022-08-11 15:00:51 -0700181#[derive(Debug, thiserror::Error, PartialEq, Eq)]
Janis Danisevskis77d72042021-01-20 15:36:30 -0800182pub enum Error {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700183 /// Wraps a LegacyKeystore error code.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800184 #[error("Error::Error({0:?})")]
185 Error(i32),
186 /// Wraps a Binder exception code other than a service specific exception.
187 #[error("Binder exception code {0:?}, {1:?}")]
188 Binder(ExceptionCode, i32),
189}
190
191impl Error {
192 /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)`
193 pub fn sys() -> Self {
194 Error::Error(ERROR_SYSTEM_ERROR)
195 }
196
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700197 /// Short hand for `Error::Error(ERROR_ENTRY_NOT_FOUND)`
Janis Danisevskis77d72042021-01-20 15:36:30 -0800198 pub fn not_found() -> Self {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700199 Error::Error(ERROR_ENTRY_NOT_FOUND)
200 }
201
202 /// Short hand for `Error::Error(ERROR_PERMISSION_DENIED)`
203 pub fn perm() -> Self {
204 Error::Error(ERROR_PERMISSION_DENIED)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800205 }
Shaquille Johnsonbe6e91d2023-10-21 19:09:17 +0100206
207 /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)`
208 pub fn deprecated() -> Self {
209 Error::Error(ERROR_SYSTEM_ERROR)
210 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800211}
212
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700213/// This function should be used by legacykeystore service calls to translate error conditions
Janis Danisevskis77d72042021-01-20 15:36:30 -0800214/// into service specific exceptions.
215///
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700216/// All error conditions get logged by this function, except for ERROR_ENTRY_NOT_FOUND error.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800217///
218/// `Error::Error(x)` variants get mapped onto a service specific error code of `x`.
219///
220/// All non `Error` error conditions get mapped onto `ERROR_SYSTEM_ERROR`.
221///
222/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
223/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
224/// typically returns Ok(value).
225fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
226where
227 F: FnOnce(U) -> BinderResult<T>,
228{
229 result.map_or_else(
230 |e| {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800231 let root_cause = e.root_cause();
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000232 let (rc, log_error) = match root_cause.downcast_ref::<Error>() {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700233 // Make the entry not found errors silent.
234 Some(Error::Error(ERROR_ENTRY_NOT_FOUND)) => (ERROR_ENTRY_NOT_FOUND, false),
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000235 Some(Error::Error(e)) => (*e, true),
236 Some(Error::Binder(_, _)) | None => (ERROR_SYSTEM_ERROR, true),
Janis Danisevskis77d72042021-01-20 15:36:30 -0800237 };
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000238 if log_error {
239 log::error!("{:?}", e);
240 }
Janis Danisevskisea03cff2021-12-16 08:10:17 -0800241 Err(BinderStatus::new_service_specific_error(
242 rc,
243 anyhow_error_to_cstring(&e).as_deref(),
244 ))
Janis Danisevskis77d72042021-01-20 15:36:30 -0800245 },
246 handle_ok,
247 )
248}
249
Shaquille Johnsonf015af12023-11-30 15:22:19 +0000250fn ensure_keystore_put_is_enabled() -> Result<()> {
251 if keystore2_flags::disable_legacy_keystore_put_v2() {
252 Err(Error::deprecated()).context(concat!(
253 "Storing into Keystore's legacy database is ",
254 "no longer supported, store in an app-specific database instead"
255 ))
256 } else {
257 Ok(())
258 }
259}
260
Janis Danisevskis5898d152021-06-15 08:23:46 -0700261struct LegacyKeystoreDeleteListener {
262 legacy_keystore: Arc<LegacyKeystore>,
263}
264
265impl DeleteListener for LegacyKeystoreDeleteListener {
266 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()> {
267 self.legacy_keystore.delete_namespace(domain, namespace)
268 }
269 fn delete_user(&self, user_id: u32) -> Result<()> {
270 self.legacy_keystore.delete_user(user_id)
271 }
272}
273
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700274/// Implements ILegacyKeystore AIDL interface.
275pub struct LegacyKeystore {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800276 db_path: PathBuf,
Janis Danisevskis06891072021-02-11 10:28:17 -0800277 async_task: AsyncTask,
278}
279
280struct AsyncState {
281 recently_imported: HashSet<(u32, String)>,
282 legacy_loader: LegacyBlobLoader,
283 db_path: PathBuf,
Janis Danisevskis77d72042021-01-20 15:36:30 -0800284}
285
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700286impl LegacyKeystore {
287 /// Note: The filename was chosen before the purpose of this module was extended.
288 /// It is kept for backward compatibility with early adopters.
289 const LEGACY_KEYSTORE_FILE_NAME: &'static str = "vpnprofilestore.sqlite";
290
Janis Danisevskis5898d152021-06-15 08:23:46 -0700291 const WIFI_NAMESPACE: i64 = 102;
292 const AID_WIFI: u32 = 1010;
293
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700294 /// Creates a new LegacyKeystore instance.
Janis Danisevskis5898d152021-06-15 08:23:46 -0700295 pub fn new_native_binder(
296 path: &Path,
297 ) -> (Box<dyn DeleteListener + Send + Sync + 'static>, Strong<dyn ILegacyKeystore>) {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800298 let mut db_path = path.to_path_buf();
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700299 db_path.push(Self::LEGACY_KEYSTORE_FILE_NAME);
Janis Danisevskis06891072021-02-11 10:28:17 -0800300
Janis Danisevskis5898d152021-06-15 08:23:46 -0700301 let legacy_keystore = Arc::new(Self { db_path, async_task: Default::default() });
302 legacy_keystore.init_shelf(path);
303 let service = LegacyKeystoreService { legacy_keystore: legacy_keystore.clone() };
304 (
305 Box::new(LegacyKeystoreDeleteListener { legacy_keystore }),
306 BnLegacyKeystore::new_binder(service, BinderFeatures::default()),
307 )
Janis Danisevskis77d72042021-01-20 15:36:30 -0800308 }
309
310 fn open_db(&self) -> Result<DB> {
311 DB::new(&self.db_path).context("In open_db: Failed to open db.")
312 }
313
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700314 fn get_effective_uid(uid: i32) -> Result<u32> {
315 const AID_SYSTEM: u32 = 1000;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800316 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700317 let uid = uid as u32;
Janis Danisevskis06891072021-02-11 10:28:17 -0800318
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700319 if uid == UID_SELF as u32 || uid == calling_uid {
320 Ok(calling_uid)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700321 } else if calling_uid == AID_SYSTEM && uid == Self::AID_WIFI {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700322 // The only exception for legacy reasons is allowing SYSTEM to access
323 // the WIFI namespace.
324 // IMPORTANT: If you attempt to add more exceptions, it means you are adding
325 // more callers to this deprecated feature. DON'T!
Janis Danisevskis5898d152021-06-15 08:23:46 -0700326 Ok(Self::AID_WIFI)
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700327 } else {
328 Err(Error::perm()).with_context(|| {
329 format!("In get_effective_uid: caller: {}, requested uid: {}.", calling_uid, uid)
330 })
Janis Danisevskis06891072021-02-11 10:28:17 -0800331 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700332 }
333
334 fn get(&self, alias: &str, uid: i32) -> Result<Vec<u8>> {
335 let mut db = self.open_db().context("In get.")?;
336 let uid = Self::get_effective_uid(uid).context("In get.")?;
337
338 if let Some(entry) = db.get(uid, alias).context("In get: Trying to load entry from DB.")? {
339 return Ok(entry);
340 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800341 if self.get_legacy(uid, alias).context("In get: Trying to import legacy blob.")? {
342 // If we were able to import a legacy blob try again.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700343 if let Some(entry) =
344 db.get(uid, alias).context("In get: Trying to load entry from DB.")?
Janis Danisevskis06891072021-02-11 10:28:17 -0800345 {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700346 return Ok(entry);
Janis Danisevskis06891072021-02-11 10:28:17 -0800347 }
348 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700349 Err(Error::not_found()).context("In get: No such entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800350 }
351
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700352 fn put(&self, alias: &str, uid: i32, entry: &[u8]) -> Result<()> {
Shaquille Johnsonf015af12023-11-30 15:22:19 +0000353 ensure_keystore_put_is_enabled()?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700354 let uid = Self::get_effective_uid(uid).context("In put.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800355 let mut db = self.open_db().context("In put.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800356 db.put(uid, alias, entry).context("In put: Trying to insert entry into DB.")?;
357 // When replacing an entry, make sure that there is no stale legacy file entry.
358 let _ = self.remove_legacy(uid, alias);
359 Ok(())
Janis Danisevskis77d72042021-01-20 15:36:30 -0800360 }
361
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700362 fn remove(&self, alias: &str, uid: i32) -> Result<()> {
363 let uid = Self::get_effective_uid(uid).context("In remove.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800364 let mut db = self.open_db().context("In remove.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800365
366 if self.remove_legacy(uid, alias).context("In remove: trying to remove legacy entry")? {
367 return Ok(());
368 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700369 let removed =
370 db.remove(uid, alias).context("In remove: Trying to remove entry from DB.")?;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800371 if removed {
372 Ok(())
373 } else {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700374 Err(Error::not_found()).context("In remove: No such entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800375 }
376 }
377
Janis Danisevskis5898d152021-06-15 08:23:46 -0700378 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()> {
379 let uid = match domain {
380 Domain::APP => namespace as u32,
381 Domain::SELINUX => {
382 if namespace == Self::WIFI_NAMESPACE {
383 // Namespace WIFI gets mapped to AID_WIFI.
384 Self::AID_WIFI
385 } else {
386 // Nothing to do for any other namespace.
387 return Ok(());
388 }
389 }
390 _ => return Ok(()),
391 };
392
393 if let Err(e) = self.bulk_delete_uid(uid) {
394 log::warn!("In LegacyKeystore::delete_namespace: {:?}", e);
395 }
396 let mut db = self.open_db().context("In LegacyKeystore::delete_namespace.")?;
397 db.remove_uid(uid).context("In LegacyKeystore::delete_namespace.")
398 }
399
400 fn delete_user(&self, user_id: u32) -> Result<()> {
401 if let Err(e) = self.bulk_delete_user(user_id) {
402 log::warn!("In LegacyKeystore::delete_user: {:?}", e);
403 }
404 let mut db = self.open_db().context("In LegacyKeystore::delete_user.")?;
405 db.remove_user(user_id).context("In LegacyKeystore::delete_user.")
406 }
407
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700408 fn list(&self, prefix: &str, uid: i32) -> Result<Vec<String>> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800409 let mut db = self.open_db().context("In list.")?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700410 let uid = Self::get_effective_uid(uid).context("In list.")?;
411 let mut result = self.list_legacy(uid).context("In list.")?;
412 result.append(&mut db.list(uid).context("In list: Trying to get list of entries.")?);
Charisee28e6f0b2022-09-15 01:07:46 +0000413 result.retain(|s| s.starts_with(prefix));
Janis Danisevskis06891072021-02-11 10:28:17 -0800414 result.sort_unstable();
415 result.dedup();
416 Ok(result)
417 }
418
419 fn init_shelf(&self, path: &Path) {
420 let mut db_path = path.to_path_buf();
421 self.async_task.queue_hi(move |shelf| {
422 let legacy_loader = LegacyBlobLoader::new(&db_path);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700423 db_path.push(Self::LEGACY_KEYSTORE_FILE_NAME);
Janis Danisevskis06891072021-02-11 10:28:17 -0800424
425 shelf.put(AsyncState { legacy_loader, db_path, recently_imported: Default::default() });
426 })
427 }
428
429 fn do_serialized<F, T: Send + 'static>(&self, f: F) -> Result<T>
430 where
431 F: FnOnce(&mut AsyncState) -> Result<T> + Send + 'static,
432 {
433 let (sender, receiver) = std::sync::mpsc::channel::<Result<T>>();
434 self.async_task.queue_hi(move |shelf| {
435 let state = shelf.get_downcast_mut::<AsyncState>().expect("Failed to get shelf.");
436 sender.send(f(state)).expect("Failed to send result.");
437 });
438 receiver.recv().context("In do_serialized: Failed to receive result.")?
439 }
440
441 fn list_legacy(&self, uid: u32) -> Result<Vec<String>> {
442 self.do_serialized(move |state| {
443 state
444 .legacy_loader
Janis Danisevskis5898d152021-06-15 08:23:46 -0700445 .list_legacy_keystore_entries_for_uid(uid)
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700446 .context("Trying to list legacy keystore entries.")
Janis Danisevskis06891072021-02-11 10:28:17 -0800447 })
448 .context("In list_legacy.")
449 }
450
451 fn get_legacy(&self, uid: u32, alias: &str) -> Result<bool> {
452 let alias = alias.to_string();
453 self.do_serialized(move |state| {
454 if state.recently_imported.contains(&(uid, alias.clone())) {
455 return Ok(true);
456 }
457 let mut db = DB::new(&state.db_path).context("In open_db: Failed to open db.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800458 let imported =
459 Self::import_one_legacy_entry(uid, &alias, &state.legacy_loader, &mut db)
460 .context("Trying to import legacy keystore entries.")?;
461 if imported {
Janis Danisevskis06891072021-02-11 10:28:17 -0800462 state.recently_imported.insert((uid, alias));
463 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800464 Ok(imported)
Janis Danisevskis06891072021-02-11 10:28:17 -0800465 })
466 .context("In get_legacy.")
467 }
468
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800469 fn remove_legacy(&self, uid: u32, alias: &str) -> Result<bool> {
470 let alias = alias.to_string();
471 self.do_serialized(move |state| {
472 if state.recently_imported.contains(&(uid, alias.clone())) {
473 return Ok(false);
474 }
475 state
476 .legacy_loader
477 .remove_legacy_keystore_entry(uid, &alias)
478 .context("Trying to remove legacy entry.")
479 })
480 }
481
Janis Danisevskis5898d152021-06-15 08:23:46 -0700482 fn bulk_delete_uid(&self, uid: u32) -> Result<()> {
483 self.do_serialized(move |state| {
484 let entries = state
485 .legacy_loader
486 .list_legacy_keystore_entries_for_uid(uid)
487 .context("In bulk_delete_uid: Trying to list entries.")?;
488 for alias in entries.iter() {
489 if let Err(e) = state.legacy_loader.remove_legacy_keystore_entry(uid, alias) {
490 log::warn!("In bulk_delete_uid: Failed to delete legacy entry. {:?}", e);
491 }
492 }
493 Ok(())
494 })
495 }
496
497 fn bulk_delete_user(&self, user_id: u32) -> Result<()> {
498 self.do_serialized(move |state| {
499 let entries = state
500 .legacy_loader
501 .list_legacy_keystore_entries_for_user(user_id)
502 .context("In bulk_delete_user: Trying to list entries.")?;
503 for (uid, entries) in entries.iter() {
504 for alias in entries.iter() {
505 if let Err(e) = state.legacy_loader.remove_legacy_keystore_entry(*uid, alias) {
506 log::warn!("In bulk_delete_user: Failed to delete legacy entry. {:?}", e);
507 }
508 }
509 }
510 Ok(())
511 })
512 }
513
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800514 fn import_one_legacy_entry(
Janis Danisevskis06891072021-02-11 10:28:17 -0800515 uid: u32,
516 alias: &str,
517 legacy_loader: &LegacyBlobLoader,
518 db: &mut DB,
519 ) -> Result<bool> {
520 let blob = legacy_loader
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800521 .read_legacy_keystore_entry(uid, alias, |ciphertext, iv, tag, _salt, _key_size| {
Eric Biggers673d34a2023-10-18 01:54:18 +0000522 if let Some(key) = SUPER_KEY
523 .read()
524 .unwrap()
525 .get_after_first_unlock_key_by_user_id(uid_to_android_user(uid))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800526 {
527 key.decrypt(ciphertext, iv, tag)
528 } else {
529 Err(Error::sys()).context("No key found for user. Device may be locked.")
530 }
531 })
532 .context("In import_one_legacy_entry: Trying to read legacy keystore entry.")?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700533 if let Some(entry) = blob {
534 db.put(uid, alias, &entry)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800535 .context("In import_one_legacy_entry: Trying to insert entry into DB.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800536 legacy_loader
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700537 .remove_legacy_keystore_entry(uid, alias)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800538 .context("In import_one_legacy_entry: Trying to delete legacy keystore entry.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800539 Ok(true)
540 } else {
541 Ok(false)
542 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800543 }
544}
545
Janis Danisevskis5898d152021-06-15 08:23:46 -0700546struct LegacyKeystoreService {
547 legacy_keystore: Arc<LegacyKeystore>,
548}
Janis Danisevskis77d72042021-01-20 15:36:30 -0800549
Janis Danisevskis5898d152021-06-15 08:23:46 -0700550impl binder::Interface for LegacyKeystoreService {}
551
552impl ILegacyKeystore for LegacyKeystoreService {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700553 fn get(&self, alias: &str, uid: i32) -> BinderResult<Vec<u8>> {
David Drysdale541846b2024-05-23 13:16:07 +0100554 let _wp = wd::watch("ILegacyKeystore::get");
Janis Danisevskis5898d152021-06-15 08:23:46 -0700555 map_or_log_err(self.legacy_keystore.get(alias, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800556 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700557 fn put(&self, alias: &str, uid: i32, entry: &[u8]) -> BinderResult<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100558 let _wp = wd::watch("ILegacyKeystore::put");
Janis Danisevskis5898d152021-06-15 08:23:46 -0700559 map_or_log_err(self.legacy_keystore.put(alias, uid, entry), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800560 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700561 fn remove(&self, alias: &str, uid: i32) -> BinderResult<()> {
David Drysdale541846b2024-05-23 13:16:07 +0100562 let _wp = wd::watch("ILegacyKeystore::remove");
Janis Danisevskis5898d152021-06-15 08:23:46 -0700563 map_or_log_err(self.legacy_keystore.remove(alias, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800564 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700565 fn list(&self, prefix: &str, uid: i32) -> BinderResult<Vec<String>> {
David Drysdale541846b2024-05-23 13:16:07 +0100566 let _wp = wd::watch("ILegacyKeystore::list");
Janis Danisevskis5898d152021-06-15 08:23:46 -0700567 map_or_log_err(self.legacy_keystore.list(prefix, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800568 }
569}
570
571#[cfg(test)]
572mod db_test {
573 use super::*;
574 use keystore2_test_utils::TempDir;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700575 use std::sync::Arc;
576 use std::thread;
577 use std::time::Duration;
578 use std::time::Instant;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800579
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700580 static TEST_ALIAS: &str = "test_alias";
Janis Danisevskis77d72042021-01-20 15:36:30 -0800581 static TEST_BLOB1: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
582 static TEST_BLOB2: &[u8] = &[2, 2, 3, 4, 5, 6, 7, 8, 9, 0];
583 static TEST_BLOB3: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
584 static TEST_BLOB4: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
585
586 #[test]
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700587 fn test_entry_db() {
588 let test_dir = TempDir::new("entrydb_test_").expect("Failed to create temp dir.");
589 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
590 .expect("Failed to open database.");
Janis Danisevskis77d72042021-01-20 15:36:30 -0800591
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700592 // Insert three entries for owner 2.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800593 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
594 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
595 db.put(2, "test3", TEST_BLOB3).expect("Failed to insert test3.");
596
597 // Check list returns all inserted aliases.
598 assert_eq!(
599 vec!["test1".to_string(), "test2".to_string(), "test3".to_string(),],
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700600 db.list(2).expect("Failed to list entries.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800601 );
602
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700603 // There should be no entries for owner 1.
604 assert_eq!(Vec::<String>::new(), db.list(1).expect("Failed to list entries."));
Janis Danisevskis77d72042021-01-20 15:36:30 -0800605
606 // Check the content of the three entries.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700607 assert_eq!(Some(TEST_BLOB1), db.get(2, "test1").expect("Failed to get entry.").as_deref());
608 assert_eq!(Some(TEST_BLOB2), db.get(2, "test2").expect("Failed to get entry.").as_deref());
609 assert_eq!(Some(TEST_BLOB3), db.get(2, "test3").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800610
611 // Remove test2 and check and check that it is no longer retrievable.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700612 assert!(db.remove(2, "test2").expect("Failed to remove entry."));
613 assert!(db.get(2, "test2").expect("Failed to get entry.").is_none());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800614
615 // test2 should now no longer be in the list.
616 assert_eq!(
617 vec!["test1".to_string(), "test3".to_string(),],
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700618 db.list(2).expect("Failed to list entries.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800619 );
620
621 // Put on existing alias replaces it.
622 // Verify test1 is TEST_BLOB1.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700623 assert_eq!(Some(TEST_BLOB1), db.get(2, "test1").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800624 db.put(2, "test1", TEST_BLOB4).expect("Failed to replace test1.");
625 // Verify test1 is TEST_BLOB4.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700626 assert_eq!(Some(TEST_BLOB4), db.get(2, "test1").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800627 }
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700628
629 #[test]
Janis Danisevskis5898d152021-06-15 08:23:46 -0700630 fn test_delete_uid() {
631 let test_dir = TempDir::new("test_delete_uid_").expect("Failed to create temp dir.");
632 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
633 .expect("Failed to open database.");
634
635 // Insert three entries for owner 2.
636 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
637 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
638 db.put(3, "test3", TEST_BLOB3).expect("Failed to insert test3.");
639
640 db.remove_uid(2).expect("Failed to remove uid 2");
641
642 assert_eq!(Vec::<String>::new(), db.list(2).expect("Failed to list entries."));
643
644 assert_eq!(vec!["test3".to_string(),], db.list(3).expect("Failed to list entries."));
645 }
646
647 #[test]
648 fn test_delete_user() {
649 let test_dir = TempDir::new("test_delete_user_").expect("Failed to create temp dir.");
650 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
651 .expect("Failed to open database.");
652
653 // Insert three entries for owner 2.
Joel Galenson81a50f22021-07-29 15:39:10 -0700654 db.put(2 + 2 * rustutils::users::AID_USER_OFFSET, "test1", TEST_BLOB1)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700655 .expect("Failed to insert test1.");
Joel Galenson81a50f22021-07-29 15:39:10 -0700656 db.put(4 + 2 * rustutils::users::AID_USER_OFFSET, "test2", TEST_BLOB2)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700657 .expect("Failed to insert test2.");
658 db.put(3, "test3", TEST_BLOB3).expect("Failed to insert test3.");
659
660 db.remove_user(2).expect("Failed to remove user 2");
661
662 assert_eq!(
663 Vec::<String>::new(),
Joel Galenson81a50f22021-07-29 15:39:10 -0700664 db.list(2 + 2 * rustutils::users::AID_USER_OFFSET).expect("Failed to list entries.")
Janis Danisevskis5898d152021-06-15 08:23:46 -0700665 );
666
667 assert_eq!(
668 Vec::<String>::new(),
Joel Galenson81a50f22021-07-29 15:39:10 -0700669 db.list(4 + 2 * rustutils::users::AID_USER_OFFSET).expect("Failed to list entries.")
Janis Danisevskis5898d152021-06-15 08:23:46 -0700670 );
671
672 assert_eq!(vec!["test3".to_string(),], db.list(3).expect("Failed to list entries."));
673 }
674
675 #[test]
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700676 fn concurrent_legacy_keystore_entry_test() -> Result<()> {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700677 let temp_dir = Arc::new(
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700678 TempDir::new("concurrent_legacy_keystore_entry_test_")
679 .expect("Failed to create temp dir."),
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700680 );
681
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700682 let db_path = temp_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME).to_owned();
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700683
684 let test_begin = Instant::now();
685
686 let mut db = DB::new(&db_path).expect("Failed to open database.");
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700687 const ENTRY_COUNT: u32 = 5000u32;
688 const ENTRY_DB_COUNT: u32 = 5000u32;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700689
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700690 let mut actual_entry_count = ENTRY_COUNT;
691 // First insert ENTRY_COUNT entries.
692 for count in 0..ENTRY_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700693 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700694 actual_entry_count = count;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700695 break;
696 }
697 let alias = format!("test_alias_{}", count);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700698 db.put(1, &alias, TEST_BLOB1).expect("Failed to add entry (1).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700699 }
700
701 // Insert more keys from a different thread and into a different namespace.
702 let db_path1 = db_path.clone();
703 let handle1 = thread::spawn(move || {
704 let mut db = DB::new(&db_path1).expect("Failed to open database.");
705
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700706 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700707 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
708 return;
709 }
710 let alias = format!("test_alias_{}", count);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700711 db.put(2, &alias, TEST_BLOB2).expect("Failed to add entry (2).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700712 }
713
714 // Then delete them again.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700715 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700716 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
717 return;
718 }
719 let alias = format!("test_alias_{}", count);
720 db.remove(2, &alias).expect("Remove Failed (2).");
721 }
722 });
723
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700724 // And start deleting the first set of entries.
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700725 let db_path2 = db_path.clone();
726 let handle2 = thread::spawn(move || {
727 let mut db = DB::new(&db_path2).expect("Failed to open database.");
728
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700729 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700730 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
731 return;
732 }
733 let alias = format!("test_alias_{}", count);
734 db.remove(1, &alias).expect("Remove Failed (1)).");
735 }
736 });
737
738 // While a lot of inserting and deleting is going on we have to open database connections
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700739 // successfully and then insert and delete a specific entry.
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700740 let db_path3 = db_path.clone();
741 let handle3 = thread::spawn(move || {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700742 for _count in 0..ENTRY_DB_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700743 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
744 return;
745 }
746 let mut db = DB::new(&db_path3).expect("Failed to open database.");
747
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700748 db.put(3, TEST_ALIAS, TEST_BLOB3).expect("Failed to add entry (3).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700749
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700750 db.remove(3, TEST_ALIAS).expect("Remove failed (3).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700751 }
752 });
753
754 // While thread 3 is inserting and deleting TEST_ALIAS, we try to get the alias.
755 // This may yield an entry or none, but it must not fail.
756 let handle4 = thread::spawn(move || {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700757 for _count in 0..ENTRY_DB_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700758 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
759 return;
760 }
761 let mut db = DB::new(&db_path).expect("Failed to open database.");
762
763 // This may return Some or None but it must not fail.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700764 db.get(3, TEST_ALIAS).expect("Failed to get entry (4).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700765 }
766 });
767
768 handle1.join().expect("Thread 1 panicked.");
769 handle2.join().expect("Thread 2 panicked.");
770 handle3.join().expect("Thread 3 panicked.");
771 handle4.join().expect("Thread 4 panicked.");
772
773 Ok(())
774 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800775}