blob: e7340a0dedd161827a2a0be6be4aed01e45fe8b8 [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
15//! Implements the android.security.vpnprofilestore interface.
16
17use android_security_vpnprofilestore::aidl::android::security::vpnprofilestore::{
18 IVpnProfileStore::BnVpnProfileStore, IVpnProfileStore::IVpnProfileStore,
19 IVpnProfileStore::ERROR_PROFILE_NOT_FOUND, IVpnProfileStore::ERROR_SYSTEM_ERROR,
20};
Andrew Walbrande45c8b2021-04-13 14:42:38 +000021use android_security_vpnprofilestore::binder::{
22 BinderFeatures, ExceptionCode, Result as BinderResult, Status as BinderStatus, Strong,
23 ThreadState,
24};
Janis Danisevskis77d72042021-01-20 15:36:30 -080025use anyhow::{Context, Result};
Janis Danisevskis06891072021-02-11 10:28:17 -080026use keystore2::{async_task::AsyncTask, legacy_blob::LegacyBlobLoader};
Janis Danisevskis77d72042021-01-20 15:36:30 -080027use rusqlite::{
28 params, Connection, OptionalExtension, Transaction, TransactionBehavior, NO_PARAMS,
29};
Janis Danisevskis06891072021-02-11 10:28:17 -080030use std::{
31 collections::HashSet,
32 path::{Path, PathBuf},
33};
Janis Danisevskis77d72042021-01-20 15:36:30 -080034
35struct DB {
36 conn: Connection,
37}
38
39impl DB {
40 fn new(db_file: &Path) -> Result<Self> {
41 let mut db = Self {
42 conn: Connection::open(db_file).context("Failed to initialize SQLite connection.")?,
43 };
Janis Danisevskis1be7e182021-04-12 14:31:12 -070044
45 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
46 db.conn.busy_handler(None).context("Failed to set busy handler.")?;
47
Janis Danisevskis77d72042021-01-20 15:36:30 -080048 db.init_tables().context("Trying to initialize vpnstore db.")?;
49 Ok(db)
50 }
51
52 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
53 where
54 F: Fn(&Transaction) -> Result<T>,
55 {
56 loop {
57 match self
58 .conn
59 .transaction_with_behavior(behavior)
60 .context("In with_transaction.")
61 .and_then(|tx| f(&tx).map(|result| (result, tx)))
62 .and_then(|(result, tx)| {
63 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
64 Ok(result)
65 }) {
66 Ok(result) => break Ok(result),
67 Err(e) => {
68 if Self::is_locked_error(&e) {
69 std::thread::sleep(std::time::Duration::from_micros(500));
70 continue;
71 } else {
72 return Err(e).context("In with_transaction.");
73 }
74 }
75 }
76 }
77 }
78
79 fn is_locked_error(e: &anyhow::Error) -> bool {
Andrew Walbrande45c8b2021-04-13 14:42:38 +000080 matches!(
81 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
82 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
83 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
84 )
Janis Danisevskis77d72042021-01-20 15:36:30 -080085 }
86
87 fn init_tables(&mut self) -> Result<()> {
88 self.with_transaction(TransactionBehavior::Immediate, |tx| {
89 tx.execute(
90 "CREATE TABLE IF NOT EXISTS profiles (
91 owner INTEGER,
92 alias BLOB,
93 profile BLOB,
94 UNIQUE(owner, alias));",
95 NO_PARAMS,
96 )
97 .context("Failed to initialize \"profiles\" table.")?;
98 Ok(())
99 })
100 }
101
102 fn list(&mut self, caller_uid: u32) -> Result<Vec<String>> {
103 self.with_transaction(TransactionBehavior::Deferred, |tx| {
104 let mut stmt = tx
105 .prepare("SELECT alias FROM profiles WHERE owner = ? ORDER BY alias ASC;")
106 .context("In list: Failed to prepare statement.")?;
107
108 let aliases = stmt
109 .query_map(params![caller_uid], |row| row.get(0))?
110 .collect::<rusqlite::Result<Vec<String>>>()
111 .context("In list: query_map failed.");
112 aliases
113 })
114 }
115
116 fn put(&mut self, caller_uid: u32, alias: &str, profile: &[u8]) -> Result<()> {
117 self.with_transaction(TransactionBehavior::Immediate, |tx| {
118 tx.execute(
119 "INSERT OR REPLACE INTO profiles (owner, alias, profile) values (?, ?, ?)",
120 params![caller_uid, alias, profile,],
121 )
122 .context("In put: Failed to insert or replace.")?;
123 Ok(())
124 })
125 }
126
127 fn get(&mut self, caller_uid: u32, alias: &str) -> Result<Option<Vec<u8>>> {
128 self.with_transaction(TransactionBehavior::Deferred, |tx| {
129 tx.query_row(
130 "SELECT profile FROM profiles WHERE owner = ? AND alias = ?;",
131 params![caller_uid, alias],
132 |row| row.get(0),
133 )
134 .optional()
135 .context("In get: failed loading profile.")
136 })
137 }
138
139 fn remove(&mut self, caller_uid: u32, alias: &str) -> Result<bool> {
140 let removed = self.with_transaction(TransactionBehavior::Immediate, |tx| {
141 tx.execute(
142 "DELETE FROM profiles WHERE owner = ? AND alias = ?;",
143 params![caller_uid, alias],
144 )
145 .context("In remove: Failed to delete row.")
146 })?;
147 Ok(removed == 1)
148 }
149}
150
151/// This is the main VpnProfileStore error type, it wraps binder exceptions and the
152/// VnpStore errors.
153#[derive(Debug, thiserror::Error, PartialEq)]
154pub enum Error {
155 /// Wraps a VpnProfileStore error code.
156 #[error("Error::Error({0:?})")]
157 Error(i32),
158 /// Wraps a Binder exception code other than a service specific exception.
159 #[error("Binder exception code {0:?}, {1:?}")]
160 Binder(ExceptionCode, i32),
161}
162
163impl Error {
164 /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)`
165 pub fn sys() -> Self {
166 Error::Error(ERROR_SYSTEM_ERROR)
167 }
168
169 /// Short hand for `Error::Error(ERROR_PROFILE_NOT_FOUND)`
170 pub fn not_found() -> Self {
171 Error::Error(ERROR_PROFILE_NOT_FOUND)
172 }
173}
174
175/// This function should be used by vpnprofilestore service calls to translate error conditions
176/// into service specific exceptions.
177///
178/// All error conditions get logged by this function.
179///
180/// `Error::Error(x)` variants get mapped onto a service specific error code of `x`.
181///
182/// All non `Error` error conditions get mapped onto `ERROR_SYSTEM_ERROR`.
183///
184/// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
185/// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it
186/// typically returns Ok(value).
187fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T>
188where
189 F: FnOnce(U) -> BinderResult<T>,
190{
191 result.map_or_else(
192 |e| {
193 log::error!("{:#?}", e);
194 let root_cause = e.root_cause();
195 let rc = match root_cause.downcast_ref::<Error>() {
196 Some(Error::Error(e)) => *e,
197 Some(Error::Binder(_, _)) | None => ERROR_SYSTEM_ERROR,
198 };
199 Err(BinderStatus::new_service_specific_error(rc, None))
200 },
201 handle_ok,
202 )
203}
204
Janis Danisevskis77d72042021-01-20 15:36:30 -0800205/// Implements IVpnProfileStore AIDL interface.
206pub struct VpnProfileStore {
207 db_path: PathBuf,
Janis Danisevskis06891072021-02-11 10:28:17 -0800208 async_task: AsyncTask,
209}
210
211struct AsyncState {
212 recently_imported: HashSet<(u32, String)>,
213 legacy_loader: LegacyBlobLoader,
214 db_path: PathBuf,
Janis Danisevskis77d72042021-01-20 15:36:30 -0800215}
216
217impl VpnProfileStore {
218 /// Creates a new VpnProfileStore instance.
Janis Danisevskis06891072021-02-11 10:28:17 -0800219 pub fn new_native_binder(path: &Path) -> Strong<dyn IVpnProfileStore> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800220 let mut db_path = path.to_path_buf();
221 db_path.push("vpnprofilestore.sqlite");
Janis Danisevskis06891072021-02-11 10:28:17 -0800222
223 let result = Self { db_path, async_task: Default::default() };
224 result.init_shelf(path);
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000225 BnVpnProfileStore::new_binder(result, BinderFeatures::default())
Janis Danisevskis77d72042021-01-20 15:36:30 -0800226 }
227
228 fn open_db(&self) -> Result<DB> {
229 DB::new(&self.db_path).context("In open_db: Failed to open db.")
230 }
231
232 fn get(&self, alias: &str) -> Result<Vec<u8>> {
233 let mut db = self.open_db().context("In get.")?;
234 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800235
236 if let Some(profile) =
237 db.get(calling_uid, alias).context("In get: Trying to load profile from DB.")?
238 {
239 return Ok(profile);
240 }
241 if self.get_legacy(calling_uid, alias).context("In get: Trying to migrate legacy blob.")? {
242 // If we were able to migrate a legacy blob try again.
243 if let Some(profile) =
244 db.get(calling_uid, alias).context("In get: Trying to load profile from DB.")?
245 {
246 return Ok(profile);
247 }
248 }
249 Err(Error::not_found()).context("In get: No such profile.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800250 }
251
252 fn put(&self, alias: &str, profile: &[u8]) -> Result<()> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800253 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800254 // In order to make sure that we don't have stale legacy profiles, make sure they are
255 // migrated before replacing them.
256 let _ = self.get_legacy(calling_uid, alias);
257 let mut db = self.open_db().context("In put.")?;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800258 db.put(calling_uid, alias, profile).context("In put: Trying to insert profile into DB.")
259 }
260
261 fn remove(&self, alias: &str) -> Result<()> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800262 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800263 let mut db = self.open_db().context("In remove.")?;
264 // In order to make sure that we don't have stale legacy profiles, make sure they are
265 // migrated before removing them.
266 let _ = self.get_legacy(calling_uid, alias);
Janis Danisevskis77d72042021-01-20 15:36:30 -0800267 let removed = db
268 .remove(calling_uid, alias)
269 .context("In remove: Trying to remove profile from DB.")?;
270 if removed {
271 Ok(())
272 } else {
273 Err(Error::not_found()).context("In remove: No such profile.")
274 }
275 }
276
277 fn list(&self, prefix: &str) -> Result<Vec<String>> {
278 let mut db = self.open_db().context("In list.")?;
279 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800280 let mut result = self.list_legacy(calling_uid).context("In list.")?;
281 result
282 .append(&mut db.list(calling_uid).context("In list: Trying to get list of profiles.")?);
283 result = result.into_iter().filter(|s| s.starts_with(prefix)).collect();
284 result.sort_unstable();
285 result.dedup();
286 Ok(result)
287 }
288
289 fn init_shelf(&self, path: &Path) {
290 let mut db_path = path.to_path_buf();
291 self.async_task.queue_hi(move |shelf| {
292 let legacy_loader = LegacyBlobLoader::new(&db_path);
293 db_path.push("vpnprofilestore.sqlite");
294
295 shelf.put(AsyncState { legacy_loader, db_path, recently_imported: Default::default() });
296 })
297 }
298
299 fn do_serialized<F, T: Send + 'static>(&self, f: F) -> Result<T>
300 where
301 F: FnOnce(&mut AsyncState) -> Result<T> + Send + 'static,
302 {
303 let (sender, receiver) = std::sync::mpsc::channel::<Result<T>>();
304 self.async_task.queue_hi(move |shelf| {
305 let state = shelf.get_downcast_mut::<AsyncState>().expect("Failed to get shelf.");
306 sender.send(f(state)).expect("Failed to send result.");
307 });
308 receiver.recv().context("In do_serialized: Failed to receive result.")?
309 }
310
311 fn list_legacy(&self, uid: u32) -> Result<Vec<String>> {
312 self.do_serialized(move |state| {
313 state
314 .legacy_loader
315 .list_vpn_profiles(uid)
316 .context("Trying to list legacy vnp profiles.")
317 })
318 .context("In list_legacy.")
319 }
320
321 fn get_legacy(&self, uid: u32, alias: &str) -> Result<bool> {
322 let alias = alias.to_string();
323 self.do_serialized(move |state| {
324 if state.recently_imported.contains(&(uid, alias.clone())) {
325 return Ok(true);
326 }
327 let mut db = DB::new(&state.db_path).context("In open_db: Failed to open db.")?;
328 let migrated =
329 Self::migrate_one_legacy_profile(uid, &alias, &state.legacy_loader, &mut db)
330 .context("Trying to migrate legacy vpn profile.")?;
331 if migrated {
332 state.recently_imported.insert((uid, alias));
333 }
334 Ok(migrated)
335 })
336 .context("In get_legacy.")
337 }
338
339 fn migrate_one_legacy_profile(
340 uid: u32,
341 alias: &str,
342 legacy_loader: &LegacyBlobLoader,
343 db: &mut DB,
344 ) -> Result<bool> {
345 let blob = legacy_loader
346 .read_vpn_profile(uid, alias)
347 .context("In migrate_one_legacy_profile: Trying to read legacy vpn profile.")?;
348 if let Some(profile) = blob {
349 db.put(uid, alias, &profile)
350 .context("In migrate_one_legacy_profile: Trying to insert profile into DB.")?;
351 legacy_loader
352 .remove_vpn_profile(uid, alias)
353 .context("In migrate_one_legacy_profile: Trying to delete legacy profile.")?;
354 Ok(true)
355 } else {
356 Ok(false)
357 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800358 }
359}
360
361impl binder::Interface for VpnProfileStore {}
362
363impl IVpnProfileStore for VpnProfileStore {
364 fn get(&self, alias: &str) -> BinderResult<Vec<u8>> {
365 map_or_log_err(self.get(alias), Ok)
366 }
367 fn put(&self, alias: &str, profile: &[u8]) -> BinderResult<()> {
368 map_or_log_err(self.put(alias, profile), Ok)
369 }
370 fn remove(&self, alias: &str) -> BinderResult<()> {
371 map_or_log_err(self.remove(alias), Ok)
372 }
373 fn list(&self, prefix: &str) -> BinderResult<Vec<String>> {
374 map_or_log_err(self.list(prefix), Ok)
375 }
376}
377
378#[cfg(test)]
379mod db_test {
380 use super::*;
381 use keystore2_test_utils::TempDir;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700382 use std::sync::Arc;
383 use std::thread;
384 use std::time::Duration;
385 use std::time::Instant;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800386
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700387 static TEST_ALIAS: &str = &"test_alias";
Janis Danisevskis77d72042021-01-20 15:36:30 -0800388 static TEST_BLOB1: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
389 static TEST_BLOB2: &[u8] = &[2, 2, 3, 4, 5, 6, 7, 8, 9, 0];
390 static TEST_BLOB3: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
391 static TEST_BLOB4: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
392
393 #[test]
394 fn test_profile_db() {
395 let test_dir = TempDir::new("profiledb_test_").expect("Failed to create temp dir.");
396 let mut db =
397 DB::new(&test_dir.build().push("vpnprofile.sqlite")).expect("Failed to open database.");
398
399 // Insert three profiles for owner 2.
400 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
401 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
402 db.put(2, "test3", TEST_BLOB3).expect("Failed to insert test3.");
403
404 // Check list returns all inserted aliases.
405 assert_eq!(
406 vec!["test1".to_string(), "test2".to_string(), "test3".to_string(),],
407 db.list(2).expect("Failed to list profiles.")
408 );
409
410 // There should be no profiles for owner 1.
411 assert_eq!(Vec::<String>::new(), db.list(1).expect("Failed to list profiles."));
412
413 // Check the content of the three entries.
414 assert_eq!(
415 Some(TEST_BLOB1),
416 db.get(2, "test1").expect("Failed to get profile.").as_deref()
417 );
418 assert_eq!(
419 Some(TEST_BLOB2),
420 db.get(2, "test2").expect("Failed to get profile.").as_deref()
421 );
422 assert_eq!(
423 Some(TEST_BLOB3),
424 db.get(2, "test3").expect("Failed to get profile.").as_deref()
425 );
426
427 // Remove test2 and check and check that it is no longer retrievable.
428 assert!(db.remove(2, "test2").expect("Failed to remove profile."));
429 assert!(db.get(2, "test2").expect("Failed to get profile.").is_none());
430
431 // test2 should now no longer be in the list.
432 assert_eq!(
433 vec!["test1".to_string(), "test3".to_string(),],
434 db.list(2).expect("Failed to list profiles.")
435 );
436
437 // Put on existing alias replaces it.
438 // Verify test1 is TEST_BLOB1.
439 assert_eq!(
440 Some(TEST_BLOB1),
441 db.get(2, "test1").expect("Failed to get profile.").as_deref()
442 );
443 db.put(2, "test1", TEST_BLOB4).expect("Failed to replace test1.");
444 // Verify test1 is TEST_BLOB4.
445 assert_eq!(
446 Some(TEST_BLOB4),
447 db.get(2, "test1").expect("Failed to get profile.").as_deref()
448 );
449 }
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700450
451 #[test]
452 fn concurrent_vpn_profile_test() -> Result<()> {
453 let temp_dir = Arc::new(
454 TempDir::new("concurrent_vpn_profile_test_").expect("Failed to create temp dir."),
455 );
456
457 let db_path = temp_dir.build().push("vpnprofile.sqlite").to_owned();
458
459 let test_begin = Instant::now();
460
461 let mut db = DB::new(&db_path).expect("Failed to open database.");
462 const PROFILE_COUNT: u32 = 5000u32;
463 const PROFILE_DB_COUNT: u32 = 5000u32;
464
465 let mut actual_profile_count = PROFILE_COUNT;
466 // First insert PROFILE_COUNT profiles.
467 for count in 0..PROFILE_COUNT {
468 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
469 actual_profile_count = count;
470 break;
471 }
472 let alias = format!("test_alias_{}", count);
473 db.put(1, &alias, TEST_BLOB1).expect("Failed to add profile (1).");
474 }
475
476 // Insert more keys from a different thread and into a different namespace.
477 let db_path1 = db_path.clone();
478 let handle1 = thread::spawn(move || {
479 let mut db = DB::new(&db_path1).expect("Failed to open database.");
480
481 for count in 0..actual_profile_count {
482 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
483 return;
484 }
485 let alias = format!("test_alias_{}", count);
486 db.put(2, &alias, TEST_BLOB2).expect("Failed to add profile (2).");
487 }
488
489 // Then delete them again.
490 for count in 0..actual_profile_count {
491 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
492 return;
493 }
494 let alias = format!("test_alias_{}", count);
495 db.remove(2, &alias).expect("Remove Failed (2).");
496 }
497 });
498
499 // And start deleting the first set of profiles.
500 let db_path2 = db_path.clone();
501 let handle2 = thread::spawn(move || {
502 let mut db = DB::new(&db_path2).expect("Failed to open database.");
503
504 for count in 0..actual_profile_count {
505 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
506 return;
507 }
508 let alias = format!("test_alias_{}", count);
509 db.remove(1, &alias).expect("Remove Failed (1)).");
510 }
511 });
512
513 // While a lot of inserting and deleting is going on we have to open database connections
514 // successfully and then insert and delete a specific profile.
515 let db_path3 = db_path.clone();
516 let handle3 = thread::spawn(move || {
517 for _count in 0..PROFILE_DB_COUNT {
518 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
519 return;
520 }
521 let mut db = DB::new(&db_path3).expect("Failed to open database.");
522
523 db.put(3, &TEST_ALIAS, TEST_BLOB3).expect("Failed to add profile (3).");
524
525 db.remove(3, &TEST_ALIAS).expect("Remove failed (3).");
526 }
527 });
528
529 // While thread 3 is inserting and deleting TEST_ALIAS, we try to get the alias.
530 // This may yield an entry or none, but it must not fail.
531 let handle4 = thread::spawn(move || {
532 for _count in 0..PROFILE_DB_COUNT {
533 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
534 return;
535 }
536 let mut db = DB::new(&db_path).expect("Failed to open database.");
537
538 // This may return Some or None but it must not fail.
539 db.get(3, &TEST_ALIAS).expect("Failed to get profile (4).");
540 }
541 });
542
543 handle1.join().expect("Thread 1 panicked.");
544 handle2.join().expect("Thread 2 panicked.");
545 handle3.join().expect("Thread 3 panicked.");
546 handle4.join().expect("Thread 4 panicked.");
547
548 Ok(())
549 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800550}