blob: f7a8198306d6021cd4a773ef9a4959fccfb51278 [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 {
58 match self
59 .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)
66 }) {
67 Ok(result) => break Ok(result),
68 Err(e) => {
69 if Self::is_locked_error(&e) {
70 std::thread::sleep(std::time::Duration::from_micros(500));
71 continue;
72 } else {
73 return Err(e).context("In with_transaction.");
74 }
75 }
76 }
77 }
78 }
79
80 fn is_locked_error(e: &anyhow::Error) -> bool {
Janis Danisevskis13f09152021-04-19 09:55:15 -070081 matches!(
82 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
83 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
84 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
85 )
Janis Danisevskis77d72042021-01-20 15:36:30 -080086 }
87
88 fn init_tables(&mut self) -> Result<()> {
89 self.with_transaction(TransactionBehavior::Immediate, |tx| {
90 tx.execute(
91 "CREATE TABLE IF NOT EXISTS profiles (
92 owner INTEGER,
93 alias BLOB,
94 profile BLOB,
95 UNIQUE(owner, alias));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +000096 [],
Janis Danisevskis77d72042021-01-20 15:36:30 -080097 )
98 .context("Failed to initialize \"profiles\" table.")?;
99 Ok(())
100 })
101 }
102
103 fn list(&mut self, caller_uid: u32) -> Result<Vec<String>> {
104 self.with_transaction(TransactionBehavior::Deferred, |tx| {
105 let mut stmt = tx
106 .prepare("SELECT alias FROM profiles WHERE owner = ? ORDER BY alias ASC;")
107 .context("In list: Failed to prepare statement.")?;
108
Chris Wailes263de9f2022-08-11 15:00:51 -0700109 // This allow is necessary to avoid the following error:
110 //
111 // error[E0597]: `stmt` does not live long enough
112 //
113 // See: https://github.com/rust-lang/rust-clippy/issues/8114
114 #[allow(clippy::let_and_return)]
Janis Danisevskis77d72042021-01-20 15:36:30 -0800115 let aliases = stmt
116 .query_map(params![caller_uid], |row| row.get(0))?
117 .collect::<rusqlite::Result<Vec<String>>>()
118 .context("In list: query_map failed.");
119 aliases
120 })
121 }
122
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700123 fn put(&mut self, caller_uid: u32, alias: &str, entry: &[u8]) -> Result<()> {
Shaquille Johnsonf015af12023-11-30 15:22:19 +0000124 ensure_keystore_put_is_enabled()?;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800125 self.with_transaction(TransactionBehavior::Immediate, |tx| {
126 tx.execute(
127 "INSERT OR REPLACE INTO profiles (owner, alias, profile) values (?, ?, ?)",
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700128 params![caller_uid, alias, entry,],
Janis Danisevskis77d72042021-01-20 15:36:30 -0800129 )
130 .context("In put: Failed to insert or replace.")?;
131 Ok(())
132 })
133 }
134
135 fn get(&mut self, caller_uid: u32, alias: &str) -> Result<Option<Vec<u8>>> {
136 self.with_transaction(TransactionBehavior::Deferred, |tx| {
137 tx.query_row(
138 "SELECT profile FROM profiles WHERE owner = ? AND alias = ?;",
139 params![caller_uid, alias],
140 |row| row.get(0),
141 )
142 .optional()
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700143 .context("In get: failed loading entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800144 })
145 }
146
147 fn remove(&mut self, caller_uid: u32, alias: &str) -> Result<bool> {
148 let removed = self.with_transaction(TransactionBehavior::Immediate, |tx| {
149 tx.execute(
150 "DELETE FROM profiles WHERE owner = ? AND alias = ?;",
151 params![caller_uid, alias],
152 )
153 .context("In remove: Failed to delete row.")
154 })?;
155 Ok(removed == 1)
156 }
Janis Danisevskis5898d152021-06-15 08:23:46 -0700157
158 fn remove_uid(&mut self, uid: u32) -> Result<()> {
159 self.with_transaction(TransactionBehavior::Immediate, |tx| {
160 tx.execute("DELETE FROM profiles WHERE owner = ?;", params![uid])
161 .context("In remove_uid: Failed to delete.")
162 })?;
163 Ok(())
164 }
165
166 fn remove_user(&mut self, user_id: u32) -> Result<()> {
167 self.with_transaction(TransactionBehavior::Immediate, |tx| {
168 tx.execute(
169 "DELETE FROM profiles WHERE cast ( ( owner/? ) as int) = ?;",
Joel Galenson81a50f22021-07-29 15:39:10 -0700170 params![rustutils::users::AID_USER_OFFSET, user_id],
Janis Danisevskis5898d152021-06-15 08:23:46 -0700171 )
172 .context("In remove_uid: Failed to delete.")
173 })?;
174 Ok(())
175 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800176}
177
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700178/// This is the main LegacyKeystore error type, it wraps binder exceptions and the
179/// LegacyKeystore errors.
Chris Wailes263de9f2022-08-11 15:00:51 -0700180#[derive(Debug, thiserror::Error, PartialEq, Eq)]
Janis Danisevskis77d72042021-01-20 15:36:30 -0800181pub enum Error {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700182 /// Wraps a LegacyKeystore error code.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800183 #[error("Error::Error({0:?})")]
184 Error(i32),
185 /// Wraps a Binder exception code other than a service specific exception.
186 #[error("Binder exception code {0:?}, {1:?}")]
187 Binder(ExceptionCode, i32),
188}
189
190impl Error {
191 /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)`
192 pub fn sys() -> Self {
193 Error::Error(ERROR_SYSTEM_ERROR)
194 }
195
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700196 /// Short hand for `Error::Error(ERROR_ENTRY_NOT_FOUND)`
Janis Danisevskis77d72042021-01-20 15:36:30 -0800197 pub fn not_found() -> Self {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700198 Error::Error(ERROR_ENTRY_NOT_FOUND)
199 }
200
201 /// Short hand for `Error::Error(ERROR_PERMISSION_DENIED)`
202 pub fn perm() -> Self {
203 Error::Error(ERROR_PERMISSION_DENIED)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800204 }
Shaquille Johnsonbe6e91d2023-10-21 19:09:17 +0100205
206 /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)`
207 pub fn deprecated() -> Self {
208 Error::Error(ERROR_SYSTEM_ERROR)
209 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800210}
211
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700212/// This function should be used by legacykeystore service calls to translate error conditions
Janis Danisevskis77d72042021-01-20 15:36:30 -0800213/// into service specific exceptions.
214///
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700215/// All error conditions get logged by this function, except for ERROR_ENTRY_NOT_FOUND error.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800216///
217/// `Error::Error(x)` variants get mapped onto a service specific error code of `x`.
218///
219/// All non `Error` error conditions get mapped onto `ERROR_SYSTEM_ERROR`.
220///
221/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
222/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
223/// typically returns Ok(value).
224fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
225where
226 F: FnOnce(U) -> BinderResult<T>,
227{
228 result.map_or_else(
229 |e| {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800230 let root_cause = e.root_cause();
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000231 let (rc, log_error) = match root_cause.downcast_ref::<Error>() {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700232 // Make the entry not found errors silent.
233 Some(Error::Error(ERROR_ENTRY_NOT_FOUND)) => (ERROR_ENTRY_NOT_FOUND, false),
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000234 Some(Error::Error(e)) => (*e, true),
235 Some(Error::Binder(_, _)) | None => (ERROR_SYSTEM_ERROR, true),
Janis Danisevskis77d72042021-01-20 15:36:30 -0800236 };
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000237 if log_error {
238 log::error!("{:?}", e);
239 }
Janis Danisevskisea03cff2021-12-16 08:10:17 -0800240 Err(BinderStatus::new_service_specific_error(
241 rc,
242 anyhow_error_to_cstring(&e).as_deref(),
243 ))
Janis Danisevskis77d72042021-01-20 15:36:30 -0800244 },
245 handle_ok,
246 )
247}
248
Shaquille Johnsonf015af12023-11-30 15:22:19 +0000249fn ensure_keystore_put_is_enabled() -> Result<()> {
250 if keystore2_flags::disable_legacy_keystore_put_v2() {
251 Err(Error::deprecated()).context(concat!(
252 "Storing into Keystore's legacy database is ",
253 "no longer supported, store in an app-specific database instead"
254 ))
255 } else {
256 Ok(())
257 }
258}
259
Janis Danisevskis5898d152021-06-15 08:23:46 -0700260struct LegacyKeystoreDeleteListener {
261 legacy_keystore: Arc<LegacyKeystore>,
262}
263
264impl DeleteListener for LegacyKeystoreDeleteListener {
265 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()> {
266 self.legacy_keystore.delete_namespace(domain, namespace)
267 }
268 fn delete_user(&self, user_id: u32) -> Result<()> {
269 self.legacy_keystore.delete_user(user_id)
270 }
271}
272
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700273/// Implements ILegacyKeystore AIDL interface.
274pub struct LegacyKeystore {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800275 db_path: PathBuf,
Janis Danisevskis06891072021-02-11 10:28:17 -0800276 async_task: AsyncTask,
277}
278
279struct AsyncState {
280 recently_imported: HashSet<(u32, String)>,
281 legacy_loader: LegacyBlobLoader,
282 db_path: PathBuf,
Janis Danisevskis77d72042021-01-20 15:36:30 -0800283}
284
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700285impl LegacyKeystore {
286 /// Note: The filename was chosen before the purpose of this module was extended.
287 /// It is kept for backward compatibility with early adopters.
288 const LEGACY_KEYSTORE_FILE_NAME: &'static str = "vpnprofilestore.sqlite";
289
Janis Danisevskis5898d152021-06-15 08:23:46 -0700290 const WIFI_NAMESPACE: i64 = 102;
291 const AID_WIFI: u32 = 1010;
292
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700293 /// Creates a new LegacyKeystore instance.
Janis Danisevskis5898d152021-06-15 08:23:46 -0700294 pub fn new_native_binder(
295 path: &Path,
296 ) -> (Box<dyn DeleteListener + Send + Sync + 'static>, Strong<dyn ILegacyKeystore>) {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800297 let mut db_path = path.to_path_buf();
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700298 db_path.push(Self::LEGACY_KEYSTORE_FILE_NAME);
Janis Danisevskis06891072021-02-11 10:28:17 -0800299
Janis Danisevskis5898d152021-06-15 08:23:46 -0700300 let legacy_keystore = Arc::new(Self { db_path, async_task: Default::default() });
301 legacy_keystore.init_shelf(path);
302 let service = LegacyKeystoreService { legacy_keystore: legacy_keystore.clone() };
303 (
304 Box::new(LegacyKeystoreDeleteListener { legacy_keystore }),
305 BnLegacyKeystore::new_binder(service, BinderFeatures::default()),
306 )
Janis Danisevskis77d72042021-01-20 15:36:30 -0800307 }
308
309 fn open_db(&self) -> Result<DB> {
310 DB::new(&self.db_path).context("In open_db: Failed to open db.")
311 }
312
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700313 fn get_effective_uid(uid: i32) -> Result<u32> {
314 const AID_SYSTEM: u32 = 1000;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800315 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700316 let uid = uid as u32;
Janis Danisevskis06891072021-02-11 10:28:17 -0800317
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700318 if uid == UID_SELF as u32 || uid == calling_uid {
319 Ok(calling_uid)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700320 } else if calling_uid == AID_SYSTEM && uid == Self::AID_WIFI {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700321 // The only exception for legacy reasons is allowing SYSTEM to access
322 // the WIFI namespace.
323 // IMPORTANT: If you attempt to add more exceptions, it means you are adding
324 // more callers to this deprecated feature. DON'T!
Janis Danisevskis5898d152021-06-15 08:23:46 -0700325 Ok(Self::AID_WIFI)
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700326 } else {
327 Err(Error::perm()).with_context(|| {
328 format!("In get_effective_uid: caller: {}, requested uid: {}.", calling_uid, uid)
329 })
Janis Danisevskis06891072021-02-11 10:28:17 -0800330 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700331 }
332
333 fn get(&self, alias: &str, uid: i32) -> Result<Vec<u8>> {
334 let mut db = self.open_db().context("In get.")?;
335 let uid = Self::get_effective_uid(uid).context("In get.")?;
336
337 if let Some(entry) = db.get(uid, alias).context("In get: Trying to load entry from DB.")? {
338 return Ok(entry);
339 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800340 if self.get_legacy(uid, alias).context("In get: Trying to import legacy blob.")? {
341 // If we were able to import a legacy blob try again.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700342 if let Some(entry) =
343 db.get(uid, alias).context("In get: Trying to load entry from DB.")?
Janis Danisevskis06891072021-02-11 10:28:17 -0800344 {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700345 return Ok(entry);
Janis Danisevskis06891072021-02-11 10:28:17 -0800346 }
347 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700348 Err(Error::not_found()).context("In get: No such entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800349 }
350
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700351 fn put(&self, alias: &str, uid: i32, entry: &[u8]) -> Result<()> {
Shaquille Johnsonf015af12023-11-30 15:22:19 +0000352 ensure_keystore_put_is_enabled()?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700353 let uid = Self::get_effective_uid(uid).context("In put.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800354 let mut db = self.open_db().context("In put.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800355 db.put(uid, alias, entry).context("In put: Trying to insert entry into DB.")?;
356 // When replacing an entry, make sure that there is no stale legacy file entry.
357 let _ = self.remove_legacy(uid, alias);
358 Ok(())
Janis Danisevskis77d72042021-01-20 15:36:30 -0800359 }
360
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700361 fn remove(&self, alias: &str, uid: i32) -> Result<()> {
362 let uid = Self::get_effective_uid(uid).context("In remove.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800363 let mut db = self.open_db().context("In remove.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800364
365 if self.remove_legacy(uid, alias).context("In remove: trying to remove legacy entry")? {
366 return Ok(());
367 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700368 let removed =
369 db.remove(uid, alias).context("In remove: Trying to remove entry from DB.")?;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800370 if removed {
371 Ok(())
372 } else {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700373 Err(Error::not_found()).context("In remove: No such entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800374 }
375 }
376
Janis Danisevskis5898d152021-06-15 08:23:46 -0700377 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()> {
378 let uid = match domain {
379 Domain::APP => namespace as u32,
380 Domain::SELINUX => {
381 if namespace == Self::WIFI_NAMESPACE {
382 // Namespace WIFI gets mapped to AID_WIFI.
383 Self::AID_WIFI
384 } else {
385 // Nothing to do for any other namespace.
386 return Ok(());
387 }
388 }
389 _ => return Ok(()),
390 };
391
392 if let Err(e) = self.bulk_delete_uid(uid) {
393 log::warn!("In LegacyKeystore::delete_namespace: {:?}", e);
394 }
395 let mut db = self.open_db().context("In LegacyKeystore::delete_namespace.")?;
396 db.remove_uid(uid).context("In LegacyKeystore::delete_namespace.")
397 }
398
399 fn delete_user(&self, user_id: u32) -> Result<()> {
400 if let Err(e) = self.bulk_delete_user(user_id) {
401 log::warn!("In LegacyKeystore::delete_user: {:?}", e);
402 }
403 let mut db = self.open_db().context("In LegacyKeystore::delete_user.")?;
404 db.remove_user(user_id).context("In LegacyKeystore::delete_user.")
405 }
406
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700407 fn list(&self, prefix: &str, uid: i32) -> Result<Vec<String>> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800408 let mut db = self.open_db().context("In list.")?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700409 let uid = Self::get_effective_uid(uid).context("In list.")?;
410 let mut result = self.list_legacy(uid).context("In list.")?;
411 result.append(&mut db.list(uid).context("In list: Trying to get list of entries.")?);
Charisee28e6f0b2022-09-15 01:07:46 +0000412 result.retain(|s| s.starts_with(prefix));
Janis Danisevskis06891072021-02-11 10:28:17 -0800413 result.sort_unstable();
414 result.dedup();
415 Ok(result)
416 }
417
418 fn init_shelf(&self, path: &Path) {
419 let mut db_path = path.to_path_buf();
420 self.async_task.queue_hi(move |shelf| {
421 let legacy_loader = LegacyBlobLoader::new(&db_path);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700422 db_path.push(Self::LEGACY_KEYSTORE_FILE_NAME);
Janis Danisevskis06891072021-02-11 10:28:17 -0800423
424 shelf.put(AsyncState { legacy_loader, db_path, recently_imported: Default::default() });
425 })
426 }
427
428 fn do_serialized<F, T: Send + 'static>(&self, f: F) -> Result<T>
429 where
430 F: FnOnce(&mut AsyncState) -> Result<T> + Send + 'static,
431 {
432 let (sender, receiver) = std::sync::mpsc::channel::<Result<T>>();
433 self.async_task.queue_hi(move |shelf| {
434 let state = shelf.get_downcast_mut::<AsyncState>().expect("Failed to get shelf.");
435 sender.send(f(state)).expect("Failed to send result.");
436 });
437 receiver.recv().context("In do_serialized: Failed to receive result.")?
438 }
439
440 fn list_legacy(&self, uid: u32) -> Result<Vec<String>> {
441 self.do_serialized(move |state| {
442 state
443 .legacy_loader
Janis Danisevskis5898d152021-06-15 08:23:46 -0700444 .list_legacy_keystore_entries_for_uid(uid)
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700445 .context("Trying to list legacy keystore entries.")
Janis Danisevskis06891072021-02-11 10:28:17 -0800446 })
447 .context("In list_legacy.")
448 }
449
450 fn get_legacy(&self, uid: u32, alias: &str) -> Result<bool> {
451 let alias = alias.to_string();
452 self.do_serialized(move |state| {
453 if state.recently_imported.contains(&(uid, alias.clone())) {
454 return Ok(true);
455 }
456 let mut db = DB::new(&state.db_path).context("In open_db: Failed to open db.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800457 let imported =
458 Self::import_one_legacy_entry(uid, &alias, &state.legacy_loader, &mut db)
459 .context("Trying to import legacy keystore entries.")?;
460 if imported {
Janis Danisevskis06891072021-02-11 10:28:17 -0800461 state.recently_imported.insert((uid, alias));
462 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800463 Ok(imported)
Janis Danisevskis06891072021-02-11 10:28:17 -0800464 })
465 .context("In get_legacy.")
466 }
467
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800468 fn remove_legacy(&self, uid: u32, alias: &str) -> Result<bool> {
469 let alias = alias.to_string();
470 self.do_serialized(move |state| {
471 if state.recently_imported.contains(&(uid, alias.clone())) {
472 return Ok(false);
473 }
474 state
475 .legacy_loader
476 .remove_legacy_keystore_entry(uid, &alias)
477 .context("Trying to remove legacy entry.")
478 })
479 }
480
Janis Danisevskis5898d152021-06-15 08:23:46 -0700481 fn bulk_delete_uid(&self, uid: u32) -> Result<()> {
482 self.do_serialized(move |state| {
483 let entries = state
484 .legacy_loader
485 .list_legacy_keystore_entries_for_uid(uid)
486 .context("In bulk_delete_uid: Trying to list entries.")?;
487 for alias in entries.iter() {
488 if let Err(e) = state.legacy_loader.remove_legacy_keystore_entry(uid, alias) {
489 log::warn!("In bulk_delete_uid: Failed to delete legacy entry. {:?}", e);
490 }
491 }
492 Ok(())
493 })
494 }
495
496 fn bulk_delete_user(&self, user_id: u32) -> Result<()> {
497 self.do_serialized(move |state| {
498 let entries = state
499 .legacy_loader
500 .list_legacy_keystore_entries_for_user(user_id)
501 .context("In bulk_delete_user: Trying to list entries.")?;
502 for (uid, entries) in entries.iter() {
503 for alias in entries.iter() {
504 if let Err(e) = state.legacy_loader.remove_legacy_keystore_entry(*uid, alias) {
505 log::warn!("In bulk_delete_user: Failed to delete legacy entry. {:?}", e);
506 }
507 }
508 }
509 Ok(())
510 })
511 }
512
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800513 fn import_one_legacy_entry(
Janis Danisevskis06891072021-02-11 10:28:17 -0800514 uid: u32,
515 alias: &str,
516 legacy_loader: &LegacyBlobLoader,
517 db: &mut DB,
518 ) -> Result<bool> {
519 let blob = legacy_loader
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800520 .read_legacy_keystore_entry(uid, alias, |ciphertext, iv, tag, _salt, _key_size| {
Eric Biggers673d34a2023-10-18 01:54:18 +0000521 if let Some(key) = SUPER_KEY
522 .read()
523 .unwrap()
524 .get_after_first_unlock_key_by_user_id(uid_to_android_user(uid))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800525 {
526 key.decrypt(ciphertext, iv, tag)
527 } else {
528 Err(Error::sys()).context("No key found for user. Device may be locked.")
529 }
530 })
531 .context("In import_one_legacy_entry: Trying to read legacy keystore entry.")?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700532 if let Some(entry) = blob {
533 db.put(uid, alias, &entry)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800534 .context("In import_one_legacy_entry: Trying to insert entry into DB.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800535 legacy_loader
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700536 .remove_legacy_keystore_entry(uid, alias)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800537 .context("In import_one_legacy_entry: Trying to delete legacy keystore entry.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800538 Ok(true)
539 } else {
540 Ok(false)
541 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800542 }
543}
544
Janis Danisevskis5898d152021-06-15 08:23:46 -0700545struct LegacyKeystoreService {
546 legacy_keystore: Arc<LegacyKeystore>,
547}
Janis Danisevskis77d72042021-01-20 15:36:30 -0800548
Janis Danisevskis5898d152021-06-15 08:23:46 -0700549impl binder::Interface for LegacyKeystoreService {}
550
551impl ILegacyKeystore for LegacyKeystoreService {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700552 fn get(&self, alias: &str, uid: i32) -> BinderResult<Vec<u8>> {
553 let _wp = wd::watch_millis("ILegacyKeystore::get", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700554 map_or_log_err(self.legacy_keystore.get(alias, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800555 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700556 fn put(&self, alias: &str, uid: i32, entry: &[u8]) -> BinderResult<()> {
557 let _wp = wd::watch_millis("ILegacyKeystore::put", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700558 map_or_log_err(self.legacy_keystore.put(alias, uid, entry), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800559 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700560 fn remove(&self, alias: &str, uid: i32) -> BinderResult<()> {
561 let _wp = wd::watch_millis("ILegacyKeystore::remove", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700562 map_or_log_err(self.legacy_keystore.remove(alias, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800563 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700564 fn list(&self, prefix: &str, uid: i32) -> BinderResult<Vec<String>> {
565 let _wp = wd::watch_millis("ILegacyKeystore::list", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700566 map_or_log_err(self.legacy_keystore.list(prefix, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800567 }
568}
569
570#[cfg(test)]
571mod db_test {
572 use super::*;
573 use keystore2_test_utils::TempDir;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700574 use std::sync::Arc;
575 use std::thread;
576 use std::time::Duration;
577 use std::time::Instant;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800578
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700579 static TEST_ALIAS: &str = "test_alias";
Janis Danisevskis77d72042021-01-20 15:36:30 -0800580 static TEST_BLOB1: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
581 static TEST_BLOB2: &[u8] = &[2, 2, 3, 4, 5, 6, 7, 8, 9, 0];
582 static TEST_BLOB3: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
583 static TEST_BLOB4: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
584
585 #[test]
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700586 fn test_entry_db() {
587 let test_dir = TempDir::new("entrydb_test_").expect("Failed to create temp dir.");
588 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
589 .expect("Failed to open database.");
Janis Danisevskis77d72042021-01-20 15:36:30 -0800590
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700591 // Insert three entries for owner 2.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800592 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
593 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
594 db.put(2, "test3", TEST_BLOB3).expect("Failed to insert test3.");
595
596 // Check list returns all inserted aliases.
597 assert_eq!(
598 vec!["test1".to_string(), "test2".to_string(), "test3".to_string(),],
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700599 db.list(2).expect("Failed to list entries.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800600 );
601
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700602 // There should be no entries for owner 1.
603 assert_eq!(Vec::<String>::new(), db.list(1).expect("Failed to list entries."));
Janis Danisevskis77d72042021-01-20 15:36:30 -0800604
605 // Check the content of the three entries.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700606 assert_eq!(Some(TEST_BLOB1), db.get(2, "test1").expect("Failed to get entry.").as_deref());
607 assert_eq!(Some(TEST_BLOB2), db.get(2, "test2").expect("Failed to get entry.").as_deref());
608 assert_eq!(Some(TEST_BLOB3), db.get(2, "test3").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800609
610 // Remove test2 and check and check that it is no longer retrievable.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700611 assert!(db.remove(2, "test2").expect("Failed to remove entry."));
612 assert!(db.get(2, "test2").expect("Failed to get entry.").is_none());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800613
614 // test2 should now no longer be in the list.
615 assert_eq!(
616 vec!["test1".to_string(), "test3".to_string(),],
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700617 db.list(2).expect("Failed to list entries.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800618 );
619
620 // Put on existing alias replaces it.
621 // Verify test1 is TEST_BLOB1.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700622 assert_eq!(Some(TEST_BLOB1), db.get(2, "test1").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800623 db.put(2, "test1", TEST_BLOB4).expect("Failed to replace test1.");
624 // Verify test1 is TEST_BLOB4.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700625 assert_eq!(Some(TEST_BLOB4), db.get(2, "test1").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800626 }
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700627
628 #[test]
Janis Danisevskis5898d152021-06-15 08:23:46 -0700629 fn test_delete_uid() {
630 let test_dir = TempDir::new("test_delete_uid_").expect("Failed to create temp dir.");
631 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
632 .expect("Failed to open database.");
633
634 // Insert three entries for owner 2.
635 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
636 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
637 db.put(3, "test3", TEST_BLOB3).expect("Failed to insert test3.");
638
639 db.remove_uid(2).expect("Failed to remove uid 2");
640
641 assert_eq!(Vec::<String>::new(), db.list(2).expect("Failed to list entries."));
642
643 assert_eq!(vec!["test3".to_string(),], db.list(3).expect("Failed to list entries."));
644 }
645
646 #[test]
647 fn test_delete_user() {
648 let test_dir = TempDir::new("test_delete_user_").expect("Failed to create temp dir.");
649 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
650 .expect("Failed to open database.");
651
652 // Insert three entries for owner 2.
Joel Galenson81a50f22021-07-29 15:39:10 -0700653 db.put(2 + 2 * rustutils::users::AID_USER_OFFSET, "test1", TEST_BLOB1)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700654 .expect("Failed to insert test1.");
Joel Galenson81a50f22021-07-29 15:39:10 -0700655 db.put(4 + 2 * rustutils::users::AID_USER_OFFSET, "test2", TEST_BLOB2)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700656 .expect("Failed to insert test2.");
657 db.put(3, "test3", TEST_BLOB3).expect("Failed to insert test3.");
658
659 db.remove_user(2).expect("Failed to remove user 2");
660
661 assert_eq!(
662 Vec::<String>::new(),
Joel Galenson81a50f22021-07-29 15:39:10 -0700663 db.list(2 + 2 * rustutils::users::AID_USER_OFFSET).expect("Failed to list entries.")
Janis Danisevskis5898d152021-06-15 08:23:46 -0700664 );
665
666 assert_eq!(
667 Vec::<String>::new(),
Joel Galenson81a50f22021-07-29 15:39:10 -0700668 db.list(4 + 2 * rustutils::users::AID_USER_OFFSET).expect("Failed to list entries.")
Janis Danisevskis5898d152021-06-15 08:23:46 -0700669 );
670
671 assert_eq!(vec!["test3".to_string(),], db.list(3).expect("Failed to list entries."));
672 }
673
674 #[test]
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700675 fn concurrent_legacy_keystore_entry_test() -> Result<()> {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700676 let temp_dir = Arc::new(
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700677 TempDir::new("concurrent_legacy_keystore_entry_test_")
678 .expect("Failed to create temp dir."),
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700679 );
680
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700681 let db_path = temp_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME).to_owned();
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700682
683 let test_begin = Instant::now();
684
685 let mut db = DB::new(&db_path).expect("Failed to open database.");
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700686 const ENTRY_COUNT: u32 = 5000u32;
687 const ENTRY_DB_COUNT: u32 = 5000u32;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700688
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700689 let mut actual_entry_count = ENTRY_COUNT;
690 // First insert ENTRY_COUNT entries.
691 for count in 0..ENTRY_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700692 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700693 actual_entry_count = count;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700694 break;
695 }
696 let alias = format!("test_alias_{}", count);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700697 db.put(1, &alias, TEST_BLOB1).expect("Failed to add entry (1).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700698 }
699
700 // Insert more keys from a different thread and into a different namespace.
701 let db_path1 = db_path.clone();
702 let handle1 = thread::spawn(move || {
703 let mut db = DB::new(&db_path1).expect("Failed to open database.");
704
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700705 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700706 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
707 return;
708 }
709 let alias = format!("test_alias_{}", count);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700710 db.put(2, &alias, TEST_BLOB2).expect("Failed to add entry (2).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700711 }
712
713 // Then delete them again.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700714 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700715 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
716 return;
717 }
718 let alias = format!("test_alias_{}", count);
719 db.remove(2, &alias).expect("Remove Failed (2).");
720 }
721 });
722
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700723 // And start deleting the first set of entries.
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700724 let db_path2 = db_path.clone();
725 let handle2 = thread::spawn(move || {
726 let mut db = DB::new(&db_path2).expect("Failed to open database.");
727
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700728 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700729 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
730 return;
731 }
732 let alias = format!("test_alias_{}", count);
733 db.remove(1, &alias).expect("Remove Failed (1)).");
734 }
735 });
736
737 // While a lot of inserting and deleting is going on we have to open database connections
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700738 // successfully and then insert and delete a specific entry.
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700739 let db_path3 = db_path.clone();
740 let handle3 = thread::spawn(move || {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700741 for _count in 0..ENTRY_DB_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700742 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
743 return;
744 }
745 let mut db = DB::new(&db_path3).expect("Failed to open database.");
746
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700747 db.put(3, TEST_ALIAS, TEST_BLOB3).expect("Failed to add entry (3).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700748
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700749 db.remove(3, TEST_ALIAS).expect("Remove failed (3).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700750 }
751 });
752
753 // While thread 3 is inserting and deleting TEST_ALIAS, we try to get the alias.
754 // This may yield an entry or none, but it must not fail.
755 let handle4 = thread::spawn(move || {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700756 for _count in 0..ENTRY_DB_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700757 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
758 return;
759 }
760 let mut db = DB::new(&db_path).expect("Failed to open database.");
761
762 // This may return Some or None but it must not fail.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700763 db.get(3, TEST_ALIAS).expect("Failed to get entry (4).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700764 }
765 });
766
767 handle1.join().expect("Thread 1 panicked.");
768 handle2.join().expect("Thread 2 panicked.");
769 handle3.join().expect("Thread 3 panicked.");
770 handle4.join().expect("Thread 4 panicked.");
771
772 Ok(())
773 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800774}