blob: d92e045a937d58b8b324717f247d04b01bfa0d16 [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 {
Janis Danisevskis13f09152021-04-19 09:55:15 -070080 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///
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000178/// All error conditions get logged by this function, except for ERROR_PROFILE_NOT_FOUND error.
Janis Danisevskis77d72042021-01-20 15:36:30 -0800179///
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| {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800193 let root_cause = e.root_cause();
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000194 let (rc, log_error) = match root_cause.downcast_ref::<Error>() {
195 // Make the profile not found errors silent.
196 Some(Error::Error(ERROR_PROFILE_NOT_FOUND)) => (ERROR_PROFILE_NOT_FOUND, false),
197 Some(Error::Error(e)) => (*e, true),
198 Some(Error::Binder(_, _)) | None => (ERROR_SYSTEM_ERROR, true),
Janis Danisevskis77d72042021-01-20 15:36:30 -0800199 };
Hasini Gunasinghee1d1bbd2021-04-20 18:13:25 +0000200 if log_error {
201 log::error!("{:?}", e);
202 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800203 Err(BinderStatus::new_service_specific_error(rc, None))
204 },
205 handle_ok,
206 )
207}
208
Janis Danisevskis77d72042021-01-20 15:36:30 -0800209/// Implements IVpnProfileStore AIDL interface.
210pub struct VpnProfileStore {
211 db_path: PathBuf,
Janis Danisevskis06891072021-02-11 10:28:17 -0800212 async_task: AsyncTask,
213}
214
215struct AsyncState {
216 recently_imported: HashSet<(u32, String)>,
217 legacy_loader: LegacyBlobLoader,
218 db_path: PathBuf,
Janis Danisevskis77d72042021-01-20 15:36:30 -0800219}
220
221impl VpnProfileStore {
222 /// Creates a new VpnProfileStore instance.
Janis Danisevskis06891072021-02-11 10:28:17 -0800223 pub fn new_native_binder(path: &Path) -> Strong<dyn IVpnProfileStore> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800224 let mut db_path = path.to_path_buf();
225 db_path.push("vpnprofilestore.sqlite");
Janis Danisevskis06891072021-02-11 10:28:17 -0800226
227 let result = Self { db_path, async_task: Default::default() };
228 result.init_shelf(path);
Andrew Walbrande45c8b2021-04-13 14:42:38 +0000229 BnVpnProfileStore::new_binder(result, BinderFeatures::default())
Janis Danisevskis77d72042021-01-20 15:36:30 -0800230 }
231
232 fn open_db(&self) -> Result<DB> {
233 DB::new(&self.db_path).context("In open_db: Failed to open db.")
234 }
235
236 fn get(&self, alias: &str) -> Result<Vec<u8>> {
237 let mut db = self.open_db().context("In get.")?;
238 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800239
240 if let Some(profile) =
241 db.get(calling_uid, alias).context("In get: Trying to load profile from DB.")?
242 {
243 return Ok(profile);
244 }
245 if self.get_legacy(calling_uid, alias).context("In get: Trying to migrate legacy blob.")? {
246 // If we were able to migrate a legacy blob try again.
247 if let Some(profile) =
248 db.get(calling_uid, alias).context("In get: Trying to load profile from DB.")?
249 {
250 return Ok(profile);
251 }
252 }
253 Err(Error::not_found()).context("In get: No such profile.")
Janis Danisevskis77d72042021-01-20 15:36:30 -0800254 }
255
256 fn put(&self, alias: &str, profile: &[u8]) -> Result<()> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800257 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800258 // In order to make sure that we don't have stale legacy profiles, make sure they are
259 // migrated before replacing them.
260 let _ = self.get_legacy(calling_uid, alias);
261 let mut db = self.open_db().context("In put.")?;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800262 db.put(calling_uid, alias, profile).context("In put: Trying to insert profile into DB.")
263 }
264
265 fn remove(&self, alias: &str) -> Result<()> {
Janis Danisevskis77d72042021-01-20 15:36:30 -0800266 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800267 let mut db = self.open_db().context("In remove.")?;
268 // In order to make sure that we don't have stale legacy profiles, make sure they are
269 // migrated before removing them.
270 let _ = self.get_legacy(calling_uid, alias);
Janis Danisevskis77d72042021-01-20 15:36:30 -0800271 let removed = db
272 .remove(calling_uid, alias)
273 .context("In remove: Trying to remove profile from DB.")?;
274 if removed {
275 Ok(())
276 } else {
277 Err(Error::not_found()).context("In remove: No such profile.")
278 }
279 }
280
281 fn list(&self, prefix: &str) -> Result<Vec<String>> {
282 let mut db = self.open_db().context("In list.")?;
283 let calling_uid = ThreadState::get_calling_uid();
Janis Danisevskis06891072021-02-11 10:28:17 -0800284 let mut result = self.list_legacy(calling_uid).context("In list.")?;
285 result
286 .append(&mut db.list(calling_uid).context("In list: Trying to get list of profiles.")?);
287 result = result.into_iter().filter(|s| s.starts_with(prefix)).collect();
288 result.sort_unstable();
289 result.dedup();
290 Ok(result)
291 }
292
293 fn init_shelf(&self, path: &Path) {
294 let mut db_path = path.to_path_buf();
295 self.async_task.queue_hi(move |shelf| {
296 let legacy_loader = LegacyBlobLoader::new(&db_path);
297 db_path.push("vpnprofilestore.sqlite");
298
299 shelf.put(AsyncState { legacy_loader, db_path, recently_imported: Default::default() });
300 })
301 }
302
303 fn do_serialized<F, T: Send + 'static>(&self, f: F) -> Result<T>
304 where
305 F: FnOnce(&mut AsyncState) -> Result<T> + Send + 'static,
306 {
307 let (sender, receiver) = std::sync::mpsc::channel::<Result<T>>();
308 self.async_task.queue_hi(move |shelf| {
309 let state = shelf.get_downcast_mut::<AsyncState>().expect("Failed to get shelf.");
310 sender.send(f(state)).expect("Failed to send result.");
311 });
312 receiver.recv().context("In do_serialized: Failed to receive result.")?
313 }
314
315 fn list_legacy(&self, uid: u32) -> Result<Vec<String>> {
316 self.do_serialized(move |state| {
317 state
318 .legacy_loader
319 .list_vpn_profiles(uid)
320 .context("Trying to list legacy vnp profiles.")
321 })
322 .context("In list_legacy.")
323 }
324
325 fn get_legacy(&self, uid: u32, alias: &str) -> Result<bool> {
326 let alias = alias.to_string();
327 self.do_serialized(move |state| {
328 if state.recently_imported.contains(&(uid, alias.clone())) {
329 return Ok(true);
330 }
331 let mut db = DB::new(&state.db_path).context("In open_db: Failed to open db.")?;
332 let migrated =
333 Self::migrate_one_legacy_profile(uid, &alias, &state.legacy_loader, &mut db)
334 .context("Trying to migrate legacy vpn profile.")?;
335 if migrated {
336 state.recently_imported.insert((uid, alias));
337 }
338 Ok(migrated)
339 })
340 .context("In get_legacy.")
341 }
342
343 fn migrate_one_legacy_profile(
344 uid: u32,
345 alias: &str,
346 legacy_loader: &LegacyBlobLoader,
347 db: &mut DB,
348 ) -> Result<bool> {
349 let blob = legacy_loader
350 .read_vpn_profile(uid, alias)
351 .context("In migrate_one_legacy_profile: Trying to read legacy vpn profile.")?;
352 if let Some(profile) = blob {
353 db.put(uid, alias, &profile)
354 .context("In migrate_one_legacy_profile: Trying to insert profile into DB.")?;
355 legacy_loader
356 .remove_vpn_profile(uid, alias)
357 .context("In migrate_one_legacy_profile: Trying to delete legacy profile.")?;
358 Ok(true)
359 } else {
360 Ok(false)
361 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800362 }
363}
364
365impl binder::Interface for VpnProfileStore {}
366
367impl IVpnProfileStore for VpnProfileStore {
368 fn get(&self, alias: &str) -> BinderResult<Vec<u8>> {
369 map_or_log_err(self.get(alias), Ok)
370 }
371 fn put(&self, alias: &str, profile: &[u8]) -> BinderResult<()> {
372 map_or_log_err(self.put(alias, profile), Ok)
373 }
374 fn remove(&self, alias: &str) -> BinderResult<()> {
375 map_or_log_err(self.remove(alias), Ok)
376 }
377 fn list(&self, prefix: &str) -> BinderResult<Vec<String>> {
378 map_or_log_err(self.list(prefix), Ok)
379 }
380}
381
382#[cfg(test)]
383mod db_test {
384 use super::*;
385 use keystore2_test_utils::TempDir;
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700386 use std::sync::Arc;
387 use std::thread;
388 use std::time::Duration;
389 use std::time::Instant;
Janis Danisevskis77d72042021-01-20 15:36:30 -0800390
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700391 static TEST_ALIAS: &str = &"test_alias";
Janis Danisevskis77d72042021-01-20 15:36:30 -0800392 static TEST_BLOB1: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
393 static TEST_BLOB2: &[u8] = &[2, 2, 3, 4, 5, 6, 7, 8, 9, 0];
394 static TEST_BLOB3: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
395 static TEST_BLOB4: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0];
396
397 #[test]
398 fn test_profile_db() {
399 let test_dir = TempDir::new("profiledb_test_").expect("Failed to create temp dir.");
400 let mut db =
401 DB::new(&test_dir.build().push("vpnprofile.sqlite")).expect("Failed to open database.");
402
403 // Insert three profiles for owner 2.
404 db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1.");
405 db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2.");
406 db.put(2, "test3", TEST_BLOB3).expect("Failed to insert test3.");
407
408 // Check list returns all inserted aliases.
409 assert_eq!(
410 vec!["test1".to_string(), "test2".to_string(), "test3".to_string(),],
411 db.list(2).expect("Failed to list profiles.")
412 );
413
414 // There should be no profiles for owner 1.
415 assert_eq!(Vec::<String>::new(), db.list(1).expect("Failed to list profiles."));
416
417 // Check the content of the three entries.
418 assert_eq!(
419 Some(TEST_BLOB1),
420 db.get(2, "test1").expect("Failed to get profile.").as_deref()
421 );
422 assert_eq!(
423 Some(TEST_BLOB2),
424 db.get(2, "test2").expect("Failed to get profile.").as_deref()
425 );
426 assert_eq!(
427 Some(TEST_BLOB3),
428 db.get(2, "test3").expect("Failed to get profile.").as_deref()
429 );
430
431 // Remove test2 and check and check that it is no longer retrievable.
432 assert!(db.remove(2, "test2").expect("Failed to remove profile."));
433 assert!(db.get(2, "test2").expect("Failed to get profile.").is_none());
434
435 // test2 should now no longer be in the list.
436 assert_eq!(
437 vec!["test1".to_string(), "test3".to_string(),],
438 db.list(2).expect("Failed to list profiles.")
439 );
440
441 // Put on existing alias replaces it.
442 // Verify test1 is TEST_BLOB1.
443 assert_eq!(
444 Some(TEST_BLOB1),
445 db.get(2, "test1").expect("Failed to get profile.").as_deref()
446 );
447 db.put(2, "test1", TEST_BLOB4).expect("Failed to replace test1.");
448 // Verify test1 is TEST_BLOB4.
449 assert_eq!(
450 Some(TEST_BLOB4),
451 db.get(2, "test1").expect("Failed to get profile.").as_deref()
452 );
453 }
Janis Danisevskis1be7e182021-04-12 14:31:12 -0700454
455 #[test]
456 fn concurrent_vpn_profile_test() -> Result<()> {
457 let temp_dir = Arc::new(
458 TempDir::new("concurrent_vpn_profile_test_").expect("Failed to create temp dir."),
459 );
460
461 let db_path = temp_dir.build().push("vpnprofile.sqlite").to_owned();
462
463 let test_begin = Instant::now();
464
465 let mut db = DB::new(&db_path).expect("Failed to open database.");
466 const PROFILE_COUNT: u32 = 5000u32;
467 const PROFILE_DB_COUNT: u32 = 5000u32;
468
469 let mut actual_profile_count = PROFILE_COUNT;
470 // First insert PROFILE_COUNT profiles.
471 for count in 0..PROFILE_COUNT {
472 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
473 actual_profile_count = count;
474 break;
475 }
476 let alias = format!("test_alias_{}", count);
477 db.put(1, &alias, TEST_BLOB1).expect("Failed to add profile (1).");
478 }
479
480 // Insert more keys from a different thread and into a different namespace.
481 let db_path1 = db_path.clone();
482 let handle1 = thread::spawn(move || {
483 let mut db = DB::new(&db_path1).expect("Failed to open database.");
484
485 for count in 0..actual_profile_count {
486 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
487 return;
488 }
489 let alias = format!("test_alias_{}", count);
490 db.put(2, &alias, TEST_BLOB2).expect("Failed to add profile (2).");
491 }
492
493 // Then delete them again.
494 for count in 0..actual_profile_count {
495 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
496 return;
497 }
498 let alias = format!("test_alias_{}", count);
499 db.remove(2, &alias).expect("Remove Failed (2).");
500 }
501 });
502
503 // And start deleting the first set of profiles.
504 let db_path2 = db_path.clone();
505 let handle2 = thread::spawn(move || {
506 let mut db = DB::new(&db_path2).expect("Failed to open database.");
507
508 for count in 0..actual_profile_count {
509 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
510 return;
511 }
512 let alias = format!("test_alias_{}", count);
513 db.remove(1, &alias).expect("Remove Failed (1)).");
514 }
515 });
516
517 // While a lot of inserting and deleting is going on we have to open database connections
518 // successfully and then insert and delete a specific profile.
519 let db_path3 = db_path.clone();
520 let handle3 = thread::spawn(move || {
521 for _count in 0..PROFILE_DB_COUNT {
522 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
523 return;
524 }
525 let mut db = DB::new(&db_path3).expect("Failed to open database.");
526
527 db.put(3, &TEST_ALIAS, TEST_BLOB3).expect("Failed to add profile (3).");
528
529 db.remove(3, &TEST_ALIAS).expect("Remove failed (3).");
530 }
531 });
532
533 // While thread 3 is inserting and deleting TEST_ALIAS, we try to get the alias.
534 // This may yield an entry or none, but it must not fail.
535 let handle4 = thread::spawn(move || {
536 for _count in 0..PROFILE_DB_COUNT {
537 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
538 return;
539 }
540 let mut db = DB::new(&db_path).expect("Failed to open database.");
541
542 // This may return Some or None but it must not fail.
543 db.get(3, &TEST_ALIAS).expect("Failed to get profile (4).");
544 }
545 });
546
547 handle1.join().expect("Thread 1 panicked.");
548 handle2.join().expect("Thread 2 panicked.");
549 handle3.join().expect("Thread 3 panicked.");
550 handle4.join().expect("Thread 4 panicked.");
551
552 Ok(())
553 }
Janis Danisevskis77d72042021-01-20 15:36:30 -0800554}