blob: b826a657999c8553dd00a825c811b664fed3742a [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<()> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800124 self.with_transaction(TransactionBehavior::Immediate, |tx| {
125 tx.execute(
126 "INSERT OR REPLACE INTO profiles (owner, alias, profile) values (?, ?, ?)",
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700127 params![caller_uid, alias, entry,],
Janis Danisevskis77d72042021-01-20 15:36:30 -0800128 )
129 .context("In put: Failed to insert or replace.")?;
130 Ok(())
131 })
132 }
133
134 fn get(&mut self, caller_uid: u32, alias: &str) -> Result<Option<Vec<u8>>> {
135 self.with_transaction(TransactionBehavior::Deferred, |tx| {
136 tx.query_row(
137 "SELECT profile FROM profiles WHERE owner = ? AND alias = ?;",
138 params![caller_uid, alias],
139 |row| row.get(0),
140 )
141 .optional()
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700142 .context("In get: failed loading entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800143 })
144 }
145
146 fn remove(&mut self, caller_uid: u32, alias: &str) -> Result<bool> {
147 let removed = self.with_transaction(TransactionBehavior::Immediate, |tx| {
148 tx.execute(
149 "DELETE FROM profiles WHERE owner = ? AND alias = ?;",
150 params![caller_uid, alias],
151 )
152 .context("In remove: Failed to delete row.")
153 })?;
154 Ok(removed == 1)
155 }
Janis Danisevskis5898d152021-06-15 08:23:46 -0700156
157 fn remove_uid(&mut self, uid: u32) -> Result<()> {
158 self.with_transaction(TransactionBehavior::Immediate, |tx| {
159 tx.execute("DELETE FROM profiles WHERE owner = ?;", params![uid])
160 .context("In remove_uid: Failed to delete.")
161 })?;
162 Ok(())
163 }
164
165 fn remove_user(&mut self, user_id: u32) -> Result<()> {
166 self.with_transaction(TransactionBehavior::Immediate, |tx| {
167 tx.execute(
168 "DELETE FROM profiles WHERE cast ( ( owner/? ) as int) = ?;",
Joel Galenson81a50f22021-07-29 15:39:10 -0700169 params![rustutils::users::AID_USER_OFFSET, user_id],
Janis Danisevskis5898d152021-06-15 08:23:46 -0700170 )
171 .context("In remove_uid: Failed to delete.")
172 })?;
173 Ok(())
174 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800175}
176
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700177/// This is the main LegacyKeystore error type, it wraps binder exceptions and the
178/// LegacyKeystore errors.
Chris Wailes263de9f2022-08-11 15:00:51 -0700179#[derive(Debug, thiserror::Error, PartialEq, Eq)]
Janis Danisevskis77d72042021-01-20 15:36:30 -0800180pub enum Error {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700181 /// Wraps a LegacyKeystore error code.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800182 #[error("Error::Error({0:?})")]
183 Error(i32),
184 /// Wraps a Binder exception code other than a service specific exception.
185 #[error("Binder exception code {0:?}, {1:?}")]
186 Binder(ExceptionCode, i32),
187}
188
189impl Error {
190 /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)`
191 pub fn sys() -> Self {
192 Error::Error(ERROR_SYSTEM_ERROR)
193 }
194
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700195 /// Short hand for `Error::Error(ERROR_ENTRY_NOT_FOUND)`
Janis Danisevskis77d72042021-01-20 15:36:30 -0800196 pub fn not_found() -> Self {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700197 Error::Error(ERROR_ENTRY_NOT_FOUND)
198 }
199
200 /// Short hand for `Error::Error(ERROR_PERMISSION_DENIED)`
201 pub fn perm() -> Self {
202 Error::Error(ERROR_PERMISSION_DENIED)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800203 }
204}
205
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700206/// This function should be used by legacykeystore service calls to translate error conditions
Janis Danisevskis77d72042021-01-20 15:36:30 -0800207/// into service specific exceptions.
208///
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700209/// All error conditions get logged by this function, except for ERROR_ENTRY_NOT_FOUND error.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800210///
211/// `Error::Error(x)` variants get mapped onto a service specific error code of `x`.
212///
213/// All non `Error` error conditions get mapped onto `ERROR_SYSTEM_ERROR`.
214///
215/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
216/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
217/// typically returns Ok(value).
218fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
219where
220 F: FnOnce(U) -> BinderResult<T>,
221{
222 result.map_or_else(
223 |e| {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800224 let root_cause = e.root_cause();
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000225 let (rc, log_error) = match root_cause.downcast_ref::<Error>() {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700226 // Make the entry not found errors silent.
227 Some(Error::Error(ERROR_ENTRY_NOT_FOUND)) => (ERROR_ENTRY_NOT_FOUND, false),
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000228 Some(Error::Error(e)) => (*e, true),
229 Some(Error::Binder(_, _)) | None => (ERROR_SYSTEM_ERROR, true),
Janis Danisevskis77d72042021-01-20 15:36:30 -0800230 };
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000231 if log_error {
232 log::error!("{:?}", e);
233 }
Janis Danisevskisea03cff2021-12-16 08:10:17 -0800234 Err(BinderStatus::new_service_specific_error(
235 rc,
236 anyhow_error_to_cstring(&e).as_deref(),
237 ))
Janis Danisevskis77d72042021-01-20 15:36:30 -0800238 },
239 handle_ok,
240 )
241}
242
Janis Danisevskis5898d152021-06-15 08:23:46 -0700243struct LegacyKeystoreDeleteListener {
244 legacy_keystore: Arc<LegacyKeystore>,
245}
246
247impl DeleteListener for LegacyKeystoreDeleteListener {
248 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()> {
249 self.legacy_keystore.delete_namespace(domain, namespace)
250 }
251 fn delete_user(&self, user_id: u32) -> Result<()> {
252 self.legacy_keystore.delete_user(user_id)
253 }
254}
255
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700256/// Implements ILegacyKeystore AIDL interface.
257pub struct LegacyKeystore {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800258 db_path: PathBuf,
Janis Danisevskis06891072021-02-11 10:28:17 -0800259 async_task: AsyncTask,
260}
261
262struct AsyncState {
263 recently_imported: HashSet<(u32, String)>,
264 legacy_loader: LegacyBlobLoader,
265 db_path: PathBuf,
Janis Danisevskis77d72042021-01-20 15:36:30 -0800266}
267
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700268impl LegacyKeystore {
269 /// Note: The filename was chosen before the purpose of this module was extended.
270 /// It is kept for backward compatibility with early adopters.
271 const LEGACY_KEYSTORE_FILE_NAME: &'static str = "vpnprofilestore.sqlite";
272
Janis Danisevskis5898d152021-06-15 08:23:46 -0700273 const WIFI_NAMESPACE: i64 = 102;
274 const AID_WIFI: u32 = 1010;
275
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700276 /// Creates a new LegacyKeystore instance.
Janis Danisevskis5898d152021-06-15 08:23:46 -0700277 pub fn new_native_binder(
278 path: &Path,
279 ) -> (Box<dyn DeleteListener + Send + Sync + 'static>, Strong<dyn ILegacyKeystore>) {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800280 let mut db_path = path.to_path_buf();
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700281 db_path.push(Self::LEGACY_KEYSTORE_FILE_NAME);
Janis Danisevskis06891072021-02-11 10:28:17 -0800282
Janis Danisevskis5898d152021-06-15 08:23:46 -0700283 let legacy_keystore = Arc::new(Self { db_path, async_task: Default::default() });
284 legacy_keystore.init_shelf(path);
285 let service = LegacyKeystoreService { legacy_keystore: legacy_keystore.clone() };
286 (
287 Box::new(LegacyKeystoreDeleteListener { legacy_keystore }),
288 BnLegacyKeystore::new_binder(service, BinderFeatures::default()),
289 )
Janis Danisevskis77d72042021-01-20 15:36:30 -0800290 }
291
292 fn open_db(&self) -> Result<DB> {
293 DB::new(&self.db_path).context("In open_db: Failed to open db.")
294 }
295
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700296 fn get_effective_uid(uid: i32) -> Result<u32> {
297 const AID_SYSTEM: u32 = 1000;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800298 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700299 let uid = uid as u32;
Janis Danisevskis06891072021-02-11 10:28:17 -0800300
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700301 if uid == UID_SELF as u32 || uid == calling_uid {
302 Ok(calling_uid)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700303 } else if calling_uid == AID_SYSTEM && uid == Self::AID_WIFI {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700304 // The only exception for legacy reasons is allowing SYSTEM to access
305 // the WIFI namespace.
306 // IMPORTANT: If you attempt to add more exceptions, it means you are adding
307 // more callers to this deprecated feature. DON'T!
Janis Danisevskis5898d152021-06-15 08:23:46 -0700308 Ok(Self::AID_WIFI)
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700309 } else {
310 Err(Error::perm()).with_context(|| {
311 format!("In get_effective_uid: caller: {}, requested uid: {}.", calling_uid, uid)
312 })
Janis Danisevskis06891072021-02-11 10:28:17 -0800313 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700314 }
315
316 fn get(&self, alias: &str, uid: i32) -> Result<Vec<u8>> {
317 let mut db = self.open_db().context("In get.")?;
318 let uid = Self::get_effective_uid(uid).context("In get.")?;
319
320 if let Some(entry) = db.get(uid, alias).context("In get: Trying to load entry from DB.")? {
321 return Ok(entry);
322 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800323 if self.get_legacy(uid, alias).context("In get: Trying to import legacy blob.")? {
324 // If we were able to import a legacy blob try again.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700325 if let Some(entry) =
326 db.get(uid, alias).context("In get: Trying to load entry from DB.")?
Janis Danisevskis06891072021-02-11 10:28:17 -0800327 {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700328 return Ok(entry);
Janis Danisevskis06891072021-02-11 10:28:17 -0800329 }
330 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700331 Err(Error::not_found()).context("In get: No such entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800332 }
333
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700334 fn put(&self, alias: &str, uid: i32, entry: &[u8]) -> Result<()> {
335 let uid = Self::get_effective_uid(uid).context("In put.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800336 let mut db = self.open_db().context("In put.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800337 db.put(uid, alias, entry).context("In put: Trying to insert entry into DB.")?;
338 // When replacing an entry, make sure that there is no stale legacy file entry.
339 let _ = self.remove_legacy(uid, alias);
340 Ok(())
Janis Danisevskis77d72042021-01-20 15:36:30 -0800341 }
342
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700343 fn remove(&self, alias: &str, uid: i32) -> Result<()> {
344 let uid = Self::get_effective_uid(uid).context("In remove.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800345 let mut db = self.open_db().context("In remove.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800346
347 if self.remove_legacy(uid, alias).context("In remove: trying to remove legacy entry")? {
348 return Ok(());
349 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700350 let removed =
351 db.remove(uid, alias).context("In remove: Trying to remove entry from DB.")?;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800352 if removed {
353 Ok(())
354 } else {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700355 Err(Error::not_found()).context("In remove: No such entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800356 }
357 }
358
Janis Danisevskis5898d152021-06-15 08:23:46 -0700359 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()> {
360 let uid = match domain {
361 Domain::APP => namespace as u32,
362 Domain::SELINUX => {
363 if namespace == Self::WIFI_NAMESPACE {
364 // Namespace WIFI gets mapped to AID_WIFI.
365 Self::AID_WIFI
366 } else {
367 // Nothing to do for any other namespace.
368 return Ok(());
369 }
370 }
371 _ => return Ok(()),
372 };
373
374 if let Err(e) = self.bulk_delete_uid(uid) {
375 log::warn!("In LegacyKeystore::delete_namespace: {:?}", e);
376 }
377 let mut db = self.open_db().context("In LegacyKeystore::delete_namespace.")?;
378 db.remove_uid(uid).context("In LegacyKeystore::delete_namespace.")
379 }
380
381 fn delete_user(&self, user_id: u32) -> Result<()> {
382 if let Err(e) = self.bulk_delete_user(user_id) {
383 log::warn!("In LegacyKeystore::delete_user: {:?}", e);
384 }
385 let mut db = self.open_db().context("In LegacyKeystore::delete_user.")?;
386 db.remove_user(user_id).context("In LegacyKeystore::delete_user.")
387 }
388
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700389 fn list(&self, prefix: &str, uid: i32) -> Result<Vec<String>> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800390 let mut db = self.open_db().context("In list.")?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700391 let uid = Self::get_effective_uid(uid).context("In list.")?;
392 let mut result = self.list_legacy(uid).context("In list.")?;
393 result.append(&mut db.list(uid).context("In list: Trying to get list of entries.")?);
Charisee28e6f0b2022-09-15 01:07:46 +0000394 result.retain(|s| s.starts_with(prefix));
Janis Danisevskis06891072021-02-11 10:28:17 -0800395 result.sort_unstable();
396 result.dedup();
397 Ok(result)
398 }
399
400 fn init_shelf(&self, path: &Path) {
401 let mut db_path = path.to_path_buf();
402 self.async_task.queue_hi(move |shelf| {
403 let legacy_loader = LegacyBlobLoader::new(&db_path);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700404 db_path.push(Self::LEGACY_KEYSTORE_FILE_NAME);
Janis Danisevskis06891072021-02-11 10:28:17 -0800405
406 shelf.put(AsyncState { legacy_loader, db_path, recently_imported: Default::default() });
407 })
408 }
409
410 fn do_serialized<F, T: Send + 'static>(&self, f: F) -> Result<T>
411 where
412 F: FnOnce(&mut AsyncState) -> Result<T> + Send + 'static,
413 {
414 let (sender, receiver) = std::sync::mpsc::channel::<Result<T>>();
415 self.async_task.queue_hi(move |shelf| {
416 let state = shelf.get_downcast_mut::<AsyncState>().expect("Failed to get shelf.");
417 sender.send(f(state)).expect("Failed to send result.");
418 });
419 receiver.recv().context("In do_serialized: Failed to receive result.")?
420 }
421
422 fn list_legacy(&self, uid: u32) -> Result<Vec<String>> {
423 self.do_serialized(move |state| {
424 state
425 .legacy_loader
Janis Danisevskis5898d152021-06-15 08:23:46 -0700426 .list_legacy_keystore_entries_for_uid(uid)
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700427 .context("Trying to list legacy keystore entries.")
Janis Danisevskis06891072021-02-11 10:28:17 -0800428 })
429 .context("In list_legacy.")
430 }
431
432 fn get_legacy(&self, uid: u32, alias: &str) -> Result<bool> {
433 let alias = alias.to_string();
434 self.do_serialized(move |state| {
435 if state.recently_imported.contains(&(uid, alias.clone())) {
436 return Ok(true);
437 }
438 let mut db = DB::new(&state.db_path).context("In open_db: Failed to open db.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800439 let imported =
440 Self::import_one_legacy_entry(uid, &alias, &state.legacy_loader, &mut db)
441 .context("Trying to import legacy keystore entries.")?;
442 if imported {
Janis Danisevskis06891072021-02-11 10:28:17 -0800443 state.recently_imported.insert((uid, alias));
444 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800445 Ok(imported)
Janis Danisevskis06891072021-02-11 10:28:17 -0800446 })
447 .context("In get_legacy.")
448 }
449
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800450 fn remove_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(false);
455 }
456 state
457 .legacy_loader
458 .remove_legacy_keystore_entry(uid, &alias)
459 .context("Trying to remove legacy entry.")
460 })
461 }
462
Janis Danisevskis5898d152021-06-15 08:23:46 -0700463 fn bulk_delete_uid(&self, uid: u32) -> Result<()> {
464 self.do_serialized(move |state| {
465 let entries = state
466 .legacy_loader
467 .list_legacy_keystore_entries_for_uid(uid)
468 .context("In bulk_delete_uid: Trying to list entries.")?;
469 for alias in entries.iter() {
470 if let Err(e) = state.legacy_loader.remove_legacy_keystore_entry(uid, alias) {
471 log::warn!("In bulk_delete_uid: Failed to delete legacy entry. {:?}", e);
472 }
473 }
474 Ok(())
475 })
476 }
477
478 fn bulk_delete_user(&self, user_id: u32) -> Result<()> {
479 self.do_serialized(move |state| {
480 let entries = state
481 .legacy_loader
482 .list_legacy_keystore_entries_for_user(user_id)
483 .context("In bulk_delete_user: Trying to list entries.")?;
484 for (uid, entries) in entries.iter() {
485 for alias in entries.iter() {
486 if let Err(e) = state.legacy_loader.remove_legacy_keystore_entry(*uid, alias) {
487 log::warn!("In bulk_delete_user: Failed to delete legacy entry. {:?}", e);
488 }
489 }
490 }
491 Ok(())
492 })
493 }
494
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800495 fn import_one_legacy_entry(
Janis Danisevskis06891072021-02-11 10:28:17 -0800496 uid: u32,
497 alias: &str,
498 legacy_loader: &LegacyBlobLoader,
499 db: &mut DB,
500 ) -> Result<bool> {
501 let blob = legacy_loader
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800502 .read_legacy_keystore_entry(uid, alias, |ciphertext, iv, tag, _salt, _key_size| {
Charisee03e00842023-01-25 01:41:23 +0000503 if let Some(key) =
504 SUPER_KEY.read().unwrap().get_per_boot_key_by_user_id(uid_to_android_user(uid))
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800505 {
506 key.decrypt(ciphertext, iv, tag)
507 } else {
508 Err(Error::sys()).context("No key found for user. Device may be locked.")
509 }
510 })
511 .context("In import_one_legacy_entry: Trying to read legacy keystore entry.")?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700512 if let Some(entry) = blob {
513 db.put(uid, alias, &entry)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800514 .context("In import_one_legacy_entry: Trying to insert entry into DB.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800515 legacy_loader
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700516 .remove_legacy_keystore_entry(uid, alias)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800517 .context("In import_one_legacy_entry: Trying to delete legacy keystore entry.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800518 Ok(true)
519 } else {
520 Ok(false)
521 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800522 }
523}
524
Janis Danisevskis5898d152021-06-15 08:23:46 -0700525struct LegacyKeystoreService {
526 legacy_keystore: Arc<LegacyKeystore>,
527}
Janis Danisevskis77d72042021-01-20 15:36:30 -0800528
Janis Danisevskis5898d152021-06-15 08:23:46 -0700529impl binder::Interface for LegacyKeystoreService {}
530
531impl ILegacyKeystore for LegacyKeystoreService {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700532 fn get(&self, alias: &str, uid: i32) -> BinderResult<Vec<u8>> {
533 let _wp = wd::watch_millis("ILegacyKeystore::get", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700534 map_or_log_err(self.legacy_keystore.get(alias, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800535 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700536 fn put(&self, alias: &str, uid: i32, entry: &[u8]) -> BinderResult<()> {
537 let _wp = wd::watch_millis("ILegacyKeystore::put", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700538 map_or_log_err(self.legacy_keystore.put(alias, uid, entry), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800539 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700540 fn remove(&self, alias: &str, uid: i32) -> BinderResult<()> {
541 let _wp = wd::watch_millis("ILegacyKeystore::remove", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700542 map_or_log_err(self.legacy_keystore.remove(alias, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800543 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700544 fn list(&self, prefix: &str, uid: i32) -> BinderResult<Vec<String>> {
545 let _wp = wd::watch_millis("ILegacyKeystore::list", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700546 map_or_log_err(self.legacy_keystore.list(prefix, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800547 }
548}
549
550#[cfg(test)]
551mod db_test {
552 use super::*;
553 use keystore2_test_utils::TempDir;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700554 use std::sync::Arc;
555 use std::thread;
556 use std::time::Duration;
557 use std::time::Instant;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800558
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700559 static TEST_ALIAS: &str = "test_alias";
Janis Danisevskis77d72042021-01-20 15:36:30 -0800560 static TEST_BLOB1: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
561 static TEST_BLOB2: &[u8] = &[2, 2, 3, 4, 5, 6, 7, 8, 9, 0];
562 static TEST_BLOB3: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
563 static TEST_BLOB4: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
564
565 #[test]
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700566 fn test_entry_db() {
567 let test_dir = TempDir::new("entrydb_test_").expect("Failed to create temp dir.");
568 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
569 .expect("Failed to open database.");
Janis Danisevskis77d72042021-01-20 15:36:30 -0800570
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700571 // Insert three entries for owner 2.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800572 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
573 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
574 db.put(2, "test3", TEST_BLOB3).expect("Failed to insert test3.");
575
576 // Check list returns all inserted aliases.
577 assert_eq!(
578 vec!["test1".to_string(), "test2".to_string(), "test3".to_string(),],
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700579 db.list(2).expect("Failed to list entries.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800580 );
581
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700582 // There should be no entries for owner 1.
583 assert_eq!(Vec::<String>::new(), db.list(1).expect("Failed to list entries."));
Janis Danisevskis77d72042021-01-20 15:36:30 -0800584
585 // Check the content of the three entries.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700586 assert_eq!(Some(TEST_BLOB1), db.get(2, "test1").expect("Failed to get entry.").as_deref());
587 assert_eq!(Some(TEST_BLOB2), db.get(2, "test2").expect("Failed to get entry.").as_deref());
588 assert_eq!(Some(TEST_BLOB3), db.get(2, "test3").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800589
590 // Remove test2 and check and check that it is no longer retrievable.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700591 assert!(db.remove(2, "test2").expect("Failed to remove entry."));
592 assert!(db.get(2, "test2").expect("Failed to get entry.").is_none());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800593
594 // test2 should now no longer be in the list.
595 assert_eq!(
596 vec!["test1".to_string(), "test3".to_string(),],
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700597 db.list(2).expect("Failed to list entries.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800598 );
599
600 // Put on existing alias replaces it.
601 // Verify test1 is TEST_BLOB1.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700602 assert_eq!(Some(TEST_BLOB1), db.get(2, "test1").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800603 db.put(2, "test1", TEST_BLOB4).expect("Failed to replace test1.");
604 // Verify test1 is TEST_BLOB4.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700605 assert_eq!(Some(TEST_BLOB4), db.get(2, "test1").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800606 }
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700607
608 #[test]
Janis Danisevskis5898d152021-06-15 08:23:46 -0700609 fn test_delete_uid() {
610 let test_dir = TempDir::new("test_delete_uid_").expect("Failed to create temp dir.");
611 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
612 .expect("Failed to open database.");
613
614 // Insert three entries for owner 2.
615 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
616 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
617 db.put(3, "test3", TEST_BLOB3).expect("Failed to insert test3.");
618
619 db.remove_uid(2).expect("Failed to remove uid 2");
620
621 assert_eq!(Vec::<String>::new(), db.list(2).expect("Failed to list entries."));
622
623 assert_eq!(vec!["test3".to_string(),], db.list(3).expect("Failed to list entries."));
624 }
625
626 #[test]
627 fn test_delete_user() {
628 let test_dir = TempDir::new("test_delete_user_").expect("Failed to create temp dir.");
629 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
630 .expect("Failed to open database.");
631
632 // Insert three entries for owner 2.
Joel Galenson81a50f22021-07-29 15:39:10 -0700633 db.put(2 + 2 * rustutils::users::AID_USER_OFFSET, "test1", TEST_BLOB1)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700634 .expect("Failed to insert test1.");
Joel Galenson81a50f22021-07-29 15:39:10 -0700635 db.put(4 + 2 * rustutils::users::AID_USER_OFFSET, "test2", TEST_BLOB2)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700636 .expect("Failed to insert test2.");
637 db.put(3, "test3", TEST_BLOB3).expect("Failed to insert test3.");
638
639 db.remove_user(2).expect("Failed to remove user 2");
640
641 assert_eq!(
642 Vec::<String>::new(),
Joel Galenson81a50f22021-07-29 15:39:10 -0700643 db.list(2 + 2 * rustutils::users::AID_USER_OFFSET).expect("Failed to list entries.")
Janis Danisevskis5898d152021-06-15 08:23:46 -0700644 );
645
646 assert_eq!(
647 Vec::<String>::new(),
Joel Galenson81a50f22021-07-29 15:39:10 -0700648 db.list(4 + 2 * rustutils::users::AID_USER_OFFSET).expect("Failed to list entries.")
Janis Danisevskis5898d152021-06-15 08:23:46 -0700649 );
650
651 assert_eq!(vec!["test3".to_string(),], db.list(3).expect("Failed to list entries."));
652 }
653
654 #[test]
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700655 fn concurrent_legacy_keystore_entry_test() -> Result<()> {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700656 let temp_dir = Arc::new(
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700657 TempDir::new("concurrent_legacy_keystore_entry_test_")
658 .expect("Failed to create temp dir."),
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700659 );
660
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700661 let db_path = temp_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME).to_owned();
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700662
663 let test_begin = Instant::now();
664
665 let mut db = DB::new(&db_path).expect("Failed to open database.");
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700666 const ENTRY_COUNT: u32 = 5000u32;
667 const ENTRY_DB_COUNT: u32 = 5000u32;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700668
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700669 let mut actual_entry_count = ENTRY_COUNT;
670 // First insert ENTRY_COUNT entries.
671 for count in 0..ENTRY_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700672 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700673 actual_entry_count = count;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700674 break;
675 }
676 let alias = format!("test_alias_{}", count);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700677 db.put(1, &alias, TEST_BLOB1).expect("Failed to add entry (1).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700678 }
679
680 // Insert more keys from a different thread and into a different namespace.
681 let db_path1 = db_path.clone();
682 let handle1 = thread::spawn(move || {
683 let mut db = DB::new(&db_path1).expect("Failed to open database.");
684
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700685 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700686 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
687 return;
688 }
689 let alias = format!("test_alias_{}", count);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700690 db.put(2, &alias, TEST_BLOB2).expect("Failed to add entry (2).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700691 }
692
693 // Then delete them again.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700694 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700695 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
696 return;
697 }
698 let alias = format!("test_alias_{}", count);
699 db.remove(2, &alias).expect("Remove Failed (2).");
700 }
701 });
702
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700703 // And start deleting the first set of entries.
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700704 let db_path2 = db_path.clone();
705 let handle2 = thread::spawn(move || {
706 let mut db = DB::new(&db_path2).expect("Failed to open database.");
707
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700708 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700709 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
710 return;
711 }
712 let alias = format!("test_alias_{}", count);
713 db.remove(1, &alias).expect("Remove Failed (1)).");
714 }
715 });
716
717 // While a lot of inserting and deleting is going on we have to open database connections
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700718 // successfully and then insert and delete a specific entry.
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700719 let db_path3 = db_path.clone();
720 let handle3 = thread::spawn(move || {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700721 for _count in 0..ENTRY_DB_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700722 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
723 return;
724 }
725 let mut db = DB::new(&db_path3).expect("Failed to open database.");
726
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700727 db.put(3, TEST_ALIAS, TEST_BLOB3).expect("Failed to add entry (3).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700728
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700729 db.remove(3, TEST_ALIAS).expect("Remove failed (3).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700730 }
731 });
732
733 // While thread 3 is inserting and deleting TEST_ALIAS, we try to get the alias.
734 // This may yield an entry or none, but it must not fail.
735 let handle4 = thread::spawn(move || {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700736 for _count in 0..ENTRY_DB_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700737 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
738 return;
739 }
740 let mut db = DB::new(&db_path).expect("Failed to open database.");
741
742 // This may return Some or None but it must not fail.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700743 db.get(3, TEST_ALIAS).expect("Failed to get entry (4).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700744 }
745 });
746
747 handle1.join().expect("Thread 1 panicked.");
748 handle2.join().expect("Thread 2 panicked.");
749 handle3.join().expect("Thread 3 panicked.");
750 handle4.join().expect("Thread 4 panicked.");
751
752 Ok(())
753 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800754}