blob: e2d952d9f1913fa439e0d94f817208de7a6b86a7 [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};
Janis Danisevskis77d72042021-01-20 15:36:30 -080032use rusqlite::{
33 params, Connection, OptionalExtension, Transaction, TransactionBehavior, NO_PARAMS,
34};
Janis Danisevskis5898d152021-06-15 08:23:46 -070035use std::sync::Arc;
Janis Danisevskis06891072021-02-11 10:28:17 -080036use std::{
37 collections::HashSet,
38 path::{Path, PathBuf},
39};
Janis Danisevskis77d72042021-01-20 15:36:30 -080040
41struct DB {
42 conn: Connection,
43}
44
45impl DB {
46 fn new(db_file: &Path) -> Result<Self> {
47 let mut db = Self {
48 conn: Connection::open(db_file).context("Failed to initialize SQLite connection.")?,
49 };
Janis Danisevskis1be7e182021-04-12 14:31:12 -070050
Janis Danisevskis3eb829d2021-06-14 14:18:20 -070051 db.init_tables().context("Trying to initialize legacy keystore db.")?;
Janis Danisevskis77d72042021-01-20 15:36:30 -080052 Ok(db)
53 }
54
55 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
56 where
57 F: Fn(&Transaction) -> Result<T>,
58 {
59 loop {
60 match self
61 .conn
62 .transaction_with_behavior(behavior)
63 .context("In with_transaction.")
64 .and_then(|tx| f(&tx).map(|result| (result, tx)))
65 .and_then(|(result, tx)| {
66 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
67 Ok(result)
68 }) {
69 Ok(result) => break Ok(result),
70 Err(e) => {
71 if Self::is_locked_error(&e) {
72 std::thread::sleep(std::time::Duration::from_micros(500));
73 continue;
74 } else {
75 return Err(e).context("In with_transaction.");
76 }
77 }
78 }
79 }
80 }
81
82 fn is_locked_error(e: &anyhow::Error) -> bool {
Janis Danisevskis13f09152021-04-19 09:55:15 -070083 matches!(
84 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
85 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
86 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
87 )
Janis Danisevskis77d72042021-01-20 15:36:30 -080088 }
89
90 fn init_tables(&mut self) -> Result<()> {
91 self.with_transaction(TransactionBehavior::Immediate, |tx| {
92 tx.execute(
93 "CREATE TABLE IF NOT EXISTS profiles (
94 owner INTEGER,
95 alias BLOB,
96 profile BLOB,
97 UNIQUE(owner, alias));",
98 NO_PARAMS,
99 )
100 .context("Failed to initialize \"profiles\" table.")?;
101 Ok(())
102 })
103 }
104
105 fn list(&mut self, caller_uid: u32) -> Result<Vec<String>> {
106 self.with_transaction(TransactionBehavior::Deferred, |tx| {
107 let mut stmt = tx
108 .prepare("SELECT alias FROM profiles WHERE owner = ? ORDER BY alias ASC;")
109 .context("In list: Failed to prepare statement.")?;
110
111 let aliases = stmt
112 .query_map(params![caller_uid], |row| row.get(0))?
113 .collect::<rusqlite::Result<Vec<String>>>()
114 .context("In list: query_map failed.");
115 aliases
116 })
117 }
118
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700119 fn put(&mut self, caller_uid: u32, alias: &str, entry: &[u8]) -> Result<()> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800120 self.with_transaction(TransactionBehavior::Immediate, |tx| {
121 tx.execute(
122 "INSERT OR REPLACE INTO profiles (owner, alias, profile) values (?, ?, ?)",
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700123 params![caller_uid, alias, entry,],
Janis Danisevskis77d72042021-01-20 15:36:30 -0800124 )
125 .context("In put: Failed to insert or replace.")?;
126 Ok(())
127 })
128 }
129
130 fn get(&mut self, caller_uid: u32, alias: &str) -> Result<Option<Vec<u8>>> {
131 self.with_transaction(TransactionBehavior::Deferred, |tx| {
132 tx.query_row(
133 "SELECT profile FROM profiles WHERE owner = ? AND alias = ?;",
134 params![caller_uid, alias],
135 |row| row.get(0),
136 )
137 .optional()
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700138 .context("In get: failed loading entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800139 })
140 }
141
142 fn remove(&mut self, caller_uid: u32, alias: &str) -> Result<bool> {
143 let removed = self.with_transaction(TransactionBehavior::Immediate, |tx| {
144 tx.execute(
145 "DELETE FROM profiles WHERE owner = ? AND alias = ?;",
146 params![caller_uid, alias],
147 )
148 .context("In remove: Failed to delete row.")
149 })?;
150 Ok(removed == 1)
151 }
Janis Danisevskis5898d152021-06-15 08:23:46 -0700152
153 fn remove_uid(&mut self, uid: u32) -> Result<()> {
154 self.with_transaction(TransactionBehavior::Immediate, |tx| {
155 tx.execute("DELETE FROM profiles WHERE owner = ?;", params![uid])
156 .context("In remove_uid: Failed to delete.")
157 })?;
158 Ok(())
159 }
160
161 fn remove_user(&mut self, user_id: u32) -> Result<()> {
162 self.with_transaction(TransactionBehavior::Immediate, |tx| {
163 tx.execute(
164 "DELETE FROM profiles WHERE cast ( ( owner/? ) as int) = ?;",
Joel Galenson81a50f22021-07-29 15:39:10 -0700165 params![rustutils::users::AID_USER_OFFSET, user_id],
Janis Danisevskis5898d152021-06-15 08:23:46 -0700166 )
167 .context("In remove_uid: Failed to delete.")
168 })?;
169 Ok(())
170 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800171}
172
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700173/// This is the main LegacyKeystore error type, it wraps binder exceptions and the
174/// LegacyKeystore errors.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800175#[derive(Debug, thiserror::Error, PartialEq)]
176pub enum Error {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700177 /// Wraps a LegacyKeystore error code.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800178 #[error("Error::Error({0:?})")]
179 Error(i32),
180 /// Wraps a Binder exception code other than a service specific exception.
181 #[error("Binder exception code {0:?}, {1:?}")]
182 Binder(ExceptionCode, i32),
183}
184
185impl Error {
186 /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)`
187 pub fn sys() -> Self {
188 Error::Error(ERROR_SYSTEM_ERROR)
189 }
190
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700191 /// Short hand for `Error::Error(ERROR_ENTRY_NOT_FOUND)`
Janis Danisevskis77d72042021-01-20 15:36:30 -0800192 pub fn not_found() -> Self {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700193 Error::Error(ERROR_ENTRY_NOT_FOUND)
194 }
195
196 /// Short hand for `Error::Error(ERROR_PERMISSION_DENIED)`
197 pub fn perm() -> Self {
198 Error::Error(ERROR_PERMISSION_DENIED)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800199 }
200}
201
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700202/// This function should be used by legacykeystore service calls to translate error conditions
Janis Danisevskis77d72042021-01-20 15:36:30 -0800203/// into service specific exceptions.
204///
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700205/// All error conditions get logged by this function, except for ERROR_ENTRY_NOT_FOUND error.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800206///
207/// `Error::Error(x)` variants get mapped onto a service specific error code of `x`.
208///
209/// All non `Error` error conditions get mapped onto `ERROR_SYSTEM_ERROR`.
210///
211/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
212/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
213/// typically returns Ok(value).
214fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
215where
216 F: FnOnce(U) -> BinderResult<T>,
217{
218 result.map_or_else(
219 |e| {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800220 let root_cause = e.root_cause();
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000221 let (rc, log_error) = match root_cause.downcast_ref::<Error>() {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700222 // Make the entry not found errors silent.
223 Some(Error::Error(ERROR_ENTRY_NOT_FOUND)) => (ERROR_ENTRY_NOT_FOUND, false),
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000224 Some(Error::Error(e)) => (*e, true),
225 Some(Error::Binder(_, _)) | None => (ERROR_SYSTEM_ERROR, true),
Janis Danisevskis77d72042021-01-20 15:36:30 -0800226 };
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000227 if log_error {
228 log::error!("{:?}", e);
229 }
Janis Danisevskisea03cff2021-12-16 08:10:17 -0800230 Err(BinderStatus::new_service_specific_error(
231 rc,
232 anyhow_error_to_cstring(&e).as_deref(),
233 ))
Janis Danisevskis77d72042021-01-20 15:36:30 -0800234 },
235 handle_ok,
236 )
237}
238
Janis Danisevskis5898d152021-06-15 08:23:46 -0700239struct LegacyKeystoreDeleteListener {
240 legacy_keystore: Arc<LegacyKeystore>,
241}
242
243impl DeleteListener for LegacyKeystoreDeleteListener {
244 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()> {
245 self.legacy_keystore.delete_namespace(domain, namespace)
246 }
247 fn delete_user(&self, user_id: u32) -> Result<()> {
248 self.legacy_keystore.delete_user(user_id)
249 }
250}
251
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700252/// Implements ILegacyKeystore AIDL interface.
253pub struct LegacyKeystore {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800254 db_path: PathBuf,
Janis Danisevskis06891072021-02-11 10:28:17 -0800255 async_task: AsyncTask,
256}
257
258struct AsyncState {
259 recently_imported: HashSet<(u32, String)>,
260 legacy_loader: LegacyBlobLoader,
261 db_path: PathBuf,
Janis Danisevskis77d72042021-01-20 15:36:30 -0800262}
263
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700264impl LegacyKeystore {
265 /// Note: The filename was chosen before the purpose of this module was extended.
266 /// It is kept for backward compatibility with early adopters.
267 const LEGACY_KEYSTORE_FILE_NAME: &'static str = "vpnprofilestore.sqlite";
268
Janis Danisevskis5898d152021-06-15 08:23:46 -0700269 const WIFI_NAMESPACE: i64 = 102;
270 const AID_WIFI: u32 = 1010;
271
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700272 /// Creates a new LegacyKeystore instance.
Janis Danisevskis5898d152021-06-15 08:23:46 -0700273 pub fn new_native_binder(
274 path: &Path,
275 ) -> (Box<dyn DeleteListener + Send + Sync + 'static>, Strong<dyn ILegacyKeystore>) {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800276 let mut db_path = path.to_path_buf();
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700277 db_path.push(Self::LEGACY_KEYSTORE_FILE_NAME);
Janis Danisevskis06891072021-02-11 10:28:17 -0800278
Janis Danisevskis5898d152021-06-15 08:23:46 -0700279 let legacy_keystore = Arc::new(Self { db_path, async_task: Default::default() });
280 legacy_keystore.init_shelf(path);
281 let service = LegacyKeystoreService { legacy_keystore: legacy_keystore.clone() };
282 (
283 Box::new(LegacyKeystoreDeleteListener { legacy_keystore }),
284 BnLegacyKeystore::new_binder(service, BinderFeatures::default()),
285 )
Janis Danisevskis77d72042021-01-20 15:36:30 -0800286 }
287
288 fn open_db(&self) -> Result<DB> {
289 DB::new(&self.db_path).context("In open_db: Failed to open db.")
290 }
291
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700292 fn get_effective_uid(uid: i32) -> Result<u32> {
293 const AID_SYSTEM: u32 = 1000;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800294 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700295 let uid = uid as u32;
Janis Danisevskis06891072021-02-11 10:28:17 -0800296
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700297 if uid == UID_SELF as u32 || uid == calling_uid {
298 Ok(calling_uid)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700299 } else if calling_uid == AID_SYSTEM && uid == Self::AID_WIFI {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700300 // The only exception for legacy reasons is allowing SYSTEM to access
301 // the WIFI namespace.
302 // IMPORTANT: If you attempt to add more exceptions, it means you are adding
303 // more callers to this deprecated feature. DON'T!
Janis Danisevskis5898d152021-06-15 08:23:46 -0700304 Ok(Self::AID_WIFI)
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700305 } else {
306 Err(Error::perm()).with_context(|| {
307 format!("In get_effective_uid: caller: {}, requested uid: {}.", calling_uid, uid)
308 })
Janis Danisevskis06891072021-02-11 10:28:17 -0800309 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700310 }
311
312 fn get(&self, alias: &str, uid: i32) -> Result<Vec<u8>> {
313 let mut db = self.open_db().context("In get.")?;
314 let uid = Self::get_effective_uid(uid).context("In get.")?;
315
316 if let Some(entry) = db.get(uid, alias).context("In get: Trying to load entry from DB.")? {
317 return Ok(entry);
318 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800319 if self.get_legacy(uid, alias).context("In get: Trying to import legacy blob.")? {
320 // If we were able to import a legacy blob try again.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700321 if let Some(entry) =
322 db.get(uid, alias).context("In get: Trying to load entry from DB.")?
Janis Danisevskis06891072021-02-11 10:28:17 -0800323 {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700324 return Ok(entry);
Janis Danisevskis06891072021-02-11 10:28:17 -0800325 }
326 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700327 Err(Error::not_found()).context("In get: No such entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800328 }
329
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700330 fn put(&self, alias: &str, uid: i32, entry: &[u8]) -> Result<()> {
331 let uid = Self::get_effective_uid(uid).context("In put.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800332 let mut db = self.open_db().context("In put.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800333 db.put(uid, alias, entry).context("In put: Trying to insert entry into DB.")?;
334 // When replacing an entry, make sure that there is no stale legacy file entry.
335 let _ = self.remove_legacy(uid, alias);
336 Ok(())
Janis Danisevskis77d72042021-01-20 15:36:30 -0800337 }
338
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700339 fn remove(&self, alias: &str, uid: i32) -> Result<()> {
340 let uid = Self::get_effective_uid(uid).context("In remove.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800341 let mut db = self.open_db().context("In remove.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800342
343 if self.remove_legacy(uid, alias).context("In remove: trying to remove legacy entry")? {
344 return Ok(());
345 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700346 let removed =
347 db.remove(uid, alias).context("In remove: Trying to remove entry from DB.")?;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800348 if removed {
349 Ok(())
350 } else {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700351 Err(Error::not_found()).context("In remove: No such entry.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800352 }
353 }
354
Janis Danisevskis5898d152021-06-15 08:23:46 -0700355 fn delete_namespace(&self, domain: Domain, namespace: i64) -> Result<()> {
356 let uid = match domain {
357 Domain::APP => namespace as u32,
358 Domain::SELINUX => {
359 if namespace == Self::WIFI_NAMESPACE {
360 // Namespace WIFI gets mapped to AID_WIFI.
361 Self::AID_WIFI
362 } else {
363 // Nothing to do for any other namespace.
364 return Ok(());
365 }
366 }
367 _ => return Ok(()),
368 };
369
370 if let Err(e) = self.bulk_delete_uid(uid) {
371 log::warn!("In LegacyKeystore::delete_namespace: {:?}", e);
372 }
373 let mut db = self.open_db().context("In LegacyKeystore::delete_namespace.")?;
374 db.remove_uid(uid).context("In LegacyKeystore::delete_namespace.")
375 }
376
377 fn delete_user(&self, user_id: u32) -> Result<()> {
378 if let Err(e) = self.bulk_delete_user(user_id) {
379 log::warn!("In LegacyKeystore::delete_user: {:?}", e);
380 }
381 let mut db = self.open_db().context("In LegacyKeystore::delete_user.")?;
382 db.remove_user(user_id).context("In LegacyKeystore::delete_user.")
383 }
384
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700385 fn list(&self, prefix: &str, uid: i32) -> Result<Vec<String>> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800386 let mut db = self.open_db().context("In list.")?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700387 let uid = Self::get_effective_uid(uid).context("In list.")?;
388 let mut result = self.list_legacy(uid).context("In list.")?;
389 result.append(&mut db.list(uid).context("In list: Trying to get list of entries.")?);
Janis Danisevskis06891072021-02-11 10:28:17 -0800390 result = result.into_iter().filter(|s| s.starts_with(prefix)).collect();
391 result.sort_unstable();
392 result.dedup();
393 Ok(result)
394 }
395
396 fn init_shelf(&self, path: &Path) {
397 let mut db_path = path.to_path_buf();
398 self.async_task.queue_hi(move |shelf| {
399 let legacy_loader = LegacyBlobLoader::new(&db_path);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700400 db_path.push(Self::LEGACY_KEYSTORE_FILE_NAME);
Janis Danisevskis06891072021-02-11 10:28:17 -0800401
402 shelf.put(AsyncState { legacy_loader, db_path, recently_imported: Default::default() });
403 })
404 }
405
406 fn do_serialized<F, T: Send + 'static>(&self, f: F) -> Result<T>
407 where
408 F: FnOnce(&mut AsyncState) -> Result<T> + Send + 'static,
409 {
410 let (sender, receiver) = std::sync::mpsc::channel::<Result<T>>();
411 self.async_task.queue_hi(move |shelf| {
412 let state = shelf.get_downcast_mut::<AsyncState>().expect("Failed to get shelf.");
413 sender.send(f(state)).expect("Failed to send result.");
414 });
415 receiver.recv().context("In do_serialized: Failed to receive result.")?
416 }
417
418 fn list_legacy(&self, uid: u32) -> Result<Vec<String>> {
419 self.do_serialized(move |state| {
420 state
421 .legacy_loader
Janis Danisevskis5898d152021-06-15 08:23:46 -0700422 .list_legacy_keystore_entries_for_uid(uid)
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700423 .context("Trying to list legacy keystore entries.")
Janis Danisevskis06891072021-02-11 10:28:17 -0800424 })
425 .context("In list_legacy.")
426 }
427
428 fn get_legacy(&self, uid: u32, alias: &str) -> Result<bool> {
429 let alias = alias.to_string();
430 self.do_serialized(move |state| {
431 if state.recently_imported.contains(&(uid, alias.clone())) {
432 return Ok(true);
433 }
434 let mut db = DB::new(&state.db_path).context("In open_db: Failed to open db.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800435 let imported =
436 Self::import_one_legacy_entry(uid, &alias, &state.legacy_loader, &mut db)
437 .context("Trying to import legacy keystore entries.")?;
438 if imported {
Janis Danisevskis06891072021-02-11 10:28:17 -0800439 state.recently_imported.insert((uid, alias));
440 }
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800441 Ok(imported)
Janis Danisevskis06891072021-02-11 10:28:17 -0800442 })
443 .context("In get_legacy.")
444 }
445
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800446 fn remove_legacy(&self, uid: u32, alias: &str) -> Result<bool> {
447 let alias = alias.to_string();
448 self.do_serialized(move |state| {
449 if state.recently_imported.contains(&(uid, alias.clone())) {
450 return Ok(false);
451 }
452 state
453 .legacy_loader
454 .remove_legacy_keystore_entry(uid, &alias)
455 .context("Trying to remove legacy entry.")
456 })
457 }
458
Janis Danisevskis5898d152021-06-15 08:23:46 -0700459 fn bulk_delete_uid(&self, uid: u32) -> Result<()> {
460 self.do_serialized(move |state| {
461 let entries = state
462 .legacy_loader
463 .list_legacy_keystore_entries_for_uid(uid)
464 .context("In bulk_delete_uid: Trying to list entries.")?;
465 for alias in entries.iter() {
466 if let Err(e) = state.legacy_loader.remove_legacy_keystore_entry(uid, alias) {
467 log::warn!("In bulk_delete_uid: Failed to delete legacy entry. {:?}", e);
468 }
469 }
470 Ok(())
471 })
472 }
473
474 fn bulk_delete_user(&self, user_id: u32) -> Result<()> {
475 self.do_serialized(move |state| {
476 let entries = state
477 .legacy_loader
478 .list_legacy_keystore_entries_for_user(user_id)
479 .context("In bulk_delete_user: Trying to list entries.")?;
480 for (uid, entries) in entries.iter() {
481 for alias in entries.iter() {
482 if let Err(e) = state.legacy_loader.remove_legacy_keystore_entry(*uid, alias) {
483 log::warn!("In bulk_delete_user: Failed to delete legacy entry. {:?}", e);
484 }
485 }
486 }
487 Ok(())
488 })
489 }
490
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800491 fn import_one_legacy_entry(
Janis Danisevskis06891072021-02-11 10:28:17 -0800492 uid: u32,
493 alias: &str,
494 legacy_loader: &LegacyBlobLoader,
495 db: &mut DB,
496 ) -> Result<bool> {
497 let blob = legacy_loader
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800498 .read_legacy_keystore_entry(uid, alias, |ciphertext, iv, tag, _salt, _key_size| {
499 if let Some(key) = SUPER_KEY
500 .read()
501 .unwrap()
502 .get_per_boot_key_by_user_id(uid_to_android_user(uid as u32))
503 {
504 key.decrypt(ciphertext, iv, tag)
505 } else {
506 Err(Error::sys()).context("No key found for user. Device may be locked.")
507 }
508 })
509 .context("In import_one_legacy_entry: Trying to read legacy keystore entry.")?;
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700510 if let Some(entry) = blob {
511 db.put(uid, alias, &entry)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800512 .context("In import_one_legacy_entry: Trying to insert entry into DB.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800513 legacy_loader
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700514 .remove_legacy_keystore_entry(uid, alias)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800515 .context("In import_one_legacy_entry: Trying to delete legacy keystore entry.")?;
Janis Danisevskis06891072021-02-11 10:28:17 -0800516 Ok(true)
517 } else {
518 Ok(false)
519 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800520 }
521}
522
Janis Danisevskis5898d152021-06-15 08:23:46 -0700523struct LegacyKeystoreService {
524 legacy_keystore: Arc<LegacyKeystore>,
525}
Janis Danisevskis77d72042021-01-20 15:36:30 -0800526
Janis Danisevskis5898d152021-06-15 08:23:46 -0700527impl binder::Interface for LegacyKeystoreService {}
528
529impl ILegacyKeystore for LegacyKeystoreService {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700530 fn get(&self, alias: &str, uid: i32) -> BinderResult<Vec<u8>> {
531 let _wp = wd::watch_millis("ILegacyKeystore::get", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700532 map_or_log_err(self.legacy_keystore.get(alias, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800533 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700534 fn put(&self, alias: &str, uid: i32, entry: &[u8]) -> BinderResult<()> {
535 let _wp = wd::watch_millis("ILegacyKeystore::put", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700536 map_or_log_err(self.legacy_keystore.put(alias, uid, entry), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800537 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700538 fn remove(&self, alias: &str, uid: i32) -> BinderResult<()> {
539 let _wp = wd::watch_millis("ILegacyKeystore::remove", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700540 map_or_log_err(self.legacy_keystore.remove(alias, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800541 }
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700542 fn list(&self, prefix: &str, uid: i32) -> BinderResult<Vec<String>> {
543 let _wp = wd::watch_millis("ILegacyKeystore::list", 500);
Janis Danisevskis5898d152021-06-15 08:23:46 -0700544 map_or_log_err(self.legacy_keystore.list(prefix, uid), Ok)
Janis Danisevskis77d72042021-01-20 15:36:30 -0800545 }
546}
547
548#[cfg(test)]
549mod db_test {
550 use super::*;
551 use keystore2_test_utils::TempDir;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700552 use std::sync::Arc;
553 use std::thread;
554 use std::time::Duration;
555 use std::time::Instant;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800556
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700557 static TEST_ALIAS: &str = "test_alias";
Janis Danisevskis77d72042021-01-20 15:36:30 -0800558 static TEST_BLOB1: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
559 static TEST_BLOB2: &[u8] = &[2, 2, 3, 4, 5, 6, 7, 8, 9, 0];
560 static TEST_BLOB3: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
561 static TEST_BLOB4: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
562
563 #[test]
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700564 fn test_entry_db() {
565 let test_dir = TempDir::new("entrydb_test_").expect("Failed to create temp dir.");
566 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
567 .expect("Failed to open database.");
Janis Danisevskis77d72042021-01-20 15:36:30 -0800568
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700569 // Insert three entries for owner 2.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800570 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
571 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
572 db.put(2, "test3", TEST_BLOB3).expect("Failed to insert test3.");
573
574 // Check list returns all inserted aliases.
575 assert_eq!(
576 vec!["test1".to_string(), "test2".to_string(), "test3".to_string(),],
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700577 db.list(2).expect("Failed to list entries.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800578 );
579
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700580 // There should be no entries for owner 1.
581 assert_eq!(Vec::<String>::new(), db.list(1).expect("Failed to list entries."));
Janis Danisevskis77d72042021-01-20 15:36:30 -0800582
583 // Check the content of the three entries.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700584 assert_eq!(Some(TEST_BLOB1), db.get(2, "test1").expect("Failed to get entry.").as_deref());
585 assert_eq!(Some(TEST_BLOB2), db.get(2, "test2").expect("Failed to get entry.").as_deref());
586 assert_eq!(Some(TEST_BLOB3), db.get(2, "test3").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800587
588 // Remove test2 and check and check that it is no longer retrievable.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700589 assert!(db.remove(2, "test2").expect("Failed to remove entry."));
590 assert!(db.get(2, "test2").expect("Failed to get entry.").is_none());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800591
592 // test2 should now no longer be in the list.
593 assert_eq!(
594 vec!["test1".to_string(), "test3".to_string(),],
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700595 db.list(2).expect("Failed to list entries.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800596 );
597
598 // Put on existing alias replaces it.
599 // Verify test1 is TEST_BLOB1.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700600 assert_eq!(Some(TEST_BLOB1), db.get(2, "test1").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800601 db.put(2, "test1", TEST_BLOB4).expect("Failed to replace test1.");
602 // Verify test1 is TEST_BLOB4.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700603 assert_eq!(Some(TEST_BLOB4), db.get(2, "test1").expect("Failed to get entry.").as_deref());
Janis Danisevskis77d72042021-01-20 15:36:30 -0800604 }
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700605
606 #[test]
Janis Danisevskis5898d152021-06-15 08:23:46 -0700607 fn test_delete_uid() {
608 let test_dir = TempDir::new("test_delete_uid_").expect("Failed to create temp dir.");
609 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
610 .expect("Failed to open database.");
611
612 // Insert three entries for owner 2.
613 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
614 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
615 db.put(3, "test3", TEST_BLOB3).expect("Failed to insert test3.");
616
617 db.remove_uid(2).expect("Failed to remove uid 2");
618
619 assert_eq!(Vec::<String>::new(), db.list(2).expect("Failed to list entries."));
620
621 assert_eq!(vec!["test3".to_string(),], db.list(3).expect("Failed to list entries."));
622 }
623
624 #[test]
625 fn test_delete_user() {
626 let test_dir = TempDir::new("test_delete_user_").expect("Failed to create temp dir.");
627 let mut db = DB::new(&test_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME))
628 .expect("Failed to open database.");
629
630 // Insert three entries for owner 2.
Joel Galenson81a50f22021-07-29 15:39:10 -0700631 db.put(2 + 2 * rustutils::users::AID_USER_OFFSET, "test1", TEST_BLOB1)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700632 .expect("Failed to insert test1.");
Joel Galenson81a50f22021-07-29 15:39:10 -0700633 db.put(4 + 2 * rustutils::users::AID_USER_OFFSET, "test2", TEST_BLOB2)
Janis Danisevskis5898d152021-06-15 08:23:46 -0700634 .expect("Failed to insert test2.");
635 db.put(3, "test3", TEST_BLOB3).expect("Failed to insert test3.");
636
637 db.remove_user(2).expect("Failed to remove user 2");
638
639 assert_eq!(
640 Vec::<String>::new(),
Joel Galenson81a50f22021-07-29 15:39:10 -0700641 db.list(2 + 2 * rustutils::users::AID_USER_OFFSET).expect("Failed to list entries.")
Janis Danisevskis5898d152021-06-15 08:23:46 -0700642 );
643
644 assert_eq!(
645 Vec::<String>::new(),
Joel Galenson81a50f22021-07-29 15:39:10 -0700646 db.list(4 + 2 * rustutils::users::AID_USER_OFFSET).expect("Failed to list entries.")
Janis Danisevskis5898d152021-06-15 08:23:46 -0700647 );
648
649 assert_eq!(vec!["test3".to_string(),], db.list(3).expect("Failed to list entries."));
650 }
651
652 #[test]
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700653 fn concurrent_legacy_keystore_entry_test() -> Result<()> {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700654 let temp_dir = Arc::new(
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700655 TempDir::new("concurrent_legacy_keystore_entry_test_")
656 .expect("Failed to create temp dir."),
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700657 );
658
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700659 let db_path = temp_dir.build().push(LegacyKeystore::LEGACY_KEYSTORE_FILE_NAME).to_owned();
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700660
661 let test_begin = Instant::now();
662
663 let mut db = DB::new(&db_path).expect("Failed to open database.");
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700664 const ENTRY_COUNT: u32 = 5000u32;
665 const ENTRY_DB_COUNT: u32 = 5000u32;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700666
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700667 let mut actual_entry_count = ENTRY_COUNT;
668 // First insert ENTRY_COUNT entries.
669 for count in 0..ENTRY_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700670 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700671 actual_entry_count = count;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700672 break;
673 }
674 let alias = format!("test_alias_{}", count);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700675 db.put(1, &alias, TEST_BLOB1).expect("Failed to add entry (1).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700676 }
677
678 // Insert more keys from a different thread and into a different namespace.
679 let db_path1 = db_path.clone();
680 let handle1 = thread::spawn(move || {
681 let mut db = DB::new(&db_path1).expect("Failed to open database.");
682
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700683 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700684 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
685 return;
686 }
687 let alias = format!("test_alias_{}", count);
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700688 db.put(2, &alias, TEST_BLOB2).expect("Failed to add entry (2).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700689 }
690
691 // Then delete them again.
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700692 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700693 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
694 return;
695 }
696 let alias = format!("test_alias_{}", count);
697 db.remove(2, &alias).expect("Remove Failed (2).");
698 }
699 });
700
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700701 // And start deleting the first set of entries.
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700702 let db_path2 = db_path.clone();
703 let handle2 = thread::spawn(move || {
704 let mut db = DB::new(&db_path2).expect("Failed to open database.");
705
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700706 for count in 0..actual_entry_count {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700707 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
708 return;
709 }
710 let alias = format!("test_alias_{}", count);
711 db.remove(1, &alias).expect("Remove Failed (1)).");
712 }
713 });
714
715 // While a lot of inserting and deleting is going on we have to open database connections
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700716 // successfully and then insert and delete a specific entry.
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700717 let db_path3 = db_path.clone();
718 let handle3 = thread::spawn(move || {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700719 for _count in 0..ENTRY_DB_COUNT {
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700720 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
721 return;
722 }
723 let mut db = DB::new(&db_path3).expect("Failed to open database.");
724
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700725 db.put(3, TEST_ALIAS, TEST_BLOB3).expect("Failed to add entry (3).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700726
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700727 db.remove(3, TEST_ALIAS).expect("Remove failed (3).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700728 }
729 });
730
731 // While thread 3 is inserting and deleting TEST_ALIAS, we try to get the alias.
732 // This may yield an entry or none, but it must not fail.
733 let handle4 = thread::spawn(move || {
Janis Danisevskis3eb829d2021-06-14 14:18:20 -0700734 for _count in 0..ENTRY_DB_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 mut db = DB::new(&db_path).expect("Failed to open database.");
739
740 // This may return Some or None but it must not fail.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700741 db.get(3, TEST_ALIAS).expect("Failed to get entry (4).");
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700742 }
743 });
744
745 handle1.join().expect("Thread 1 panicked.");
746 handle2.join().expect("Thread 2 panicked.");
747 handle3.join().expect("Thread 3 panicked.");
748 handle4.join().expect("Thread 4 panicked.");
749
750 Ok(())
751 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800752}