blob: a665405e9d802dceaaa8524569f1c4756bc1f723 [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
Shaquille Johnsond28f5cb2023-11-23 11:12:18 +000049 if keystore2_flags::wal_db_journalmode_v2() {
50 // Update journal mode to WAL
51 db.conn
52 .pragma_update(None, "journal_mode", "WAL")
53 .context("Failed to connect in WAL mode for persistent db")?;
54 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -070055 db.init_tables().context("Trying to initialize legacy keystore db.")?;
Janis Danisevskis77d72042021-01-20 15:36:30 -080056 Ok(db)
57 }
58
59 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
60 where
61 F: Fn(&Transaction) -> Result<T>,
62 {
63 loop {
64 match self
65 .conn
66 .transaction_with_behavior(behavior)
67 .context("In with_transaction.")
68 .and_then(|tx| f(&tx).map(|result| (result, tx)))
69 .and_then(|(result, tx)| {
70 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
71 Ok(result)
72 }) {
73 Ok(result) => break Ok(result),
74 Err(e) => {
75 if Self::is_locked_error(&e) {
76 std::thread::sleep(std::time::Duration::from_micros(500));
77 continue;
78 } else {
79 return Err(e).context("In with_transaction.");
80 }
81 }
82 }
83 }
84 }
85
86 fn is_locked_error(e: &anyhow::Error) -> bool {
Janis Danisevskis13f09152021-04-19 09:55:15 -070087 matches!(
88 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
89 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
90 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
91 )
Janis Danisevskis77d72042021-01-20 15:36:30 -080092 }
93
94 fn init_tables(&mut self) -> Result<()> {
95 self.with_transaction(TransactionBehavior::Immediate, |tx| {
96 tx.execute(
97 "CREATE TABLE IF NOT EXISTS profiles (
98 owner INTEGER,
99 alias BLOB,
100 profile BLOB,
101 UNIQUE(owner, alias));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000102 [],
Janis Danisevskis77d72042021-01-20 15:36:30 -0800103 )
104 .context("Failed to initialize \"profiles\" table.")?;
105 Ok(())
106 })
107 }
108
109 fn list(&mut self, caller_uid: u32) -> Result<Vec<String>> {
110 self.with_transaction(TransactionBehavior::Deferred, |tx| {
111 let mut stmt = tx
112 .prepare("SELECT alias FROM profiles WHERE owner = ? ORDER BY alias ASC;")
113 .context("In list: Failed to prepare statement.")?;
114
Chris Wailes263de9f2022-08-11 15:00:51 -0700115 // This allow is necessary to avoid the following error:
116 //
117 // error[E0597]: `stmt` does not live long enough
118 //
119 // See: https://github.com/rust-lang/rust-clippy/issues/8114
120 #[allow(clippy::let_and_return)]
Janis Danisevskis77d72042021-01-20 15:36:30 -0800121 let aliases = stmt
122 .query_map(params![caller_uid], |row| row.get(0))?
123 .collect::<rusqlite::Result<Vec<String>>>()
124 .context("In list: query_map failed.");
125 aliases
126 })
127 }
128
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700129 fn put(&mut self, caller_uid: u32, alias: &str, entry: &[u8]) -> Result<()> {
Shaquille Johnsonf015af12023-11-30 15:22:19 +0000130 ensure_keystore_put_is_enabled()?;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800131 self.with_transaction(TransactionBehavior::Immediate, |tx| {
132 tx.execute(
133 "INSERT OR REPLACE INTO profiles (owner, alias, profile) values (?, ?, ?)",
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700134 params![caller_uid, alias, entry,],
Janis Danisevskis77d72042021-01-20 15:36:30 -0800135 )
136 .context("In put: Failed to insert or replace.")?;
137 Ok(())
138 })
139 }
140
141 fn get(&mut self, caller_uid: u32, alias: &str) -> Result<Option<Vec<u8>>> {
142 self.with_transaction(TransactionBehavior::Deferred, |tx| {
143 tx.query_row(
144 "SELECT profile FROM profiles WHERE owner = ? AND alias = ?;",
145 params![caller_uid, alias],
146 |row| row.get(0),
147 )
148 .optional()
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700149 .context("In get: failed loading entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800150 })
151 }
152
153 fn remove(&mut self, caller_uid: u32, alias: &str) -> Result<bool> {
154 let removed = self.with_transaction(TransactionBehavior::Immediate, |tx| {
155 tx.execute(
156 "DELETE FROM profiles WHERE owner = ? AND alias = ?;",
157 params![caller_uid, alias],
158 )
159 .context("In remove: Failed to delete row.")
160 })?;
161 Ok(removed == 1)
162 }
Janis Danisevskis5898d152021-06-15 08:23:46 -0700163
164 fn remove_uid(&mut self, uid: u32) -> Result<()> {
165 self.with_transaction(TransactionBehavior::Immediate, |tx| {
166 tx.execute("DELETE FROM profiles WHERE owner = ?;", params![uid])
167 .context("In remove_uid: Failed to delete.")
168 })?;
169 Ok(())
170 }
171
172 fn remove_user(&mut self, user_id: u32) -> Result<()> {
173 self.with_transaction(TransactionBehavior::Immediate, |tx| {
174 tx.execute(
175 "DELETE FROM profiles WHERE cast ( ( owner/? ) as int) = ?;",
Joel Galenson81a50f22021-07-29 15:39:10 -0700176 params![rustutils::users::AID_USER_OFFSET, user_id],
Janis Danisevskis5898d152021-06-15 08:23:46 -0700177 )
178 .context("In remove_uid: Failed to delete.")
179 })?;
180 Ok(())
181 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800182}
183
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700184/// This is the main LegacyKeystore error type, it wraps binder exceptions and the
185/// LegacyKeystore errors.
Chris Wailes263de9f2022-08-11 15:00:51 -0700186#[derive(Debug, thiserror::Error, PartialEq, Eq)]
Janis Danisevskis77d72042021-01-20 15:36:30 -0800187pub enum Error {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700188 /// Wraps a LegacyKeystore error code.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800189 #[error("Error::Error({0:?})")]
190 Error(i32),
191 /// Wraps a Binder exception code other than a service specific exception.
192 #[error("Binder exception code {0:?}, {1:?}")]
193 Binder(ExceptionCode, i32),
194}
195
196impl Error {
197 /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)`
198 pub fn sys() -> Self {
199 Error::Error(ERROR_SYSTEM_ERROR)
200 }
201
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700202 /// Short hand for `Error::Error(ERROR_ENTRY_NOT_FOUND)`
Janis Danisevskis77d72042021-01-20 15:36:30 -0800203 pub fn not_found() -> Self {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700204 Error::Error(ERROR_ENTRY_NOT_FOUND)
205 }
206
207 /// Short hand for `Error::Error(ERROR_PERMISSION_DENIED)`
208 pub fn perm() -> Self {
209 Error::Error(ERROR_PERMISSION_DENIED)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800210 }
Shaquille Johnsonbe6e91d2023-10-21 19:09:17 +0100211
212 /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)`
213 pub fn deprecated() -> Self {
214 Error::Error(ERROR_SYSTEM_ERROR)
215 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800216}
217
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700218/// This function should be used by legacykeystore service calls to translate error conditions
Janis Danisevskis77d72042021-01-20 15:36:30 -0800219/// into service specific exceptions.
220///
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700221/// All error conditions get logged by this function, except for ERROR_ENTRY_NOT_FOUND error.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800222///
223/// `Error::Error(x)` variants get mapped onto a service specific error code of `x`.
224///
225/// All non `Error` error conditions get mapped onto `ERROR_SYSTEM_ERROR`.
226///
227/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
228/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
229/// typically returns Ok(value).
230fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
231where
232 F: FnOnce(U) -> BinderResult<T>,
233{
234 result.map_or_else(
235 |e| {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800236 let root_cause = e.root_cause();
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000237 let (rc, log_error) = match root_cause.downcast_ref::<Error>() {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700238 // Make the entry not found errors silent.
239 Some(Error::Error(ERROR_ENTRY_NOT_FOUND)) => (ERROR_ENTRY_NOT_FOUND, false),
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000240 Some(Error::Error(e)) => (*e, true),
241 Some(Error::Binder(_, _)) | None => (ERROR_SYSTEM_ERROR, true),
Janis Danisevskis77d72042021-01-20 15:36:30 -0800242 };
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000243 if log_error {
244 log::error!("{:?}", e);
245 }
Janis Danisevskisea03cff2021-12-16 08:10:17 -0800246 Err(BinderStatus::new_service_specific_error(
247 rc,
248 anyhow_error_to_cstring(&e).as_deref(),
249 ))
Janis Danisevskis77d72042021-01-20 15:36:30 -0800250 },
251 handle_ok,
252 )
253}
254
Shaquille Johnsonf015af12023-11-30 15:22:19 +0000255fn ensure_keystore_put_is_enabled() -> Result<()> {
256 if keystore2_flags::disable_legacy_keystore_put_v2() {
257 Err(Error::deprecated()).context(concat!(
258 "Storing into Keystore's legacy database is ",
259 "no longer supported, store in an app-specific database instead"
260 ))
261 } else {
262 Ok(())
263 }
264}
265
Janis Danisevskis5898d152021-06-15 08:23:46 -0700266struct LegacyKeystoreDeleteListener {
267 legacy_keystore: Arc<LegacyKeystore>,
268}
269
270impl DeleteListener for LegacyKeystoreDeleteListener {
271 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()> {
272 self.legacy_keystore.delete_namespace(domain, namespace)
273 }
274 fn delete_user(&self, user_id: u32) -> Result<()> {
275 self.legacy_keystore.delete_user(user_id)
276 }
277}
278
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700279/// Implements ILegacyKeystore AIDL interface.
280pub struct LegacyKeystore {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800281 db_path: PathBuf,
Janis Danisevskis06891072021-02-11 10:28:17 -0800282 async_task: AsyncTask,
283}
284
285struct AsyncState {
286 recently_imported: HashSet<(u32, String)>,
287 legacy_loader: LegacyBlobLoader,
288 db_path: PathBuf,
Janis Danisevskis77d72042021-01-20 15:36:30 -0800289}
290
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700291impl LegacyKeystore {
292 /// Note: The filename was chosen before the purpose of this module was extended.
293 /// It is kept for backward compatibility with early adopters.
294 const LEGACY_KEYSTORE_FILE_NAME: &'static str = "vpnprofilestore.sqlite";
295
Janis Danisevskis5898d152021-06-15 08:23:46 -0700296 const WIFI_NAMESPACE: i64 = 102;
297 const AID_WIFI: u32 = 1010;
298
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700299 /// Creates a new LegacyKeystore instance.
Janis Danisevskis5898d152021-06-15 08:23:46 -0700300 pub fn new_native_binder(
301 path: &Path,
302 ) -> (Box<dyn DeleteListener + Send + Sync + 'static>, Strong<dyn ILegacyKeystore>) {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800303 let mut db_path = path.to_path_buf();
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700304 db_path.push(Self::LEGACY_KEYSTORE_FILE_NAME);
Janis Danisevskis06891072021-02-11 10:28:17 -0800305
Janis Danisevskis5898d152021-06-15 08:23:46 -0700306 let legacy_keystore = Arc::new(Self { db_path, async_task: Default::default() });
307 legacy_keystore.init_shelf(path);
308 let service = LegacyKeystoreService { legacy_keystore: legacy_keystore.clone() };
309 (
310 Box::new(LegacyKeystoreDeleteListener { legacy_keystore }),
311 BnLegacyKeystore::new_binder(service, BinderFeatures::default()),
312 )
Janis Danisevskis77d72042021-01-20 15:36:30 -0800313 }
314
315 fn open_db(&self) -> Result<DB> {
316 DB::new(&self.db_path).context("In open_db: Failed to open db.")
317 }
318
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700319 fn get_effective_uid(uid: i32) -> Result<u32> {
320 const AID_SYSTEM: u32 = 1000;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800321 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700322 let uid = uid as u32;
Janis Danisevskis06891072021-02-11 10:28:17 -0800323
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700324 if uid == UID_SELF as u32 || uid == calling_uid {
325 Ok(calling_uid)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700326 } else if calling_uid == AID_SYSTEM && uid == Self::AID_WIFI {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700327 // The only exception for legacy reasons is allowing SYSTEM to access
328 // the WIFI namespace.
329 // IMPORTANT: If you attempt to add more exceptions, it means you are adding
330 // more callers to this deprecated feature. DON'T!
Janis Danisevskis5898d152021-06-15 08:23:46 -0700331 Ok(Self::AID_WIFI)
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700332 } else {
333 Err(Error::perm()).with_context(|| {
334 format!("In get_effective_uid: caller: {}, requested uid: {}.", calling_uid, uid)
335 })
Janis Danisevskis06891072021-02-11 10:28:17 -0800336 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700337 }
338
339 fn get(&self, alias: &str, uid: i32) -> Result<Vec<u8>> {
340 let mut db = self.open_db().context("In get.")?;
341 let uid = Self::get_effective_uid(uid).context("In get.")?;
342
343 if let Some(entry) = db.get(uid, alias).context("In get: Trying to load entry from DB.")? {
344 return Ok(entry);
345 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800346 if self.get_legacy(uid, alias).context("In get: Trying to import legacy blob.")? {
347 // If we were able to import a legacy blob try again.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700348 if let Some(entry) =
349 db.get(uid, alias).context("In get: Trying to load entry from DB.")?
Janis Danisevskis06891072021-02-11 10:28:17 -0800350 {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700351 return Ok(entry);
Janis Danisevskis06891072021-02-11 10:28:17 -0800352 }
353 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700354 Err(Error::not_found()).context("In get: No such entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800355 }
356
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700357 fn put(&self, alias: &str, uid: i32, entry: &[u8]) -> Result<()> {
Shaquille Johnsonf015af12023-11-30 15:22:19 +0000358 ensure_keystore_put_is_enabled()?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700359 let uid = Self::get_effective_uid(uid).context("In put.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800360 let mut db = self.open_db().context("In put.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800361 db.put(uid, alias, entry).context("In put: Trying to insert entry into DB.")?;
362 // When replacing an entry, make sure that there is no stale legacy file entry.
363 let _ = self.remove_legacy(uid, alias);
364 Ok(())
Janis Danisevskis77d72042021-01-20 15:36:30 -0800365 }
366
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700367 fn remove(&self, alias: &str, uid: i32) -> Result<()> {
368 let uid = Self::get_effective_uid(uid).context("In remove.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800369 let mut db = self.open_db().context("In remove.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800370
371 if self.remove_legacy(uid, alias).context("In remove: trying to remove legacy entry")? {
372 return Ok(());
373 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700374 let removed =
375 db.remove(uid, alias).context("In remove: Trying to remove entry from DB.")?;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800376 if removed {
377 Ok(())
378 } else {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700379 Err(Error::not_found()).context("In remove: No such entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800380 }
381 }
382
Janis Danisevskis5898d152021-06-15 08:23:46 -0700383 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()> {
384 let uid = match domain {
385 Domain::APP => namespace as u32,
386 Domain::SELINUX => {
387 if namespace == Self::WIFI_NAMESPACE {
388 // Namespace WIFI gets mapped to AID_WIFI.
389 Self::AID_WIFI
390 } else {
391 // Nothing to do for any other namespace.
392 return Ok(());
393 }
394 }
395 _ => return Ok(()),
396 };
397
398 if let Err(e) = self.bulk_delete_uid(uid) {
399 log::warn!("In LegacyKeystore::delete_namespace: {:?}", e);
400 }
401 let mut db = self.open_db().context("In LegacyKeystore::delete_namespace.")?;
402 db.remove_uid(uid).context("In LegacyKeystore::delete_namespace.")
403 }
404
405 fn delete_user(&self, user_id: u32) -> Result<()> {
406 if let Err(e) = self.bulk_delete_user(user_id) {
407 log::warn!("In LegacyKeystore::delete_user: {:?}", e);
408 }
409 let mut db = self.open_db().context("In LegacyKeystore::delete_user.")?;
410 db.remove_user(user_id).context("In LegacyKeystore::delete_user.")
411 }
412
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700413 fn list(&self, prefix: &str, uid: i32) -> Result<Vec<String>> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800414 let mut db = self.open_db().context("In list.")?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700415 let uid = Self::get_effective_uid(uid).context("In list.")?;
416 let mut result = self.list_legacy(uid).context("In list.")?;
417 result.append(&mut db.list(uid).context("In list: Trying to get list of entries.")?);
Charisee28e6f0b2022-09-15 01:07:46 +0000418 result.retain(|s| s.starts_with(prefix));
Janis Danisevskis06891072021-02-11 10:28:17 -0800419 result.sort_unstable();
420 result.dedup();
421 Ok(result)
422 }
423
424 fn init_shelf(&self, path: &Path) {
425 let mut db_path = path.to_path_buf();
426 self.async_task.queue_hi(move |shelf| {
427 let legacy_loader = LegacyBlobLoader::new(&db_path);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700428 db_path.push(Self::LEGACY_KEYSTORE_FILE_NAME);
Janis Danisevskis06891072021-02-11 10:28:17 -0800429
430 shelf.put(AsyncState { legacy_loader, db_path, recently_imported: Default::default() });
431 })
432 }
433
434 fn do_serialized<F, T: Send + 'static>(&self, f: F) -> Result<T>
435 where
436 F: FnOnce(&mut AsyncState) -> Result<T> + Send + 'static,
437 {
438 let (sender, receiver) = std::sync::mpsc::channel::<Result<T>>();
439 self.async_task.queue_hi(move |shelf| {
440 let state = shelf.get_downcast_mut::<AsyncState>().expect("Failed to get shelf.");
441 sender.send(f(state)).expect("Failed to send result.");
442 });
443 receiver.recv().context("In do_serialized: Failed to receive result.")?
444 }
445
446 fn list_legacy(&self, uid: u32) -> Result<Vec<String>> {
447 self.do_serialized(move |state| {
448 state
449 .legacy_loader
Janis Danisevskis5898d152021-06-15 08:23:46 -0700450 .list_legacy_keystore_entries_for_uid(uid)
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700451 .context("Trying to list legacy keystore entries.")
Janis Danisevskis06891072021-02-11 10:28:17 -0800452 })
453 .context("In list_legacy.")
454 }
455
456 fn get_legacy(&self, uid: u32, alias: &str) -> Result<bool> {
457 let alias = alias.to_string();
458 self.do_serialized(move |state| {
459 if state.recently_imported.contains(&(uid, alias.clone())) {
460 return Ok(true);
461 }
462 let mut db = DB::new(&state.db_path).context("In open_db: Failed to open db.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800463 let imported =
464 Self::import_one_legacy_entry(uid, &alias, &state.legacy_loader, &mut db)
465 .context("Trying to import legacy keystore entries.")?;
466 if imported {
Janis Danisevskis06891072021-02-11 10:28:17 -0800467 state.recently_imported.insert((uid, alias));
468 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800469 Ok(imported)
Janis Danisevskis06891072021-02-11 10:28:17 -0800470 })
471 .context("In get_legacy.")
472 }
473
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800474 fn remove_legacy(&self, uid: u32, alias: &str) -> Result<bool> {
475 let alias = alias.to_string();
476 self.do_serialized(move |state| {
477 if state.recently_imported.contains(&(uid, alias.clone())) {
478 return Ok(false);
479 }
480 state
481 .legacy_loader
482 .remove_legacy_keystore_entry(uid, &alias)
483 .context("Trying to remove legacy entry.")
484 })
485 }
486
Janis Danisevskis5898d152021-06-15 08:23:46 -0700487 fn bulk_delete_uid(&self, uid: u32) -> Result<()> {
488 self.do_serialized(move |state| {
489 let entries = state
490 .legacy_loader
491 .list_legacy_keystore_entries_for_uid(uid)
492 .context("In bulk_delete_uid: Trying to list entries.")?;
493 for alias in entries.iter() {
494 if let Err(e) = state.legacy_loader.remove_legacy_keystore_entry(uid, alias) {
495 log::warn!("In bulk_delete_uid: Failed to delete legacy entry. {:?}", e);
496 }
497 }
498 Ok(())
499 })
500 }
501
502 fn bulk_delete_user(&self, user_id: u32) -> Result<()> {
503 self.do_serialized(move |state| {
504 let entries = state
505 .legacy_loader
506 .list_legacy_keystore_entries_for_user(user_id)
507 .context("In bulk_delete_user: Trying to list entries.")?;
508 for (uid, entries) in entries.iter() {
509 for alias in entries.iter() {
510 if let Err(e) = state.legacy_loader.remove_legacy_keystore_entry(*uid, alias) {
511 log::warn!("In bulk_delete_user: Failed to delete legacy entry. {:?}", e);
512 }
513 }
514 }
515 Ok(())
516 })
517 }
518
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800519 fn import_one_legacy_entry(
Janis Danisevskis06891072021-02-11 10:28:17 -0800520 uid: u32,
521 alias: &str,
522 legacy_loader: &LegacyBlobLoader,
523 db: &mut DB,
524 ) -> Result<bool> {
525 let blob = legacy_loader
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800526 .read_legacy_keystore_entry(uid, alias, |ciphertext, iv, tag, _salt, _key_size| {
Eric Biggers673d34a2023-10-18 01:54:18 +0000527 if let Some(key) = SUPER_KEY
528 .read()
529 .unwrap()
530 .get_after_first_unlock_key_by_user_id(uid_to_android_user(uid))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800531 {
532 key.decrypt(ciphertext, iv, tag)
533 } else {
534 Err(Error::sys()).context("No key found for user. Device may be locked.")
535 }
536 })
537 .context("In import_one_legacy_entry: Trying to read legacy keystore entry.")?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700538 if let Some(entry) = blob {
539 db.put(uid, alias, &entry)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800540 .context("In import_one_legacy_entry: Trying to insert entry into DB.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800541 legacy_loader
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700542 .remove_legacy_keystore_entry(uid, alias)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800543 .context("In import_one_legacy_entry: Trying to delete legacy keystore entry.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800544 Ok(true)
545 } else {
546 Ok(false)
547 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800548 }
549}
550
Janis Danisevskis5898d152021-06-15 08:23:46 -0700551struct LegacyKeystoreService {
552 legacy_keystore: Arc<LegacyKeystore>,
553}
Janis Danisevskis77d72042021-01-20 15:36:30 -0800554
Janis Danisevskis5898d152021-06-15 08:23:46 -0700555impl binder::Interface for LegacyKeystoreService {}
556
557impl ILegacyKeystore for LegacyKeystoreService {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700558 fn get(&self, alias: &str, uid: i32) -> BinderResult<Vec<u8>> {
559 let _wp = wd::watch_millis("ILegacyKeystore::get", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700560 map_or_log_err(self.legacy_keystore.get(alias, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800561 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700562 fn put(&self, alias: &str, uid: i32, entry: &[u8]) -> BinderResult<()> {
563 let _wp = wd::watch_millis("ILegacyKeystore::put", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700564 map_or_log_err(self.legacy_keystore.put(alias, uid, entry), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800565 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700566 fn remove(&self, alias: &str, uid: i32) -> BinderResult<()> {
567 let _wp = wd::watch_millis("ILegacyKeystore::remove", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700568 map_or_log_err(self.legacy_keystore.remove(alias, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800569 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700570 fn list(&self, prefix: &str, uid: i32) -> BinderResult<Vec<String>> {
571 let _wp = wd::watch_millis("ILegacyKeystore::list", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700572 map_or_log_err(self.legacy_keystore.list(prefix, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800573 }
574}
575
576#[cfg(test)]
577mod db_test {
578 use super::*;
579 use keystore2_test_utils::TempDir;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700580 use std::sync::Arc;
581 use std::thread;
582 use std::time::Duration;
583 use std::time::Instant;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800584
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700585 static TEST_ALIAS: &str = "test_alias";
Janis Danisevskis77d72042021-01-20 15:36:30 -0800586 static TEST_BLOB1: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
587 static TEST_BLOB2: &[u8] = &[2, 2, 3, 4, 5, 6, 7, 8, 9, 0];
588 static TEST_BLOB3: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
589 static TEST_BLOB4: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
590
591 #[test]
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700592 fn test_entry_db() {
593 let test_dir = TempDir::new("entrydb_test_").expect("Failed to create temp dir.");
594 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
595 .expect("Failed to open database.");
Janis Danisevskis77d72042021-01-20 15:36:30 -0800596
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700597 // Insert three entries for owner 2.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800598 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
599 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
600 db.put(2, "test3", TEST_BLOB3).expect("Failed to insert test3.");
601
602 // Check list returns all inserted aliases.
603 assert_eq!(
604 vec!["test1".to_string(), "test2".to_string(), "test3".to_string(),],
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700605 db.list(2).expect("Failed to list entries.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800606 );
607
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700608 // There should be no entries for owner 1.
609 assert_eq!(Vec::<String>::new(), db.list(1).expect("Failed to list entries."));
Janis Danisevskis77d72042021-01-20 15:36:30 -0800610
611 // Check the content of the three entries.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700612 assert_eq!(Some(TEST_BLOB1), db.get(2, "test1").expect("Failed to get entry.").as_deref());
613 assert_eq!(Some(TEST_BLOB2), db.get(2, "test2").expect("Failed to get entry.").as_deref());
614 assert_eq!(Some(TEST_BLOB3), db.get(2, "test3").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800615
616 // Remove test2 and check and check that it is no longer retrievable.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700617 assert!(db.remove(2, "test2").expect("Failed to remove entry."));
618 assert!(db.get(2, "test2").expect("Failed to get entry.").is_none());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800619
620 // test2 should now no longer be in the list.
621 assert_eq!(
622 vec!["test1".to_string(), "test3".to_string(),],
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700623 db.list(2).expect("Failed to list entries.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800624 );
625
626 // Put on existing alias replaces it.
627 // Verify test1 is TEST_BLOB1.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700628 assert_eq!(Some(TEST_BLOB1), db.get(2, "test1").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800629 db.put(2, "test1", TEST_BLOB4).expect("Failed to replace test1.");
630 // Verify test1 is TEST_BLOB4.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700631 assert_eq!(Some(TEST_BLOB4), db.get(2, "test1").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800632 }
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700633
634 #[test]
Janis Danisevskis5898d152021-06-15 08:23:46 -0700635 fn test_delete_uid() {
636 let test_dir = TempDir::new("test_delete_uid_").expect("Failed to create temp dir.");
637 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
638 .expect("Failed to open database.");
639
640 // Insert three entries for owner 2.
641 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
642 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
643 db.put(3, "test3", TEST_BLOB3).expect("Failed to insert test3.");
644
645 db.remove_uid(2).expect("Failed to remove uid 2");
646
647 assert_eq!(Vec::<String>::new(), db.list(2).expect("Failed to list entries."));
648
649 assert_eq!(vec!["test3".to_string(),], db.list(3).expect("Failed to list entries."));
650 }
651
652 #[test]
653 fn test_delete_user() {
654 let test_dir = TempDir::new("test_delete_user_").expect("Failed to create temp dir.");
655 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
656 .expect("Failed to open database.");
657
658 // Insert three entries for owner 2.
Joel Galenson81a50f22021-07-29 15:39:10 -0700659 db.put(2 + 2 * rustutils::users::AID_USER_OFFSET, "test1", TEST_BLOB1)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700660 .expect("Failed to insert test1.");
Joel Galenson81a50f22021-07-29 15:39:10 -0700661 db.put(4 + 2 * rustutils::users::AID_USER_OFFSET, "test2", TEST_BLOB2)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700662 .expect("Failed to insert test2.");
663 db.put(3, "test3", TEST_BLOB3).expect("Failed to insert test3.");
664
665 db.remove_user(2).expect("Failed to remove user 2");
666
667 assert_eq!(
668 Vec::<String>::new(),
Joel Galenson81a50f22021-07-29 15:39:10 -0700669 db.list(2 + 2 * rustutils::users::AID_USER_OFFSET).expect("Failed to list entries.")
Janis Danisevskis5898d152021-06-15 08:23:46 -0700670 );
671
672 assert_eq!(
673 Vec::<String>::new(),
Joel Galenson81a50f22021-07-29 15:39:10 -0700674 db.list(4 + 2 * rustutils::users::AID_USER_OFFSET).expect("Failed to list entries.")
Janis Danisevskis5898d152021-06-15 08:23:46 -0700675 );
676
677 assert_eq!(vec!["test3".to_string(),], db.list(3).expect("Failed to list entries."));
678 }
679
680 #[test]
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700681 fn concurrent_legacy_keystore_entry_test() -> Result<()> {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700682 let temp_dir = Arc::new(
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700683 TempDir::new("concurrent_legacy_keystore_entry_test_")
684 .expect("Failed to create temp dir."),
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700685 );
686
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700687 let db_path = temp_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME).to_owned();
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700688
689 let test_begin = Instant::now();
690
691 let mut db = DB::new(&db_path).expect("Failed to open database.");
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700692 const ENTRY_COUNT: u32 = 5000u32;
693 const ENTRY_DB_COUNT: u32 = 5000u32;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700694
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700695 let mut actual_entry_count = ENTRY_COUNT;
696 // First insert ENTRY_COUNT entries.
697 for count in 0..ENTRY_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700698 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700699 actual_entry_count = count;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700700 break;
701 }
702 let alias = format!("test_alias_{}", count);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700703 db.put(1, &alias, TEST_BLOB1).expect("Failed to add entry (1).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700704 }
705
706 // Insert more keys from a different thread and into a different namespace.
707 let db_path1 = db_path.clone();
708 let handle1 = thread::spawn(move || {
709 let mut db = DB::new(&db_path1).expect("Failed to open database.");
710
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700711 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700712 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
713 return;
714 }
715 let alias = format!("test_alias_{}", count);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700716 db.put(2, &alias, TEST_BLOB2).expect("Failed to add entry (2).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700717 }
718
719 // Then delete them again.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700720 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700721 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
722 return;
723 }
724 let alias = format!("test_alias_{}", count);
725 db.remove(2, &alias).expect("Remove Failed (2).");
726 }
727 });
728
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700729 // And start deleting the first set of entries.
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700730 let db_path2 = db_path.clone();
731 let handle2 = thread::spawn(move || {
732 let mut db = DB::new(&db_path2).expect("Failed to open database.");
733
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700734 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700735 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
736 return;
737 }
738 let alias = format!("test_alias_{}", count);
739 db.remove(1, &alias).expect("Remove Failed (1)).");
740 }
741 });
742
743 // While a lot of inserting and deleting is going on we have to open database connections
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700744 // successfully and then insert and delete a specific entry.
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700745 let db_path3 = db_path.clone();
746 let handle3 = thread::spawn(move || {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700747 for _count in 0..ENTRY_DB_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700748 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
749 return;
750 }
751 let mut db = DB::new(&db_path3).expect("Failed to open database.");
752
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700753 db.put(3, TEST_ALIAS, TEST_BLOB3).expect("Failed to add entry (3).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700754
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700755 db.remove(3, TEST_ALIAS).expect("Remove failed (3).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700756 }
757 });
758
759 // While thread 3 is inserting and deleting TEST_ALIAS, we try to get the alias.
760 // This may yield an entry or none, but it must not fail.
761 let handle4 = thread::spawn(move || {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700762 for _count in 0..ENTRY_DB_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700763 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
764 return;
765 }
766 let mut db = DB::new(&db_path).expect("Failed to open database.");
767
768 // This may return Some or None but it must not fail.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700769 db.get(3, TEST_ALIAS).expect("Failed to get entry (4).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700770 }
771 });
772
773 handle1.join().expect("Thread 1 panicked.");
774 handle2.join().expect("Thread 2 panicked.");
775 handle3.join().expect("Thread 3 panicked.");
776 handle4.join().expect("Thread 4 panicked.");
777
778 Ok(())
779 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800780}